var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __esm = (fn, res) => function __init() {
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
var __commonJS = (cb, mod) => function __require() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all2) => {
  for (var name2 in all2)
    __defProp(target, name2, { get: all2[name2], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));

// deno_ral/original-real-path.ts
var originalRealPathSync;
var init_original_real_path = __esm({
  "deno_ral/original-real-path.ts"() {
    originalRealPathSync = Deno.realPathSync;
  }
});

// https://jsr.io/@std/log/0.224.0/levels.ts
function getLevelByName(name2) {
  const level = LogLevels[name2];
  if (level !== void 0) {
    return level;
  }
  throw new Error(`no log level found for name: ${name2}`);
}
function getLevelName(level) {
  const levelName = byLevel[level];
  if (levelName) {
    return levelName;
  }
  throw new Error(`no level name found for level: ${level}`);
}
var LogLevels, LogLevelNames, byLevel;
var init_levels = __esm({
  "https://jsr.io/@std/log/0.224.0/levels.ts"() {
    LogLevels = {
      NOTSET: 0,
      DEBUG: 10,
      INFO: 20,
      WARN: 30,
      ERROR: 40,
      CRITICAL: 50
    };
    LogLevelNames = Object.keys(LogLevels).filter(
      (key) => isNaN(Number(key))
    );
    byLevel = {
      [LogLevels.NOTSET]: "NOTSET",
      [LogLevels.DEBUG]: "DEBUG",
      [LogLevels.INFO]: "INFO",
      [LogLevels.WARN]: "WARN",
      [LogLevels.ERROR]: "ERROR",
      [LogLevels.CRITICAL]: "CRITICAL"
    };
  }
});

// https://jsr.io/@std/log/0.224.0/base_handler.ts
var DEFAULT_FORMATTER, BaseHandler;
var init_base_handler = __esm({
  "https://jsr.io/@std/log/0.224.0/base_handler.ts"() {
    init_levels();
    DEFAULT_FORMATTER = ({ levelName, msg: msg5 }) => `${levelName} ${msg5}`;
    BaseHandler = class {
      #levelName;
      #level;
      formatter;
      constructor(levelName, { formatter = DEFAULT_FORMATTER } = {}) {
        this.#levelName = levelName;
        this.#level = getLevelByName(levelName);
        this.formatter = formatter;
      }
      get level() {
        return this.#level;
      }
      set level(level) {
        this.#level = level;
        this.#levelName = getLevelName(level);
      }
      get levelName() {
        return this.#levelName;
      }
      set levelName(levelName) {
        this.#levelName = levelName;
        this.#level = getLevelByName(levelName);
      }
      handle(logRecord) {
        if (this.level > logRecord.level) return;
        const msg5 = this.format(logRecord);
        this.log(msg5);
      }
      format(logRecord) {
        return this.formatter(logRecord);
      }
      log(_msg) {
      }
      setup() {
      }
      destroy() {
      }
      [Symbol.dispose]() {
        this.destroy();
      }
    };
  }
});

// https://jsr.io/@std/fmt/0.224.0/colors.ts
function code(open, close) {
  return {
    open: `\x1B[${open.join(";")}m`,
    close: `\x1B[${close}m`,
    regexp: new RegExp(`\\x1b\\[${close}m`, "g")
  };
}
function run(str3, code5) {
  return enabled ? `${code5.open}${str3.replace(code5.regexp, code5.open)}${code5.close}` : str3;
}
function bold(str3) {
  return run(str3, code([1], 22));
}
function red(str3) {
  return run(str3, code([31], 39));
}
function yellow(str3) {
  return run(str3, code([33], 39));
}
function blue(str3) {
  return run(str3, code([34], 39));
}
var Deno2, noColor, enabled, ANSI_PATTERN;
var init_colors = __esm({
  "https://jsr.io/@std/fmt/0.224.0/colors.ts"() {
    ({ Deno: Deno2 } = globalThis);
    noColor = typeof Deno2?.noColor === "boolean" ? Deno2.noColor : false;
    enabled = !noColor;
    ANSI_PATTERN = new RegExp(
      [
        "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
        "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TXZcf-nq-uy=><~]))"
      ].join("|"),
      "g"
    );
  }
});

// https://jsr.io/@std/log/0.224.0/console_handler.ts
var ConsoleHandler;
var init_console_handler = __esm({
  "https://jsr.io/@std/log/0.224.0/console_handler.ts"() {
    init_levels();
    init_colors();
    init_base_handler();
    ConsoleHandler = class extends BaseHandler {
      #useColors;
      constructor(levelName, options = {}) {
        super(levelName, options);
        this.#useColors = options.useColors ?? true;
      }
      format(logRecord) {
        let msg5 = super.format(logRecord);
        if (this.#useColors) {
          msg5 = this.applyColors(msg5, logRecord.level);
        }
        return msg5;
      }
      applyColors(msg5, level) {
        switch (level) {
          case LogLevels.INFO:
            msg5 = blue(msg5);
            break;
          case LogLevels.WARN:
            msg5 = yellow(msg5);
            break;
          case LogLevels.ERROR:
            msg5 = red(msg5);
            break;
          case LogLevels.CRITICAL:
            msg5 = bold(red(msg5));
            break;
          default:
            break;
        }
        return msg5;
      }
      log(msg5) {
        console.log(msg5);
      }
    };
  }
});

// https://jsr.io/@std/io/0.224.0/write_all.ts
async function writeAll(writer, data3) {
  let nwritten = 0;
  while (nwritten < data3.length) {
    nwritten += await writer.write(data3.subarray(nwritten));
  }
}
function writeAllSync(writer, data3) {
  let nwritten = 0;
  while (nwritten < data3.length) {
    nwritten += writer.writeSync(data3.subarray(nwritten));
  }
}
var init_write_all = __esm({
  "https://jsr.io/@std/io/0.224.0/write_all.ts"() {
  }
});

// https://jsr.io/@std/log/0.224.0/file_handler.ts
var PAGE_SIZE, FileHandler;
var init_file_handler = __esm({
  "https://jsr.io/@std/log/0.224.0/file_handler.ts"() {
    init_levels();
    init_base_handler();
    init_write_all();
    PAGE_SIZE = 4096;
    FileHandler = class extends BaseHandler {
      _file;
      _buf = new Uint8Array(PAGE_SIZE);
      _pointer = 0;
      _filename;
      _mode;
      _openOptions;
      _encoder = new TextEncoder();
      #unloadCallback = (() => {
        this.destroy();
      }).bind(this);
      constructor(levelName, options) {
        super(levelName, options);
        this._filename = options.filename;
        this._mode = options.mode ? options.mode : "a";
        this._openOptions = {
          createNew: this._mode === "x",
          create: this._mode !== "x",
          append: this._mode === "a",
          truncate: this._mode !== "a",
          write: true
        };
      }
      setup() {
        this._file = Deno.openSync(this._filename, this._openOptions);
        this.#resetBuffer();
        addEventListener("unload", this.#unloadCallback);
      }
      handle(logRecord) {
        super.handle(logRecord);
        if (logRecord.level > LogLevels.ERROR) {
          this.flush();
        }
      }
      log(msg5) {
        const bytes = this._encoder.encode(msg5 + "\n");
        if (bytes.byteLength > this._buf.byteLength - this._pointer) {
          this.flush();
        }
        if (bytes.byteLength > this._buf.byteLength) {
          writeAllSync(this._file, bytes);
        } else {
          this._buf.set(bytes, this._pointer);
          this._pointer += bytes.byteLength;
        }
      }
      flush() {
        if (this._pointer > 0 && this._file) {
          let written = 0;
          while (written < this._pointer) {
            written += this._file.writeSync(
              this._buf.subarray(written, this._pointer)
            );
          }
          this.#resetBuffer();
        }
      }
      #resetBuffer() {
        this._pointer = 0;
      }
      destroy() {
        this.flush();
        this._file?.close();
        this._file = void 0;
        removeEventListener("unload", this.#unloadCallback);
      }
    };
  }
});

// https://jsr.io/@std/fs/0.224.0/exists.ts
var init_exists = __esm({
  "https://jsr.io/@std/fs/0.224.0/exists.ts"() {
  }
});

// https://jsr.io/@std/log/0.224.0/rotating_file_handler.ts
var init_rotating_file_handler = __esm({
  "https://jsr.io/@std/log/0.224.0/rotating_file_handler.ts"() {
    init_exists();
    init_file_handler();
  }
});

// https://jsr.io/@std/log/0.224.0/logger.ts
var LogRecord, Logger;
var init_logger = __esm({
  "https://jsr.io/@std/log/0.224.0/logger.ts"() {
    init_levels();
    LogRecord = class {
      msg;
      #args;
      #datetime;
      level;
      levelName;
      loggerName;
      constructor(options) {
        this.msg = options.msg;
        this.#args = [...options.args];
        this.level = options.level;
        this.loggerName = options.loggerName;
        this.#datetime = /* @__PURE__ */ new Date();
        this.levelName = getLevelName(options.level);
      }
      get args() {
        return [...this.#args];
      }
      get datetime() {
        return new Date(this.#datetime.getTime());
      }
    };
    Logger = class {
      #level;
      handlers;
      #loggerName;
      constructor(loggerName, levelName, options = {}) {
        this.#loggerName = loggerName;
        this.#level = getLevelByName(levelName);
        this.handlers = options.handlers || [];
      }
      /** Use this to retrieve the current numeric log level. */
      get level() {
        return this.#level;
      }
      /** Use this to set the numeric log level. */
      set level(level) {
        try {
          this.#level = getLevelByName(getLevelName(level));
        } catch (_3) {
          throw new TypeError(`Invalid log level: ${level}`);
        }
      }
      get levelName() {
        return getLevelName(this.#level);
      }
      set levelName(levelName) {
        this.#level = getLevelByName(levelName);
      }
      get loggerName() {
        return this.#loggerName;
      }
      /**
       * If the level of the logger is greater than the level to log, then nothing
       * is logged, otherwise a log record is passed to each log handler.  `msg` data
       * passed in is returned.  If a function is passed in, it is only evaluated
       * if the msg will be logged and the return value will be the result of the
       * function, not the function itself, unless the function isn't called, in which
       * case undefined is returned.  All types are coerced to strings for logging.
       */
      #log(level, msg5, ...args) {
        if (this.level > level) {
          return msg5 instanceof Function ? void 0 : msg5;
        }
        let fnResult;
        let logMessage;
        if (msg5 instanceof Function) {
          fnResult = msg5();
          logMessage = this.asString(fnResult);
        } else {
          logMessage = this.asString(msg5);
        }
        const record = new LogRecord({
          msg: logMessage,
          args,
          level,
          loggerName: this.loggerName
        });
        this.handlers.forEach((handler) => {
          handler.handle(record);
        });
        return msg5 instanceof Function ? fnResult : msg5;
      }
      asString(data3, isProperty = false) {
        if (typeof data3 === "string") {
          if (isProperty) return `"${data3}"`;
          return data3;
        } else if (data3 === null || typeof data3 === "number" || typeof data3 === "bigint" || typeof data3 === "boolean" || typeof data3 === "undefined" || typeof data3 === "symbol") {
          return String(data3);
        } else if (data3 instanceof Error) {
          return data3.stack;
        } else if (typeof data3 === "object") {
          return `{${Object.entries(data3).map(([k3, v4]) => `"${k3}":${this.asString(v4, true)}`).join(",")}}`;
        }
        return "undefined";
      }
      debug(msg5, ...args) {
        return this.#log(LogLevels.DEBUG, msg5, ...args);
      }
      info(msg5, ...args) {
        return this.#log(LogLevels.INFO, msg5, ...args);
      }
      warn(msg5, ...args) {
        return this.#log(LogLevels.WARN, msg5, ...args);
      }
      error(msg5, ...args) {
        return this.#log(LogLevels.ERROR, msg5, ...args);
      }
      critical(msg5, ...args) {
        return this.#log(LogLevels.CRITICAL, msg5, ...args);
      }
    };
  }
});

// https://jsr.io/@std/log/0.224.0/formatters.ts
var init_formatters = __esm({
  "https://jsr.io/@std/log/0.224.0/formatters.ts"() {
  }
});

// https://jsr.io/@std/assert/0.224.0/assertion_error.ts
var AssertionError;
var init_assertion_error = __esm({
  "https://jsr.io/@std/assert/0.224.0/assertion_error.ts"() {
    AssertionError = class extends Error {
      /** Constructs a new instance. */
      constructor(message) {
        super(message);
        this.name = "AssertionError";
      }
    };
  }
});

// https://jsr.io/@std/assert/0.224.0/assert.ts
function assert(expr, msg5 = "") {
  if (!expr) {
    throw new AssertionError(msg5);
  }
}
var init_assert = __esm({
  "https://jsr.io/@std/assert/0.224.0/assert.ts"() {
    init_assertion_error();
  }
});

// https://jsr.io/@std/log/0.224.0/_config.ts
var DEFAULT_LEVEL, DEFAULT_CONFIG;
var init_config = __esm({
  "https://jsr.io/@std/log/0.224.0/_config.ts"() {
    init_console_handler();
    DEFAULT_LEVEL = "INFO";
    DEFAULT_CONFIG = {
      handlers: {
        default: new ConsoleHandler(DEFAULT_LEVEL)
      },
      loggers: {
        default: {
          level: DEFAULT_LEVEL,
          handlers: ["default"]
        }
      }
    };
  }
});

// https://jsr.io/@std/log/0.224.0/_state.ts
var state;
var init_state = __esm({
  "https://jsr.io/@std/log/0.224.0/_state.ts"() {
    init_config();
    state = {
      handlers: /* @__PURE__ */ new Map(),
      loggers: /* @__PURE__ */ new Map(),
      config: DEFAULT_CONFIG
    };
  }
});

// https://jsr.io/@std/log/0.224.0/get_logger.ts
function getLogger(name2) {
  if (!name2) {
    const d4 = state.loggers.get("default");
    assert(
      d4 !== void 0,
      `"default" logger must be set for getting logger without name`
    );
    return d4;
  }
  const result2 = state.loggers.get(name2);
  if (!result2) {
    const logger = new Logger(name2, "NOTSET", { handlers: [] });
    state.loggers.set(name2, logger);
    return logger;
  }
  return result2;
}
var init_get_logger = __esm({
  "https://jsr.io/@std/log/0.224.0/get_logger.ts"() {
    init_assert();
    init_logger();
    init_state();
  }
});

// https://jsr.io/@std/log/0.224.0/critical.ts
var init_critical = __esm({
  "https://jsr.io/@std/log/0.224.0/critical.ts"() {
    init_get_logger();
  }
});

// https://jsr.io/@std/log/0.224.0/debug.ts
function debug(msg5, ...args) {
  if (msg5 instanceof Function) {
    return getLogger("default").debug(msg5, ...args);
  }
  return getLogger("default").debug(msg5, ...args);
}
var init_debug = __esm({
  "https://jsr.io/@std/log/0.224.0/debug.ts"() {
    init_get_logger();
  }
});

// https://jsr.io/@std/log/0.224.0/error.ts
function error(msg5, ...args) {
  if (msg5 instanceof Function) {
    return getLogger("default").error(msg5, ...args);
  }
  return getLogger("default").error(msg5, ...args);
}
var init_error = __esm({
  "https://jsr.io/@std/log/0.224.0/error.ts"() {
    init_get_logger();
  }
});

// https://jsr.io/@std/log/0.224.0/info.ts
function info(msg5, ...args) {
  if (msg5 instanceof Function) {
    return getLogger("default").info(msg5, ...args);
  }
  return getLogger("default").info(msg5, ...args);
}
var init_info = __esm({
  "https://jsr.io/@std/log/0.224.0/info.ts"() {
    init_get_logger();
  }
});

// https://jsr.io/@std/log/0.224.0/setup.ts
function setup(config2) {
  state.config = {
    handlers: { ...DEFAULT_CONFIG.handlers, ...config2.handlers },
    loggers: { ...DEFAULT_CONFIG.loggers, ...config2.loggers }
  };
  state.handlers.forEach((handler) => {
    handler.destroy();
  });
  state.handlers.clear();
  const handlers3 = state.config.handlers || {};
  for (const [handlerName, handler] of Object.entries(handlers3)) {
    handler.setup();
    state.handlers.set(handlerName, handler);
  }
  state.loggers.clear();
  const loggers = state.config.loggers || {};
  for (const [loggerName, loggerConfig] of Object.entries(loggers)) {
    const handlerNames = loggerConfig.handlers || [];
    const handlers4 = [];
    handlerNames.forEach((handlerName) => {
      const handler = state.handlers.get(handlerName);
      if (handler) {
        handlers4.push(handler);
      }
    });
    const levelName = loggerConfig.level || DEFAULT_LEVEL;
    const logger = new Logger(loggerName, levelName, { handlers: handlers4 });
    state.loggers.set(loggerName, logger);
  }
}
var init_setup = __esm({
  "https://jsr.io/@std/log/0.224.0/setup.ts"() {
    init_config();
    init_logger();
    init_state();
    setup(DEFAULT_CONFIG);
  }
});

// https://jsr.io/@std/log/0.224.0/warn.ts
function warn(msg5, ...args) {
  if (msg5 instanceof Function) {
    return getLogger("default").warn(msg5, ...args);
  }
  return getLogger("default").warn(msg5, ...args);
}
var init_warn = __esm({
  "https://jsr.io/@std/log/0.224.0/warn.ts"() {
    init_get_logger();
  }
});

// https://jsr.io/@std/log/0.224.0/mod.ts
var init_mod = __esm({
  "https://jsr.io/@std/log/0.224.0/mod.ts"() {
    init_base_handler();
    init_console_handler();
    init_file_handler();
    init_rotating_file_handler();
    init_levels();
    init_logger();
    init_formatters();
    init_critical();
    init_debug();
    init_error();
    init_get_logger();
    init_info();
    init_setup();
    init_warn();
  }
});

// deno_ral/log.ts
var init_log = __esm({
  "deno_ral/log.ts"() {
    init_mod();
  }
});

// https://jsr.io/@std/path/1.0.8/_os.ts
var isWindows;
var init_os = __esm({
  "https://jsr.io/@std/path/1.0.8/_os.ts"() {
    isWindows = globalThis.Deno?.build.os === "windows" || globalThis.navigator?.platform?.startsWith("Win") || globalThis.process?.platform?.startsWith("win") || false;
  }
});

// https://jsr.io/@std/path/1.0.8/_common/assert_path.ts
function assertPath(path3) {
  if (typeof path3 !== "string") {
    throw new TypeError(
      `Path must be a string, received "${JSON.stringify(path3)}"`
    );
  }
}
var init_assert_path = __esm({
  "https://jsr.io/@std/path/1.0.8/_common/assert_path.ts"() {
  }
});

// https://jsr.io/@std/path/1.0.8/_common/basename.ts
function stripSuffix(name2, suffix) {
  if (suffix.length >= name2.length) {
    return name2;
  }
  const lenDiff = name2.length - suffix.length;
  for (let i6 = suffix.length - 1; i6 >= 0; --i6) {
    if (name2.charCodeAt(lenDiff + i6) !== suffix.charCodeAt(i6)) {
      return name2;
    }
  }
  return name2.slice(0, -suffix.length);
}
function lastPathSegment(path3, isSep, start = 0) {
  let matchedNonSeparator = false;
  let end = path3.length;
  for (let i6 = path3.length - 1; i6 >= start; --i6) {
    if (isSep(path3.charCodeAt(i6))) {
      if (matchedNonSeparator) {
        start = i6 + 1;
        break;
      }
    } else if (!matchedNonSeparator) {
      matchedNonSeparator = true;
      end = i6 + 1;
    }
  }
  return path3.slice(start, end);
}
function assertArgs(path3, suffix) {
  assertPath(path3);
  if (path3.length === 0) return path3;
  if (typeof suffix !== "string") {
    throw new TypeError(
      `Suffix must be a string, received "${JSON.stringify(suffix)}"`
    );
  }
}
var init_basename = __esm({
  "https://jsr.io/@std/path/1.0.8/_common/basename.ts"() {
    init_assert_path();
  }
});

// https://jsr.io/@std/path/1.0.8/_common/strip_trailing_separators.ts
function stripTrailingSeparators(segment, isSep) {
  if (segment.length <= 1) {
    return segment;
  }
  let end = segment.length;
  for (let i6 = segment.length - 1; i6 > 0; i6--) {
    if (isSep(segment.charCodeAt(i6))) {
      end = i6;
    } else {
      break;
    }
  }
  return segment.slice(0, end);
}
var init_strip_trailing_separators = __esm({
  "https://jsr.io/@std/path/1.0.8/_common/strip_trailing_separators.ts"() {
  }
});

// https://jsr.io/@std/path/1.0.8/_common/constants.ts
var CHAR_UPPERCASE_A, CHAR_LOWERCASE_A, CHAR_UPPERCASE_Z, CHAR_LOWERCASE_Z, CHAR_DOT, CHAR_FORWARD_SLASH, CHAR_BACKWARD_SLASH, CHAR_COLON;
var init_constants = __esm({
  "https://jsr.io/@std/path/1.0.8/_common/constants.ts"() {
    CHAR_UPPERCASE_A = 65;
    CHAR_LOWERCASE_A = 97;
    CHAR_UPPERCASE_Z = 90;
    CHAR_LOWERCASE_Z = 122;
    CHAR_DOT = 46;
    CHAR_FORWARD_SLASH = 47;
    CHAR_BACKWARD_SLASH = 92;
    CHAR_COLON = 58;
  }
});

// https://jsr.io/@std/path/1.0.8/posix/_util.ts
function isPosixPathSeparator(code5) {
  return code5 === CHAR_FORWARD_SLASH;
}
var init_util = __esm({
  "https://jsr.io/@std/path/1.0.8/posix/_util.ts"() {
    init_constants();
  }
});

// https://jsr.io/@std/path/1.0.8/posix/basename.ts
function basename(path3, suffix = "") {
  assertArgs(path3, suffix);
  const lastSegment = lastPathSegment(path3, isPosixPathSeparator);
  const strippedSegment = stripTrailingSeparators(
    lastSegment,
    isPosixPathSeparator
  );
  return suffix ? stripSuffix(strippedSegment, suffix) : strippedSegment;
}
var init_basename2 = __esm({
  "https://jsr.io/@std/path/1.0.8/posix/basename.ts"() {
    init_basename();
    init_strip_trailing_separators();
    init_util();
  }
});

// https://jsr.io/@std/path/1.0.8/windows/_util.ts
function isPosixPathSeparator2(code5) {
  return code5 === CHAR_FORWARD_SLASH;
}
function isPathSeparator(code5) {
  return code5 === CHAR_FORWARD_SLASH || code5 === CHAR_BACKWARD_SLASH;
}
function isWindowsDeviceRoot(code5) {
  return code5 >= CHAR_LOWERCASE_A && code5 <= CHAR_LOWERCASE_Z || code5 >= CHAR_UPPERCASE_A && code5 <= CHAR_UPPERCASE_Z;
}
var init_util2 = __esm({
  "https://jsr.io/@std/path/1.0.8/windows/_util.ts"() {
    init_constants();
  }
});

// https://jsr.io/@std/path/1.0.8/windows/basename.ts
function basename2(path3, suffix = "") {
  assertArgs(path3, suffix);
  let start = 0;
  if (path3.length >= 2) {
    const drive = path3.charCodeAt(0);
    if (isWindowsDeviceRoot(drive)) {
      if (path3.charCodeAt(1) === CHAR_COLON) start = 2;
    }
  }
  const lastSegment = lastPathSegment(path3, isPathSeparator, start);
  const strippedSegment = stripTrailingSeparators(lastSegment, isPathSeparator);
  return suffix ? stripSuffix(strippedSegment, suffix) : strippedSegment;
}
var init_basename3 = __esm({
  "https://jsr.io/@std/path/1.0.8/windows/basename.ts"() {
    init_basename();
    init_constants();
    init_strip_trailing_separators();
    init_util2();
  }
});

// https://jsr.io/@std/path/1.0.8/basename.ts
function basename3(path3, suffix = "") {
  return isWindows ? basename2(path3, suffix) : basename(path3, suffix);
}
var init_basename4 = __esm({
  "https://jsr.io/@std/path/1.0.8/basename.ts"() {
    init_os();
    init_basename2();
    init_basename3();
  }
});

// https://jsr.io/@std/path/1.0.8/constants.ts
var SEPARATOR, SEPARATOR_PATTERN;
var init_constants2 = __esm({
  "https://jsr.io/@std/path/1.0.8/constants.ts"() {
    init_os();
    SEPARATOR = isWindows ? "\\" : "/";
    SEPARATOR_PATTERN = isWindows ? /[\\/]+/ : /\/+/;
  }
});

// https://jsr.io/@std/path/1.0.8/_common/dirname.ts
function assertArg(path3) {
  assertPath(path3);
  if (path3.length === 0) return ".";
}
var init_dirname = __esm({
  "https://jsr.io/@std/path/1.0.8/_common/dirname.ts"() {
    init_assert_path();
  }
});

// https://jsr.io/@std/path/1.0.8/posix/dirname.ts
function dirname(path3) {
  assertArg(path3);
  let end = -1;
  let matchedNonSeparator = false;
  for (let i6 = path3.length - 1; i6 >= 1; --i6) {
    if (isPosixPathSeparator(path3.charCodeAt(i6))) {
      if (matchedNonSeparator) {
        end = i6;
        break;
      }
    } else {
      matchedNonSeparator = true;
    }
  }
  if (end === -1) {
    return isPosixPathSeparator(path3.charCodeAt(0)) ? "/" : ".";
  }
  return stripTrailingSeparators(
    path3.slice(0, end),
    isPosixPathSeparator
  );
}
var init_dirname2 = __esm({
  "https://jsr.io/@std/path/1.0.8/posix/dirname.ts"() {
    init_dirname();
    init_strip_trailing_separators();
    init_util();
  }
});

// https://jsr.io/@std/path/1.0.8/windows/dirname.ts
function dirname2(path3) {
  assertArg(path3);
  const len = path3.length;
  let rootEnd = -1;
  let end = -1;
  let matchedSlash = true;
  let offset3 = 0;
  const code5 = path3.charCodeAt(0);
  if (len > 1) {
    if (isPathSeparator(code5)) {
      rootEnd = offset3 = 1;
      if (isPathSeparator(path3.charCodeAt(1))) {
        let j3 = 2;
        let last = j3;
        for (; j3 < len; ++j3) {
          if (isPathSeparator(path3.charCodeAt(j3))) break;
        }
        if (j3 < len && j3 !== last) {
          last = j3;
          for (; j3 < len; ++j3) {
            if (!isPathSeparator(path3.charCodeAt(j3))) break;
          }
          if (j3 < len && j3 !== last) {
            last = j3;
            for (; j3 < len; ++j3) {
              if (isPathSeparator(path3.charCodeAt(j3))) break;
            }
            if (j3 === len) {
              return path3;
            }
            if (j3 !== last) {
              rootEnd = offset3 = j3 + 1;
            }
          }
        }
      }
    } else if (isWindowsDeviceRoot(code5)) {
      if (path3.charCodeAt(1) === CHAR_COLON) {
        rootEnd = offset3 = 2;
        if (len > 2) {
          if (isPathSeparator(path3.charCodeAt(2))) rootEnd = offset3 = 3;
        }
      }
    }
  } else if (isPathSeparator(code5)) {
    return path3;
  }
  for (let i6 = len - 1; i6 >= offset3; --i6) {
    if (isPathSeparator(path3.charCodeAt(i6))) {
      if (!matchedSlash) {
        end = i6;
        break;
      }
    } else {
      matchedSlash = false;
    }
  }
  if (end === -1) {
    if (rootEnd === -1) return ".";
    else end = rootEnd;
  }
  return stripTrailingSeparators(path3.slice(0, end), isPosixPathSeparator2);
}
var init_dirname3 = __esm({
  "https://jsr.io/@std/path/1.0.8/windows/dirname.ts"() {
    init_dirname();
    init_constants();
    init_strip_trailing_separators();
    init_util2();
  }
});

// https://jsr.io/@std/path/1.0.8/dirname.ts
function dirname3(path3) {
  return isWindows ? dirname2(path3) : dirname(path3);
}
var init_dirname4 = __esm({
  "https://jsr.io/@std/path/1.0.8/dirname.ts"() {
    init_os();
    init_dirname2();
    init_dirname3();
  }
});

// https://jsr.io/@std/path/1.0.8/posix/extname.ts
function extname(path3) {
  assertPath(path3);
  let startDot = -1;
  let startPart = 0;
  let end = -1;
  let matchedSlash = true;
  let preDotState = 0;
  for (let i6 = path3.length - 1; i6 >= 0; --i6) {
    const code5 = path3.charCodeAt(i6);
    if (isPosixPathSeparator(code5)) {
      if (!matchedSlash) {
        startPart = i6 + 1;
        break;
      }
      continue;
    }
    if (end === -1) {
      matchedSlash = false;
      end = i6 + 1;
    }
    if (code5 === CHAR_DOT) {
      if (startDot === -1) startDot = i6;
      else if (preDotState !== 1) preDotState = 1;
    } else if (startDot !== -1) {
      preDotState = -1;
    }
  }
  if (startDot === -1 || end === -1 || // We saw a non-dot character immediately before the dot
  preDotState === 0 || // The (right-most) trimmed path component is exactly '..'
  preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
    return "";
  }
  return path3.slice(startDot, end);
}
var init_extname = __esm({
  "https://jsr.io/@std/path/1.0.8/posix/extname.ts"() {
    init_constants();
    init_assert_path();
    init_util();
  }
});

// https://jsr.io/@std/path/1.0.8/windows/extname.ts
function extname2(path3) {
  assertPath(path3);
  let start = 0;
  let startDot = -1;
  let startPart = 0;
  let end = -1;
  let matchedSlash = true;
  let preDotState = 0;
  if (path3.length >= 2 && path3.charCodeAt(1) === CHAR_COLON && isWindowsDeviceRoot(path3.charCodeAt(0))) {
    start = startPart = 2;
  }
  for (let i6 = path3.length - 1; i6 >= start; --i6) {
    const code5 = path3.charCodeAt(i6);
    if (isPathSeparator(code5)) {
      if (!matchedSlash) {
        startPart = i6 + 1;
        break;
      }
      continue;
    }
    if (end === -1) {
      matchedSlash = false;
      end = i6 + 1;
    }
    if (code5 === CHAR_DOT) {
      if (startDot === -1) startDot = i6;
      else if (preDotState !== 1) preDotState = 1;
    } else if (startDot !== -1) {
      preDotState = -1;
    }
  }
  if (startDot === -1 || end === -1 || // We saw a non-dot character immediately before the dot
  preDotState === 0 || // The (right-most) trimmed path component is exactly '..'
  preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
    return "";
  }
  return path3.slice(startDot, end);
}
var init_extname2 = __esm({
  "https://jsr.io/@std/path/1.0.8/windows/extname.ts"() {
    init_constants();
    init_assert_path();
    init_util2();
  }
});

// https://jsr.io/@std/path/1.0.8/extname.ts
function extname3(path3) {
  return isWindows ? extname2(path3) : extname(path3);
}
var init_extname3 = __esm({
  "https://jsr.io/@std/path/1.0.8/extname.ts"() {
    init_os();
    init_extname();
    init_extname2();
  }
});

// https://jsr.io/@std/path/1.0.8/_common/format.ts
var init_format = __esm({
  "https://jsr.io/@std/path/1.0.8/_common/format.ts"() {
  }
});

// https://jsr.io/@std/path/1.0.8/posix/format.ts
var init_format2 = __esm({
  "https://jsr.io/@std/path/1.0.8/posix/format.ts"() {
    init_format();
  }
});

// https://jsr.io/@std/path/1.0.8/windows/format.ts
var init_format3 = __esm({
  "https://jsr.io/@std/path/1.0.8/windows/format.ts"() {
    init_format();
  }
});

// https://jsr.io/@std/path/1.0.8/format.ts
var init_format4 = __esm({
  "https://jsr.io/@std/path/1.0.8/format.ts"() {
    init_os();
    init_format2();
    init_format3();
  }
});

// https://jsr.io/@std/path/1.0.8/_common/from_file_url.ts
function assertArg3(url) {
  url = url instanceof URL ? url : new URL(url);
  if (url.protocol !== "file:") {
    throw new TypeError(
      `URL must be a file URL: received "${url.protocol}"`
    );
  }
  return url;
}
var init_from_file_url = __esm({
  "https://jsr.io/@std/path/1.0.8/_common/from_file_url.ts"() {
  }
});

// https://jsr.io/@std/path/1.0.8/posix/from_file_url.ts
function fromFileUrl(url) {
  url = assertArg3(url);
  return decodeURIComponent(
    url.pathname.replace(/%(?![0-9A-Fa-f]{2})/g, "%25")
  );
}
var init_from_file_url2 = __esm({
  "https://jsr.io/@std/path/1.0.8/posix/from_file_url.ts"() {
    init_from_file_url();
  }
});

// https://jsr.io/@std/path/1.0.8/windows/from_file_url.ts
function fromFileUrl2(url) {
  url = assertArg3(url);
  let path3 = decodeURIComponent(
    url.pathname.replace(/\//g, "\\").replace(/%(?![0-9A-Fa-f]{2})/g, "%25")
  ).replace(/^\\*([A-Za-z]:)(\\|$)/, "$1\\");
  if (url.hostname !== "") {
    path3 = `\\\\${url.hostname}${path3}`;
  }
  return path3;
}
var init_from_file_url3 = __esm({
  "https://jsr.io/@std/path/1.0.8/windows/from_file_url.ts"() {
    init_from_file_url();
  }
});

// https://jsr.io/@std/path/1.0.8/from_file_url.ts
function fromFileUrl3(url) {
  return isWindows ? fromFileUrl2(url) : fromFileUrl(url);
}
var init_from_file_url4 = __esm({
  "https://jsr.io/@std/path/1.0.8/from_file_url.ts"() {
    init_os();
    init_from_file_url2();
    init_from_file_url3();
  }
});

// https://jsr.io/@std/path/1.0.8/posix/is_absolute.ts
function isAbsolute(path3) {
  assertPath(path3);
  return path3.length > 0 && isPosixPathSeparator(path3.charCodeAt(0));
}
var init_is_absolute = __esm({
  "https://jsr.io/@std/path/1.0.8/posix/is_absolute.ts"() {
    init_assert_path();
    init_util();
  }
});

// https://jsr.io/@std/path/1.0.8/windows/is_absolute.ts
function isAbsolute2(path3) {
  assertPath(path3);
  const len = path3.length;
  if (len === 0) return false;
  const code5 = path3.charCodeAt(0);
  if (isPathSeparator(code5)) {
    return true;
  } else if (isWindowsDeviceRoot(code5)) {
    if (len > 2 && path3.charCodeAt(1) === CHAR_COLON) {
      if (isPathSeparator(path3.charCodeAt(2))) return true;
    }
  }
  return false;
}
var init_is_absolute2 = __esm({
  "https://jsr.io/@std/path/1.0.8/windows/is_absolute.ts"() {
    init_constants();
    init_assert_path();
    init_util2();
  }
});

// https://jsr.io/@std/path/1.0.8/is_absolute.ts
function isAbsolute3(path3) {
  return isWindows ? isAbsolute2(path3) : isAbsolute(path3);
}
var init_is_absolute3 = __esm({
  "https://jsr.io/@std/path/1.0.8/is_absolute.ts"() {
    init_os();
    init_is_absolute();
    init_is_absolute2();
  }
});

// https://jsr.io/@std/path/1.0.8/_common/normalize.ts
function assertArg4(path3) {
  assertPath(path3);
  if (path3.length === 0) return ".";
}
var init_normalize = __esm({
  "https://jsr.io/@std/path/1.0.8/_common/normalize.ts"() {
    init_assert_path();
  }
});

// https://jsr.io/@std/path/1.0.8/_common/normalize_string.ts
function normalizeString(path3, allowAboveRoot, separator, isPathSeparator5) {
  let res = "";
  let lastSegmentLength = 0;
  let lastSlash = -1;
  let dots = 0;
  let code5;
  for (let i6 = 0; i6 <= path3.length; ++i6) {
    if (i6 < path3.length) code5 = path3.charCodeAt(i6);
    else if (isPathSeparator5(code5)) break;
    else code5 = CHAR_FORWARD_SLASH;
    if (isPathSeparator5(code5)) {
      if (lastSlash === i6 - 1 || dots === 1) {
      } else if (lastSlash !== i6 - 1 && dots === 2) {
        if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== CHAR_DOT || res.charCodeAt(res.length - 2) !== CHAR_DOT) {
          if (res.length > 2) {
            const lastSlashIndex = res.lastIndexOf(separator);
            if (lastSlashIndex === -1) {
              res = "";
              lastSegmentLength = 0;
            } else {
              res = res.slice(0, lastSlashIndex);
              lastSegmentLength = res.length - 1 - res.lastIndexOf(separator);
            }
            lastSlash = i6;
            dots = 0;
            continue;
          } else if (res.length === 2 || res.length === 1) {
            res = "";
            lastSegmentLength = 0;
            lastSlash = i6;
            dots = 0;
            continue;
          }
        }
        if (allowAboveRoot) {
          if (res.length > 0) res += `${separator}..`;
          else res = "..";
          lastSegmentLength = 2;
        }
      } else {
        if (res.length > 0) res += separator + path3.slice(lastSlash + 1, i6);
        else res = path3.slice(lastSlash + 1, i6);
        lastSegmentLength = i6 - lastSlash - 1;
      }
      lastSlash = i6;
      dots = 0;
    } else if (code5 === CHAR_DOT && dots !== -1) {
      ++dots;
    } else {
      dots = -1;
    }
  }
  return res;
}
var init_normalize_string = __esm({
  "https://jsr.io/@std/path/1.0.8/_common/normalize_string.ts"() {
    init_constants();
  }
});

// https://jsr.io/@std/path/1.0.8/posix/normalize.ts
function normalize(path3) {
  assertArg4(path3);
  const isAbsolute12 = isPosixPathSeparator(path3.charCodeAt(0));
  const trailingSeparator = isPosixPathSeparator(
    path3.charCodeAt(path3.length - 1)
  );
  path3 = normalizeString(path3, !isAbsolute12, "/", isPosixPathSeparator);
  if (path3.length === 0 && !isAbsolute12) path3 = ".";
  if (path3.length > 0 && trailingSeparator) path3 += "/";
  if (isAbsolute12) return `/${path3}`;
  return path3;
}
var init_normalize2 = __esm({
  "https://jsr.io/@std/path/1.0.8/posix/normalize.ts"() {
    init_normalize();
    init_normalize_string();
    init_util();
  }
});

// https://jsr.io/@std/path/1.0.8/posix/join.ts
function join(...paths) {
  if (paths.length === 0) return ".";
  paths.forEach((path3) => assertPath(path3));
  const joined = paths.filter((path3) => path3.length > 0).join("/");
  return joined === "" ? "." : normalize(joined);
}
var init_join = __esm({
  "https://jsr.io/@std/path/1.0.8/posix/join.ts"() {
    init_assert_path();
    init_normalize2();
  }
});

// https://jsr.io/@std/path/1.0.8/windows/normalize.ts
function normalize2(path3) {
  assertArg4(path3);
  const len = path3.length;
  let rootEnd = 0;
  let device;
  let isAbsolute12 = false;
  const code5 = path3.charCodeAt(0);
  if (len > 1) {
    if (isPathSeparator(code5)) {
      isAbsolute12 = true;
      if (isPathSeparator(path3.charCodeAt(1))) {
        let j3 = 2;
        let last = j3;
        for (; j3 < len; ++j3) {
          if (isPathSeparator(path3.charCodeAt(j3))) break;
        }
        if (j3 < len && j3 !== last) {
          const firstPart = path3.slice(last, j3);
          last = j3;
          for (; j3 < len; ++j3) {
            if (!isPathSeparator(path3.charCodeAt(j3))) break;
          }
          if (j3 < len && j3 !== last) {
            last = j3;
            for (; j3 < len; ++j3) {
              if (isPathSeparator(path3.charCodeAt(j3))) break;
            }
            if (j3 === len) {
              return `\\\\${firstPart}\\${path3.slice(last)}\\`;
            } else if (j3 !== last) {
              device = `\\\\${firstPart}\\${path3.slice(last, j3)}`;
              rootEnd = j3;
            }
          }
        }
      } else {
        rootEnd = 1;
      }
    } else if (isWindowsDeviceRoot(code5)) {
      if (path3.charCodeAt(1) === CHAR_COLON) {
        device = path3.slice(0, 2);
        rootEnd = 2;
        if (len > 2) {
          if (isPathSeparator(path3.charCodeAt(2))) {
            isAbsolute12 = true;
            rootEnd = 3;
          }
        }
      }
    }
  } else if (isPathSeparator(code5)) {
    return "\\";
  }
  let tail;
  if (rootEnd < len) {
    tail = normalizeString(
      path3.slice(rootEnd),
      !isAbsolute12,
      "\\",
      isPathSeparator
    );
  } else {
    tail = "";
  }
  if (tail.length === 0 && !isAbsolute12) tail = ".";
  if (tail.length > 0 && isPathSeparator(path3.charCodeAt(len - 1))) {
    tail += "\\";
  }
  if (device === void 0) {
    if (isAbsolute12) {
      if (tail.length > 0) return `\\${tail}`;
      else return "\\";
    }
    return tail;
  } else if (isAbsolute12) {
    if (tail.length > 0) return `${device}\\${tail}`;
    else return `${device}\\`;
  }
  return device + tail;
}
var init_normalize3 = __esm({
  "https://jsr.io/@std/path/1.0.8/windows/normalize.ts"() {
    init_normalize();
    init_constants();
    init_normalize_string();
    init_util2();
  }
});

// https://jsr.io/@std/path/1.0.8/windows/join.ts
function join2(...paths) {
  paths.forEach((path3) => assertPath(path3));
  paths = paths.filter((path3) => path3.length > 0);
  if (paths.length === 0) return ".";
  let needsReplace = true;
  let slashCount = 0;
  const firstPart = paths[0];
  if (isPathSeparator(firstPart.charCodeAt(0))) {
    ++slashCount;
    const firstLen = firstPart.length;
    if (firstLen > 1) {
      if (isPathSeparator(firstPart.charCodeAt(1))) {
        ++slashCount;
        if (firstLen > 2) {
          if (isPathSeparator(firstPart.charCodeAt(2))) ++slashCount;
          else {
            needsReplace = false;
          }
        }
      }
    }
  }
  let joined = paths.join("\\");
  if (needsReplace) {
    for (; slashCount < joined.length; ++slashCount) {
      if (!isPathSeparator(joined.charCodeAt(slashCount))) break;
    }
    if (slashCount >= 2) joined = `\\${joined.slice(slashCount)}`;
  }
  return normalize2(joined);
}
var init_join2 = __esm({
  "https://jsr.io/@std/path/1.0.8/windows/join.ts"() {
    init_assert_path();
    init_util2();
    init_normalize3();
  }
});

// https://jsr.io/@std/path/1.0.8/join.ts
function join3(...paths) {
  return isWindows ? join2(...paths) : join(...paths);
}
var init_join3 = __esm({
  "https://jsr.io/@std/path/1.0.8/join.ts"() {
    init_os();
    init_join();
    init_join2();
  }
});

// https://jsr.io/@std/path/1.0.8/normalize.ts
function normalize3(path3) {
  return isWindows ? normalize2(path3) : normalize(path3);
}
var init_normalize4 = __esm({
  "https://jsr.io/@std/path/1.0.8/normalize.ts"() {
    init_os();
    init_normalize2();
    init_normalize3();
  }
});

// https://jsr.io/@std/path/1.0.8/posix/parse.ts
var init_parse = __esm({
  "https://jsr.io/@std/path/1.0.8/posix/parse.ts"() {
    init_constants();
    init_strip_trailing_separators();
    init_assert_path();
    init_util();
  }
});

// https://jsr.io/@std/path/1.0.8/windows/parse.ts
var init_parse2 = __esm({
  "https://jsr.io/@std/path/1.0.8/windows/parse.ts"() {
    init_constants();
    init_assert_path();
    init_util2();
  }
});

// https://jsr.io/@std/path/1.0.8/parse.ts
var init_parse3 = __esm({
  "https://jsr.io/@std/path/1.0.8/parse.ts"() {
    init_os();
    init_parse();
    init_parse2();
  }
});

// https://jsr.io/@std/path/1.0.8/posix/resolve.ts
function resolve(...pathSegments) {
  let resolvedPath = "";
  let resolvedAbsolute = false;
  for (let i6 = pathSegments.length - 1; i6 >= -1 && !resolvedAbsolute; i6--) {
    let path3;
    if (i6 >= 0) path3 = pathSegments[i6];
    else {
      const { Deno: Deno6 } = globalThis;
      if (typeof Deno6?.cwd !== "function") {
        throw new TypeError(
          "Resolved a relative path without a current working directory (CWD)"
        );
      }
      path3 = Deno6.cwd();
    }
    assertPath(path3);
    if (path3.length === 0) {
      continue;
    }
    resolvedPath = `${path3}/${resolvedPath}`;
    resolvedAbsolute = isPosixPathSeparator(path3.charCodeAt(0));
  }
  resolvedPath = normalizeString(
    resolvedPath,
    !resolvedAbsolute,
    "/",
    isPosixPathSeparator
  );
  if (resolvedAbsolute) {
    if (resolvedPath.length > 0) return `/${resolvedPath}`;
    else return "/";
  } else if (resolvedPath.length > 0) return resolvedPath;
  else return ".";
}
var init_resolve = __esm({
  "https://jsr.io/@std/path/1.0.8/posix/resolve.ts"() {
    init_normalize_string();
    init_assert_path();
    init_util();
  }
});

// https://jsr.io/@std/path/1.0.8/_common/relative.ts
function assertArgs2(from, to) {
  assertPath(from);
  assertPath(to);
  if (from === to) return "";
}
var init_relative = __esm({
  "https://jsr.io/@std/path/1.0.8/_common/relative.ts"() {
    init_assert_path();
  }
});

// https://jsr.io/@std/path/1.0.8/posix/relative.ts
function relative(from, to) {
  assertArgs2(from, to);
  from = resolve(from);
  to = resolve(to);
  if (from === to) return "";
  let fromStart = 1;
  const fromEnd = from.length;
  for (; fromStart < fromEnd; ++fromStart) {
    if (!isPosixPathSeparator(from.charCodeAt(fromStart))) break;
  }
  const fromLen = fromEnd - fromStart;
  let toStart = 1;
  const toEnd = to.length;
  for (; toStart < toEnd; ++toStart) {
    if (!isPosixPathSeparator(to.charCodeAt(toStart))) break;
  }
  const toLen = toEnd - toStart;
  const length = fromLen < toLen ? fromLen : toLen;
  let lastCommonSep = -1;
  let i6 = 0;
  for (; i6 <= length; ++i6) {
    if (i6 === length) {
      if (toLen > length) {
        if (isPosixPathSeparator(to.charCodeAt(toStart + i6))) {
          return to.slice(toStart + i6 + 1);
        } else if (i6 === 0) {
          return to.slice(toStart + i6);
        }
      } else if (fromLen > length) {
        if (isPosixPathSeparator(from.charCodeAt(fromStart + i6))) {
          lastCommonSep = i6;
        } else if (i6 === 0) {
          lastCommonSep = 0;
        }
      }
      break;
    }
    const fromCode = from.charCodeAt(fromStart + i6);
    const toCode = to.charCodeAt(toStart + i6);
    if (fromCode !== toCode) break;
    else if (isPosixPathSeparator(fromCode)) lastCommonSep = i6;
  }
  let out = "";
  for (i6 = fromStart + lastCommonSep + 1; i6 <= fromEnd; ++i6) {
    if (i6 === fromEnd || isPosixPathSeparator(from.charCodeAt(i6))) {
      if (out.length === 0) out += "..";
      else out += "/..";
    }
  }
  if (out.length > 0) return out + to.slice(toStart + lastCommonSep);
  else {
    toStart += lastCommonSep;
    if (isPosixPathSeparator(to.charCodeAt(toStart))) ++toStart;
    return to.slice(toStart);
  }
}
var init_relative2 = __esm({
  "https://jsr.io/@std/path/1.0.8/posix/relative.ts"() {
    init_util();
    init_resolve();
    init_relative();
  }
});

// https://jsr.io/@std/path/1.0.8/windows/resolve.ts
function resolve2(...pathSegments) {
  let resolvedDevice = "";
  let resolvedTail = "";
  let resolvedAbsolute = false;
  for (let i6 = pathSegments.length - 1; i6 >= -1; i6--) {
    let path3;
    const { Deno: Deno6 } = globalThis;
    if (i6 >= 0) {
      path3 = pathSegments[i6];
    } else if (!resolvedDevice) {
      if (typeof Deno6?.cwd !== "function") {
        throw new TypeError(
          "Resolved a drive-letter-less path without a current working directory (CWD)"
        );
      }
      path3 = Deno6.cwd();
    } else {
      if (typeof Deno6?.env?.get !== "function" || typeof Deno6?.cwd !== "function") {
        throw new TypeError(
          "Resolved a relative path without a current working directory (CWD)"
        );
      }
      path3 = Deno6.cwd();
      if (path3 === void 0 || path3.slice(0, 3).toLowerCase() !== `${resolvedDevice.toLowerCase()}\\`) {
        path3 = `${resolvedDevice}\\`;
      }
    }
    assertPath(path3);
    const len = path3.length;
    if (len === 0) continue;
    let rootEnd = 0;
    let device = "";
    let isAbsolute12 = false;
    const code5 = path3.charCodeAt(0);
    if (len > 1) {
      if (isPathSeparator(code5)) {
        isAbsolute12 = true;
        if (isPathSeparator(path3.charCodeAt(1))) {
          let j3 = 2;
          let last = j3;
          for (; j3 < len; ++j3) {
            if (isPathSeparator(path3.charCodeAt(j3))) break;
          }
          if (j3 < len && j3 !== last) {
            const firstPart = path3.slice(last, j3);
            last = j3;
            for (; j3 < len; ++j3) {
              if (!isPathSeparator(path3.charCodeAt(j3))) break;
            }
            if (j3 < len && j3 !== last) {
              last = j3;
              for (; j3 < len; ++j3) {
                if (isPathSeparator(path3.charCodeAt(j3))) break;
              }
              if (j3 === len) {
                device = `\\\\${firstPart}\\${path3.slice(last)}`;
                rootEnd = j3;
              } else if (j3 !== last) {
                device = `\\\\${firstPart}\\${path3.slice(last, j3)}`;
                rootEnd = j3;
              }
            }
          }
        } else {
          rootEnd = 1;
        }
      } else if (isWindowsDeviceRoot(code5)) {
        if (path3.charCodeAt(1) === CHAR_COLON) {
          device = path3.slice(0, 2);
          rootEnd = 2;
          if (len > 2) {
            if (isPathSeparator(path3.charCodeAt(2))) {
              isAbsolute12 = true;
              rootEnd = 3;
            }
          }
        }
      }
    } else if (isPathSeparator(code5)) {
      rootEnd = 1;
      isAbsolute12 = true;
    }
    if (device.length > 0 && resolvedDevice.length > 0 && device.toLowerCase() !== resolvedDevice.toLowerCase()) {
      continue;
    }
    if (resolvedDevice.length === 0 && device.length > 0) {
      resolvedDevice = device;
    }
    if (!resolvedAbsolute) {
      resolvedTail = `${path3.slice(rootEnd)}\\${resolvedTail}`;
      resolvedAbsolute = isAbsolute12;
    }
    if (resolvedAbsolute && resolvedDevice.length > 0) break;
  }
  resolvedTail = normalizeString(
    resolvedTail,
    !resolvedAbsolute,
    "\\",
    isPathSeparator
  );
  return resolvedDevice + (resolvedAbsolute ? "\\" : "") + resolvedTail || ".";
}
var init_resolve2 = __esm({
  "https://jsr.io/@std/path/1.0.8/windows/resolve.ts"() {
    init_constants();
    init_normalize_string();
    init_assert_path();
    init_util2();
  }
});

// https://jsr.io/@std/path/1.0.8/windows/relative.ts
function relative2(from, to) {
  assertArgs2(from, to);
  const fromOrig = resolve2(from);
  const toOrig = resolve2(to);
  if (fromOrig === toOrig) return "";
  from = fromOrig.toLowerCase();
  to = toOrig.toLowerCase();
  if (from === to) return "";
  let fromStart = 0;
  let fromEnd = from.length;
  for (; fromStart < fromEnd; ++fromStart) {
    if (from.charCodeAt(fromStart) !== CHAR_BACKWARD_SLASH) break;
  }
  for (; fromEnd - 1 > fromStart; --fromEnd) {
    if (from.charCodeAt(fromEnd - 1) !== CHAR_BACKWARD_SLASH) break;
  }
  const fromLen = fromEnd - fromStart;
  let toStart = 0;
  let toEnd = to.length;
  for (; toStart < toEnd; ++toStart) {
    if (to.charCodeAt(toStart) !== CHAR_BACKWARD_SLASH) break;
  }
  for (; toEnd - 1 > toStart; --toEnd) {
    if (to.charCodeAt(toEnd - 1) !== CHAR_BACKWARD_SLASH) break;
  }
  const toLen = toEnd - toStart;
  const length = fromLen < toLen ? fromLen : toLen;
  let lastCommonSep = -1;
  let i6 = 0;
  for (; i6 <= length; ++i6) {
    if (i6 === length) {
      if (toLen > length) {
        if (to.charCodeAt(toStart + i6) === CHAR_BACKWARD_SLASH) {
          return toOrig.slice(toStart + i6 + 1);
        } else if (i6 === 2) {
          return toOrig.slice(toStart + i6);
        }
      }
      if (fromLen > length) {
        if (from.charCodeAt(fromStart + i6) === CHAR_BACKWARD_SLASH) {
          lastCommonSep = i6;
        } else if (i6 === 2) {
          lastCommonSep = 3;
        }
      }
      break;
    }
    const fromCode = from.charCodeAt(fromStart + i6);
    const toCode = to.charCodeAt(toStart + i6);
    if (fromCode !== toCode) break;
    else if (fromCode === CHAR_BACKWARD_SLASH) lastCommonSep = i6;
  }
  if (i6 !== length && lastCommonSep === -1) {
    return toOrig;
  }
  let out = "";
  if (lastCommonSep === -1) lastCommonSep = 0;
  for (i6 = fromStart + lastCommonSep + 1; i6 <= fromEnd; ++i6) {
    if (i6 === fromEnd || from.charCodeAt(i6) === CHAR_BACKWARD_SLASH) {
      if (out.length === 0) out += "..";
      else out += "\\..";
    }
  }
  if (out.length > 0) {
    return out + toOrig.slice(toStart + lastCommonSep, toEnd);
  } else {
    toStart += lastCommonSep;
    if (toOrig.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) ++toStart;
    return toOrig.slice(toStart, toEnd);
  }
}
var init_relative3 = __esm({
  "https://jsr.io/@std/path/1.0.8/windows/relative.ts"() {
    init_constants();
    init_resolve2();
    init_relative();
  }
});

// https://jsr.io/@std/path/1.0.8/relative.ts
function relative3(from, to) {
  return isWindows ? relative2(from, to) : relative(from, to);
}
var init_relative4 = __esm({
  "https://jsr.io/@std/path/1.0.8/relative.ts"() {
    init_os();
    init_relative2();
    init_relative3();
  }
});

// https://jsr.io/@std/path/1.0.8/resolve.ts
function resolve3(...pathSegments) {
  return isWindows ? resolve2(...pathSegments) : resolve(...pathSegments);
}
var init_resolve3 = __esm({
  "https://jsr.io/@std/path/1.0.8/resolve.ts"() {
    init_os();
    init_resolve();
    init_resolve2();
  }
});

// https://jsr.io/@std/path/1.0.8/_common/to_file_url.ts
function encodeWhitespace(string2) {
  return string2.replaceAll(/[\s]/g, (c6) => {
    return WHITESPACE_ENCODINGS[c6] ?? c6;
  });
}
var WHITESPACE_ENCODINGS;
var init_to_file_url = __esm({
  "https://jsr.io/@std/path/1.0.8/_common/to_file_url.ts"() {
    WHITESPACE_ENCODINGS = {
      "	": "%09",
      "\n": "%0A",
      "\v": "%0B",
      "\f": "%0C",
      "\r": "%0D",
      " ": "%20"
    };
  }
});

// https://jsr.io/@std/path/1.0.8/posix/to_file_url.ts
function toFileUrl(path3) {
  if (!isAbsolute(path3)) {
    throw new TypeError(`Path must be absolute: received "${path3}"`);
  }
  const url = new URL("file:///");
  url.pathname = encodeWhitespace(
    path3.replace(/%/g, "%25").replace(/\\/g, "%5C")
  );
  return url;
}
var init_to_file_url2 = __esm({
  "https://jsr.io/@std/path/1.0.8/posix/to_file_url.ts"() {
    init_to_file_url();
    init_is_absolute();
  }
});

// https://jsr.io/@std/path/1.0.8/windows/to_file_url.ts
function toFileUrl2(path3) {
  if (!isAbsolute2(path3)) {
    throw new TypeError(`Path must be absolute: received "${path3}"`);
  }
  const [, hostname, pathname] = path3.match(
    /^(?:[/\\]{2}([^/\\]+)(?=[/\\](?:[^/\\]|$)))?(.*)/
  );
  const url = new URL("file:///");
  url.pathname = encodeWhitespace(pathname.replace(/%/g, "%25"));
  if (hostname !== void 0 && hostname !== "localhost") {
    url.hostname = hostname;
    if (!url.hostname) {
      throw new TypeError(`Invalid hostname: "${url.hostname}"`);
    }
  }
  return url;
}
var init_to_file_url3 = __esm({
  "https://jsr.io/@std/path/1.0.8/windows/to_file_url.ts"() {
    init_to_file_url();
    init_is_absolute2();
  }
});

// https://jsr.io/@std/path/1.0.8/to_file_url.ts
function toFileUrl3(path3) {
  return isWindows ? toFileUrl2(path3) : toFileUrl(path3);
}
var init_to_file_url4 = __esm({
  "https://jsr.io/@std/path/1.0.8/to_file_url.ts"() {
    init_os();
    init_to_file_url2();
    init_to_file_url3();
  }
});

// https://jsr.io/@std/path/1.0.8/posix/to_namespaced_path.ts
var init_to_namespaced_path = __esm({
  "https://jsr.io/@std/path/1.0.8/posix/to_namespaced_path.ts"() {
  }
});

// https://jsr.io/@std/path/1.0.8/windows/to_namespaced_path.ts
var init_to_namespaced_path2 = __esm({
  "https://jsr.io/@std/path/1.0.8/windows/to_namespaced_path.ts"() {
    init_constants();
    init_util2();
    init_resolve2();
  }
});

// https://jsr.io/@std/path/1.0.8/to_namespaced_path.ts
var init_to_namespaced_path3 = __esm({
  "https://jsr.io/@std/path/1.0.8/to_namespaced_path.ts"() {
    init_os();
    init_to_namespaced_path();
    init_to_namespaced_path2();
  }
});

// https://jsr.io/@std/path/1.0.8/_common/common.ts
var init_common = __esm({
  "https://jsr.io/@std/path/1.0.8/_common/common.ts"() {
  }
});

// https://jsr.io/@std/path/1.0.8/common.ts
var init_common2 = __esm({
  "https://jsr.io/@std/path/1.0.8/common.ts"() {
    init_common();
    init_constants2();
  }
});

// https://jsr.io/@std/path/1.0.8/types.ts
var init_types = __esm({
  "https://jsr.io/@std/path/1.0.8/types.ts"() {
  }
});

// https://jsr.io/@std/path/1.0.8/_common/glob_to_reg_exp.ts
function _globToRegExp(c6, glob, {
  extended = true,
  globstar: globstarOption = true,
  // os = osType,
  caseInsensitive = false
} = {}) {
  if (glob === "") {
    return /(?!)/;
  }
  let newLength = glob.length;
  for (; newLength > 1 && c6.seps.includes(glob[newLength - 1]); newLength--) ;
  glob = glob.slice(0, newLength);
  let regExpString = "";
  for (let j3 = 0; j3 < glob.length; ) {
    let segment = "";
    const groupStack = [];
    let inRange = false;
    let inEscape = false;
    let endsWithSep = false;
    let i6 = j3;
    for (; i6 < glob.length && !c6.seps.includes(glob[i6]); i6++) {
      if (inEscape) {
        inEscape = false;
        const escapeChars = inRange ? RANGE_ESCAPE_CHARS : REG_EXP_ESCAPE_CHARS;
        segment += escapeChars.includes(glob[i6]) ? `\\${glob[i6]}` : glob[i6];
        continue;
      }
      if (glob[i6] === c6.escapePrefix) {
        inEscape = true;
        continue;
      }
      if (glob[i6] === "[") {
        if (!inRange) {
          inRange = true;
          segment += "[";
          if (glob[i6 + 1] === "!") {
            i6++;
            segment += "^";
          } else if (glob[i6 + 1] === "^") {
            i6++;
            segment += "\\^";
          }
          continue;
        } else if (glob[i6 + 1] === ":") {
          let k3 = i6 + 1;
          let value = "";
          while (glob[k3 + 1] !== void 0 && glob[k3 + 1] !== ":") {
            value += glob[k3 + 1];
            k3++;
          }
          if (glob[k3 + 1] === ":" && glob[k3 + 2] === "]") {
            i6 = k3 + 2;
            if (value === "alnum") segment += "\\dA-Za-z";
            else if (value === "alpha") segment += "A-Za-z";
            else if (value === "ascii") segment += "\0-\x7F";
            else if (value === "blank") segment += "	 ";
            else if (value === "cntrl") segment += "\0-\x7F";
            else if (value === "digit") segment += "\\d";
            else if (value === "graph") segment += "!-~";
            else if (value === "lower") segment += "a-z";
            else if (value === "print") segment += " -~";
            else if (value === "punct") {
              segment += `!"#$%&'()*+,\\-./:;<=>?@[\\\\\\]^_\u2018{|}~`;
            } else if (value === "space") segment += "\\s\v";
            else if (value === "upper") segment += "A-Z";
            else if (value === "word") segment += "\\w";
            else if (value === "xdigit") segment += "\\dA-Fa-f";
            continue;
          }
        }
      }
      if (glob[i6] === "]" && inRange) {
        inRange = false;
        segment += "]";
        continue;
      }
      if (inRange) {
        segment += glob[i6];
        continue;
      }
      if (glob[i6] === ")" && groupStack.length > 0 && groupStack[groupStack.length - 1] !== "BRACE") {
        segment += ")";
        const type4 = groupStack.pop();
        if (type4 === "!") {
          segment += c6.wildcard;
        } else if (type4 !== "@") {
          segment += type4;
        }
        continue;
      }
      if (glob[i6] === "|" && groupStack.length > 0 && groupStack[groupStack.length - 1] !== "BRACE") {
        segment += "|";
        continue;
      }
      if (glob[i6] === "+" && extended && glob[i6 + 1] === "(") {
        i6++;
        groupStack.push("+");
        segment += "(?:";
        continue;
      }
      if (glob[i6] === "@" && extended && glob[i6 + 1] === "(") {
        i6++;
        groupStack.push("@");
        segment += "(?:";
        continue;
      }
      if (glob[i6] === "?") {
        if (extended && glob[i6 + 1] === "(") {
          i6++;
          groupStack.push("?");
          segment += "(?:";
        } else {
          segment += ".";
        }
        continue;
      }
      if (glob[i6] === "!" && extended && glob[i6 + 1] === "(") {
        i6++;
        groupStack.push("!");
        segment += "(?!";
        continue;
      }
      if (glob[i6] === "{") {
        groupStack.push("BRACE");
        segment += "(?:";
        continue;
      }
      if (glob[i6] === "}" && groupStack[groupStack.length - 1] === "BRACE") {
        groupStack.pop();
        segment += ")";
        continue;
      }
      if (glob[i6] === "," && groupStack[groupStack.length - 1] === "BRACE") {
        segment += "|";
        continue;
      }
      if (glob[i6] === "*") {
        if (extended && glob[i6 + 1] === "(") {
          i6++;
          groupStack.push("*");
          segment += "(?:";
        } else {
          const prevChar = glob[i6 - 1];
          let numStars = 1;
          while (glob[i6 + 1] === "*") {
            i6++;
            numStars++;
          }
          const nextChar = glob[i6 + 1];
          if (globstarOption && numStars === 2 && [...c6.seps, void 0].includes(prevChar) && [...c6.seps, void 0].includes(nextChar)) {
            segment += c6.globstar;
            endsWithSep = true;
          } else {
            segment += c6.wildcard;
          }
        }
        continue;
      }
      segment += REG_EXP_ESCAPE_CHARS.includes(glob[i6]) ? `\\${glob[i6]}` : glob[i6];
    }
    if (groupStack.length > 0 || inRange || inEscape) {
      segment = "";
      for (const c7 of glob.slice(j3, i6)) {
        segment += REG_EXP_ESCAPE_CHARS.includes(c7) ? `\\${c7}` : c7;
        endsWithSep = false;
      }
    }
    regExpString += segment;
    if (!endsWithSep) {
      regExpString += i6 < glob.length ? c6.sep : c6.sepMaybe;
      endsWithSep = true;
    }
    while (c6.seps.includes(glob[i6])) i6++;
    j3 = i6;
  }
  regExpString = `^${regExpString}$`;
  return new RegExp(regExpString, caseInsensitive ? "i" : "");
}
var REG_EXP_ESCAPE_CHARS, RANGE_ESCAPE_CHARS;
var init_glob_to_reg_exp = __esm({
  "https://jsr.io/@std/path/1.0.8/_common/glob_to_reg_exp.ts"() {
    REG_EXP_ESCAPE_CHARS = [
      "!",
      "$",
      "(",
      ")",
      "*",
      "+",
      ".",
      "=",
      "?",
      "[",
      "\\",
      "^",
      "{",
      "|"
    ];
    RANGE_ESCAPE_CHARS = ["-", "\\", "]"];
  }
});

// https://jsr.io/@std/path/1.0.8/posix/glob_to_regexp.ts
function globToRegExp(glob, options = {}) {
  return _globToRegExp(constants, glob, options);
}
var constants;
var init_glob_to_regexp = __esm({
  "https://jsr.io/@std/path/1.0.8/posix/glob_to_regexp.ts"() {
    init_glob_to_reg_exp();
    constants = {
      sep: "/+",
      sepMaybe: "/*",
      seps: ["/"],
      globstar: "(?:[^/]*(?:/|$)+)*",
      wildcard: "[^/]*",
      escapePrefix: "\\"
    };
  }
});

// https://jsr.io/@std/path/1.0.8/windows/glob_to_regexp.ts
function globToRegExp2(glob, options = {}) {
  return _globToRegExp(constants2, glob, options);
}
var constants2;
var init_glob_to_regexp2 = __esm({
  "https://jsr.io/@std/path/1.0.8/windows/glob_to_regexp.ts"() {
    init_glob_to_reg_exp();
    constants2 = {
      sep: "(?:\\\\|/)+",
      sepMaybe: "(?:\\\\|/)*",
      seps: ["\\", "/"],
      globstar: "(?:[^\\\\/]*(?:\\\\|/|$)+)*",
      wildcard: "[^\\\\/]*",
      escapePrefix: "`"
    };
  }
});

// https://jsr.io/@std/path/1.0.8/glob_to_regexp.ts
function globToRegExp3(glob, options = {}) {
  return isWindows ? globToRegExp2(glob, options) : globToRegExp(glob, options);
}
var init_glob_to_regexp3 = __esm({
  "https://jsr.io/@std/path/1.0.8/glob_to_regexp.ts"() {
    init_os();
    init_glob_to_regexp();
    init_glob_to_regexp2();
  }
});

// https://jsr.io/@std/path/1.0.8/is_glob.ts
function isGlob(str3) {
  const chars = { "{": "}", "(": ")", "[": "]" };
  const regex = /\\(.)|(^!|\*|\?|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\)|\([^|]+\|[^\\)]+\))/;
  if (str3 === "") {
    return false;
  }
  let match;
  while (match = regex.exec(str3)) {
    if (match[2]) return true;
    let idx = match.index + match[0].length;
    const open = match[1];
    const close = open ? chars[open] : null;
    if (open && close) {
      const n5 = str3.indexOf(close, idx);
      if (n5 !== -1) {
        idx = n5 + 1;
      }
    }
    str3 = str3.slice(idx);
  }
  return false;
}
var init_is_glob = __esm({
  "https://jsr.io/@std/path/1.0.8/is_glob.ts"() {
  }
});

// https://jsr.io/@std/path/1.0.8/posix/constants.ts
var SEPARATOR2, SEPARATOR_PATTERN2;
var init_constants3 = __esm({
  "https://jsr.io/@std/path/1.0.8/posix/constants.ts"() {
    SEPARATOR2 = "/";
    SEPARATOR_PATTERN2 = /\/+/;
  }
});

// https://jsr.io/@std/path/1.0.8/posix/normalize_glob.ts
function normalizeGlob(glob, options = {}) {
  const { globstar = false } = options;
  if (glob.match(/\0/g)) {
    throw new Error(`Glob contains invalid characters: "${glob}"`);
  }
  if (!globstar) {
    return normalize(glob);
  }
  const s5 = SEPARATOR_PATTERN2.source;
  const badParentPattern = new RegExp(
    `(?<=(${s5}|^)\\*\\*${s5})\\.\\.(?=${s5}|$)`,
    "g"
  );
  return normalize(glob.replace(badParentPattern, "\0")).replace(/\0/g, "..");
}
var init_normalize_glob = __esm({
  "https://jsr.io/@std/path/1.0.8/posix/normalize_glob.ts"() {
    init_normalize2();
    init_constants3();
  }
});

// https://jsr.io/@std/path/1.0.8/posix/join_globs.ts
function joinGlobs(globs, options = {}) {
  const { globstar = false } = options;
  if (!globstar || globs.length === 0) {
    return join(...globs);
  }
  let joined;
  for (const glob of globs) {
    const path3 = glob;
    if (path3.length > 0) {
      if (!joined) joined = path3;
      else joined += `${SEPARATOR2}${path3}`;
    }
  }
  if (!joined) return ".";
  return normalizeGlob(joined, { globstar });
}
var init_join_globs = __esm({
  "https://jsr.io/@std/path/1.0.8/posix/join_globs.ts"() {
    init_join();
    init_constants3();
    init_normalize_glob();
  }
});

// https://jsr.io/@std/path/1.0.8/windows/constants.ts
var SEPARATOR3, SEPARATOR_PATTERN3;
var init_constants4 = __esm({
  "https://jsr.io/@std/path/1.0.8/windows/constants.ts"() {
    SEPARATOR3 = "\\";
    SEPARATOR_PATTERN3 = /[\\/]+/;
  }
});

// https://jsr.io/@std/path/1.0.8/windows/normalize_glob.ts
function normalizeGlob2(glob, options = {}) {
  const { globstar = false } = options;
  if (glob.match(/\0/g)) {
    throw new Error(`Glob contains invalid characters: "${glob}"`);
  }
  if (!globstar) {
    return normalize2(glob);
  }
  const s5 = SEPARATOR_PATTERN3.source;
  const badParentPattern = new RegExp(
    `(?<=(${s5}|^)\\*\\*${s5})\\.\\.(?=${s5}|$)`,
    "g"
  );
  return normalize2(glob.replace(badParentPattern, "\0")).replace(/\0/g, "..");
}
var init_normalize_glob2 = __esm({
  "https://jsr.io/@std/path/1.0.8/windows/normalize_glob.ts"() {
    init_normalize3();
    init_constants4();
  }
});

// https://jsr.io/@std/path/1.0.8/windows/join_globs.ts
function joinGlobs2(globs, options = {}) {
  const { globstar = false } = options;
  if (!globstar || globs.length === 0) {
    return join2(...globs);
  }
  let joined;
  for (const glob of globs) {
    const path3 = glob;
    if (path3.length > 0) {
      if (!joined) joined = path3;
      else joined += `${SEPARATOR3}${path3}`;
    }
  }
  if (!joined) return ".";
  return normalizeGlob2(joined, { globstar });
}
var init_join_globs2 = __esm({
  "https://jsr.io/@std/path/1.0.8/windows/join_globs.ts"() {
    init_join2();
    init_constants4();
    init_normalize_glob2();
  }
});

// https://jsr.io/@std/path/1.0.8/join_globs.ts
function joinGlobs3(globs, options = {}) {
  return isWindows ? joinGlobs2(globs, options) : joinGlobs(globs, options);
}
var init_join_globs3 = __esm({
  "https://jsr.io/@std/path/1.0.8/join_globs.ts"() {
    init_os();
    init_join_globs();
    init_join_globs2();
  }
});

// https://jsr.io/@std/path/1.0.8/normalize_glob.ts
var init_normalize_glob3 = __esm({
  "https://jsr.io/@std/path/1.0.8/normalize_glob.ts"() {
    init_os();
    init_normalize_glob();
    init_normalize_glob2();
  }
});

// https://jsr.io/@std/path/1.0.8/mod.ts
var init_mod2 = __esm({
  "https://jsr.io/@std/path/1.0.8/mod.ts"() {
    init_basename4();
    init_constants2();
    init_dirname4();
    init_extname3();
    init_format4();
    init_from_file_url4();
    init_is_absolute3();
    init_join3();
    init_normalize4();
    init_parse3();
    init_relative4();
    init_resolve3();
    init_to_file_url4();
    init_to_namespaced_path3();
    init_common2();
    init_types();
    init_glob_to_regexp3();
    init_is_glob();
    init_join_globs3();
    init_normalize_glob3();
  }
});

// https://jsr.io/@std/path/1.0.8/posix/common.ts
var init_common3 = __esm({
  "https://jsr.io/@std/path/1.0.8/posix/common.ts"() {
    init_common();
    init_constants3();
  }
});

// https://jsr.io/@std/path/1.0.8/posix/is_glob.ts
var init_is_glob2 = __esm({
  "https://jsr.io/@std/path/1.0.8/posix/is_glob.ts"() {
    init_is_glob();
  }
});

// https://jsr.io/@std/path/1.0.8/posix/mod.ts
var init_mod3 = __esm({
  "https://jsr.io/@std/path/1.0.8/posix/mod.ts"() {
    init_basename2();
    init_constants3();
    init_dirname2();
    init_extname();
    init_format2();
    init_from_file_url2();
    init_is_absolute();
    init_join();
    init_normalize2();
    init_parse();
    init_relative2();
    init_resolve();
    init_to_file_url2();
    init_to_namespaced_path();
    init_common3();
    init_types();
    init_glob_to_regexp();
    init_is_glob2();
    init_join_globs();
    init_normalize_glob();
  }
});

// deno_ral/path.ts
var SEP, SEP_PATTERN, basename4, extname4, dirname4, fromFileUrl4, globToRegExp4, isAbsolute4, join4, relative4, resolve4, normalize4, toFileUrl4, isGlob2, posix;
var init_path = __esm({
  "deno_ral/path.ts"() {
    init_mod2();
    init_mod3();
    SEP = SEPARATOR;
    SEP_PATTERN = SEPARATOR_PATTERN;
    basename4 = basename3;
    extname4 = extname3;
    dirname4 = dirname3;
    fromFileUrl4 = fromFileUrl3;
    globToRegExp4 = globToRegExp3;
    isAbsolute4 = isAbsolute3;
    join4 = join3;
    relative4 = relative3;
    resolve4 = resolve3;
    normalize4 = normalize3;
    toFileUrl4 = toFileUrl3;
    isGlob2 = isGlob;
    posix = { normalize };
  }
});

// https://jsr.io/@std/fs/1.0.16/_get_file_info_type.ts
function getFileInfoType(fileInfo) {
  return fileInfo.isFile ? "file" : fileInfo.isDirectory ? "dir" : fileInfo.isSymlink ? "symlink" : void 0;
}
var init_get_file_info_type = __esm({
  "https://jsr.io/@std/fs/1.0.16/_get_file_info_type.ts"() {
  }
});

// https://jsr.io/@std/fs/1.0.16/ensure_dir.ts
async function ensureDir(dir) {
  try {
    const fileInfo = await Deno.stat(dir);
    throwIfNotDirectory(fileInfo);
    return;
  } catch (err2) {
    if (!(err2 instanceof Deno.errors.NotFound)) {
      throw err2;
    }
  }
  try {
    await Deno.mkdir(dir, { recursive: true });
  } catch (err2) {
    if (!(err2 instanceof Deno.errors.AlreadyExists)) {
      throw err2;
    }
    const fileInfo = await Deno.stat(dir);
    throwIfNotDirectory(fileInfo);
  }
}
function ensureDirSync(dir) {
  try {
    const fileInfo = Deno.statSync(dir);
    throwIfNotDirectory(fileInfo);
    return;
  } catch (err2) {
    if (!(err2 instanceof Deno.errors.NotFound)) {
      throw err2;
    }
  }
  try {
    Deno.mkdirSync(dir, { recursive: true });
  } catch (err2) {
    if (!(err2 instanceof Deno.errors.AlreadyExists)) {
      throw err2;
    }
    const fileInfo = Deno.statSync(dir);
    throwIfNotDirectory(fileInfo);
  }
}
function throwIfNotDirectory(fileInfo) {
  if (!fileInfo.isDirectory) {
    throw new Error(
      `Failed to ensure directory exists: expected 'dir', got '${getFileInfoType(fileInfo)}'`
    );
  }
}
var init_ensure_dir = __esm({
  "https://jsr.io/@std/fs/1.0.16/ensure_dir.ts"() {
    init_get_file_info_type();
  }
});

// https://jsr.io/@std/fs/1.0.16/_to_path_string.ts
function toPathString(pathUrl) {
  return pathUrl instanceof URL ? fromFileUrl3(pathUrl) : pathUrl;
}
var init_to_path_string = __esm({
  "https://jsr.io/@std/fs/1.0.16/_to_path_string.ts"() {
    init_from_file_url4();
  }
});

// https://jsr.io/@std/fs/1.0.16/_is_subdir.ts
function isSubdir(src2, dest, sep6 = SEPARATOR) {
  src2 = toPathString(src2);
  dest = toPathString(dest);
  if (resolve3(src2) === resolve3(dest)) {
    return false;
  }
  const srcArray = src2.split(sep6);
  const destArray = dest.split(sep6);
  return srcArray.every((current3, i6) => destArray[i6] === current3);
}
var init_is_subdir = __esm({
  "https://jsr.io/@std/fs/1.0.16/_is_subdir.ts"() {
    init_resolve3();
    init_constants2();
    init_to_path_string();
  }
});

// https://jsr.io/@std/fs/1.0.16/copy.ts
function assertIsDate(date, name2) {
  if (date === null) {
    throw new Error(`${name2} is unavailable`);
  }
}
async function ensureValidCopy(src2, dest, options) {
  let destStat;
  try {
    destStat = await Deno.lstat(dest);
  } catch (err2) {
    if (err2 instanceof Deno.errors.NotFound) {
      return;
    }
    throw err2;
  }
  if (options.isFolder && !destStat.isDirectory) {
    throw new Error(
      `Cannot overwrite non-directory '${dest}' with directory '${src2}'`
    );
  }
  if (!options.overwrite) {
    throw new Deno.errors.AlreadyExists(`'${dest}' already exists.`);
  }
  return destStat;
}
function ensureValidCopySync(src2, dest, options) {
  let destStat;
  try {
    destStat = Deno.lstatSync(dest);
  } catch (err2) {
    if (err2 instanceof Deno.errors.NotFound) {
      return;
    }
    throw err2;
  }
  if (options.isFolder && !destStat.isDirectory) {
    throw new Error(
      `Cannot overwrite non-directory '${dest}' with directory '${src2}'`
    );
  }
  if (!options.overwrite) {
    throw new Deno.errors.AlreadyExists(`'${dest}' already exists`);
  }
  return destStat;
}
async function copyFile(src2, dest, options) {
  await ensureValidCopy(src2, dest, options);
  await Deno.copyFile(src2, dest);
  if (options.preserveTimestamps) {
    const statInfo = await Deno.stat(src2);
    assertIsDate(statInfo.atime, "statInfo.atime");
    assertIsDate(statInfo.mtime, "statInfo.mtime");
    await Deno.utime(dest, statInfo.atime, statInfo.mtime);
  }
}
function copyFileSync(src2, dest, options) {
  ensureValidCopySync(src2, dest, options);
  Deno.copyFileSync(src2, dest);
  if (options.preserveTimestamps) {
    const statInfo = Deno.statSync(src2);
    assertIsDate(statInfo.atime, "statInfo.atime");
    assertIsDate(statInfo.mtime, "statInfo.mtime");
    Deno.utimeSync(dest, statInfo.atime, statInfo.mtime);
  }
}
async function copySymLink(src2, dest, options) {
  await ensureValidCopy(src2, dest, options);
  const originSrcFilePath = await Deno.readLink(src2);
  const type4 = getFileInfoType(await Deno.lstat(src2));
  if (isWindows2) {
    await Deno.symlink(originSrcFilePath, dest, {
      type: type4 === "dir" ? "dir" : "file"
    });
  } else {
    await Deno.symlink(originSrcFilePath, dest);
  }
  if (options.preserveTimestamps) {
    const statInfo = await Deno.lstat(src2);
    assertIsDate(statInfo.atime, "statInfo.atime");
    assertIsDate(statInfo.mtime, "statInfo.mtime");
    await Deno.utime(dest, statInfo.atime, statInfo.mtime);
  }
}
function copySymlinkSync(src2, dest, options) {
  ensureValidCopySync(src2, dest, options);
  const originSrcFilePath = Deno.readLinkSync(src2);
  const type4 = getFileInfoType(Deno.lstatSync(src2));
  if (isWindows2) {
    Deno.symlinkSync(originSrcFilePath, dest, {
      type: type4 === "dir" ? "dir" : "file"
    });
  } else {
    Deno.symlinkSync(originSrcFilePath, dest);
  }
  if (options.preserveTimestamps) {
    const statInfo = Deno.lstatSync(src2);
    assertIsDate(statInfo.atime, "statInfo.atime");
    assertIsDate(statInfo.mtime, "statInfo.mtime");
    Deno.utimeSync(dest, statInfo.atime, statInfo.mtime);
  }
}
async function copyDir(src2, dest, options) {
  const destStat = await ensureValidCopy(src2, dest, {
    ...options,
    isFolder: true
  });
  if (!destStat) {
    await ensureDir(dest);
  }
  if (options.preserveTimestamps) {
    const srcStatInfo = await Deno.stat(src2);
    assertIsDate(srcStatInfo.atime, "statInfo.atime");
    assertIsDate(srcStatInfo.mtime, "statInfo.mtime");
    await Deno.utime(dest, srcStatInfo.atime, srcStatInfo.mtime);
  }
  src2 = toPathString(src2);
  dest = toPathString(dest);
  const promises2 = [];
  for await (const entry of Deno.readDir(src2)) {
    const srcPath = join3(src2, entry.name);
    const destPath = join3(dest, basename3(srcPath));
    if (entry.isSymlink) {
      promises2.push(copySymLink(srcPath, destPath, options));
    } else if (entry.isDirectory) {
      promises2.push(copyDir(srcPath, destPath, options));
    } else if (entry.isFile) {
      promises2.push(copyFile(srcPath, destPath, options));
    }
  }
  await Promise.all(promises2);
}
function copyDirSync(src2, dest, options) {
  const destStat = ensureValidCopySync(src2, dest, {
    ...options,
    isFolder: true
  });
  if (!destStat) {
    ensureDirSync(dest);
  }
  if (options.preserveTimestamps) {
    const srcStatInfo = Deno.statSync(src2);
    assertIsDate(srcStatInfo.atime, "statInfo.atime");
    assertIsDate(srcStatInfo.mtime, "statInfo.mtime");
    Deno.utimeSync(dest, srcStatInfo.atime, srcStatInfo.mtime);
  }
  src2 = toPathString(src2);
  dest = toPathString(dest);
  for (const entry of Deno.readDirSync(src2)) {
    const srcPath = join3(src2, entry.name);
    const destPath = join3(dest, basename3(srcPath));
    if (entry.isSymlink) {
      copySymlinkSync(srcPath, destPath, options);
    } else if (entry.isDirectory) {
      copyDirSync(srcPath, destPath, options);
    } else if (entry.isFile) {
      copyFileSync(srcPath, destPath, options);
    }
  }
}
async function copy(src2, dest, options = {}) {
  src2 = resolve3(toPathString(src2));
  dest = resolve3(toPathString(dest));
  if (src2 === dest) {
    throw new Error("Source and destination cannot be the same");
  }
  const srcStat = await Deno.lstat(src2);
  if (srcStat.isDirectory && isSubdir(src2, dest)) {
    throw new Error(
      `Cannot copy '${src2}' to a subdirectory of itself: '${dest}'`
    );
  }
  if (srcStat.isSymlink) {
    await copySymLink(src2, dest, options);
  } else if (srcStat.isDirectory) {
    await copyDir(src2, dest, options);
  } else if (srcStat.isFile) {
    await copyFile(src2, dest, options);
  }
}
function copySync(src2, dest, options = {}) {
  src2 = resolve3(toPathString(src2));
  dest = resolve3(toPathString(dest));
  if (src2 === dest) {
    throw new Error("Source and destination cannot be the same");
  }
  const srcStat = Deno.lstatSync(src2);
  if (srcStat.isDirectory && isSubdir(src2, dest)) {
    throw new Error(
      `Cannot copy '${src2}' to a subdirectory of itself: '${dest}'`
    );
  }
  if (srcStat.isSymlink) {
    copySymlinkSync(src2, dest, options);
  } else if (srcStat.isDirectory) {
    copyDirSync(src2, dest, options);
  } else if (srcStat.isFile) {
    copyFileSync(src2, dest, options);
  }
}
var isWindows2;
var init_copy = __esm({
  "https://jsr.io/@std/fs/1.0.16/copy.ts"() {
    init_basename4();
    init_join3();
    init_resolve3();
    init_ensure_dir();
    init_get_file_info_type();
    init_to_path_string();
    init_is_subdir();
    isWindows2 = globalThis.Deno?.build.os === "windows";
  }
});

// https://jsr.io/@std/fs/1.0.16/exists.ts
function existsSync2(path3, options) {
  try {
    const stat = Deno.statSync(path3);
    if (options && (options.isReadable || options.isDirectory || options.isFile)) {
      if (options.isDirectory && options.isFile) {
        throw new TypeError(
          "ExistsOptions.options.isDirectory and ExistsOptions.options.isFile must not be true together"
        );
      }
      if (options.isDirectory && !stat.isDirectory || options.isFile && !stat.isFile) {
        return false;
      }
      if (options.isReadable) {
        return fileIsReadable(stat);
      }
    }
    return true;
  } catch (error2) {
    if (error2 instanceof Deno.errors.NotFound) {
      return false;
    }
    if (error2 instanceof Deno.errors.PermissionDenied) {
      if (Deno.permissions.querySync({ name: "read", path: path3 }).state === "granted") {
        return !options?.isReadable;
      }
    }
    throw error2;
  }
}
function fileIsReadable(stat) {
  if (stat.mode === null) {
    return true;
  } else if (Deno.uid() === stat.uid) {
    return (stat.mode & 256) === 256;
  } else if (Deno.gid() === stat.gid) {
    return (stat.mode & 32) === 32;
  }
  return (stat.mode & 4) === 4;
}
var init_exists2 = __esm({
  "https://jsr.io/@std/fs/1.0.16/exists.ts"() {
  }
});

// https://jsr.io/@std/fs/1.0.16/_create_walk_entry.ts
function createWalkEntrySync(path3) {
  path3 = toPathString(path3);
  path3 = normalize3(path3);
  const name2 = basename3(path3);
  const info2 = Deno.statSync(path3);
  return {
    path: path3,
    name: name2,
    isFile: info2.isFile,
    isDirectory: info2.isDirectory,
    isSymlink: info2.isSymlink
  };
}
async function createWalkEntry(path3) {
  path3 = toPathString(path3);
  path3 = normalize3(path3);
  const name2 = basename3(path3);
  const info2 = await Deno.stat(path3);
  return {
    path: path3,
    name: name2,
    isFile: info2.isFile,
    isDirectory: info2.isDirectory,
    isSymlink: info2.isSymlink
  };
}
var init_create_walk_entry = __esm({
  "https://jsr.io/@std/fs/1.0.16/_create_walk_entry.ts"() {
    init_basename4();
    init_normalize4();
    init_to_path_string();
  }
});

// https://jsr.io/@std/fs/1.0.16/walk.ts
function include(path3, exts, match, skip) {
  if (exts && !exts.some((ext) => path3.endsWith(ext))) {
    return false;
  }
  if (match && !match.some((pattern) => !!path3.match(pattern))) {
    return false;
  }
  if (skip && skip.some((pattern) => !!path3.match(pattern))) {
    return false;
  }
  return true;
}
async function* walk(root, options) {
  let {
    maxDepth = Infinity,
    includeFiles = true,
    includeDirs = true,
    includeSymlinks = true,
    followSymlinks = false,
    canonicalize: canonicalize2 = true,
    exts = void 0,
    match = void 0,
    skip = void 0
  } = options ?? {};
  if (maxDepth < 0) {
    return;
  }
  root = toPathString(root);
  if (exts) {
    exts = exts.map((ext) => ext.startsWith(".") ? ext : `.${ext}`);
  }
  if (includeDirs && include(root, exts, match, skip)) {
    yield await createWalkEntry(root);
  }
  if (maxDepth < 1 || !include(root, void 0, void 0, skip)) {
    return;
  }
  for await (const entry of Deno.readDir(root)) {
    let path3 = join3(root, entry.name);
    let { isSymlink, isDirectory: isDirectory2 } = entry;
    if (isSymlink) {
      if (!followSymlinks) {
        if (includeSymlinks && include(path3, exts, match, skip)) {
          yield { path: path3, ...entry };
        }
        continue;
      }
      const realPath = await Deno.realPath(path3);
      if (canonicalize2) {
        path3 = realPath;
      }
      ({ isSymlink, isDirectory: isDirectory2 } = await Deno.lstat(realPath));
    }
    if (isSymlink || isDirectory2) {
      const opts = {
        maxDepth: maxDepth - 1,
        includeFiles,
        includeDirs,
        includeSymlinks,
        followSymlinks
      };
      if (exts !== void 0) {
        opts.exts = exts;
      }
      if (match !== void 0) {
        opts.match = match;
      }
      if (skip !== void 0) {
        opts.skip = skip;
      }
      yield* walk(path3, opts);
    } else if (includeFiles && include(path3, exts, match, skip)) {
      yield { path: path3, ...entry };
    }
  }
}
function* walkSync(root, options) {
  let {
    maxDepth = Infinity,
    includeFiles = true,
    includeDirs = true,
    includeSymlinks = true,
    followSymlinks = false,
    canonicalize: canonicalize2 = true,
    exts = void 0,
    match = void 0,
    skip = void 0
  } = options ?? {};
  root = toPathString(root);
  if (exts) {
    exts = exts.map((ext) => ext.startsWith(".") ? ext : `.${ext}`);
  }
  if (maxDepth < 0) {
    return;
  }
  if (includeDirs && include(root, exts, match, skip)) {
    yield createWalkEntrySync(root);
  }
  if (maxDepth < 1 || !include(root, void 0, void 0, skip)) {
    return;
  }
  const entries = Deno.readDirSync(root);
  for (const entry of entries) {
    let path3 = join3(root, entry.name);
    let { isSymlink, isDirectory: isDirectory2 } = entry;
    if (isSymlink) {
      if (!followSymlinks) {
        if (includeSymlinks && include(path3, exts, match, skip)) {
          yield { path: path3, ...entry };
        }
        continue;
      }
      const realPath = Deno.realPathSync(path3);
      if (canonicalize2) {
        path3 = realPath;
      }
      ({ isSymlink, isDirectory: isDirectory2 } = Deno.lstatSync(realPath));
    }
    if (isSymlink || isDirectory2) {
      const opts = {
        maxDepth: maxDepth - 1,
        includeFiles,
        includeDirs,
        includeSymlinks,
        followSymlinks
      };
      if (exts !== void 0) {
        opts.exts = exts;
      }
      if (match !== void 0) {
        opts.match = match;
      }
      if (skip !== void 0) {
        opts.skip = skip;
      }
      yield* walkSync(path3, opts);
    } else if (includeFiles && include(path3, exts, match, skip)) {
      yield { path: path3, ...entry };
    }
  }
}
var init_walk = __esm({
  "https://jsr.io/@std/fs/1.0.16/walk.ts"() {
    init_join3();
    init_to_path_string();
    init_create_walk_entry();
  }
});

// https://jsr.io/@std/fs/1.0.16/expand_glob.ts
function split(path3) {
  const s5 = SEPARATOR_PATTERN.source;
  const segments = path3.replace(new RegExp(`^${s5}|${s5}$`, "g"), "").split(SEPARATOR_PATTERN);
  const isAbsolute_ = isAbsolute3(path3);
  const split2 = {
    segments,
    isAbsolute: isAbsolute_,
    hasTrailingSep: path3.match(new RegExp(`${s5}$`)) !== null
  };
  if (isWindows3 && isAbsolute_) {
    split2.winRoot = segments.shift();
  }
  return split2;
}
function throwUnlessNotFound(error2) {
  if (!(error2 instanceof Deno.errors.NotFound)) {
    throw error2;
  }
}
function comparePath(a5, b3) {
  if (a5.path < b3.path) return -1;
  if (a5.path > b3.path) return 1;
  return 0;
}
function* expandGlobSync(glob, options) {
  let {
    root,
    exclude = [],
    includeDirs = true,
    extended = true,
    globstar = true,
    caseInsensitive = false,
    followSymlinks = false,
    canonicalize: canonicalize2 = true
  } = options ?? {};
  const {
    segments,
    isAbsolute: isGlobAbsolute,
    hasTrailingSep,
    winRoot
  } = split(toPathString(glob));
  root ??= isGlobAbsolute ? winRoot ?? "/" : Deno.cwd();
  const globOptions = { extended, globstar, caseInsensitive };
  const absRoot = isGlobAbsolute ? root : resolve3(root);
  const resolveFromRoot = (path3) => resolve3(absRoot, path3);
  const excludePatterns = exclude.map(resolveFromRoot).map((s5) => globToRegExp3(s5, globOptions));
  const shouldInclude2 = (path3) => !excludePatterns.some((p5) => !!path3.match(p5));
  let fixedRoot = isGlobAbsolute ? winRoot ?? "/" : absRoot;
  while (segments.length > 0 && !isGlob(segments[0])) {
    const seg = segments.shift();
    fixedRoot = joinGlobs3([fixedRoot, seg], globOptions);
  }
  let fixedRootInfo;
  try {
    fixedRootInfo = createWalkEntrySync(fixedRoot);
  } catch (error2) {
    return throwUnlessNotFound(error2);
  }
  function* advanceMatch(walkInfo, globSegment) {
    if (!walkInfo.isDirectory) {
      return;
    } else if (globSegment === "..") {
      const parentPath = joinGlobs3([walkInfo.path, ".."], globOptions);
      if (shouldInclude2(parentPath)) {
        return yield createWalkEntrySync(parentPath);
      }
      return;
    } else if (globSegment === "**") {
      return yield* walkSync(walkInfo.path, {
        skip: excludePatterns,
        maxDepth: globstar ? Infinity : 1,
        followSymlinks,
        canonicalize: canonicalize2
      });
    }
    const globPattern = globToRegExp3(globSegment, globOptions);
    for (const walkEntry of walkSync(walkInfo.path, {
      maxDepth: 1,
      skip: excludePatterns,
      followSymlinks
    })) {
      if (walkEntry.path !== walkInfo.path && walkEntry.name.match(globPattern)) {
        yield walkEntry;
      }
    }
  }
  let currentMatches = [fixedRootInfo];
  for (const segment of segments) {
    const nextMatchMap = /* @__PURE__ */ new Map();
    for (const currentMatch of currentMatches) {
      for (const nextMatch of advanceMatch(currentMatch, segment)) {
        nextMatchMap.set(nextMatch.path, nextMatch);
      }
    }
    currentMatches = [...nextMatchMap.values()].sort(comparePath);
  }
  if (hasTrailingSep) {
    currentMatches = currentMatches.filter(
      (entry) => entry.isDirectory
    );
  }
  if (!includeDirs) {
    currentMatches = currentMatches.filter(
      (entry) => !entry.isDirectory
    );
  }
  yield* currentMatches;
}
var isWindows3;
var init_expand_glob = __esm({
  "https://jsr.io/@std/fs/1.0.16/expand_glob.ts"() {
    init_glob_to_regexp3();
    init_join_globs3();
    init_is_glob();
    init_is_absolute3();
    init_resolve3();
    init_constants2();
    init_walk();
    init_to_path_string();
    init_create_walk_entry();
    isWindows3 = globalThis.Deno?.build.os === "windows";
  }
});

// https://jsr.io/@std/fs/1.0.16/eol.ts
function format3(content, eol) {
  return content.replace(regDetect, eol);
}
var LF, CRLF, EOL, regDetect;
var init_eol = __esm({
  "https://jsr.io/@std/fs/1.0.16/eol.ts"() {
    LF = "\n";
    CRLF = "\r\n";
    EOL = // deno-lint-ignore no-explicit-any
    globalThis.Deno?.build.os === "windows" ? CRLF : LF;
    regDetect = /(?:\r?\n)/g;
  }
});

// https://jsr.io/@std/fs/1.0.16/_is_same_path.ts
function isSamePath(src2, dest) {
  src2 = toPathString(src2);
  dest = toPathString(dest);
  return resolve3(src2) === resolve3(dest);
}
var init_is_same_path = __esm({
  "https://jsr.io/@std/fs/1.0.16/_is_same_path.ts"() {
    init_resolve3();
    init_to_path_string();
  }
});

// https://jsr.io/@std/fs/1.0.16/move.ts
function moveSync(src2, dest, options) {
  const { overwrite = false } = options ?? {};
  const srcStat = Deno.statSync(src2);
  if (srcStat.isDirectory && (isSubdir(src2, dest) || isSamePath(src2, dest))) {
    throw new Deno.errors.NotSupported(
      `Cannot move '${src2}' to a subdirectory of itself, '${dest}'.`
    );
  }
  if (overwrite) {
    if (isSamePath(src2, dest)) return;
    try {
      Deno.removeSync(dest, { recursive: true });
    } catch (error2) {
      if (!(error2 instanceof Deno.errors.NotFound)) {
        throw error2;
      }
    }
  } else {
    try {
      Deno.lstatSync(dest);
      throw EXISTS_ERROR;
    } catch (error2) {
      if (error2 === EXISTS_ERROR) {
        throw error2;
      }
    }
  }
  Deno.renameSync(src2, dest);
}
var EXISTS_ERROR;
var init_move = __esm({
  "https://jsr.io/@std/fs/1.0.16/move.ts"() {
    init_is_subdir();
    init_is_same_path();
    EXISTS_ERROR = new Deno.errors.AlreadyExists("dest already exists.");
  }
});

// https://jsr.io/@std/fs/1.0.16/empty_dir.ts
var init_empty_dir = __esm({
  "https://jsr.io/@std/fs/1.0.16/empty_dir.ts"() {
    init_join3();
    init_to_path_string();
  }
});

// deno_ral/fs.ts
function getFileInfoType2(fileInfo) {
  return fileInfo.isFile ? "file" : fileInfo.isDirectory ? "dir" : fileInfo.isSymlink ? "symlink" : void 0;
}
function isSubdir2(path1, path22, sep6 = SEP) {
  path1 = toPathString2(path1);
  path22 = toPathString2(path22);
  path1 = resolve4(path1);
  path22 = resolve4(path22);
  if (path1 === path22) {
    return false;
  }
  const path1Array = path1.split(sep6);
  const path2Array = path22.split(sep6);
  return path1Array.every((current3, i6) => path2Array[i6] === current3);
}
function toPathString2(pathUrl) {
  return pathUrl instanceof URL ? fromFileUrl4(pathUrl) : pathUrl;
}
function safeMoveSync(src2, dest) {
  try {
    Deno.renameSync(src2, dest);
  } catch (err2) {
    if (err2.code !== "EXDEV") {
      throw err2;
    }
    copySync(src2, dest, { overwrite: true });
    safeRemoveSync(src2, { recursive: true });
  }
}
function safeRemoveSync(file, options = {}) {
  try {
    Deno.removeSync(file, options);
  } catch (e5) {
    if (existsSync2(file)) {
      throw e5;
    }
  }
}
function safeRemoveDirSync(path3, boundary) {
  let resolvedPath = path3;
  let resolvedBoundary = boundary;
  try {
    resolvedPath = originalRealPathSync(path3);
    resolvedBoundary = originalRealPathSync(boundary);
  } catch {
  }
  if (resolvedPath === resolvedBoundary || !isSubdir2(resolvedBoundary, resolvedPath)) {
    throw new UnsafeRemovalError(
      `Refusing to remove directory ${path3} that isn't a subdirectory of ${boundary}`
    );
  }
  return safeRemoveSync(path3, { recursive: true });
}
function safeModeFromFile(path3) {
  if (Deno.build.os !== "windows") {
    const stat = Deno.statSync(path3);
    if (stat.mode !== null) {
      return stat.mode;
    }
  }
}
function safeChmodSync(path3, mode) {
  if (Deno.build.os !== "windows") {
    try {
      Deno.chmodSync(path3, mode);
    } catch (e5) {
      debug(`safeChmodSync: failed to chmod ${path3}: ${e5}`);
    }
  }
}
function ensureUserWritable(path3) {
  const mode = safeModeFromFile(path3);
  if (mode !== void 0 && !(mode & 128)) {
    safeChmodSync(path3, mode | 128);
  }
}
var UnsafeRemovalError;
var init_fs = __esm({
  "deno_ral/fs.ts"() {
    init_path();
    init_path();
    init_copy();
    init_exists2();
    init_original_real_path();
    init_log();
    init_ensure_dir();
    init_exists2();
    init_walk();
    init_expand_glob();
    init_eol();
    init_copy();
    init_move();
    init_empty_dir();
    UnsafeRemovalError = class extends Error {
      constructor(msg5) {
        super(msg5);
      }
    };
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_listCacheClear.js
var require_listCacheClear = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_listCacheClear.js"(exports23, module2) {
    function listCacheClear() {
      this.__data__ = [];
      this.size = 0;
    }
    module2.exports = listCacheClear;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/eq.js
var require_eq = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/eq.js"(exports23, module2) {
    function eq2(value, other) {
      return value === other || value !== value && other !== other;
    }
    module2.exports = eq2;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_assocIndexOf.js
var require_assocIndexOf = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_assocIndexOf.js"(exports23, module2) {
    var eq2 = require_eq();
    function assocIndexOf(array, key) {
      var length = array.length;
      while (length--) {
        if (eq2(array[length][0], key)) {
          return length;
        }
      }
      return -1;
    }
    module2.exports = assocIndexOf;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_listCacheDelete.js
var require_listCacheDelete = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_listCacheDelete.js"(exports23, module2) {
    var assocIndexOf = require_assocIndexOf();
    var arrayProto = Array.prototype;
    var splice2 = arrayProto.splice;
    function listCacheDelete(key) {
      var data3 = this.__data__, index2 = assocIndexOf(data3, key);
      if (index2 < 0) {
        return false;
      }
      var lastIndex = data3.length - 1;
      if (index2 == lastIndex) {
        data3.pop();
      } else {
        splice2.call(data3, index2, 1);
      }
      --this.size;
      return true;
    }
    module2.exports = listCacheDelete;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_listCacheGet.js
var require_listCacheGet = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_listCacheGet.js"(exports23, module2) {
    var assocIndexOf = require_assocIndexOf();
    function listCacheGet(key) {
      var data3 = this.__data__, index2 = assocIndexOf(data3, key);
      return index2 < 0 ? void 0 : data3[index2][1];
    }
    module2.exports = listCacheGet;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_listCacheHas.js
var require_listCacheHas = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_listCacheHas.js"(exports23, module2) {
    var assocIndexOf = require_assocIndexOf();
    function listCacheHas(key) {
      return assocIndexOf(this.__data__, key) > -1;
    }
    module2.exports = listCacheHas;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_listCacheSet.js
var require_listCacheSet = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_listCacheSet.js"(exports23, module2) {
    var assocIndexOf = require_assocIndexOf();
    function listCacheSet(key, value) {
      var data3 = this.__data__, index2 = assocIndexOf(data3, key);
      if (index2 < 0) {
        ++this.size;
        data3.push([key, value]);
      } else {
        data3[index2][1] = value;
      }
      return this;
    }
    module2.exports = listCacheSet;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_ListCache.js
var require_ListCache = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_ListCache.js"(exports23, module2) {
    var listCacheClear = require_listCacheClear();
    var listCacheDelete = require_listCacheDelete();
    var listCacheGet = require_listCacheGet();
    var listCacheHas = require_listCacheHas();
    var listCacheSet = require_listCacheSet();
    function ListCache(entries) {
      var index2 = -1, length = entries == null ? 0 : entries.length;
      this.clear();
      while (++index2 < length) {
        var entry = entries[index2];
        this.set(entry[0], entry[1]);
      }
    }
    ListCache.prototype.clear = listCacheClear;
    ListCache.prototype["delete"] = listCacheDelete;
    ListCache.prototype.get = listCacheGet;
    ListCache.prototype.has = listCacheHas;
    ListCache.prototype.set = listCacheSet;
    module2.exports = ListCache;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_stackClear.js
var require_stackClear = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_stackClear.js"(exports23, module2) {
    var ListCache = require_ListCache();
    function stackClear() {
      this.__data__ = new ListCache();
      this.size = 0;
    }
    module2.exports = stackClear;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_stackDelete.js
var require_stackDelete = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_stackDelete.js"(exports23, module2) {
    function stackDelete(key) {
      var data3 = this.__data__, result2 = data3["delete"](key);
      this.size = data3.size;
      return result2;
    }
    module2.exports = stackDelete;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_stackGet.js
var require_stackGet = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_stackGet.js"(exports23, module2) {
    function stackGet(key) {
      return this.__data__.get(key);
    }
    module2.exports = stackGet;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_stackHas.js
var require_stackHas = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_stackHas.js"(exports23, module2) {
    function stackHas(key) {
      return this.__data__.has(key);
    }
    module2.exports = stackHas;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_freeGlobal.js
var require_freeGlobal = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_freeGlobal.js"(exports23, module2) {
    var freeGlobal = typeof global == "object" && global && global.Object === Object && global;
    module2.exports = freeGlobal;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_root.js
var require_root = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_root.js"(exports23, module2) {
    var freeGlobal = require_freeGlobal();
    var freeSelf = typeof self == "object" && self && self.Object === Object && self;
    var root = freeGlobal || freeSelf || Function("return this")();
    module2.exports = root;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_Symbol.js
var require_Symbol = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_Symbol.js"(exports23, module2) {
    var root = require_root();
    var Symbol2 = root.Symbol;
    module2.exports = Symbol2;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_getRawTag.js
var require_getRawTag = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_getRawTag.js"(exports23, module2) {
    var Symbol2 = require_Symbol();
    var objectProto = Object.prototype;
    var hasOwnProperty3 = objectProto.hasOwnProperty;
    var nativeObjectToString = objectProto.toString;
    var symToStringTag = Symbol2 ? Symbol2.toStringTag : void 0;
    function getRawTag(value) {
      var isOwn = hasOwnProperty3.call(value, symToStringTag), tag = value[symToStringTag];
      try {
        value[symToStringTag] = void 0;
        var unmasked = true;
      } catch (e5) {
      }
      var result2 = nativeObjectToString.call(value);
      if (unmasked) {
        if (isOwn) {
          value[symToStringTag] = tag;
        } else {
          delete value[symToStringTag];
        }
      }
      return result2;
    }
    module2.exports = getRawTag;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_objectToString.js
var require_objectToString = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_objectToString.js"(exports23, module2) {
    var objectProto = Object.prototype;
    var nativeObjectToString = objectProto.toString;
    function objectToString(value) {
      return nativeObjectToString.call(value);
    }
    module2.exports = objectToString;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseGetTag.js
var require_baseGetTag = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseGetTag.js"(exports23, module2) {
    var Symbol2 = require_Symbol();
    var getRawTag = require_getRawTag();
    var objectToString = require_objectToString();
    var nullTag = "[object Null]";
    var undefinedTag = "[object Undefined]";
    var symToStringTag = Symbol2 ? Symbol2.toStringTag : void 0;
    function baseGetTag(value) {
      if (value == null) {
        return value === void 0 ? undefinedTag : nullTag;
      }
      return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value);
    }
    module2.exports = baseGetTag;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/isObject.js
var require_isObject = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/isObject.js"(exports23, module2) {
    function isObject7(value) {
      var type4 = typeof value;
      return value != null && (type4 == "object" || type4 == "function");
    }
    module2.exports = isObject7;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/isFunction.js
var require_isFunction = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/isFunction.js"(exports23, module2) {
    var baseGetTag = require_baseGetTag();
    var isObject7 = require_isObject();
    var asyncTag = "[object AsyncFunction]";
    var funcTag = "[object Function]";
    var genTag = "[object GeneratorFunction]";
    var proxyTag = "[object Proxy]";
    function isFunction3(value) {
      if (!isObject7(value)) {
        return false;
      }
      var tag = baseGetTag(value);
      return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
    }
    module2.exports = isFunction3;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_coreJsData.js
var require_coreJsData = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_coreJsData.js"(exports23, module2) {
    var root = require_root();
    var coreJsData = root["__core-js_shared__"];
    module2.exports = coreJsData;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_isMasked.js
var require_isMasked = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_isMasked.js"(exports23, module2) {
    var coreJsData = require_coreJsData();
    var maskSrcKey = (function() {
      var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || "");
      return uid ? "Symbol(src)_1." + uid : "";
    })();
    function isMasked(func) {
      return !!maskSrcKey && maskSrcKey in func;
    }
    module2.exports = isMasked;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_toSource.js
var require_toSource = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_toSource.js"(exports23, module2) {
    var funcProto = Function.prototype;
    var funcToString = funcProto.toString;
    function toSource(func) {
      if (func != null) {
        try {
          return funcToString.call(func);
        } catch (e5) {
        }
        try {
          return func + "";
        } catch (e5) {
        }
      }
      return "";
    }
    module2.exports = toSource;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseIsNative.js
var require_baseIsNative = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseIsNative.js"(exports23, module2) {
    var isFunction3 = require_isFunction();
    var isMasked = require_isMasked();
    var isObject7 = require_isObject();
    var toSource = require_toSource();
    var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
    var reIsHostCtor = /^\[object .+?Constructor\]$/;
    var funcProto = Function.prototype;
    var objectProto = Object.prototype;
    var funcToString = funcProto.toString;
    var hasOwnProperty3 = objectProto.hasOwnProperty;
    var reIsNative = RegExp(
      "^" + funcToString.call(hasOwnProperty3).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$"
    );
    function baseIsNative(value) {
      if (!isObject7(value) || isMasked(value)) {
        return false;
      }
      var pattern = isFunction3(value) ? reIsNative : reIsHostCtor;
      return pattern.test(toSource(value));
    }
    module2.exports = baseIsNative;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_getValue.js
var require_getValue = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_getValue.js"(exports23, module2) {
    function getValue(object, key) {
      return object == null ? void 0 : object[key];
    }
    module2.exports = getValue;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_getNative.js
var require_getNative = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_getNative.js"(exports23, module2) {
    var baseIsNative = require_baseIsNative();
    var getValue = require_getValue();
    function getNative(object, key) {
      var value = getValue(object, key);
      return baseIsNative(value) ? value : void 0;
    }
    module2.exports = getNative;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_Map.js
var require_Map = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_Map.js"(exports23, module2) {
    var getNative = require_getNative();
    var root = require_root();
    var Map2 = getNative(root, "Map");
    module2.exports = Map2;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_nativeCreate.js
var require_nativeCreate = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_nativeCreate.js"(exports23, module2) {
    var getNative = require_getNative();
    var nativeCreate = getNative(Object, "create");
    module2.exports = nativeCreate;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_hashClear.js
var require_hashClear = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_hashClear.js"(exports23, module2) {
    var nativeCreate = require_nativeCreate();
    function hashClear() {
      this.__data__ = nativeCreate ? nativeCreate(null) : {};
      this.size = 0;
    }
    module2.exports = hashClear;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_hashDelete.js
var require_hashDelete = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_hashDelete.js"(exports23, module2) {
    function hashDelete(key) {
      var result2 = this.has(key) && delete this.__data__[key];
      this.size -= result2 ? 1 : 0;
      return result2;
    }
    module2.exports = hashDelete;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_hashGet.js
var require_hashGet = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_hashGet.js"(exports23, module2) {
    var nativeCreate = require_nativeCreate();
    var HASH_UNDEFINED = "__lodash_hash_undefined__";
    var objectProto = Object.prototype;
    var hasOwnProperty3 = objectProto.hasOwnProperty;
    function hashGet(key) {
      var data3 = this.__data__;
      if (nativeCreate) {
        var result2 = data3[key];
        return result2 === HASH_UNDEFINED ? void 0 : result2;
      }
      return hasOwnProperty3.call(data3, key) ? data3[key] : void 0;
    }
    module2.exports = hashGet;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_hashHas.js
var require_hashHas = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_hashHas.js"(exports23, module2) {
    var nativeCreate = require_nativeCreate();
    var objectProto = Object.prototype;
    var hasOwnProperty3 = objectProto.hasOwnProperty;
    function hashHas(key) {
      var data3 = this.__data__;
      return nativeCreate ? data3[key] !== void 0 : hasOwnProperty3.call(data3, key);
    }
    module2.exports = hashHas;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_hashSet.js
var require_hashSet = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_hashSet.js"(exports23, module2) {
    var nativeCreate = require_nativeCreate();
    var HASH_UNDEFINED = "__lodash_hash_undefined__";
    function hashSet(key, value) {
      var data3 = this.__data__;
      this.size += this.has(key) ? 0 : 1;
      data3[key] = nativeCreate && value === void 0 ? HASH_UNDEFINED : value;
      return this;
    }
    module2.exports = hashSet;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_Hash.js
var require_Hash = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_Hash.js"(exports23, module2) {
    var hashClear = require_hashClear();
    var hashDelete = require_hashDelete();
    var hashGet = require_hashGet();
    var hashHas = require_hashHas();
    var hashSet = require_hashSet();
    function Hash2(entries) {
      var index2 = -1, length = entries == null ? 0 : entries.length;
      this.clear();
      while (++index2 < length) {
        var entry = entries[index2];
        this.set(entry[0], entry[1]);
      }
    }
    Hash2.prototype.clear = hashClear;
    Hash2.prototype["delete"] = hashDelete;
    Hash2.prototype.get = hashGet;
    Hash2.prototype.has = hashHas;
    Hash2.prototype.set = hashSet;
    module2.exports = Hash2;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_mapCacheClear.js
var require_mapCacheClear = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_mapCacheClear.js"(exports23, module2) {
    var Hash2 = require_Hash();
    var ListCache = require_ListCache();
    var Map2 = require_Map();
    function mapCacheClear() {
      this.size = 0;
      this.__data__ = {
        "hash": new Hash2(),
        "map": new (Map2 || ListCache)(),
        "string": new Hash2()
      };
    }
    module2.exports = mapCacheClear;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_isKeyable.js
var require_isKeyable = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_isKeyable.js"(exports23, module2) {
    function isKeyable(value) {
      var type4 = typeof value;
      return type4 == "string" || type4 == "number" || type4 == "symbol" || type4 == "boolean" ? value !== "__proto__" : value === null;
    }
    module2.exports = isKeyable;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_getMapData.js
var require_getMapData = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_getMapData.js"(exports23, module2) {
    var isKeyable = require_isKeyable();
    function getMapData(map3, key) {
      var data3 = map3.__data__;
      return isKeyable(key) ? data3[typeof key == "string" ? "string" : "hash"] : data3.map;
    }
    module2.exports = getMapData;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_mapCacheDelete.js
var require_mapCacheDelete = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_mapCacheDelete.js"(exports23, module2) {
    var getMapData = require_getMapData();
    function mapCacheDelete(key) {
      var result2 = getMapData(this, key)["delete"](key);
      this.size -= result2 ? 1 : 0;
      return result2;
    }
    module2.exports = mapCacheDelete;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_mapCacheGet.js
var require_mapCacheGet = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_mapCacheGet.js"(exports23, module2) {
    var getMapData = require_getMapData();
    function mapCacheGet(key) {
      return getMapData(this, key).get(key);
    }
    module2.exports = mapCacheGet;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_mapCacheHas.js
var require_mapCacheHas = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_mapCacheHas.js"(exports23, module2) {
    var getMapData = require_getMapData();
    function mapCacheHas(key) {
      return getMapData(this, key).has(key);
    }
    module2.exports = mapCacheHas;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_mapCacheSet.js
var require_mapCacheSet = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_mapCacheSet.js"(exports23, module2) {
    var getMapData = require_getMapData();
    function mapCacheSet(key, value) {
      var data3 = getMapData(this, key), size = data3.size;
      data3.set(key, value);
      this.size += data3.size == size ? 0 : 1;
      return this;
    }
    module2.exports = mapCacheSet;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_MapCache.js
var require_MapCache = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_MapCache.js"(exports23, module2) {
    var mapCacheClear = require_mapCacheClear();
    var mapCacheDelete = require_mapCacheDelete();
    var mapCacheGet = require_mapCacheGet();
    var mapCacheHas = require_mapCacheHas();
    var mapCacheSet = require_mapCacheSet();
    function MapCache(entries) {
      var index2 = -1, length = entries == null ? 0 : entries.length;
      this.clear();
      while (++index2 < length) {
        var entry = entries[index2];
        this.set(entry[0], entry[1]);
      }
    }
    MapCache.prototype.clear = mapCacheClear;
    MapCache.prototype["delete"] = mapCacheDelete;
    MapCache.prototype.get = mapCacheGet;
    MapCache.prototype.has = mapCacheHas;
    MapCache.prototype.set = mapCacheSet;
    module2.exports = MapCache;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_stackSet.js
var require_stackSet = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_stackSet.js"(exports23, module2) {
    var ListCache = require_ListCache();
    var Map2 = require_Map();
    var MapCache = require_MapCache();
    var LARGE_ARRAY_SIZE = 200;
    function stackSet(key, value) {
      var data3 = this.__data__;
      if (data3 instanceof ListCache) {
        var pairs3 = data3.__data__;
        if (!Map2 || pairs3.length < LARGE_ARRAY_SIZE - 1) {
          pairs3.push([key, value]);
          this.size = ++data3.size;
          return this;
        }
        data3 = this.__data__ = new MapCache(pairs3);
      }
      data3.set(key, value);
      this.size = data3.size;
      return this;
    }
    module2.exports = stackSet;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_Stack.js
var require_Stack = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_Stack.js"(exports23, module2) {
    var ListCache = require_ListCache();
    var stackClear = require_stackClear();
    var stackDelete = require_stackDelete();
    var stackGet = require_stackGet();
    var stackHas = require_stackHas();
    var stackSet = require_stackSet();
    function Stack(entries) {
      var data3 = this.__data__ = new ListCache(entries);
      this.size = data3.size;
    }
    Stack.prototype.clear = stackClear;
    Stack.prototype["delete"] = stackDelete;
    Stack.prototype.get = stackGet;
    Stack.prototype.has = stackHas;
    Stack.prototype.set = stackSet;
    module2.exports = Stack;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_arrayEach.js
var require_arrayEach = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_arrayEach.js"(exports23, module2) {
    function arrayEach(array, iteratee) {
      var index2 = -1, length = array == null ? 0 : array.length;
      while (++index2 < length) {
        if (iteratee(array[index2], index2, array) === false) {
          break;
        }
      }
      return array;
    }
    module2.exports = arrayEach;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_defineProperty.js
var require_defineProperty = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_defineProperty.js"(exports23, module2) {
    var getNative = require_getNative();
    var defineProperty = (function() {
      try {
        var func = getNative(Object, "defineProperty");
        func({}, "", {});
        return func;
      } catch (e5) {
      }
    })();
    module2.exports = defineProperty;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseAssignValue.js
var require_baseAssignValue = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseAssignValue.js"(exports23, module2) {
    var defineProperty = require_defineProperty();
    function baseAssignValue(object, key, value) {
      if (key == "__proto__" && defineProperty) {
        defineProperty(object, key, {
          "configurable": true,
          "enumerable": true,
          "value": value,
          "writable": true
        });
      } else {
        object[key] = value;
      }
    }
    module2.exports = baseAssignValue;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_assignValue.js
var require_assignValue = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_assignValue.js"(exports23, module2) {
    var baseAssignValue = require_baseAssignValue();
    var eq2 = require_eq();
    var objectProto = Object.prototype;
    var hasOwnProperty3 = objectProto.hasOwnProperty;
    function assignValue(object, key, value) {
      var objValue = object[key];
      if (!(hasOwnProperty3.call(object, key) && eq2(objValue, value)) || value === void 0 && !(key in object)) {
        baseAssignValue(object, key, value);
      }
    }
    module2.exports = assignValue;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_copyObject.js
var require_copyObject = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_copyObject.js"(exports23, module2) {
    var assignValue = require_assignValue();
    var baseAssignValue = require_baseAssignValue();
    function copyObject(source2, props, object, customizer) {
      var isNew = !object;
      object || (object = {});
      var index2 = -1, length = props.length;
      while (++index2 < length) {
        var key = props[index2];
        var newValue = customizer ? customizer(object[key], source2[key], key, object, source2) : void 0;
        if (newValue === void 0) {
          newValue = source2[key];
        }
        if (isNew) {
          baseAssignValue(object, key, newValue);
        } else {
          assignValue(object, key, newValue);
        }
      }
      return object;
    }
    module2.exports = copyObject;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseTimes.js
var require_baseTimes = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseTimes.js"(exports23, module2) {
    function baseTimes(n5, iteratee) {
      var index2 = -1, result2 = Array(n5);
      while (++index2 < n5) {
        result2[index2] = iteratee(index2);
      }
      return result2;
    }
    module2.exports = baseTimes;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/isObjectLike.js
var require_isObjectLike = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/isObjectLike.js"(exports23, module2) {
    function isObjectLike(value) {
      return value != null && typeof value == "object";
    }
    module2.exports = isObjectLike;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseIsArguments.js
var require_baseIsArguments = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseIsArguments.js"(exports23, module2) {
    var baseGetTag = require_baseGetTag();
    var isObjectLike = require_isObjectLike();
    var argsTag = "[object Arguments]";
    function baseIsArguments(value) {
      return isObjectLike(value) && baseGetTag(value) == argsTag;
    }
    module2.exports = baseIsArguments;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/isArguments.js
var require_isArguments = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/isArguments.js"(exports23, module2) {
    var baseIsArguments = require_baseIsArguments();
    var isObjectLike = require_isObjectLike();
    var objectProto = Object.prototype;
    var hasOwnProperty3 = objectProto.hasOwnProperty;
    var propertyIsEnumerable = objectProto.propertyIsEnumerable;
    var isArguments = baseIsArguments(/* @__PURE__ */ (function() {
      return arguments;
    })()) ? baseIsArguments : function(value) {
      return isObjectLike(value) && hasOwnProperty3.call(value, "callee") && !propertyIsEnumerable.call(value, "callee");
    };
    module2.exports = isArguments;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/isArray.js
var require_isArray = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/isArray.js"(exports23, module2) {
    var isArray6 = Array.isArray;
    module2.exports = isArray6;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/stubFalse.js
var require_stubFalse = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/stubFalse.js"(exports23, module2) {
    function stubFalse() {
      return false;
    }
    module2.exports = stubFalse;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/isBuffer.js
var require_isBuffer = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/isBuffer.js"(exports23, module2) {
    var root = require_root();
    var stubFalse = require_stubFalse();
    var freeExports = typeof exports23 == "object" && exports23 && !exports23.nodeType && exports23;
    var freeModule = freeExports && typeof module2 == "object" && module2 && !module2.nodeType && module2;
    var moduleExports = freeModule && freeModule.exports === freeExports;
    var Buffer4 = moduleExports ? root.Buffer : void 0;
    var nativeIsBuffer = Buffer4 ? Buffer4.isBuffer : void 0;
    var isBuffer3 = nativeIsBuffer || stubFalse;
    module2.exports = isBuffer3;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_isIndex.js
var require_isIndex = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_isIndex.js"(exports23, module2) {
    var MAX_SAFE_INTEGER2 = 9007199254740991;
    var reIsUint = /^(?:0|[1-9]\d*)$/;
    function isIndex(value, length) {
      var type4 = typeof value;
      length = length == null ? MAX_SAFE_INTEGER2 : length;
      return !!length && (type4 == "number" || type4 != "symbol" && reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length);
    }
    module2.exports = isIndex;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/isLength.js
var require_isLength = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/isLength.js"(exports23, module2) {
    var MAX_SAFE_INTEGER2 = 9007199254740991;
    function isLength(value) {
      return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER2;
    }
    module2.exports = isLength;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseIsTypedArray.js
var require_baseIsTypedArray = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseIsTypedArray.js"(exports23, module2) {
    var baseGetTag = require_baseGetTag();
    var isLength = require_isLength();
    var isObjectLike = require_isObjectLike();
    var argsTag = "[object Arguments]";
    var arrayTag = "[object Array]";
    var boolTag = "[object Boolean]";
    var dateTag = "[object Date]";
    var errorTag = "[object Error]";
    var funcTag = "[object Function]";
    var mapTag = "[object Map]";
    var numberTag = "[object Number]";
    var objectTag = "[object Object]";
    var regexpTag = "[object RegExp]";
    var setTag = "[object Set]";
    var stringTag = "[object String]";
    var weakMapTag = "[object WeakMap]";
    var arrayBufferTag = "[object ArrayBuffer]";
    var dataViewTag = "[object DataView]";
    var float32Tag = "[object Float32Array]";
    var float64Tag = "[object Float64Array]";
    var int8Tag = "[object Int8Array]";
    var int16Tag = "[object Int16Array]";
    var int32Tag = "[object Int32Array]";
    var uint8Tag = "[object Uint8Array]";
    var uint8ClampedTag = "[object Uint8ClampedArray]";
    var uint16Tag = "[object Uint16Array]";
    var uint32Tag = "[object Uint32Array]";
    var typedArrayTags = {};
    typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true;
    typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
    function baseIsTypedArray(value) {
      return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
    }
    module2.exports = baseIsTypedArray;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseUnary.js
var require_baseUnary = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseUnary.js"(exports23, module2) {
    function baseUnary(func) {
      return function(value) {
        return func(value);
      };
    }
    module2.exports = baseUnary;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_nodeUtil.js
var require_nodeUtil = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_nodeUtil.js"(exports23, module2) {
    var freeGlobal = require_freeGlobal();
    var freeExports = typeof exports23 == "object" && exports23 && !exports23.nodeType && exports23;
    var freeModule = freeExports && typeof module2 == "object" && module2 && !module2.nodeType && module2;
    var moduleExports = freeModule && freeModule.exports === freeExports;
    var freeProcess = moduleExports && freeGlobal.process;
    var nodeUtil = (function() {
      try {
        var types8 = freeModule && freeModule.require && freeModule.require("util").types;
        if (types8) {
          return types8;
        }
        return freeProcess && freeProcess.binding && freeProcess.binding("util");
      } catch (e5) {
      }
    })();
    module2.exports = nodeUtil;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/isTypedArray.js
var require_isTypedArray = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/isTypedArray.js"(exports23, module2) {
    var baseIsTypedArray = require_baseIsTypedArray();
    var baseUnary = require_baseUnary();
    var nodeUtil = require_nodeUtil();
    var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
    var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
    module2.exports = isTypedArray;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_arrayLikeKeys.js
var require_arrayLikeKeys = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_arrayLikeKeys.js"(exports23, module2) {
    var baseTimes = require_baseTimes();
    var isArguments = require_isArguments();
    var isArray6 = require_isArray();
    var isBuffer3 = require_isBuffer();
    var isIndex = require_isIndex();
    var isTypedArray = require_isTypedArray();
    var objectProto = Object.prototype;
    var hasOwnProperty3 = objectProto.hasOwnProperty;
    function arrayLikeKeys(value, inherited) {
      var isArr = isArray6(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer3(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result2 = skipIndexes ? baseTimes(value.length, String) : [], length = result2.length;
      for (var key in value) {
        if ((inherited || hasOwnProperty3.call(value, key)) && !(skipIndexes && // Safari 9 has enumerable `arguments.length` in strict mode.
        (key == "length" || // Node.js 0.10 has enumerable non-index properties on buffers.
        isBuff && (key == "offset" || key == "parent") || // PhantomJS 2 has enumerable non-index properties on typed arrays.
        isType && (key == "buffer" || key == "byteLength" || key == "byteOffset") || // Skip index properties.
        isIndex(key, length)))) {
          result2.push(key);
        }
      }
      return result2;
    }
    module2.exports = arrayLikeKeys;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_isPrototype.js
var require_isPrototype = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_isPrototype.js"(exports23, module2) {
    var objectProto = Object.prototype;
    function isPrototype(value) {
      var Ctor = value && value.constructor, proto2 = typeof Ctor == "function" && Ctor.prototype || objectProto;
      return value === proto2;
    }
    module2.exports = isPrototype;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_overArg.js
var require_overArg = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_overArg.js"(exports23, module2) {
    function overArg(func, transform) {
      return function(arg) {
        return func(transform(arg));
      };
    }
    module2.exports = overArg;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_nativeKeys.js
var require_nativeKeys = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_nativeKeys.js"(exports23, module2) {
    var overArg = require_overArg();
    var nativeKeys = overArg(Object.keys, Object);
    module2.exports = nativeKeys;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseKeys.js
var require_baseKeys = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseKeys.js"(exports23, module2) {
    var isPrototype = require_isPrototype();
    var nativeKeys = require_nativeKeys();
    var objectProto = Object.prototype;
    var hasOwnProperty3 = objectProto.hasOwnProperty;
    function baseKeys(object) {
      if (!isPrototype(object)) {
        return nativeKeys(object);
      }
      var result2 = [];
      for (var key in Object(object)) {
        if (hasOwnProperty3.call(object, key) && key != "constructor") {
          result2.push(key);
        }
      }
      return result2;
    }
    module2.exports = baseKeys;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/isArrayLike.js
var require_isArrayLike = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/isArrayLike.js"(exports23, module2) {
    var isFunction3 = require_isFunction();
    var isLength = require_isLength();
    function isArrayLike(value) {
      return value != null && isLength(value.length) && !isFunction3(value);
    }
    module2.exports = isArrayLike;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/keys.js
var require_keys = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/keys.js"(exports23, module2) {
    var arrayLikeKeys = require_arrayLikeKeys();
    var baseKeys = require_baseKeys();
    var isArrayLike = require_isArrayLike();
    function keys(object) {
      return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
    }
    module2.exports = keys;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseAssign.js
var require_baseAssign = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseAssign.js"(exports23, module2) {
    var copyObject = require_copyObject();
    var keys = require_keys();
    function baseAssign(object, source2) {
      return object && copyObject(source2, keys(source2), object);
    }
    module2.exports = baseAssign;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_nativeKeysIn.js
var require_nativeKeysIn = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_nativeKeysIn.js"(exports23, module2) {
    function nativeKeysIn(object) {
      var result2 = [];
      if (object != null) {
        for (var key in Object(object)) {
          result2.push(key);
        }
      }
      return result2;
    }
    module2.exports = nativeKeysIn;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseKeysIn.js
var require_baseKeysIn = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseKeysIn.js"(exports23, module2) {
    var isObject7 = require_isObject();
    var isPrototype = require_isPrototype();
    var nativeKeysIn = require_nativeKeysIn();
    var objectProto = Object.prototype;
    var hasOwnProperty3 = objectProto.hasOwnProperty;
    function baseKeysIn(object) {
      if (!isObject7(object)) {
        return nativeKeysIn(object);
      }
      var isProto = isPrototype(object), result2 = [];
      for (var key in object) {
        if (!(key == "constructor" && (isProto || !hasOwnProperty3.call(object, key)))) {
          result2.push(key);
        }
      }
      return result2;
    }
    module2.exports = baseKeysIn;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/keysIn.js
var require_keysIn = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/keysIn.js"(exports23, module2) {
    var arrayLikeKeys = require_arrayLikeKeys();
    var baseKeysIn = require_baseKeysIn();
    var isArrayLike = require_isArrayLike();
    function keysIn(object) {
      return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);
    }
    module2.exports = keysIn;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseAssignIn.js
var require_baseAssignIn = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseAssignIn.js"(exports23, module2) {
    var copyObject = require_copyObject();
    var keysIn = require_keysIn();
    function baseAssignIn(object, source2) {
      return object && copyObject(source2, keysIn(source2), object);
    }
    module2.exports = baseAssignIn;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_cloneBuffer.js
var require_cloneBuffer = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_cloneBuffer.js"(exports23, module2) {
    var root = require_root();
    var freeExports = typeof exports23 == "object" && exports23 && !exports23.nodeType && exports23;
    var freeModule = freeExports && typeof module2 == "object" && module2 && !module2.nodeType && module2;
    var moduleExports = freeModule && freeModule.exports === freeExports;
    var Buffer4 = moduleExports ? root.Buffer : void 0;
    var allocUnsafe = Buffer4 ? Buffer4.allocUnsafe : void 0;
    function cloneBuffer(buffer2, isDeep) {
      if (isDeep) {
        return buffer2.slice();
      }
      var length = buffer2.length, result2 = allocUnsafe ? allocUnsafe(length) : new buffer2.constructor(length);
      buffer2.copy(result2);
      return result2;
    }
    module2.exports = cloneBuffer;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_copyArray.js
var require_copyArray = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_copyArray.js"(exports23, module2) {
    function copyArray(source2, array) {
      var index2 = -1, length = source2.length;
      array || (array = Array(length));
      while (++index2 < length) {
        array[index2] = source2[index2];
      }
      return array;
    }
    module2.exports = copyArray;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_arrayFilter.js
var require_arrayFilter = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_arrayFilter.js"(exports23, module2) {
    function arrayFilter(array, predicate) {
      var index2 = -1, length = array == null ? 0 : array.length, resIndex = 0, result2 = [];
      while (++index2 < length) {
        var value = array[index2];
        if (predicate(value, index2, array)) {
          result2[resIndex++] = value;
        }
      }
      return result2;
    }
    module2.exports = arrayFilter;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/stubArray.js
var require_stubArray = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/stubArray.js"(exports23, module2) {
    function stubArray() {
      return [];
    }
    module2.exports = stubArray;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_getSymbols.js
var require_getSymbols = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_getSymbols.js"(exports23, module2) {
    var arrayFilter = require_arrayFilter();
    var stubArray = require_stubArray();
    var objectProto = Object.prototype;
    var propertyIsEnumerable = objectProto.propertyIsEnumerable;
    var nativeGetSymbols = Object.getOwnPropertySymbols;
    var getSymbols = !nativeGetSymbols ? stubArray : function(object) {
      if (object == null) {
        return [];
      }
      object = Object(object);
      return arrayFilter(nativeGetSymbols(object), function(symbol) {
        return propertyIsEnumerable.call(object, symbol);
      });
    };
    module2.exports = getSymbols;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_copySymbols.js
var require_copySymbols = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_copySymbols.js"(exports23, module2) {
    var copyObject = require_copyObject();
    var getSymbols = require_getSymbols();
    function copySymbols(source2, object) {
      return copyObject(source2, getSymbols(source2), object);
    }
    module2.exports = copySymbols;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_arrayPush.js
var require_arrayPush = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_arrayPush.js"(exports23, module2) {
    function arrayPush(array, values) {
      var index2 = -1, length = values.length, offset3 = array.length;
      while (++index2 < length) {
        array[offset3 + index2] = values[index2];
      }
      return array;
    }
    module2.exports = arrayPush;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_getPrototype.js
var require_getPrototype = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_getPrototype.js"(exports23, module2) {
    var overArg = require_overArg();
    var getPrototype = overArg(Object.getPrototypeOf, Object);
    module2.exports = getPrototype;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_getSymbolsIn.js
var require_getSymbolsIn = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_getSymbolsIn.js"(exports23, module2) {
    var arrayPush = require_arrayPush();
    var getPrototype = require_getPrototype();
    var getSymbols = require_getSymbols();
    var stubArray = require_stubArray();
    var nativeGetSymbols = Object.getOwnPropertySymbols;
    var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {
      var result2 = [];
      while (object) {
        arrayPush(result2, getSymbols(object));
        object = getPrototype(object);
      }
      return result2;
    };
    module2.exports = getSymbolsIn;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_copySymbolsIn.js
var require_copySymbolsIn = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_copySymbolsIn.js"(exports23, module2) {
    var copyObject = require_copyObject();
    var getSymbolsIn = require_getSymbolsIn();
    function copySymbolsIn(source2, object) {
      return copyObject(source2, getSymbolsIn(source2), object);
    }
    module2.exports = copySymbolsIn;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseGetAllKeys.js
var require_baseGetAllKeys = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseGetAllKeys.js"(exports23, module2) {
    var arrayPush = require_arrayPush();
    var isArray6 = require_isArray();
    function baseGetAllKeys(object, keysFunc, symbolsFunc) {
      var result2 = keysFunc(object);
      return isArray6(object) ? result2 : arrayPush(result2, symbolsFunc(object));
    }
    module2.exports = baseGetAllKeys;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_getAllKeys.js
var require_getAllKeys = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_getAllKeys.js"(exports23, module2) {
    var baseGetAllKeys = require_baseGetAllKeys();
    var getSymbols = require_getSymbols();
    var keys = require_keys();
    function getAllKeys(object) {
      return baseGetAllKeys(object, keys, getSymbols);
    }
    module2.exports = getAllKeys;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_getAllKeysIn.js
var require_getAllKeysIn = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_getAllKeysIn.js"(exports23, module2) {
    var baseGetAllKeys = require_baseGetAllKeys();
    var getSymbolsIn = require_getSymbolsIn();
    var keysIn = require_keysIn();
    function getAllKeysIn(object) {
      return baseGetAllKeys(object, keysIn, getSymbolsIn);
    }
    module2.exports = getAllKeysIn;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_DataView.js
var require_DataView = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_DataView.js"(exports23, module2) {
    var getNative = require_getNative();
    var root = require_root();
    var DataView2 = getNative(root, "DataView");
    module2.exports = DataView2;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_Promise.js
var require_Promise = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_Promise.js"(exports23, module2) {
    var getNative = require_getNative();
    var root = require_root();
    var Promise3 = getNative(root, "Promise");
    module2.exports = Promise3;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_Set.js
var require_Set = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_Set.js"(exports23, module2) {
    var getNative = require_getNative();
    var root = require_root();
    var Set2 = getNative(root, "Set");
    module2.exports = Set2;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_WeakMap.js
var require_WeakMap = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_WeakMap.js"(exports23, module2) {
    var getNative = require_getNative();
    var root = require_root();
    var WeakMap2 = getNative(root, "WeakMap");
    module2.exports = WeakMap2;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_getTag.js
var require_getTag = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_getTag.js"(exports23, module2) {
    var DataView2 = require_DataView();
    var Map2 = require_Map();
    var Promise3 = require_Promise();
    var Set2 = require_Set();
    var WeakMap2 = require_WeakMap();
    var baseGetTag = require_baseGetTag();
    var toSource = require_toSource();
    var mapTag = "[object Map]";
    var objectTag = "[object Object]";
    var promiseTag = "[object Promise]";
    var setTag = "[object Set]";
    var weakMapTag = "[object WeakMap]";
    var dataViewTag = "[object DataView]";
    var dataViewCtorString = toSource(DataView2);
    var mapCtorString = toSource(Map2);
    var promiseCtorString = toSource(Promise3);
    var setCtorString = toSource(Set2);
    var weakMapCtorString = toSource(WeakMap2);
    var getTag = baseGetTag;
    if (DataView2 && getTag(new DataView2(new ArrayBuffer(1))) != dataViewTag || Map2 && getTag(new Map2()) != mapTag || Promise3 && getTag(Promise3.resolve()) != promiseTag || Set2 && getTag(new Set2()) != setTag || WeakMap2 && getTag(new WeakMap2()) != weakMapTag) {
      getTag = function(value) {
        var result2 = baseGetTag(value), Ctor = result2 == objectTag ? value.constructor : void 0, ctorString = Ctor ? toSource(Ctor) : "";
        if (ctorString) {
          switch (ctorString) {
            case dataViewCtorString:
              return dataViewTag;
            case mapCtorString:
              return mapTag;
            case promiseCtorString:
              return promiseTag;
            case setCtorString:
              return setTag;
            case weakMapCtorString:
              return weakMapTag;
          }
        }
        return result2;
      };
    }
    module2.exports = getTag;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_initCloneArray.js
var require_initCloneArray = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_initCloneArray.js"(exports23, module2) {
    var objectProto = Object.prototype;
    var hasOwnProperty3 = objectProto.hasOwnProperty;
    function initCloneArray(array) {
      var length = array.length, result2 = new array.constructor(length);
      if (length && typeof array[0] == "string" && hasOwnProperty3.call(array, "index")) {
        result2.index = array.index;
        result2.input = array.input;
      }
      return result2;
    }
    module2.exports = initCloneArray;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_Uint8Array.js
var require_Uint8Array = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_Uint8Array.js"(exports23, module2) {
    var root = require_root();
    var Uint8Array2 = root.Uint8Array;
    module2.exports = Uint8Array2;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_cloneArrayBuffer.js
var require_cloneArrayBuffer = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_cloneArrayBuffer.js"(exports23, module2) {
    var Uint8Array2 = require_Uint8Array();
    function cloneArrayBuffer(arrayBuffer) {
      var result2 = new arrayBuffer.constructor(arrayBuffer.byteLength);
      new Uint8Array2(result2).set(new Uint8Array2(arrayBuffer));
      return result2;
    }
    module2.exports = cloneArrayBuffer;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_cloneDataView.js
var require_cloneDataView = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_cloneDataView.js"(exports23, module2) {
    var cloneArrayBuffer = require_cloneArrayBuffer();
    function cloneDataView(dataView, isDeep) {
      var buffer2 = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;
      return new dataView.constructor(buffer2, dataView.byteOffset, dataView.byteLength);
    }
    module2.exports = cloneDataView;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_cloneRegExp.js
var require_cloneRegExp = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_cloneRegExp.js"(exports23, module2) {
    var reFlags = /\w*$/;
    function cloneRegExp(regexp) {
      var result2 = new regexp.constructor(regexp.source, reFlags.exec(regexp));
      result2.lastIndex = regexp.lastIndex;
      return result2;
    }
    module2.exports = cloneRegExp;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_cloneSymbol.js
var require_cloneSymbol = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_cloneSymbol.js"(exports23, module2) {
    var Symbol2 = require_Symbol();
    var symbolProto = Symbol2 ? Symbol2.prototype : void 0;
    var symbolValueOf = symbolProto ? symbolProto.valueOf : void 0;
    function cloneSymbol(symbol) {
      return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
    }
    module2.exports = cloneSymbol;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_cloneTypedArray.js
var require_cloneTypedArray = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_cloneTypedArray.js"(exports23, module2) {
    var cloneArrayBuffer = require_cloneArrayBuffer();
    function cloneTypedArray(typedArray, isDeep) {
      var buffer2 = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
      return new typedArray.constructor(buffer2, typedArray.byteOffset, typedArray.length);
    }
    module2.exports = cloneTypedArray;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_initCloneByTag.js
var require_initCloneByTag = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_initCloneByTag.js"(exports23, module2) {
    var cloneArrayBuffer = require_cloneArrayBuffer();
    var cloneDataView = require_cloneDataView();
    var cloneRegExp = require_cloneRegExp();
    var cloneSymbol = require_cloneSymbol();
    var cloneTypedArray = require_cloneTypedArray();
    var boolTag = "[object Boolean]";
    var dateTag = "[object Date]";
    var mapTag = "[object Map]";
    var numberTag = "[object Number]";
    var regexpTag = "[object RegExp]";
    var setTag = "[object Set]";
    var stringTag = "[object String]";
    var symbolTag = "[object Symbol]";
    var arrayBufferTag = "[object ArrayBuffer]";
    var dataViewTag = "[object DataView]";
    var float32Tag = "[object Float32Array]";
    var float64Tag = "[object Float64Array]";
    var int8Tag = "[object Int8Array]";
    var int16Tag = "[object Int16Array]";
    var int32Tag = "[object Int32Array]";
    var uint8Tag = "[object Uint8Array]";
    var uint8ClampedTag = "[object Uint8ClampedArray]";
    var uint16Tag = "[object Uint16Array]";
    var uint32Tag = "[object Uint32Array]";
    function initCloneByTag(object, tag, isDeep) {
      var Ctor = object.constructor;
      switch (tag) {
        case arrayBufferTag:
          return cloneArrayBuffer(object);
        case boolTag:
        case dateTag:
          return new Ctor(+object);
        case dataViewTag:
          return cloneDataView(object, isDeep);
        case float32Tag:
        case float64Tag:
        case int8Tag:
        case int16Tag:
        case int32Tag:
        case uint8Tag:
        case uint8ClampedTag:
        case uint16Tag:
        case uint32Tag:
          return cloneTypedArray(object, isDeep);
        case mapTag:
          return new Ctor();
        case numberTag:
        case stringTag:
          return new Ctor(object);
        case regexpTag:
          return cloneRegExp(object);
        case setTag:
          return new Ctor();
        case symbolTag:
          return cloneSymbol(object);
      }
    }
    module2.exports = initCloneByTag;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseCreate.js
var require_baseCreate = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseCreate.js"(exports23, module2) {
    var isObject7 = require_isObject();
    var objectCreate = Object.create;
    var baseCreate = /* @__PURE__ */ (function() {
      function object() {
      }
      return function(proto2) {
        if (!isObject7(proto2)) {
          return {};
        }
        if (objectCreate) {
          return objectCreate(proto2);
        }
        object.prototype = proto2;
        var result2 = new object();
        object.prototype = void 0;
        return result2;
      };
    })();
    module2.exports = baseCreate;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_initCloneObject.js
var require_initCloneObject = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_initCloneObject.js"(exports23, module2) {
    var baseCreate = require_baseCreate();
    var getPrototype = require_getPrototype();
    var isPrototype = require_isPrototype();
    function initCloneObject(object) {
      return typeof object.constructor == "function" && !isPrototype(object) ? baseCreate(getPrototype(object)) : {};
    }
    module2.exports = initCloneObject;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseIsMap.js
var require_baseIsMap = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseIsMap.js"(exports23, module2) {
    var getTag = require_getTag();
    var isObjectLike = require_isObjectLike();
    var mapTag = "[object Map]";
    function baseIsMap(value) {
      return isObjectLike(value) && getTag(value) == mapTag;
    }
    module2.exports = baseIsMap;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/isMap.js
var require_isMap = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/isMap.js"(exports23, module2) {
    var baseIsMap = require_baseIsMap();
    var baseUnary = require_baseUnary();
    var nodeUtil = require_nodeUtil();
    var nodeIsMap = nodeUtil && nodeUtil.isMap;
    var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap;
    module2.exports = isMap;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseIsSet.js
var require_baseIsSet = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseIsSet.js"(exports23, module2) {
    var getTag = require_getTag();
    var isObjectLike = require_isObjectLike();
    var setTag = "[object Set]";
    function baseIsSet(value) {
      return isObjectLike(value) && getTag(value) == setTag;
    }
    module2.exports = baseIsSet;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/isSet.js
var require_isSet = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/isSet.js"(exports23, module2) {
    var baseIsSet = require_baseIsSet();
    var baseUnary = require_baseUnary();
    var nodeUtil = require_nodeUtil();
    var nodeIsSet = nodeUtil && nodeUtil.isSet;
    var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;
    module2.exports = isSet;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseClone.js
var require_baseClone = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseClone.js"(exports23, module2) {
    var Stack = require_Stack();
    var arrayEach = require_arrayEach();
    var assignValue = require_assignValue();
    var baseAssign = require_baseAssign();
    var baseAssignIn = require_baseAssignIn();
    var cloneBuffer = require_cloneBuffer();
    var copyArray = require_copyArray();
    var copySymbols = require_copySymbols();
    var copySymbolsIn = require_copySymbolsIn();
    var getAllKeys = require_getAllKeys();
    var getAllKeysIn = require_getAllKeysIn();
    var getTag = require_getTag();
    var initCloneArray = require_initCloneArray();
    var initCloneByTag = require_initCloneByTag();
    var initCloneObject = require_initCloneObject();
    var isArray6 = require_isArray();
    var isBuffer3 = require_isBuffer();
    var isMap = require_isMap();
    var isObject7 = require_isObject();
    var isSet = require_isSet();
    var keys = require_keys();
    var keysIn = require_keysIn();
    var CLONE_DEEP_FLAG = 1;
    var CLONE_FLAT_FLAG = 2;
    var CLONE_SYMBOLS_FLAG = 4;
    var argsTag = "[object Arguments]";
    var arrayTag = "[object Array]";
    var boolTag = "[object Boolean]";
    var dateTag = "[object Date]";
    var errorTag = "[object Error]";
    var funcTag = "[object Function]";
    var genTag = "[object GeneratorFunction]";
    var mapTag = "[object Map]";
    var numberTag = "[object Number]";
    var objectTag = "[object Object]";
    var regexpTag = "[object RegExp]";
    var setTag = "[object Set]";
    var stringTag = "[object String]";
    var symbolTag = "[object Symbol]";
    var weakMapTag = "[object WeakMap]";
    var arrayBufferTag = "[object ArrayBuffer]";
    var dataViewTag = "[object DataView]";
    var float32Tag = "[object Float32Array]";
    var float64Tag = "[object Float64Array]";
    var int8Tag = "[object Int8Array]";
    var int16Tag = "[object Int16Array]";
    var int32Tag = "[object Int32Array]";
    var uint8Tag = "[object Uint8Array]";
    var uint8ClampedTag = "[object Uint8ClampedArray]";
    var uint16Tag = "[object Uint16Array]";
    var uint32Tag = "[object Uint32Array]";
    var cloneableTags = {};
    cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[mapTag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[setTag] = cloneableTags[stringTag] = cloneableTags[symbolTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
    cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[weakMapTag] = false;
    function baseClone(value, bitmask, customizer, key, object, stack) {
      var result2, isDeep = bitmask & CLONE_DEEP_FLAG, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG;
      if (customizer) {
        result2 = object ? customizer(value, key, object, stack) : customizer(value);
      }
      if (result2 !== void 0) {
        return result2;
      }
      if (!isObject7(value)) {
        return value;
      }
      var isArr = isArray6(value);
      if (isArr) {
        result2 = initCloneArray(value);
        if (!isDeep) {
          return copyArray(value, result2);
        }
      } else {
        var tag = getTag(value), isFunc = tag == funcTag || tag == genTag;
        if (isBuffer3(value)) {
          return cloneBuffer(value, isDeep);
        }
        if (tag == objectTag || tag == argsTag || isFunc && !object) {
          result2 = isFlat || isFunc ? {} : initCloneObject(value);
          if (!isDeep) {
            return isFlat ? copySymbolsIn(value, baseAssignIn(result2, value)) : copySymbols(value, baseAssign(result2, value));
          }
        } else {
          if (!cloneableTags[tag]) {
            return object ? value : {};
          }
          result2 = initCloneByTag(value, tag, isDeep);
        }
      }
      stack || (stack = new Stack());
      var stacked = stack.get(value);
      if (stacked) {
        return stacked;
      }
      stack.set(value, result2);
      if (isSet(value)) {
        value.forEach(function(subValue) {
          result2.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));
        });
      } else if (isMap(value)) {
        value.forEach(function(subValue, key2) {
          result2.set(key2, baseClone(subValue, bitmask, customizer, key2, value, stack));
        });
      }
      var keysFunc = isFull ? isFlat ? getAllKeysIn : getAllKeys : isFlat ? keysIn : keys;
      var props = isArr ? void 0 : keysFunc(value);
      arrayEach(props || value, function(subValue, key2) {
        if (props) {
          key2 = subValue;
          subValue = value[key2];
        }
        assignValue(result2, key2, baseClone(subValue, bitmask, customizer, key2, value, stack));
      });
      return result2;
    }
    module2.exports = baseClone;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/cloneDeep.js
var require_cloneDeep = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/cloneDeep.js"(exports23, module2) {
    var baseClone = require_baseClone();
    var CLONE_DEEP_FLAG = 1;
    var CLONE_SYMBOLS_FLAG = 4;
    function cloneDeep2(value) {
      return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG);
    }
    module2.exports = cloneDeep2;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/now.js
var require_now = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/now.js"(exports23, module2) {
    var root = require_root();
    var now = function() {
      return root.Date.now();
    };
    module2.exports = now;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_trimmedEndIndex.js
var require_trimmedEndIndex = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_trimmedEndIndex.js"(exports23, module2) {
    var reWhitespace2 = /\s/;
    function trimmedEndIndex(string2) {
      var index2 = string2.length;
      while (index2-- && reWhitespace2.test(string2.charAt(index2))) {
      }
      return index2;
    }
    module2.exports = trimmedEndIndex;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseTrim.js
var require_baseTrim = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseTrim.js"(exports23, module2) {
    var trimmedEndIndex = require_trimmedEndIndex();
    var reTrimStart = /^\s+/;
    function baseTrim(string2) {
      return string2 ? string2.slice(0, trimmedEndIndex(string2) + 1).replace(reTrimStart, "") : string2;
    }
    module2.exports = baseTrim;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/isSymbol.js
var require_isSymbol = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/isSymbol.js"(exports23, module2) {
    var baseGetTag = require_baseGetTag();
    var isObjectLike = require_isObjectLike();
    var symbolTag = "[object Symbol]";
    function isSymbol3(value) {
      return typeof value == "symbol" || isObjectLike(value) && baseGetTag(value) == symbolTag;
    }
    module2.exports = isSymbol3;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/toNumber.js
var require_toNumber = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/toNumber.js"(exports23, module2) {
    var baseTrim = require_baseTrim();
    var isObject7 = require_isObject();
    var isSymbol3 = require_isSymbol();
    var NAN = 0 / 0;
    var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
    var reIsBinary = /^0b[01]+$/i;
    var reIsOctal = /^0o[0-7]+$/i;
    var freeParseInt = parseInt;
    function toNumber(value) {
      if (typeof value == "number") {
        return value;
      }
      if (isSymbol3(value)) {
        return NAN;
      }
      if (isObject7(value)) {
        var other = typeof value.valueOf == "function" ? value.valueOf() : value;
        value = isObject7(other) ? other + "" : other;
      }
      if (typeof value != "string") {
        return value === 0 ? value : +value;
      }
      value = baseTrim(value);
      var isBinary3 = reIsBinary.test(value);
      return isBinary3 || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary3 ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
    }
    module2.exports = toNumber;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/debounce.js
var require_debounce = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/debounce.js"(exports23, module2) {
    var isObject7 = require_isObject();
    var now = require_now();
    var toNumber = require_toNumber();
    var FUNC_ERROR_TEXT = "Expected a function";
    var nativeMax = Math.max;
    var nativeMin = Math.min;
    function debounce2(func, wait, options) {
      var lastArgs, lastThis, maxWait, result2, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true;
      if (typeof func != "function") {
        throw new TypeError(FUNC_ERROR_TEXT);
      }
      wait = toNumber(wait) || 0;
      if (isObject7(options)) {
        leading = !!options.leading;
        maxing = "maxWait" in options;
        maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
        trailing = "trailing" in options ? !!options.trailing : trailing;
      }
      function invokeFunc(time) {
        var args = lastArgs, thisArg = lastThis;
        lastArgs = lastThis = void 0;
        lastInvokeTime = time;
        result2 = func.apply(thisArg, args);
        return result2;
      }
      function leadingEdge(time) {
        lastInvokeTime = time;
        timerId = setTimeout(timerExpired, wait);
        return leading ? invokeFunc(time) : result2;
      }
      function remainingWait(time) {
        var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, timeWaiting = wait - timeSinceLastCall;
        return maxing ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting;
      }
      function shouldInvoke(time) {
        var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime;
        return lastCallTime === void 0 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
      }
      function timerExpired() {
        var time = now();
        if (shouldInvoke(time)) {
          return trailingEdge(time);
        }
        timerId = setTimeout(timerExpired, remainingWait(time));
      }
      function trailingEdge(time) {
        timerId = void 0;
        if (trailing && lastArgs) {
          return invokeFunc(time);
        }
        lastArgs = lastThis = void 0;
        return result2;
      }
      function cancel() {
        if (timerId !== void 0) {
          clearTimeout(timerId);
        }
        lastInvokeTime = 0;
        lastArgs = lastCallTime = lastThis = timerId = void 0;
      }
      function flush() {
        return timerId === void 0 ? result2 : trailingEdge(now());
      }
      function debounced() {
        var time = now(), isInvoking = shouldInvoke(time);
        lastArgs = arguments;
        lastThis = this;
        lastCallTime = time;
        if (isInvoking) {
          if (timerId === void 0) {
            return leadingEdge(lastCallTime);
          }
          if (maxing) {
            clearTimeout(timerId);
            timerId = setTimeout(timerExpired, wait);
            return invokeFunc(lastCallTime);
          }
        }
        if (timerId === void 0) {
          timerId = setTimeout(timerExpired, wait);
        }
        return result2;
      }
      debounced.cancel = cancel;
      debounced.flush = flush;
      return debounced;
    }
    module2.exports = debounce2;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_setCacheAdd.js
var require_setCacheAdd = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_setCacheAdd.js"(exports23, module2) {
    var HASH_UNDEFINED = "__lodash_hash_undefined__";
    function setCacheAdd(value) {
      this.__data__.set(value, HASH_UNDEFINED);
      return this;
    }
    module2.exports = setCacheAdd;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_setCacheHas.js
var require_setCacheHas = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_setCacheHas.js"(exports23, module2) {
    function setCacheHas(value) {
      return this.__data__.has(value);
    }
    module2.exports = setCacheHas;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_SetCache.js
var require_SetCache = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_SetCache.js"(exports23, module2) {
    var MapCache = require_MapCache();
    var setCacheAdd = require_setCacheAdd();
    var setCacheHas = require_setCacheHas();
    function SetCache(values) {
      var index2 = -1, length = values == null ? 0 : values.length;
      this.__data__ = new MapCache();
      while (++index2 < length) {
        this.add(values[index2]);
      }
    }
    SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
    SetCache.prototype.has = setCacheHas;
    module2.exports = SetCache;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseFindIndex.js
var require_baseFindIndex = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseFindIndex.js"(exports23, module2) {
    function baseFindIndex(array, predicate, fromIndex, fromRight) {
      var length = array.length, index2 = fromIndex + (fromRight ? 1 : -1);
      while (fromRight ? index2-- : ++index2 < length) {
        if (predicate(array[index2], index2, array)) {
          return index2;
        }
      }
      return -1;
    }
    module2.exports = baseFindIndex;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseIsNaN.js
var require_baseIsNaN = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseIsNaN.js"(exports23, module2) {
    function baseIsNaN(value) {
      return value !== value;
    }
    module2.exports = baseIsNaN;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_strictIndexOf.js
var require_strictIndexOf = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_strictIndexOf.js"(exports23, module2) {
    function strictIndexOf(array, value, fromIndex) {
      var index2 = fromIndex - 1, length = array.length;
      while (++index2 < length) {
        if (array[index2] === value) {
          return index2;
        }
      }
      return -1;
    }
    module2.exports = strictIndexOf;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseIndexOf.js
var require_baseIndexOf = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseIndexOf.js"(exports23, module2) {
    var baseFindIndex = require_baseFindIndex();
    var baseIsNaN = require_baseIsNaN();
    var strictIndexOf = require_strictIndexOf();
    function baseIndexOf(array, value, fromIndex) {
      return value === value ? strictIndexOf(array, value, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex);
    }
    module2.exports = baseIndexOf;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_arrayIncludes.js
var require_arrayIncludes = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_arrayIncludes.js"(exports23, module2) {
    var baseIndexOf = require_baseIndexOf();
    function arrayIncludes(array, value) {
      var length = array == null ? 0 : array.length;
      return !!length && baseIndexOf(array, value, 0) > -1;
    }
    module2.exports = arrayIncludes;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_arrayIncludesWith.js
var require_arrayIncludesWith = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_arrayIncludesWith.js"(exports23, module2) {
    function arrayIncludesWith(array, value, comparator) {
      var index2 = -1, length = array == null ? 0 : array.length;
      while (++index2 < length) {
        if (comparator(value, array[index2])) {
          return true;
        }
      }
      return false;
    }
    module2.exports = arrayIncludesWith;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_arrayMap.js
var require_arrayMap = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_arrayMap.js"(exports23, module2) {
    function arrayMap(array, iteratee) {
      var index2 = -1, length = array == null ? 0 : array.length, result2 = Array(length);
      while (++index2 < length) {
        result2[index2] = iteratee(array[index2], index2, array);
      }
      return result2;
    }
    module2.exports = arrayMap;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_cacheHas.js
var require_cacheHas = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_cacheHas.js"(exports23, module2) {
    function cacheHas(cache3, key) {
      return cache3.has(key);
    }
    module2.exports = cacheHas;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseDifference.js
var require_baseDifference = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseDifference.js"(exports23, module2) {
    var SetCache = require_SetCache();
    var arrayIncludes = require_arrayIncludes();
    var arrayIncludesWith = require_arrayIncludesWith();
    var arrayMap = require_arrayMap();
    var baseUnary = require_baseUnary();
    var cacheHas = require_cacheHas();
    var LARGE_ARRAY_SIZE = 200;
    function baseDifference(array, values, iteratee, comparator) {
      var index2 = -1, includes = arrayIncludes, isCommon = true, length = array.length, result2 = [], valuesLength = values.length;
      if (!length) {
        return result2;
      }
      if (iteratee) {
        values = arrayMap(values, baseUnary(iteratee));
      }
      if (comparator) {
        includes = arrayIncludesWith;
        isCommon = false;
      } else if (values.length >= LARGE_ARRAY_SIZE) {
        includes = cacheHas;
        isCommon = false;
        values = new SetCache(values);
      }
      outer:
        while (++index2 < length) {
          var value = array[index2], computed = iteratee == null ? value : iteratee(value);
          value = comparator || value !== 0 ? value : 0;
          if (isCommon && computed === computed) {
            var valuesIndex = valuesLength;
            while (valuesIndex--) {
              if (values[valuesIndex] === computed) {
                continue outer;
              }
            }
            result2.push(value);
          } else if (!includes(values, computed, comparator)) {
            result2.push(value);
          }
        }
      return result2;
    }
    module2.exports = baseDifference;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_isFlattenable.js
var require_isFlattenable = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_isFlattenable.js"(exports23, module2) {
    var Symbol2 = require_Symbol();
    var isArguments = require_isArguments();
    var isArray6 = require_isArray();
    var spreadableSymbol = Symbol2 ? Symbol2.isConcatSpreadable : void 0;
    function isFlattenable(value) {
      return isArray6(value) || isArguments(value) || !!(spreadableSymbol && value && value[spreadableSymbol]);
    }
    module2.exports = isFlattenable;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseFlatten.js
var require_baseFlatten = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseFlatten.js"(exports23, module2) {
    var arrayPush = require_arrayPush();
    var isFlattenable = require_isFlattenable();
    function baseFlatten(array, depth, predicate, isStrict, result2) {
      var index2 = -1, length = array.length;
      predicate || (predicate = isFlattenable);
      result2 || (result2 = []);
      while (++index2 < length) {
        var value = array[index2];
        if (depth > 0 && predicate(value)) {
          if (depth > 1) {
            baseFlatten(value, depth - 1, predicate, isStrict, result2);
          } else {
            arrayPush(result2, value);
          }
        } else if (!isStrict) {
          result2[result2.length] = value;
        }
      }
      return result2;
    }
    module2.exports = baseFlatten;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/identity.js
var require_identity = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/identity.js"(exports23, module2) {
    function identity(value) {
      return value;
    }
    module2.exports = identity;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_apply.js
var require_apply = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_apply.js"(exports23, module2) {
    function apply(func, thisArg, args) {
      switch (args.length) {
        case 0:
          return func.call(thisArg);
        case 1:
          return func.call(thisArg, args[0]);
        case 2:
          return func.call(thisArg, args[0], args[1]);
        case 3:
          return func.call(thisArg, args[0], args[1], args[2]);
      }
      return func.apply(thisArg, args);
    }
    module2.exports = apply;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_overRest.js
var require_overRest = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_overRest.js"(exports23, module2) {
    var apply = require_apply();
    var nativeMax = Math.max;
    function overRest(func, start, transform) {
      start = nativeMax(start === void 0 ? func.length - 1 : start, 0);
      return function() {
        var args = arguments, index2 = -1, length = nativeMax(args.length - start, 0), array = Array(length);
        while (++index2 < length) {
          array[index2] = args[start + index2];
        }
        index2 = -1;
        var otherArgs = Array(start + 1);
        while (++index2 < start) {
          otherArgs[index2] = args[index2];
        }
        otherArgs[start] = transform(array);
        return apply(func, this, otherArgs);
      };
    }
    module2.exports = overRest;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/constant.js
var require_constant = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/constant.js"(exports23, module2) {
    function constant(value) {
      return function() {
        return value;
      };
    }
    module2.exports = constant;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseSetToString.js
var require_baseSetToString = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseSetToString.js"(exports23, module2) {
    var constant = require_constant();
    var defineProperty = require_defineProperty();
    var identity = require_identity();
    var baseSetToString = !defineProperty ? identity : function(func, string2) {
      return defineProperty(func, "toString", {
        "configurable": true,
        "enumerable": false,
        "value": constant(string2),
        "writable": true
      });
    };
    module2.exports = baseSetToString;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_shortOut.js
var require_shortOut = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_shortOut.js"(exports23, module2) {
    var HOT_COUNT = 800;
    var HOT_SPAN = 16;
    var nativeNow = Date.now;
    function shortOut(func) {
      var count = 0, lastCalled = 0;
      return function() {
        var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled);
        lastCalled = stamp;
        if (remaining > 0) {
          if (++count >= HOT_COUNT) {
            return arguments[0];
          }
        } else {
          count = 0;
        }
        return func.apply(void 0, arguments);
      };
    }
    module2.exports = shortOut;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_setToString.js
var require_setToString = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_setToString.js"(exports23, module2) {
    var baseSetToString = require_baseSetToString();
    var shortOut = require_shortOut();
    var setToString = shortOut(baseSetToString);
    module2.exports = setToString;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseRest.js
var require_baseRest = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseRest.js"(exports23, module2) {
    var identity = require_identity();
    var overRest = require_overRest();
    var setToString = require_setToString();
    function baseRest(func, start) {
      return setToString(overRest(func, start, identity), func + "");
    }
    module2.exports = baseRest;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/isArrayLikeObject.js
var require_isArrayLikeObject = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/isArrayLikeObject.js"(exports23, module2) {
    var isArrayLike = require_isArrayLike();
    var isObjectLike = require_isObjectLike();
    function isArrayLikeObject(value) {
      return isObjectLike(value) && isArrayLike(value);
    }
    module2.exports = isArrayLikeObject;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/difference.js
var require_difference = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/difference.js"(exports23, module2) {
    var baseDifference = require_baseDifference();
    var baseFlatten = require_baseFlatten();
    var baseRest = require_baseRest();
    var isArrayLikeObject = require_isArrayLikeObject();
    var difference2 = baseRest(function(array, values) {
      return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) : [];
    });
    module2.exports = difference2;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_createBaseFor.js
var require_createBaseFor = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_createBaseFor.js"(exports23, module2) {
    function createBaseFor(fromRight) {
      return function(object, iteratee, keysFunc) {
        var index2 = -1, iterable = Object(object), props = keysFunc(object), length = props.length;
        while (length--) {
          var key = props[fromRight ? length : ++index2];
          if (iteratee(iterable[key], key, iterable) === false) {
            break;
          }
        }
        return object;
      };
    }
    module2.exports = createBaseFor;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseFor.js
var require_baseFor = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseFor.js"(exports23, module2) {
    var createBaseFor = require_createBaseFor();
    var baseFor = createBaseFor();
    module2.exports = baseFor;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseForOwn.js
var require_baseForOwn = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseForOwn.js"(exports23, module2) {
    var baseFor = require_baseFor();
    var keys = require_keys();
    function baseForOwn(object, iteratee) {
      return object && baseFor(object, iteratee, keys);
    }
    module2.exports = baseForOwn;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_createBaseEach.js
var require_createBaseEach = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_createBaseEach.js"(exports23, module2) {
    var isArrayLike = require_isArrayLike();
    function createBaseEach(eachFunc, fromRight) {
      return function(collection, iteratee) {
        if (collection == null) {
          return collection;
        }
        if (!isArrayLike(collection)) {
          return eachFunc(collection, iteratee);
        }
        var length = collection.length, index2 = fromRight ? length : -1, iterable = Object(collection);
        while (fromRight ? index2-- : ++index2 < length) {
          if (iteratee(iterable[index2], index2, iterable) === false) {
            break;
          }
        }
        return collection;
      };
    }
    module2.exports = createBaseEach;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseEach.js
var require_baseEach = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseEach.js"(exports23, module2) {
    var baseForOwn = require_baseForOwn();
    var createBaseEach = require_createBaseEach();
    var baseEach = createBaseEach(baseForOwn);
    module2.exports = baseEach;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_castFunction.js
var require_castFunction = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_castFunction.js"(exports23, module2) {
    var identity = require_identity();
    function castFunction(value) {
      return typeof value == "function" ? value : identity;
    }
    module2.exports = castFunction;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/forEach.js
var require_forEach = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/forEach.js"(exports23, module2) {
    var arrayEach = require_arrayEach();
    var baseEach = require_baseEach();
    var castFunction = require_castFunction();
    var isArray6 = require_isArray();
    function forEach2(collection, iteratee) {
      var func = isArray6(collection) ? arrayEach : baseEach;
      return func(collection, castFunction(iteratee));
    }
    module2.exports = forEach2;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/each.js
var require_each = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/each.js"(exports23, module2) {
    module2.exports = require_forEach();
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_assignMergeValue.js
var require_assignMergeValue = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_assignMergeValue.js"(exports23, module2) {
    var baseAssignValue = require_baseAssignValue();
    var eq2 = require_eq();
    function assignMergeValue(object, key, value) {
      if (value !== void 0 && !eq2(object[key], value) || value === void 0 && !(key in object)) {
        baseAssignValue(object, key, value);
      }
    }
    module2.exports = assignMergeValue;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/isPlainObject.js
var require_isPlainObject = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/isPlainObject.js"(exports23, module2) {
    var baseGetTag = require_baseGetTag();
    var getPrototype = require_getPrototype();
    var isObjectLike = require_isObjectLike();
    var objectTag = "[object Object]";
    var funcProto = Function.prototype;
    var objectProto = Object.prototype;
    var funcToString = funcProto.toString;
    var hasOwnProperty3 = objectProto.hasOwnProperty;
    var objectCtorString = funcToString.call(Object);
    function isPlainObject(value) {
      if (!isObjectLike(value) || baseGetTag(value) != objectTag) {
        return false;
      }
      var proto2 = getPrototype(value);
      if (proto2 === null) {
        return true;
      }
      var Ctor = hasOwnProperty3.call(proto2, "constructor") && proto2.constructor;
      return typeof Ctor == "function" && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString;
    }
    module2.exports = isPlainObject;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_safeGet.js
var require_safeGet = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_safeGet.js"(exports23, module2) {
    function safeGet(object, key) {
      if (key === "constructor" && typeof object[key] === "function") {
        return;
      }
      if (key == "__proto__") {
        return;
      }
      return object[key];
    }
    module2.exports = safeGet;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/toPlainObject.js
var require_toPlainObject = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/toPlainObject.js"(exports23, module2) {
    var copyObject = require_copyObject();
    var keysIn = require_keysIn();
    function toPlainObject(value) {
      return copyObject(value, keysIn(value));
    }
    module2.exports = toPlainObject;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseMergeDeep.js
var require_baseMergeDeep = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseMergeDeep.js"(exports23, module2) {
    var assignMergeValue = require_assignMergeValue();
    var cloneBuffer = require_cloneBuffer();
    var cloneTypedArray = require_cloneTypedArray();
    var copyArray = require_copyArray();
    var initCloneObject = require_initCloneObject();
    var isArguments = require_isArguments();
    var isArray6 = require_isArray();
    var isArrayLikeObject = require_isArrayLikeObject();
    var isBuffer3 = require_isBuffer();
    var isFunction3 = require_isFunction();
    var isObject7 = require_isObject();
    var isPlainObject = require_isPlainObject();
    var isTypedArray = require_isTypedArray();
    var safeGet = require_safeGet();
    var toPlainObject = require_toPlainObject();
    function baseMergeDeep(object, source2, key, srcIndex, mergeFunc, customizer, stack) {
      var objValue = safeGet(object, key), srcValue = safeGet(source2, key), stacked = stack.get(srcValue);
      if (stacked) {
        assignMergeValue(object, key, stacked);
        return;
      }
      var newValue = customizer ? customizer(objValue, srcValue, key + "", object, source2, stack) : void 0;
      var isCommon = newValue === void 0;
      if (isCommon) {
        var isArr = isArray6(srcValue), isBuff = !isArr && isBuffer3(srcValue), isTyped = !isArr && !isBuff && isTypedArray(srcValue);
        newValue = srcValue;
        if (isArr || isBuff || isTyped) {
          if (isArray6(objValue)) {
            newValue = objValue;
          } else if (isArrayLikeObject(objValue)) {
            newValue = copyArray(objValue);
          } else if (isBuff) {
            isCommon = false;
            newValue = cloneBuffer(srcValue, true);
          } else if (isTyped) {
            isCommon = false;
            newValue = cloneTypedArray(srcValue, true);
          } else {
            newValue = [];
          }
        } else if (isPlainObject(srcValue) || isArguments(srcValue)) {
          newValue = objValue;
          if (isArguments(objValue)) {
            newValue = toPlainObject(objValue);
          } else if (!isObject7(objValue) || isFunction3(objValue)) {
            newValue = initCloneObject(srcValue);
          }
        } else {
          isCommon = false;
        }
      }
      if (isCommon) {
        stack.set(srcValue, newValue);
        mergeFunc(newValue, srcValue, srcIndex, customizer, stack);
        stack["delete"](srcValue);
      }
      assignMergeValue(object, key, newValue);
    }
    module2.exports = baseMergeDeep;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseMerge.js
var require_baseMerge = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseMerge.js"(exports23, module2) {
    var Stack = require_Stack();
    var assignMergeValue = require_assignMergeValue();
    var baseFor = require_baseFor();
    var baseMergeDeep = require_baseMergeDeep();
    var isObject7 = require_isObject();
    var keysIn = require_keysIn();
    var safeGet = require_safeGet();
    function baseMerge(object, source2, srcIndex, customizer, stack) {
      if (object === source2) {
        return;
      }
      baseFor(source2, function(srcValue, key) {
        stack || (stack = new Stack());
        if (isObject7(srcValue)) {
          baseMergeDeep(object, source2, key, srcIndex, baseMerge, customizer, stack);
        } else {
          var newValue = customizer ? customizer(safeGet(object, key), srcValue, key + "", object, source2, stack) : void 0;
          if (newValue === void 0) {
            newValue = srcValue;
          }
          assignMergeValue(object, key, newValue);
        }
      }, keysIn);
    }
    module2.exports = baseMerge;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_isIterateeCall.js
var require_isIterateeCall = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_isIterateeCall.js"(exports23, module2) {
    var eq2 = require_eq();
    var isArrayLike = require_isArrayLike();
    var isIndex = require_isIndex();
    var isObject7 = require_isObject();
    function isIterateeCall(value, index2, object) {
      if (!isObject7(object)) {
        return false;
      }
      var type4 = typeof index2;
      if (type4 == "number" ? isArrayLike(object) && isIndex(index2, object.length) : type4 == "string" && index2 in object) {
        return eq2(object[index2], value);
      }
      return false;
    }
    module2.exports = isIterateeCall;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_createAssigner.js
var require_createAssigner = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_createAssigner.js"(exports23, module2) {
    var baseRest = require_baseRest();
    var isIterateeCall = require_isIterateeCall();
    function createAssigner(assigner) {
      return baseRest(function(object, sources) {
        var index2 = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : void 0, guard = length > 2 ? sources[2] : void 0;
        customizer = assigner.length > 3 && typeof customizer == "function" ? (length--, customizer) : void 0;
        if (guard && isIterateeCall(sources[0], sources[1], guard)) {
          customizer = length < 3 ? void 0 : customizer;
          length = 1;
        }
        object = Object(object);
        while (++index2 < length) {
          var source2 = sources[index2];
          if (source2) {
            assigner(object, source2, index2, customizer);
          }
        }
        return object;
      });
    }
    module2.exports = createAssigner;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/mergeWith.js
var require_mergeWith = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/mergeWith.js"(exports23, module2) {
    var baseMerge = require_baseMerge();
    var createAssigner = require_createAssigner();
    var mergeWith2 = createAssigner(function(object, source2, srcIndex, customizer) {
      baseMerge(object, source2, srcIndex, customizer);
    });
    module2.exports = mergeWith2;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseRandom.js
var require_baseRandom = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseRandom.js"(exports23, module2) {
    var nativeFloor = Math.floor;
    var nativeRandom = Math.random;
    function baseRandom(lower, upper) {
      return lower + nativeFloor(nativeRandom() * (upper - lower + 1));
    }
    module2.exports = baseRandom;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_shuffleSelf.js
var require_shuffleSelf = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_shuffleSelf.js"(exports23, module2) {
    var baseRandom = require_baseRandom();
    function shuffleSelf(array, size) {
      var index2 = -1, length = array.length, lastIndex = length - 1;
      size = size === void 0 ? length : size;
      while (++index2 < size) {
        var rand = baseRandom(index2, lastIndex), value = array[rand];
        array[rand] = array[index2];
        array[index2] = value;
      }
      array.length = size;
      return array;
    }
    module2.exports = shuffleSelf;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_arrayShuffle.js
var require_arrayShuffle = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_arrayShuffle.js"(exports23, module2) {
    var copyArray = require_copyArray();
    var shuffleSelf = require_shuffleSelf();
    function arrayShuffle(array) {
      return shuffleSelf(copyArray(array));
    }
    module2.exports = arrayShuffle;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseValues.js
var require_baseValues = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseValues.js"(exports23, module2) {
    var arrayMap = require_arrayMap();
    function baseValues(object, props) {
      return arrayMap(props, function(key) {
        return object[key];
      });
    }
    module2.exports = baseValues;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/values.js
var require_values = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/values.js"(exports23, module2) {
    var baseValues = require_baseValues();
    var keys = require_keys();
    function values(object) {
      return object == null ? [] : baseValues(object, keys(object));
    }
    module2.exports = values;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseShuffle.js
var require_baseShuffle = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseShuffle.js"(exports23, module2) {
    var shuffleSelf = require_shuffleSelf();
    var values = require_values();
    function baseShuffle(collection) {
      return shuffleSelf(values(collection));
    }
    module2.exports = baseShuffle;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/shuffle.js
var require_shuffle = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/shuffle.js"(exports23, module2) {
    var arrayShuffle = require_arrayShuffle();
    var baseShuffle = require_baseShuffle();
    var isArray6 = require_isArray();
    function shuffle2(collection) {
      var func = isArray6(collection) ? arrayShuffle : baseShuffle;
      return func(collection);
    }
    module2.exports = shuffle2;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/assignInWith.js
var require_assignInWith = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/assignInWith.js"(exports23, module2) {
    var copyObject = require_copyObject();
    var createAssigner = require_createAssigner();
    var keysIn = require_keysIn();
    var assignInWith = createAssigner(function(object, source2, srcIndex, customizer) {
      copyObject(source2, keysIn(source2), object, customizer);
    });
    module2.exports = assignInWith;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/isError.js
var require_isError = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/isError.js"(exports23, module2) {
    var baseGetTag = require_baseGetTag();
    var isObjectLike = require_isObjectLike();
    var isPlainObject = require_isPlainObject();
    var domExcTag = "[object DOMException]";
    var errorTag = "[object Error]";
    function isError3(value) {
      if (!isObjectLike(value)) {
        return false;
      }
      var tag = baseGetTag(value);
      return tag == errorTag || tag == domExcTag || typeof value.message == "string" && typeof value.name == "string" && !isPlainObject(value);
    }
    module2.exports = isError3;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/attempt.js
var require_attempt = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/attempt.js"(exports23, module2) {
    var apply = require_apply();
    var baseRest = require_baseRest();
    var isError3 = require_isError();
    var attempt = baseRest(function(func, args) {
      try {
        return apply(func, void 0, args);
      } catch (e5) {
        return isError3(e5) ? e5 : new Error(e5);
      }
    });
    module2.exports = attempt;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_customDefaultsAssignIn.js
var require_customDefaultsAssignIn = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_customDefaultsAssignIn.js"(exports23, module2) {
    var eq2 = require_eq();
    var objectProto = Object.prototype;
    var hasOwnProperty3 = objectProto.hasOwnProperty;
    function customDefaultsAssignIn(objValue, srcValue, key, object) {
      if (objValue === void 0 || eq2(objValue, objectProto[key]) && !hasOwnProperty3.call(object, key)) {
        return srcValue;
      }
      return objValue;
    }
    module2.exports = customDefaultsAssignIn;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_escapeStringChar.js
var require_escapeStringChar = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_escapeStringChar.js"(exports23, module2) {
    var stringEscapes = {
      "\\": "\\",
      "'": "'",
      "\n": "n",
      "\r": "r",
      "\u2028": "u2028",
      "\u2029": "u2029"
    };
    function escapeStringChar(chr) {
      return "\\" + stringEscapes[chr];
    }
    module2.exports = escapeStringChar;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_reInterpolate.js
var require_reInterpolate = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_reInterpolate.js"(exports23, module2) {
    var reInterpolate = /<%=([\s\S]+?)%>/g;
    module2.exports = reInterpolate;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_basePropertyOf.js
var require_basePropertyOf = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_basePropertyOf.js"(exports23, module2) {
    function basePropertyOf(object) {
      return function(key) {
        return object == null ? void 0 : object[key];
      };
    }
    module2.exports = basePropertyOf;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_escapeHtmlChar.js
var require_escapeHtmlChar = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_escapeHtmlChar.js"(exports23, module2) {
    var basePropertyOf = require_basePropertyOf();
    var htmlEscapes = {
      "&": "&amp;",
      "<": "&lt;",
      ">": "&gt;",
      '"': "&quot;",
      "'": "&#39;"
    };
    var escapeHtmlChar = basePropertyOf(htmlEscapes);
    module2.exports = escapeHtmlChar;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseToString.js
var require_baseToString = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseToString.js"(exports23, module2) {
    var Symbol2 = require_Symbol();
    var arrayMap = require_arrayMap();
    var isArray6 = require_isArray();
    var isSymbol3 = require_isSymbol();
    var INFINITY = 1 / 0;
    var symbolProto = Symbol2 ? Symbol2.prototype : void 0;
    var symbolToString = symbolProto ? symbolProto.toString : void 0;
    function baseToString(value) {
      if (typeof value == "string") {
        return value;
      }
      if (isArray6(value)) {
        return arrayMap(value, baseToString) + "";
      }
      if (isSymbol3(value)) {
        return symbolToString ? symbolToString.call(value) : "";
      }
      var result2 = value + "";
      return result2 == "0" && 1 / value == -INFINITY ? "-0" : result2;
    }
    module2.exports = baseToString;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/toString.js
var require_toString = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/toString.js"(exports23, module2) {
    var baseToString = require_baseToString();
    function toString8(value) {
      return value == null ? "" : baseToString(value);
    }
    module2.exports = toString8;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/escape.js
var require_escape = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/escape.js"(exports23, module2) {
    var escapeHtmlChar = require_escapeHtmlChar();
    var toString8 = require_toString();
    var reUnescapedHtml = /[&<>"']/g;
    var reHasUnescapedHtml = RegExp(reUnescapedHtml.source);
    function escape2(string2) {
      string2 = toString8(string2);
      return string2 && reHasUnescapedHtml.test(string2) ? string2.replace(reUnescapedHtml, escapeHtmlChar) : string2;
    }
    module2.exports = escape2;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_reEscape.js
var require_reEscape = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_reEscape.js"(exports23, module2) {
    var reEscape = /<%-([\s\S]+?)%>/g;
    module2.exports = reEscape;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_reEvaluate.js
var require_reEvaluate = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_reEvaluate.js"(exports23, module2) {
    var reEvaluate = /<%([\s\S]+?)%>/g;
    module2.exports = reEvaluate;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/templateSettings.js
var require_templateSettings = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/templateSettings.js"(exports23, module2) {
    var escape2 = require_escape();
    var reEscape = require_reEscape();
    var reEvaluate = require_reEvaluate();
    var reInterpolate = require_reInterpolate();
    var templateSettings = {
      /**
       * Used to detect `data` property values to be HTML-escaped.
       *
       * @memberOf _.templateSettings
       * @type {RegExp}
       */
      "escape": reEscape,
      /**
       * Used to detect code to be evaluated.
       *
       * @memberOf _.templateSettings
       * @type {RegExp}
       */
      "evaluate": reEvaluate,
      /**
       * Used to detect `data` property values to inject.
       *
       * @memberOf _.templateSettings
       * @type {RegExp}
       */
      "interpolate": reInterpolate,
      /**
       * Used to reference the data object in the template text.
       *
       * @memberOf _.templateSettings
       * @type {string}
       */
      "variable": "",
      /**
       * Used to import variables into the compiled template.
       *
       * @memberOf _.templateSettings
       * @type {Object}
       */
      "imports": {
        /**
         * A reference to the `lodash` function.
         *
         * @memberOf _.templateSettings.imports
         * @type {Function}
         */
        "_": { "escape": escape2 }
      }
    };
    module2.exports = templateSettings;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/template.js
var require_template = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/template.js"(exports23, module2) {
    var assignInWith = require_assignInWith();
    var attempt = require_attempt();
    var baseValues = require_baseValues();
    var customDefaultsAssignIn = require_customDefaultsAssignIn();
    var escapeStringChar = require_escapeStringChar();
    var isError3 = require_isError();
    var isIterateeCall = require_isIterateeCall();
    var keys = require_keys();
    var reInterpolate = require_reInterpolate();
    var templateSettings = require_templateSettings();
    var toString8 = require_toString();
    var INVALID_TEMPL_VAR_ERROR_TEXT = "Invalid `variable` option passed into `_.template`";
    var reEmptyStringLeading = /\b__p \+= '';/g;
    var reEmptyStringMiddle = /\b(__p \+=) '' \+/g;
    var reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
    var reForbiddenIdentifierChars = /[()=,{}\[\]\/\s]/;
    var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
    var reNoMatch = /($^)/;
    var reUnescapedString = /['\n\r\u2028\u2029\\]/g;
    var objectProto = Object.prototype;
    var hasOwnProperty3 = objectProto.hasOwnProperty;
    function template2(string2, options, guard) {
      var settings = templateSettings.imports._.templateSettings || templateSettings;
      if (guard && isIterateeCall(string2, options, guard)) {
        options = void 0;
      }
      string2 = toString8(string2);
      options = assignInWith({}, options, settings, customDefaultsAssignIn);
      var imports2 = assignInWith({}, options.imports, settings.imports, customDefaultsAssignIn), importsKeys = keys(imports2), importsValues = baseValues(imports2, importsKeys);
      var isEscaping, isEvaluating, index2 = 0, interpolate = options.interpolate || reNoMatch, source2 = "__p += '";
      var reDelimiters = RegExp(
        (options.escape || reNoMatch).source + "|" + interpolate.source + "|" + (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + "|" + (options.evaluate || reNoMatch).source + "|$",
        "g"
      );
      var sourceURL = hasOwnProperty3.call(options, "sourceURL") ? "//# sourceURL=" + (options.sourceURL + "").replace(/\s/g, " ") + "\n" : "";
      string2.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset3) {
        interpolateValue || (interpolateValue = esTemplateValue);
        source2 += string2.slice(index2, offset3).replace(reUnescapedString, escapeStringChar);
        if (escapeValue) {
          isEscaping = true;
          source2 += "' +\n__e(" + escapeValue + ") +\n'";
        }
        if (evaluateValue) {
          isEvaluating = true;
          source2 += "';\n" + evaluateValue + ";\n__p += '";
        }
        if (interpolateValue) {
          source2 += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
        }
        index2 = offset3 + match.length;
        return match;
      });
      source2 += "';\n";
      var variable = hasOwnProperty3.call(options, "variable") && options.variable;
      if (!variable) {
        source2 = "with (obj) {\n" + source2 + "\n}\n";
      } else if (reForbiddenIdentifierChars.test(variable)) {
        throw new Error(INVALID_TEMPL_VAR_ERROR_TEXT);
      }
      source2 = (isEvaluating ? source2.replace(reEmptyStringLeading, "") : source2).replace(reEmptyStringMiddle, "$1").replace(reEmptyStringTrailing, "$1;");
      source2 = "function(" + (variable || "obj") + ") {\n" + (variable ? "" : "obj || (obj = {});\n") + "var __t, __p = ''" + (isEscaping ? ", __e = _.escape" : "") + (isEvaluating ? ", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n" : ";\n") + source2 + "return __p\n}";
      var result2 = attempt(function() {
        return Function(importsKeys, sourceURL + "return " + source2).apply(void 0, importsValues);
      });
      result2.source = source2;
      if (isError3(result2)) {
        throw result2;
      }
      return result2;
    }
    module2.exports = template2;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/noop.js
var require_noop = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/noop.js"(exports23, module2) {
    function noop2() {
    }
    module2.exports = noop2;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_setToArray.js
var require_setToArray = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_setToArray.js"(exports23, module2) {
    function setToArray(set3) {
      var index2 = -1, result2 = Array(set3.size);
      set3.forEach(function(value) {
        result2[++index2] = value;
      });
      return result2;
    }
    module2.exports = setToArray;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_createSet.js
var require_createSet = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_createSet.js"(exports23, module2) {
    var Set2 = require_Set();
    var noop2 = require_noop();
    var setToArray = require_setToArray();
    var INFINITY = 1 / 0;
    var createSet = !(Set2 && 1 / setToArray(new Set2([, -0]))[1] == INFINITY) ? noop2 : function(values) {
      return new Set2(values);
    };
    module2.exports = createSet;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseUniq.js
var require_baseUniq = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseUniq.js"(exports23, module2) {
    var SetCache = require_SetCache();
    var arrayIncludes = require_arrayIncludes();
    var arrayIncludesWith = require_arrayIncludesWith();
    var cacheHas = require_cacheHas();
    var createSet = require_createSet();
    var setToArray = require_setToArray();
    var LARGE_ARRAY_SIZE = 200;
    function baseUniq(array, iteratee, comparator) {
      var index2 = -1, includes = arrayIncludes, length = array.length, isCommon = true, result2 = [], seen = result2;
      if (comparator) {
        isCommon = false;
        includes = arrayIncludesWith;
      } else if (length >= LARGE_ARRAY_SIZE) {
        var set3 = iteratee ? null : createSet(array);
        if (set3) {
          return setToArray(set3);
        }
        isCommon = false;
        includes = cacheHas;
        seen = new SetCache();
      } else {
        seen = iteratee ? [] : result2;
      }
      outer:
        while (++index2 < length) {
          var value = array[index2], computed = iteratee ? iteratee(value) : value;
          value = comparator || value !== 0 ? value : 0;
          if (isCommon && computed === computed) {
            var seenIndex = seen.length;
            while (seenIndex--) {
              if (seen[seenIndex] === computed) {
                continue outer;
              }
            }
            if (iteratee) {
              seen.push(computed);
            }
            result2.push(value);
          } else if (!includes(seen, computed, comparator)) {
            if (seen !== result2) {
              seen.push(computed);
            }
            result2.push(value);
          }
        }
      return result2;
    }
    module2.exports = baseUniq;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/uniq.js
var require_uniq = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/uniq.js"(exports23, module2) {
    var baseUniq = require_baseUniq();
    function uniq2(array) {
      return array && array.length ? baseUniq(array) : [];
    }
    module2.exports = uniq2;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_arraySome.js
var require_arraySome = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_arraySome.js"(exports23, module2) {
    function arraySome(array, predicate) {
      var index2 = -1, length = array == null ? 0 : array.length;
      while (++index2 < length) {
        if (predicate(array[index2], index2, array)) {
          return true;
        }
      }
      return false;
    }
    module2.exports = arraySome;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_equalArrays.js
var require_equalArrays = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_equalArrays.js"(exports23, module2) {
    var SetCache = require_SetCache();
    var arraySome = require_arraySome();
    var cacheHas = require_cacheHas();
    var COMPARE_PARTIAL_FLAG = 1;
    var COMPARE_UNORDERED_FLAG = 2;
    function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
      var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length;
      if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
        return false;
      }
      var arrStacked = stack.get(array);
      var othStacked = stack.get(other);
      if (arrStacked && othStacked) {
        return arrStacked == other && othStacked == array;
      }
      var index2 = -1, result2 = true, seen = bitmask & COMPARE_UNORDERED_FLAG ? new SetCache() : void 0;
      stack.set(array, other);
      stack.set(other, array);
      while (++index2 < arrLength) {
        var arrValue = array[index2], othValue = other[index2];
        if (customizer) {
          var compared = isPartial ? customizer(othValue, arrValue, index2, other, array, stack) : customizer(arrValue, othValue, index2, array, other, stack);
        }
        if (compared !== void 0) {
          if (compared) {
            continue;
          }
          result2 = false;
          break;
        }
        if (seen) {
          if (!arraySome(other, function(othValue2, othIndex) {
            if (!cacheHas(seen, othIndex) && (arrValue === othValue2 || equalFunc(arrValue, othValue2, bitmask, customizer, stack))) {
              return seen.push(othIndex);
            }
          })) {
            result2 = false;
            break;
          }
        } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
          result2 = false;
          break;
        }
      }
      stack["delete"](array);
      stack["delete"](other);
      return result2;
    }
    module2.exports = equalArrays;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_mapToArray.js
var require_mapToArray = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_mapToArray.js"(exports23, module2) {
    function mapToArray(map3) {
      var index2 = -1, result2 = Array(map3.size);
      map3.forEach(function(value, key) {
        result2[++index2] = [key, value];
      });
      return result2;
    }
    module2.exports = mapToArray;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_equalByTag.js
var require_equalByTag = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_equalByTag.js"(exports23, module2) {
    var Symbol2 = require_Symbol();
    var Uint8Array2 = require_Uint8Array();
    var eq2 = require_eq();
    var equalArrays = require_equalArrays();
    var mapToArray = require_mapToArray();
    var setToArray = require_setToArray();
    var COMPARE_PARTIAL_FLAG = 1;
    var COMPARE_UNORDERED_FLAG = 2;
    var boolTag = "[object Boolean]";
    var dateTag = "[object Date]";
    var errorTag = "[object Error]";
    var mapTag = "[object Map]";
    var numberTag = "[object Number]";
    var regexpTag = "[object RegExp]";
    var setTag = "[object Set]";
    var stringTag = "[object String]";
    var symbolTag = "[object Symbol]";
    var arrayBufferTag = "[object ArrayBuffer]";
    var dataViewTag = "[object DataView]";
    var symbolProto = Symbol2 ? Symbol2.prototype : void 0;
    var symbolValueOf = symbolProto ? symbolProto.valueOf : void 0;
    function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
      switch (tag) {
        case dataViewTag:
          if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) {
            return false;
          }
          object = object.buffer;
          other = other.buffer;
        case arrayBufferTag:
          if (object.byteLength != other.byteLength || !equalFunc(new Uint8Array2(object), new Uint8Array2(other))) {
            return false;
          }
          return true;
        case boolTag:
        case dateTag:
        case numberTag:
          return eq2(+object, +other);
        case errorTag:
          return object.name == other.name && object.message == other.message;
        case regexpTag:
        case stringTag:
          return object == other + "";
        case mapTag:
          var convert = mapToArray;
        case setTag:
          var isPartial = bitmask & COMPARE_PARTIAL_FLAG;
          convert || (convert = setToArray);
          if (object.size != other.size && !isPartial) {
            return false;
          }
          var stacked = stack.get(object);
          if (stacked) {
            return stacked == other;
          }
          bitmask |= COMPARE_UNORDERED_FLAG;
          stack.set(object, other);
          var result2 = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
          stack["delete"](object);
          return result2;
        case symbolTag:
          if (symbolValueOf) {
            return symbolValueOf.call(object) == symbolValueOf.call(other);
          }
      }
      return false;
    }
    module2.exports = equalByTag;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_equalObjects.js
var require_equalObjects = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_equalObjects.js"(exports23, module2) {
    var getAllKeys = require_getAllKeys();
    var COMPARE_PARTIAL_FLAG = 1;
    var objectProto = Object.prototype;
    var hasOwnProperty3 = objectProto.hasOwnProperty;
    function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
      var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length;
      if (objLength != othLength && !isPartial) {
        return false;
      }
      var index2 = objLength;
      while (index2--) {
        var key = objProps[index2];
        if (!(isPartial ? key in other : hasOwnProperty3.call(other, key))) {
          return false;
        }
      }
      var objStacked = stack.get(object);
      var othStacked = stack.get(other);
      if (objStacked && othStacked) {
        return objStacked == other && othStacked == object;
      }
      var result2 = true;
      stack.set(object, other);
      stack.set(other, object);
      var skipCtor = isPartial;
      while (++index2 < objLength) {
        key = objProps[index2];
        var objValue = object[key], othValue = other[key];
        if (customizer) {
          var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack);
        }
        if (!(compared === void 0 ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) {
          result2 = false;
          break;
        }
        skipCtor || (skipCtor = key == "constructor");
      }
      if (result2 && !skipCtor) {
        var objCtor = object.constructor, othCtor = other.constructor;
        if (objCtor != othCtor && ("constructor" in object && "constructor" in other) && !(typeof objCtor == "function" && objCtor instanceof objCtor && typeof othCtor == "function" && othCtor instanceof othCtor)) {
          result2 = false;
        }
      }
      stack["delete"](object);
      stack["delete"](other);
      return result2;
    }
    module2.exports = equalObjects;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseIsEqualDeep.js
var require_baseIsEqualDeep = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseIsEqualDeep.js"(exports23, module2) {
    var Stack = require_Stack();
    var equalArrays = require_equalArrays();
    var equalByTag = require_equalByTag();
    var equalObjects = require_equalObjects();
    var getTag = require_getTag();
    var isArray6 = require_isArray();
    var isBuffer3 = require_isBuffer();
    var isTypedArray = require_isTypedArray();
    var COMPARE_PARTIAL_FLAG = 1;
    var argsTag = "[object Arguments]";
    var arrayTag = "[object Array]";
    var objectTag = "[object Object]";
    var objectProto = Object.prototype;
    var hasOwnProperty3 = objectProto.hasOwnProperty;
    function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
      var objIsArr = isArray6(object), othIsArr = isArray6(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other);
      objTag = objTag == argsTag ? objectTag : objTag;
      othTag = othTag == argsTag ? objectTag : othTag;
      var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag;
      if (isSameTag && isBuffer3(object)) {
        if (!isBuffer3(other)) {
          return false;
        }
        objIsArr = true;
        objIsObj = false;
      }
      if (isSameTag && !objIsObj) {
        stack || (stack = new Stack());
        return objIsArr || isTypedArray(object) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
      }
      if (!(bitmask & COMPARE_PARTIAL_FLAG)) {
        var objIsWrapped = objIsObj && hasOwnProperty3.call(object, "__wrapped__"), othIsWrapped = othIsObj && hasOwnProperty3.call(other, "__wrapped__");
        if (objIsWrapped || othIsWrapped) {
          var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other;
          stack || (stack = new Stack());
          return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
        }
      }
      if (!isSameTag) {
        return false;
      }
      stack || (stack = new Stack());
      return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
    }
    module2.exports = baseIsEqualDeep;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseIsEqual.js
var require_baseIsEqual = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseIsEqual.js"(exports23, module2) {
    var baseIsEqualDeep = require_baseIsEqualDeep();
    var isObjectLike = require_isObjectLike();
    function baseIsEqual(value, other, bitmask, customizer, stack) {
      if (value === other) {
        return true;
      }
      if (value == null || other == null || !isObjectLike(value) && !isObjectLike(other)) {
        return value !== value && other !== other;
      }
      return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
    }
    module2.exports = baseIsEqual;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseIsMatch.js
var require_baseIsMatch = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseIsMatch.js"(exports23, module2) {
    var Stack = require_Stack();
    var baseIsEqual = require_baseIsEqual();
    var COMPARE_PARTIAL_FLAG = 1;
    var COMPARE_UNORDERED_FLAG = 2;
    function baseIsMatch(object, source2, matchData, customizer) {
      var index2 = matchData.length, length = index2, noCustomizer = !customizer;
      if (object == null) {
        return !length;
      }
      object = Object(object);
      while (index2--) {
        var data3 = matchData[index2];
        if (noCustomizer && data3[2] ? data3[1] !== object[data3[0]] : !(data3[0] in object)) {
          return false;
        }
      }
      while (++index2 < length) {
        data3 = matchData[index2];
        var key = data3[0], objValue = object[key], srcValue = data3[1];
        if (noCustomizer && data3[2]) {
          if (objValue === void 0 && !(key in object)) {
            return false;
          }
        } else {
          var stack = new Stack();
          if (customizer) {
            var result2 = customizer(objValue, srcValue, key, object, source2, stack);
          }
          if (!(result2 === void 0 ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) : result2)) {
            return false;
          }
        }
      }
      return true;
    }
    module2.exports = baseIsMatch;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_isStrictComparable.js
var require_isStrictComparable = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_isStrictComparable.js"(exports23, module2) {
    var isObject7 = require_isObject();
    function isStrictComparable(value) {
      return value === value && !isObject7(value);
    }
    module2.exports = isStrictComparable;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_getMatchData.js
var require_getMatchData = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_getMatchData.js"(exports23, module2) {
    var isStrictComparable = require_isStrictComparable();
    var keys = require_keys();
    function getMatchData(object) {
      var result2 = keys(object), length = result2.length;
      while (length--) {
        var key = result2[length], value = object[key];
        result2[length] = [key, value, isStrictComparable(value)];
      }
      return result2;
    }
    module2.exports = getMatchData;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_matchesStrictComparable.js
var require_matchesStrictComparable = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_matchesStrictComparable.js"(exports23, module2) {
    function matchesStrictComparable(key, srcValue) {
      return function(object) {
        if (object == null) {
          return false;
        }
        return object[key] === srcValue && (srcValue !== void 0 || key in Object(object));
      };
    }
    module2.exports = matchesStrictComparable;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseMatches.js
var require_baseMatches = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseMatches.js"(exports23, module2) {
    var baseIsMatch = require_baseIsMatch();
    var getMatchData = require_getMatchData();
    var matchesStrictComparable = require_matchesStrictComparable();
    function baseMatches(source2) {
      var matchData = getMatchData(source2);
      if (matchData.length == 1 && matchData[0][2]) {
        return matchesStrictComparable(matchData[0][0], matchData[0][1]);
      }
      return function(object) {
        return object === source2 || baseIsMatch(object, source2, matchData);
      };
    }
    module2.exports = baseMatches;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_isKey.js
var require_isKey = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_isKey.js"(exports23, module2) {
    var isArray6 = require_isArray();
    var isSymbol3 = require_isSymbol();
    var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/;
    var reIsPlainProp = /^\w*$/;
    function isKey(value, object) {
      if (isArray6(value)) {
        return false;
      }
      var type4 = typeof value;
      if (type4 == "number" || type4 == "symbol" || type4 == "boolean" || value == null || isSymbol3(value)) {
        return true;
      }
      return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object);
    }
    module2.exports = isKey;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/memoize.js
var require_memoize = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/memoize.js"(exports23, module2) {
    var MapCache = require_MapCache();
    var FUNC_ERROR_TEXT = "Expected a function";
    function memoize2(func, resolver) {
      if (typeof func != "function" || resolver != null && typeof resolver != "function") {
        throw new TypeError(FUNC_ERROR_TEXT);
      }
      var memoized = function() {
        var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache3 = memoized.cache;
        if (cache3.has(key)) {
          return cache3.get(key);
        }
        var result2 = func.apply(this, args);
        memoized.cache = cache3.set(key, result2) || cache3;
        return result2;
      };
      memoized.cache = new (memoize2.Cache || MapCache)();
      return memoized;
    }
    memoize2.Cache = MapCache;
    module2.exports = memoize2;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_memoizeCapped.js
var require_memoizeCapped = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_memoizeCapped.js"(exports23, module2) {
    var memoize2 = require_memoize();
    var MAX_MEMOIZE_SIZE = 500;
    function memoizeCapped(func) {
      var result2 = memoize2(func, function(key) {
        if (cache3.size === MAX_MEMOIZE_SIZE) {
          cache3.clear();
        }
        return key;
      });
      var cache3 = result2.cache;
      return result2;
    }
    module2.exports = memoizeCapped;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_stringToPath.js
var require_stringToPath = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_stringToPath.js"(exports23, module2) {
    var memoizeCapped = require_memoizeCapped();
    var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
    var reEscapeChar = /\\(\\)?/g;
    var stringToPath = memoizeCapped(function(string2) {
      var result2 = [];
      if (string2.charCodeAt(0) === 46) {
        result2.push("");
      }
      string2.replace(rePropName, function(match, number2, quote, subString) {
        result2.push(quote ? subString.replace(reEscapeChar, "$1") : number2 || match);
      });
      return result2;
    });
    module2.exports = stringToPath;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_castPath.js
var require_castPath = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_castPath.js"(exports23, module2) {
    var isArray6 = require_isArray();
    var isKey = require_isKey();
    var stringToPath = require_stringToPath();
    var toString8 = require_toString();
    function castPath(value, object) {
      if (isArray6(value)) {
        return value;
      }
      return isKey(value, object) ? [value] : stringToPath(toString8(value));
    }
    module2.exports = castPath;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_toKey.js
var require_toKey = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_toKey.js"(exports23, module2) {
    var isSymbol3 = require_isSymbol();
    var INFINITY = 1 / 0;
    function toKey(value) {
      if (typeof value == "string" || isSymbol3(value)) {
        return value;
      }
      var result2 = value + "";
      return result2 == "0" && 1 / value == -INFINITY ? "-0" : result2;
    }
    module2.exports = toKey;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseGet.js
var require_baseGet = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseGet.js"(exports23, module2) {
    var castPath = require_castPath();
    var toKey = require_toKey();
    function baseGet(object, path3) {
      path3 = castPath(path3, object);
      var index2 = 0, length = path3.length;
      while (object != null && index2 < length) {
        object = object[toKey(path3[index2++])];
      }
      return index2 && index2 == length ? object : void 0;
    }
    module2.exports = baseGet;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/get.js
var require_get = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/get.js"(exports23, module2) {
    var baseGet = require_baseGet();
    function get2(object, path3, defaultValue) {
      var result2 = object == null ? void 0 : baseGet(object, path3);
      return result2 === void 0 ? defaultValue : result2;
    }
    module2.exports = get2;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseHasIn.js
var require_baseHasIn = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseHasIn.js"(exports23, module2) {
    function baseHasIn(object, key) {
      return object != null && key in Object(object);
    }
    module2.exports = baseHasIn;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_hasPath.js
var require_hasPath = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_hasPath.js"(exports23, module2) {
    var castPath = require_castPath();
    var isArguments = require_isArguments();
    var isArray6 = require_isArray();
    var isIndex = require_isIndex();
    var isLength = require_isLength();
    var toKey = require_toKey();
    function hasPath(object, path3, hasFunc) {
      path3 = castPath(path3, object);
      var index2 = -1, length = path3.length, result2 = false;
      while (++index2 < length) {
        var key = toKey(path3[index2]);
        if (!(result2 = object != null && hasFunc(object, key))) {
          break;
        }
        object = object[key];
      }
      if (result2 || ++index2 != length) {
        return result2;
      }
      length = object == null ? 0 : object.length;
      return !!length && isLength(length) && isIndex(key, length) && (isArray6(object) || isArguments(object));
    }
    module2.exports = hasPath;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/hasIn.js
var require_hasIn = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/hasIn.js"(exports23, module2) {
    var baseHasIn = require_baseHasIn();
    var hasPath = require_hasPath();
    function hasIn(object, path3) {
      return object != null && hasPath(object, path3, baseHasIn);
    }
    module2.exports = hasIn;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseMatchesProperty.js
var require_baseMatchesProperty = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseMatchesProperty.js"(exports23, module2) {
    var baseIsEqual = require_baseIsEqual();
    var get2 = require_get();
    var hasIn = require_hasIn();
    var isKey = require_isKey();
    var isStrictComparable = require_isStrictComparable();
    var matchesStrictComparable = require_matchesStrictComparable();
    var toKey = require_toKey();
    var COMPARE_PARTIAL_FLAG = 1;
    var COMPARE_UNORDERED_FLAG = 2;
    function baseMatchesProperty(path3, srcValue) {
      if (isKey(path3) && isStrictComparable(srcValue)) {
        return matchesStrictComparable(toKey(path3), srcValue);
      }
      return function(object) {
        var objValue = get2(object, path3);
        return objValue === void 0 && objValue === srcValue ? hasIn(object, path3) : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);
      };
    }
    module2.exports = baseMatchesProperty;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseProperty.js
var require_baseProperty = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseProperty.js"(exports23, module2) {
    function baseProperty(key) {
      return function(object) {
        return object == null ? void 0 : object[key];
      };
    }
    module2.exports = baseProperty;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_basePropertyDeep.js
var require_basePropertyDeep = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_basePropertyDeep.js"(exports23, module2) {
    var baseGet = require_baseGet();
    function basePropertyDeep(path3) {
      return function(object) {
        return baseGet(object, path3);
      };
    }
    module2.exports = basePropertyDeep;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/property.js
var require_property = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/property.js"(exports23, module2) {
    var baseProperty = require_baseProperty();
    var basePropertyDeep = require_basePropertyDeep();
    var isKey = require_isKey();
    var toKey = require_toKey();
    function property(path3) {
      return isKey(path3) ? baseProperty(toKey(path3)) : basePropertyDeep(path3);
    }
    module2.exports = property;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseIteratee.js
var require_baseIteratee = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseIteratee.js"(exports23, module2) {
    var baseMatches = require_baseMatches();
    var baseMatchesProperty = require_baseMatchesProperty();
    var identity = require_identity();
    var isArray6 = require_isArray();
    var property = require_property();
    function baseIteratee(value) {
      if (typeof value == "function") {
        return value;
      }
      if (value == null) {
        return identity;
      }
      if (typeof value == "object") {
        return isArray6(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value);
      }
      return property(value);
    }
    module2.exports = baseIteratee;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/uniqBy.js
var require_uniqBy = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/uniqBy.js"(exports23, module2) {
    var baseIteratee = require_baseIteratee();
    var baseUniq = require_baseUniq();
    function uniqBy2(array, iteratee) {
      return array && array.length ? baseUniq(array, baseIteratee(iteratee, 2)) : [];
    }
    module2.exports = uniqBy2;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/isEqual.js
var require_isEqual = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/isEqual.js"(exports23, module2) {
    var baseIsEqual = require_baseIsEqual();
    function isEqual2(value, other) {
      return baseIsEqual(value, other);
    }
    module2.exports = isEqual2;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseMap.js
var require_baseMap = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseMap.js"(exports23, module2) {
    var baseEach = require_baseEach();
    var isArrayLike = require_isArrayLike();
    function baseMap(collection, iteratee) {
      var index2 = -1, result2 = isArrayLike(collection) ? Array(collection.length) : [];
      baseEach(collection, function(value, key, collection2) {
        result2[++index2] = iteratee(value, key, collection2);
      });
      return result2;
    }
    module2.exports = baseMap;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseSortBy.js
var require_baseSortBy = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseSortBy.js"(exports23, module2) {
    function baseSortBy(array, comparer) {
      var length = array.length;
      array.sort(comparer);
      while (length--) {
        array[length] = array[length].value;
      }
      return array;
    }
    module2.exports = baseSortBy;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_compareAscending.js
var require_compareAscending = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_compareAscending.js"(exports23, module2) {
    var isSymbol3 = require_isSymbol();
    function compareAscending(value, other) {
      if (value !== other) {
        var valIsDefined = value !== void 0, valIsNull = value === null, valIsReflexive = value === value, valIsSymbol = isSymbol3(value);
        var othIsDefined = other !== void 0, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = isSymbol3(other);
        if (!othIsNull && !othIsSymbol && !valIsSymbol && value > other || valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol || valIsNull && othIsDefined && othIsReflexive || !valIsDefined && othIsReflexive || !valIsReflexive) {
          return 1;
        }
        if (!valIsNull && !valIsSymbol && !othIsSymbol && value < other || othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol || othIsNull && valIsDefined && valIsReflexive || !othIsDefined && valIsReflexive || !othIsReflexive) {
          return -1;
        }
      }
      return 0;
    }
    module2.exports = compareAscending;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_compareMultiple.js
var require_compareMultiple = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_compareMultiple.js"(exports23, module2) {
    var compareAscending = require_compareAscending();
    function compareMultiple(object, other, orders) {
      var index2 = -1, objCriteria = object.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length;
      while (++index2 < length) {
        var result2 = compareAscending(objCriteria[index2], othCriteria[index2]);
        if (result2) {
          if (index2 >= ordersLength) {
            return result2;
          }
          var order = orders[index2];
          return result2 * (order == "desc" ? -1 : 1);
        }
      }
      return object.index - other.index;
    }
    module2.exports = compareMultiple;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseOrderBy.js
var require_baseOrderBy = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/_baseOrderBy.js"(exports23, module2) {
    var arrayMap = require_arrayMap();
    var baseGet = require_baseGet();
    var baseIteratee = require_baseIteratee();
    var baseMap = require_baseMap();
    var baseSortBy = require_baseSortBy();
    var baseUnary = require_baseUnary();
    var compareMultiple = require_compareMultiple();
    var identity = require_identity();
    var isArray6 = require_isArray();
    function baseOrderBy(collection, iteratees, orders) {
      if (iteratees.length) {
        iteratees = arrayMap(iteratees, function(iteratee) {
          if (isArray6(iteratee)) {
            return function(value) {
              return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee);
            };
          }
          return iteratee;
        });
      } else {
        iteratees = [identity];
      }
      var index2 = -1;
      iteratees = arrayMap(iteratees, baseUnary(baseIteratee));
      var result2 = baseMap(collection, function(value, key, collection2) {
        var criteria = arrayMap(iteratees, function(iteratee) {
          return iteratee(value);
        });
        return { "criteria": criteria, "index": ++index2, "value": value };
      });
      return baseSortBy(result2, function(object, other) {
        return compareMultiple(object, other, orders);
      });
    }
    module2.exports = baseOrderBy;
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/orderBy.js
var require_orderBy = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/lodash@4.17.21/node_modules/lodash/orderBy.js"(exports23, module2) {
    var baseOrderBy = require_baseOrderBy();
    var isArray6 = require_isArray();
    function orderBy2(collection, iteratees, orders, guard) {
      if (collection == null) {
        return [];
      }
      if (!isArray6(iteratees)) {
        iteratees = iteratees == null ? [] : [iteratees];
      }
      orders = guard ? void 0 : orders;
      if (!isArray6(orders)) {
        orders = orders == null ? [] : [orders];
      }
      return baseOrderBy(collection, iteratees, orders);
    }
    module2.exports = orderBy2;
  }
});

// core/performance/stats.ts
var Stats;
var init_stats = __esm({
  "core/performance/stats.ts"() {
    Stats = class {
      // let's use Welford's algorithm for online variance calculation
      count;
      mean;
      m2;
      min;
      max;
      constructor() {
        this.count = 0;
        this.mean = 0;
        this.m2 = 0;
        this.min = Number.MAX_VALUE;
        this.max = -Number.MAX_VALUE;
      }
      add(x3) {
        this.count++;
        const delta = x3 - this.mean;
        this.mean += delta / this.count;
        const delta2 = x3 - this.mean;
        this.m2 += delta * delta2;
        this.min = Math.min(this.min, x3);
        this.max = Math.max(this.max, x3);
      }
      report() {
        if (this.count === 0) {
          return {
            count: 0,
            total: 0
          };
        }
        return {
          min: this.min,
          max: this.max,
          count: this.count,
          mean: this.mean,
          variance: this.m2 / this.count,
          total: this.mean * this.count
        };
      }
    };
  }
});

// core/performance/function-times.ts
var functionTimes, makeTimedFunction, makeTimedFunctionAsync;
var init_function_times = __esm({
  "core/performance/function-times.ts"() {
    init_stats();
    functionTimes = {};
    makeTimedFunction = (name2, fn) => {
      if (Deno.env.get("QUARTO_REPORT_PERFORMANCE_METRICS") === void 0) {
        return fn;
      }
      if (!functionTimes[name2]) {
        functionTimes[name2] = new Stats();
      }
      return function(...args) {
        const start = performance.now();
        try {
          const result2 = fn(...args);
          return result2;
        } finally {
          const end = performance.now();
          functionTimes[name2].add(end - start);
        }
      };
    };
    makeTimedFunctionAsync = (name2, fn) => {
      if (Deno.env.get("QUARTO_REPORT_PERFORMANCE_METRICS") === void 0) {
        return fn;
      }
      if (!functionTimes[name2]) {
        functionTimes[name2] = new Stats();
      }
      return async function(...args) {
        const start = performance.now();
        try {
          const result2 = await fn(...args);
          return result2;
        } finally {
          const end = performance.now();
          functionTimes[name2].add(end - start);
        }
      };
    };
  }
});

// core/lodash.ts
var import_cloneDeep, import_debounce, import_difference, import_each, import_forEach, import_isArray, import_mergeWith, import_shuffle, import_template, import_toString, import_uniq, import_uniqBy, import_isObject, import_isEqual, import_orderBy, import_escape, cloneDeep, debounce, difference, each, forEach, isArray, mergeWith, shuffle, template, toString, uniq, uniqBy, isObject, isEqual, orderBy, escape;
var init_lodash = __esm({
  "core/lodash.ts"() {
    import_cloneDeep = __toESM(require_cloneDeep());
    import_debounce = __toESM(require_debounce());
    import_difference = __toESM(require_difference());
    import_each = __toESM(require_each());
    import_forEach = __toESM(require_forEach());
    import_isArray = __toESM(require_isArray());
    import_mergeWith = __toESM(require_mergeWith());
    import_shuffle = __toESM(require_shuffle());
    import_template = __toESM(require_template());
    import_toString = __toESM(require_toString());
    import_uniq = __toESM(require_uniq());
    import_uniqBy = __toESM(require_uniqBy());
    import_isObject = __toESM(require_isObject());
    import_isEqual = __toESM(require_isEqual());
    import_orderBy = __toESM(require_orderBy());
    import_escape = __toESM(require_escape());
    init_function_times();
    cloneDeep = makeTimedFunction("ld_cloneDeep", import_cloneDeep.default);
    debounce = import_debounce.default;
    difference = import_difference.default;
    each = import_each.default;
    forEach = import_forEach.default;
    isArray = import_isArray.default;
    mergeWith = import_mergeWith.default;
    shuffle = import_shuffle.default;
    template = import_template.default;
    toString = import_toString.default;
    uniq = import_uniq.default;
    uniqBy = import_uniqBy.default;
    isObject = import_isObject.default;
    isEqual = import_isEqual.default;
    orderBy = import_orderBy.default;
    escape = import_escape.default;
  }
});

// deno_ral/platform.ts
var isWindows4, isMac, isLinux, os, arch;
var init_platform = __esm({
  "deno_ral/platform.ts"() {
    isWindows4 = Deno.build.os === "windows";
    isMac = Deno.build.os === "darwin";
    isLinux = Deno.build.os === "linux";
    os = Deno.build.os;
    arch = Deno.build.arch;
  }
});

// core/env.ts
function getenv(name2, defaultValue) {
  const value = Deno.env.get(name2);
  if (value === void 0) {
    if (defaultValue === void 0) {
      throw new Error(`Required environment variable ${name2} not specified.`);
    } else {
      return defaultValue;
    }
  } else {
    return value;
  }
}
function withPath(paths) {
  const delimiter6 = isWindows4 ? ";" : ":";
  const currentPath = Deno.env.get("PATH") || "";
  if (paths.append !== void 0 && paths.prepend !== void 0) {
    return currentPath;
  } else if (paths.append?.length === 0 && paths.prepend?.length === 0) {
    return currentPath;
  } else {
    const modifiedPaths = [currentPath];
    if (paths.append) {
      modifiedPaths.unshift(...paths.append);
    }
    if (paths.prepend) {
      modifiedPaths.push(...paths.prepend);
    }
    return modifiedPaths.join(delimiter6);
  }
}
var init_env = __esm({
  "core/env.ts"() {
    init_platform();
  }
});

// https://jsr.io/@std/async/1.0.12/abortable.ts
var init_abortable = __esm({
  "https://jsr.io/@std/async/1.0.12/abortable.ts"() {
  }
});

// https://jsr.io/@std/async/1.0.12/deadline.ts
var init_deadline = __esm({
  "https://jsr.io/@std/async/1.0.12/deadline.ts"() {
    init_abortable();
  }
});

// https://jsr.io/@std/async/1.0.12/debounce.ts
var init_debounce = __esm({
  "https://jsr.io/@std/async/1.0.12/debounce.ts"() {
  }
});

// https://jsr.io/@std/async/1.0.12/delay.ts
var init_delay = __esm({
  "https://jsr.io/@std/async/1.0.12/delay.ts"() {
  }
});

// https://jsr.io/@std/async/1.0.12/mux_async_iterator.ts
var MuxAsyncIterator;
var init_mux_async_iterator = __esm({
  "https://jsr.io/@std/async/1.0.12/mux_async_iterator.ts"() {
    MuxAsyncIterator = class {
      #iteratorCount = 0;
      #yields = [];
      // deno-lint-ignore no-explicit-any
      #throws = [];
      #signal = Promise.withResolvers();
      /**
       * Add an async iterable to the stream.
       *
       * @param iterable The async iterable to add.
       *
       * @example Usage
       * ```ts
       * import { MuxAsyncIterator } from "@std/async/mux-async-iterator";
       * import { assertEquals } from "@std/assert";
       *
       * async function* gen123(): AsyncIterableIterator<number> {
       *   yield 1;
       *   yield 2;
       *   yield 3;
       * }
       *
       * const mux = new MuxAsyncIterator<number>();
       * mux.add(gen123());
       *
       * const result = await Array.fromAsync(mux.iterate());
       *
       * assertEquals(result, [1, 2, 3]);
       * ```
       */
      add(iterable) {
        ++this.#iteratorCount;
        this.#callIteratorNext(iterable[Symbol.asyncIterator]());
      }
      async #callIteratorNext(iterator) {
        try {
          const { value, done } = await iterator.next();
          if (done) {
            --this.#iteratorCount;
          } else {
            this.#yields.push({ iterator, value });
          }
        } catch (e5) {
          this.#throws.push(e5);
        }
        this.#signal.resolve();
      }
      /**
       * Returns an async iterator of the stream.
       * @returns the async iterator for all the added async iterables.
       *
       * @example Usage
       * ```ts
       * import { MuxAsyncIterator } from "@std/async/mux-async-iterator";
       * import { assertEquals } from "@std/assert";
       *
       * async function* gen123(): AsyncIterableIterator<number> {
       *   yield 1;
       *   yield 2;
       *   yield 3;
       * }
       *
       * const mux = new MuxAsyncIterator<number>();
       * mux.add(gen123());
       *
       * const result = await Array.fromAsync(mux.iterate());
       *
       * assertEquals(result, [1, 2, 3]);
       * ```
       */
      async *iterate() {
        while (this.#iteratorCount > 0) {
          await this.#signal.promise;
          for (const { iterator, value } of this.#yields) {
            yield value;
            this.#callIteratorNext(iterator);
          }
          if (this.#throws.length) {
            for (const e5 of this.#throws) {
              throw e5;
            }
          }
          this.#yields.length = 0;
          this.#signal = Promise.withResolvers();
        }
      }
      /**
       * Implements an async iterator for the stream.
       * @returns the async iterator for all the added async iterables.
       *
       * @example Usage
       * ```ts
       * import { MuxAsyncIterator } from "@std/async/mux-async-iterator";
       * import { assertEquals } from "@std/assert";
       *
       * async function* gen123(): AsyncIterableIterator<number> {
       *   yield 1;
       *   yield 2;
       *   yield 3;
       * }
       *
       * const mux = new MuxAsyncIterator<number>();
       * mux.add(gen123());
       *
       * const result = await Array.fromAsync(mux);
       *
       * assertEquals(result, [1, 2, 3]);
       * ```
       */
      [Symbol.asyncIterator]() {
        return this.iterate();
      }
    };
  }
});

// https://jsr.io/@std/async/1.0.12/pool.ts
function pooledMap(poolLimit, array, iteratorFn) {
  const res = new TransformStream({
    async transform(p5, controller) {
      try {
        const s5 = await p5;
        controller.enqueue(s5);
      } catch (e5) {
        if (e5 instanceof AggregateError && e5.message === ERROR_WHILE_MAPPING_MESSAGE) {
          controller.error(e5);
        }
      }
    }
  });
  (async () => {
    const writer = res.writable.getWriter();
    const executing = [];
    try {
      for await (const item of array) {
        const p5 = Promise.resolve().then(() => iteratorFn(item));
        writer.write(p5);
        const e5 = p5.then(
          () => executing.splice(executing.indexOf(e5), 1)
        );
        executing.push(e5);
        if (executing.length >= poolLimit) {
          await Promise.race(executing);
        }
      }
      await Promise.all(executing);
      writer.close();
    } catch {
      const errors2 = [];
      for (const result2 of await Promise.allSettled(executing)) {
        if (result2.status === "rejected") {
          errors2.push(result2.reason);
        }
      }
      writer.write(Promise.reject(
        new AggregateError(errors2, ERROR_WHILE_MAPPING_MESSAGE)
      )).catch(() => {
      });
    }
  })();
  return Symbol.asyncIterator in res.readable && typeof res.readable[Symbol.asyncIterator] === "function" ? res.readable[Symbol.asyncIterator]() : (async function* () {
    const reader = res.readable.getReader();
    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      yield value;
    }
    reader.releaseLock();
  })();
}
var ERROR_WHILE_MAPPING_MESSAGE;
var init_pool = __esm({
  "https://jsr.io/@std/async/1.0.12/pool.ts"() {
    ERROR_WHILE_MAPPING_MESSAGE = "Cannot complete the mapping as an error was thrown from an item";
  }
});

// https://jsr.io/@std/async/1.0.12/tee.ts
var init_tee = __esm({
  "https://jsr.io/@std/async/1.0.12/tee.ts"() {
  }
});

// https://jsr.io/@std/async/1.0.12/_util.ts
var init_util3 = __esm({
  "https://jsr.io/@std/async/1.0.12/_util.ts"() {
  }
});

// https://jsr.io/@std/async/1.0.12/retry.ts
var init_retry = __esm({
  "https://jsr.io/@std/async/1.0.12/retry.ts"() {
    init_util3();
  }
});

// https://jsr.io/@std/async/1.0.12/mod.ts
var init_mod4 = __esm({
  "https://jsr.io/@std/async/1.0.12/mod.ts"() {
    init_abortable();
    init_deadline();
    init_debounce();
    init_delay();
    init_mux_async_iterator();
    init_pool();
    init_tee();
    init_retry();
  }
});

// core/cleanup.ts
function onCleanup(handler) {
  cleanupHandlers.push(handler);
}
function exitWithCleanup(code5) {
  for (let i6 = cleanupHandlers.length - 1; i6 >= 0; i6--) {
    const handler = cleanupHandlers[i6];
    try {
      handler();
    } catch (error2) {
      info("Error occurred during cleanup: " + error2);
    }
  }
  Deno.exit(code5);
}
var cleanupHandlers;
var init_cleanup = __esm({
  "core/cleanup.ts"() {
    init_log();
    cleanupHandlers = [];
  }
});

// core/process.ts
function registerForExitCleanup(process4) {
  const thisProcessId = ++processCount;
  processList.set(thisProcessId, process4);
  return thisProcessId;
}
function unregisterForExitCleanup(processId) {
  processList.delete(processId);
}
function ensureCleanup() {
  if (!cleanupRegistered) {
    cleanupRegistered = true;
    onCleanup(() => {
      for (const process4 of processList.values()) {
        try {
          process4.kill();
        } catch (error2) {
          info("Error occurred during cleanup: " + error2);
        }
      }
    });
  }
}
async function execProcess(options, stdin2, mergeOutput, stderrFilter, respectStreams, timeout) {
  const withTimeout = (promise) => {
    return timeout ? Promise.race([
      promise,
      new Promise(
        (_3, reject2) => setTimeout(() => reject2(new Error("Process timed out")), timeout)
      )
    ]) : promise;
  };
  ensureCleanup();
  try {
    debug(`[execProcess] ${[options.cmd, ...options.args || []].join(" ")}`);
    const denoCmd = new Deno.Command(options.cmd, {
      ...options,
      stdin: stdin2 !== void 0 ? "piped" : options.stdin,
      stdout: typeof options.stdout === "number" ? options.stdout : "piped",
      stderr: typeof options.stderr === "number" ? options.stderr : "piped"
    });
    const process4 = denoCmd.spawn();
    const thisProcessId = registerForExitCleanup(process4);
    if (stdin2 !== void 0) {
      const stdinWriter = process4.stdin.getWriter();
      if (!process4.stdin) {
        unregisterForExitCleanup(thisProcessId);
        throw new Error("Process stdin not available");
      }
      const kWindowSize = 4096;
      const buffer2 = new TextEncoder().encode(stdin2);
      let offset3 = 0;
      while (offset3 < buffer2.length) {
        const end = Math.min(offset3 + kWindowSize, buffer2.length);
        const window2 = buffer2.subarray(offset3, end);
        await stdinWriter.write(window2);
        offset3 += window2.byteLength;
      }
      stdinWriter.releaseLock();
      process4.stdin.close();
    }
    let stdoutText = "";
    let stderrText = "";
    if (mergeOutput) {
      const multiplexIterator = new MuxAsyncIterator();
      const addStream = (iterator, filter3) => {
        const streamIter = filter3 ? filteredAsyncIterator(iterator, filter3) : iterator;
        multiplexIterator.add(streamIter);
      };
      addStream(process4.stdout.values());
      addStream(process4.stderr.values(), stderrFilter);
      const allOutput = await processOutput(
        multiplexIterator,
        mergeOutput === "stderr>stdout" ? options.stdout : options.stderr
      );
      if (mergeOutput === "stderr>stdout") {
        stdoutText = allOutput;
      } else {
        stderrText = allOutput;
      }
    } else {
      const promises2 = [];
      if (process4.stdout !== null) {
        promises2.push(
          processOutput(
            process4.stdout.values(),
            options.stdout,
            respectStreams ? "stdout" : void 0
          ).then((text) => {
            stdoutText = text;
          })
        );
      }
      if (process4.stderr != null) {
        const iterator = stderrFilter ? filteredAsyncIterator(process4.stderr.values(), stderrFilter) : process4.stderr.values();
        promises2.push(
          processOutput(
            iterator,
            options.stderr,
            respectStreams ? "stderr" : void 0
          ).then((text) => {
            stderrText = text;
          })
        );
      }
      await withTimeout(Promise.all(promises2));
    }
    const status = await withTimeout(process4.output());
    unregisterForExitCleanup(thisProcessId);
    debug(`[execProcess] Success: ${status.success}, code: ${status.code}`);
    return {
      success: status.success,
      code: status.code,
      stdout: stdoutText,
      stderr: stderrText
    };
  } catch (e5) {
    if (!(e5 instanceof Error)) {
      throw e5;
    }
    throw new Error(`Error executing '${options.cmd}': ${e5.message}`);
  }
}
function processSuccessResult() {
  return {
    success: true,
    code: 0
  };
}
function filteredAsyncIterator(iterator, filter3) {
  const encoder4 = new TextEncoder();
  const decoder3 = new TextDecoder();
  return pooledMap(1, iterator, (data3) => {
    return Promise.resolve(
      encoder4.encode(filter3(decoder3.decode(data3)))
    );
  });
}
async function processOutput(iterator, output, which2) {
  const decoder3 = new TextDecoder();
  let outputText = "";
  for await (const chunk of iterator) {
    if (output === "inherit" || output === void 0) {
      if (which2 === "stdout") {
        Deno.stdout.writeSync(chunk);
      } else if (which2 === "stderr") {
        Deno.stderr.writeSync(chunk);
      } else {
        info(decoder3.decode(chunk), { newline: false });
      }
    }
    const text = decoder3.decode(chunk);
    outputText += text;
  }
  return outputText;
}
var processList, processCount, cleanupRegistered;
var init_process = __esm({
  "core/process.ts"() {
    init_mod4();
    init_log();
    init_cleanup();
    processList = /* @__PURE__ */ new Map();
    processCount = 0;
    cleanupRegistered = false;
  }
});

// core/path.ts
function removeIfExists(file) {
  if (existsSync2(file)) {
    safeRemoveSync(file, { recursive: true });
  }
}
function safeRemoveIfExists(file) {
  try {
    removeIfExists(file);
  } catch (error2) {
    if (!(error2 instanceof Error)) {
      throw error2;
    }
    warn(`Error removing file ${file}: ${error2.message}`);
  }
}
function removeIfEmptyDir(dir) {
  if (existsSync2(dir)) {
    let empty3 = true;
    for (const _entry of Deno.readDirSync(dir)) {
      empty3 = false;
      break;
    }
    if (empty3) {
      safeRemoveSync(dir, { recursive: true });
      return true;
    }
    return false;
  } else {
    return false;
  }
}
function isModifiedAfter(file, otherFile) {
  if (!existsSync2(file)) {
    throw new Error(`${file} does not exist`);
  }
  if (!existsSync2(otherFile)) {
    return true;
  }
  const fileInfo = Deno.statSync(file);
  const otherfileInfo = Deno.statSync(otherFile);
  if (fileInfo.mtime === null || otherfileInfo.mtime === null) {
    return true;
  } else {
    return fileInfo.mtime > otherfileInfo.mtime;
  }
}
function dirAndStem(file) {
  return [
    dirname4(file),
    basename4(file, extname4(file))
  ];
}
function isQmdFile(file) {
  const ext = extname4(file).toLowerCase();
  const kQmdExtensions2 = [".qmd"];
  return kQmdExtensions2.includes(ext);
}
function expandPath(path3) {
  if (path3 === "~") {
    return getenv("HOME", "~");
  } else {
    return path3.replace(/^~\//, getenv("HOME", "~") + "/");
  }
}
function safeExistsSync(path3) {
  try {
    return existsSync2(path3);
  } catch {
    return false;
  }
}
async function which(cmd) {
  const args = isWindows4 ? ["CMD", "/C", "where", cmd] : ["which", cmd];
  const result2 = await execProcess(
    { cmd: args[0], args: args.slice(1), stderr: "piped", stdout: "piped" }
  );
  if (result2.code === 0) {
    return isWindows4 ? result2.stdout?.split("\n")[0].trim() : result2.stdout?.trim();
  } else {
    return void 0;
  }
}
function filterPaths(root, paths, globs, options) {
  const expandGlobs = (targetGlobs) => {
    const expanded = [];
    for (const glob of targetGlobs) {
      const needSlash = !root.endsWith("/") && !glob.startsWith("/");
      const regex = globToRegExp4(`${root}${needSlash ? "/" : ""}${glob}`);
      const matchingFiles = paths.filter((path3) => {
        return regex.test(path3);
      });
      expanded.push(...matchingFiles);
    }
    return uniq(expanded);
  };
  return resolveGlobs(root, globs, expandGlobs, options);
}
function resolvePathGlobs(root, globs, exclude, options) {
  const expandGlobs = (targetGlobs) => {
    const expanded = [];
    for (const glob of targetGlobs) {
      try {
        for (const file of expandGlobSync(
          glob,
          { root, exclude, includeDirs: true, extended: true, globstar: true }
        )) {
          expanded.push(file.path);
        }
      } catch (e5) {
        if (!(e5 instanceof Deno.errors.NotFound)) {
          throw e5;
        }
      }
    }
    return uniq(expanded);
  };
  return resolveGlobs(root, globs, expandGlobs, options);
}
function pathWithForwardSlashes(path3) {
  return path3.replace(/\\/g, "/");
}
function ensureTrailingSlash(path3) {
  if (path3 && !path3.endsWith("/")) {
    return path3 + "/";
  } else {
    return path3;
  }
}
function ensureLeadingSlash(path3) {
  if (path3 && !path3.startsWith("/")) {
    return "/" + path3;
  } else {
    return path3;
  }
}
function resolveGlobs(root, globs, expandGlobs, options) {
  const includeGlobs = [];
  const excludeGlobs = [];
  const asFullGlob = (glob, preferSmart) => {
    const useSmartGlobs = () => {
      if (options?.mode === "strict") {
        return false;
      } else if (options?.mode === "always") {
        return true;
      } else if (options?.mode === "auto") {
        if (preferSmart) {
          return true;
        } else {
          return isGlob2(glob);
        }
      } else {
        return true;
      }
    };
    const smartGlob = useSmartGlobs();
    if (glob.startsWith("\\!")) {
      glob = glob.slice(1);
    }
    if (smartGlob) {
      glob = glob.replace(/^\.([\/\\])+/, "$1");
      if (glob.endsWith("/")) {
        glob = glob + "**/*";
      } else {
        const fullPath = join4(root, glob);
        try {
          if (Deno.statSync(fullPath).isDirectory) {
            glob = glob + "/**/*";
          }
        } catch {
        }
      }
    }
    if (!glob.startsWith("/")) {
      if (smartGlob && (!options || !options.explicitSubfolderSearch)) {
        return "**/" + glob;
      } else {
        return glob;
      }
    } else {
      return glob.slice(1);
    }
  };
  for (const glob of globs) {
    if (glob.startsWith("!")) {
      excludeGlobs.push(asFullGlob(glob.slice(1), true));
    } else {
      includeGlobs.push(asFullGlob(glob));
    }
  }
  const includeFiles = expandGlobs(includeGlobs);
  const excludeFiles = expandGlobs(excludeGlobs);
  return {
    include: includeFiles,
    exclude: excludeFiles
  };
}
function normalizePath(path3) {
  let file = path3 instanceof URL ? fromFileUrl4(path3) : path3;
  if (!isAbsolute4(file)) {
    file = join4(Deno.cwd(), file);
  }
  file = normalize4(file);
  return file.replace(/^\w:\\/, (m4) => m4[0].toUpperCase() + ":\\");
}
function suggestUserBinPaths() {
  if (!isWindows4) {
    const possiblePaths = [
      "/usr/local/bin",
      "~/.local/bin",
      "~/bin"
    ];
    const pathRaw = Deno.env.get("PATH");
    const paths = pathRaw ? pathRaw.split(":") : [];
    return possiblePaths.filter((path3) => {
      return paths.includes(path3) || paths.includes(expandPath(path3));
    });
  } else {
    throw new Error("suggestUserBinPaths not currently supported on Windows");
  }
}
var kSkipHidden;
var init_path2 = __esm({
  "core/path.ts"() {
    init_path();
    init_log();
    init_fs();
    init_fs();
    init_lodash();
    init_env();
    init_process();
    init_platform();
    kSkipHidden = /[/\\][\.]/;
  }
});

// https://jsr.io/@std/fmt/1.0.6/colors.ts
function code3(open, close) {
  return {
    open: `\x1B[${open.join(";")}m`,
    close: `\x1B[${close}m`,
    regexp: new RegExp(`\\x1b\\[${close}m`, "g")
  };
}
function run3(str3, code5) {
  return enabled3 ? `${code5.open}${str3.replace(code5.regexp, code5.open)}${code5.close}` : str3;
}
function bold3(str3) {
  return run3(str3, code3([1], 22));
}
function dim2(str3) {
  return run3(str3, code3([2], 22));
}
function underline2(str3) {
  return run3(str3, code3([4], 24));
}
function red3(str3) {
  return run3(str3, code3([31], 39));
}
function green2(str3) {
  return run3(str3, code3([32], 39));
}
function yellow3(str3) {
  return run3(str3, code3([33], 39));
}
function blue3(str3) {
  return run3(str3, code3([34], 39));
}
function brightRed2(str3) {
  return run3(str3, code3([91], 39));
}
function stripAnsiCode(string2) {
  return string2.replace(ANSI_PATTERN3, "");
}
var Deno4, noColor3, enabled3, ANSI_PATTERN3;
var init_colors2 = __esm({
  "https://jsr.io/@std/fmt/1.0.6/colors.ts"() {
    ({ Deno: Deno4 } = globalThis);
    noColor3 = typeof Deno4?.noColor === "boolean" ? Deno4.noColor : false;
    enabled3 = !noColor3;
    ANSI_PATTERN3 = new RegExp(
      [
        "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
        "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TXZcf-nq-uy=><~]))"
      ].join("|"),
      "g"
    );
  }
});

// https://jsr.io/@std/fmt/1.0.6/printf.ts
var init_printf = __esm({
  "https://jsr.io/@std/fmt/1.0.6/printf.ts"() {
    init_colors2();
  }
});

// core/lib/binary-search.ts
function glb(array, value, compare2) {
  compare2 = compare2 || ((a5, b3) => a5 - b3);
  if (array.length === 0) {
    return -1;
  }
  if (array.length === 1) {
    if (compare2(value, array[0]) < 0) {
      return -1;
    } else {
      return 0;
    }
  }
  let left = 0;
  let right = array.length - 1;
  const vLeft = array[left], vRight = array[right];
  if (compare2(value, vRight) >= 0) {
    return right;
  }
  if (compare2(value, vLeft) < 0) {
    return -1;
  }
  while (right - left > 1) {
    const center = left + (right - left >> 1);
    const vCenter = array[center];
    const cmp2 = compare2(value, vCenter);
    if (cmp2 < 0) {
      right = center;
    } else if (cmp2 === 0) {
      left = center;
    } else {
      left = center;
    }
  }
  return left;
}
var init_binary_search = __esm({
  "core/lib/binary-search.ts"() {
  }
});

// core/lib/error.ts
function asErrorEx(e5, defaultShowStack = true) {
  if (e5 instanceof ErrorEx) {
    return e5;
  } else if (e5 instanceof Error) {
    e5.printName = e5.name !== "Error";
    e5.printStack = defaultShowStack && !!e5.message;
    return e5;
  } else {
    return new ErrorEx("Error", String(e5), false, true);
  }
}
var DynamicTypeCheckError, InternalError, UnreachableError, ErrorEx;
var init_error2 = __esm({
  "core/lib/error.ts"() {
    DynamicTypeCheckError = class extends Error {
      constructor(message, printName = true, printStack = true) {
        super(message);
        this.name = "Dynamic Type-Checking Error";
        this.printName = printName;
        this.printStack = printStack;
      }
      printName;
      printStack;
    };
    InternalError = class extends Error {
      constructor(message, printName = true, printStack = true) {
        super(message);
        this.name = "Internal Error";
        this.printName = printName;
        this.printStack = printStack;
      }
      printName;
      printStack;
    };
    UnreachableError = class extends InternalError {
      constructor() {
        super("Unreachable code was reached.", true, true);
      }
    };
    ErrorEx = class extends Error {
      constructor(name2, message, printName = true, printStack = true) {
        super(message);
        this.name = name2;
        this.printName = printName;
        this.printStack = printStack;
      }
      printName;
      printStack;
    };
  }
});

// core/lib/external/colors.ts
function code4(open, close) {
  return {
    open: `\x1B[${open.join(";")}m`,
    close: `\x1B[${close}m`,
    regexp: new RegExp(`\\x1b\\[${close}m`, "g")
  };
}
function run4(str3, code5) {
  return enabled4 ? `${code5.open}${str3.replace(code5.regexp, code5.open)}${code5.close}` : str3;
}
function red4(str3) {
  return run4(str3, code4([31], 39));
}
function blue4(str3) {
  return run4(str3, code4([34], 39));
}
function stripColor2(string2) {
  return string2.replace(ANSI_PATTERN4, "");
}
var Deno5, noColor4, enabled4, ANSI_PATTERN4;
var init_colors3 = __esm({
  "core/lib/external/colors.ts"() {
    try {
      Deno5 = globalThis.Deno;
    } catch (_e) {
    }
    noColor4 = typeof (Deno5 && Deno5.noColor) === "boolean" ? Deno5.noColor : true;
    enabled4 = !noColor4;
    ANSI_PATTERN4 = new RegExp(
      [
        "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
        "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"
      ].join("|"),
      "g"
    );
  }
});

// core/lib/errors.ts
function platformHasNonAsciiCharacters() {
  try {
    return Deno.build.os !== "windows";
  } catch (_e) {
    return true;
  }
}
function tidyverseInfo(msg5) {
  if (platformHasNonAsciiCharacters()) {
    return `${blue4("\u2139")} ${msg5}`;
  } else {
    return `${blue4("i")} ${msg5}`;
  }
}
function tidyverseError(msg5) {
  if (platformHasNonAsciiCharacters()) {
    return `${red4("\u2716")} ${msg5}`;
  } else {
    return `${red4("x")} ${msg5}`;
  }
}
function tidyverseFormatError(msg5) {
  let { heading, error: error2, info: info2 } = msg5;
  if (msg5.location) {
    heading = `${locationString(msg5.location)} ${heading}`;
  }
  if (msg5.fileName) {
    heading = `In file ${msg5.fileName}
${heading}`;
  }
  const strings3 = [
    heading,
    msg5.sourceContext,
    ...error2.map(tidyverseError),
    ...Object.values(info2).map(tidyverseInfo),
    ""
  ];
  return strings3.join("\n");
}
function quotedStringColor(msg5) {
  return blue4(msg5);
}
function addFileInfo(msg5, src2) {
  if (src2.fileName !== void 0) {
    msg5.fileName = src2.fileName;
  }
}
function addInstancePathInfo(msg5, instancePath) {
  if (instancePath.length) {
    const niceInstancePath = instancePath.map((s5) => blue4(String(s5))).join(":");
    msg5.info["instance-path-location"] = `The error happened in location ${niceInstancePath}.`;
  }
}
function locationString(loc) {
  const { start, end } = loc;
  if (start.line === end.line) {
    if (start.column === end.column) {
      return `(line ${start.line + 1}, column ${start.column + 1})`;
    } else {
      return `(line ${start.line + 1}, columns ${start.column + 1}--${end.column + 1})`;
    }
  } else {
    return `(line ${start.line + 1}, column ${start.column + 1} through line ${end.line + 1}, column ${end.column + 1})`;
  }
}
function errorKey(err2) {
  const positionKey = (pos) => `${pos.line}-${pos.column}`;
  return `${err2.fileName || ""}-${positionKey(err2.location.start)}-${positionKey(err2.location.end)}`;
}
function reportOnce(reporter, reportSet) {
  const errorsReported = reportSet || /* @__PURE__ */ new Set();
  return (err2) => {
    const key = errorKey(err2);
    if (errorsReported.has(key)) {
      return;
    }
    errorsReported.add(key);
    reporter(err2);
  };
}
var init_errors = __esm({
  "core/lib/errors.ts"() {
    init_colors3();
  }
});

// core/lib/text.ts
function lines(text) {
  return text.split(/\r\n?|\n/);
}
function normalizeNewlines(text) {
  return lines(text).join("\n");
}
function trimEmptyLines(lines2, trim = "all") {
  if (trim === "all" || trim === "leading") {
    const firstNonEmpty = lines2.findIndex((line) => line.trim().length > 0);
    if (firstNonEmpty === -1) {
      return [];
    }
    lines2 = lines2.slice(firstNonEmpty);
  }
  if (trim === "all" || trim === "trailing") {
    let lastNonEmpty = -1;
    for (let i6 = lines2.length - 1; i6 >= 0; i6--) {
      if (lines2[i6].trim().length > 0) {
        lastNonEmpty = i6;
        break;
      }
    }
    if (lastNonEmpty > -1) {
      lines2 = lines2.slice(0, lastNonEmpty + 1);
    }
  }
  return lines2;
}
function* matchAll(text, regexp) {
  if (!regexp.global) {
    throw new Error("matchAll requires global regexps");
  }
  let match;
  while ((match = regexp.exec(text)) !== null) {
    yield match;
  }
}
function* lineOffsets(text) {
  yield 0;
  for (const match of matchAll(text, /\r\n?|\n/g)) {
    yield match.index + match[0].length;
  }
}
function* lineBreakPositions(text) {
  for (const match of matchAll(text, /\r\n?|\n/g)) {
    yield match.index;
  }
}
function indexToLineCol(text) {
  const offsets = Array.from(lineOffsets(text));
  return function(offset3) {
    if (offset3 === 0) {
      return {
        line: 0,
        column: 0
      };
    }
    const startIndex = glb(offsets, offset3);
    return {
      line: startIndex,
      column: offset3 - offsets[startIndex]
    };
  };
}
function lineColToIndex(text) {
  const offsets = Array.from(lineOffsets(text));
  return function(position) {
    return offsets[position.line] + position.column;
  };
}
function formatLineRange(text, firstLine, lastLine) {
  const lineWidth = Math.max(
    String(firstLine + 1).length,
    String(lastLine + 1).length
  );
  const pad = " ".repeat(lineWidth);
  const ls = lines(text);
  const result2 = [];
  for (let i6 = firstLine; i6 <= lastLine; ++i6) {
    const numberStr = `${pad}${i6 + 1}: `.slice(-(lineWidth + 2));
    const lineStr = ls[i6];
    result2.push({
      lineNumber: i6,
      content: numberStr + quotedStringColor(lineStr),
      rawLine: ls[i6]
    });
  }
  return {
    prefixWidth: lineWidth + 2,
    lines: result2
  };
}
function editDistance(w1, w22) {
  const cost = (c6) => {
    if ("_-".indexOf(c6) !== -1) {
      return 1;
    }
    return 10;
  };
  const cost2 = (c1, c22) => {
    if (c1 === c22) {
      return 0;
    }
    if ("_-".indexOf(c1) !== -1 && "_-".indexOf(c22) !== -1) {
      return 1;
    }
    if (c1.toLocaleLowerCase() === c22.toLocaleLowerCase()) {
      return 1;
    }
    const cc1 = c1.charCodeAt(0);
    const cc2 = c22.charCodeAt(0);
    if (cc1 >= 48 && cc1 <= 57 && cc2 >= 48 && cc2 <= 57) {
      return 1;
    }
    return 10;
  };
  const s1 = w1.length + 1;
  const s22 = w22.length + 1;
  const v4 = new Int32Array(s1 * s22);
  for (let i6 = 0; i6 < s1; ++i6) {
    for (let j3 = 0; j3 < s22; ++j3) {
      if (i6 === 0 && j3 === 0) {
        continue;
      } else if (i6 === 0) {
        v4[i6 * s22 + j3] = v4[i6 * s22 + (j3 - 1)] + cost(w22[j3 - 1]);
      } else if (j3 === 0) {
        v4[i6 * s22 + j3] = v4[(i6 - 1) * s22 + j3] + cost(w1[i6 - 1]);
      } else {
        v4[i6 * s22 + j3] = Math.min(
          v4[(i6 - 1) * s22 + (j3 - 1)] + cost2(w1[i6 - 1], w22[j3 - 1]),
          v4[i6 * s22 + (j3 - 1)] + cost(w22[j3 - 1]),
          v4[(i6 - 1) * s22 + j3] + cost(w1[i6 - 1])
        );
      }
    }
  }
  return v4[(w1.length + 1) * (w22.length + 1) - 1];
}
function detectCaseConvention(key) {
  if (key.toLocaleLowerCase() !== key) {
    return "capitalizationCase";
  }
  const underscoreIndex = key.indexOf("_");
  if (underscoreIndex !== -1 && underscoreIndex !== 0 && underscoreIndex !== key.length - 1) {
    return "underscore_case";
  }
  const dashIndex = key.indexOf("-");
  if (dashIndex !== -1 && dashIndex !== 0 && dashIndex !== key.length - 1) {
    return "dash-case";
  }
  return void 0;
}
function resolveCaseConventionRegex(keys, conventions) {
  if (conventions !== void 0) {
    if (conventions.length === 0) {
      throw new InternalError(
        "resolveCaseConventionRegex requires nonempty `conventions`"
      );
    }
    return {
      pattern: conventions.map((c6) => `(${c6})`).join("|"),
      list: conventions
    };
  }
  const disallowedNearMisses = [];
  const keySet = new Set(keys);
  const addNearMiss = (value) => {
    if (!keySet.has(value)) {
      disallowedNearMisses.push(value);
    }
  };
  const foundConventions = /* @__PURE__ */ new Set();
  for (const key of keys) {
    const found = detectCaseConvention(key);
    if (found) {
      foundConventions.add(found);
    }
    switch (found) {
      case "capitalizationCase":
        addNearMiss(toUnderscoreCase(key));
        addNearMiss(toDashCase(key));
        break;
      case "dash-case":
        addNearMiss(toUnderscoreCase(key));
        addNearMiss(toCapitalizationCase(key));
        break;
      case "underscore_case":
        addNearMiss(toDashCase(key));
        addNearMiss(toCapitalizationCase(key));
        break;
    }
  }
  if (foundConventions.size === 0) {
    return {
      pattern: void 0,
      list: []
    };
  }
  return {
    pattern: `(?!(${disallowedNearMisses.map((c6) => `^${c6}$`).join("|")}))`,
    list: Array.from(foundConventions)
  };
}
function toDashCase(str3) {
  return toUnderscoreCase(str3).replace(/_/g, "-");
}
function toUnderscoreCase(str3) {
  return str3.replace(
    /([A-Z]+)/g,
    (_match, p1) => `-${p1}`
  ).replace(/-/g, "_").split("_").filter((x3) => x3.length).join("_").toLocaleLowerCase();
}
function toCapitalizationCase(str3) {
  return toUnderscoreCase(str3).replace(
    /_(.)/g,
    (_match, p1) => p1.toLocaleUpperCase()
  );
}
var getEndingNewlineCount;
var init_text = __esm({
  "core/lib/text.ts"() {
    init_binary_search();
    init_error2();
    init_errors();
    getEndingNewlineCount = (lines2) => {
      let count = 0;
      for (let i6 = lines2.length - 1; i6 >= 0; i6--) {
        if (lines2[i6].match(/^\n+$/)) {
          count += lines2[i6].length;
          continue;
        }
        const m4 = lines2[i6].match(/\n+$/);
        if (m4) {
          count += m4[0].length;
          break;
        }
        if (lines2[i6].length) {
          break;
        }
      }
      return count;
    };
  }
});

// core/text.ts
function capitalizeWord(str3) {
  return str3.slice(0, 1).toUpperCase() + str3.slice(1);
}
function capitalizeTitle(str3) {
  return str3.split(/\s+/).map((str4, index2, arr) => {
    if (index2 === 0 || index2 === arr.length - 1 || !isNotCapitalized(str4)) {
      return capitalizeWord(str4);
    } else {
      return str4;
    }
  }).join(" ");
}
function isNotCapitalized(str3) {
  return [
    // articles
    "a",
    "an",
    "the",
    // coordinating conjunctions
    "for",
    "and",
    "nor",
    "but",
    "or",
    "yet",
    "so",
    // prepositions
    "with",
    "at",
    "by",
    "to",
    "in",
    "for",
    "from",
    "of",
    "on"
  ].includes(str3);
}
function trimSentence(text) {
  const match = text.match(kLastPunctuationRegex);
  if (match) {
    return {
      text: match[0],
      trimmed: true
    };
  } else {
    return {
      text,
      trimmed: false
    };
  }
}
function trimLength(text, length) {
  if (text.length < length) {
    return {
      text,
      trimmed: false
    };
  } else {
    return {
      text: text.substring(0, length),
      trimmed: true
    };
  }
}
function trimSpace(text) {
  const lastSpace = text.lastIndexOf(" ");
  if (lastSpace > 0) {
    return {
      text: text.substring(0, lastSpace),
      trimmed: true
    };
  } else {
    return {
      text,
      trimmed: false
    };
  }
}
function truncateText(text, length, breakAt) {
  const trimEnd = (text2) => {
    if ([",", "/", ":"].includes(text2.charAt(text2.length - 1))) {
      return text2.substring(0, text2.length - 1);
    } else {
      return text2;
    }
  };
  const trimAtSpace = (text2) => {
    const spaceResult = trimSpace(
      text2.substring(0, text2.length - 1)
    );
    return trimEnd(spaceResult.text) + "\u2026";
  };
  const trimPunc = (text2) => {
    const puncResult = trimSentence(text2);
    if (puncResult.trimmed) {
      return puncResult.text;
    } else {
      return trimAtSpace(puncResult.text);
    }
  };
  const lengthResult = trimLength(text, length);
  if (lengthResult.trimmed) {
    if (breakAt === "punctuation") {
      return trimPunc(lengthResult.text);
    } else {
      return trimAtSpace(lengthResult.text);
    }
  } else {
    return lengthResult.text;
  }
}
var kLastPunctuationRegex;
var init_text2 = __esm({
  "core/text.ts"() {
    init_printf();
    init_colors2();
    init_text();
    init_text();
    kLastPunctuationRegex = /([\S\s]*)[\.\?\!]/;
  }
});

// core/lib/yaml-schema/constants.ts
var booleanSchema, numberSchema, stringSchema, nullSchema;
var init_constants5 = __esm({
  "core/lib/yaml-schema/constants.ts"() {
    booleanSchema = {
      "type": "boolean",
      "description": "be `true` or `false`",
      "completions": ["true", "false"],
      "exhaustiveCompletions": true
    };
    numberSchema = {
      "type": "number",
      "description": "be a number"
    };
    stringSchema = {
      "type": "string",
      "description": "be a string"
    };
    nullSchema = {
      "type": "null",
      "description": "be the null value",
      "completions": ["null"],
      "exhaustiveCompletions": true
    };
  }
});

// core/lib/yaml-schema/types.ts
function schemaType(schema4) {
  if (schema4 === false) {
    return "false";
  }
  if (schema4 === true) {
    return "true";
  }
  return schema4.type;
}
function schemaDispatch(s5, d4) {
  const st = schemaType(s5);
  if (d4[st]) {
    d4[st](s5);
  }
}
function schemaCall(s5, d4, other) {
  const st = schemaType(s5);
  if (d4[st]) {
    return d4[st](s5);
  }
  if (other) {
    return other(s5);
  }
  throw new Error(`Internal Error: Dispatch failed for type ${st}`);
}
function schemaDocString(d4) {
  if (typeof d4 === "string") {
    return d4;
  }
  if (d4.short) {
    return d4.short;
  }
  return "";
}
function schemaDescription(schema4) {
  if (schema4 === true) {
    return `be anything`;
  } else if (schema4 === false) {
    return `be no possible value`;
  } else {
    return schema4.description || `be ${schemaType(schema4)}`;
  }
}
var init_types2 = __esm({
  "core/lib/yaml-schema/types.ts"() {
  }
});

// core/lib/yaml-schema/common.ts
function internalId() {
  return {
    _internalId: ++globalInternalIdCounter
  };
}
function tagSchema(schema4, tags) {
  return {
    ...schema4,
    tags: {
      ...schema4.tags || {},
      ...tags
    }
  };
}
function anySchema(description) {
  return {
    ...internalId(),
    description,
    "type": "any"
  };
}
function enumSchema(...args) {
  if (args.length === 0) {
    throw new InternalError("Empty enum schema not supported.");
  }
  return {
    ...internalId(),
    "type": "enum",
    "enum": args,
    "description": args.length > 1 ? `be one of: ${args.map((x3) => "`" + x3 + "`").join(", ")}` : `be '${args[0]}'`,
    "completions": args.map(String),
    "exhaustiveCompletions": true
  };
}
function regexSchema(arg, description) {
  const result2 = {
    ...internalId(),
    "type": "string",
    "pattern": arg
  };
  if (description) {
    result2.description = description;
  } else {
    result2.description = `be a string that satisfies regex "${arg}"`;
  }
  return result2;
}
function anyOfSchema(...args) {
  return {
    ...internalId(),
    "type": "anyOf",
    "anyOf": args,
    "description": `be at least one of: ${args.map((x3) => schemaDescription(x3).slice(3)).join(", ")}`
  };
}
function allOfSchema(...args) {
  return {
    ...internalId(),
    "type": "allOf",
    "allOf": args,
    "description": `be all of: ${args.map((x3) => schemaDescription(x3).slice(3)).join(", ")}`
  };
}
function objectSchema(params = {}) {
  let {
    properties,
    patternProperties,
    required,
    additionalProperties,
    description,
    baseSchema,
    exhaustive,
    completions: completionsParam,
    namingConvention,
    propertyNames: propertyNamesSchema,
    closed
  } = params;
  required = required || [];
  properties = properties || {};
  patternProperties = patternProperties || {};
  let tags = {};
  let tagsAreSet = false;
  let propertyNames = propertyNamesSchema;
  if (completionsParam) {
    tags["completions"] = completionsParam;
    tagsAreSet = true;
  }
  const createCaseConventionSchema = (props) => {
    if (namingConvention === "ignore") {
      return void 0;
    }
    const objectKeys = Object.getOwnPropertyNames(
      props
    );
    const { pattern, list } = resolveCaseConventionRegex(
      objectKeys,
      namingConvention
    );
    if (pattern === void 0) {
      return void 0;
    }
    if (propertyNames !== void 0) {
      console.error(
        "Warning: propertyNames and case convention detection are mutually exclusive."
      );
      console.error(
        "Add `namingConvention: 'ignore'` to your schema definition to remove this warning."
      );
      return void 0;
    }
    const tags2 = {
      "case-convention": list,
      "error-importance": -5,
      "case-detection": true
    };
    return {
      errorMessage: `property \${value} does not match case convention ${objectKeys.join(",")}`,
      "type": "string",
      pattern,
      tags: tags2
    };
  };
  const hasDescription = description !== void 0;
  description = description || "be an object";
  let result2 = void 0;
  if (baseSchema) {
    if (!Array.isArray(baseSchema)) {
      baseSchema = [baseSchema];
    }
    if (baseSchema.some((s5) => s5.type !== "object")) {
      throw new InternalError("Attempted to extend a non-object schema");
    }
    if (baseSchema.length <= 0) {
      throw new InternalError("base schema cannot be empty list");
    }
    let temp = {
      ...internalId()
    };
    for (const base3 of baseSchema) {
      temp = Object.assign(temp, base3);
    }
    result2 = temp;
    if (result2 === void 0) {
      throw new UnreachableError();
    }
    if (result2.$id) {
      delete result2.$id;
    }
    for (const base3 of baseSchema) {
      if (base3.exhaustiveCompletions) {
        result2.exhaustiveCompletions = true;
      }
    }
    if (hasDescription) {
      result2.description = description;
    }
    const m4 = /* @__PURE__ */ new Map();
    for (const base3 of baseSchema) {
      for (const [k3, v4] of Object.entries(base3.properties || {})) {
        if (!m4.has(k3)) {
          m4.set(k3, []);
        }
        m4.get(k3).push([v4, base3.$id]);
      }
    }
    const errorMsgs = /* @__PURE__ */ new Set();
    for (const [k3, l6] of m4) {
      if (l6.length > 1) {
        errorMsgs.add(
          `Internal Error: base schemas ${l6.map((x3) => x3[1]).join(", ")} share property ${k3}.`
        );
      }
    }
    if (errorMsgs.size > 0) {
      console.error(
        [...errorMsgs].toSorted((a5, b3) => a5.localeCompare(b3)).join("\n")
      );
      console.error("This is a bug in quarto's schemas.");
      console.error(
        "Note that we don't throw in order to allow build-artifacts to finish, but the generated schemas will be invalid."
      );
    }
    result2.properties = Object.assign(
      {},
      ...baseSchema.map((s5) => s5.properties),
      properties
    );
    result2.patternProperties = Object.assign(
      {},
      ...baseSchema.map((s5) => s5.patternProperties).filter(
        (s5) => s5 !== void 0
      ),
      patternProperties
    );
    result2.required = [
      ...baseSchema.map((s5) => s5.required || []),
      required || []
    ].flat();
    if (result2.required && result2.required.length === 0) {
      result2.required = void 0;
    }
    const additionalPropArray = baseSchema.map((s5) => s5.additionalProperties).filter((s5) => s5 !== void 0);
    if (additionalProperties) {
      additionalPropArray.push(additionalProperties);
    }
    if (additionalPropArray.length) {
      result2.additionalProperties = allOfSchema(...additionalPropArray);
    }
    const propNamesArray = baseSchema.map((s5) => s5.propertyNames).filter((s5) => {
      if (typeof s5 !== "object") return true;
      if (s5.tags === void 0) return true;
      if (s5.tags["case-detection"] === true) {
        return false;
      }
      return true;
    }).filter((s5) => s5 !== void 0);
    if (propNamesArray.length === 1) {
      result2.propertyNames = propNamesArray[0];
    } else if (propNamesArray.length > 1) {
      result2.propertyNames = anyOfSchema(...propNamesArray);
    } else {
      delete result2.propertyNames;
    }
    result2.closed = closed || baseSchema.some((s5) => s5.closed);
  } else {
    const caseConventionSchema = createCaseConventionSchema(properties);
    if (caseConventionSchema !== void 0) {
      propertyNames = caseConventionSchema;
      tags = {
        ...tags,
        ...caseConventionSchema.tags
      };
      tagsAreSet = true;
    }
    result2 = {
      ...internalId(),
      "type": "object",
      description
    };
    if (exhaustive) {
      result2.exhaustiveCompletions = true;
    }
    if (properties) {
      result2.properties = properties;
    }
    if (patternProperties) {
      result2.patternProperties = patternProperties;
    }
    if (required && required.length > 0) {
      result2.required = required;
    }
    result2.closed = closed;
    if (additionalProperties !== void 0) {
      result2.additionalProperties = additionalProperties;
    }
    if (propertyNames !== void 0) {
      result2.propertyNames = propertyNames;
    }
  }
  if (tagsAreSet) {
    result2.tags = tags;
  }
  return result2;
}
function arraySchema(items) {
  if (items) {
    return {
      ...internalId(),
      "type": "array",
      "description": `be an array of values, where each element must ${schemaDescription(items)}`,
      items
    };
  } else {
    return {
      ...internalId(),
      "type": "array",
      "description": `be an array of values`
    };
  }
}
function documentSchema(schema4, doc) {
  const result2 = Object.assign({}, schema4);
  result2.documentation = doc;
  return result2;
}
function describeSchema(schema4, description) {
  const result2 = Object.assign({}, schema4);
  result2.description = `be ${description}`;
  return result2;
}
function completeSchema(schema4, ...completions) {
  const result2 = Object.assign({}, schema4);
  const prevCompletions = (schema4.completions || []).slice();
  prevCompletions.push(...completions);
  result2.completions = prevCompletions;
  return result2;
}
function completeSchemaOverwrite(schema4, ...completions) {
  const result2 = Object.assign({}, schema4);
  result2.completions = completions;
  return result2;
}
function idSchema(schema4, id) {
  const result2 = Object.assign({}, schema4);
  result2["$id"] = id;
  return result2;
}
function errorMessageSchema(schema4, errorMessage) {
  return {
    ...schema4,
    errorMessage
  };
}
function refSchema($ref, description) {
  return {
    ...internalId(),
    "type": "ref",
    $ref,
    description
  };
}
function valueSchema(val, description) {
  return {
    ...internalId(),
    "type": "enum",
    "enum": [val],
    // enum takes non-strings too (!)
    "description": description || `be ${JSON.stringify(val)}`
  };
}
var globalInternalIdCounter;
var init_common4 = __esm({
  "core/lib/yaml-schema/common.ts"() {
    init_error2();
    init_text();
    init_types2();
    globalInternalIdCounter = 0;
  }
});

// core/lib/yaml-validation/schema.ts
function hasSchemaDefinition(key) {
  return definitionsObject[key] !== void 0;
}
function getSchemaDefinition(key) {
  if (definitionsObject[key] === void 0) {
    throw new InternalError(`Schema ${key} not found.`);
  }
  return definitionsObject[key];
}
function setSchemaDefinition(schema4) {
  if (schema4.$id === void 0) {
    throw new InternalError(
      "setSchemaDefinition needs $id"
    );
  }
  if (definitionsObject[schema4.$id] === void 0) {
    definitionsObject[schema4.$id] = schema4;
  }
}
function getSchemaDefinitionsObject() {
  return Object.assign({}, definitionsObject);
}
function expandAliasesFrom(lst, defs) {
  const aliases = defs;
  const result2 = [];
  lst = lst.slice();
  for (let i6 = 0; i6 < lst.length; ++i6) {
    const el = lst[i6];
    if (el.startsWith("$")) {
      const v4 = aliases[el.slice(1)];
      if (v4 === void 0) {
        throw new InternalError(
          `${el} doesn't have an entry in the aliases map`
        );
      }
      lst.push(...v4);
    } else {
      result2.push(el);
    }
  }
  return result2;
}
var definitionsObject;
var init_schema = __esm({
  "core/lib/yaml-validation/schema.ts"() {
    init_error2();
    init_types2();
    definitionsObject = {};
  }
});

// core/lib/yaml-validation/resolve.ts
function resolveSchema(schema4, visit, hasRef, next) {
  if (schema4 === false || schema4 === true) {
    return schema4;
  }
  if (hasRef === void 0) {
    hasRef = (cursor) => {
      return schemaCall(cursor, {
        ref: (_s) => true
      }, (_s) => false);
    };
  }
  if (!hasRef(schema4)) {
    return schema4;
  }
  if (visit === void 0) {
    visit = (_schema) => {
    };
  }
  if (next === void 0) {
    next = (cursor) => {
      const result2 = schemaCall(cursor, {
        ref: (s5) => getSchemaDefinition(s5.$ref)
      });
      if (result2 === void 0) {
        throw new InternalError(
          "couldn't resolve schema ${JSON.stringify(cursor)}"
        );
      }
      return result2;
    };
  }
  let cursor1 = schema4;
  let cursor2 = schema4;
  let stopped = false;
  do {
    cursor1 = next(cursor1);
    visit(cursor1);
    if (hasRef(cursor2)) {
      cursor2 = next(cursor2);
    } else {
      stopped = true;
    }
    if (hasRef(cursor2)) {
      cursor2 = next(cursor2);
    } else {
      stopped = true;
    }
    if (!stopped && cursor1 === cursor2) {
      throw new Error(`reference cycle detected at ${JSON.stringify(cursor1)}`);
    }
  } while (hasRef(cursor1));
  return cursor1;
}
var init_resolve4 = __esm({
  "core/lib/yaml-validation/resolve.ts"() {
    init_schema();
    init_types2();
    init_error2();
  }
});

// core/lib/ranged-text.ts
function matchAll2(str3, regex) {
  let match;
  regex = new RegExp(regex);
  const result2 = [];
  while ((match = regex.exec(str3)) != null) {
    result2.push(match);
  }
  return result2;
}
function rangedLines(text, includeNewLines = false) {
  const regex = /\r\n?|\n/g;
  const result2 = [];
  let startOffset = 0;
  if (!includeNewLines) {
    for (const r5 of matchAll2(text, regex)) {
      result2.push({
        substring: text.substring(startOffset, r5.index),
        range: {
          start: startOffset,
          end: r5.index
        }
      });
      startOffset = r5.index + r5[0].length;
    }
    result2.push({
      substring: text.substring(startOffset, text.length),
      range: {
        start: startOffset,
        end: text.length
      }
    });
    return result2;
  } else {
    const matches = matchAll2(text, regex);
    let prevOffset = 0;
    for (const r5 of matches) {
      const stringEnd = r5.index + r5[0].length;
      result2.push({
        substring: text.substring(prevOffset, stringEnd),
        range: {
          start: prevOffset,
          end: stringEnd
        }
      });
      prevOffset = stringEnd;
    }
    result2.push({
      substring: text.substring(prevOffset, text.length),
      range: {
        start: prevOffset,
        end: text.length
      }
    });
    return result2;
  }
}
var init_ranged_text = __esm({
  "core/lib/ranged-text.ts"() {
  }
});

// core/lib/mapped-text.ts
function mappedSubstring(source2, start, end) {
  if (typeof source2 === "string") {
    source2 = asMappedString(source2);
  }
  const value = source2.value.substring(start, end);
  const mappedSource2 = source2;
  return {
    value,
    fileName: mappedSource2.fileName,
    map: (index2, closest2) => {
      if (closest2) {
        index2 = Math.max(0, Math.min(value.length, index2 - 1));
      }
      if (index2 === 0 && index2 === value.length) {
        return mappedSource2.map(index2 + start, closest2);
      }
      if (index2 < 0 || index2 >= value.length) {
        return void 0;
      }
      return mappedSource2.map(index2 + start, closest2);
    }
  };
}
function mappedString(source2, pieces, fileName) {
  if (typeof source2 === "string") {
    source2 = asMappedString(source2, fileName);
  }
  const mappedPieces = pieces.map((piece) => {
    if (typeof piece === "string") {
      return asMappedString(piece);
    } else if (piece.value !== void 0) {
      return piece;
    } else {
      const { start, end } = piece;
      return mappedSubstring(source2, start, end);
    }
  });
  return mappedConcat(mappedPieces);
}
function asMappedString(str3, fileName) {
  if (typeof str3 === "string") {
    return {
      value: str3,
      fileName,
      map: function(index2, closest2) {
        if (closest2) {
          index2 = Math.min(str3.length - 1, Math.max(0, index2));
        }
        if (index2 < 0 || index2 >= str3.length) {
          return void 0;
        }
        return {
          index: index2,
          originalString: this
        };
      }
    };
  } else if (fileName !== void 0) {
    throw new InternalError(
      "can't change the fileName of an existing MappedString"
    );
  } else {
    return str3;
  }
}
function mappedConcat(strings3) {
  if (strings3.length === 0) {
    return {
      value: "",
      map: (_index, _closest) => void 0
    };
  }
  if (strings3.every((s5) => typeof s5 === "string")) {
    return asMappedString(strings3.join(""));
  }
  const mappedStrings = strings3.map((s5) => {
    if (typeof s5 === "string") {
      return asMappedString(s5);
    } else return s5;
  });
  let currentOffset = 0;
  const offsets = [0];
  for (const s5 of mappedStrings) {
    currentOffset += s5.value.length;
    offsets.push(currentOffset);
  }
  const value = mappedStrings.map((s5) => s5.value).join("");
  return {
    value,
    map: (offset3, closest2) => {
      if (closest2) {
        offset3 = Math.max(0, Math.min(offset3, value.length - 1));
      }
      if (offset3 === 0 && offset3 == value.length && mappedStrings.length) {
        return mappedStrings[0].map(0, closest2);
      }
      if (offset3 < 0 || offset3 >= value.length) {
        return void 0;
      }
      const ix = glb(offsets, offset3);
      const v4 = mappedStrings[ix];
      return v4.map(offset3 - offsets[ix]);
    }
  };
}
function mappedIndexToLineCol(eitherText) {
  const text = asMappedString(eitherText);
  return function(offset3) {
    const mapResult = text.map(offset3, true);
    if (mapResult === void 0) {
      throw new InternalError("bad offset in mappedIndexRowCol");
    }
    const { index: index2, originalString } = mapResult;
    return indexToLineCol(originalString.value)(index2);
  };
}
function mappedNormalizeNewlines(eitherText) {
  const text = asMappedString(eitherText);
  let start = 0;
  const chunks = [];
  for (const offset3 of lineBreakPositions(text.value)) {
    if (text.value[offset3] !== "\r") {
      continue;
    }
    chunks.push({ start, end: offset3 });
    chunks.push({ start: offset3 + 1, end: offset3 + 2 });
    start = offset3 + 2;
  }
  if (start !== text.value.length) {
    chunks.push({ start, end: text.value.length });
  }
  return mappedString(text, chunks);
}
function join5(mappedStrs, sep6) {
  const innerStrings = [];
  const mappedSep = asMappedString(sep6);
  for (let i6 = 0; i6 < mappedStrs.length; ++i6) {
    const mappedStr = mappedStrs[i6];
    if (typeof mappedStr === "string") {
      innerStrings.push(asMappedString(mappedStr));
    } else {
      innerStrings.push(mappedStr);
    }
    if (i6 < mappedStrs.length) {
      innerStrings.push(mappedSep);
    }
  }
  return mappedConcat(innerStrings);
}
function mappedLines(str3, keepNewLines = false) {
  const lines2 = rangedLines(str3.value, keepNewLines);
  return lines2.map((v4) => mappedString(str3, [v4.range]));
}
function findSpaceStart(string2) {
  const result2 = string2.value.match(/^\s+/);
  if (result2 === null || result2.length === 0) {
    return 0;
  }
  return result2[0].length;
}
function findSpaceEnd(string2) {
  const result2 = string2.value.match(/\s+$/);
  if (result2 === null || result2.length === 0) {
    return 0;
  }
  return result2[0].length;
}
function mappedTrim(string2) {
  const start = findSpaceStart(string2);
  const end = findSpaceEnd(string2);
  if (start === 0 && end === 0) {
    return string2;
  }
  if (start > string2.value.length - end) {
    return mappedSubstring(string2, 0, 0);
  }
  return mappedSubstring(string2, start, string2.value.length - end);
}
var init_mapped_text = __esm({
  "core/lib/mapped-text.ts"() {
    init_binary_search();
    init_ranged_text();
    init_text();
    init_error2();
  }
});

// core/lib/external/regexpp.mjs
var DataSet, gcValueSets, scValueSets, binPropertySets;
var init_regexpp = __esm({
  "core/lib/external/regexpp.mjs"() {
    DataSet = class {
      constructor(raw2018, raw2019, raw2020, raw2021) {
        this._raw2018 = raw2018;
        this._raw2019 = raw2019;
        this._raw2020 = raw2020;
        this._raw2021 = raw2021;
      }
      get es2018() {
        return this._set2018 || (this._set2018 = new Set(this._raw2018.split(" ")));
      }
      get es2019() {
        return this._set2019 || (this._set2019 = new Set(this._raw2019.split(" ")));
      }
      get es2020() {
        return this._set2020 || (this._set2020 = new Set(this._raw2020.split(" ")));
      }
      get es2021() {
        return this._set2021 || (this._set2021 = new Set(this._raw2021.split(" ")));
      }
    };
    gcValueSets = new DataSet("C Cased_Letter Cc Cf Close_Punctuation Cn Co Combining_Mark Connector_Punctuation Control Cs Currency_Symbol Dash_Punctuation Decimal_Number Enclosing_Mark Final_Punctuation Format Initial_Punctuation L LC Letter Letter_Number Line_Separator Ll Lm Lo Lowercase_Letter Lt Lu M Mark Math_Symbol Mc Me Mn Modifier_Letter Modifier_Symbol N Nd Nl No Nonspacing_Mark Number Open_Punctuation Other Other_Letter Other_Number Other_Punctuation Other_Symbol P Paragraph_Separator Pc Pd Pe Pf Pi Po Private_Use Ps Punctuation S Sc Separator Sk Sm So Space_Separator Spacing_Mark Surrogate Symbol Titlecase_Letter Unassigned Uppercase_Letter Z Zl Zp Zs cntrl digit punct", "", "", "");
    scValueSets = new DataSet("Adlam Adlm Aghb Ahom Anatolian_Hieroglyphs Arab Arabic Armenian Armi Armn Avestan Avst Bali Balinese Bamu Bamum Bass Bassa_Vah Batak Batk Beng Bengali Bhaiksuki Bhks Bopo Bopomofo Brah Brahmi Brai Braille Bugi Buginese Buhd Buhid Cakm Canadian_Aboriginal Cans Cari Carian Caucasian_Albanian Chakma Cham Cher Cherokee Common Copt Coptic Cprt Cuneiform Cypriot Cyrillic Cyrl Deseret Deva Devanagari Dsrt Dupl Duployan Egyp Egyptian_Hieroglyphs Elba Elbasan Ethi Ethiopic Geor Georgian Glag Glagolitic Gonm Goth Gothic Gran Grantha Greek Grek Gujarati Gujr Gurmukhi Guru Han Hang Hangul Hani Hano Hanunoo Hatr Hatran Hebr Hebrew Hira Hiragana Hluw Hmng Hung Imperial_Aramaic Inherited Inscriptional_Pahlavi Inscriptional_Parthian Ital Java Javanese Kaithi Kali Kana Kannada Katakana Kayah_Li Khar Kharoshthi Khmer Khmr Khoj Khojki Khudawadi Knda Kthi Lana Lao Laoo Latin Latn Lepc Lepcha Limb Limbu Lina Linb Linear_A Linear_B Lisu Lyci Lycian Lydi Lydian Mahajani Mahj Malayalam Mand Mandaic Mani Manichaean Marc Marchen Masaram_Gondi Meetei_Mayek Mend Mende_Kikakui Merc Mero Meroitic_Cursive Meroitic_Hieroglyphs Miao Mlym Modi Mong Mongolian Mro Mroo Mtei Mult Multani Myanmar Mymr Nabataean Narb Nbat New_Tai_Lue Newa Nko Nkoo Nshu Nushu Ogam Ogham Ol_Chiki Olck Old_Hungarian Old_Italic Old_North_Arabian Old_Permic Old_Persian Old_South_Arabian Old_Turkic Oriya Orkh Orya Osage Osge Osma Osmanya Pahawh_Hmong Palm Palmyrene Pau_Cin_Hau Pauc Perm Phag Phags_Pa Phli Phlp Phnx Phoenician Plrd Prti Psalter_Pahlavi Qaac Qaai Rejang Rjng Runic Runr Samaritan Samr Sarb Saur Saurashtra Sgnw Sharada Shavian Shaw Shrd Sidd Siddham SignWriting Sind Sinh Sinhala Sora Sora_Sompeng Soyo Soyombo Sund Sundanese Sylo Syloti_Nagri Syrc Syriac Tagalog Tagb Tagbanwa Tai_Le Tai_Tham Tai_Viet Takr Takri Tale Talu Tamil Taml Tang Tangut Tavt Telu Telugu Tfng Tglg Thaa Thaana Thai Tibetan Tibt Tifinagh Tirh Tirhuta Ugar Ugaritic Vai Vaii Wara Warang_Citi Xpeo Xsux Yi Yiii Zanabazar_Square Zanb Zinh Zyyy", "Dogr Dogra Gong Gunjala_Gondi Hanifi_Rohingya Maka Makasar Medefaidrin Medf Old_Sogdian Rohg Sogd Sogdian Sogo", "Elym Elymaic Hmnp Nand Nandinagari Nyiakeng_Puachue_Hmong Wancho Wcho", "Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi");
    binPropertySets = new DataSet("AHex ASCII ASCII_Hex_Digit Alpha Alphabetic Any Assigned Bidi_C Bidi_Control Bidi_M Bidi_Mirrored CI CWCF CWCM CWKCF CWL CWT CWU Case_Ignorable Cased Changes_When_Casefolded Changes_When_Casemapped Changes_When_Lowercased Changes_When_NFKC_Casefolded Changes_When_Titlecased Changes_When_Uppercased DI Dash Default_Ignorable_Code_Point Dep Deprecated Dia Diacritic Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Ext Extender Gr_Base Gr_Ext Grapheme_Base Grapheme_Extend Hex Hex_Digit IDC IDS IDSB IDST IDS_Binary_Operator IDS_Trinary_Operator ID_Continue ID_Start Ideo Ideographic Join_C Join_Control LOE Logical_Order_Exception Lower Lowercase Math NChar Noncharacter_Code_Point Pat_Syn Pat_WS Pattern_Syntax Pattern_White_Space QMark Quotation_Mark RI Radical Regional_Indicator SD STerm Sentence_Terminal Soft_Dotted Term Terminal_Punctuation UIdeo Unified_Ideograph Upper Uppercase VS Variation_Selector White_Space XIDC XIDS XID_Continue XID_Start space", "Extended_Pictographic", "", "EBase EComp EMod EPres ExtPict");
  }
});

// core/lib/regexp.js
var init_regexp = __esm({
  "core/lib/regexp.js"() {
    init_regexpp();
  }
});

// core/lib/yaml-validation/schema-navigation.ts
function navigateSchemaBySchemaPathSingle(schema4, path3) {
  const ensurePathFragment = (fragment, expected) => {
    if (fragment !== expected) {
      throw new InternalError(
        `navigateSchemaBySchemaPathSingle: ${fragment} !== ${expected}`
      );
    }
  };
  const inner = (subschema, index2) => {
    subschema = resolveSchema(subschema);
    if (subschema === void 0) {
      throw new InternalError(
        `navigateSchemaBySchemaPathSingle: invalid path navigation`
      );
    }
    if (index2 === path3.length) {
      return subschema;
    }
    const st = schemaType(subschema);
    switch (st) {
      case "anyOf":
        ensurePathFragment(path3[index2], "anyOf");
        return inner(subschema.anyOf[path3[index2 + 1]], index2 + 2);
      case "allOf":
        ensurePathFragment(path3[index2], "allOf");
        return inner(subschema.allOf[path3[index2 + 1]], index2 + 2);
      case "array":
        ensurePathFragment(path3[index2], "array");
        return inner(subschema.arrayOf.schema, index2 + 2);
      case "object":
        ensurePathFragment(path3[index2], "object");
        if (path3[index2 + 1] === "properties") {
          return inner(subschema.properties[path3[index2 + 2]], index2 + 3);
        } else if (path3[index2 + 1] === "patternProperties") {
          return inner(subschema.patternProperties[path3[index2 + 2]], index2 + 3);
        } else if (path3[index2 + 1] === "additionalProperties") {
          return inner(subschema.additionalProperties, index2 + 2);
        } else {
          throw new InternalError(
            `navigateSchemaBySchemaPathSingle: bad path fragment ${path3[index2]} in object navigation`
          );
        }
      default:
        throw new InternalError(
          `navigateSchemaBySchemaPathSingle: can't navigate schema type ${st}`
        );
    }
  };
  return inner(schema4, 0);
}
var init_schema_navigation = __esm({
  "core/lib/yaml-validation/schema-navigation.ts"() {
    init_resolve4();
    init_regexp();
    init_types2();
    init_error2();
  }
});

// core/lib/yaml-validation/schema-utils.ts
function resolveDescription(s5) {
  if (typeof s5 === "string") {
    return s5;
  }
  const valueS = resolveSchema(s5);
  if (valueS === false || valueS === true) {
    return "";
  }
  if (valueS.documentation === void 0) {
    return "";
  }
  if (typeof valueS.documentation === "string") {
    return valueS.documentation;
  }
  if (valueS.documentation.short) {
    return valueS.documentation.short;
  } else {
    return "";
  }
}
function schemaCompletions(s5) {
  if (s5 === true || s5 === false) {
    return [];
  }
  let schema4 = resolveSchema(s5);
  schema4 = resolveSchema(
    schema4,
    (_schema) => {
    },
    // visit
    (schema5) => {
      return schema5.tags !== void 0 && schema5.tags["complete-from"] !== void 0;
    },
    (schema5) => {
      return navigateSchemaBySchemaPathSingle(
        schema5,
        schema5.tags["complete-from"]
      );
    }
  );
  if (schema4 === true || schema4 === false) {
    return [];
  }
  const normalize14 = (completions) => {
    const result2 = (completions || []).map((c6) => {
      if (typeof c6 === "string") {
        return {
          type: "value",
          display: c6,
          value: c6,
          description: "",
          suggest_on_accept: false,
          schema: schema4
        };
      }
      return {
        ...c6,
        description: resolveDescription(c6.description),
        schema: schema4
      };
    });
    return result2;
  };
  if (schema4.completions && schema4.completions.length) {
    return normalize14(schema4.completions);
  }
  if (schema4.tags && schema4.tags.completions) {
    if (Array.isArray(schema4.tags.completions) && schema4.tags.completions.length) {
      return normalize14(schema4.tags.completions);
    } else {
      return normalize14(
        Object.values(schema4.tags.completions)
      );
    }
  }
  return schemaCall(schema4, {
    array: (s6) => {
      if (s6.items) {
        return schemaCompletions(s6.items);
      } else {
        return [];
      }
    },
    anyOf: (s6) => {
      return s6.anyOf.map(schemaCompletions).flat();
    },
    allOf: (s6) => {
      return s6.allOf.map(schemaCompletions).flat();
    },
    "object": (s6) => {
      s6.cachedCompletions = getObjectCompletions(s6);
      return normalize14(s6.cachedCompletions);
    }
  }, (_3) => []);
}
function getObjectCompletions(s5) {
  const completionsParam = s5.tags && s5.tags.completions || [];
  return schemaCall(s5, {
    "object": (schema4) => {
      const properties = schema4.properties;
      const objectKeys = completionsParam.length ? completionsParam : Object.getOwnPropertyNames(properties);
      const _uniqueValues = (lst) => {
        const obj = {};
        for (const c6 of lst) {
          obj[c6.value] = c6;
        }
        return Object.getOwnPropertyNames(obj).map((k3) => obj[k3]);
      };
      const completions = [];
      for (const k3 of objectKeys) {
        const schema5 = properties && properties[k3];
        const maybeDescriptions = [];
        let hidden2 = false;
        if (schema5 !== void 0 && schema5 !== true && schema5 !== false) {
          if (schema5.documentation) {
            maybeDescriptions.push(schemaDocString(schema5.documentation));
          } else {
            let described = false;
            const visitor = (schema6) => {
              if (schema6 === false || schema6 === true) {
                return;
              }
              if (schema6.hidden) {
                hidden2 = true;
              }
              if (described) {
                return;
              }
              if (schema6.documentation) {
                maybeDescriptions.push(schemaDocString(schema6.documentation));
                described = true;
              }
            };
            try {
              resolveSchema(schema5, visitor);
            } catch (_e) {
            }
            if (!described) {
              schemaDispatch(schema5, {
                ref: (schema6) => maybeDescriptions.push({ $ref: schema6.$ref })
              });
            }
          }
        }
        if (hidden2) {
          continue;
        }
        let description = "";
        for (const md of maybeDescriptions) {
          if (md !== void 0) {
            description = md;
            break;
          }
        }
        completions.push({
          type: "key",
          display: "",
          // attempt to not show completion title.
          value: `${k3}: `,
          description,
          suggest_on_accept: true
        });
      }
      return completions;
    }
  }, (_3) => completionsParam.map((c6) => ({
    type: "value",
    display: "",
    value: c6,
    description: "",
    suggest_on_accept: false
  })));
}
function possibleSchemaKeys(schema4) {
  const precomputedCompletions = schemaCompletions(schema4).filter(
    (c6) => c6.type === "key"
  ).map((c6) => c6.value.split(":")[0]);
  if (precomputedCompletions.length) {
    return precomputedCompletions;
  }
  const results = [];
  walkSchema(schema4, {
    "object": (s5) => {
      results.push(...Object.keys(s5.properties || {}));
      return true;
    },
    "array": (_s) => true
  });
  return results;
}
function possibleSchemaValues(schema4) {
  const results = [];
  walkSchema(schema4, {
    "enum": (s5) => {
      results.push(...s5["enum"].map(String));
      return true;
    },
    // don't recurse into anything that introduces instancePath values
    "array": (_s) => true,
    "object": (_s) => true
  });
  return results;
}
function walkSchema(schema4, f5) {
  const recur = {
    "anyOf": (ss) => {
      for (const s5 of ss.anyOf) {
        walkSchema(s5, f5);
      }
    },
    "allOf": (ss) => {
      for (const s5 of ss.allOf) {
        walkSchema(s5, f5);
      }
    },
    "array": (x3) => {
      if (x3.items) {
        walkSchema(x3.items, f5);
      }
    },
    "object": (x3) => {
      if (x3.properties) {
        for (const ss of Object.values(x3.properties)) {
          walkSchema(ss, f5);
        }
      }
      if (x3.patternProperties) {
        for (const ss of Object.values(x3.patternProperties)) {
          walkSchema(ss, f5);
        }
      }
      if (x3.propertyNames) {
        walkSchema(x3.propertyNames, f5);
      }
    }
  };
  if (typeof f5 === "function") {
    if (f5(schema4) === true) {
      return;
    }
  } else {
    if (schemaCall(schema4, f5, (_3) => false) === true) {
      return;
    }
  }
  schemaCall(schema4, recur, (_3) => false);
}
var init_schema_utils = __esm({
  "core/lib/yaml-validation/schema-utils.ts"() {
    init_schema_navigation();
    init_types2();
    init_resolve4();
  }
});

// core/lib/yaml-validation/errors.ts
function setDefaultErrorHandlers(validator) {
  validator.addHandler(ignoreExprViolations);
  validator.addHandler(expandEmptySpan);
  validator.addHandler(improveErrorHeadingForValueErrors);
  validator.addHandler(checkForTypeMismatch);
  validator.addHandler(checkForBadBoolean);
  validator.addHandler(checkForBadColon);
  validator.addHandler(checkForBadEquals);
  validator.addHandler(identifyKeyErrors);
  validator.addHandler(checkForNearbyCorrection);
  validator.addHandler(checkForNearbyRequired);
  validator.addHandler(schemaDefinedErrors);
}
function errorKeyword(error2) {
  if (error2.schemaPath.length === 0) {
    return "";
  }
  return String(error2.schemaPath[error2.schemaPath.length - 1]);
}
function schemaPathMatches(error2, strs) {
  const schemaPath = error2.schemaPath.slice(-strs.length);
  if (schemaPath.length !== strs.length) {
    return false;
  }
  return strs.every((str3, i6) => str3 === schemaPath[i6]);
}
function getBadKey(error2) {
  if (error2.schemaPath.indexOf("propertyNames") === -1 && error2.schemaPath.indexOf("closed") === -1) {
    return void 0;
  }
  const result2 = error2.violatingObject.result;
  if (typeof result2 !== "string") {
    throw new InternalError(
      "propertyNames error has a violating non-string."
    );
  }
  return result2;
}
function getVerbatimInput(error2) {
  return error2.source.value;
}
function navigate(path3, annotation, returnKey = false, pathIndex = 0) {
  if (annotation === void 0) {
    throw new Error("Can't navigate an undefined annotation");
  }
  if (pathIndex >= path3.length) {
    return annotation;
  }
  if (annotation.kind === "mapping" || annotation.kind === "block_mapping") {
    const { components } = annotation;
    const searchKey = path3[pathIndex];
    const lastKeyIndex = ~~((components.length - 1) / 2) * 2;
    for (let i6 = lastKeyIndex; i6 >= 0; i6 -= 2) {
      const key = components[i6].result;
      if (key === searchKey) {
        if (returnKey && pathIndex === path3.length - 1) {
          return navigate(path3, components[i6], returnKey, pathIndex + 1);
        } else {
          return navigate(path3, components[i6 + 1], returnKey, pathIndex + 1);
        }
      }
    }
    return annotation;
  } else if (["sequence", "block_sequence", "flow_sequence"].indexOf(annotation.kind) !== -1) {
    const searchKey = Number(path3[pathIndex]);
    if (isNaN(searchKey) || searchKey < 0 || searchKey >= annotation.components.length) {
      return annotation;
    }
    return navigate(
      path3,
      annotation.components[searchKey],
      returnKey,
      pathIndex + 1
    );
  } else {
    return annotation;
  }
}
function isEmptyValue(error2) {
  const rawVerbatimInput = getVerbatimInput(error2);
  return rawVerbatimInput.trim().length === 0;
}
function getLastFragment(instancePath) {
  if (instancePath.length === 0) {
    return void 0;
  }
  return instancePath[instancePath.length - 1];
}
function reindent(str3) {
  const s5 = /* @__PURE__ */ new Set();
  const ls = lines(str3);
  for (const l6 of ls) {
    const r5 = l6.match("^[ ]+");
    if (r5) {
      s5.add(r5[0].length);
    }
  }
  if (s5.size === 0) {
    return str3;
  } else if (s5.size === 1) {
    const v4 = Array.from(s5)[0];
    const oldIndent = " ".repeat(v4);
    if (v4 <= 2) {
      return str3;
    }
    return ls.map((l6) => l6.startsWith(oldIndent) ? l6.slice(v4 - 2) : l6).join(
      "\n"
    );
  } else {
    const [first, second] = Array.from(s5);
    const oldIndent = " ".repeat(first);
    const newIndent = second - first;
    if (newIndent >= first) {
      return str3;
    }
    return ls.map(
      (l6) => l6.startsWith(oldIndent) ? l6.slice(first - newIndent) : l6
    ).join("\n");
  }
}
function ignoreExprViolations(error2, _parse, _schema) {
  const { result: result2 } = error2.violatingObject;
  if (typeof result2 !== "object" || Array.isArray(result2) || result2 === null || error2.schemaPath.slice(-1)[0] !== "type") {
    return error2;
  }
  if (result2.tag === "!expr" && typeof result2.value === "string") {
    return null;
  } else {
    return error2;
  }
}
function formatHeadingForKeyError(_error, _parse, _schema, key) {
  return `property name ${blue4(key)} is invalid`;
}
function formatHeadingForValueError(error2, _parse, _schema) {
  const rawVerbatimInput = reindent(getVerbatimInput(error2));
  const rawLines = lines(rawVerbatimInput);
  let verbatimInput;
  if (rawLines.length > 4) {
    verbatimInput = quotedStringColor(
      [...rawLines.slice(0, 2), "...", ...rawLines.slice(-2)].join("\n")
    );
  } else {
    verbatimInput = quotedStringColor(rawVerbatimInput);
  }
  const empty3 = isEmptyValue(error2);
  const lastFragment = getLastFragment(error2.instancePath);
  switch (typeof lastFragment) {
    case "undefined":
      if (empty3) {
        return "YAML value is missing.";
      } else {
        return `YAML value ${verbatimInput} must ${schemaDescription(error2.schema)}.`;
      }
    case "number":
      if (empty3) {
        return `Array entry ${lastFragment + 1} is empty but it must instead ${schemaDescription(error2.schema)}.`;
      } else {
        return `Array entry ${lastFragment + 1} with value ${verbatimInput} failed to ${schemaDescription(error2.schema)}.`;
      }
    case "string": {
      const formatLastFragment = '"' + blue4(lastFragment) + '"';
      if (empty3) {
        return `Field ${formatLastFragment} has empty value but it must instead ${schemaDescription(error2.schema)}`;
      } else {
        if (verbatimInput.indexOf("\n") !== -1) {
          return `Field ${formatLastFragment} has value

${verbatimInput}

The value must instead ${schemaDescription(error2.schema)}.`;
        } else {
          return `Field ${formatLastFragment} has value ${verbatimInput}, which must instead ${schemaDescription(error2.schema)}`;
        }
      }
    }
  }
}
function identifyKeyErrors(error2, parse24, schema4) {
  if (error2.schemaPath.indexOf("propertyNames") === -1 && error2.schemaPath.indexOf("closed") === -1) {
    return error2;
  }
  const badKey = getBadKey(error2);
  if (badKey) {
    if (error2.instancePath.length && error2.instancePath[error2.instancePath.length - 1] !== badKey) {
      addInstancePathInfo(
        error2.niceError,
        [...error2.instancePath, badKey]
      );
    } else {
      addInstancePathInfo(
        error2.niceError,
        error2.instancePath
      );
    }
    error2.niceError.heading = formatHeadingForKeyError(
      error2,
      parse24,
      schema4,
      badKey
    );
  }
  return error2;
}
function improveErrorHeadingForValueErrors(error2, parse24, schema4) {
  if (error2.schemaPath.indexOf("propertyNames") !== -1 || error2.schemaPath.indexOf("closed") !== -1 || errorKeyword(error2) === "required") {
    return error2;
  }
  return {
    ...error2,
    niceError: {
      ...error2.niceError,
      heading: formatHeadingForValueError(error2, parse24, schema4)
    }
  };
}
function expandEmptySpan(error2, parse24, _schema) {
  if (error2.location.start.line !== error2.location.end.line || error2.location.start.column !== error2.location.end.column || !isEmptyValue(error2) || typeof getLastFragment(error2.instancePath) === "undefined") {
    return error2;
  }
  const lastKey = navigate(
    error2.instancePath,
    parse24,
    true
  );
  const locF = mappedIndexToLineCol(parse24.source);
  try {
    const location = {
      start: locF(lastKey.start),
      end: locF(lastKey.end)
    };
    return {
      ...error2,
      location,
      niceError: {
        ...error2.niceError,
        location
      }
    };
  } catch (_e) {
    return error2;
  }
}
function checkForTypeMismatch(error2, parse24, schema4) {
  const rawVerbatimInput = getVerbatimInput(error2);
  const rawLines = lines(rawVerbatimInput);
  let verbatimInput;
  if (rawLines.length > 4) {
    verbatimInput = quotedStringColor(
      [...rawLines.slice(0, 2), "...", ...rawLines.slice(-2)].join("\n")
    );
  } else {
    verbatimInput = quotedStringColor(rawVerbatimInput);
  }
  const goodType = (obj) => {
    if (Array.isArray(obj)) {
      return "an array";
    }
    if (obj === null) {
      return "a null value";
    }
    return typeof obj;
  };
  if (errorKeyword(error2) === "type" && rawVerbatimInput.length > 0) {
    const reindented = reindent(verbatimInput);
    const subject = reindented.indexOf("\n") === -1 ? `The value ${reindented} ` : `The value

${reindented}

`;
    const newError = {
      ...error2.niceError,
      heading: formatHeadingForValueError(
        error2,
        parse24,
        schema4
      ),
      error: [
        `${subject}is of type ${goodType(
          error2.violatingObject.result
        )}.`
      ],
      info: {},
      location: error2.niceError.location
    };
    addInstancePathInfo(newError, error2.instancePath);
    addFileInfo(newError, error2.source);
    return {
      ...error2,
      niceError: newError
    };
  }
  return error2;
}
function checkForBadBoolean(error2, parse24, _schema) {
  const schema4 = error2.schema;
  if (!(typeof error2.violatingObject.result === "string" && errorKeyword(error2) === "type" && schemaType(schema4) === "boolean")) {
    return error2;
  }
  const strValue = error2.violatingObject.result;
  const verbatimInput = quotedStringColor(getVerbatimInput(error2));
  const yesses = new Set("y|Y|yes|Yes|YES|true|True|TRUE|on|On|ON".split("|"));
  const nos = new Set("n|N|no|No|NO|false|False|FALSE|off|Off|OFF".split("|"));
  let fix;
  if (yesses.has(strValue)) {
    fix = true;
  } else if (nos.has(strValue)) {
    fix = false;
  } else {
    return error2;
  }
  const errorMessage = `The value ${verbatimInput} is a string.`;
  const suggestion1 = `Quarto uses YAML 1.2, which interprets booleans strictly.`;
  const suggestion2 = `Try using ${quotedStringColor(String(fix))} instead.`;
  const newError = {
    heading: formatHeadingForValueError(error2, parse24, schema4),
    error: [errorMessage],
    info: {},
    location: error2.niceError.location
  };
  addInstancePathInfo(newError, error2.instancePath);
  addFileInfo(newError, error2.source);
  newError.info["yaml-version-1.2"] = suggestion1;
  newError.info["suggestion-fix"] = suggestion2;
  return {
    ...error2,
    niceError: newError
  };
}
function checkForBadColon(error2, parse24, schema4) {
  if (typeof error2.violatingObject.result !== "string") {
    return error2;
  }
  if (!schemaPathMatches(error2, ["object", "type"])) {
    return error2;
  }
  if (!error2.violatingObject.result.match(/^.+:[^ ].*$/)) {
    return error2;
  }
  const verbatimInput = quotedStringColor(getVerbatimInput(error2));
  const errorMessage = `The value ${verbatimInput} is a string.`;
  const suggestion1 = `In YAML, key-value pairs in objects must be separated by a space.`;
  const suggestion2 = `Did you mean ${quotedStringColor(
    quotedStringColor(getVerbatimInput(error2)).replace(/:/g, ": ")
  )} instead?`;
  const newError = {
    heading: formatHeadingForValueError(error2, parse24, schema4),
    error: [errorMessage],
    info: {},
    location: error2.niceError.location
  };
  addInstancePathInfo(newError, error2.instancePath);
  addFileInfo(newError, error2.source);
  newError.info["yaml-key-value-pairs"] = suggestion1;
  newError.info["suggestion-fix"] = suggestion2;
  return {
    ...error2,
    niceError: newError
  };
}
function checkForBadEquals(error2, parse24, schema4) {
  if (typeof error2.violatingObject.result !== "string") {
    return error2;
  }
  if (!schemaPathMatches(error2, ["object", "type"]) && !schemaPathMatches(error2, ["object", "propertyNames", "string", "pattern"])) {
    return error2;
  }
  if (!error2.violatingObject.result.match(/^.+ *= *.+$/)) {
    return error2;
  }
  const verbatimInput = quotedStringColor(getVerbatimInput(error2));
  const errorMessage = `The value ${verbatimInput} is a string.`;
  const suggestion1 = `In YAML, key-value pairs in objects must be separated by a colon and a space.`;
  const suggestion2 = `Did you mean ${quotedStringColor(
    quotedStringColor(getVerbatimInput(error2)).replace(/ *= */g, ": ")
  )} instead?`;
  const newError = {
    heading: formatHeadingForValueError(error2, parse24, schema4),
    error: [errorMessage],
    info: {},
    location: error2.niceError.location
  };
  addInstancePathInfo(newError, error2.instancePath);
  addFileInfo(newError, error2.source);
  newError.info["yaml-key-value-pairs"] = suggestion1;
  newError.info["suggestion-fix"] = suggestion2;
  return {
    ...error2,
    niceError: newError
  };
}
function createErrorFragments(error2) {
  const rawVerbatimInput = getVerbatimInput(error2);
  const verbatimInput = quotedStringColor(reindent(rawVerbatimInput));
  const pathFragments = error2.instancePath.map((s5) => blue4(String(s5)));
  return {
    location: locationString(error2.location),
    fullPath: pathFragments.join(":"),
    key: pathFragments[pathFragments.length - 1],
    value: verbatimInput
  };
}
function schemaDefinedErrors(error2, _parse, _schema) {
  const schema4 = error2.schema;
  if (schema4 === true || schema4 === false) {
    return error2;
  }
  if (schema4.errorMessage === void 0) {
    return error2;
  }
  if (typeof schema4.errorMessage !== "string") {
    return error2;
  }
  let result2 = schema4.errorMessage;
  for (const [k3, v4] of Object.entries(createErrorFragments(error2))) {
    result2 = result2.replace("${" + k3 + "}", v4);
  }
  return {
    ...error2,
    niceError: {
      ...error2.niceError,
      heading: result2
    }
  };
}
function checkForNearbyRequired(error2, _parse, _schema) {
  const schema4 = error2.schema;
  if (errorKeyword(error2) !== "required") {
    return error2;
  }
  const missingKeys = [];
  const errObj = error2.violatingObject.result;
  const keys = Object.keys(errObj);
  schemaCall(schema4, {
    object(s5) {
      if (s5.required === void 0) {
        throw new InternalError(
          "required schema error without a required field"
        );
      }
      for (const r5 of s5.required) {
        if (keys.indexOf(r5) === -1) {
          missingKeys.push(r5);
        }
      }
    }
  }, (_3) => {
    throw new InternalError("required error on a non-object schema");
  });
  for (const missingKey of missingKeys) {
    let bestCorrection;
    let bestDistance = Infinity;
    for (const correction of keys) {
      const d4 = editDistance(correction, missingKey);
      if (d4 < bestDistance) {
        bestCorrection = [correction];
        bestDistance = d4;
      } else if (d4 === bestDistance) {
        bestCorrection.push(correction);
        bestDistance = d4;
      }
    }
    if (bestDistance > missingKey.length * 10 * 0.3) {
      continue;
    }
    const suggestions = bestCorrection.map((s5) => blue4(s5));
    if (suggestions.length === 1) {
      error2.niceError.info[`did-you-mean-key`] = `Is ${suggestions[0]} a typo of ${blue4(missingKey)}?`;
    } else if (suggestions.length === 2) {
      error2.niceError.info[`did-you-mean-key`] = `Is ${suggestions[0]} or ${suggestions[1]} a typo of ${blue4(missingKey)}?`;
    } else {
      suggestions[suggestions.length - 1] = `or ${suggestions[suggestions.length - 1]}`;
      error2.niceError.info[`did-you-mean-key`] = `Is one of ${suggestions.join(", ")} a typo of ${blue4(missingKey)}?`;
    }
  }
  return error2;
}
function checkForNearbyCorrection(error2, parse24, _schema) {
  const schema4 = error2.schema;
  const corrections = [];
  let errVal = "";
  let keyOrValue = "";
  const key = getBadKey(error2);
  if (key) {
    errVal = key;
    corrections.push(...possibleSchemaKeys(schema4));
    keyOrValue = "key";
  } else {
    const val = navigate(error2.instancePath, parse24);
    if (typeof val.result !== "string") {
      return error2;
    }
    errVal = val.result;
    corrections.push(...possibleSchemaValues(schema4));
    keyOrValue = "value";
  }
  if (corrections.length === 0) {
    return error2;
  }
  let bestCorrection;
  let bestDistance = Infinity;
  for (const correction of corrections) {
    const d4 = editDistance(correction, errVal);
    if (d4 < bestDistance) {
      bestCorrection = [correction];
      bestDistance = d4;
    } else if (d4 === bestDistance) {
      bestCorrection.push(correction);
      bestDistance = d4;
    }
  }
  if (bestDistance > errVal.length * 10 * 0.3) {
    return error2;
  }
  const suggestions = bestCorrection.map((s5) => blue4(s5));
  if (suggestions.length === 1) {
    error2.niceError.info[`did-you-mean-${keyOrValue}`] = `Did you mean ${suggestions[0]}?`;
  } else if (suggestions.length === 2) {
    error2.niceError.info[`did-you-mean-${keyOrValue}`] = `Did you mean ${suggestions[0]} or ${suggestions[1]}?`;
  } else {
    suggestions[suggestions.length - 1] = `or ${suggestions[suggestions.length - 1]}`;
    error2.niceError.info[`did-you-mean-${keyOrValue}`] = `Did you mean ${suggestions.join(", ")}?`;
  }
  return error2;
}
function createSourceContext(src2, location) {
  if (src2.value.length === 0) {
    return "";
  }
  const startMapResult = src2.map(location.start, true);
  const endMapResult = src2.map(location.end, true);
  const locF = mappedIndexToLineCol(src2);
  let sourceLocation;
  try {
    sourceLocation = {
      start: locF(location.start),
      end: locF(location.end)
    };
  } catch (_e) {
    sourceLocation = {
      start: { line: 0, column: 0 },
      end: { line: 0, column: 0 }
    };
  }
  if (startMapResult === void 0 || endMapResult === void 0) {
    throw new InternalError(
      `createSourceContext called with bad location ${location.start}-${location.end}.`
    );
  }
  if (startMapResult.originalString !== endMapResult.originalString) {
    throw new InternalError(
      "don't know how to create source context across different source files"
    );
  }
  const originalString = startMapResult.originalString;
  const nLines = lines(originalString.value).length;
  const {
    start,
    end
  } = sourceLocation;
  const {
    prefixWidth,
    lines: formattedLines
  } = formatLineRange(
    originalString.value,
    Math.max(0, start.line - 1),
    Math.min(end.line + 1, nLines - 1)
  );
  const contextLines = [];
  let mustPrintEllipsis = true;
  for (const { lineNumber, content, rawLine } of formattedLines) {
    if (lineNumber < start.line || lineNumber > end.line) {
      if (rawLine.trim().length) {
        contextLines.push(content);
      }
    } else {
      if (lineNumber >= start.line + 2 && lineNumber <= end.line - 2) {
        if (mustPrintEllipsis) {
          mustPrintEllipsis = false;
          contextLines.push("...");
        }
      } else {
        const startColumn = lineNumber > start.line ? 0 : start.column;
        const endColumn = lineNumber < end.line ? rawLine.length : end.column;
        contextLines.push(content);
        contextLines.push(
          " ".repeat(prefixWidth + startColumn - 1) + "~".repeat(endColumn - startColumn + 1)
        );
      }
    }
  }
  return contextLines.join("\n");
}
function createLocalizedError(obj) {
  const {
    violatingObject,
    instancePath,
    schemaPath,
    source: source2,
    message,
    schema: schema4
  } = obj;
  const locF = mappedIndexToLineCol(source2);
  let location;
  try {
    location = {
      start: locF(violatingObject.start),
      end: locF(violatingObject.end)
    };
  } catch (_e) {
    location = {
      start: { line: 0, column: 0 },
      end: { line: 0, column: 0 }
    };
  }
  const mapResult = source2.map(violatingObject.start);
  const fileName = mapResult ? mapResult.originalString.fileName : void 0;
  return {
    source: mappedString(source2, [{
      start: violatingObject.start,
      end: violatingObject.end
    }]),
    violatingObject,
    instancePath,
    schemaPath,
    schema: schema4,
    message,
    location,
    niceError: {
      heading: message,
      error: [],
      info: {},
      fileName,
      location,
      sourceContext: createSourceContext(violatingObject.source, {
        start: violatingObject.start,
        end: violatingObject.end
      })
      // location!),
    }
  };
}
var init_errors2 = __esm({
  "core/lib/yaml-validation/errors.ts"() {
    init_colors3();
    init_errors();
    init_mapped_text();
    init_schema_utils();
    init_text();
    init_types2();
    init_text();
    init_error2();
  }
});

// core/lib/yaml-validation/validator.ts
function createNiceError(obj) {
  const {
    violatingObject,
    source: source2,
    message
  } = obj;
  const locF = mappedIndexToLineCol(source2);
  let location;
  try {
    location = {
      start: locF(violatingObject.start),
      end: locF(violatingObject.end)
    };
  } catch (_e) {
    location = {
      start: { line: 0, column: 0 },
      end: { line: 0, column: 0 }
    };
  }
  const mapResult = source2.map(violatingObject.start);
  const fileName = mapResult ? mapResult.originalString.fileName : void 0;
  return {
    heading: message,
    error: [],
    info: {},
    fileName,
    location,
    sourceContext: createSourceContext(violatingObject.source, {
      start: violatingObject.start,
      end: violatingObject.end
    })
  };
}
function validateGeneric(value, s5, context) {
  s5 = resolveSchema(s5);
  const st = schemaType(s5);
  return context.withSchemaPath(st, () => schemaCall(s5, {
    "false": (schema4) => {
      context.error(value, schema4, "false");
      return false;
    },
    "true": (_3) => true,
    "any": (schema4) => validateAny(value, schema4, context),
    "boolean": (schema4) => validateBoolean(value, schema4, context),
    "number": (schema4) => validateNumber(value, schema4, context),
    "string": (schema4) => validateString(value, schema4, context),
    "null": ((schema4) => validateNull(value, schema4, context)),
    "enum": ((schema4) => validateEnum(value, schema4, context)),
    "anyOf": (schema4) => validateAnyOf(value, schema4, context),
    "allOf": (schema4) => validateAllOf(value, schema4, context),
    "array": (schema4) => validateArray(value, schema4, context),
    "object": (schema4) => validateObject(value, schema4, context),
    "ref": (schema4) => validateGeneric(value, resolveSchema(schema4), context)
  }));
}
function typeIsValid(value, schema4, context, valid) {
  if (!valid) {
    return context.withSchemaPath(
      "type",
      () => {
        context.error(value, schema4, "type mismatch");
        return false;
      }
    );
  }
  return valid;
}
function validateAny(_value, _schema, _context) {
  return true;
}
function validateBoolean(value, schema4, context) {
  return typeIsValid(value, schema4, context, typeof value.result === "boolean");
}
function validateNumber(value, schema4, context) {
  if (!typeIsValid(value, schema4, context, typeof value.result === "number")) {
    return false;
  }
  let result2 = true;
  if (schema4.minimum !== void 0) {
    result2 = context.withSchemaPath(
      "minimum",
      () => {
        const v4 = value.result;
        if (!(v4 >= schema4.minimum)) {
          context.error(
            value,
            schema4,
            `value ${value.result} is less than required minimum ${schema4.minimum}`
          );
          return false;
        }
        return true;
      }
    );
  }
  if (schema4.maximum !== void 0) {
    result2 = context.withSchemaPath(
      "maximum",
      () => {
        const v4 = value.result;
        if (!(v4 <= schema4.maximum)) {
          context.error(
            value,
            schema4,
            `value ${value.result} is greater than required maximum ${schema4.maximum}`
          );
          return false;
        }
        return true;
      }
    );
  }
  if (schema4.exclusiveMinimum !== void 0) {
    result2 = context.withSchemaPath(
      "exclusiveMinimum",
      () => {
        const v4 = value.result;
        if (!(v4 > schema4.exclusiveMinimum)) {
          context.error(
            value,
            schema4,
            `value ${value.result} is less than or equal to required (exclusive) minimum ${schema4.exclusiveMinimum}`
          );
          return false;
        }
        return true;
      }
    );
  }
  if (schema4.exclusiveMaximum !== void 0) {
    result2 = context.withSchemaPath(
      "exclusiveMaximum",
      () => {
        const v4 = value.result;
        if (!(v4 < schema4.exclusiveMaximum)) {
          context.error(
            value,
            schema4,
            `value ${value.result} is greater than or equal to required (exclusive) maximum ${schema4.exclusiveMaximum}`
          );
          return false;
        }
        return true;
      }
    );
  }
  return result2;
}
function validateString(value, schema4, context) {
  if (!typeIsValid(value, schema4, context, typeof value.result === "string")) {
    return false;
  }
  if (schema4.pattern !== void 0) {
    if (schema4.compiledPattern === void 0) {
      schema4.compiledPattern = new RegExp(schema4.pattern);
    }
    if (!value.result.match(schema4.compiledPattern)) {
      return context.withSchemaPath(
        "pattern",
        () => {
          context.error(value, schema4, `value doesn't match pattern`);
          return false;
        }
      );
    }
  }
  return true;
}
function validateNull(value, schema4, context) {
  if (!typeIsValid(value, schema4, context, value.result === null)) {
    return false;
  }
  return true;
}
function validateEnum(value, schema4, context) {
  for (const enumValue of schema4["enum"]) {
    if (enumValue === value.result) {
      return true;
    }
  }
  context.error(value, schema4, `must match one of the values`);
  return false;
}
function validateAnyOf(value, schema4, context) {
  let passingSchemas = 0;
  for (let i6 = 0; i6 < schema4.anyOf.length; ++i6) {
    const subSchema = schema4.anyOf[i6];
    context.withSchemaPath(i6, () => {
      if (validateGeneric(value, subSchema, context)) {
        passingSchemas++;
        return true;
      }
      return false;
    });
  }
  return passingSchemas > 0;
}
function validateAllOf(value, schema4, context) {
  let passingSchemas = 0;
  for (let i6 = 0; i6 < schema4.allOf.length; ++i6) {
    const subSchema = schema4.allOf[i6];
    context.withSchemaPath(i6, () => {
      if (validateGeneric(value, subSchema, context)) {
        passingSchemas++;
        return true;
      }
      return false;
    });
  }
  return passingSchemas === schema4.allOf.length;
}
function validateArray(value, schema4, context) {
  let result2 = true;
  if (!typeIsValid(value, schema4, context, Array.isArray(value.result))) {
    return false;
  }
  const length = value.result.length;
  if (schema4.minItems !== void 0 && length < schema4.minItems) {
    context.withSchemaPath(
      "minItems",
      () => {
        context.error(
          value,
          schema4,
          `array should have at least ${schema4.minItems} items but has ${length} items instead`
        );
        return false;
      }
    );
    result2 = false;
  }
  if (schema4.maxItems !== void 0 && length > schema4.maxItems) {
    context.withSchemaPath(
      "maxItems",
      () => {
        context.error(
          value,
          schema4,
          `array should have at most ${schema4.maxItems} items but has ${length} items instead`
        );
        return false;
      }
    );
    result2 = false;
  }
  if (schema4.items !== void 0) {
    result2 = context.withSchemaPath("items", () => {
      let result3 = true;
      for (let i6 = 0; i6 < value.components.length; ++i6) {
        context.pushInstance(i6);
        result3 = validateGeneric(value.components[i6], schema4.items, context) && result3;
        context.popInstance();
      }
      return result3;
    }) && result2;
  }
  return result2;
}
function validateObject(value, schema4, context) {
  const isObject7 = typeof value.result === "object" && !Array.isArray(value.result) && value.result !== null;
  if (!typeIsValid(value, schema4, context, isObject7)) {
    return false;
  }
  let result2 = true;
  const ownProperties = new Set(
    Object.getOwnPropertyNames(value.result)
  );
  const objResult = value.result;
  const locate = (key, keyOrValue = "value") => {
    for (let i6 = 0; i6 < value.components.length; i6 += 2) {
      if (String(value.components[i6].result) === key) {
        if (keyOrValue === "value") {
          return value.components[i6 + 1];
        } else {
          return value.components[i6];
        }
      }
    }
    if (value.result && typeof value.result === "object" && !Array.isArray(value.result) && value.result.tag === "!expr") {
      throw new NoExprTag(value, value.source);
    }
    throw new InternalError(`Couldn't locate key ${key}`);
  };
  const inspectedProps = /* @__PURE__ */ new Set();
  if (schema4.closed) {
    result2 = context.withSchemaPath("closed", () => {
      if (schema4.properties === void 0) {
        throw new InternalError("Closed schemas need properties");
      }
      let innerResult = true;
      for (const key of ownProperties) {
        if (!schema4.properties[key]) {
          context.error(
            locate(key, "key"),
            schema4,
            `object has invalid field ${key}`
          );
          innerResult = false;
        }
      }
      return innerResult;
    }) && result2;
  }
  if (schema4.properties !== void 0) {
    result2 = context.withSchemaPath("properties", () => {
      let result3 = true;
      for (const [key, subSchema] of Object.entries(schema4.properties)) {
        if (ownProperties.has(key)) {
          inspectedProps.add(key);
          context.pushInstance(key);
          result3 = context.withSchemaPath(
            key,
            () => validateGeneric(locate(key), subSchema, context)
          ) && result3;
          context.popInstance();
        }
      }
      return result3;
    }) && result2;
  }
  if (schema4.patternProperties !== void 0) {
    result2 = context.withSchemaPath("patternProperties", () => {
      let result3 = true;
      for (const [key, subSchema] of Object.entries(schema4.patternProperties)) {
        if (schema4.compiledPatterns === void 0) {
          schema4.compiledPatterns = {};
        }
        if (schema4.compiledPatterns[key] === void 0) {
          schema4.compiledPatterns[key] = new RegExp(key);
        }
        const regexp = schema4.compiledPatterns[key];
        for (const [objectKey, _val] of Object.entries(objResult)) {
          if (objectKey.match(regexp)) {
            inspectedProps.add(objectKey);
            context.pushInstance(objectKey);
            result3 = context.withSchemaPath(
              key,
              () => validateGeneric(locate(objectKey), subSchema, context)
            ) && result3;
            context.popInstance();
          }
        }
      }
      return result3;
    }) && result2;
  }
  if (schema4.additionalProperties !== void 0) {
    result2 = context.withSchemaPath("additionalProperties", () => {
      return Object.keys(objResult).filter((objectKey) => !inspectedProps.has(objectKey)).every(
        (objectKey) => validateGeneric(
          locate(objectKey),
          schema4.additionalProperties,
          context
        )
      );
    }) && result2;
  }
  if (schema4.propertyNames !== void 0) {
    result2 = context.withSchemaPath("propertyNames", () => {
      return Array.from(ownProperties).every(
        (key) => validateGeneric(locate(key, "key"), schema4.propertyNames, context)
      );
    }) && result2;
  }
  if (schema4.required !== void 0) {
    result2 = context.withSchemaPath("required", () => {
      let result3 = true;
      for (const reqKey of schema4.required) {
        if (!ownProperties.has(reqKey)) {
          context.error(
            value,
            schema4,
            `object is missing required property ${reqKey}`
          );
          result3 = false;
        }
      }
      return result3;
    }) && result2;
  }
  return result2;
}
function validate(value, schema4, source2, pruneErrors = true) {
  const context = new ValidationContext();
  return context.validate(schema4, source2, value, pruneErrors);
}
var NoExprTag, ValidationContext;
var init_validator = __esm({
  "core/lib/yaml-validation/validator.ts"() {
    init_types2();
    init_resolve4();
    init_errors2();
    init_error2();
    init_mapped_text();
    NoExprTag = class extends Error {
      constructor(violatingObject, source2) {
        super(`Unexpected !expr tag`);
        this.name = "NoExprTag";
        this.niceError = createNiceError({
          violatingObject,
          source: source2,
          message: "!expr tags are not allowed in Quarto outside of knitr code cells."
        });
      }
      niceError;
    };
    ValidationContext = class {
      instancePath;
      root;
      nodeStack;
      currentNode;
      constructor() {
        this.instancePath = [];
        this.currentNode = { edge: "#", errors: [], children: [] };
        this.nodeStack = [this.currentNode];
        this.root = this.currentNode;
      }
      error(value, schema4, message) {
        this.currentNode.errors.push({
          value,
          schema: schema4,
          message,
          instancePath: this.instancePath.slice(),
          schemaPath: this.nodeStack.map((node) => node.edge)
        });
      }
      pushSchema(schemaPath) {
        const newNode = {
          edge: schemaPath,
          errors: [],
          children: []
        };
        this.currentNode.children.push(newNode);
        this.currentNode = newNode;
        this.nodeStack.push(newNode);
      }
      popSchema(success) {
        this.nodeStack.pop();
        this.currentNode = this.nodeStack[this.nodeStack.length - 1];
        if (success) {
          this.currentNode.children.pop();
        }
        return success;
      }
      pushInstance(instance) {
        this.instancePath.push(instance);
      }
      popInstance() {
        this.instancePath.pop();
      }
      withSchemaPath(schemaPath, chunk) {
        this.pushSchema(schemaPath);
        return this.popSchema(chunk());
      }
      validate(schema4, source2, value, pruneErrors = true) {
        if (validateGeneric(value, schema4, this)) {
          return [];
        }
        return this.collectErrors(schema4, source2, value, pruneErrors);
      }
      // if pruneErrors is false, we return all errors. This is typically
      // hard to interpret directly because of anyOf errors.
      //
      // it's possible that the best API is for LocalizedErrors to explicitly nest
      // so that anyOf errors are reported in their natural structure.
      //
      // if pruneErrors is true, then we only report one of the anyOf
      // errors, avoiding most issues. (`patternProperties` can still
      // cause error overlap and potential confusion, and we need those
      // because of pandoc properties..)
      collectErrors(_schema, source2, _value, pruneErrors = true) {
        const inner = (node) => {
          const result3 = [];
          if (node.edge === "anyOf" && pruneErrors) {
            const innerResults = node.children.map(inner);
            const isRequiredError = (e5) => e5.schemaPath.indexOf("required") === e5.schemaPath.length - 1;
            const isPropertyNamesError = (e5) => e5.schemaPath.indexOf("propertyNames") !== -1;
            if (innerResults.some((el) => el.length && isRequiredError(el[0])) && innerResults.some((el) => el.length && isPropertyNamesError(el[0]))) {
              return innerResults.filter((r5) => {
                return r5.length && r5[0].schemaPath.slice(-1)[0] === "required";
              })[0];
            }
            const errorTypeQuality = (e5) => {
              const t5 = e5.schemaPath.slice().reverse();
              if (typeof e5.schema === "object") {
                if (e5.schema.tags && e5.schema.tags["error-importance"] && typeof e5.schema.tags["error-importance"] === "number") {
                  return e5.schema.tags["error-importance"];
                }
              }
              if (e5.schemaPath.indexOf("propertyNames") !== -1) {
                return 10;
              }
              if (t5[0] === "required") {
                return 0;
              }
              if (t5[0] === "type") {
                if (t5[1] === "null") {
                  return 10;
                }
                return 1;
              }
              return 1;
            };
            const errorComparator = (a5, b3) => {
              for (let i6 = 0; i6 < a5.length; ++i6) {
                if (a5[i6] < b3[i6]) {
                  return -1;
                }
                if (a5[i6] > b3[i6]) {
                  return 1;
                }
              }
              return 0;
            };
            let bestResults = [];
            let bestError = [Infinity, Infinity];
            for (const resultGroup of innerResults) {
              let maxQuality = -Infinity;
              let totalSpan = 0;
              for (const result4 of resultGroup) {
                totalSpan += result4.value.end - result4.value.start;
                maxQuality = Math.max(maxQuality, errorTypeQuality(result4));
              }
              const thisError = [maxQuality, totalSpan];
              if (errorComparator(thisError, bestError) === -1) {
                bestError = thisError;
                bestResults = resultGroup;
              }
            }
            return bestResults;
          } else {
            result3.push(...node.errors);
            for (const child of node.children) {
              result3.push(...inner(child));
            }
            return result3;
          }
        };
        const errors2 = inner(this.root);
        const result2 = errors2.map(
          (validationError) => createLocalizedError({
            violatingObject: validationError.value,
            instancePath: validationError.instancePath,
            schemaPath: validationError.schemaPath,
            schema: validationError.schema,
            message: validationError.message,
            source: source2
          })
        );
        return result2;
      }
    };
  }
});

// core/lib/yaml-validation/yaml-schema.ts
var YAMLSchema;
var init_yaml_schema = __esm({
  "core/lib/yaml-validation/yaml-schema.ts"() {
    init_validator();
    YAMLSchema = class {
      schema;
      // These are schema-specific error transformers to yield custom
      // error messages.
      errorHandlers;
      constructor(schema4) {
        this.errorHandlers = [];
        this.schema = schema4;
      }
      addHandler(handler) {
        this.errorHandlers.push(handler);
      }
      transformErrors(annotation, errors2) {
        return errors2.map((error2) => {
          for (const handler of this.errorHandlers) {
            const localError = handler(error2, annotation, this.schema);
            if (localError === null) {
              return null;
            }
            error2 = localError;
          }
          return error2;
        }).filter((error2) => error2 !== null);
      }
      // deno-lint-ignore require-await
      async validateParse(src2, annotation, pruneErrors = true) {
        const validationErrors = validate(
          annotation,
          this.schema,
          src2,
          pruneErrors
        );
        if (validationErrors.length) {
          const localizedErrors = this.transformErrors(
            annotation,
            validationErrors
          );
          return {
            result: annotation.result,
            errors: localizedErrors
          };
        } else {
          return {
            result: annotation.result,
            errors: []
          };
        }
      }
      // NB this needs explicit params for "error" and "log" because it might
      // get called from the IDE, where we lack quarto's "error" and "log"
      // infra
      reportErrorsInSource(result2, _src, message, error2, log3) {
        if (result2.errors.length) {
          if (message.length) {
            error2(message);
          }
          for (const err2 of result2.errors) {
            log3(err2.niceError);
          }
        }
        return result2;
      }
      // NB this needs explicit params for "error" and "log" because it might
      // get called from the IDE, where we lack quarto's "error" and "log"
      // infra
      async validateParseWithErrors(src2, annotation, message, error2, log3) {
        const result2 = await this.validateParse(src2, annotation);
        this.reportErrorsInSource(result2, src2, message, error2, log3);
        return result2;
      }
    };
  }
});

// core/lib/yaml-validation/validator-queue.ts
function getSchemaName(schema4) {
  if (schema4 === true || schema4 === false) {
    throw new Error("Expected schema to be named");
  }
  let schemaName = schema4["$id"];
  if (schemaName !== void 0) {
    return schemaName;
  }
  if (schemaType(schema4) === "ref") {
    schemaName = schema4["$ref"];
  }
  if (schemaName !== void 0) {
    return schemaName;
  }
  throw new Error("Expected schema to be named");
}
function getValidator(schema4) {
  const schemaName = getSchemaName(schema4);
  if (yamlValidators[schemaName]) {
    return yamlValidators[schemaName];
  }
  const validator = new YAMLSchema(schema4);
  yamlValidators[schemaName] = validator;
  setDefaultErrorHandlers(validator);
  return validator;
}
async function withValidator(schema4, fun) {
  let result2;
  let error2;
  try {
    const validator = getValidator(schema4);
    result2 = await fun(validator);
  } catch (e5) {
    error2 = e5;
  }
  if (error2 !== void 0) {
    throw error2;
  }
  return result2;
}
function addValidatorErrorHandler(schema4, handler) {
  return withValidator(schema4, async (validator) => {
    validator.addHandler(handler);
  });
}
var yamlValidators;
var init_validator_queue = __esm({
  "core/lib/yaml-validation/validator-queue.ts"() {
    init_yaml_schema();
    init_errors2();
    init_types2();
    yamlValidators = {};
  }
});

// core/lib/memoize.ts
function memoize(f5, keyMemoizer) {
  const memo = {};
  const inner = (...args) => {
    const key = keyMemoizer(...args);
    const v4 = memo[key];
    if (v4 !== void 0) {
      return v4;
    }
    memo[key] = f5(...args);
    return memo[key];
  };
  return inner;
}
var init_memoize = __esm({
  "core/lib/memoize.ts"() {
  }
});

// core/lib/glob.ts
function globToRegExp5(glob, {
  extended = true,
  globstar: globstarOption = true,
  caseInsensitive = false
} = {}) {
  if (glob == "") {
    return /(?!)/;
  }
  const sep6 = "/+";
  const sepMaybe = "/*";
  const seps = ["/"];
  const globstar = "(?:[^/]*(?:/|$)+)*";
  const wildcard = "[^/]*";
  const escapePrefix = "\\";
  let newLength = glob.length;
  for (; newLength > 1 && seps.includes(glob[newLength - 1]); newLength--) ;
  glob = glob.slice(0, newLength);
  let regExpString = "";
  for (let j3 = 0; j3 < glob.length; ) {
    let segment = "";
    const groupStack = [];
    let inRange = false;
    let inEscape = false;
    let endsWithSep = false;
    let i6 = j3;
    for (; i6 < glob.length && !seps.includes(glob[i6]); i6++) {
      if (inEscape) {
        inEscape = false;
        const escapeChars = inRange ? rangeEscapeChars : regExpEscapeChars;
        segment += escapeChars.includes(glob[i6]) ? `\\${glob[i6]}` : glob[i6];
        continue;
      }
      if (glob[i6] == escapePrefix) {
        inEscape = true;
        continue;
      }
      if (glob[i6] == "[") {
        if (!inRange) {
          inRange = true;
          segment += "[";
          if (glob[i6 + 1] == "!") {
            i6++;
            segment += "^";
          } else if (glob[i6 + 1] == "^") {
            i6++;
            segment += "\\^";
          }
          continue;
        } else if (glob[i6 + 1] == ":") {
          let k3 = i6 + 1;
          let value = "";
          while (glob[k3 + 1] != null && glob[k3 + 1] != ":") {
            value += glob[k3 + 1];
            k3++;
          }
          if (glob[k3 + 1] == ":" && glob[k3 + 2] == "]") {
            i6 = k3 + 2;
            if (value == "alnum") segment += "\\dA-Za-z";
            else if (value == "alpha") segment += "A-Za-z";
            else if (value == "ascii") segment += "\0-\x7F";
            else if (value == "blank") segment += "	 ";
            else if (value == "cntrl") segment += "\0-\x7F";
            else if (value == "digit") segment += "\\d";
            else if (value == "graph") segment += "!-~";
            else if (value == "lower") segment += "a-z";
            else if (value == "print") segment += " -~";
            else if (value == "punct") {
              segment += `!"#$%&'()*+,\\-./:;<=>?@[\\\\\\]^_\u2018{|}~`;
            } else if (value == "space") segment += "\\s\v";
            else if (value == "upper") segment += "A-Z";
            else if (value == "word") segment += "\\w";
            else if (value == "xdigit") segment += "\\dA-Fa-f";
            continue;
          }
        }
      }
      if (glob[i6] == "]" && inRange) {
        inRange = false;
        segment += "]";
        continue;
      }
      if (inRange) {
        if (glob[i6] == "\\") {
          segment += `\\\\`;
        } else {
          segment += glob[i6];
        }
        continue;
      }
      if (glob[i6] == ")" && groupStack.length > 0 && groupStack[groupStack.length - 1] != "BRACE") {
        segment += ")";
        const type4 = groupStack.pop();
        if (type4 == "!") {
          segment += wildcard;
        } else if (type4 != "@") {
          segment += type4;
        }
        continue;
      }
      if (glob[i6] == "|" && groupStack.length > 0 && groupStack[groupStack.length - 1] != "BRACE") {
        segment += "|";
        continue;
      }
      if (glob[i6] == "+" && extended && glob[i6 + 1] == "(") {
        i6++;
        groupStack.push("+");
        segment += "(?:";
        continue;
      }
      if (glob[i6] == "@" && extended && glob[i6 + 1] == "(") {
        i6++;
        groupStack.push("@");
        segment += "(?:";
        continue;
      }
      if (glob[i6] == "?") {
        if (extended && glob[i6 + 1] == "(") {
          i6++;
          groupStack.push("?");
          segment += "(?:";
        } else {
          segment += ".";
        }
        continue;
      }
      if (glob[i6] == "!" && extended && glob[i6 + 1] == "(") {
        i6++;
        groupStack.push("!");
        segment += "(?!";
        continue;
      }
      if (glob[i6] == "{") {
        groupStack.push("BRACE");
        segment += "(?:";
        continue;
      }
      if (glob[i6] == "}" && groupStack[groupStack.length - 1] == "BRACE") {
        groupStack.pop();
        segment += ")";
        continue;
      }
      if (glob[i6] == "," && groupStack[groupStack.length - 1] == "BRACE") {
        segment += "|";
        continue;
      }
      if (glob[i6] == "*") {
        if (extended && glob[i6 + 1] == "(") {
          i6++;
          groupStack.push("*");
          segment += "(?:";
        } else {
          const prevChar = glob[i6 - 1];
          let numStars = 1;
          while (glob[i6 + 1] == "*") {
            i6++;
            numStars++;
          }
          const nextChar = glob[i6 + 1];
          if (globstarOption && numStars == 2 && [...seps, void 0].includes(prevChar) && [...seps, void 0].includes(nextChar)) {
            segment += globstar;
            endsWithSep = true;
          } else {
            segment += wildcard;
          }
        }
        continue;
      }
      segment += regExpEscapeChars.includes(glob[i6]) ? `\\${glob[i6]}` : glob[i6];
    }
    if (groupStack.length > 0 || inRange || inEscape) {
      segment = "";
      for (const c6 of glob.slice(j3, i6)) {
        segment += regExpEscapeChars.includes(c6) ? `\\${c6}` : c6;
        endsWithSep = false;
      }
    }
    regExpString += segment;
    if (!endsWithSep) {
      regExpString += i6 < glob.length ? sep6 : sepMaybe;
      endsWithSep = true;
    }
    while (seps.includes(glob[i6])) i6++;
    if (!(i6 > j3)) {
      throw new Error("Assertion failure: i > j (potential infinite loop)");
    }
    j3 = i6;
  }
  regExpString = `^${regExpString}$`;
  return new RegExp(regExpString, caseInsensitive ? "i" : "");
}
function isGlob3(str3) {
  const chars = { "{": "}", "(": ")", "[": "]" };
  const regex = /\\(.)|(^!|\*|\?|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\)|\([^|]+\|[^\\)]+\))/;
  if (str3 === "") {
    return false;
  }
  let match;
  while (match = regex.exec(str3)) {
    if (match[2]) return true;
    let idx = match.index + match[0].length;
    const open = match[1];
    const close = open ? chars[open] : null;
    if (open && close) {
      const n5 = str3.indexOf(close, idx);
      if (n5 !== -1) {
        idx = n5 + 1;
      }
    }
    str3 = str3.slice(idx);
  }
  return false;
}
var regExpEscapeChars, rangeEscapeChars;
var init_glob = __esm({
  "core/lib/glob.ts"() {
    regExpEscapeChars = [
      "!",
      "$",
      "(",
      ")",
      "*",
      "+",
      ".",
      "=",
      "?",
      "[",
      "\\",
      "^",
      "{",
      "|"
    ];
    rangeEscapeChars = ["-", "\\", "]"];
  }
});

// core/lib/yaml-intelligence/resources.ts
function setYamlIntelligenceResources(resources) {
  for (const [key, value] of Object.entries(resources)) {
    _resources[key] = value;
  }
}
function exportYamlIntelligenceResources(pretty = false) {
  if (pretty) {
    return JSON.stringify(_resources, null, 2);
  } else {
    return JSON.stringify(_resources);
  }
}
function getYamlIntelligenceResource(filename) {
  if (_resources[filename] === void 0) {
    throw new InternalError(
      `getYamlIntelligenceResource called with missing resource ${filename}`
    );
  }
  return _resources[filename];
}
function expandResourceGlob(glob) {
  return Object.keys(_resources).filter(
    (key) => key.match(globToRegExp5(glob))
  ).map((key) => [key, getYamlIntelligenceResource(key)]);
}
var _resources;
var init_resources = __esm({
  "core/lib/yaml-intelligence/resources.ts"() {
    init_error2();
    init_glob();
    _resources = {};
  }
});

// core/lib/polyfills.ts
function fromEntries(iterable) {
  return [...iterable].reduce((obj, [key, val]) => {
    obj[key] = val;
    return obj;
  }, {});
}
var init_polyfills = __esm({
  "core/lib/polyfills.ts"() {
  }
});

// core/lib/yaml-intelligence/parsing.ts
function setTreeSitter(parser) {
  _parser = parser;
}
function getTreeSitterSync() {
  if (_parser === void 0) {
    throw new Error("tree-sitter uninitialized");
  }
  return _parser;
}
var _parser;
var init_parsing = __esm({
  "core/lib/yaml-intelligence/parsing.ts"() {
    init_error2();
    init_mapped_text();
    init_ranged_text();
    init_text();
  }
});

// core/lib/external/js-yaml.js
function isNothing(subject) {
  return typeof subject === "undefined" || subject === null;
}
function isObject2(subject) {
  return typeof subject === "object" && subject !== null;
}
function toArray(sequence) {
  if (Array.isArray(sequence)) return sequence;
  else if (isNothing(sequence)) return [];
  return [sequence];
}
function extend(target, source2) {
  var index2, length, key, sourceKeys;
  if (source2) {
    sourceKeys = Object.keys(source2);
    for (index2 = 0, length = sourceKeys.length; index2 < length; index2 += 1) {
      key = sourceKeys[index2];
      target[key] = source2[key];
    }
  }
  return target;
}
function repeat(string2, count) {
  var result2 = "", cycle;
  for (cycle = 0; cycle < count; cycle += 1) {
    result2 += string2;
  }
  return result2;
}
function isNegativeZero(number2) {
  return number2 === 0 && Number.NEGATIVE_INFINITY === 1 / number2;
}
function formatError(exception22, compact) {
  var where = "", message = exception22.reason || "(unknown reason)";
  if (!exception22.mark) return message;
  if (exception22.mark.name) {
    where += 'in "' + exception22.mark.name + '" ';
  }
  where += "(" + (exception22.mark.line + 1) + ":" + (exception22.mark.column + 1) + ")";
  if (!compact && exception22.mark.snippet) {
    where += "\n\n" + exception22.mark.snippet;
  }
  return message + " " + where;
}
function YAMLException$1(reason, mark) {
  Error.call(this);
  this.name = "YAMLException";
  this.reason = reason;
  this.mark = mark;
  this.message = formatError(this, false);
  if (Error.captureStackTrace) {
    Error.captureStackTrace(this, this.constructor);
  } else {
    this.stack = new Error().stack || "";
  }
}
function getLine(buffer2, lineStart, lineEnd, position, maxLineLength) {
  var head = "";
  var tail = "";
  var maxHalfLength = Math.floor(maxLineLength / 2) - 1;
  if (position - lineStart > maxHalfLength) {
    head = " ... ";
    lineStart = position - maxHalfLength + head.length;
  }
  if (lineEnd - position > maxHalfLength) {
    tail = " ...";
    lineEnd = position + maxHalfLength - tail.length;
  }
  return {
    str: head + buffer2.slice(lineStart, lineEnd).replace(/\t/g, "\u2192") + tail,
    pos: position - lineStart + head.length
  };
}
function padStart(string2, max) {
  return common2.repeat(" ", max - string2.length) + string2;
}
function makeSnippet(mark, options) {
  options = Object.create(options || null);
  if (!mark.buffer) return null;
  if (!options.maxLength) options.maxLength = 79;
  if (typeof options.indent !== "number") options.indent = 1;
  if (typeof options.linesBefore !== "number") options.linesBefore = 3;
  if (typeof options.linesAfter !== "number") options.linesAfter = 2;
  var re3 = /\r?\n|\r|\0/g;
  var lineStarts = [0];
  var lineEnds = [];
  var match;
  var foundLineNo = -1;
  while (match = re3.exec(mark.buffer)) {
    lineEnds.push(match.index);
    lineStarts.push(match.index + match[0].length);
    if (mark.position <= match.index && foundLineNo < 0) {
      foundLineNo = lineStarts.length - 2;
    }
  }
  if (foundLineNo < 0) foundLineNo = lineStarts.length - 1;
  var result2 = "", i6, line;
  var lineNoLength = Math.min(
    mark.line + options.linesAfter,
    lineEnds.length
  ).toString().length;
  var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3);
  for (i6 = 1; i6 <= options.linesBefore; i6++) {
    if (foundLineNo - i6 < 0) break;
    line = getLine(
      mark.buffer,
      lineStarts[foundLineNo - i6],
      lineEnds[foundLineNo - i6],
      mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i6]),
      maxLineLength
    );
    result2 = common2.repeat(" ", options.indent) + padStart((mark.line - i6 + 1).toString(), lineNoLength) + " | " + line.str + "\n" + result2;
  }
  line = getLine(
    mark.buffer,
    lineStarts[foundLineNo],
    lineEnds[foundLineNo],
    mark.position,
    maxLineLength
  );
  result2 += common2.repeat(" ", options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + " | " + line.str + "\n";
  result2 += common2.repeat("-", options.indent + lineNoLength + 3 + line.pos) + "^\n";
  for (i6 = 1; i6 <= options.linesAfter; i6++) {
    if (foundLineNo + i6 >= lineEnds.length) break;
    line = getLine(
      mark.buffer,
      lineStarts[foundLineNo + i6],
      lineEnds[foundLineNo + i6],
      mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i6]),
      maxLineLength
    );
    result2 += common2.repeat(" ", options.indent) + padStart((mark.line + i6 + 1).toString(), lineNoLength) + " | " + line.str + "\n";
  }
  return result2.replace(/\n$/, "");
}
function compileStyleAliases(map22) {
  var result2 = {};
  if (map22 !== null) {
    Object.keys(map22).forEach(function(style) {
      map22[style].forEach(function(alias) {
        result2[String(alias)] = style;
      });
    });
  }
  return result2;
}
function Type$1(tag, options) {
  options = options || {};
  Object.keys(options).forEach(function(name2) {
    if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name2) === -1) {
      throw new exception(
        'Unknown option "' + name2 + '" is met in definition of "' + tag + '" YAML type.'
      );
    }
  });
  this.options = options;
  this.tag = tag;
  this.kind = options["kind"] || null;
  this.resolve = options["resolve"] || function() {
    return true;
  };
  this.construct = options["construct"] || function(data3) {
    return data3;
  };
  this.instanceOf = options["instanceOf"] || null;
  this.predicate = options["predicate"] || null;
  this.represent = options["represent"] || null;
  this.representName = options["representName"] || null;
  this.defaultStyle = options["defaultStyle"] || null;
  this.multi = options["multi"] || false;
  this.styleAliases = compileStyleAliases(options["styleAliases"] || null);
  if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {
    throw new exception(
      'Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'
    );
  }
}
function compileList(schema22, name2) {
  var result2 = [];
  schema22[name2].forEach(function(currentType) {
    var newIndex = result2.length;
    result2.forEach(function(previousType, previousIndex) {
      if (previousType.tag === currentType.tag && previousType.kind === currentType.kind && previousType.multi === currentType.multi) {
        newIndex = previousIndex;
      }
    });
    result2[newIndex] = currentType;
  });
  return result2;
}
function compileMap() {
  var result2 = {
    scalar: {},
    sequence: {},
    mapping: {},
    fallback: {},
    multi: {
      scalar: [],
      sequence: [],
      mapping: [],
      fallback: []
    }
  }, index2, length;
  function collectType(type22) {
    if (type22.multi) {
      result2.multi[type22.kind].push(type22);
      result2.multi["fallback"].push(type22);
    } else {
      result2[type22.kind][type22.tag] = result2["fallback"][type22.tag] = type22;
    }
  }
  for (index2 = 0, length = arguments.length; index2 < length; index2 += 1) {
    arguments[index2].forEach(collectType);
  }
  return result2;
}
function Schema$1(definition) {
  return this.extend(definition);
}
function resolveYamlNull(data3) {
  if (data3 === null) return true;
  var max = data3.length;
  return max === 1 && data3 === "~" || max === 4 && (data3 === "null" || data3 === "Null" || data3 === "NULL");
}
function constructYamlNull() {
  return null;
}
function isNull(object) {
  return object === null;
}
function resolveYamlBoolean(data3) {
  if (data3 === null) return false;
  var max = data3.length;
  return max === 4 && (data3 === "true" || data3 === "True" || data3 === "TRUE") || max === 5 && (data3 === "false" || data3 === "False" || data3 === "FALSE");
}
function constructYamlBoolean(data3) {
  return data3 === "true" || data3 === "True" || data3 === "TRUE";
}
function isBoolean(object) {
  return Object.prototype.toString.call(object) === "[object Boolean]";
}
function isHexCode(c6) {
  return 48 <= c6 && c6 <= 57 || 65 <= c6 && c6 <= 70 || 97 <= c6 && c6 <= 102;
}
function isOctCode(c6) {
  return 48 <= c6 && c6 <= 55;
}
function isDecCode(c6) {
  return 48 <= c6 && c6 <= 57;
}
function resolveYamlInteger(data3) {
  if (data3 === null) return false;
  var max = data3.length, index2 = 0, hasDigits = false, ch;
  if (!max) return false;
  ch = data3[index2];
  if (ch === "-" || ch === "+") {
    ch = data3[++index2];
  }
  if (ch === "0") {
    if (index2 + 1 === max) return true;
    ch = data3[++index2];
    if (ch === "b") {
      index2++;
      for (; index2 < max; index2++) {
        ch = data3[index2];
        if (ch === "_") continue;
        if (ch !== "0" && ch !== "1") return false;
        hasDigits = true;
      }
      return hasDigits && ch !== "_";
    }
    if (ch === "x") {
      index2++;
      for (; index2 < max; index2++) {
        ch = data3[index2];
        if (ch === "_") continue;
        if (!isHexCode(data3.charCodeAt(index2))) return false;
        hasDigits = true;
      }
      return hasDigits && ch !== "_";
    }
    if (ch === "o") {
      index2++;
      for (; index2 < max; index2++) {
        ch = data3[index2];
        if (ch === "_") continue;
        if (!isOctCode(data3.charCodeAt(index2))) return false;
        hasDigits = true;
      }
      return hasDigits && ch !== "_";
    }
  }
  if (ch === "_") return false;
  for (; index2 < max; index2++) {
    ch = data3[index2];
    if (ch === "_") continue;
    if (!isDecCode(data3.charCodeAt(index2))) {
      return false;
    }
    hasDigits = true;
  }
  if (!hasDigits || ch === "_") return false;
  return true;
}
function constructYamlInteger(data3) {
  var value = data3, sign = 1, ch;
  if (value.indexOf("_") !== -1) {
    value = value.replace(/_/g, "");
  }
  ch = value[0];
  if (ch === "-" || ch === "+") {
    if (ch === "-") sign = -1;
    value = value.slice(1);
    ch = value[0];
  }
  if (value === "0") return 0;
  if (ch === "0") {
    if (value[1] === "b") return sign * parseInt(value.slice(2), 2);
    if (value[1] === "x") return sign * parseInt(value.slice(2), 16);
    if (value[1] === "o") return sign * parseInt(value.slice(2), 8);
  }
  return sign * parseInt(value, 10);
}
function isInteger(object) {
  return Object.prototype.toString.call(object) === "[object Number]" && object % 1 === 0 && !common2.isNegativeZero(object);
}
function resolveYamlFloat(data3) {
  if (data3 === null) return false;
  if (!YAML_FLOAT_PATTERN.test(data3) || data3[data3.length - 1] === "_") {
    return false;
  }
  return true;
}
function constructYamlFloat(data3) {
  var value, sign;
  value = data3.replace(/_/g, "").toLowerCase();
  sign = value[0] === "-" ? -1 : 1;
  if ("+-".indexOf(value[0]) >= 0) {
    value = value.slice(1);
  }
  if (value === ".inf") {
    return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
  } else if (value === ".nan") {
    return NaN;
  }
  return sign * parseFloat(value, 10);
}
function representYamlFloat(object, style) {
  var res;
  if (isNaN(object)) {
    switch (style) {
      case "lowercase":
        return ".nan";
      case "uppercase":
        return ".NAN";
      case "camelcase":
        return ".NaN";
    }
  } else if (Number.POSITIVE_INFINITY === object) {
    switch (style) {
      case "lowercase":
        return ".inf";
      case "uppercase":
        return ".INF";
      case "camelcase":
        return ".Inf";
    }
  } else if (Number.NEGATIVE_INFINITY === object) {
    switch (style) {
      case "lowercase":
        return "-.inf";
      case "uppercase":
        return "-.INF";
      case "camelcase":
        return "-.Inf";
    }
  } else if (common2.isNegativeZero(object)) {
    return "-0.0";
  }
  res = object.toString(10);
  return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace("e", ".e") : res;
}
function isFloat(object) {
  return Object.prototype.toString.call(object) === "[object Number]" && (object % 1 !== 0 || common2.isNegativeZero(object));
}
function resolveYamlTimestamp(data3) {
  if (data3 === null) return false;
  if (YAML_DATE_REGEXP.exec(data3) !== null) return true;
  if (YAML_TIMESTAMP_REGEXP.exec(data3) !== null) return true;
  return false;
}
function constructYamlTimestamp(data3) {
  var match, year, month, day, hour, minute, second, fraction = 0, delta = null, tz_hour, tz_minute, date;
  match = YAML_DATE_REGEXP.exec(data3);
  if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data3);
  if (match === null) throw new Error("Date resolve error");
  year = +match[1];
  month = +match[2] - 1;
  day = +match[3];
  if (!match[4]) {
    return new Date(Date.UTC(year, month, day));
  }
  hour = +match[4];
  minute = +match[5];
  second = +match[6];
  if (match[7]) {
    fraction = match[7].slice(0, 3);
    while (fraction.length < 3) {
      fraction += "0";
    }
    fraction = +fraction;
  }
  if (match[9]) {
    tz_hour = +match[10];
    tz_minute = +(match[11] || 0);
    delta = (tz_hour * 60 + tz_minute) * 6e4;
    if (match[9] === "-") delta = -delta;
  }
  date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));
  if (delta) date.setTime(date.getTime() - delta);
  return date;
}
function representYamlTimestamp(object) {
  return object.toISOString();
}
function resolveYamlMerge(data3) {
  return data3 === "<<" || data3 === null;
}
function resolveYamlBinary(data3) {
  if (data3 === null) return false;
  var code5, idx, bitlen = 0, max = data3.length, map22 = BASE64_MAP;
  for (idx = 0; idx < max; idx++) {
    code5 = map22.indexOf(data3.charAt(idx));
    if (code5 > 64) continue;
    if (code5 < 0) return false;
    bitlen += 6;
  }
  return bitlen % 8 === 0;
}
function constructYamlBinary(data3) {
  var idx, tailbits, input = data3.replace(/[\r\n=]/g, ""), max = input.length, map22 = BASE64_MAP, bits = 0, result2 = [];
  for (idx = 0; idx < max; idx++) {
    if (idx % 4 === 0 && idx) {
      result2.push(bits >> 16 & 255);
      result2.push(bits >> 8 & 255);
      result2.push(bits & 255);
    }
    bits = bits << 6 | map22.indexOf(input.charAt(idx));
  }
  tailbits = max % 4 * 6;
  if (tailbits === 0) {
    result2.push(bits >> 16 & 255);
    result2.push(bits >> 8 & 255);
    result2.push(bits & 255);
  } else if (tailbits === 18) {
    result2.push(bits >> 10 & 255);
    result2.push(bits >> 2 & 255);
  } else if (tailbits === 12) {
    result2.push(bits >> 4 & 255);
  }
  return new Uint8Array(result2);
}
function representYamlBinary(object) {
  var result2 = "", bits = 0, idx, tail, max = object.length, map22 = BASE64_MAP;
  for (idx = 0; idx < max; idx++) {
    if (idx % 3 === 0 && idx) {
      result2 += map22[bits >> 18 & 63];
      result2 += map22[bits >> 12 & 63];
      result2 += map22[bits >> 6 & 63];
      result2 += map22[bits & 63];
    }
    bits = (bits << 8) + object[idx];
  }
  tail = max % 3;
  if (tail === 0) {
    result2 += map22[bits >> 18 & 63];
    result2 += map22[bits >> 12 & 63];
    result2 += map22[bits >> 6 & 63];
    result2 += map22[bits & 63];
  } else if (tail === 2) {
    result2 += map22[bits >> 10 & 63];
    result2 += map22[bits >> 4 & 63];
    result2 += map22[bits << 2 & 63];
    result2 += map22[64];
  } else if (tail === 1) {
    result2 += map22[bits >> 2 & 63];
    result2 += map22[bits << 4 & 63];
    result2 += map22[64];
    result2 += map22[64];
  }
  return result2;
}
function isBinary(obj) {
  return Object.prototype.toString.call(obj) === "[object Uint8Array]";
}
function resolveYamlOmap(data3) {
  if (data3 === null) return true;
  var objectKeys = [], index2, length, pair, pairKey, pairHasKey, object = data3;
  for (index2 = 0, length = object.length; index2 < length; index2 += 1) {
    pair = object[index2];
    pairHasKey = false;
    if (_toString$2.call(pair) !== "[object Object]") return false;
    for (pairKey in pair) {
      if (_hasOwnProperty$3.call(pair, pairKey)) {
        if (!pairHasKey) pairHasKey = true;
        else return false;
      }
    }
    if (!pairHasKey) return false;
    if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey);
    else return false;
  }
  return true;
}
function constructYamlOmap(data3) {
  return data3 !== null ? data3 : [];
}
function resolveYamlPairs(data3) {
  if (data3 === null) return true;
  var index2, length, pair, keys, result2, object = data3;
  result2 = new Array(object.length);
  for (index2 = 0, length = object.length; index2 < length; index2 += 1) {
    pair = object[index2];
    if (_toString$1.call(pair) !== "[object Object]") return false;
    keys = Object.keys(pair);
    if (keys.length !== 1) return false;
    result2[index2] = [keys[0], pair[keys[0]]];
  }
  return true;
}
function constructYamlPairs(data3) {
  if (data3 === null) return [];
  var index2, length, pair, keys, result2, object = data3;
  result2 = new Array(object.length);
  for (index2 = 0, length = object.length; index2 < length; index2 += 1) {
    pair = object[index2];
    keys = Object.keys(pair);
    result2[index2] = [keys[0], pair[keys[0]]];
  }
  return result2;
}
function resolveYamlSet(data3) {
  if (data3 === null) return true;
  var key, object = data3;
  for (key in object) {
    if (_hasOwnProperty$2.call(object, key)) {
      if (object[key] !== null) return false;
    }
  }
  return true;
}
function constructYamlSet(data3) {
  return data3 !== null ? data3 : {};
}
function _class(obj) {
  return Object.prototype.toString.call(obj);
}
function is_EOL(c6) {
  return c6 === 10 || c6 === 13;
}
function is_WHITE_SPACE(c6) {
  return c6 === 9 || c6 === 32;
}
function is_WS_OR_EOL(c6) {
  return c6 === 9 || c6 === 32 || c6 === 10 || c6 === 13;
}
function is_FLOW_INDICATOR(c6) {
  return c6 === 44 || c6 === 91 || c6 === 93 || c6 === 123 || c6 === 125;
}
function fromHexCode(c6) {
  var lc;
  if (48 <= c6 && c6 <= 57) {
    return c6 - 48;
  }
  lc = c6 | 32;
  if (97 <= lc && lc <= 102) {
    return lc - 97 + 10;
  }
  return -1;
}
function escapedHexLen(c6) {
  if (c6 === 120) {
    return 2;
  }
  if (c6 === 117) {
    return 4;
  }
  if (c6 === 85) {
    return 8;
  }
  return 0;
}
function fromDecimalCode(c6) {
  if (48 <= c6 && c6 <= 57) {
    return c6 - 48;
  }
  return -1;
}
function simpleEscapeSequence(c6) {
  return c6 === 48 ? "\0" : c6 === 97 ? "\x07" : c6 === 98 ? "\b" : c6 === 116 ? "	" : c6 === 9 ? "	" : c6 === 110 ? "\n" : c6 === 118 ? "\v" : c6 === 102 ? "\f" : c6 === 114 ? "\r" : c6 === 101 ? "\x1B" : c6 === 32 ? " " : c6 === 34 ? '"' : c6 === 47 ? "/" : c6 === 92 ? "\\" : c6 === 78 ? "\x85" : c6 === 95 ? "\xA0" : c6 === 76 ? "\u2028" : c6 === 80 ? "\u2029" : "";
}
function charFromCodepoint(c6) {
  if (c6 <= 65535) {
    return String.fromCharCode(c6);
  }
  return String.fromCharCode(
    (c6 - 65536 >> 10) + 55296,
    (c6 - 65536 & 1023) + 56320
  );
}
function State$1(input, options) {
  this.input = input;
  this.filename = options["filename"] || null;
  this.schema = options["schema"] || _default;
  this.onWarning = options["onWarning"] || null;
  this.legacy = options["legacy"] || false;
  this.json = options["json"] || false;
  this.listener = options["listener"] || null;
  this.implicitTypes = this.schema.compiledImplicit;
  this.typeMap = this.schema.compiledTypeMap;
  this.length = input.length;
  this.position = 0;
  this.line = 0;
  this.lineStart = 0;
  this.lineIndent = 0;
  this.firstTabInLine = -1;
  this.documents = [];
}
function generateError(state2, message) {
  var mark = {
    name: state2.filename,
    buffer: state2.input.slice(0, -1),
    position: state2.position,
    line: state2.line,
    column: state2.position - state2.lineStart
  };
  mark.snippet = snippet(mark);
  return new exception(message, mark);
}
function throwError(state2, message) {
  throw generateError(state2, message);
}
function throwWarning(state2, message) {
  if (state2.onWarning) {
    state2.onWarning.call(null, generateError(state2, message));
  }
}
function captureSegment(state2, start, end, checkJson) {
  var _position, _length, _character, _result;
  if (start < end) {
    _result = state2.input.slice(start, end);
    if (checkJson) {
      for (_position = 0, _length = _result.length; _position < _length; _position += 1) {
        _character = _result.charCodeAt(_position);
        if (!(_character === 9 || 32 <= _character && _character <= 1114111)) {
          throwError(state2, "expected valid JSON character");
        }
      }
    } else if (PATTERN_NON_PRINTABLE.test(_result)) {
      throwError(state2, "the stream contains non-printable characters");
    }
    state2.result += _result;
  }
}
function mergeMappings(state2, destination, source2, overridableKeys) {
  var sourceKeys, key, index2, quantity;
  if (!common2.isObject(source2)) {
    throwError(
      state2,
      "cannot merge mappings; the provided source object is unacceptable"
    );
  }
  sourceKeys = Object.keys(source2);
  for (index2 = 0, quantity = sourceKeys.length; index2 < quantity; index2 += 1) {
    key = sourceKeys[index2];
    if (!_hasOwnProperty$1.call(destination, key)) {
      destination[key] = source2[key];
      overridableKeys[key] = true;
    }
  }
}
function storeMappingPair(state2, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startLineStart, startPos) {
  var index2, quantity;
  if (Array.isArray(keyNode)) {
    keyNode = Array.prototype.slice.call(keyNode);
    for (index2 = 0, quantity = keyNode.length; index2 < quantity; index2 += 1) {
      if (Array.isArray(keyNode[index2])) {
        throwError(state2, "nested arrays are not supported inside keys");
      }
      if (typeof keyNode === "object" && _class(keyNode[index2]) === "[object Object]") {
        keyNode[index2] = "[object Object]";
      }
    }
  }
  if (typeof keyNode === "object" && _class(keyNode) === "[object Object]") {
    keyNode = "[object Object]";
  }
  keyNode = String(keyNode);
  if (_result === null) {
    _result = {};
  }
  if (keyTag === "tag:yaml.org,2002:merge") {
    if (Array.isArray(valueNode)) {
      for (index2 = 0, quantity = valueNode.length; index2 < quantity; index2 += 1) {
        mergeMappings(state2, _result, valueNode[index2], overridableKeys);
      }
    } else {
      mergeMappings(state2, _result, valueNode, overridableKeys);
    }
  } else {
    if (!state2.json && !_hasOwnProperty$1.call(overridableKeys, keyNode) && _hasOwnProperty$1.call(_result, keyNode)) {
      state2.line = startLine || state2.line;
      state2.lineStart = startLineStart || state2.lineStart;
      state2.position = startPos || state2.position;
      throwError(state2, "duplicated mapping key");
    }
    if (keyNode === "__proto__") {
      Object.defineProperty(_result, keyNode, {
        configurable: true,
        enumerable: true,
        writable: true,
        value: valueNode
      });
    } else {
      _result[keyNode] = valueNode;
    }
    delete overridableKeys[keyNode];
  }
  return _result;
}
function readLineBreak(state2) {
  var ch;
  ch = state2.input.charCodeAt(state2.position);
  if (ch === 10) {
    state2.position++;
  } else if (ch === 13) {
    state2.position++;
    if (state2.input.charCodeAt(state2.position) === 10) {
      state2.position++;
    }
  } else {
    throwError(state2, "a line break is expected");
  }
  state2.line += 1;
  state2.lineStart = state2.position;
  state2.firstTabInLine = -1;
}
function skipSeparationSpace(state2, allowComments, checkIndent) {
  var lineBreaks = 0, ch = state2.input.charCodeAt(state2.position);
  while (ch !== 0) {
    while (is_WHITE_SPACE(ch)) {
      if (ch === 9 && state2.firstTabInLine === -1) {
        state2.firstTabInLine = state2.position;
      }
      ch = state2.input.charCodeAt(++state2.position);
    }
    if (allowComments && ch === 35) {
      do {
        ch = state2.input.charCodeAt(++state2.position);
      } while (ch !== 10 && ch !== 13 && ch !== 0);
    }
    if (is_EOL(ch)) {
      readLineBreak(state2);
      ch = state2.input.charCodeAt(state2.position);
      lineBreaks++;
      state2.lineIndent = 0;
      while (ch === 32) {
        state2.lineIndent++;
        ch = state2.input.charCodeAt(++state2.position);
      }
    } else {
      break;
    }
  }
  if (checkIndent !== -1 && lineBreaks !== 0 && state2.lineIndent < checkIndent) {
    throwWarning(state2, "deficient indentation");
  }
  return lineBreaks;
}
function testDocumentSeparator(state2) {
  var _position = state2.position, ch;
  ch = state2.input.charCodeAt(_position);
  if ((ch === 45 || ch === 46) && ch === state2.input.charCodeAt(_position + 1) && ch === state2.input.charCodeAt(_position + 2)) {
    _position += 3;
    ch = state2.input.charCodeAt(_position);
    if (ch === 0 || is_WS_OR_EOL(ch)) {
      return true;
    }
  }
  return false;
}
function writeFoldedLines(state2, count) {
  if (count === 1) {
    state2.result += " ";
  } else if (count > 1) {
    state2.result += common2.repeat("\n", count - 1);
  }
}
function readPlainScalar(state2, nodeIndent, withinFlowCollection) {
  var preceding, following, captureStart, captureEnd, hasPendingContent, _line, _lineStart, _lineIndent, _kind = state2.kind, _result = state2.result, ch;
  ch = state2.input.charCodeAt(state2.position);
  if (is_WS_OR_EOL(ch) || is_FLOW_INDICATOR(ch) || ch === 35 || ch === 38 || ch === 42 || ch === 33 || ch === 124 || ch === 62 || ch === 39 || ch === 34 || ch === 37 || ch === 64 || ch === 96) {
    return false;
  }
  if (ch === 63 || ch === 45) {
    following = state2.input.charCodeAt(state2.position + 1);
    if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) {
      return false;
    }
  }
  state2.kind = "scalar";
  state2.result = "";
  captureStart = captureEnd = state2.position;
  hasPendingContent = false;
  while (ch !== 0) {
    if (ch === 58) {
      following = state2.input.charCodeAt(state2.position + 1);
      if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) {
        break;
      }
    } else if (ch === 35) {
      preceding = state2.input.charCodeAt(state2.position - 1);
      if (is_WS_OR_EOL(preceding)) {
        break;
      }
    } else if (state2.position === state2.lineStart && testDocumentSeparator(state2) || withinFlowCollection && is_FLOW_INDICATOR(ch)) {
      break;
    } else if (is_EOL(ch)) {
      _line = state2.line;
      _lineStart = state2.lineStart;
      _lineIndent = state2.lineIndent;
      skipSeparationSpace(state2, false, -1);
      if (state2.lineIndent >= nodeIndent) {
        hasPendingContent = true;
        ch = state2.input.charCodeAt(state2.position);
        continue;
      } else {
        state2.position = captureEnd;
        state2.line = _line;
        state2.lineStart = _lineStart;
        state2.lineIndent = _lineIndent;
        break;
      }
    }
    if (hasPendingContent) {
      captureSegment(state2, captureStart, captureEnd, false);
      writeFoldedLines(state2, state2.line - _line);
      captureStart = captureEnd = state2.position;
      hasPendingContent = false;
    }
    if (!is_WHITE_SPACE(ch)) {
      captureEnd = state2.position + 1;
    }
    ch = state2.input.charCodeAt(++state2.position);
  }
  captureSegment(state2, captureStart, captureEnd, false);
  if (state2.result) {
    return true;
  }
  state2.kind = _kind;
  state2.result = _result;
  return false;
}
function readSingleQuotedScalar(state2, nodeIndent) {
  var ch, captureStart, captureEnd;
  ch = state2.input.charCodeAt(state2.position);
  if (ch !== 39) {
    return false;
  }
  state2.kind = "scalar";
  state2.result = "";
  state2.position++;
  captureStart = captureEnd = state2.position;
  while ((ch = state2.input.charCodeAt(state2.position)) !== 0) {
    if (ch === 39) {
      captureSegment(state2, captureStart, state2.position, true);
      ch = state2.input.charCodeAt(++state2.position);
      if (ch === 39) {
        captureStart = state2.position;
        state2.position++;
        captureEnd = state2.position;
      } else {
        return true;
      }
    } else if (is_EOL(ch)) {
      captureSegment(state2, captureStart, captureEnd, true);
      writeFoldedLines(state2, skipSeparationSpace(state2, false, nodeIndent));
      captureStart = captureEnd = state2.position;
    } else if (state2.position === state2.lineStart && testDocumentSeparator(state2)) {
      throwError(
        state2,
        "unexpected end of the document within a single quoted scalar"
      );
    } else {
      state2.position++;
      captureEnd = state2.position;
    }
  }
  throwError(
    state2,
    "unexpected end of the stream within a single quoted scalar"
  );
}
function readDoubleQuotedScalar(state2, nodeIndent) {
  var captureStart, captureEnd, hexLength, hexResult, tmp, ch;
  ch = state2.input.charCodeAt(state2.position);
  if (ch !== 34) {
    return false;
  }
  state2.kind = "scalar";
  state2.result = "";
  state2.position++;
  captureStart = captureEnd = state2.position;
  while ((ch = state2.input.charCodeAt(state2.position)) !== 0) {
    if (ch === 34) {
      captureSegment(state2, captureStart, state2.position, true);
      state2.position++;
      return true;
    } else if (ch === 92) {
      captureSegment(state2, captureStart, state2.position, true);
      ch = state2.input.charCodeAt(++state2.position);
      if (is_EOL(ch)) {
        skipSeparationSpace(state2, false, nodeIndent);
      } else if (ch < 256 && simpleEscapeCheck[ch]) {
        state2.result += simpleEscapeMap[ch];
        state2.position++;
      } else if ((tmp = escapedHexLen(ch)) > 0) {
        hexLength = tmp;
        hexResult = 0;
        for (; hexLength > 0; hexLength--) {
          ch = state2.input.charCodeAt(++state2.position);
          if ((tmp = fromHexCode(ch)) >= 0) {
            hexResult = (hexResult << 4) + tmp;
          } else {
            throwError(state2, "expected hexadecimal character");
          }
        }
        state2.result += charFromCodepoint(hexResult);
        state2.position++;
      } else {
        throwError(state2, "unknown escape sequence");
      }
      captureStart = captureEnd = state2.position;
    } else if (is_EOL(ch)) {
      captureSegment(state2, captureStart, captureEnd, true);
      writeFoldedLines(state2, skipSeparationSpace(state2, false, nodeIndent));
      captureStart = captureEnd = state2.position;
    } else if (state2.position === state2.lineStart && testDocumentSeparator(state2)) {
      throwError(
        state2,
        "unexpected end of the document within a double quoted scalar"
      );
    } else {
      state2.position++;
      captureEnd = state2.position;
    }
  }
  throwError(
    state2,
    "unexpected end of the stream within a double quoted scalar"
  );
}
function readFlowCollection(state2, nodeIndent) {
  var readNext = true, _line, _lineStart, _pos, _tag = state2.tag, _result, _anchor = state2.anchor, following, terminator, isPair, isExplicitPair, isMapping, overridableKeys = /* @__PURE__ */ Object.create(null), keyNode, keyTag, valueNode, ch;
  ch = state2.input.charCodeAt(state2.position);
  if (ch === 91) {
    terminator = 93;
    isMapping = false;
    _result = [];
  } else if (ch === 123) {
    terminator = 125;
    isMapping = true;
    _result = {};
  } else {
    return false;
  }
  if (state2.anchor !== null) {
    state2.anchorMap[state2.anchor] = _result;
  }
  ch = state2.input.charCodeAt(++state2.position);
  while (ch !== 0) {
    skipSeparationSpace(state2, true, nodeIndent);
    ch = state2.input.charCodeAt(state2.position);
    if (ch === terminator) {
      state2.position++;
      state2.tag = _tag;
      state2.anchor = _anchor;
      state2.kind = isMapping ? "mapping" : "sequence";
      state2.result = _result;
      return true;
    } else if (!readNext) {
      throwError(state2, "missed comma between flow collection entries");
    } else if (ch === 44) {
      throwError(state2, "expected the node content, but found ','");
    }
    keyTag = keyNode = valueNode = null;
    isPair = isExplicitPair = false;
    if (ch === 63) {
      following = state2.input.charCodeAt(state2.position + 1);
      if (is_WS_OR_EOL(following)) {
        isPair = isExplicitPair = true;
        state2.position++;
        skipSeparationSpace(state2, true, nodeIndent);
      }
    }
    _line = state2.line;
    _lineStart = state2.lineStart;
    _pos = state2.position;
    composeNode(state2, nodeIndent, CONTEXT_FLOW_IN, false, true);
    keyTag = state2.tag;
    keyNode = state2.result;
    skipSeparationSpace(state2, true, nodeIndent);
    ch = state2.input.charCodeAt(state2.position);
    if ((isExplicitPair || state2.line === _line) && ch === 58) {
      isPair = true;
      ch = state2.input.charCodeAt(++state2.position);
      skipSeparationSpace(state2, true, nodeIndent);
      composeNode(state2, nodeIndent, CONTEXT_FLOW_IN, false, true);
      valueNode = state2.result;
    }
    if (isMapping) {
      storeMappingPair(
        state2,
        _result,
        overridableKeys,
        keyTag,
        keyNode,
        valueNode,
        _line,
        _lineStart,
        _pos
      );
    } else if (isPair) {
      _result.push(
        storeMappingPair(
          state2,
          null,
          overridableKeys,
          keyTag,
          keyNode,
          valueNode,
          _line,
          _lineStart,
          _pos
        )
      );
    } else {
      _result.push(keyNode);
    }
    skipSeparationSpace(state2, true, nodeIndent);
    ch = state2.input.charCodeAt(state2.position);
    if (ch === 44) {
      readNext = true;
      ch = state2.input.charCodeAt(++state2.position);
    } else {
      readNext = false;
    }
  }
  throwError(state2, "unexpected end of the stream within a flow collection");
}
function readBlockScalar(state2, nodeIndent) {
  var captureStart, folding, chomping = CHOMPING_CLIP, didReadContent = false, detectedIndent = false, textIndent = nodeIndent, emptyLines = 0, atMoreIndented = false, tmp, ch;
  ch = state2.input.charCodeAt(state2.position);
  if (ch === 124) {
    folding = false;
  } else if (ch === 62) {
    folding = true;
  } else {
    return false;
  }
  state2.kind = "scalar";
  state2.result = "";
  while (ch !== 0) {
    ch = state2.input.charCodeAt(++state2.position);
    if (ch === 43 || ch === 45) {
      if (CHOMPING_CLIP === chomping) {
        chomping = ch === 43 ? CHOMPING_KEEP : CHOMPING_STRIP;
      } else {
        throwError(state2, "repeat of a chomping mode identifier");
      }
    } else if ((tmp = fromDecimalCode(ch)) >= 0) {
      if (tmp === 0) {
        throwError(
          state2,
          "bad explicit indentation width of a block scalar; it cannot be less than one"
        );
      } else if (!detectedIndent) {
        textIndent = nodeIndent + tmp - 1;
        detectedIndent = true;
      } else {
        throwError(state2, "repeat of an indentation width identifier");
      }
    } else {
      break;
    }
  }
  if (is_WHITE_SPACE(ch)) {
    do {
      ch = state2.input.charCodeAt(++state2.position);
    } while (is_WHITE_SPACE(ch));
    if (ch === 35) {
      do {
        ch = state2.input.charCodeAt(++state2.position);
      } while (!is_EOL(ch) && ch !== 0);
    }
  }
  while (ch !== 0) {
    readLineBreak(state2);
    state2.lineIndent = 0;
    ch = state2.input.charCodeAt(state2.position);
    while ((!detectedIndent || state2.lineIndent < textIndent) && ch === 32) {
      state2.lineIndent++;
      ch = state2.input.charCodeAt(++state2.position);
    }
    if (!detectedIndent && state2.lineIndent > textIndent) {
      textIndent = state2.lineIndent;
    }
    if (is_EOL(ch)) {
      emptyLines++;
      continue;
    }
    if (state2.lineIndent < textIndent) {
      if (chomping === CHOMPING_KEEP) {
        state2.result += common2.repeat(
          "\n",
          didReadContent ? 1 + emptyLines : emptyLines
        );
      } else if (chomping === CHOMPING_CLIP) {
        if (didReadContent) {
          state2.result += "\n";
        }
      }
      break;
    }
    if (folding) {
      if (is_WHITE_SPACE(ch)) {
        atMoreIndented = true;
        state2.result += common2.repeat(
          "\n",
          didReadContent ? 1 + emptyLines : emptyLines
        );
      } else if (atMoreIndented) {
        atMoreIndented = false;
        state2.result += common2.repeat("\n", emptyLines + 1);
      } else if (emptyLines === 0) {
        if (didReadContent) {
          state2.result += " ";
        }
      } else {
        state2.result += common2.repeat("\n", emptyLines);
      }
    } else {
      state2.result += common2.repeat(
        "\n",
        didReadContent ? 1 + emptyLines : emptyLines
      );
    }
    didReadContent = true;
    detectedIndent = true;
    emptyLines = 0;
    captureStart = state2.position;
    while (!is_EOL(ch) && ch !== 0) {
      ch = state2.input.charCodeAt(++state2.position);
    }
    captureSegment(state2, captureStart, state2.position, false);
  }
  return true;
}
function readBlockSequence(state2, nodeIndent) {
  var _line, _tag = state2.tag, _anchor = state2.anchor, _result = [], following, detected = false, ch;
  if (state2.firstTabInLine !== -1) return false;
  if (state2.anchor !== null) {
    state2.anchorMap[state2.anchor] = _result;
  }
  ch = state2.input.charCodeAt(state2.position);
  while (ch !== 0) {
    if (state2.firstTabInLine !== -1) {
      state2.position = state2.firstTabInLine;
      throwError(state2, "tab characters must not be used in indentation");
    }
    if (ch !== 45) {
      break;
    }
    following = state2.input.charCodeAt(state2.position + 1);
    if (!is_WS_OR_EOL(following)) {
      break;
    }
    detected = true;
    state2.position++;
    if (skipSeparationSpace(state2, true, -1)) {
      if (state2.lineIndent <= nodeIndent) {
        _result.push(null);
        ch = state2.input.charCodeAt(state2.position);
        continue;
      }
    }
    _line = state2.line;
    composeNode(state2, nodeIndent, CONTEXT_BLOCK_IN, false, true);
    _result.push(state2.result);
    skipSeparationSpace(state2, true, -1);
    ch = state2.input.charCodeAt(state2.position);
    if ((state2.line === _line || state2.lineIndent > nodeIndent) && ch !== 0) {
      throwError(state2, "bad indentation of a sequence entry");
    } else if (state2.lineIndent < nodeIndent) {
      break;
    }
  }
  if (detected) {
    state2.tag = _tag;
    state2.anchor = _anchor;
    state2.kind = "sequence";
    state2.result = _result;
    return true;
  }
  return false;
}
function readBlockMapping(state2, nodeIndent, flowIndent) {
  var following, allowCompact, _line, _keyLine, _keyLineStart, _keyPos, _tag = state2.tag, _anchor = state2.anchor, _result = {}, overridableKeys = /* @__PURE__ */ Object.create(null), keyTag = null, keyNode = null, valueNode = null, atExplicitKey = false, detected = false, ch;
  if (state2.firstTabInLine !== -1) return false;
  if (state2.anchor !== null) {
    state2.anchorMap[state2.anchor] = _result;
  }
  ch = state2.input.charCodeAt(state2.position);
  while (ch !== 0) {
    if (!atExplicitKey && state2.firstTabInLine !== -1) {
      state2.position = state2.firstTabInLine;
      throwError(state2, "tab characters must not be used in indentation");
    }
    following = state2.input.charCodeAt(state2.position + 1);
    _line = state2.line;
    if ((ch === 63 || ch === 58) && is_WS_OR_EOL(following)) {
      if (ch === 63) {
        if (atExplicitKey) {
          storeMappingPair(
            state2,
            _result,
            overridableKeys,
            keyTag,
            keyNode,
            null,
            _keyLine,
            _keyLineStart,
            _keyPos
          );
          keyTag = keyNode = valueNode = null;
        }
        detected = true;
        atExplicitKey = true;
        allowCompact = true;
      } else if (atExplicitKey) {
        atExplicitKey = false;
        allowCompact = true;
      } else {
        throwError(
          state2,
          "incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line"
        );
      }
      state2.position += 1;
      ch = following;
    } else {
      _keyLine = state2.line;
      _keyLineStart = state2.lineStart;
      _keyPos = state2.position;
      if (!composeNode(state2, flowIndent, CONTEXT_FLOW_OUT, false, true)) {
        break;
      }
      if (state2.line === _line) {
        ch = state2.input.charCodeAt(state2.position);
        while (is_WHITE_SPACE(ch)) {
          ch = state2.input.charCodeAt(++state2.position);
        }
        if (ch === 58) {
          ch = state2.input.charCodeAt(++state2.position);
          if (!is_WS_OR_EOL(ch)) {
            throwError(
              state2,
              "a whitespace character is expected after the key-value separator within a block mapping"
            );
          }
          if (atExplicitKey) {
            storeMappingPair(
              state2,
              _result,
              overridableKeys,
              keyTag,
              keyNode,
              null,
              _keyLine,
              _keyLineStart,
              _keyPos
            );
            keyTag = keyNode = valueNode = null;
          }
          detected = true;
          atExplicitKey = false;
          allowCompact = false;
          keyTag = state2.tag;
          keyNode = state2.result;
        } else if (detected) {
          throwError(
            state2,
            "can not read an implicit mapping pair; a colon is missed"
          );
        } else {
          state2.tag = _tag;
          state2.anchor = _anchor;
          return true;
        }
      } else if (detected) {
        throwError(
          state2,
          "can not read a block mapping entry; a multiline key may not be an implicit key"
        );
      } else {
        state2.tag = _tag;
        state2.anchor = _anchor;
        return true;
      }
    }
    if (state2.line === _line || state2.lineIndent > nodeIndent) {
      if (atExplicitKey) {
        _keyLine = state2.line;
        _keyLineStart = state2.lineStart;
        _keyPos = state2.position;
      }
      if (composeNode(state2, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) {
        if (atExplicitKey) {
          keyNode = state2.result;
        } else {
          valueNode = state2.result;
        }
      }
      if (!atExplicitKey) {
        storeMappingPair(
          state2,
          _result,
          overridableKeys,
          keyTag,
          keyNode,
          valueNode,
          _keyLine,
          _keyLineStart,
          _keyPos
        );
        keyTag = keyNode = valueNode = null;
      }
      skipSeparationSpace(state2, true, -1);
      ch = state2.input.charCodeAt(state2.position);
    }
    if ((state2.line === _line || state2.lineIndent > nodeIndent) && ch !== 0) {
      throwError(state2, "bad indentation of a mapping entry");
    } else if (state2.lineIndent < nodeIndent) {
      break;
    }
  }
  if (atExplicitKey) {
    storeMappingPair(
      state2,
      _result,
      overridableKeys,
      keyTag,
      keyNode,
      null,
      _keyLine,
      _keyLineStart,
      _keyPos
    );
  }
  if (detected) {
    state2.tag = _tag;
    state2.anchor = _anchor;
    state2.kind = "mapping";
    state2.result = _result;
  }
  return detected;
}
function readTagProperty(state2) {
  var _position, isVerbatim = false, isNamed = false, tagHandle, tagName, ch;
  ch = state2.input.charCodeAt(state2.position);
  if (ch !== 33) return false;
  if (state2.tag !== null) {
    throwError(state2, "duplication of a tag property");
  }
  ch = state2.input.charCodeAt(++state2.position);
  if (ch === 60) {
    isVerbatim = true;
    ch = state2.input.charCodeAt(++state2.position);
  } else if (ch === 33) {
    isNamed = true;
    tagHandle = "!!";
    ch = state2.input.charCodeAt(++state2.position);
  } else {
    tagHandle = "!";
  }
  _position = state2.position;
  if (isVerbatim) {
    do {
      ch = state2.input.charCodeAt(++state2.position);
    } while (ch !== 0 && ch !== 62);
    if (state2.position < state2.length) {
      tagName = state2.input.slice(_position, state2.position);
      ch = state2.input.charCodeAt(++state2.position);
    } else {
      throwError(state2, "unexpected end of the stream within a verbatim tag");
    }
  } else {
    while (ch !== 0 && !is_WS_OR_EOL(ch)) {
      if (ch === 33) {
        if (!isNamed) {
          tagHandle = state2.input.slice(_position - 1, state2.position + 1);
          if (!PATTERN_TAG_HANDLE.test(tagHandle)) {
            throwError(
              state2,
              "named tag handle cannot contain such characters"
            );
          }
          isNamed = true;
          _position = state2.position + 1;
        } else {
          throwError(state2, "tag suffix cannot contain exclamation marks");
        }
      }
      ch = state2.input.charCodeAt(++state2.position);
    }
    tagName = state2.input.slice(_position, state2.position);
    if (PATTERN_FLOW_INDICATORS.test(tagName)) {
      throwError(state2, "tag suffix cannot contain flow indicator characters");
    }
  }
  if (tagName && !PATTERN_TAG_URI.test(tagName)) {
    throwError(state2, "tag name cannot contain such characters: " + tagName);
  }
  try {
    tagName = decodeURIComponent(tagName);
  } catch (err2) {
    throwError(state2, "tag name is malformed: " + tagName);
  }
  if (isVerbatim) {
    state2.tag = tagName;
  } else if (_hasOwnProperty$1.call(state2.tagMap, tagHandle)) {
    state2.tag = state2.tagMap[tagHandle] + tagName;
  } else if (tagHandle === "!") {
    state2.tag = "!" + tagName;
  } else if (tagHandle === "!!") {
    state2.tag = "tag:yaml.org,2002:" + tagName;
  } else {
    throwError(state2, 'undeclared tag handle "' + tagHandle + '"');
  }
  return true;
}
function readAnchorProperty(state2) {
  var _position, ch;
  ch = state2.input.charCodeAt(state2.position);
  if (ch !== 38) return false;
  if (state2.anchor !== null) {
    throwError(state2, "duplication of an anchor property");
  }
  ch = state2.input.charCodeAt(++state2.position);
  _position = state2.position;
  while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
    ch = state2.input.charCodeAt(++state2.position);
  }
  if (state2.position === _position) {
    throwError(
      state2,
      "name of an anchor node must contain at least one character"
    );
  }
  state2.anchor = state2.input.slice(_position, state2.position);
  return true;
}
function readAlias(state2) {
  var _position, alias, ch;
  ch = state2.input.charCodeAt(state2.position);
  if (ch !== 42) return false;
  ch = state2.input.charCodeAt(++state2.position);
  _position = state2.position;
  while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
    ch = state2.input.charCodeAt(++state2.position);
  }
  if (state2.position === _position) {
    throwError(
      state2,
      "name of an alias node must contain at least one character"
    );
  }
  alias = state2.input.slice(_position, state2.position);
  if (!_hasOwnProperty$1.call(state2.anchorMap, alias)) {
    throwError(state2, 'unidentified alias "' + alias + '"');
  }
  state2.result = state2.anchorMap[alias];
  skipSeparationSpace(state2, true, -1);
  return true;
}
function composeNode(state2, parentIndent, nodeContext, allowToSeek, allowCompact) {
  var allowBlockStyles, allowBlockScalars, allowBlockCollections, indentStatus = 1, atNewLine = false, hasContent = false, typeIndex, typeQuantity, typeList, type22, flowIndent, blockIndent;
  if (state2.listener !== null) {
    state2.listener("open", state2);
  }
  state2.tag = null;
  state2.anchor = null;
  state2.kind = null;
  state2.result = null;
  allowBlockStyles = allowBlockScalars = allowBlockCollections = CONTEXT_BLOCK_OUT === nodeContext || CONTEXT_BLOCK_IN === nodeContext;
  if (allowToSeek) {
    if (skipSeparationSpace(state2, true, -1)) {
      atNewLine = true;
      if (state2.lineIndent > parentIndent) {
        indentStatus = 1;
      } else if (state2.lineIndent === parentIndent) {
        indentStatus = 0;
      } else if (state2.lineIndent < parentIndent) {
        indentStatus = -1;
      }
    }
  }
  if (indentStatus === 1) {
    while (readTagProperty(state2) || readAnchorProperty(state2)) {
      if (skipSeparationSpace(state2, true, -1)) {
        atNewLine = true;
        allowBlockCollections = allowBlockStyles;
        if (state2.lineIndent > parentIndent) {
          indentStatus = 1;
        } else if (state2.lineIndent === parentIndent) {
          indentStatus = 0;
        } else if (state2.lineIndent < parentIndent) {
          indentStatus = -1;
        }
      } else {
        allowBlockCollections = false;
      }
    }
  }
  if (allowBlockCollections) {
    allowBlockCollections = atNewLine || allowCompact;
  }
  if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) {
    if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) {
      flowIndent = parentIndent;
    } else {
      flowIndent = parentIndent + 1;
    }
    blockIndent = state2.position - state2.lineStart;
    if (indentStatus === 1) {
      if (allowBlockCollections && (readBlockSequence(state2, blockIndent) || readBlockMapping(state2, blockIndent, flowIndent)) || readFlowCollection(state2, flowIndent)) {
        hasContent = true;
      } else {
        if (allowBlockScalars && readBlockScalar(state2, flowIndent) || readSingleQuotedScalar(state2, flowIndent) || readDoubleQuotedScalar(state2, flowIndent)) {
          hasContent = true;
        } else if (readAlias(state2)) {
          hasContent = true;
          if (state2.tag !== null || state2.anchor !== null) {
            throwError(state2, "alias node should not have any properties");
          }
        } else if (readPlainScalar(state2, flowIndent, CONTEXT_FLOW_IN === nodeContext)) {
          hasContent = true;
          if (state2.tag === null) {
            state2.tag = "?";
          }
        }
        if (state2.anchor !== null) {
          state2.anchorMap[state2.anchor] = state2.result;
        }
      }
    } else if (indentStatus === 0) {
      hasContent = allowBlockCollections && readBlockSequence(state2, blockIndent);
    }
  }
  if (state2.tag === null) {
    if (state2.anchor !== null) {
      state2.anchorMap[state2.anchor] = state2.result;
    }
  } else if (state2.tag === "?") {
    if (state2.result !== null && state2.kind !== "scalar") {
      throwError(
        state2,
        'unacceptable node kind for !<?> tag; it should be "scalar", not "' + state2.kind + '"'
      );
    }
    for (typeIndex = 0, typeQuantity = state2.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) {
      type22 = state2.implicitTypes[typeIndex];
      if (type22.resolve(state2.result)) {
        state2.result = type22.construct(state2.result);
        state2.tag = type22.tag;
        if (state2.anchor !== null) {
          state2.anchorMap[state2.anchor] = state2.result;
        }
        break;
      }
    }
  } else if (state2.tag !== "!") {
    if (_hasOwnProperty$1.call(state2.typeMap[state2.kind || "fallback"], state2.tag)) {
      type22 = state2.typeMap[state2.kind || "fallback"][state2.tag];
    } else {
      type22 = null;
      typeList = state2.typeMap.multi[state2.kind || "fallback"];
      for (typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) {
        if (state2.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) {
          type22 = typeList[typeIndex];
          break;
        }
      }
    }
    if (!type22) {
      throwError(state2, "unknown tag !<" + state2.tag + ">");
    }
    if (state2.result !== null && type22.kind !== state2.kind) {
      throwError(
        state2,
        "unacceptable node kind for !<" + state2.tag + '> tag; it should be "' + type22.kind + '", not "' + state2.kind + '"'
      );
    }
    if (!type22.resolve(state2.result, state2.tag)) {
      throwError(
        state2,
        "cannot resolve a node with !<" + state2.tag + "> explicit tag"
      );
    } else {
      state2.result = type22.construct(state2.result, state2.tag);
      if (state2.anchor !== null) {
        state2.anchorMap[state2.anchor] = state2.result;
      }
    }
  }
  if (state2.listener !== null) {
    state2.listener("close", state2);
  }
  return state2.tag !== null || state2.anchor !== null || hasContent;
}
function readDocument(state2) {
  var documentStart = state2.position, _position, directiveName, directiveArgs, hasDirectives = false, ch;
  state2.version = null;
  state2.checkLineBreaks = state2.legacy;
  state2.tagMap = /* @__PURE__ */ Object.create(null);
  state2.anchorMap = /* @__PURE__ */ Object.create(null);
  while ((ch = state2.input.charCodeAt(state2.position)) !== 0) {
    skipSeparationSpace(state2, true, -1);
    ch = state2.input.charCodeAt(state2.position);
    if (state2.lineIndent > 0 || ch !== 37) {
      break;
    }
    hasDirectives = true;
    ch = state2.input.charCodeAt(++state2.position);
    _position = state2.position;
    while (ch !== 0 && !is_WS_OR_EOL(ch)) {
      ch = state2.input.charCodeAt(++state2.position);
    }
    directiveName = state2.input.slice(_position, state2.position);
    directiveArgs = [];
    if (directiveName.length < 1) {
      throwError(
        state2,
        "directive name must not be less than one character in length"
      );
    }
    while (ch !== 0) {
      while (is_WHITE_SPACE(ch)) {
        ch = state2.input.charCodeAt(++state2.position);
      }
      if (ch === 35) {
        do {
          ch = state2.input.charCodeAt(++state2.position);
        } while (ch !== 0 && !is_EOL(ch));
        break;
      }
      if (is_EOL(ch)) break;
      _position = state2.position;
      while (ch !== 0 && !is_WS_OR_EOL(ch)) {
        ch = state2.input.charCodeAt(++state2.position);
      }
      directiveArgs.push(state2.input.slice(_position, state2.position));
    }
    if (ch !== 0) readLineBreak(state2);
    if (_hasOwnProperty$1.call(directiveHandlers, directiveName)) {
      directiveHandlers[directiveName](state2, directiveName, directiveArgs);
    } else {
      throwWarning(state2, 'unknown document directive "' + directiveName + '"');
    }
  }
  skipSeparationSpace(state2, true, -1);
  if (state2.lineIndent === 0 && state2.input.charCodeAt(state2.position) === 45 && state2.input.charCodeAt(state2.position + 1) === 45 && state2.input.charCodeAt(state2.position + 2) === 45) {
    state2.position += 3;
    skipSeparationSpace(state2, true, -1);
  } else if (hasDirectives) {
    throwError(state2, "directives end mark is expected");
  }
  composeNode(state2, state2.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true);
  skipSeparationSpace(state2, true, -1);
  if (state2.checkLineBreaks && PATTERN_NON_ASCII_LINE_BREAKS.test(
    state2.input.slice(documentStart, state2.position)
  )) {
    throwWarning(state2, "non-ASCII line breaks are interpreted as content");
  }
  state2.documents.push(state2.result);
  if (state2.position === state2.lineStart && testDocumentSeparator(state2)) {
    if (state2.input.charCodeAt(state2.position) === 46) {
      state2.position += 3;
      skipSeparationSpace(state2, true, -1);
    }
    return;
  }
  if (state2.position < state2.length - 1) {
    throwError(state2, "end of the stream or a document separator is expected");
  } else {
    return;
  }
}
function loadDocuments(input, options) {
  input = String(input);
  options = options || {};
  if (input.length !== 0) {
    if (input.charCodeAt(input.length - 1) !== 10 && input.charCodeAt(input.length - 1) !== 13) {
      input += "\n";
    }
    if (input.charCodeAt(0) === 65279) {
      input = input.slice(1);
    }
  }
  var state2 = new State$1(input, options);
  var nullpos = input.indexOf("\0");
  if (nullpos !== -1) {
    state2.position = nullpos;
    throwError(state2, "null byte is not allowed in input");
  }
  state2.input += "\0";
  while (state2.input.charCodeAt(state2.position) === 32) {
    state2.lineIndent += 1;
    state2.position += 1;
  }
  while (state2.position < state2.length - 1) {
    readDocument(state2);
  }
  return state2.documents;
}
function loadAll$1(input, iterator, options) {
  if (iterator !== null && typeof iterator === "object" && typeof options === "undefined") {
    options = iterator;
    iterator = null;
  }
  var documents = loadDocuments(input, options);
  if (typeof iterator !== "function") {
    return documents;
  }
  for (var index2 = 0, length = documents.length; index2 < length; index2 += 1) {
    iterator(documents[index2]);
  }
}
function load$1(input, options) {
  var documents = loadDocuments(input, options);
  if (documents.length === 0) {
    return void 0;
  } else if (documents.length === 1) {
    return documents[0];
  }
  throw new exception(
    "expected a single document in the stream, but found more"
  );
}
function compileStyleMap(schema22, map22) {
  var result2, keys, index2, length, tag, style, type22;
  if (map22 === null) return {};
  result2 = {};
  keys = Object.keys(map22);
  for (index2 = 0, length = keys.length; index2 < length; index2 += 1) {
    tag = keys[index2];
    style = String(map22[tag]);
    if (tag.slice(0, 2) === "!!") {
      tag = "tag:yaml.org,2002:" + tag.slice(2);
    }
    type22 = schema22.compiledTypeMap["fallback"][tag];
    if (type22 && _hasOwnProperty.call(type22.styleAliases, style)) {
      style = type22.styleAliases[style];
    }
    result2[tag] = style;
  }
  return result2;
}
function encodeHex(character) {
  var string2, handle, length;
  string2 = character.toString(16).toUpperCase();
  if (character <= 255) {
    handle = "x";
    length = 2;
  } else if (character <= 65535) {
    handle = "u";
    length = 4;
  } else if (character <= 4294967295) {
    handle = "U";
    length = 8;
  } else {
    throw new exception(
      "code point within a string may not be greater than 0xFFFFFFFF"
    );
  }
  return "\\" + handle + common2.repeat("0", length - string2.length) + string2;
}
function State(options) {
  this.schema = options["schema"] || _default;
  this.indent = Math.max(1, options["indent"] || 2);
  this.noArrayIndent = options["noArrayIndent"] || false;
  this.skipInvalid = options["skipInvalid"] || false;
  this.flowLevel = common2.isNothing(options["flowLevel"]) ? -1 : options["flowLevel"];
  this.styleMap = compileStyleMap(this.schema, options["styles"] || null);
  this.sortKeys = options["sortKeys"] || false;
  this.lineWidth = options["lineWidth"] || 80;
  this.noRefs = options["noRefs"] || false;
  this.noCompatMode = options["noCompatMode"] || false;
  this.condenseFlow = options["condenseFlow"] || false;
  this.quotingType = options["quotingType"] === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE;
  this.forceQuotes = options["forceQuotes"] || false;
  this.replacer = typeof options["replacer"] === "function" ? options["replacer"] : null;
  this.implicitTypes = this.schema.compiledImplicit;
  this.explicitTypes = this.schema.compiledExplicit;
  this.tag = null;
  this.result = "";
  this.duplicates = [];
  this.usedDuplicates = null;
}
function indentString(string2, spaces) {
  var ind = common2.repeat(" ", spaces), position = 0, next = -1, result2 = "", line, length = string2.length;
  while (position < length) {
    next = string2.indexOf("\n", position);
    if (next === -1) {
      line = string2.slice(position);
      position = length;
    } else {
      line = string2.slice(position, next + 1);
      position = next + 1;
    }
    if (line.length && line !== "\n") result2 += ind;
    result2 += line;
  }
  return result2;
}
function generateNextLine(state2, level) {
  return "\n" + common2.repeat(" ", state2.indent * level);
}
function testImplicitResolving(state2, str22) {
  var index2, length, type22;
  for (index2 = 0, length = state2.implicitTypes.length; index2 < length; index2 += 1) {
    type22 = state2.implicitTypes[index2];
    if (type22.resolve(str22)) {
      return true;
    }
  }
  return false;
}
function isWhitespace(c6) {
  return c6 === CHAR_SPACE || c6 === CHAR_TAB;
}
function isPrintable(c6) {
  return 32 <= c6 && c6 <= 126 || 161 <= c6 && c6 <= 55295 && c6 !== 8232 && c6 !== 8233 || 57344 <= c6 && c6 <= 65533 && c6 !== CHAR_BOM || 65536 <= c6 && c6 <= 1114111;
}
function isNsCharOrWhitespace(c6) {
  return isPrintable(c6) && c6 !== CHAR_BOM && c6 !== CHAR_CARRIAGE_RETURN && c6 !== CHAR_LINE_FEED;
}
function isPlainSafe(c6, prev, inblock) {
  var cIsNsCharOrWhitespace = isNsCharOrWhitespace(c6);
  var cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c6);
  return (inblock ? cIsNsCharOrWhitespace : cIsNsCharOrWhitespace && c6 !== CHAR_COMMA && c6 !== CHAR_LEFT_SQUARE_BRACKET && c6 !== CHAR_RIGHT_SQUARE_BRACKET && c6 !== CHAR_LEFT_CURLY_BRACKET && c6 !== CHAR_RIGHT_CURLY_BRACKET) && c6 !== CHAR_SHARP && !(prev === CHAR_COLON2 && !cIsNsChar) || isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c6 === CHAR_SHARP || prev === CHAR_COLON2 && cIsNsChar;
}
function isPlainSafeFirst(c6) {
  return isPrintable(c6) && c6 !== CHAR_BOM && !isWhitespace(c6) && c6 !== CHAR_MINUS && c6 !== CHAR_QUESTION && c6 !== CHAR_COLON2 && c6 !== CHAR_COMMA && c6 !== CHAR_LEFT_SQUARE_BRACKET && c6 !== CHAR_RIGHT_SQUARE_BRACKET && c6 !== CHAR_LEFT_CURLY_BRACKET && c6 !== CHAR_RIGHT_CURLY_BRACKET && c6 !== CHAR_SHARP && c6 !== CHAR_AMPERSAND && c6 !== CHAR_ASTERISK && c6 !== CHAR_EXCLAMATION && c6 !== CHAR_VERTICAL_LINE && c6 !== CHAR_EQUALS && c6 !== CHAR_GREATER_THAN && c6 !== CHAR_SINGLE_QUOTE && c6 !== CHAR_DOUBLE_QUOTE && c6 !== CHAR_PERCENT && c6 !== CHAR_COMMERCIAL_AT && c6 !== CHAR_GRAVE_ACCENT;
}
function isPlainSafeLast(c6) {
  return !isWhitespace(c6) && c6 !== CHAR_COLON2;
}
function codePointAt(string2, pos) {
  var first = string2.charCodeAt(pos), second;
  if (first >= 55296 && first <= 56319 && pos + 1 < string2.length) {
    second = string2.charCodeAt(pos + 1);
    if (second >= 56320 && second <= 57343) {
      return (first - 55296) * 1024 + second - 56320 + 65536;
    }
  }
  return first;
}
function needIndentIndicator(string2) {
  var leadingSpaceRe = /^\n* /;
  return leadingSpaceRe.test(string2);
}
function chooseScalarStyle(string2, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType, quotingType, forceQuotes, inblock) {
  var i6;
  var char = 0;
  var prevChar = null;
  var hasLineBreak = false;
  var hasFoldableLine = false;
  var shouldTrackWidth = lineWidth !== -1;
  var previousLineBreak = -1;
  var plain = isPlainSafeFirst(codePointAt(string2, 0)) && isPlainSafeLast(codePointAt(string2, string2.length - 1));
  if (singleLineOnly || forceQuotes) {
    for (i6 = 0; i6 < string2.length; char >= 65536 ? i6 += 2 : i6++) {
      char = codePointAt(string2, i6);
      if (!isPrintable(char)) {
        return STYLE_DOUBLE;
      }
      plain = plain && isPlainSafe(char, prevChar, inblock);
      prevChar = char;
    }
  } else {
    for (i6 = 0; i6 < string2.length; char >= 65536 ? i6 += 2 : i6++) {
      char = codePointAt(string2, i6);
      if (char === CHAR_LINE_FEED) {
        hasLineBreak = true;
        if (shouldTrackWidth) {
          hasFoldableLine = hasFoldableLine || i6 - previousLineBreak - 1 > lineWidth && string2[previousLineBreak + 1] !== " ";
          previousLineBreak = i6;
        }
      } else if (!isPrintable(char)) {
        return STYLE_DOUBLE;
      }
      plain = plain && isPlainSafe(char, prevChar, inblock);
      prevChar = char;
    }
    hasFoldableLine = hasFoldableLine || shouldTrackWidth && i6 - previousLineBreak - 1 > lineWidth && string2[previousLineBreak + 1] !== " ";
  }
  if (!hasLineBreak && !hasFoldableLine) {
    if (plain && !forceQuotes && !testAmbiguousType(string2)) {
      return STYLE_PLAIN;
    }
    return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;
  }
  if (indentPerLevel > 9 && needIndentIndicator(string2)) {
    return STYLE_DOUBLE;
  }
  if (!forceQuotes) {
    return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;
  }
  return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;
}
function writeScalar(state2, string2, level, iskey, inblock) {
  state2.dump = (function() {
    if (string2.length === 0) {
      return state2.quotingType === QUOTING_TYPE_DOUBLE ? '""' : "''";
    }
    if (!state2.noCompatMode) {
      if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string2) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string2)) {
        return state2.quotingType === QUOTING_TYPE_DOUBLE ? '"' + string2 + '"' : "'" + string2 + "'";
      }
    }
    var indent = state2.indent * Math.max(1, level);
    var lineWidth = state2.lineWidth === -1 ? -1 : Math.max(Math.min(state2.lineWidth, 40), state2.lineWidth - indent);
    var singleLineOnly = iskey || state2.flowLevel > -1 && level >= state2.flowLevel;
    function testAmbiguity(string22) {
      return testImplicitResolving(state2, string22);
    }
    switch (chooseScalarStyle(
      string2,
      singleLineOnly,
      state2.indent,
      lineWidth,
      testAmbiguity,
      state2.quotingType,
      state2.forceQuotes && !iskey,
      inblock
    )) {
      case STYLE_PLAIN:
        return string2;
      case STYLE_SINGLE:
        return "'" + string2.replace(/'/g, "''") + "'";
      case STYLE_LITERAL:
        return "|" + blockHeader(string2, state2.indent) + dropEndingNewline(indentString(string2, indent));
      case STYLE_FOLDED:
        return ">" + blockHeader(string2, state2.indent) + dropEndingNewline(indentString(foldString(string2, lineWidth), indent));
      case STYLE_DOUBLE:
        return '"' + escapeString(string2) + '"';
      default:
        throw new exception("impossible error: invalid scalar style");
    }
  })();
}
function blockHeader(string2, indentPerLevel) {
  var indentIndicator = needIndentIndicator(string2) ? String(indentPerLevel) : "";
  var clip = string2[string2.length - 1] === "\n";
  var keep = clip && (string2[string2.length - 2] === "\n" || string2 === "\n");
  var chomp = keep ? "+" : clip ? "" : "-";
  return indentIndicator + chomp + "\n";
}
function dropEndingNewline(string2) {
  return string2[string2.length - 1] === "\n" ? string2.slice(0, -1) : string2;
}
function foldString(string2, width) {
  var lineRe = /(\n+)([^\n]*)/g;
  var result2 = (function() {
    var nextLF = string2.indexOf("\n");
    nextLF = nextLF !== -1 ? nextLF : string2.length;
    lineRe.lastIndex = nextLF;
    return foldLine(string2.slice(0, nextLF), width);
  })();
  var prevMoreIndented = string2[0] === "\n" || string2[0] === " ";
  var moreIndented;
  var match;
  while (match = lineRe.exec(string2)) {
    var prefix = match[1], line = match[2];
    moreIndented = line[0] === " ";
    result2 += prefix + (!prevMoreIndented && !moreIndented && line !== "" ? "\n" : "") + foldLine(line, width);
    prevMoreIndented = moreIndented;
  }
  return result2;
}
function foldLine(line, width) {
  if (line === "" || line[0] === " ") return line;
  var breakRe = / [^ ]/g;
  var match;
  var start = 0, end, curr = 0, next = 0;
  var result2 = "";
  while (match = breakRe.exec(line)) {
    next = match.index;
    if (next - start > width) {
      end = curr > start ? curr : next;
      result2 += "\n" + line.slice(start, end);
      start = end + 1;
    }
    curr = next;
  }
  result2 += "\n";
  if (line.length - start > width && curr > start) {
    result2 += line.slice(start, curr) + "\n" + line.slice(curr + 1);
  } else {
    result2 += line.slice(start);
  }
  return result2.slice(1);
}
function escapeString(string2) {
  var result2 = "";
  var char = 0;
  var escapeSeq;
  for (var i6 = 0; i6 < string2.length; char >= 65536 ? i6 += 2 : i6++) {
    char = codePointAt(string2, i6);
    escapeSeq = ESCAPE_SEQUENCES[char];
    if (!escapeSeq && isPrintable(char)) {
      result2 += string2[i6];
      if (char >= 65536) result2 += string2[i6 + 1];
    } else {
      result2 += escapeSeq || encodeHex(char);
    }
  }
  return result2;
}
function writeFlowSequence(state2, level, object) {
  var _result = "", _tag = state2.tag, index2, length, value;
  for (index2 = 0, length = object.length; index2 < length; index2 += 1) {
    value = object[index2];
    if (state2.replacer) {
      value = state2.replacer.call(object, String(index2), value);
    }
    if (writeNode(state2, level, value, false, false) || typeof value === "undefined" && writeNode(state2, level, null, false, false)) {
      if (_result !== "") _result += "," + (!state2.condenseFlow ? " " : "");
      _result += state2.dump;
    }
  }
  state2.tag = _tag;
  state2.dump = "[" + _result + "]";
}
function writeBlockSequence(state2, level, object, compact) {
  var _result = "", _tag = state2.tag, index2, length, value;
  for (index2 = 0, length = object.length; index2 < length; index2 += 1) {
    value = object[index2];
    if (state2.replacer) {
      value = state2.replacer.call(object, String(index2), value);
    }
    if (writeNode(state2, level + 1, value, true, true, false, true) || typeof value === "undefined" && writeNode(state2, level + 1, null, true, true, false, true)) {
      if (!compact || _result !== "") {
        _result += generateNextLine(state2, level);
      }
      if (state2.dump && CHAR_LINE_FEED === state2.dump.charCodeAt(0)) {
        _result += "-";
      } else {
        _result += "- ";
      }
      _result += state2.dump;
    }
  }
  state2.tag = _tag;
  state2.dump = _result || "[]";
}
function writeFlowMapping(state2, level, object) {
  var _result = "", _tag = state2.tag, objectKeyList = Object.keys(object), index2, length, objectKey, objectValue, pairBuffer;
  for (index2 = 0, length = objectKeyList.length; index2 < length; index2 += 1) {
    pairBuffer = "";
    if (_result !== "") pairBuffer += ", ";
    if (state2.condenseFlow) pairBuffer += '"';
    objectKey = objectKeyList[index2];
    objectValue = object[objectKey];
    if (state2.replacer) {
      objectValue = state2.replacer.call(object, objectKey, objectValue);
    }
    if (!writeNode(state2, level, objectKey, false, false)) {
      continue;
    }
    if (state2.dump.length > 1024) pairBuffer += "? ";
    pairBuffer += state2.dump + (state2.condenseFlow ? '"' : "") + ":" + (state2.condenseFlow ? "" : " ");
    if (!writeNode(state2, level, objectValue, false, false)) {
      continue;
    }
    pairBuffer += state2.dump;
    _result += pairBuffer;
  }
  state2.tag = _tag;
  state2.dump = "{" + _result + "}";
}
function writeBlockMapping(state2, level, object, compact) {
  var _result = "", _tag = state2.tag, objectKeyList = Object.keys(object), index2, length, objectKey, objectValue, explicitPair, pairBuffer;
  if (state2.sortKeys === true) {
    objectKeyList.sort();
  } else if (typeof state2.sortKeys === "function") {
    objectKeyList.sort(state2.sortKeys);
  } else if (state2.sortKeys) {
    throw new exception("sortKeys must be a boolean or a function");
  }
  for (index2 = 0, length = objectKeyList.length; index2 < length; index2 += 1) {
    pairBuffer = "";
    if (!compact || _result !== "") {
      pairBuffer += generateNextLine(state2, level);
    }
    objectKey = objectKeyList[index2];
    objectValue = object[objectKey];
    if (state2.replacer) {
      objectValue = state2.replacer.call(object, objectKey, objectValue);
    }
    if (!writeNode(state2, level + 1, objectKey, true, true, true)) {
      continue;
    }
    explicitPair = state2.tag !== null && state2.tag !== "?" || state2.dump && state2.dump.length > 1024;
    if (explicitPair) {
      if (state2.dump && CHAR_LINE_FEED === state2.dump.charCodeAt(0)) {
        pairBuffer += "?";
      } else {
        pairBuffer += "? ";
      }
    }
    pairBuffer += state2.dump;
    if (explicitPair) {
      pairBuffer += generateNextLine(state2, level);
    }
    if (!writeNode(state2, level + 1, objectValue, true, explicitPair)) {
      continue;
    }
    if (state2.dump && CHAR_LINE_FEED === state2.dump.charCodeAt(0)) {
      pairBuffer += ":";
    } else {
      pairBuffer += ": ";
    }
    pairBuffer += state2.dump;
    _result += pairBuffer;
  }
  state2.tag = _tag;
  state2.dump = _result || "{}";
}
function detectType(state2, object, explicit) {
  var _result, typeList, index2, length, type22, style;
  typeList = explicit ? state2.explicitTypes : state2.implicitTypes;
  for (index2 = 0, length = typeList.length; index2 < length; index2 += 1) {
    type22 = typeList[index2];
    if ((type22.instanceOf || type22.predicate) && (!type22.instanceOf || typeof object === "object" && object instanceof type22.instanceOf) && (!type22.predicate || type22.predicate(object))) {
      if (explicit) {
        if (type22.multi && type22.representName) {
          state2.tag = type22.representName(object);
        } else {
          state2.tag = type22.tag;
        }
      } else {
        state2.tag = "?";
      }
      if (type22.represent) {
        style = state2.styleMap[type22.tag] || type22.defaultStyle;
        if (_toString.call(type22.represent) === "[object Function]") {
          _result = type22.represent(object, style);
        } else if (_hasOwnProperty.call(type22.represent, style)) {
          _result = type22.represent[style](object, style);
        } else {
          throw new exception(
            "!<" + type22.tag + '> tag resolver accepts not "' + style + '" style'
          );
        }
        state2.dump = _result;
      }
      return true;
    }
  }
  return false;
}
function writeNode(state2, level, object, block, compact, iskey, isblockseq) {
  state2.tag = null;
  state2.dump = object;
  if (!detectType(state2, object, false)) {
    detectType(state2, object, true);
  }
  var type22 = _toString.call(state2.dump);
  var inblock = block;
  var tagStr;
  if (block) {
    block = state2.flowLevel < 0 || state2.flowLevel > level;
  }
  var objectOrArray = type22 === "[object Object]" || type22 === "[object Array]", duplicateIndex, duplicate;
  if (objectOrArray) {
    duplicateIndex = state2.duplicates.indexOf(object);
    duplicate = duplicateIndex !== -1;
  }
  if (state2.tag !== null && state2.tag !== "?" || duplicate || state2.indent !== 2 && level > 0) {
    compact = false;
  }
  if (duplicate && state2.usedDuplicates[duplicateIndex]) {
    state2.dump = "*ref_" + duplicateIndex;
  } else {
    if (objectOrArray && duplicate && !state2.usedDuplicates[duplicateIndex]) {
      state2.usedDuplicates[duplicateIndex] = true;
    }
    if (type22 === "[object Object]") {
      if (block && Object.keys(state2.dump).length !== 0) {
        writeBlockMapping(state2, level, state2.dump, compact);
        if (duplicate) {
          state2.dump = "&ref_" + duplicateIndex + state2.dump;
        }
      } else {
        writeFlowMapping(state2, level, state2.dump);
        if (duplicate) {
          state2.dump = "&ref_" + duplicateIndex + " " + state2.dump;
        }
      }
    } else if (type22 === "[object Array]") {
      if (block && state2.dump.length !== 0) {
        if (state2.noArrayIndent && !isblockseq && level > 0) {
          writeBlockSequence(state2, level - 1, state2.dump, compact);
        } else {
          writeBlockSequence(state2, level, state2.dump, compact);
        }
        if (duplicate) {
          state2.dump = "&ref_" + duplicateIndex + state2.dump;
        }
      } else {
        writeFlowSequence(state2, level, state2.dump);
        if (duplicate) {
          state2.dump = "&ref_" + duplicateIndex + " " + state2.dump;
        }
      }
    } else if (type22 === "[object String]") {
      if (state2.tag !== "?") {
        writeScalar(state2, state2.dump, level, iskey, inblock);
      }
    } else if (type22 === "[object Undefined]") {
      return false;
    } else {
      if (state2.skipInvalid) return false;
      throw new exception("unacceptable kind of an object to dump " + type22);
    }
    if (state2.tag !== null && state2.tag !== "?") {
      tagStr = encodeURI(
        state2.tag[0] === "!" ? state2.tag.slice(1) : state2.tag
      ).replace(/!/g, "%21");
      if (state2.tag[0] === "!") {
        tagStr = "!" + tagStr;
      } else if (tagStr.slice(0, 18) === "tag:yaml.org,2002:") {
        tagStr = "!!" + tagStr.slice(18);
      } else {
        tagStr = "!<" + tagStr + ">";
      }
      state2.dump = tagStr + " " + state2.dump;
    }
  }
  return true;
}
function getDuplicateReferences(object, state2) {
  var objects = [], duplicatesIndexes = [], index2, length;
  inspectNode(object, objects, duplicatesIndexes);
  for (index2 = 0, length = duplicatesIndexes.length; index2 < length; index2 += 1) {
    state2.duplicates.push(objects[duplicatesIndexes[index2]]);
  }
  state2.usedDuplicates = new Array(length);
}
function inspectNode(object, objects, duplicatesIndexes) {
  var objectKeyList, index2, length;
  if (object !== null && typeof object === "object") {
    index2 = objects.indexOf(object);
    if (index2 !== -1) {
      if (duplicatesIndexes.indexOf(index2) === -1) {
        duplicatesIndexes.push(index2);
      }
    } else {
      objects.push(object);
      if (Array.isArray(object)) {
        for (index2 = 0, length = object.length; index2 < length; index2 += 1) {
          inspectNode(object[index2], objects, duplicatesIndexes);
        }
      } else {
        objectKeyList = Object.keys(object);
        for (index2 = 0, length = objectKeyList.length; index2 < length; index2 += 1) {
          inspectNode(object[objectKeyList[index2]], objects, duplicatesIndexes);
        }
      }
    }
  }
}
function dump$1(input, options) {
  options = options || {};
  var state2 = new State(options);
  if (!state2.noRefs) getDuplicateReferences(input, state2);
  var value = input;
  if (state2.replacer) {
    value = state2.replacer.call({ "": value }, "", value);
  }
  if (writeNode(state2, 0, value, true, true)) return state2.dump + "\n";
  return "";
}
function renamed(from, to) {
  return function() {
    throw new Error(
      "Function yaml." + from + " is removed in js-yaml 4. Use yaml." + to + " instead, which is now safe by default."
    );
  };
}
var isNothing_1, isObject_1, toArray_1, repeat_1, isNegativeZero_1, extend_1, common2, exception, snippet, TYPE_CONSTRUCTOR_OPTIONS, YAML_NODE_KINDS, type, schema, str, seq, map, failsafe, _null, bool, int, YAML_FLOAT_PATTERN, SCIENTIFIC_WITHOUT_DOT, float, json, core, YAML_DATE_REGEXP, YAML_TIMESTAMP_REGEXP, timestamp, merge, BASE64_MAP, binary, _hasOwnProperty$3, _toString$2, omap, _toString$1, pairs, _hasOwnProperty$2, set, _default, _hasOwnProperty$1, CONTEXT_FLOW_IN, CONTEXT_FLOW_OUT, CONTEXT_BLOCK_IN, CONTEXT_BLOCK_OUT, CHOMPING_CLIP, CHOMPING_STRIP, CHOMPING_KEEP, PATTERN_NON_PRINTABLE, PATTERN_NON_ASCII_LINE_BREAKS, PATTERN_FLOW_INDICATORS, PATTERN_TAG_HANDLE, PATTERN_TAG_URI, simpleEscapeCheck, simpleEscapeMap, i6, directiveHandlers, loadAll_1, load_1, loader, _toString, _hasOwnProperty, CHAR_BOM, CHAR_TAB, CHAR_LINE_FEED, CHAR_CARRIAGE_RETURN, CHAR_SPACE, CHAR_EXCLAMATION, CHAR_DOUBLE_QUOTE, CHAR_SHARP, CHAR_PERCENT, CHAR_AMPERSAND, CHAR_SINGLE_QUOTE, CHAR_ASTERISK, CHAR_COMMA, CHAR_MINUS, CHAR_COLON2, CHAR_EQUALS, CHAR_GREATER_THAN, CHAR_QUESTION, CHAR_COMMERCIAL_AT, CHAR_LEFT_SQUARE_BRACKET, CHAR_RIGHT_SQUARE_BRACKET, CHAR_GRAVE_ACCENT, CHAR_LEFT_CURLY_BRACKET, CHAR_VERTICAL_LINE, CHAR_RIGHT_CURLY_BRACKET, ESCAPE_SEQUENCES, DEPRECATED_BOOLEANS_SYNTAX, DEPRECATED_BASE60_SYNTAX, QUOTING_TYPE_SINGLE, QUOTING_TYPE_DOUBLE, STYLE_PLAIN, STYLE_SINGLE, STYLE_LITERAL, STYLE_FOLDED, STYLE_DOUBLE, dump_1, dumper, Type2, Schema7, load, loadAll, dump, safeLoad, safeLoadAll, safeDump;
var init_js_yaml = __esm({
  "core/lib/external/js-yaml.js"() {
    isNothing_1 = isNothing;
    isObject_1 = isObject2;
    toArray_1 = toArray;
    repeat_1 = repeat;
    isNegativeZero_1 = isNegativeZero;
    extend_1 = extend;
    common2 = {
      isNothing: isNothing_1,
      isObject: isObject_1,
      toArray: toArray_1,
      repeat: repeat_1,
      isNegativeZero: isNegativeZero_1,
      extend: extend_1
    };
    YAMLException$1.prototype = Object.create(Error.prototype);
    YAMLException$1.prototype.constructor = YAMLException$1;
    YAMLException$1.prototype.toString = function toString2(compact) {
      return this.name + ": " + formatError(this, compact);
    };
    exception = YAMLException$1;
    snippet = makeSnippet;
    TYPE_CONSTRUCTOR_OPTIONS = [
      "kind",
      "multi",
      "resolve",
      "construct",
      "instanceOf",
      "predicate",
      "represent",
      "representName",
      "defaultStyle",
      "styleAliases"
    ];
    YAML_NODE_KINDS = ["scalar", "sequence", "mapping"];
    type = Type$1;
    Schema$1.prototype.extend = function extend2(definition) {
      var implicit = [];
      var explicit = [];
      if (definition instanceof type) {
        explicit.push(definition);
      } else if (Array.isArray(definition)) {
        explicit = explicit.concat(definition);
      } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) {
        if (definition.implicit) implicit = implicit.concat(definition.implicit);
        if (definition.explicit) explicit = explicit.concat(definition.explicit);
      } else {
        throw new exception(
          "Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })"
        );
      }
      implicit.forEach(function(type$1) {
        if (!(type$1 instanceof type)) {
          throw new exception(
            "Specified list of YAML types (or a single Type object) contains a non-Type object."
          );
        }
        if (type$1.loadKind && type$1.loadKind !== "scalar") {
          throw new exception(
            "There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported."
          );
        }
        if (type$1.multi) {
          throw new exception(
            "There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit."
          );
        }
      });
      explicit.forEach(function(type$1) {
        if (!(type$1 instanceof type)) {
          throw new exception(
            "Specified list of YAML types (or a single Type object) contains a non-Type object."
          );
        }
      });
      var result2 = Object.create(Schema$1.prototype);
      result2.implicit = (this.implicit || []).concat(implicit);
      result2.explicit = (this.explicit || []).concat(explicit);
      result2.compiledImplicit = compileList(result2, "implicit");
      result2.compiledExplicit = compileList(result2, "explicit");
      result2.compiledTypeMap = compileMap(
        result2.compiledImplicit,
        result2.compiledExplicit
      );
      return result2;
    };
    schema = Schema$1;
    str = new type("tag:yaml.org,2002:str", {
      kind: "scalar",
      construct: function(data3) {
        return data3 !== null ? data3 : "";
      }
    });
    seq = new type("tag:yaml.org,2002:seq", {
      kind: "sequence",
      construct: function(data3) {
        return data3 !== null ? data3 : [];
      }
    });
    map = new type("tag:yaml.org,2002:map", {
      kind: "mapping",
      construct: function(data3) {
        return data3 !== null ? data3 : {};
      }
    });
    failsafe = new schema({
      explicit: [str, seq, map]
    });
    _null = new type("tag:yaml.org,2002:null", {
      kind: "scalar",
      resolve: resolveYamlNull,
      construct: constructYamlNull,
      predicate: isNull,
      represent: {
        canonical: function() {
          return "~";
        },
        lowercase: function() {
          return "null";
        },
        uppercase: function() {
          return "NULL";
        },
        camelcase: function() {
          return "Null";
        },
        empty: function() {
          return "";
        }
      },
      defaultStyle: "lowercase"
    });
    bool = new type("tag:yaml.org,2002:bool", {
      kind: "scalar",
      resolve: resolveYamlBoolean,
      construct: constructYamlBoolean,
      predicate: isBoolean,
      represent: {
        lowercase: function(object) {
          return object ? "true" : "false";
        },
        uppercase: function(object) {
          return object ? "TRUE" : "FALSE";
        },
        camelcase: function(object) {
          return object ? "True" : "False";
        }
      },
      defaultStyle: "lowercase"
    });
    int = new type("tag:yaml.org,2002:int", {
      kind: "scalar",
      resolve: resolveYamlInteger,
      construct: constructYamlInteger,
      predicate: isInteger,
      represent: {
        binary: function(obj) {
          return obj >= 0 ? "0b" + obj.toString(2) : "-0b" + obj.toString(2).slice(1);
        },
        octal: function(obj) {
          return obj >= 0 ? "0o" + obj.toString(8) : "-0o" + obj.toString(8).slice(1);
        },
        decimal: function(obj) {
          return obj.toString(10);
        },
        hexadecimal: function(obj) {
          return obj >= 0 ? "0x" + obj.toString(16).toUpperCase() : "-0x" + obj.toString(16).toUpperCase().slice(1);
        }
      },
      defaultStyle: "decimal",
      styleAliases: {
        binary: [2, "bin"],
        octal: [8, "oct"],
        decimal: [10, "dec"],
        hexadecimal: [16, "hex"]
      }
    });
    YAML_FLOAT_PATTERN = new RegExp(
      "^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"
    );
    SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;
    float = new type("tag:yaml.org,2002:float", {
      kind: "scalar",
      resolve: resolveYamlFloat,
      construct: constructYamlFloat,
      predicate: isFloat,
      represent: representYamlFloat,
      defaultStyle: "lowercase"
    });
    json = failsafe.extend({
      implicit: [_null, bool, int, float]
    });
    core = json;
    YAML_DATE_REGEXP = new RegExp(
      "^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"
    );
    YAML_TIMESTAMP_REGEXP = new RegExp(
      "^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$"
    );
    timestamp = new type("tag:yaml.org,2002:timestamp", {
      kind: "scalar",
      resolve: resolveYamlTimestamp,
      construct: constructYamlTimestamp,
      instanceOf: Date,
      represent: representYamlTimestamp
    });
    merge = new type("tag:yaml.org,2002:merge", {
      kind: "scalar",
      resolve: resolveYamlMerge
    });
    BASE64_MAP = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r";
    binary = new type("tag:yaml.org,2002:binary", {
      kind: "scalar",
      resolve: resolveYamlBinary,
      construct: constructYamlBinary,
      predicate: isBinary,
      represent: representYamlBinary
    });
    _hasOwnProperty$3 = Object.prototype.hasOwnProperty;
    _toString$2 = Object.prototype.toString;
    omap = new type("tag:yaml.org,2002:omap", {
      kind: "sequence",
      resolve: resolveYamlOmap,
      construct: constructYamlOmap
    });
    _toString$1 = Object.prototype.toString;
    pairs = new type("tag:yaml.org,2002:pairs", {
      kind: "sequence",
      resolve: resolveYamlPairs,
      construct: constructYamlPairs
    });
    _hasOwnProperty$2 = Object.prototype.hasOwnProperty;
    set = new type("tag:yaml.org,2002:set", {
      kind: "mapping",
      resolve: resolveYamlSet,
      construct: constructYamlSet
    });
    _default = core.extend({
      implicit: [timestamp, merge],
      explicit: [binary, omap, pairs, set]
    });
    _hasOwnProperty$1 = Object.prototype.hasOwnProperty;
    CONTEXT_FLOW_IN = 1;
    CONTEXT_FLOW_OUT = 2;
    CONTEXT_BLOCK_IN = 3;
    CONTEXT_BLOCK_OUT = 4;
    CHOMPING_CLIP = 1;
    CHOMPING_STRIP = 2;
    CHOMPING_KEEP = 3;
    PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
    PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/;
    PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/;
    PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i;
    PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;
    simpleEscapeCheck = new Array(256);
    simpleEscapeMap = new Array(256);
    for (i6 = 0; i6 < 256; i6++) {
      simpleEscapeCheck[i6] = simpleEscapeSequence(i6) ? 1 : 0;
      simpleEscapeMap[i6] = simpleEscapeSequence(i6);
    }
    directiveHandlers = {
      YAML: function handleYamlDirective(state2, name2, args) {
        var match, major, minor;
        if (state2.version !== null) {
          throwError(state2, "duplication of %YAML directive");
        }
        if (args.length !== 1) {
          throwError(state2, "YAML directive accepts exactly one argument");
        }
        match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]);
        if (match === null) {
          throwError(state2, "ill-formed argument of the YAML directive");
        }
        major = parseInt(match[1], 10);
        minor = parseInt(match[2], 10);
        if (major !== 1) {
          throwError(state2, "unacceptable YAML version of the document");
        }
        state2.version = args[0];
        state2.checkLineBreaks = minor < 2;
        if (minor !== 1 && minor !== 2) {
          throwWarning(state2, "unsupported YAML version of the document");
        }
      },
      TAG: function handleTagDirective(state2, name2, args) {
        var handle, prefix;
        if (args.length !== 2) {
          throwError(state2, "TAG directive accepts exactly two arguments");
        }
        handle = args[0];
        prefix = args[1];
        if (!PATTERN_TAG_HANDLE.test(handle)) {
          throwError(
            state2,
            "ill-formed tag handle (first argument) of the TAG directive"
          );
        }
        if (_hasOwnProperty$1.call(state2.tagMap, handle)) {
          throwError(
            state2,
            'there is a previously declared suffix for "' + handle + '" tag handle'
          );
        }
        if (!PATTERN_TAG_URI.test(prefix)) {
          throwError(
            state2,
            "ill-formed tag prefix (second argument) of the TAG directive"
          );
        }
        try {
          prefix = decodeURIComponent(prefix);
        } catch (err2) {
          throwError(state2, "tag prefix is malformed: " + prefix);
        }
        state2.tagMap[handle] = prefix;
      }
    };
    loadAll_1 = loadAll$1;
    load_1 = load$1;
    loader = {
      loadAll: loadAll_1,
      load: load_1
    };
    _toString = Object.prototype.toString;
    _hasOwnProperty = Object.prototype.hasOwnProperty;
    CHAR_BOM = 65279;
    CHAR_TAB = 9;
    CHAR_LINE_FEED = 10;
    CHAR_CARRIAGE_RETURN = 13;
    CHAR_SPACE = 32;
    CHAR_EXCLAMATION = 33;
    CHAR_DOUBLE_QUOTE = 34;
    CHAR_SHARP = 35;
    CHAR_PERCENT = 37;
    CHAR_AMPERSAND = 38;
    CHAR_SINGLE_QUOTE = 39;
    CHAR_ASTERISK = 42;
    CHAR_COMMA = 44;
    CHAR_MINUS = 45;
    CHAR_COLON2 = 58;
    CHAR_EQUALS = 61;
    CHAR_GREATER_THAN = 62;
    CHAR_QUESTION = 63;
    CHAR_COMMERCIAL_AT = 64;
    CHAR_LEFT_SQUARE_BRACKET = 91;
    CHAR_RIGHT_SQUARE_BRACKET = 93;
    CHAR_GRAVE_ACCENT = 96;
    CHAR_LEFT_CURLY_BRACKET = 123;
    CHAR_VERTICAL_LINE = 124;
    CHAR_RIGHT_CURLY_BRACKET = 125;
    ESCAPE_SEQUENCES = {};
    ESCAPE_SEQUENCES[0] = "\\0";
    ESCAPE_SEQUENCES[7] = "\\a";
    ESCAPE_SEQUENCES[8] = "\\b";
    ESCAPE_SEQUENCES[9] = "\\t";
    ESCAPE_SEQUENCES[10] = "\\n";
    ESCAPE_SEQUENCES[11] = "\\v";
    ESCAPE_SEQUENCES[12] = "\\f";
    ESCAPE_SEQUENCES[13] = "\\r";
    ESCAPE_SEQUENCES[27] = "\\e";
    ESCAPE_SEQUENCES[34] = '\\"';
    ESCAPE_SEQUENCES[92] = "\\\\";
    ESCAPE_SEQUENCES[133] = "\\N";
    ESCAPE_SEQUENCES[160] = "\\_";
    ESCAPE_SEQUENCES[8232] = "\\L";
    ESCAPE_SEQUENCES[8233] = "\\P";
    DEPRECATED_BOOLEANS_SYNTAX = [
      "y",
      "Y",
      "yes",
      "Yes",
      "YES",
      "on",
      "On",
      "ON",
      "n",
      "N",
      "no",
      "No",
      "NO",
      "off",
      "Off",
      "OFF"
    ];
    DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;
    QUOTING_TYPE_SINGLE = 1;
    QUOTING_TYPE_DOUBLE = 2;
    STYLE_PLAIN = 1;
    STYLE_SINGLE = 2;
    STYLE_LITERAL = 3;
    STYLE_FOLDED = 4;
    STYLE_DOUBLE = 5;
    dump_1 = dump$1;
    dumper = {
      dump: dump_1
    };
    Type2 = type;
    Schema7 = schema;
    load = loader.load;
    loadAll = loader.loadAll;
    dump = dumper.dump;
    safeLoad = renamed("safeLoad", "load");
    safeLoadAll = renamed("safeLoadAll", "loadAll");
    safeDump = renamed("safeDump", "dump");
  }
});

// core/lib/yaml-intelligence/js-yaml-schema.ts
var QuartoJSONSchema;
var init_js_yaml_schema = __esm({
  "core/lib/yaml-intelligence/js-yaml-schema.ts"() {
    init_js_yaml();
    QuartoJSONSchema = new Schema7({
      implicit: [_null, bool, int, float],
      include: [failsafe],
      explicit: [
        new Type2("!expr", {
          kind: "scalar",
          // deno-lint-ignore no-explicit-any
          construct(data3) {
            const result2 = data3 !== null ? data3 : "";
            return {
              value: result2,
              tag: "!expr"
            };
          }
        })
      ]
    });
  }
});

// core/lib/is-circular.ts
var isCircular;
var init_is_circular = __esm({
  "core/lib/is-circular.ts"() {
    isCircular = (obj) => {
      const objectSet = /* @__PURE__ */ new WeakSet();
      const detect = (obj2) => {
        if (obj2 && typeof obj2 === "object") {
          if (objectSet.has(obj2)) {
            return true;
          }
          objectSet.add(obj2);
          for (const key in obj2) {
            if (Object.hasOwn(obj2, key) && detect(obj2[key])) {
              return true;
            }
          }
          objectSet.delete(obj2);
        }
        return false;
      };
      return detect(obj);
    };
  }
});

// core/lib/yaml-intelligence/annotated-yaml.ts
function postProcessAnnotation(parse24) {
  if (parse24.components.length === 1 && parse24.start === parse24.components[0].start && parse24.end === parse24.components[0].end) {
    return postProcessAnnotation(parse24.components[0]);
  } else {
    parse24.components = parse24.components.map(postProcessAnnotation);
    return parse24;
  }
}
function jsYamlParseLenient(yml) {
  try {
    return load(yml, { schema: QuartoJSONSchema });
  } catch (_e) {
    return yml;
  }
}
function readAnnotatedYamlFromMappedString(mappedSource2, lenient = false) {
  if (lenient) {
    const parser = getTreeSitterSync();
    const tree = parser.parse(mappedSource2.value);
    const treeSitterAnnotation = buildTreeSitterAnnotation(tree, mappedSource2);
    if (treeSitterAnnotation) {
      return treeSitterAnnotation;
    }
  }
  try {
    return buildJsYamlAnnotation(mappedSource2);
  } catch (e5) {
    if (e5.name === "YAMLError") {
      e5.name = "YAML Parsing";
    }
    const m4 = e5.stack.split("\n")[0].match(/^.+ \((\d+):(\d+)\)$/);
    if (m4) {
      const m1 = mappedSource2.value.match(/([^\s]+):([^\s]+)/);
      if (m1 && e5.reason.match(/a multiline key may not be an implicit key/)) {
        e5.name = "YAML Parse Error";
        e5.reason = "block has incorrect key formatting";
        const { originalString } = mappedSource2.map(m1.index, true);
        const filename = originalString.fileName;
        const map3 = mappedSource2.map(m1.index);
        const { line, column } = indexToLineCol(map3.originalString.value)(
          map3.index
        );
        const sourceContext = createSourceContext(mappedSource2, {
          start: m1.index + 1,
          end: m1.index + m1[0].length
        });
        e5.stack = `${e5.reason} (${filename}, ${line + 1}:${column + 1})
${sourceContext}`;
        e5.message = e5.stack;
        e5.message = `${e5.message}
${tidyverseInfo(
          "Is it possible you missed a space after a colon in the key-value mapping?"
        )}`;
      } else {
        const f5 = lineColToIndex(mappedSource2.value);
        const location = { line: Number(m4[1]) - 1, column: Number(m4[2] - 1) };
        const offset3 = f5(location);
        const { originalString } = mappedSource2.map(offset3, true);
        const filename = originalString.fileName;
        const f22 = mappedIndexToLineCol(mappedSource2);
        const { line, column } = f22(offset3);
        const sourceContext = createSourceContext(mappedSource2, {
          start: offset3,
          end: offset3 + 1
        });
        e5.stack = `${e5.reason} (${filename}, ${line + 1}:${column + 1})
${sourceContext}`;
        e5.message = e5.stack;
        if (mappedLines(mappedSource2)[location.line].value.indexOf("!expr") !== -1 && e5.reason.match(/bad indentation of a mapping entry/)) {
          e5.message = `${e5.message}
${tidyverseInfo(
            "YAML tags like !expr must be followed by YAML strings."
          )}
${tidyverseInfo(
            "Is it possible you need to quote the value you passed to !expr ?"
          )}`;
        }
      }
      e5.stack = "";
    }
    throw e5;
  }
}
function buildJsYamlAnnotation(mappedYaml) {
  const yml = mappedYaml.value;
  const stack = [];
  const results = [];
  function listener(what, state2) {
    const { result: result2, position, kind } = state2;
    if (what === "close") {
      const { position: openPosition, kind: openKind } = stack.pop();
      if (results.length > 0) {
        const last = results[results.length - 1];
        if (last.start === openPosition && last.end === position) {
          return;
        }
      }
      const components = [];
      while (results.length > 0) {
        const last = results[results.length - 1];
        if (last.end <= openPosition) {
          break;
        }
        components.push(results.pop());
      }
      components.reverse();
      const rawRange = yml.substring(openPosition, position);
      const leftTrim = rawRange.length - rawRange.trimStart().length;
      const rightTrim = rawRange.length - rawRange.trimEnd().length;
      if (openKind === null && kind === null) {
      } else if (rawRange.trim().length === 0) {
        results.push({
          start: position - rightTrim,
          end: position - rightTrim,
          result: result2,
          components,
          kind,
          source: mappedYaml
        });
      } else {
        results.push({
          start: openPosition + leftTrim,
          end: position - rightTrim,
          result: result2,
          components,
          kind,
          source: mappedYaml
        });
      }
    } else {
      stack.push({ position, kind });
    }
  }
  load(yml, { listener, schema: QuartoJSONSchema });
  if (results.length === 0) {
    return {
      start: 0,
      end: 0,
      result: null,
      kind: "null",
      components: [],
      source: mappedYaml
    };
  }
  if (results.length !== 1) {
    throw new InternalError(
      `Expected a single result, got ${results.length} instead`
    );
  }
  if (isCircular(results[0])) {
    throw new InternalError(
      `Circular structure detected in yaml`
    );
  }
  return postProcessAnnotation(results[0]);
}
function buildTreeSitterAnnotation(tree, mappedSource2) {
  const errors2 = [];
  const singletonBuild = (node) => {
    let tag = void 0;
    for (const child of node.children) {
      if (child.type === "tag") {
        tag = child;
        continue;
      }
      if (child.type !== "comment") {
        const result3 = buildNode(child, node.endIndex);
        if (tag) {
          return annotateTag(result3, tag, node);
        } else {
          return result3;
        }
      }
    }
    return annotateEmpty(node.endIndex);
  };
  const buildNode = (node, endIndex) => {
    if (node === null) {
      return annotateEmpty(endIndex === void 0 ? -1 : endIndex);
    }
    if (dispatch[node.type] === void 0) {
      return annotateEmpty(endIndex || node.endIndex || -1);
    }
    return dispatch[node.type](node);
  };
  const annotateEmpty = (position) => {
    return {
      start: position,
      end: position,
      result: null,
      kind: "<<EMPTY>>",
      components: [],
      source: mappedSource2
    };
  };
  const annotate = (node, result3, components) => {
    return {
      start: node.startIndex,
      end: node.endIndex,
      result: result3,
      kind: node.type,
      // NB this doesn't match js-yaml, so you need
      // to make sure your annotated walkers know
      // about tree-sitter and js-yaml both.
      components,
      source: mappedSource2
    };
  };
  const annotateTag = (innerParse, tagNode, outerNode) => {
    const tagParse = annotate(tagNode, tagNode.text, []);
    const result3 = annotate(outerNode, {
      tag: tagNode.text,
      value: innerParse.result
    }, [tagParse, innerParse]);
    return result3;
  };
  const buildPair = (node) => {
    let key, value;
    const children = node.children.filter((n5) => n5.type !== "comment");
    if (children.length === 3) {
      key = annotate(children[0], children[0].text, []);
      value = buildNode(children[2], node.endIndex);
    } else if (children.length === 2) {
      key = annotate(children[0], children[0].text, []);
      value = annotateEmpty(node.endIndex);
    } else {
      key = annotateEmpty(node.endIndex);
      value = annotateEmpty(node.endIndex);
    }
    return annotate(node, {
      key: key.result,
      value: value.result
    }, [key, value]);
  };
  const dispatch = {
    "stream": singletonBuild,
    "document": singletonBuild,
    "block_node": singletonBuild,
    "flow_node": singletonBuild,
    "double_quote_scalar": (node) => {
      return annotate(node, jsYamlParseLenient(node.text), []);
    },
    "single_quote_scalar": (node) => {
      return annotate(node, jsYamlParseLenient(node.text), []);
    },
    "plain_scalar": (node) => {
      return annotate(node, jsYamlParseLenient(node.text), []);
    },
    "block_scalar": (node) => {
      return annotate(node, jsYamlParseLenient(node.text), []);
    },
    "block_sequence": (node) => {
      const result3 = [], components = [];
      for (let i6 = 0; i6 < node.childCount; ++i6) {
        const child = node.child(i6);
        if (child.type !== "block_sequence_item") {
          continue;
        }
        const component = buildNode(child, node.endIndex);
        components.push(component);
        result3.push(component && component.result);
      }
      return annotate(node, result3, components);
    },
    "block_sequence_item": (node) => {
      if (node.childCount < 2) {
        return annotateEmpty(node.endIndex);
      } else {
        return buildNode(node.child(1), node.endIndex);
      }
    },
    "flow_sequence": (node) => {
      const result3 = [], components = [];
      for (let i6 = 0; i6 < node.childCount; ++i6) {
        const child = node.child(i6);
        if (child.type !== "flow_node") {
          continue;
        }
        const component = buildNode(child, node.endIndex);
        components.push(component);
        result3.push(component.result);
      }
      return annotate(node, result3, components);
    },
    "block_mapping": (node) => {
      const result3 = {}, components = [];
      for (let i6 = 0; i6 < node.childCount; ++i6) {
        const child = node.child(i6);
        let component;
        if (child.type === "ERROR") {
          result3[child.text] = "<<ERROR>>";
          const key2 = annotate(child, child.text, []);
          const value2 = annotateEmpty(child.endIndex);
          component = annotate(child, {
            key: key2.result,
            value: value2.result
          }, [key2, value2]);
        } else if (child.type !== "block_mapping_pair") {
          continue;
        } else {
          component = buildNode(child, node.endIndex);
        }
        const { key, value } = component.result;
        result3[String(key)] = value;
        components.push(...component.components);
      }
      return annotate(node, result3, components);
    },
    "flow_pair": buildPair,
    "flow_mapping": (node) => {
      const result3 = {}, components = [];
      for (let i6 = 0; i6 < node.childCount; ++i6) {
        const child = node.child(i6);
        if (child.type === "flow_node") {
          continue;
        }
        if (child.type === "flow_pair") {
          const component = buildNode(child, node.endIndex);
          const { key, value } = component.result;
          result3[String(key)] = value;
          components.push(...component.components);
        }
      }
      return annotate(node, result3, components);
    },
    "block_mapping_pair": buildPair
  };
  const result2 = buildNode(tree.rootNode, tree.rootNode.endIndex);
  if (errors2.length) {
    result2.errors = errors2;
  }
  const parsedSize = tree.rootNode.text.trim().length;
  const codeSize = mappedSource2.value.trim().length;
  const lossage = parsedSize / codeSize;
  if (lossage < 0.95) {
    return null;
  }
  return result2;
}
function locateAnnotation(annotation, position, kind) {
  const originalSource = annotation.source;
  kind = kind || "value";
  for (let i6 = 0; i6 < position.length; ++i6) {
    const value = position[i6];
    if (typeof value === "number") {
      const inner = annotation.components[value];
      if (inner === void 0) {
        throw new InternalError("invalid path for locateAnnotation");
      }
      annotation = inner;
    } else {
      let found = false;
      for (let j3 = 0; j3 < annotation.components.length; j3 += 2) {
        if (originalSource.value.substring(
          annotation.components[j3].start,
          annotation.components[j3].end
        ).trim() === value) {
          if (i6 === position.length - 1) {
            if (kind === "key") {
              annotation = annotation.components[j3];
            } else {
              annotation = annotation.components[j3 + 1];
            }
          }
          found = true;
          break;
        }
      }
      if (!found) {
        throw new InternalError("invalid path for locateAnnotation");
      }
    }
  }
  return annotation;
}
var init_annotated_yaml = __esm({
  "core/lib/yaml-intelligence/annotated-yaml.ts"() {
    init_text();
    init_mapped_text();
    init_parsing();
    init_js_yaml();
    init_js_yaml_schema();
    init_errors2();
    init_errors();
    init_error2();
    init_is_circular();
  }
});

// core/lib/yaml-schema/validated-yaml.ts
async function readAndValidateYamlFromMappedString(mappedYaml, schema4, pruneErrors = true, lenient = false) {
  const annotation = await readAnnotatedYamlFromMappedString(
    mappedYaml,
    lenient
  );
  if (annotation === null) {
    throw new Error("Parse error in readAnnotatedYamlFromMappedString");
  }
  const validateYaml = !isObject3(annotation.result) || annotation.result["validate-yaml"] !== false;
  if (!validateYaml) {
    return {
      yaml: annotation.result,
      yamlValidationErrors: []
    };
  }
  const validate2 = async (validator) => {
    const valResult = await validator.validateParse(
      mappedYaml,
      annotation,
      pruneErrors
    );
    return {
      yaml: annotation.result,
      yamlValidationErrors: valResult.errors
    };
  };
  if (typeof annotation.result === "object" && !Array.isArray(annotation.result)) {
    const preCheckResult = await withValidator(
      getSchemaDefinition("bad-parse-schema"),
      validate2
    );
    if (preCheckResult.yamlValidationErrors.length !== 0) {
      return preCheckResult;
    }
  }
  const result2 = await withValidator(schema4, validate2);
  return result2;
}
var ValidationError4, isObject3;
var init_validated_yaml = __esm({
  "core/lib/yaml-schema/validated-yaml.ts"() {
    init_annotated_yaml();
    init_validator_queue();
    init_errors();
    init_schema();
    ValidationError4 = class _ValidationError extends Error {
      validationErrors;
      constructor(msg5, validationErrors) {
        super(
          [msg5, ...validationErrors.map((e5) => tidyverseFormatError(e5.niceError))].join(
            "\n\n"
          )
        );
        Object.setPrototypeOf(this, _ValidationError.prototype);
        this.validationErrors = validationErrors;
      }
    };
    isObject3 = (value) => {
      const type4 = typeof value;
      return value !== null && (type4 === "object" || type4 === "function");
    };
  }
});

// core/lib/yaml-schema/from-yaml.ts
function setBaseSchemaProperties(yaml, schema4) {
  if (yaml.additionalCompletions) {
    schema4 = completeSchema(schema4, ...yaml.additionalCompletions);
  }
  if (yaml.completions) {
    schema4 = completeSchemaOverwrite(schema4, ...yaml.completions);
  }
  if (yaml.id) {
    schema4 = idSchema(schema4, yaml.id);
  }
  if (yaml.hidden === true) {
    schema4 = completeSchemaOverwrite(schema4);
    schema4 = tagSchema(schema4, {
      "hidden": true
    });
  }
  if (yaml.tags) {
    schema4 = tagSchema(schema4, yaml.tags);
  }
  if (yaml.description) {
    schema4 = tagSchema(schema4, { description: yaml.description });
    if (typeof yaml.description === "string") {
      schema4 = documentSchema(schema4, yaml.description);
    } else if (typeof yaml.description === "object") {
      schema4 = documentSchema(schema4, yaml.description.short);
    }
  }
  const result2 = Object.assign({}, schema4);
  if (yaml.errorDescription) {
    result2.description = yaml.errorDescription;
  }
  if (yaml.errorMessage) {
    result2.errorMessage = yaml.errorMessage;
  }
  return result2;
}
function convertFromNull(yaml) {
  return setBaseSchemaProperties(yaml["null"], nullSchema);
}
function convertFromSchema(yaml) {
  const schema4 = convertFromYaml(yaml.schema);
  return setBaseSchemaProperties(yaml, schema4);
}
function convertFromString(yaml) {
  if (yaml["string"].pattern) {
    return setBaseSchemaProperties(
      yaml,
      setBaseSchemaProperties(
        yaml["string"],
        regexSchema(yaml["string"].pattern)
      )
    );
  } else {
    return setBaseSchemaProperties(
      yaml,
      setBaseSchemaProperties(
        yaml["string"],
        stringSchema
      )
    );
  }
}
function convertFromPattern(yaml) {
  if (typeof yaml.pattern === "string") {
    return setBaseSchemaProperties(yaml, regexSchema(yaml.pattern));
  } else {
    return setBaseSchemaProperties(
      yaml,
      setBaseSchemaProperties(yaml.pattern, regexSchema(yaml.pattern.regex))
    );
  }
}
function convertFromPath(yaml) {
  return setBaseSchemaProperties(yaml["path"], stringSchema);
}
function convertFromNumber(yaml) {
  return setBaseSchemaProperties(yaml["number"], numberSchema);
}
function convertFromBoolean(yaml) {
  return setBaseSchemaProperties(yaml["boolean"], booleanSchema);
}
function convertFromRef(yaml) {
  return setBaseSchemaProperties(yaml, refSchema(yaml.ref, `be ${yaml.ref}`));
}
function convertFromMaybeArrayOf(yaml) {
  const inner = convertFromYaml(yaml.maybeArrayOf);
  const schema4 = tagSchema(
    anyOfSchema(inner, arraySchema(inner)),
    {
      "complete-from": ["anyOf", 0]
      // complete from `schema` completions, ignoring arrayOf
    }
  );
  return setBaseSchemaProperties(yaml, schema4);
}
function convertFromArrayOf(yaml) {
  if (yaml.arrayOf.schema) {
    const result2 = arraySchema(convertFromYaml(yaml.arrayOf.schema));
    return setBaseSchemaProperties(
      yaml,
      setBaseSchemaProperties(yaml.arrayOf, result2)
    );
  } else {
    return setBaseSchemaProperties(
      yaml,
      arraySchema(convertFromYaml(yaml.arrayOf))
    );
  }
}
function convertFromAllOf(yaml) {
  if (yaml.allOf.schemas) {
    const inner = yaml.allOf.schemas.map((x3) => convertFromYaml(x3));
    const schema4 = allOfSchema(...inner);
    return setBaseSchemaProperties(
      yaml,
      setBaseSchemaProperties(yaml.allOf, schema4)
    );
  } else {
    const inner = yaml.allOf.map((x3) => convertFromYaml(x3));
    const schema4 = allOfSchema(...inner);
    return setBaseSchemaProperties(yaml, schema4);
  }
}
function convertFromAnyOf(yaml) {
  if (yaml.anyOf.schemas) {
    const inner = yaml.anyOf.schemas.map((x3) => convertFromYaml(x3));
    const schema4 = anyOfSchema(...inner);
    return setBaseSchemaProperties(
      yaml,
      setBaseSchemaProperties(yaml.anyOf, schema4)
    );
  } else {
    const inner = yaml.anyOf.map((x3) => convertFromYaml(x3));
    const schema4 = anyOfSchema(...inner);
    return setBaseSchemaProperties(yaml, schema4);
  }
}
function convertFromEnum(yaml) {
  const schema4 = yaml["enum"];
  if (schema4.hasOwnProperty("values")) {
    return setBaseSchemaProperties(
      yaml,
      setBaseSchemaProperties(yaml["enum"], enumSchema(...schema4.values))
    );
  } else {
    return setBaseSchemaProperties(yaml, enumSchema(...schema4));
  }
}
function convertFromRecord(yaml) {
  if (yaml.record.properties) {
    const schema4 = convertFromObject({
      "object": {
        "properties": yaml.record.properties,
        "closed": true,
        "required": "all"
      }
    });
    return setBaseSchemaProperties(
      yaml,
      setBaseSchemaProperties(yaml.record, schema4)
    );
  } else {
    const schema4 = convertFromObject({
      "object": {
        "properties": yaml.record,
        "closed": true,
        "required": "all"
      }
    });
    return setBaseSchemaProperties(yaml, schema4);
  }
}
function convertFromObject(yaml) {
  const schema4 = yaml["object"];
  const params = {};
  if (schema4.namingConvention && typeof schema4.namingConvention === "string") {
    switch (schema4.namingConvention) {
      case "ignore":
        params.namingConvention = "ignore";
        break;
      case "capitalizationCase":
        params.namingConvention = "capitalizationCase";
        break;
      case "capitalization-case":
        params.namingConvention = "capitalizationCase";
        break;
      case "capitalization_case":
        params.namingConvention = "capitalizationCase";
        break;
      case "underscoreCase":
        params.namingConvention = "underscore_case";
        break;
      case "underscore-case":
        params.namingConvention = "underscore_case";
        break;
      case "underscore_case":
        params.namingConvention = "underscore_case";
        break;
      case "dashCase":
        params.namingConvention = "dash-case";
        break;
      case "dash-case":
        params.namingConvention = "dash-case";
        break;
      case "dash_case":
        params.namingConvention = "dash-case";
        break;
      case "camelCase":
        params.namingConvention = "capitalizationCase";
        break;
      case "camel-case":
        params.namingConvention = "capitalizationCase";
        break;
      case "camel_case":
        params.namingConvention = "capitalizationCase";
        break;
      case "snakeCase":
        params.namingConvention = "underscore_case";
        break;
      case "snake-case":
        params.namingConvention = "underscore_case";
        break;
      case "snake_case":
        params.namingConvention = "underscore_case";
        break;
      case "kebabCase":
        params.namingConvention = "dash-case";
        break;
      case "kebab-case":
        params.namingConvention = "dash-case";
        break;
      case "kebab_case":
        params.namingConvention = "dash-case";
        break;
      default:
        throw new InternalError(
          `Unrecognized naming convention ${schema4.namingConvention} should have failed validation`
        );
    }
  } else {
    params.namingConvention = schema4.namingConvention;
  }
  if (schema4.properties) {
    params.properties = fromEntries(
      Object.entries(schema4.properties).map(([key, value]) => [key, convertFromYaml(value)])
    );
  }
  if (schema4.patternProperties) {
    params.patternProperties = fromEntries(
      Object.entries(schema4.properties).map(([key, value]) => [key, convertFromYaml(value)])
    );
  }
  if (schema4.propertyNames !== void 0) {
    params.propertyNames = convertFromYaml(schema4.propertyNames);
  } else if (schema4.closed === true) {
    const objectKeys = Object.keys(params.properties || {});
    if (objectKeys.length === 0) {
      throw new Error("object schema `closed` requires field `properties`.");
    }
    if (params.namingConvention !== void 0 && params.namingConvention !== "ignore") {
      throw new Error(
        "object schema `closed` is only supported with namingConvention: `ignore`"
      );
    }
    params.namingConvention = "ignore";
    params.closed = true;
  }
  if (schema4.additionalProperties !== void 0) {
    if (schema4.additionalProperties === false) {
      params.additionalProperties = false;
    } else {
      params.additionalProperties = convertFromYaml(
        schema4.additionalProperties
      );
    }
  }
  if (schema4["super"]) {
    if (Array.isArray(schema4["super"])) {
      params.baseSchema = schema4["super"].map((s5) => convertFromYaml(s5));
    } else {
      params.baseSchema = convertFromYaml(schema4["super"]);
    }
  }
  if (schema4["required"] === "all") {
    params.required = Object.keys(schema4.properties || {});
  } else if (schema4["required"]) {
    params.required = schema4["required"];
  }
  if (schema4["completions"]) {
    params.completions = schema4["completions"];
  }
  return setBaseSchemaProperties(
    yaml,
    setBaseSchemaProperties(schema4, objectSchema(params))
  );
}
function lookup(yaml) {
  if (!hasSchemaDefinition(yaml.resolveRef)) {
    throw new Error(`lookup of key ${yaml.resolveRef} in definitions failed`);
  }
  return getSchemaDefinition(yaml.resolveRef);
}
function convertFromYaml(yaml) {
  const literalValues = [
    { val: "object", schema: objectSchema() },
    { val: "path", schema: stringSchema },
    // FIXME we should treat this one differently to record the autocompletion difference
    { val: "string", schema: stringSchema },
    { val: "number", schema: numberSchema },
    { val: "boolean", schema: booleanSchema },
    { val: "any", schema: anySchema() },
    { val: null, schema: nullSchema }
  ];
  for (const { val, schema: schema4 } of literalValues) {
    if (yaml === val) {
      return schema4;
    }
  }
  if (typeof yaml !== "object") {
    return valueSchema(yaml);
  }
  const schemaObjectKeyFunctions = [
    { key: "anyOf", value: convertFromAnyOf },
    { key: "allOf", value: convertFromAllOf },
    { key: "boolean", value: convertFromBoolean },
    { key: "arrayOf", value: convertFromArrayOf },
    { key: "enum", value: convertFromEnum },
    { key: "maybeArrayOf", value: convertFromMaybeArrayOf },
    { key: "null", value: convertFromNull },
    { key: "number", value: convertFromNumber },
    { key: "object", value: convertFromObject },
    { key: "path", value: convertFromPath },
    { key: "record", value: convertFromRecord },
    { key: "ref", value: convertFromRef },
    { key: "resolveRef", value: lookup },
    { key: "string", value: convertFromString },
    { key: "pattern", value: convertFromPattern },
    { key: "schema", value: convertFromSchema }
  ];
  for (const { key: objectKey, value: fun } of schemaObjectKeyFunctions) {
    if (yaml[objectKey] !== void 0) {
      return fun(yaml);
    }
  }
  throw new InternalError(
    "Cannot convert object; this should have failed validation."
  );
}
function objectSchemaFromFieldsObject(fields, exclude) {
  exclude = exclude || ((_key) => false);
  const properties = {};
  convertFromFieldsObject(fields, properties);
  for (const key of Object.keys(properties)) {
    if (exclude(key)) {
      delete properties[key];
    }
  }
  return objectSchema({ properties });
}
function annotateSchemaFromField(field, schema4) {
  if (field.enabled !== void 0) {
    schema4 = tagSchema(schema4, {
      formats: field.enabled
    });
  }
  if (field.disabled !== void 0) {
    schema4 = tagSchema(schema4, {
      formats: field.disabled.map((x3) => `!${x3}`)
    });
  }
  if (field.tags) {
    schema4 = tagSchema(schema4, field.tags);
  }
  if (field.description) {
    if (typeof field.description === "string") {
      schema4 = documentSchema(schema4, field.description);
    } else if (typeof field.description === "object") {
      schema4 = documentSchema(schema4, field.description.short);
    }
    schema4 = tagSchema(schema4, {
      description: field.description
    });
  }
  if (field.hidden) {
    schema4 = tagSchema(schema4, {
      "hidden": true
    });
  }
  return schema4;
}
function schemaFromField(entry) {
  const schema4 = convertFromYaml(entry.schema);
  return annotateSchemaFromField(entry, schema4);
}
function convertFromFieldsObject(yaml, obj) {
  const result2 = obj || {};
  for (const field of yaml) {
    let schema4 = convertFromYaml(field.schema);
    schema4 = annotateSchemaFromField(field, schema4);
    result2[field.name] = schema4;
    if (field.alias) {
      result2[field.alias] = schema4;
    }
  }
  return result2;
}
function schemaFieldsFromGlob(globPath, testFun) {
  const result2 = [];
  testFun = testFun || ((_e, _p) => true);
  for (const [file, fields] of expandResourceGlob(globPath)) {
    for (const field of fields) {
      const fieldName = field.name;
      const schemaId = `quarto-resource-${file.split("/").slice(-1)[0].slice(0, -4)}-${fieldName}`;
      if (testFun(field, file)) {
        result2.push({
          schemaId,
          field
        });
      }
    }
  }
  return result2;
}
function objectRefSchemaFromContextGlob(contextGlob, testFun) {
  const regexp = globToRegExp5(contextGlob);
  return objectRefSchemaFromGlob(
    "schema/{document,cell}-*.yml",
    (field, path3) => {
      if (testFun !== void 0 && !testFun(field, path3)) {
        return false;
      }
      const pathContext = path3.split("/").slice(-1)[0].slice(0, -4);
      const schemaContexts = field !== void 0 && field.tags !== void 0 && field.tags.contexts || [];
      if (pathContext.match(regexp)) {
        return true;
      }
      return schemaContexts.some((c6) => c6.match(regexp));
    }
  );
}
function objectRefSchemaFromGlob(glob, testFun) {
  const properties = {};
  for (const { schemaId, field } of schemaFieldsFromGlob(glob, testFun)) {
    const schema4 = refSchema(schemaId, schemaId);
    properties[field.name] = schema4;
    if (field.alias) {
      properties[field.alias] = schema4;
    }
  }
  return objectSchema({ properties });
}
async function buildResourceSchemas() {
  const path3 = "schema/{cell-*,document-*,project}.yml";
  for (const [file, fields] of expandResourceGlob(path3)) {
    const yaml = fields;
    const entries = Object.entries(convertFromFieldsObject(yaml));
    for (const [fieldName, fieldSchema] of entries) {
      const schemaId = `quarto-resource-${file.split("/").slice(-1)[0].slice(0, -4)}-${fieldName}`;
      const schema4 = idSchema(fieldSchema, schemaId);
      setSchemaDefinition(schema4);
      await withValidator(schema4, async (_validator) => {
      });
    }
  }
}
function getSchemaSchemas() {
  const yaml = getYamlIntelligenceResource("schema/schema.yml");
  const dict = {};
  for (const obj of yaml) {
    const schema4 = convertFromYaml(obj);
    setSchemaDefinition(schema4);
    dict[schema4.$id] = schema4;
  }
  return dict;
}
var schemaRefContexts;
var init_from_yaml = __esm({
  "core/lib/yaml-schema/from-yaml.ts"() {
    init_schema();
    init_validator_queue();
    init_constants5();
    init_common4();
    init_memoize();
    init_resources();
    init_glob();
    init_polyfills();
    init_mapped_text();
    init_validated_yaml();
    init_error2();
    schemaRefContexts = memoize(() => {
      const groups = getYamlIntelligenceResource("schema/groups.yml");
      const result2 = [];
      for (const [topLevel, sub] of Object.entries(groups)) {
        for (const key of Object.keys(sub)) {
          result2.push(`${topLevel}-${key}`);
        }
      }
      return result2;
    }, () => "const");
  }
});

// core/lib/yaml-schema/definitions.ts
function defineCached(thunk, schemaId) {
  let schema4;
  return async () => {
    if (hasSchemaDefinition(schemaId)) {
      schema4 = getSchemaDefinition(schemaId);
      return refSchema(
        schema4.$id,
        schema4.description || `be a {schema['$id'] as string}`
      );
    }
    const result2 = await thunk();
    const { errorHandlers } = result2;
    schema4 = result2.schema;
    if (schemaId !== schema4.$id) {
      schema4 = idSchema(schema4, schemaId);
    }
    define2(schema4);
    for (const fun of errorHandlers) {
      addValidatorErrorHandler(schema4, fun);
    }
    return refSchema(
      schema4.$id,
      schema4.description || `be a {schema['$id']}`
    );
  };
}
function define2(schema4) {
  if (schema4 !== true && schema4 !== false && schema4.$id && !hasSchemaDefinition(schema4.$id)) {
    setSchemaDefinition(schema4);
  }
}
async function loadDefaultSchemaDefinitions() {
  await loadSchemaDefinitions(
    getYamlIntelligenceResource("schema/definitions.yml")
  );
  await buildResourceSchemas();
}
async function loadSchemaDefinitions(yaml) {
  await Promise.all(yaml.map(async (yamlSchema) => {
    const schema4 = convertFromYaml(yamlSchema);
    if (schema4.$id === void 0) {
      throw new InternalError(`Unnamed schema in definitions`);
    }
    setSchemaDefinition(schema4);
  }));
}
var init_definitions = __esm({
  "core/lib/yaml-schema/definitions.ts"() {
    init_common4();
    init_resources();
    init_from_yaml();
    init_validator_queue();
    init_schema();
    init_error2();
  }
});

// core/lib/yaml-schema/execute.ts
function getFormatExecuteOptionsSchema() {
  const schema4 = idSchema(
    objectRefSchemaFromContextGlob("document-execute"),
    "front-matter-execute"
  );
  define2(schema4);
  return refSchema("front-matter-execute", "be a front-matter-execute object");
}
var init_execute = __esm({
  "core/lib/yaml-schema/execute.ts"() {
    init_from_yaml();
    init_common4();
    init_definitions();
  }
});

// core/lib/yaml-schema/format-aliases.ts
function getFormatAliases() {
  if (formatAliases !== void 0) {
    return formatAliases;
  }
  formatAliases = getYamlIntelligenceResource("schema/format-aliases.yml").aliases;
  return formatAliases;
}
function expandFormatAliases(lst) {
  return expandAliasesFrom(lst, getFormatAliases());
}
var formatAliases;
var init_format_aliases = __esm({
  "core/lib/yaml-schema/format-aliases.ts"() {
    init_schema();
    init_resources();
    formatAliases = void 0;
  }
});

// core/lib/yaml-schema/format-schemas.ts
function useSchema(schema4, format14) {
  const formats2 = schema4 && schema4.tags && schema4.tags.formats;
  if (formats2 === void 0) {
    return true;
  }
  const disabled = formats2.filter((f5) => f5.startsWith("!")).map(
    (f5) => f5.slice(1)
  );
  const enabled5 = formats2.filter((f5) => !f5.startsWith("!"));
  if (disabled.length > 0 && expandFormatAliases(disabled).indexOf(format14) !== -1) {
    return false;
  }
  if (enabled5.length > 0 && expandFormatAliases(enabled5).indexOf(format14) === -1) {
    return false;
  }
  return true;
}
function getFormatSchema(format14) {
  const schema4 = objectRefSchemaFromContextGlob(
    "document-*",
    (field) => {
      const schema5 = schemaFromField(field);
      return useSchema(schema5, format14);
    }
  );
  return anyOfSchema(schema4, enumSchema("default"));
}
var init_format_schemas = __esm({
  "core/lib/yaml-schema/format-schemas.ts"() {
    init_format_aliases();
    init_from_yaml();
    init_common4();
  }
});

// core/lib/yaml-schema/front-matter.ts
function pandocFormatsResource() {
  return getYamlIntelligenceResource("pandoc/formats.yml");
}
async function makeFrontMatterFormatSchema(nonStrict = false) {
  const hideFormat = (format14) => {
    const hideList = ["html", "epub", "docbook"];
    const hidden2 = hideList.some(
      (h5) => format14.startsWith(h5) && format14.length > h5.length
    );
    return { name: format14, hidden: hidden2 };
  };
  const formatSchemaDescriptorList = (await pandocFormatsResource()).concat(
    "md",
    // alias for 'commonmark'
    "hugo",
    // tolerage for compatibility: initially built-in, now referrred to as 'hugo-md'
    "dashboard",
    // our built in format for dashboards
    "email"
    // for the HTML email format (used with Posit Connect)
  ).map(
    (format14) => {
      const {
        name: name2,
        hidden: hidden2
      } = hideFormat(format14);
      return {
        regex: `^(.+-)?${name2}([-+].+)?$`,
        // NOTE: the following regex supports format:foo and format[foo]. It currently breaks
        // our autocompletion because it uses non-capturing groups. Since we haven't decided
        // on it, we're reverting for now.
        //
        // regex:
        //   `^${name}(?:(?:[[][^\\]\\ s]+[\\]])|(?:[:][^:+\\s]+))?(?:[+].+)?$`,
        schema: getFormatSchema(name2),
        name: name2,
        hidden: hidden2
      };
    }
  );
  const formatSchemas = formatSchemaDescriptorList.map(
    ({ regex, schema: schema4 }) => [regex, schema4]
  );
  const plusFormatStringSchemas = formatSchemaDescriptorList.map(
    ({ regex, name: name2, hidden: hidden2 }) => {
      const schema4 = regexSchema(regex, `be '${name2}'`);
      if (hidden2) {
        return schema4;
      }
      return completeSchema(schema4, name2);
    }
  );
  const luaFilenameS = regexSchema("^.+.lua$");
  plusFormatStringSchemas.push(luaFilenameS);
  const completionsObject = fromEntries(
    formatSchemaDescriptorList.filter(({ hidden: hidden2 }) => !hidden2).map(({ name: name2 }) => [name2, {
      type: "key",
      display: name2,
      value: `${name2}: `,
      description: `be '${name2}'`,
      suggest_on_accept: true
    }])
  );
  return errorMessageSchema(
    anyOfSchema(
      describeSchema(
        anyOfSchema(...plusFormatStringSchemas),
        "the name of a pandoc-supported output format"
      ),
      objectSchema({
        propertyNames: luaFilenameS
      }),
      allOfSchema(
        objectSchema({
          patternProperties: fromEntries(formatSchemas),
          completions: completionsObject,
          additionalProperties: nonStrict
        })
      )
    ),
    "${value} is not a valid output format."
  );
}
var getFrontMatterFormatSchema, getNonStrictFrontMatterFormatSchema, getFrontMatterSchema;
var init_front_matter = __esm({
  "core/lib/yaml-schema/front-matter.ts"() {
    init_constants5();
    init_common4();
    init_execute();
    init_from_yaml();
    init_format_schemas();
    init_definitions();
    init_common4();
    init_resources();
    init_polyfills();
    getFrontMatterFormatSchema = defineCached(
      async () => {
        return {
          schema: await makeFrontMatterFormatSchema(),
          errorHandlers: []
        };
      },
      "front-matter-format"
    );
    getNonStrictFrontMatterFormatSchema = defineCached(
      async () => {
        return {
          schema: await makeFrontMatterFormatSchema(true),
          errorHandlers: []
        };
      },
      "front-matter-format-nonstrict"
    );
    getFrontMatterSchema = defineCached(
      async () => {
        const executeObjSchema = await getFormatExecuteOptionsSchema();
        return {
          schema: anyOfSchema(
            nullSchema,
            allOfSchema(
              objectSchema({
                properties: {
                  execute: executeObjSchema,
                  format: await getFrontMatterFormatSchema()
                },
                description: "be a Quarto YAML front matter object"
              }),
              objectRefSchemaFromContextGlob(
                "document-*",
                (field) => field.name !== "format"
              ),
              executeObjSchema,
              refSchema("quarto-dev-schema", "")
            )
          ),
          errorHandlers: []
        };
      },
      "front-matter"
    );
  }
});

// core/lib/external/diff.js
function Diff() {
}
function buildValues(diff3, components, newString, oldString, useLongestToken) {
  var componentPos = 0, componentLen = components.length, newPos = 0, oldPos = 0;
  for (; componentPos < componentLen; componentPos++) {
    var component = components[componentPos];
    if (!component.removed) {
      if (!component.added && useLongestToken) {
        var value = newString.slice(newPos, newPos + component.count);
        value = value.map(function(value2, i6) {
          var oldValue = oldString[oldPos + i6];
          return oldValue.length > value2.length ? oldValue : value2;
        });
        component.value = diff3.join(value);
      } else {
        component.value = diff3.join(newString.slice(newPos, newPos + component.count));
      }
      newPos += component.count;
      if (!component.added) {
        oldPos += component.count;
      }
    } else {
      component.value = diff3.join(oldString.slice(oldPos, oldPos + component.count));
      oldPos += component.count;
      if (componentPos && components[componentPos - 1].added) {
        var tmp = components[componentPos - 1];
        components[componentPos - 1] = components[componentPos];
        components[componentPos] = tmp;
      }
    }
  }
  var lastComponent = components[componentLen - 1];
  if (componentLen > 1 && typeof lastComponent.value === "string" && (lastComponent.added || lastComponent.removed) && diff3.equals("", lastComponent.value)) {
    components[componentLen - 2].value += lastComponent.value;
    components.pop();
  }
  return components;
}
function clonePath(path3) {
  return {
    newPos: path3.newPos,
    components: path3.components.slice(0)
  };
}
function diffLines(oldStr, newStr, callback) {
  return lineDiff.diff(oldStr, newStr, callback);
}
function _typeof(obj) {
  "@babel/helpers - typeof";
  if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
    _typeof = function(obj2) {
      return typeof obj2;
    };
  } else {
    _typeof = function(obj2) {
      return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
    };
  }
  return _typeof(obj);
}
function canonicalize(obj, stack, replacementStack, replacer, key) {
  stack = stack || [];
  replacementStack = replacementStack || [];
  if (replacer) {
    obj = replacer(key, obj);
  }
  var i6;
  for (i6 = 0; i6 < stack.length; i6 += 1) {
    if (stack[i6] === obj) {
      return replacementStack[i6];
    }
  }
  var canonicalizedObj;
  if ("[object Array]" === objectPrototypeToString.call(obj)) {
    stack.push(obj);
    canonicalizedObj = new Array(obj.length);
    replacementStack.push(canonicalizedObj);
    for (i6 = 0; i6 < obj.length; i6 += 1) {
      canonicalizedObj[i6] = canonicalize(obj[i6], stack, replacementStack, replacer, key);
    }
    stack.pop();
    replacementStack.pop();
    return canonicalizedObj;
  }
  if (obj && obj.toJSON) {
    obj = obj.toJSON();
  }
  if (_typeof(obj) === "object" && obj !== null) {
    stack.push(obj);
    canonicalizedObj = {};
    replacementStack.push(canonicalizedObj);
    var sortedKeys = [], _key;
    for (_key in obj) {
      if (obj.hasOwnProperty(_key)) {
        sortedKeys.push(_key);
      }
    }
    sortedKeys.sort();
    for (i6 = 0; i6 < sortedKeys.length; i6 += 1) {
      _key = sortedKeys[i6];
      canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key);
    }
    stack.pop();
    replacementStack.pop();
  } else {
    canonicalizedObj = obj;
  }
  return canonicalizedObj;
}
var characterDiff, extendedWordChars, reWhitespace, wordDiff, lineDiff, sentenceDiff, cssDiff, objectPrototypeToString, jsonDiff, arrayDiff;
var init_diff = __esm({
  "core/lib/external/diff.js"() {
    Diff.prototype = {
      diff: function diff(oldString, newString) {
        var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
        var callback = options.callback;
        if (typeof options === "function") {
          callback = options;
          options = {};
        }
        this.options = options;
        var self2 = this;
        function done(value) {
          return value;
        }
        oldString = this.castInput(oldString);
        newString = this.castInput(newString);
        oldString = this.removeEmpty(this.tokenize(oldString));
        newString = this.removeEmpty(this.tokenize(newString));
        var newLen = newString.length, oldLen = oldString.length;
        var editLength = 1;
        var maxEditLength = newLen + oldLen;
        if (options.maxEditLength) {
          maxEditLength = Math.min(maxEditLength, options.maxEditLength);
        }
        var bestPath = [{
          newPos: -1,
          components: []
        }];
        var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
        if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
          return done([{
            value: this.join(newString),
            count: newString.length
          }]);
        }
        function execEditLength() {
          for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
            var basePath = void 0;
            var addPath2 = bestPath[diagonalPath - 1], removePath2 = bestPath[diagonalPath + 1], _oldPos = (removePath2 ? removePath2.newPos : 0) - diagonalPath;
            if (addPath2) {
              bestPath[diagonalPath - 1] = void 0;
            }
            var canAdd = addPath2 && addPath2.newPos + 1 < newLen, canRemove = removePath2 && 0 <= _oldPos && _oldPos < oldLen;
            if (!canAdd && !canRemove) {
              bestPath[diagonalPath] = void 0;
              continue;
            }
            if (!canAdd || canRemove && addPath2.newPos < removePath2.newPos) {
              basePath = clonePath(removePath2);
              self2.pushComponent(basePath.components, void 0, true);
            } else {
              basePath = addPath2;
              basePath.newPos++;
              self2.pushComponent(basePath.components, true, void 0);
            }
            _oldPos = self2.extractCommon(basePath, newString, oldString, diagonalPath);
            if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) {
              return done(buildValues(self2, basePath.components, newString, oldString, self2.useLongestToken));
            } else {
              bestPath[diagonalPath] = basePath;
            }
          }
          editLength++;
        }
        while (editLength <= maxEditLength) {
          var ret = execEditLength();
          if (callback && callback(ret, editLength, maxEditLength)) {
            return ret;
          }
          if (ret) {
            return ret;
          }
        }
      },
      pushComponent: function pushComponent(components, added, removed) {
        var last = components[components.length - 1];
        if (last && last.added === added && last.removed === removed) {
          components[components.length - 1] = {
            count: last.count + 1,
            added,
            removed
          };
        } else {
          components.push({
            count: 1,
            added,
            removed
          });
        }
      },
      extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) {
        var newLen = newString.length, oldLen = oldString.length, newPos = basePath.newPos, oldPos = newPos - diagonalPath, commonCount = 0;
        while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) {
          newPos++;
          oldPos++;
          commonCount++;
        }
        if (commonCount) {
          basePath.components.push({
            count: commonCount
          });
        }
        basePath.newPos = newPos;
        return oldPos;
      },
      equals: function equals(left, right) {
        if (this.options.comparator) {
          return this.options.comparator(left, right);
        } else {
          return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase();
        }
      },
      removeEmpty: function removeEmpty(array) {
        var ret = [];
        for (var i6 = 0; i6 < array.length; i6++) {
          if (array[i6]) {
            ret.push(array[i6]);
          }
        }
        return ret;
      },
      castInput: function castInput(value) {
        return value;
      },
      tokenize: function tokenize(value) {
        return value.split("");
      },
      join: function join6(chars) {
        return chars.join("");
      }
    };
    characterDiff = new Diff();
    extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/;
    reWhitespace = /\S/;
    wordDiff = new Diff();
    wordDiff.equals = function(left, right) {
      if (this.options.ignoreCase) {
        left = left.toLowerCase();
        right = right.toLowerCase();
      }
      return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right);
    };
    wordDiff.tokenize = function(value) {
      var tokens2 = value.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/);
      for (var i6 = 0; i6 < tokens2.length - 1; i6++) {
        if (!tokens2[i6 + 1] && tokens2[i6 + 2] && extendedWordChars.test(tokens2[i6]) && extendedWordChars.test(tokens2[i6 + 2])) {
          tokens2[i6] += tokens2[i6 + 2];
          tokens2.splice(i6 + 1, 2);
          i6--;
        }
      }
      return tokens2;
    };
    lineDiff = new Diff();
    lineDiff.tokenize = function(value) {
      var retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/);
      if (!linesAndNewlines[linesAndNewlines.length - 1]) {
        linesAndNewlines.pop();
      }
      for (var i6 = 0; i6 < linesAndNewlines.length; i6++) {
        var line = linesAndNewlines[i6];
        if (i6 % 2 && !this.options.newlineIsToken) {
          retLines[retLines.length - 1] += line;
        } else {
          if (this.options.ignoreWhitespace) {
            line = line.trim();
          }
          retLines.push(line);
        }
      }
      return retLines;
    };
    sentenceDiff = new Diff();
    sentenceDiff.tokenize = function(value) {
      return value.split(/(\S.+?[.!?])(?=\s+|$)/);
    };
    cssDiff = new Diff();
    cssDiff.tokenize = function(value) {
      return value.split(/([{}:;,]|\s+)/);
    };
    objectPrototypeToString = Object.prototype.toString;
    jsonDiff = new Diff();
    jsonDiff.useLongestToken = true;
    jsonDiff.tokenize = lineDiff.tokenize;
    jsonDiff.castInput = function(value) {
      var _this$options = this.options, undefinedReplacement = _this$options.undefinedReplacement, _this$options$stringi = _this$options.stringifyReplacer, stringifyReplacer = _this$options$stringi === void 0 ? function(k3, v4) {
        return typeof v4 === "undefined" ? undefinedReplacement : v4;
      } : _this$options$stringi;
      return typeof value === "string" ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, "  ");
    };
    jsonDiff.equals = function(left, right) {
      return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, "$1"), right.replace(/,([\r\n])/g, "$1"));
    };
    arrayDiff = new Diff();
    arrayDiff.tokenize = function(value) {
      return value.slice();
    };
    arrayDiff.join = arrayDiff.removeEmpty = function(value) {
      return value;
    };
  }
});

// core/timing.ts
function withTiming(name2, fun) {
  push(name2);
  try {
    const result2 = fun();
    return result2;
  } finally {
    pop();
  }
}
async function withTimingAsync(name2, fun) {
  push(name2);
  try {
    const result2 = await fun();
    pop();
    return result2;
  } catch (e5) {
    pop();
    throw e5;
  }
}
function push(name2) {
  nodeStack.push({
    name: name2,
    start: performance.now(),
    end: 0,
    children: []
  });
}
function pop(at3) {
  if (nodeStack.length <= 1) {
    throw new Error("Can't pop top node");
  }
  const node = nodeStack.pop();
  node.end = at3 ?? performance.now();
  node.elapsed = node.end - node.start;
  nodeStack[nodeStack.length - 1].children.push(node);
}
function getData() {
  nodeStack[0].end = performance.now();
  nodeStack[0].elapsed = nodeStack[0].end - nodeStack[0].start;
  return nodeStack[0];
}
var nodeStack;
var init_timing = __esm({
  "core/timing.ts"() {
    nodeStack = [{
      name: "global",
      children: [{
        name: "deno-init",
        start: 0,
        end: performance.now(),
        elapsed: performance.now(),
        children: []
      }],
      start: 0,
      end: 0
    }];
  }
});

// core/mapped-text.ts
function mappedDiffInner(source2, target) {
  return withTiming("mapped-diff", () => {
    const sourceLineRanges = rangedLines(source2.value).map((x3) => x3.range);
    let sourceCursor = 0;
    const resultChunks = [];
    const started = performance.now();
    const maxTime = 200;
    const diffResult = diffLines(
      source2.value,
      target,
      () => {
        const now = performance.now();
        if (now - started > maxTime) {
          return true;
        }
      }
    );
    if (diffResult === void 0) {
      debug(
        "The computation used to determine source line information from the engine timed out.\nLine number information will be unavailable and/or inaccurate."
      );
      return asMappedString(target);
    }
    for (const action of diffResult) {
      if (action.removed) {
        sourceCursor += action.count;
      } else if (action.added) {
        resultChunks.push(action.value);
      } else {
        const start = sourceLineRanges[sourceCursor].start;
        const nextCursor = sourceCursor + action.count;
        const end = nextCursor < sourceLineRanges.length ? sourceLineRanges[nextCursor].start : sourceLineRanges[sourceLineRanges.length - 1].end;
        sourceCursor = nextCursor;
        resultChunks.push({ start, end });
      }
    }
    return mappedString(source2, resultChunks, source2.fileName);
  });
}
function mappedStringFromFile(filename) {
  const value = Deno.readTextFileSync(filename);
  if (filename.startsWith("/")) {
    filename = relative4(Deno.cwd(), filename);
  }
  return asMappedString(value, filename);
}
var mappedDiff;
var init_mapped_text2 = __esm({
  "core/mapped-text.ts"() {
    init_diff();
    init_ranged_text();
    init_mapped_text();
    init_path();
    init_log();
    init_timing();
    init_function_times();
    init_mapped_text();
    mappedDiff = makeTimedFunction("mappedDiff", mappedDiffInner);
  }
});

// https://cdn.skypack.dev/-/js-yaml@v4.1.1-8B0j8wiUmEXyI4j5ClPv/dist=es2019,mode=imports/optimized/js-yaml.js
function isNothing2(subject) {
  return typeof subject === "undefined" || subject === null;
}
function isObject4(subject) {
  return typeof subject === "object" && subject !== null;
}
function toArray2(sequence) {
  if (Array.isArray(sequence))
    return sequence;
  else if (isNothing2(sequence))
    return [];
  return [sequence];
}
function extend3(target, source2) {
  var index2, length, key, sourceKeys;
  if (source2) {
    sourceKeys = Object.keys(source2);
    for (index2 = 0, length = sourceKeys.length; index2 < length; index2 += 1) {
      key = sourceKeys[index2];
      target[key] = source2[key];
    }
  }
  return target;
}
function repeat2(string2, count) {
  var result2 = "", cycle;
  for (cycle = 0; cycle < count; cycle += 1) {
    result2 += string2;
  }
  return result2;
}
function isNegativeZero2(number2) {
  return number2 === 0 && Number.NEGATIVE_INFINITY === 1 / number2;
}
function formatError2(exception22, compact) {
  var where = "", message = exception22.reason || "(unknown reason)";
  if (!exception22.mark)
    return message;
  if (exception22.mark.name) {
    where += 'in "' + exception22.mark.name + '" ';
  }
  where += "(" + (exception22.mark.line + 1) + ":" + (exception22.mark.column + 1) + ")";
  if (!compact && exception22.mark.snippet) {
    where += "\n\n" + exception22.mark.snippet;
  }
  return message + " " + where;
}
function YAMLException$12(reason, mark) {
  Error.call(this);
  this.name = "YAMLException";
  this.reason = reason;
  this.mark = mark;
  this.message = formatError2(this, false);
  if (Error.captureStackTrace) {
    Error.captureStackTrace(this, this.constructor);
  } else {
    this.stack = new Error().stack || "";
  }
}
function getLine2(buffer2, lineStart, lineEnd, position, maxLineLength) {
  var head = "";
  var tail = "";
  var maxHalfLength = Math.floor(maxLineLength / 2) - 1;
  if (position - lineStart > maxHalfLength) {
    head = " ... ";
    lineStart = position - maxHalfLength + head.length;
  }
  if (lineEnd - position > maxHalfLength) {
    tail = " ...";
    lineEnd = position + maxHalfLength - tail.length;
  }
  return {
    str: head + buffer2.slice(lineStart, lineEnd).replace(/\t/g, "\u2192") + tail,
    pos: position - lineStart + head.length
  };
}
function padStart2(string2, max) {
  return common3.repeat(" ", max - string2.length) + string2;
}
function makeSnippet2(mark, options) {
  options = Object.create(options || null);
  if (!mark.buffer)
    return null;
  if (!options.maxLength)
    options.maxLength = 79;
  if (typeof options.indent !== "number")
    options.indent = 1;
  if (typeof options.linesBefore !== "number")
    options.linesBefore = 3;
  if (typeof options.linesAfter !== "number")
    options.linesAfter = 2;
  var re3 = /\r?\n|\r|\0/g;
  var lineStarts = [0];
  var lineEnds = [];
  var match;
  var foundLineNo = -1;
  while (match = re3.exec(mark.buffer)) {
    lineEnds.push(match.index);
    lineStarts.push(match.index + match[0].length);
    if (mark.position <= match.index && foundLineNo < 0) {
      foundLineNo = lineStarts.length - 2;
    }
  }
  if (foundLineNo < 0)
    foundLineNo = lineStarts.length - 1;
  var result2 = "", i6, line;
  var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length;
  var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3);
  for (i6 = 1; i6 <= options.linesBefore; i6++) {
    if (foundLineNo - i6 < 0)
      break;
    line = getLine2(mark.buffer, lineStarts[foundLineNo - i6], lineEnds[foundLineNo - i6], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i6]), maxLineLength);
    result2 = common3.repeat(" ", options.indent) + padStart2((mark.line - i6 + 1).toString(), lineNoLength) + " | " + line.str + "\n" + result2;
  }
  line = getLine2(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength);
  result2 += common3.repeat(" ", options.indent) + padStart2((mark.line + 1).toString(), lineNoLength) + " | " + line.str + "\n";
  result2 += common3.repeat("-", options.indent + lineNoLength + 3 + line.pos) + "^\n";
  for (i6 = 1; i6 <= options.linesAfter; i6++) {
    if (foundLineNo + i6 >= lineEnds.length)
      break;
    line = getLine2(mark.buffer, lineStarts[foundLineNo + i6], lineEnds[foundLineNo + i6], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i6]), maxLineLength);
    result2 += common3.repeat(" ", options.indent) + padStart2((mark.line + i6 + 1).toString(), lineNoLength) + " | " + line.str + "\n";
  }
  return result2.replace(/\n$/, "");
}
function compileStyleAliases2(map22) {
  var result2 = {};
  if (map22 !== null) {
    Object.keys(map22).forEach(function(style) {
      map22[style].forEach(function(alias) {
        result2[String(alias)] = style;
      });
    });
  }
  return result2;
}
function Type$12(tag, options) {
  options = options || {};
  Object.keys(options).forEach(function(name2) {
    if (TYPE_CONSTRUCTOR_OPTIONS2.indexOf(name2) === -1) {
      throw new exception2('Unknown option "' + name2 + '" is met in definition of "' + tag + '" YAML type.');
    }
  });
  this.options = options;
  this.tag = tag;
  this.kind = options["kind"] || null;
  this.resolve = options["resolve"] || function() {
    return true;
  };
  this.construct = options["construct"] || function(data3) {
    return data3;
  };
  this.instanceOf = options["instanceOf"] || null;
  this.predicate = options["predicate"] || null;
  this.represent = options["represent"] || null;
  this.representName = options["representName"] || null;
  this.defaultStyle = options["defaultStyle"] || null;
  this.multi = options["multi"] || false;
  this.styleAliases = compileStyleAliases2(options["styleAliases"] || null);
  if (YAML_NODE_KINDS2.indexOf(this.kind) === -1) {
    throw new exception2('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.');
  }
}
function compileList2(schema22, name2) {
  var result2 = [];
  schema22[name2].forEach(function(currentType) {
    var newIndex = result2.length;
    result2.forEach(function(previousType, previousIndex) {
      if (previousType.tag === currentType.tag && previousType.kind === currentType.kind && previousType.multi === currentType.multi) {
        newIndex = previousIndex;
      }
    });
    result2[newIndex] = currentType;
  });
  return result2;
}
function compileMap2() {
  var result2 = {
    scalar: {},
    sequence: {},
    mapping: {},
    fallback: {},
    multi: {
      scalar: [],
      sequence: [],
      mapping: [],
      fallback: []
    }
  }, index2, length;
  function collectType(type22) {
    if (type22.multi) {
      result2.multi[type22.kind].push(type22);
      result2.multi["fallback"].push(type22);
    } else {
      result2[type22.kind][type22.tag] = result2["fallback"][type22.tag] = type22;
    }
  }
  for (index2 = 0, length = arguments.length; index2 < length; index2 += 1) {
    arguments[index2].forEach(collectType);
  }
  return result2;
}
function Schema$12(definition) {
  return this.extend(definition);
}
function resolveYamlNull2(data3) {
  if (data3 === null)
    return true;
  var max = data3.length;
  return max === 1 && data3 === "~" || max === 4 && (data3 === "null" || data3 === "Null" || data3 === "NULL");
}
function constructYamlNull2() {
  return null;
}
function isNull2(object) {
  return object === null;
}
function resolveYamlBoolean2(data3) {
  if (data3 === null)
    return false;
  var max = data3.length;
  return max === 4 && (data3 === "true" || data3 === "True" || data3 === "TRUE") || max === 5 && (data3 === "false" || data3 === "False" || data3 === "FALSE");
}
function constructYamlBoolean2(data3) {
  return data3 === "true" || data3 === "True" || data3 === "TRUE";
}
function isBoolean2(object) {
  return Object.prototype.toString.call(object) === "[object Boolean]";
}
function isHexCode2(c6) {
  return 48 <= c6 && c6 <= 57 || 65 <= c6 && c6 <= 70 || 97 <= c6 && c6 <= 102;
}
function isOctCode2(c6) {
  return 48 <= c6 && c6 <= 55;
}
function isDecCode2(c6) {
  return 48 <= c6 && c6 <= 57;
}
function resolveYamlInteger2(data3) {
  if (data3 === null)
    return false;
  var max = data3.length, index2 = 0, hasDigits = false, ch;
  if (!max)
    return false;
  ch = data3[index2];
  if (ch === "-" || ch === "+") {
    ch = data3[++index2];
  }
  if (ch === "0") {
    if (index2 + 1 === max)
      return true;
    ch = data3[++index2];
    if (ch === "b") {
      index2++;
      for (; index2 < max; index2++) {
        ch = data3[index2];
        if (ch === "_")
          continue;
        if (ch !== "0" && ch !== "1")
          return false;
        hasDigits = true;
      }
      return hasDigits && ch !== "_";
    }
    if (ch === "x") {
      index2++;
      for (; index2 < max; index2++) {
        ch = data3[index2];
        if (ch === "_")
          continue;
        if (!isHexCode2(data3.charCodeAt(index2)))
          return false;
        hasDigits = true;
      }
      return hasDigits && ch !== "_";
    }
    if (ch === "o") {
      index2++;
      for (; index2 < max; index2++) {
        ch = data3[index2];
        if (ch === "_")
          continue;
        if (!isOctCode2(data3.charCodeAt(index2)))
          return false;
        hasDigits = true;
      }
      return hasDigits && ch !== "_";
    }
  }
  if (ch === "_")
    return false;
  for (; index2 < max; index2++) {
    ch = data3[index2];
    if (ch === "_")
      continue;
    if (!isDecCode2(data3.charCodeAt(index2))) {
      return false;
    }
    hasDigits = true;
  }
  if (!hasDigits || ch === "_")
    return false;
  return true;
}
function constructYamlInteger2(data3) {
  var value = data3, sign = 1, ch;
  if (value.indexOf("_") !== -1) {
    value = value.replace(/_/g, "");
  }
  ch = value[0];
  if (ch === "-" || ch === "+") {
    if (ch === "-")
      sign = -1;
    value = value.slice(1);
    ch = value[0];
  }
  if (value === "0")
    return 0;
  if (ch === "0") {
    if (value[1] === "b")
      return sign * parseInt(value.slice(2), 2);
    if (value[1] === "x")
      return sign * parseInt(value.slice(2), 16);
    if (value[1] === "o")
      return sign * parseInt(value.slice(2), 8);
  }
  return sign * parseInt(value, 10);
}
function isInteger2(object) {
  return Object.prototype.toString.call(object) === "[object Number]" && (object % 1 === 0 && !common3.isNegativeZero(object));
}
function resolveYamlFloat2(data3) {
  if (data3 === null)
    return false;
  if (!YAML_FLOAT_PATTERN2.test(data3) || data3[data3.length - 1] === "_") {
    return false;
  }
  return true;
}
function constructYamlFloat2(data3) {
  var value, sign;
  value = data3.replace(/_/g, "").toLowerCase();
  sign = value[0] === "-" ? -1 : 1;
  if ("+-".indexOf(value[0]) >= 0) {
    value = value.slice(1);
  }
  if (value === ".inf") {
    return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
  } else if (value === ".nan") {
    return NaN;
  }
  return sign * parseFloat(value, 10);
}
function representYamlFloat2(object, style) {
  var res;
  if (isNaN(object)) {
    switch (style) {
      case "lowercase":
        return ".nan";
      case "uppercase":
        return ".NAN";
      case "camelcase":
        return ".NaN";
    }
  } else if (Number.POSITIVE_INFINITY === object) {
    switch (style) {
      case "lowercase":
        return ".inf";
      case "uppercase":
        return ".INF";
      case "camelcase":
        return ".Inf";
    }
  } else if (Number.NEGATIVE_INFINITY === object) {
    switch (style) {
      case "lowercase":
        return "-.inf";
      case "uppercase":
        return "-.INF";
      case "camelcase":
        return "-.Inf";
    }
  } else if (common3.isNegativeZero(object)) {
    return "-0.0";
  }
  res = object.toString(10);
  return SCIENTIFIC_WITHOUT_DOT2.test(res) ? res.replace("e", ".e") : res;
}
function isFloat2(object) {
  return Object.prototype.toString.call(object) === "[object Number]" && (object % 1 !== 0 || common3.isNegativeZero(object));
}
function resolveYamlTimestamp2(data3) {
  if (data3 === null)
    return false;
  if (YAML_DATE_REGEXP2.exec(data3) !== null)
    return true;
  if (YAML_TIMESTAMP_REGEXP2.exec(data3) !== null)
    return true;
  return false;
}
function constructYamlTimestamp2(data3) {
  var match, year, month, day, hour, minute, second, fraction = 0, delta = null, tz_hour, tz_minute, date;
  match = YAML_DATE_REGEXP2.exec(data3);
  if (match === null)
    match = YAML_TIMESTAMP_REGEXP2.exec(data3);
  if (match === null)
    throw new Error("Date resolve error");
  year = +match[1];
  month = +match[2] - 1;
  day = +match[3];
  if (!match[4]) {
    return new Date(Date.UTC(year, month, day));
  }
  hour = +match[4];
  minute = +match[5];
  second = +match[6];
  if (match[7]) {
    fraction = match[7].slice(0, 3);
    while (fraction.length < 3) {
      fraction += "0";
    }
    fraction = +fraction;
  }
  if (match[9]) {
    tz_hour = +match[10];
    tz_minute = +(match[11] || 0);
    delta = (tz_hour * 60 + tz_minute) * 6e4;
    if (match[9] === "-")
      delta = -delta;
  }
  date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));
  if (delta)
    date.setTime(date.getTime() - delta);
  return date;
}
function representYamlTimestamp2(object) {
  return object.toISOString();
}
function resolveYamlMerge2(data3) {
  return data3 === "<<" || data3 === null;
}
function resolveYamlBinary2(data3) {
  if (data3 === null)
    return false;
  var code5, idx, bitlen = 0, max = data3.length, map22 = BASE64_MAP2;
  for (idx = 0; idx < max; idx++) {
    code5 = map22.indexOf(data3.charAt(idx));
    if (code5 > 64)
      continue;
    if (code5 < 0)
      return false;
    bitlen += 6;
  }
  return bitlen % 8 === 0;
}
function constructYamlBinary2(data3) {
  var idx, tailbits, input = data3.replace(/[\r\n=]/g, ""), max = input.length, map22 = BASE64_MAP2, bits = 0, result2 = [];
  for (idx = 0; idx < max; idx++) {
    if (idx % 4 === 0 && idx) {
      result2.push(bits >> 16 & 255);
      result2.push(bits >> 8 & 255);
      result2.push(bits & 255);
    }
    bits = bits << 6 | map22.indexOf(input.charAt(idx));
  }
  tailbits = max % 4 * 6;
  if (tailbits === 0) {
    result2.push(bits >> 16 & 255);
    result2.push(bits >> 8 & 255);
    result2.push(bits & 255);
  } else if (tailbits === 18) {
    result2.push(bits >> 10 & 255);
    result2.push(bits >> 2 & 255);
  } else if (tailbits === 12) {
    result2.push(bits >> 4 & 255);
  }
  return new Uint8Array(result2);
}
function representYamlBinary2(object) {
  var result2 = "", bits = 0, idx, tail, max = object.length, map22 = BASE64_MAP2;
  for (idx = 0; idx < max; idx++) {
    if (idx % 3 === 0 && idx) {
      result2 += map22[bits >> 18 & 63];
      result2 += map22[bits >> 12 & 63];
      result2 += map22[bits >> 6 & 63];
      result2 += map22[bits & 63];
    }
    bits = (bits << 8) + object[idx];
  }
  tail = max % 3;
  if (tail === 0) {
    result2 += map22[bits >> 18 & 63];
    result2 += map22[bits >> 12 & 63];
    result2 += map22[bits >> 6 & 63];
    result2 += map22[bits & 63];
  } else if (tail === 2) {
    result2 += map22[bits >> 10 & 63];
    result2 += map22[bits >> 4 & 63];
    result2 += map22[bits << 2 & 63];
    result2 += map22[64];
  } else if (tail === 1) {
    result2 += map22[bits >> 2 & 63];
    result2 += map22[bits << 4 & 63];
    result2 += map22[64];
    result2 += map22[64];
  }
  return result2;
}
function isBinary2(obj) {
  return Object.prototype.toString.call(obj) === "[object Uint8Array]";
}
function resolveYamlOmap2(data3) {
  if (data3 === null)
    return true;
  var objectKeys = [], index2, length, pair, pairKey, pairHasKey, object = data3;
  for (index2 = 0, length = object.length; index2 < length; index2 += 1) {
    pair = object[index2];
    pairHasKey = false;
    if (_toString$22.call(pair) !== "[object Object]")
      return false;
    for (pairKey in pair) {
      if (_hasOwnProperty$32.call(pair, pairKey)) {
        if (!pairHasKey)
          pairHasKey = true;
        else
          return false;
      }
    }
    if (!pairHasKey)
      return false;
    if (objectKeys.indexOf(pairKey) === -1)
      objectKeys.push(pairKey);
    else
      return false;
  }
  return true;
}
function constructYamlOmap2(data3) {
  return data3 !== null ? data3 : [];
}
function resolveYamlPairs2(data3) {
  if (data3 === null)
    return true;
  var index2, length, pair, keys, result2, object = data3;
  result2 = new Array(object.length);
  for (index2 = 0, length = object.length; index2 < length; index2 += 1) {
    pair = object[index2];
    if (_toString$12.call(pair) !== "[object Object]")
      return false;
    keys = Object.keys(pair);
    if (keys.length !== 1)
      return false;
    result2[index2] = [keys[0], pair[keys[0]]];
  }
  return true;
}
function constructYamlPairs2(data3) {
  if (data3 === null)
    return [];
  var index2, length, pair, keys, result2, object = data3;
  result2 = new Array(object.length);
  for (index2 = 0, length = object.length; index2 < length; index2 += 1) {
    pair = object[index2];
    keys = Object.keys(pair);
    result2[index2] = [keys[0], pair[keys[0]]];
  }
  return result2;
}
function resolveYamlSet2(data3) {
  if (data3 === null)
    return true;
  var key, object = data3;
  for (key in object) {
    if (_hasOwnProperty$22.call(object, key)) {
      if (object[key] !== null)
        return false;
    }
  }
  return true;
}
function constructYamlSet2(data3) {
  return data3 !== null ? data3 : {};
}
function _class2(obj) {
  return Object.prototype.toString.call(obj);
}
function is_EOL2(c6) {
  return c6 === 10 || c6 === 13;
}
function is_WHITE_SPACE2(c6) {
  return c6 === 9 || c6 === 32;
}
function is_WS_OR_EOL2(c6) {
  return c6 === 9 || c6 === 32 || c6 === 10 || c6 === 13;
}
function is_FLOW_INDICATOR2(c6) {
  return c6 === 44 || c6 === 91 || c6 === 93 || c6 === 123 || c6 === 125;
}
function fromHexCode2(c6) {
  var lc;
  if (48 <= c6 && c6 <= 57) {
    return c6 - 48;
  }
  lc = c6 | 32;
  if (97 <= lc && lc <= 102) {
    return lc - 97 + 10;
  }
  return -1;
}
function escapedHexLen2(c6) {
  if (c6 === 120) {
    return 2;
  }
  if (c6 === 117) {
    return 4;
  }
  if (c6 === 85) {
    return 8;
  }
  return 0;
}
function fromDecimalCode2(c6) {
  if (48 <= c6 && c6 <= 57) {
    return c6 - 48;
  }
  return -1;
}
function simpleEscapeSequence2(c6) {
  return c6 === 48 ? "\0" : c6 === 97 ? "\x07" : c6 === 98 ? "\b" : c6 === 116 ? "	" : c6 === 9 ? "	" : c6 === 110 ? "\n" : c6 === 118 ? "\v" : c6 === 102 ? "\f" : c6 === 114 ? "\r" : c6 === 101 ? "\x1B" : c6 === 32 ? " " : c6 === 34 ? '"' : c6 === 47 ? "/" : c6 === 92 ? "\\" : c6 === 78 ? "\x85" : c6 === 95 ? "\xA0" : c6 === 76 ? "\u2028" : c6 === 80 ? "\u2029" : "";
}
function charFromCodepoint2(c6) {
  if (c6 <= 65535) {
    return String.fromCharCode(c6);
  }
  return String.fromCharCode((c6 - 65536 >> 10) + 55296, (c6 - 65536 & 1023) + 56320);
}
function setProperty(object, key, value) {
  if (key === "__proto__") {
    Object.defineProperty(object, key, {
      configurable: true,
      enumerable: true,
      writable: true,
      value
    });
  } else {
    object[key] = value;
  }
}
function State$12(input, options) {
  this.input = input;
  this.filename = options["filename"] || null;
  this.schema = options["schema"] || _default2;
  this.onWarning = options["onWarning"] || null;
  this.legacy = options["legacy"] || false;
  this.json = options["json"] || false;
  this.listener = options["listener"] || null;
  this.implicitTypes = this.schema.compiledImplicit;
  this.typeMap = this.schema.compiledTypeMap;
  this.length = input.length;
  this.position = 0;
  this.line = 0;
  this.lineStart = 0;
  this.lineIndent = 0;
  this.firstTabInLine = -1;
  this.documents = [];
}
function generateError2(state2, message) {
  var mark = {
    name: state2.filename,
    buffer: state2.input.slice(0, -1),
    position: state2.position,
    line: state2.line,
    column: state2.position - state2.lineStart
  };
  mark.snippet = snippet2(mark);
  return new exception2(message, mark);
}
function throwError2(state2, message) {
  throw generateError2(state2, message);
}
function throwWarning2(state2, message) {
  if (state2.onWarning) {
    state2.onWarning.call(null, generateError2(state2, message));
  }
}
function captureSegment2(state2, start, end, checkJson) {
  var _position, _length, _character, _result;
  if (start < end) {
    _result = state2.input.slice(start, end);
    if (checkJson) {
      for (_position = 0, _length = _result.length; _position < _length; _position += 1) {
        _character = _result.charCodeAt(_position);
        if (!(_character === 9 || 32 <= _character && _character <= 1114111)) {
          throwError2(state2, "expected valid JSON character");
        }
      }
    } else if (PATTERN_NON_PRINTABLE2.test(_result)) {
      throwError2(state2, "the stream contains non-printable characters");
    }
    state2.result += _result;
  }
}
function mergeMappings2(state2, destination, source2, overridableKeys) {
  var sourceKeys, key, index2, quantity;
  if (!common3.isObject(source2)) {
    throwError2(state2, "cannot merge mappings; the provided source object is unacceptable");
  }
  sourceKeys = Object.keys(source2);
  for (index2 = 0, quantity = sourceKeys.length; index2 < quantity; index2 += 1) {
    key = sourceKeys[index2];
    if (!_hasOwnProperty$12.call(destination, key)) {
      setProperty(destination, key, source2[key]);
      overridableKeys[key] = true;
    }
  }
}
function storeMappingPair2(state2, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startLineStart, startPos) {
  var index2, quantity;
  if (Array.isArray(keyNode)) {
    keyNode = Array.prototype.slice.call(keyNode);
    for (index2 = 0, quantity = keyNode.length; index2 < quantity; index2 += 1) {
      if (Array.isArray(keyNode[index2])) {
        throwError2(state2, "nested arrays are not supported inside keys");
      }
      if (typeof keyNode === "object" && _class2(keyNode[index2]) === "[object Object]") {
        keyNode[index2] = "[object Object]";
      }
    }
  }
  if (typeof keyNode === "object" && _class2(keyNode) === "[object Object]") {
    keyNode = "[object Object]";
  }
  keyNode = String(keyNode);
  if (_result === null) {
    _result = {};
  }
  if (keyTag === "tag:yaml.org,2002:merge") {
    if (Array.isArray(valueNode)) {
      for (index2 = 0, quantity = valueNode.length; index2 < quantity; index2 += 1) {
        mergeMappings2(state2, _result, valueNode[index2], overridableKeys);
      }
    } else {
      mergeMappings2(state2, _result, valueNode, overridableKeys);
    }
  } else {
    if (!state2.json && !_hasOwnProperty$12.call(overridableKeys, keyNode) && _hasOwnProperty$12.call(_result, keyNode)) {
      state2.line = startLine || state2.line;
      state2.lineStart = startLineStart || state2.lineStart;
      state2.position = startPos || state2.position;
      throwError2(state2, "duplicated mapping key");
    }
    setProperty(_result, keyNode, valueNode);
    delete overridableKeys[keyNode];
  }
  return _result;
}
function readLineBreak2(state2) {
  var ch;
  ch = state2.input.charCodeAt(state2.position);
  if (ch === 10) {
    state2.position++;
  } else if (ch === 13) {
    state2.position++;
    if (state2.input.charCodeAt(state2.position) === 10) {
      state2.position++;
    }
  } else {
    throwError2(state2, "a line break is expected");
  }
  state2.line += 1;
  state2.lineStart = state2.position;
  state2.firstTabInLine = -1;
}
function skipSeparationSpace2(state2, allowComments, checkIndent) {
  var lineBreaks = 0, ch = state2.input.charCodeAt(state2.position);
  while (ch !== 0) {
    while (is_WHITE_SPACE2(ch)) {
      if (ch === 9 && state2.firstTabInLine === -1) {
        state2.firstTabInLine = state2.position;
      }
      ch = state2.input.charCodeAt(++state2.position);
    }
    if (allowComments && ch === 35) {
      do {
        ch = state2.input.charCodeAt(++state2.position);
      } while (ch !== 10 && ch !== 13 && ch !== 0);
    }
    if (is_EOL2(ch)) {
      readLineBreak2(state2);
      ch = state2.input.charCodeAt(state2.position);
      lineBreaks++;
      state2.lineIndent = 0;
      while (ch === 32) {
        state2.lineIndent++;
        ch = state2.input.charCodeAt(++state2.position);
      }
    } else {
      break;
    }
  }
  if (checkIndent !== -1 && lineBreaks !== 0 && state2.lineIndent < checkIndent) {
    throwWarning2(state2, "deficient indentation");
  }
  return lineBreaks;
}
function testDocumentSeparator2(state2) {
  var _position = state2.position, ch;
  ch = state2.input.charCodeAt(_position);
  if ((ch === 45 || ch === 46) && ch === state2.input.charCodeAt(_position + 1) && ch === state2.input.charCodeAt(_position + 2)) {
    _position += 3;
    ch = state2.input.charCodeAt(_position);
    if (ch === 0 || is_WS_OR_EOL2(ch)) {
      return true;
    }
  }
  return false;
}
function writeFoldedLines2(state2, count) {
  if (count === 1) {
    state2.result += " ";
  } else if (count > 1) {
    state2.result += common3.repeat("\n", count - 1);
  }
}
function readPlainScalar2(state2, nodeIndent, withinFlowCollection) {
  var preceding, following, captureStart, captureEnd, hasPendingContent, _line, _lineStart, _lineIndent, _kind = state2.kind, _result = state2.result, ch;
  ch = state2.input.charCodeAt(state2.position);
  if (is_WS_OR_EOL2(ch) || is_FLOW_INDICATOR2(ch) || ch === 35 || ch === 38 || ch === 42 || ch === 33 || ch === 124 || ch === 62 || ch === 39 || ch === 34 || ch === 37 || ch === 64 || ch === 96) {
    return false;
  }
  if (ch === 63 || ch === 45) {
    following = state2.input.charCodeAt(state2.position + 1);
    if (is_WS_OR_EOL2(following) || withinFlowCollection && is_FLOW_INDICATOR2(following)) {
      return false;
    }
  }
  state2.kind = "scalar";
  state2.result = "";
  captureStart = captureEnd = state2.position;
  hasPendingContent = false;
  while (ch !== 0) {
    if (ch === 58) {
      following = state2.input.charCodeAt(state2.position + 1);
      if (is_WS_OR_EOL2(following) || withinFlowCollection && is_FLOW_INDICATOR2(following)) {
        break;
      }
    } else if (ch === 35) {
      preceding = state2.input.charCodeAt(state2.position - 1);
      if (is_WS_OR_EOL2(preceding)) {
        break;
      }
    } else if (state2.position === state2.lineStart && testDocumentSeparator2(state2) || withinFlowCollection && is_FLOW_INDICATOR2(ch)) {
      break;
    } else if (is_EOL2(ch)) {
      _line = state2.line;
      _lineStart = state2.lineStart;
      _lineIndent = state2.lineIndent;
      skipSeparationSpace2(state2, false, -1);
      if (state2.lineIndent >= nodeIndent) {
        hasPendingContent = true;
        ch = state2.input.charCodeAt(state2.position);
        continue;
      } else {
        state2.position = captureEnd;
        state2.line = _line;
        state2.lineStart = _lineStart;
        state2.lineIndent = _lineIndent;
        break;
      }
    }
    if (hasPendingContent) {
      captureSegment2(state2, captureStart, captureEnd, false);
      writeFoldedLines2(state2, state2.line - _line);
      captureStart = captureEnd = state2.position;
      hasPendingContent = false;
    }
    if (!is_WHITE_SPACE2(ch)) {
      captureEnd = state2.position + 1;
    }
    ch = state2.input.charCodeAt(++state2.position);
  }
  captureSegment2(state2, captureStart, captureEnd, false);
  if (state2.result) {
    return true;
  }
  state2.kind = _kind;
  state2.result = _result;
  return false;
}
function readSingleQuotedScalar2(state2, nodeIndent) {
  var ch, captureStart, captureEnd;
  ch = state2.input.charCodeAt(state2.position);
  if (ch !== 39) {
    return false;
  }
  state2.kind = "scalar";
  state2.result = "";
  state2.position++;
  captureStart = captureEnd = state2.position;
  while ((ch = state2.input.charCodeAt(state2.position)) !== 0) {
    if (ch === 39) {
      captureSegment2(state2, captureStart, state2.position, true);
      ch = state2.input.charCodeAt(++state2.position);
      if (ch === 39) {
        captureStart = state2.position;
        state2.position++;
        captureEnd = state2.position;
      } else {
        return true;
      }
    } else if (is_EOL2(ch)) {
      captureSegment2(state2, captureStart, captureEnd, true);
      writeFoldedLines2(state2, skipSeparationSpace2(state2, false, nodeIndent));
      captureStart = captureEnd = state2.position;
    } else if (state2.position === state2.lineStart && testDocumentSeparator2(state2)) {
      throwError2(state2, "unexpected end of the document within a single quoted scalar");
    } else {
      state2.position++;
      captureEnd = state2.position;
    }
  }
  throwError2(state2, "unexpected end of the stream within a single quoted scalar");
}
function readDoubleQuotedScalar2(state2, nodeIndent) {
  var captureStart, captureEnd, hexLength, hexResult, tmp, ch;
  ch = state2.input.charCodeAt(state2.position);
  if (ch !== 34) {
    return false;
  }
  state2.kind = "scalar";
  state2.result = "";
  state2.position++;
  captureStart = captureEnd = state2.position;
  while ((ch = state2.input.charCodeAt(state2.position)) !== 0) {
    if (ch === 34) {
      captureSegment2(state2, captureStart, state2.position, true);
      state2.position++;
      return true;
    } else if (ch === 92) {
      captureSegment2(state2, captureStart, state2.position, true);
      ch = state2.input.charCodeAt(++state2.position);
      if (is_EOL2(ch)) {
        skipSeparationSpace2(state2, false, nodeIndent);
      } else if (ch < 256 && simpleEscapeCheck2[ch]) {
        state2.result += simpleEscapeMap2[ch];
        state2.position++;
      } else if ((tmp = escapedHexLen2(ch)) > 0) {
        hexLength = tmp;
        hexResult = 0;
        for (; hexLength > 0; hexLength--) {
          ch = state2.input.charCodeAt(++state2.position);
          if ((tmp = fromHexCode2(ch)) >= 0) {
            hexResult = (hexResult << 4) + tmp;
          } else {
            throwError2(state2, "expected hexadecimal character");
          }
        }
        state2.result += charFromCodepoint2(hexResult);
        state2.position++;
      } else {
        throwError2(state2, "unknown escape sequence");
      }
      captureStart = captureEnd = state2.position;
    } else if (is_EOL2(ch)) {
      captureSegment2(state2, captureStart, captureEnd, true);
      writeFoldedLines2(state2, skipSeparationSpace2(state2, false, nodeIndent));
      captureStart = captureEnd = state2.position;
    } else if (state2.position === state2.lineStart && testDocumentSeparator2(state2)) {
      throwError2(state2, "unexpected end of the document within a double quoted scalar");
    } else {
      state2.position++;
      captureEnd = state2.position;
    }
  }
  throwError2(state2, "unexpected end of the stream within a double quoted scalar");
}
function readFlowCollection2(state2, nodeIndent) {
  var readNext = true, _line, _lineStart, _pos, _tag = state2.tag, _result, _anchor = state2.anchor, following, terminator, isPair, isExplicitPair, isMapping, overridableKeys = /* @__PURE__ */ Object.create(null), keyNode, keyTag, valueNode, ch;
  ch = state2.input.charCodeAt(state2.position);
  if (ch === 91) {
    terminator = 93;
    isMapping = false;
    _result = [];
  } else if (ch === 123) {
    terminator = 125;
    isMapping = true;
    _result = {};
  } else {
    return false;
  }
  if (state2.anchor !== null) {
    state2.anchorMap[state2.anchor] = _result;
  }
  ch = state2.input.charCodeAt(++state2.position);
  while (ch !== 0) {
    skipSeparationSpace2(state2, true, nodeIndent);
    ch = state2.input.charCodeAt(state2.position);
    if (ch === terminator) {
      state2.position++;
      state2.tag = _tag;
      state2.anchor = _anchor;
      state2.kind = isMapping ? "mapping" : "sequence";
      state2.result = _result;
      return true;
    } else if (!readNext) {
      throwError2(state2, "missed comma between flow collection entries");
    } else if (ch === 44) {
      throwError2(state2, "expected the node content, but found ','");
    }
    keyTag = keyNode = valueNode = null;
    isPair = isExplicitPair = false;
    if (ch === 63) {
      following = state2.input.charCodeAt(state2.position + 1);
      if (is_WS_OR_EOL2(following)) {
        isPair = isExplicitPair = true;
        state2.position++;
        skipSeparationSpace2(state2, true, nodeIndent);
      }
    }
    _line = state2.line;
    _lineStart = state2.lineStart;
    _pos = state2.position;
    composeNode2(state2, nodeIndent, CONTEXT_FLOW_IN2, false, true);
    keyTag = state2.tag;
    keyNode = state2.result;
    skipSeparationSpace2(state2, true, nodeIndent);
    ch = state2.input.charCodeAt(state2.position);
    if ((isExplicitPair || state2.line === _line) && ch === 58) {
      isPair = true;
      ch = state2.input.charCodeAt(++state2.position);
      skipSeparationSpace2(state2, true, nodeIndent);
      composeNode2(state2, nodeIndent, CONTEXT_FLOW_IN2, false, true);
      valueNode = state2.result;
    }
    if (isMapping) {
      storeMappingPair2(state2, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos);
    } else if (isPair) {
      _result.push(storeMappingPair2(state2, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos));
    } else {
      _result.push(keyNode);
    }
    skipSeparationSpace2(state2, true, nodeIndent);
    ch = state2.input.charCodeAt(state2.position);
    if (ch === 44) {
      readNext = true;
      ch = state2.input.charCodeAt(++state2.position);
    } else {
      readNext = false;
    }
  }
  throwError2(state2, "unexpected end of the stream within a flow collection");
}
function readBlockScalar2(state2, nodeIndent) {
  var captureStart, folding, chomping = CHOMPING_CLIP2, didReadContent = false, detectedIndent = false, textIndent = nodeIndent, emptyLines = 0, atMoreIndented = false, tmp, ch;
  ch = state2.input.charCodeAt(state2.position);
  if (ch === 124) {
    folding = false;
  } else if (ch === 62) {
    folding = true;
  } else {
    return false;
  }
  state2.kind = "scalar";
  state2.result = "";
  while (ch !== 0) {
    ch = state2.input.charCodeAt(++state2.position);
    if (ch === 43 || ch === 45) {
      if (CHOMPING_CLIP2 === chomping) {
        chomping = ch === 43 ? CHOMPING_KEEP2 : CHOMPING_STRIP2;
      } else {
        throwError2(state2, "repeat of a chomping mode identifier");
      }
    } else if ((tmp = fromDecimalCode2(ch)) >= 0) {
      if (tmp === 0) {
        throwError2(state2, "bad explicit indentation width of a block scalar; it cannot be less than one");
      } else if (!detectedIndent) {
        textIndent = nodeIndent + tmp - 1;
        detectedIndent = true;
      } else {
        throwError2(state2, "repeat of an indentation width identifier");
      }
    } else {
      break;
    }
  }
  if (is_WHITE_SPACE2(ch)) {
    do {
      ch = state2.input.charCodeAt(++state2.position);
    } while (is_WHITE_SPACE2(ch));
    if (ch === 35) {
      do {
        ch = state2.input.charCodeAt(++state2.position);
      } while (!is_EOL2(ch) && ch !== 0);
    }
  }
  while (ch !== 0) {
    readLineBreak2(state2);
    state2.lineIndent = 0;
    ch = state2.input.charCodeAt(state2.position);
    while ((!detectedIndent || state2.lineIndent < textIndent) && ch === 32) {
      state2.lineIndent++;
      ch = state2.input.charCodeAt(++state2.position);
    }
    if (!detectedIndent && state2.lineIndent > textIndent) {
      textIndent = state2.lineIndent;
    }
    if (is_EOL2(ch)) {
      emptyLines++;
      continue;
    }
    if (state2.lineIndent < textIndent) {
      if (chomping === CHOMPING_KEEP2) {
        state2.result += common3.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines);
      } else if (chomping === CHOMPING_CLIP2) {
        if (didReadContent) {
          state2.result += "\n";
        }
      }
      break;
    }
    if (folding) {
      if (is_WHITE_SPACE2(ch)) {
        atMoreIndented = true;
        state2.result += common3.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines);
      } else if (atMoreIndented) {
        atMoreIndented = false;
        state2.result += common3.repeat("\n", emptyLines + 1);
      } else if (emptyLines === 0) {
        if (didReadContent) {
          state2.result += " ";
        }
      } else {
        state2.result += common3.repeat("\n", emptyLines);
      }
    } else {
      state2.result += common3.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines);
    }
    didReadContent = true;
    detectedIndent = true;
    emptyLines = 0;
    captureStart = state2.position;
    while (!is_EOL2(ch) && ch !== 0) {
      ch = state2.input.charCodeAt(++state2.position);
    }
    captureSegment2(state2, captureStart, state2.position, false);
  }
  return true;
}
function readBlockSequence2(state2, nodeIndent) {
  var _line, _tag = state2.tag, _anchor = state2.anchor, _result = [], following, detected = false, ch;
  if (state2.firstTabInLine !== -1)
    return false;
  if (state2.anchor !== null) {
    state2.anchorMap[state2.anchor] = _result;
  }
  ch = state2.input.charCodeAt(state2.position);
  while (ch !== 0) {
    if (state2.firstTabInLine !== -1) {
      state2.position = state2.firstTabInLine;
      throwError2(state2, "tab characters must not be used in indentation");
    }
    if (ch !== 45) {
      break;
    }
    following = state2.input.charCodeAt(state2.position + 1);
    if (!is_WS_OR_EOL2(following)) {
      break;
    }
    detected = true;
    state2.position++;
    if (skipSeparationSpace2(state2, true, -1)) {
      if (state2.lineIndent <= nodeIndent) {
        _result.push(null);
        ch = state2.input.charCodeAt(state2.position);
        continue;
      }
    }
    _line = state2.line;
    composeNode2(state2, nodeIndent, CONTEXT_BLOCK_IN2, false, true);
    _result.push(state2.result);
    skipSeparationSpace2(state2, true, -1);
    ch = state2.input.charCodeAt(state2.position);
    if ((state2.line === _line || state2.lineIndent > nodeIndent) && ch !== 0) {
      throwError2(state2, "bad indentation of a sequence entry");
    } else if (state2.lineIndent < nodeIndent) {
      break;
    }
  }
  if (detected) {
    state2.tag = _tag;
    state2.anchor = _anchor;
    state2.kind = "sequence";
    state2.result = _result;
    return true;
  }
  return false;
}
function readBlockMapping2(state2, nodeIndent, flowIndent) {
  var following, allowCompact, _line, _keyLine, _keyLineStart, _keyPos, _tag = state2.tag, _anchor = state2.anchor, _result = {}, overridableKeys = /* @__PURE__ */ Object.create(null), keyTag = null, keyNode = null, valueNode = null, atExplicitKey = false, detected = false, ch;
  if (state2.firstTabInLine !== -1)
    return false;
  if (state2.anchor !== null) {
    state2.anchorMap[state2.anchor] = _result;
  }
  ch = state2.input.charCodeAt(state2.position);
  while (ch !== 0) {
    if (!atExplicitKey && state2.firstTabInLine !== -1) {
      state2.position = state2.firstTabInLine;
      throwError2(state2, "tab characters must not be used in indentation");
    }
    following = state2.input.charCodeAt(state2.position + 1);
    _line = state2.line;
    if ((ch === 63 || ch === 58) && is_WS_OR_EOL2(following)) {
      if (ch === 63) {
        if (atExplicitKey) {
          storeMappingPair2(state2, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
          keyTag = keyNode = valueNode = null;
        }
        detected = true;
        atExplicitKey = true;
        allowCompact = true;
      } else if (atExplicitKey) {
        atExplicitKey = false;
        allowCompact = true;
      } else {
        throwError2(state2, "incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line");
      }
      state2.position += 1;
      ch = following;
    } else {
      _keyLine = state2.line;
      _keyLineStart = state2.lineStart;
      _keyPos = state2.position;
      if (!composeNode2(state2, flowIndent, CONTEXT_FLOW_OUT2, false, true)) {
        break;
      }
      if (state2.line === _line) {
        ch = state2.input.charCodeAt(state2.position);
        while (is_WHITE_SPACE2(ch)) {
          ch = state2.input.charCodeAt(++state2.position);
        }
        if (ch === 58) {
          ch = state2.input.charCodeAt(++state2.position);
          if (!is_WS_OR_EOL2(ch)) {
            throwError2(state2, "a whitespace character is expected after the key-value separator within a block mapping");
          }
          if (atExplicitKey) {
            storeMappingPair2(state2, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
            keyTag = keyNode = valueNode = null;
          }
          detected = true;
          atExplicitKey = false;
          allowCompact = false;
          keyTag = state2.tag;
          keyNode = state2.result;
        } else if (detected) {
          throwError2(state2, "can not read an implicit mapping pair; a colon is missed");
        } else {
          state2.tag = _tag;
          state2.anchor = _anchor;
          return true;
        }
      } else if (detected) {
        throwError2(state2, "can not read a block mapping entry; a multiline key may not be an implicit key");
      } else {
        state2.tag = _tag;
        state2.anchor = _anchor;
        return true;
      }
    }
    if (state2.line === _line || state2.lineIndent > nodeIndent) {
      if (atExplicitKey) {
        _keyLine = state2.line;
        _keyLineStart = state2.lineStart;
        _keyPos = state2.position;
      }
      if (composeNode2(state2, nodeIndent, CONTEXT_BLOCK_OUT2, true, allowCompact)) {
        if (atExplicitKey) {
          keyNode = state2.result;
        } else {
          valueNode = state2.result;
        }
      }
      if (!atExplicitKey) {
        storeMappingPair2(state2, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos);
        keyTag = keyNode = valueNode = null;
      }
      skipSeparationSpace2(state2, true, -1);
      ch = state2.input.charCodeAt(state2.position);
    }
    if ((state2.line === _line || state2.lineIndent > nodeIndent) && ch !== 0) {
      throwError2(state2, "bad indentation of a mapping entry");
    } else if (state2.lineIndent < nodeIndent) {
      break;
    }
  }
  if (atExplicitKey) {
    storeMappingPair2(state2, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
  }
  if (detected) {
    state2.tag = _tag;
    state2.anchor = _anchor;
    state2.kind = "mapping";
    state2.result = _result;
  }
  return detected;
}
function readTagProperty2(state2) {
  var _position, isVerbatim = false, isNamed = false, tagHandle, tagName, ch;
  ch = state2.input.charCodeAt(state2.position);
  if (ch !== 33)
    return false;
  if (state2.tag !== null) {
    throwError2(state2, "duplication of a tag property");
  }
  ch = state2.input.charCodeAt(++state2.position);
  if (ch === 60) {
    isVerbatim = true;
    ch = state2.input.charCodeAt(++state2.position);
  } else if (ch === 33) {
    isNamed = true;
    tagHandle = "!!";
    ch = state2.input.charCodeAt(++state2.position);
  } else {
    tagHandle = "!";
  }
  _position = state2.position;
  if (isVerbatim) {
    do {
      ch = state2.input.charCodeAt(++state2.position);
    } while (ch !== 0 && ch !== 62);
    if (state2.position < state2.length) {
      tagName = state2.input.slice(_position, state2.position);
      ch = state2.input.charCodeAt(++state2.position);
    } else {
      throwError2(state2, "unexpected end of the stream within a verbatim tag");
    }
  } else {
    while (ch !== 0 && !is_WS_OR_EOL2(ch)) {
      if (ch === 33) {
        if (!isNamed) {
          tagHandle = state2.input.slice(_position - 1, state2.position + 1);
          if (!PATTERN_TAG_HANDLE2.test(tagHandle)) {
            throwError2(state2, "named tag handle cannot contain such characters");
          }
          isNamed = true;
          _position = state2.position + 1;
        } else {
          throwError2(state2, "tag suffix cannot contain exclamation marks");
        }
      }
      ch = state2.input.charCodeAt(++state2.position);
    }
    tagName = state2.input.slice(_position, state2.position);
    if (PATTERN_FLOW_INDICATORS2.test(tagName)) {
      throwError2(state2, "tag suffix cannot contain flow indicator characters");
    }
  }
  if (tagName && !PATTERN_TAG_URI2.test(tagName)) {
    throwError2(state2, "tag name cannot contain such characters: " + tagName);
  }
  try {
    tagName = decodeURIComponent(tagName);
  } catch (err2) {
    throwError2(state2, "tag name is malformed: " + tagName);
  }
  if (isVerbatim) {
    state2.tag = tagName;
  } else if (_hasOwnProperty$12.call(state2.tagMap, tagHandle)) {
    state2.tag = state2.tagMap[tagHandle] + tagName;
  } else if (tagHandle === "!") {
    state2.tag = "!" + tagName;
  } else if (tagHandle === "!!") {
    state2.tag = "tag:yaml.org,2002:" + tagName;
  } else {
    throwError2(state2, 'undeclared tag handle "' + tagHandle + '"');
  }
  return true;
}
function readAnchorProperty2(state2) {
  var _position, ch;
  ch = state2.input.charCodeAt(state2.position);
  if (ch !== 38)
    return false;
  if (state2.anchor !== null) {
    throwError2(state2, "duplication of an anchor property");
  }
  ch = state2.input.charCodeAt(++state2.position);
  _position = state2.position;
  while (ch !== 0 && !is_WS_OR_EOL2(ch) && !is_FLOW_INDICATOR2(ch)) {
    ch = state2.input.charCodeAt(++state2.position);
  }
  if (state2.position === _position) {
    throwError2(state2, "name of an anchor node must contain at least one character");
  }
  state2.anchor = state2.input.slice(_position, state2.position);
  return true;
}
function readAlias2(state2) {
  var _position, alias, ch;
  ch = state2.input.charCodeAt(state2.position);
  if (ch !== 42)
    return false;
  ch = state2.input.charCodeAt(++state2.position);
  _position = state2.position;
  while (ch !== 0 && !is_WS_OR_EOL2(ch) && !is_FLOW_INDICATOR2(ch)) {
    ch = state2.input.charCodeAt(++state2.position);
  }
  if (state2.position === _position) {
    throwError2(state2, "name of an alias node must contain at least one character");
  }
  alias = state2.input.slice(_position, state2.position);
  if (!_hasOwnProperty$12.call(state2.anchorMap, alias)) {
    throwError2(state2, 'unidentified alias "' + alias + '"');
  }
  state2.result = state2.anchorMap[alias];
  skipSeparationSpace2(state2, true, -1);
  return true;
}
function composeNode2(state2, parentIndent, nodeContext, allowToSeek, allowCompact) {
  var allowBlockStyles, allowBlockScalars, allowBlockCollections, indentStatus = 1, atNewLine = false, hasContent = false, typeIndex, typeQuantity, typeList, type22, flowIndent, blockIndent;
  if (state2.listener !== null) {
    state2.listener("open", state2);
  }
  state2.tag = null;
  state2.anchor = null;
  state2.kind = null;
  state2.result = null;
  allowBlockStyles = allowBlockScalars = allowBlockCollections = CONTEXT_BLOCK_OUT2 === nodeContext || CONTEXT_BLOCK_IN2 === nodeContext;
  if (allowToSeek) {
    if (skipSeparationSpace2(state2, true, -1)) {
      atNewLine = true;
      if (state2.lineIndent > parentIndent) {
        indentStatus = 1;
      } else if (state2.lineIndent === parentIndent) {
        indentStatus = 0;
      } else if (state2.lineIndent < parentIndent) {
        indentStatus = -1;
      }
    }
  }
  if (indentStatus === 1) {
    while (readTagProperty2(state2) || readAnchorProperty2(state2)) {
      if (skipSeparationSpace2(state2, true, -1)) {
        atNewLine = true;
        allowBlockCollections = allowBlockStyles;
        if (state2.lineIndent > parentIndent) {
          indentStatus = 1;
        } else if (state2.lineIndent === parentIndent) {
          indentStatus = 0;
        } else if (state2.lineIndent < parentIndent) {
          indentStatus = -1;
        }
      } else {
        allowBlockCollections = false;
      }
    }
  }
  if (allowBlockCollections) {
    allowBlockCollections = atNewLine || allowCompact;
  }
  if (indentStatus === 1 || CONTEXT_BLOCK_OUT2 === nodeContext) {
    if (CONTEXT_FLOW_IN2 === nodeContext || CONTEXT_FLOW_OUT2 === nodeContext) {
      flowIndent = parentIndent;
    } else {
      flowIndent = parentIndent + 1;
    }
    blockIndent = state2.position - state2.lineStart;
    if (indentStatus === 1) {
      if (allowBlockCollections && (readBlockSequence2(state2, blockIndent) || readBlockMapping2(state2, blockIndent, flowIndent)) || readFlowCollection2(state2, flowIndent)) {
        hasContent = true;
      } else {
        if (allowBlockScalars && readBlockScalar2(state2, flowIndent) || readSingleQuotedScalar2(state2, flowIndent) || readDoubleQuotedScalar2(state2, flowIndent)) {
          hasContent = true;
        } else if (readAlias2(state2)) {
          hasContent = true;
          if (state2.tag !== null || state2.anchor !== null) {
            throwError2(state2, "alias node should not have any properties");
          }
        } else if (readPlainScalar2(state2, flowIndent, CONTEXT_FLOW_IN2 === nodeContext)) {
          hasContent = true;
          if (state2.tag === null) {
            state2.tag = "?";
          }
        }
        if (state2.anchor !== null) {
          state2.anchorMap[state2.anchor] = state2.result;
        }
      }
    } else if (indentStatus === 0) {
      hasContent = allowBlockCollections && readBlockSequence2(state2, blockIndent);
    }
  }
  if (state2.tag === null) {
    if (state2.anchor !== null) {
      state2.anchorMap[state2.anchor] = state2.result;
    }
  } else if (state2.tag === "?") {
    if (state2.result !== null && state2.kind !== "scalar") {
      throwError2(state2, 'unacceptable node kind for !<?> tag; it should be "scalar", not "' + state2.kind + '"');
    }
    for (typeIndex = 0, typeQuantity = state2.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) {
      type22 = state2.implicitTypes[typeIndex];
      if (type22.resolve(state2.result)) {
        state2.result = type22.construct(state2.result);
        state2.tag = type22.tag;
        if (state2.anchor !== null) {
          state2.anchorMap[state2.anchor] = state2.result;
        }
        break;
      }
    }
  } else if (state2.tag !== "!") {
    if (_hasOwnProperty$12.call(state2.typeMap[state2.kind || "fallback"], state2.tag)) {
      type22 = state2.typeMap[state2.kind || "fallback"][state2.tag];
    } else {
      type22 = null;
      typeList = state2.typeMap.multi[state2.kind || "fallback"];
      for (typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) {
        if (state2.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) {
          type22 = typeList[typeIndex];
          break;
        }
      }
    }
    if (!type22) {
      throwError2(state2, "unknown tag !<" + state2.tag + ">");
    }
    if (state2.result !== null && type22.kind !== state2.kind) {
      throwError2(state2, "unacceptable node kind for !<" + state2.tag + '> tag; it should be "' + type22.kind + '", not "' + state2.kind + '"');
    }
    if (!type22.resolve(state2.result, state2.tag)) {
      throwError2(state2, "cannot resolve a node with !<" + state2.tag + "> explicit tag");
    } else {
      state2.result = type22.construct(state2.result, state2.tag);
      if (state2.anchor !== null) {
        state2.anchorMap[state2.anchor] = state2.result;
      }
    }
  }
  if (state2.listener !== null) {
    state2.listener("close", state2);
  }
  return state2.tag !== null || state2.anchor !== null || hasContent;
}
function readDocument2(state2) {
  var documentStart = state2.position, _position, directiveName, directiveArgs, hasDirectives = false, ch;
  state2.version = null;
  state2.checkLineBreaks = state2.legacy;
  state2.tagMap = /* @__PURE__ */ Object.create(null);
  state2.anchorMap = /* @__PURE__ */ Object.create(null);
  while ((ch = state2.input.charCodeAt(state2.position)) !== 0) {
    skipSeparationSpace2(state2, true, -1);
    ch = state2.input.charCodeAt(state2.position);
    if (state2.lineIndent > 0 || ch !== 37) {
      break;
    }
    hasDirectives = true;
    ch = state2.input.charCodeAt(++state2.position);
    _position = state2.position;
    while (ch !== 0 && !is_WS_OR_EOL2(ch)) {
      ch = state2.input.charCodeAt(++state2.position);
    }
    directiveName = state2.input.slice(_position, state2.position);
    directiveArgs = [];
    if (directiveName.length < 1) {
      throwError2(state2, "directive name must not be less than one character in length");
    }
    while (ch !== 0) {
      while (is_WHITE_SPACE2(ch)) {
        ch = state2.input.charCodeAt(++state2.position);
      }
      if (ch === 35) {
        do {
          ch = state2.input.charCodeAt(++state2.position);
        } while (ch !== 0 && !is_EOL2(ch));
        break;
      }
      if (is_EOL2(ch))
        break;
      _position = state2.position;
      while (ch !== 0 && !is_WS_OR_EOL2(ch)) {
        ch = state2.input.charCodeAt(++state2.position);
      }
      directiveArgs.push(state2.input.slice(_position, state2.position));
    }
    if (ch !== 0)
      readLineBreak2(state2);
    if (_hasOwnProperty$12.call(directiveHandlers2, directiveName)) {
      directiveHandlers2[directiveName](state2, directiveName, directiveArgs);
    } else {
      throwWarning2(state2, 'unknown document directive "' + directiveName + '"');
    }
  }
  skipSeparationSpace2(state2, true, -1);
  if (state2.lineIndent === 0 && state2.input.charCodeAt(state2.position) === 45 && state2.input.charCodeAt(state2.position + 1) === 45 && state2.input.charCodeAt(state2.position + 2) === 45) {
    state2.position += 3;
    skipSeparationSpace2(state2, true, -1);
  } else if (hasDirectives) {
    throwError2(state2, "directives end mark is expected");
  }
  composeNode2(state2, state2.lineIndent - 1, CONTEXT_BLOCK_OUT2, false, true);
  skipSeparationSpace2(state2, true, -1);
  if (state2.checkLineBreaks && PATTERN_NON_ASCII_LINE_BREAKS2.test(state2.input.slice(documentStart, state2.position))) {
    throwWarning2(state2, "non-ASCII line breaks are interpreted as content");
  }
  state2.documents.push(state2.result);
  if (state2.position === state2.lineStart && testDocumentSeparator2(state2)) {
    if (state2.input.charCodeAt(state2.position) === 46) {
      state2.position += 3;
      skipSeparationSpace2(state2, true, -1);
    }
    return;
  }
  if (state2.position < state2.length - 1) {
    throwError2(state2, "end of the stream or a document separator is expected");
  } else {
    return;
  }
}
function loadDocuments2(input, options) {
  input = String(input);
  options = options || {};
  if (input.length !== 0) {
    if (input.charCodeAt(input.length - 1) !== 10 && input.charCodeAt(input.length - 1) !== 13) {
      input += "\n";
    }
    if (input.charCodeAt(0) === 65279) {
      input = input.slice(1);
    }
  }
  var state2 = new State$12(input, options);
  var nullpos = input.indexOf("\0");
  if (nullpos !== -1) {
    state2.position = nullpos;
    throwError2(state2, "null byte is not allowed in input");
  }
  state2.input += "\0";
  while (state2.input.charCodeAt(state2.position) === 32) {
    state2.lineIndent += 1;
    state2.position += 1;
  }
  while (state2.position < state2.length - 1) {
    readDocument2(state2);
  }
  return state2.documents;
}
function loadAll$12(input, iterator, options) {
  if (iterator !== null && typeof iterator === "object" && typeof options === "undefined") {
    options = iterator;
    iterator = null;
  }
  var documents = loadDocuments2(input, options);
  if (typeof iterator !== "function") {
    return documents;
  }
  for (var index2 = 0, length = documents.length; index2 < length; index2 += 1) {
    iterator(documents[index2]);
  }
}
function load$12(input, options) {
  var documents = loadDocuments2(input, options);
  if (documents.length === 0) {
    return void 0;
  } else if (documents.length === 1) {
    return documents[0];
  }
  throw new exception2("expected a single document in the stream, but found more");
}
function compileStyleMap2(schema22, map22) {
  var result2, keys, index2, length, tag, style, type22;
  if (map22 === null)
    return {};
  result2 = {};
  keys = Object.keys(map22);
  for (index2 = 0, length = keys.length; index2 < length; index2 += 1) {
    tag = keys[index2];
    style = String(map22[tag]);
    if (tag.slice(0, 2) === "!!") {
      tag = "tag:yaml.org,2002:" + tag.slice(2);
    }
    type22 = schema22.compiledTypeMap["fallback"][tag];
    if (type22 && _hasOwnProperty2.call(type22.styleAliases, style)) {
      style = type22.styleAliases[style];
    }
    result2[tag] = style;
  }
  return result2;
}
function encodeHex2(character) {
  var string2, handle, length;
  string2 = character.toString(16).toUpperCase();
  if (character <= 255) {
    handle = "x";
    length = 2;
  } else if (character <= 65535) {
    handle = "u";
    length = 4;
  } else if (character <= 4294967295) {
    handle = "U";
    length = 8;
  } else {
    throw new exception2("code point within a string may not be greater than 0xFFFFFFFF");
  }
  return "\\" + handle + common3.repeat("0", length - string2.length) + string2;
}
function State2(options) {
  this.schema = options["schema"] || _default2;
  this.indent = Math.max(1, options["indent"] || 2);
  this.noArrayIndent = options["noArrayIndent"] || false;
  this.skipInvalid = options["skipInvalid"] || false;
  this.flowLevel = common3.isNothing(options["flowLevel"]) ? -1 : options["flowLevel"];
  this.styleMap = compileStyleMap2(this.schema, options["styles"] || null);
  this.sortKeys = options["sortKeys"] || false;
  this.lineWidth = options["lineWidth"] || 80;
  this.noRefs = options["noRefs"] || false;
  this.noCompatMode = options["noCompatMode"] || false;
  this.condenseFlow = options["condenseFlow"] || false;
  this.quotingType = options["quotingType"] === '"' ? QUOTING_TYPE_DOUBLE2 : QUOTING_TYPE_SINGLE2;
  this.forceQuotes = options["forceQuotes"] || false;
  this.replacer = typeof options["replacer"] === "function" ? options["replacer"] : null;
  this.implicitTypes = this.schema.compiledImplicit;
  this.explicitTypes = this.schema.compiledExplicit;
  this.tag = null;
  this.result = "";
  this.duplicates = [];
  this.usedDuplicates = null;
}
function indentString2(string2, spaces) {
  var ind = common3.repeat(" ", spaces), position = 0, next = -1, result2 = "", line, length = string2.length;
  while (position < length) {
    next = string2.indexOf("\n", position);
    if (next === -1) {
      line = string2.slice(position);
      position = length;
    } else {
      line = string2.slice(position, next + 1);
      position = next + 1;
    }
    if (line.length && line !== "\n")
      result2 += ind;
    result2 += line;
  }
  return result2;
}
function generateNextLine2(state2, level) {
  return "\n" + common3.repeat(" ", state2.indent * level);
}
function testImplicitResolving2(state2, str22) {
  var index2, length, type22;
  for (index2 = 0, length = state2.implicitTypes.length; index2 < length; index2 += 1) {
    type22 = state2.implicitTypes[index2];
    if (type22.resolve(str22)) {
      return true;
    }
  }
  return false;
}
function isWhitespace2(c6) {
  return c6 === CHAR_SPACE2 || c6 === CHAR_TAB2;
}
function isPrintable2(c6) {
  return 32 <= c6 && c6 <= 126 || 161 <= c6 && c6 <= 55295 && c6 !== 8232 && c6 !== 8233 || 57344 <= c6 && c6 <= 65533 && c6 !== CHAR_BOM2 || 65536 <= c6 && c6 <= 1114111;
}
function isNsCharOrWhitespace2(c6) {
  return isPrintable2(c6) && c6 !== CHAR_BOM2 && c6 !== CHAR_CARRIAGE_RETURN2 && c6 !== CHAR_LINE_FEED2;
}
function isPlainSafe2(c6, prev, inblock) {
  var cIsNsCharOrWhitespace = isNsCharOrWhitespace2(c6);
  var cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace2(c6);
  return (inblock ? cIsNsCharOrWhitespace : cIsNsCharOrWhitespace && c6 !== CHAR_COMMA2 && c6 !== CHAR_LEFT_SQUARE_BRACKET2 && c6 !== CHAR_RIGHT_SQUARE_BRACKET2 && c6 !== CHAR_LEFT_CURLY_BRACKET2 && c6 !== CHAR_RIGHT_CURLY_BRACKET2) && c6 !== CHAR_SHARP2 && !(prev === CHAR_COLON3 && !cIsNsChar) || isNsCharOrWhitespace2(prev) && !isWhitespace2(prev) && c6 === CHAR_SHARP2 || prev === CHAR_COLON3 && cIsNsChar;
}
function isPlainSafeFirst2(c6) {
  return isPrintable2(c6) && c6 !== CHAR_BOM2 && !isWhitespace2(c6) && c6 !== CHAR_MINUS2 && c6 !== CHAR_QUESTION2 && c6 !== CHAR_COLON3 && c6 !== CHAR_COMMA2 && c6 !== CHAR_LEFT_SQUARE_BRACKET2 && c6 !== CHAR_RIGHT_SQUARE_BRACKET2 && c6 !== CHAR_LEFT_CURLY_BRACKET2 && c6 !== CHAR_RIGHT_CURLY_BRACKET2 && c6 !== CHAR_SHARP2 && c6 !== CHAR_AMPERSAND2 && c6 !== CHAR_ASTERISK2 && c6 !== CHAR_EXCLAMATION2 && c6 !== CHAR_VERTICAL_LINE2 && c6 !== CHAR_EQUALS2 && c6 !== CHAR_GREATER_THAN2 && c6 !== CHAR_SINGLE_QUOTE2 && c6 !== CHAR_DOUBLE_QUOTE2 && c6 !== CHAR_PERCENT2 && c6 !== CHAR_COMMERCIAL_AT2 && c6 !== CHAR_GRAVE_ACCENT2;
}
function isPlainSafeLast2(c6) {
  return !isWhitespace2(c6) && c6 !== CHAR_COLON3;
}
function codePointAt2(string2, pos) {
  var first = string2.charCodeAt(pos), second;
  if (first >= 55296 && first <= 56319 && pos + 1 < string2.length) {
    second = string2.charCodeAt(pos + 1);
    if (second >= 56320 && second <= 57343) {
      return (first - 55296) * 1024 + second - 56320 + 65536;
    }
  }
  return first;
}
function needIndentIndicator2(string2) {
  var leadingSpaceRe = /^\n* /;
  return leadingSpaceRe.test(string2);
}
function chooseScalarStyle2(string2, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType, quotingType, forceQuotes, inblock) {
  var i6;
  var char = 0;
  var prevChar = null;
  var hasLineBreak = false;
  var hasFoldableLine = false;
  var shouldTrackWidth = lineWidth !== -1;
  var previousLineBreak = -1;
  var plain = isPlainSafeFirst2(codePointAt2(string2, 0)) && isPlainSafeLast2(codePointAt2(string2, string2.length - 1));
  if (singleLineOnly || forceQuotes) {
    for (i6 = 0; i6 < string2.length; char >= 65536 ? i6 += 2 : i6++) {
      char = codePointAt2(string2, i6);
      if (!isPrintable2(char)) {
        return STYLE_DOUBLE2;
      }
      plain = plain && isPlainSafe2(char, prevChar, inblock);
      prevChar = char;
    }
  } else {
    for (i6 = 0; i6 < string2.length; char >= 65536 ? i6 += 2 : i6++) {
      char = codePointAt2(string2, i6);
      if (char === CHAR_LINE_FEED2) {
        hasLineBreak = true;
        if (shouldTrackWidth) {
          hasFoldableLine = hasFoldableLine || i6 - previousLineBreak - 1 > lineWidth && string2[previousLineBreak + 1] !== " ";
          previousLineBreak = i6;
        }
      } else if (!isPrintable2(char)) {
        return STYLE_DOUBLE2;
      }
      plain = plain && isPlainSafe2(char, prevChar, inblock);
      prevChar = char;
    }
    hasFoldableLine = hasFoldableLine || shouldTrackWidth && (i6 - previousLineBreak - 1 > lineWidth && string2[previousLineBreak + 1] !== " ");
  }
  if (!hasLineBreak && !hasFoldableLine) {
    if (plain && !forceQuotes && !testAmbiguousType(string2)) {
      return STYLE_PLAIN2;
    }
    return quotingType === QUOTING_TYPE_DOUBLE2 ? STYLE_DOUBLE2 : STYLE_SINGLE2;
  }
  if (indentPerLevel > 9 && needIndentIndicator2(string2)) {
    return STYLE_DOUBLE2;
  }
  if (!forceQuotes) {
    return hasFoldableLine ? STYLE_FOLDED2 : STYLE_LITERAL2;
  }
  return quotingType === QUOTING_TYPE_DOUBLE2 ? STYLE_DOUBLE2 : STYLE_SINGLE2;
}
function writeScalar2(state2, string2, level, iskey, inblock) {
  state2.dump = (function() {
    if (string2.length === 0) {
      return state2.quotingType === QUOTING_TYPE_DOUBLE2 ? '""' : "''";
    }
    if (!state2.noCompatMode) {
      if (DEPRECATED_BOOLEANS_SYNTAX2.indexOf(string2) !== -1 || DEPRECATED_BASE60_SYNTAX2.test(string2)) {
        return state2.quotingType === QUOTING_TYPE_DOUBLE2 ? '"' + string2 + '"' : "'" + string2 + "'";
      }
    }
    var indent = state2.indent * Math.max(1, level);
    var lineWidth = state2.lineWidth === -1 ? -1 : Math.max(Math.min(state2.lineWidth, 40), state2.lineWidth - indent);
    var singleLineOnly = iskey || state2.flowLevel > -1 && level >= state2.flowLevel;
    function testAmbiguity(string22) {
      return testImplicitResolving2(state2, string22);
    }
    switch (chooseScalarStyle2(string2, singleLineOnly, state2.indent, lineWidth, testAmbiguity, state2.quotingType, state2.forceQuotes && !iskey, inblock)) {
      case STYLE_PLAIN2:
        return string2;
      case STYLE_SINGLE2:
        return "'" + string2.replace(/'/g, "''") + "'";
      case STYLE_LITERAL2:
        return "|" + blockHeader2(string2, state2.indent) + dropEndingNewline2(indentString2(string2, indent));
      case STYLE_FOLDED2:
        return ">" + blockHeader2(string2, state2.indent) + dropEndingNewline2(indentString2(foldString2(string2, lineWidth), indent));
      case STYLE_DOUBLE2:
        return '"' + escapeString2(string2) + '"';
      default:
        throw new exception2("impossible error: invalid scalar style");
    }
  })();
}
function blockHeader2(string2, indentPerLevel) {
  var indentIndicator = needIndentIndicator2(string2) ? String(indentPerLevel) : "";
  var clip = string2[string2.length - 1] === "\n";
  var keep = clip && (string2[string2.length - 2] === "\n" || string2 === "\n");
  var chomp = keep ? "+" : clip ? "" : "-";
  return indentIndicator + chomp + "\n";
}
function dropEndingNewline2(string2) {
  return string2[string2.length - 1] === "\n" ? string2.slice(0, -1) : string2;
}
function foldString2(string2, width) {
  var lineRe = /(\n+)([^\n]*)/g;
  var result2 = (function() {
    var nextLF = string2.indexOf("\n");
    nextLF = nextLF !== -1 ? nextLF : string2.length;
    lineRe.lastIndex = nextLF;
    return foldLine2(string2.slice(0, nextLF), width);
  })();
  var prevMoreIndented = string2[0] === "\n" || string2[0] === " ";
  var moreIndented;
  var match;
  while (match = lineRe.exec(string2)) {
    var prefix = match[1], line = match[2];
    moreIndented = line[0] === " ";
    result2 += prefix + (!prevMoreIndented && !moreIndented && line !== "" ? "\n" : "") + foldLine2(line, width);
    prevMoreIndented = moreIndented;
  }
  return result2;
}
function foldLine2(line, width) {
  if (line === "" || line[0] === " ")
    return line;
  var breakRe = / [^ ]/g;
  var match;
  var start = 0, end, curr = 0, next = 0;
  var result2 = "";
  while (match = breakRe.exec(line)) {
    next = match.index;
    if (next - start > width) {
      end = curr > start ? curr : next;
      result2 += "\n" + line.slice(start, end);
      start = end + 1;
    }
    curr = next;
  }
  result2 += "\n";
  if (line.length - start > width && curr > start) {
    result2 += line.slice(start, curr) + "\n" + line.slice(curr + 1);
  } else {
    result2 += line.slice(start);
  }
  return result2.slice(1);
}
function escapeString2(string2) {
  var result2 = "";
  var char = 0;
  var escapeSeq;
  for (var i6 = 0; i6 < string2.length; char >= 65536 ? i6 += 2 : i6++) {
    char = codePointAt2(string2, i6);
    escapeSeq = ESCAPE_SEQUENCES2[char];
    if (!escapeSeq && isPrintable2(char)) {
      result2 += string2[i6];
      if (char >= 65536)
        result2 += string2[i6 + 1];
    } else {
      result2 += escapeSeq || encodeHex2(char);
    }
  }
  return result2;
}
function writeFlowSequence2(state2, level, object) {
  var _result = "", _tag = state2.tag, index2, length, value;
  for (index2 = 0, length = object.length; index2 < length; index2 += 1) {
    value = object[index2];
    if (state2.replacer) {
      value = state2.replacer.call(object, String(index2), value);
    }
    if (writeNode2(state2, level, value, false, false) || typeof value === "undefined" && writeNode2(state2, level, null, false, false)) {
      if (_result !== "")
        _result += "," + (!state2.condenseFlow ? " " : "");
      _result += state2.dump;
    }
  }
  state2.tag = _tag;
  state2.dump = "[" + _result + "]";
}
function writeBlockSequence2(state2, level, object, compact) {
  var _result = "", _tag = state2.tag, index2, length, value;
  for (index2 = 0, length = object.length; index2 < length; index2 += 1) {
    value = object[index2];
    if (state2.replacer) {
      value = state2.replacer.call(object, String(index2), value);
    }
    if (writeNode2(state2, level + 1, value, true, true, false, true) || typeof value === "undefined" && writeNode2(state2, level + 1, null, true, true, false, true)) {
      if (!compact || _result !== "") {
        _result += generateNextLine2(state2, level);
      }
      if (state2.dump && CHAR_LINE_FEED2 === state2.dump.charCodeAt(0)) {
        _result += "-";
      } else {
        _result += "- ";
      }
      _result += state2.dump;
    }
  }
  state2.tag = _tag;
  state2.dump = _result || "[]";
}
function writeFlowMapping2(state2, level, object) {
  var _result = "", _tag = state2.tag, objectKeyList = Object.keys(object), index2, length, objectKey, objectValue, pairBuffer;
  for (index2 = 0, length = objectKeyList.length; index2 < length; index2 += 1) {
    pairBuffer = "";
    if (_result !== "")
      pairBuffer += ", ";
    if (state2.condenseFlow)
      pairBuffer += '"';
    objectKey = objectKeyList[index2];
    objectValue = object[objectKey];
    if (state2.replacer) {
      objectValue = state2.replacer.call(object, objectKey, objectValue);
    }
    if (!writeNode2(state2, level, objectKey, false, false)) {
      continue;
    }
    if (state2.dump.length > 1024)
      pairBuffer += "? ";
    pairBuffer += state2.dump + (state2.condenseFlow ? '"' : "") + ":" + (state2.condenseFlow ? "" : " ");
    if (!writeNode2(state2, level, objectValue, false, false)) {
      continue;
    }
    pairBuffer += state2.dump;
    _result += pairBuffer;
  }
  state2.tag = _tag;
  state2.dump = "{" + _result + "}";
}
function writeBlockMapping2(state2, level, object, compact) {
  var _result = "", _tag = state2.tag, objectKeyList = Object.keys(object), index2, length, objectKey, objectValue, explicitPair, pairBuffer;
  if (state2.sortKeys === true) {
    objectKeyList.sort();
  } else if (typeof state2.sortKeys === "function") {
    objectKeyList.sort(state2.sortKeys);
  } else if (state2.sortKeys) {
    throw new exception2("sortKeys must be a boolean or a function");
  }
  for (index2 = 0, length = objectKeyList.length; index2 < length; index2 += 1) {
    pairBuffer = "";
    if (!compact || _result !== "") {
      pairBuffer += generateNextLine2(state2, level);
    }
    objectKey = objectKeyList[index2];
    objectValue = object[objectKey];
    if (state2.replacer) {
      objectValue = state2.replacer.call(object, objectKey, objectValue);
    }
    if (!writeNode2(state2, level + 1, objectKey, true, true, true)) {
      continue;
    }
    explicitPair = state2.tag !== null && state2.tag !== "?" || state2.dump && state2.dump.length > 1024;
    if (explicitPair) {
      if (state2.dump && CHAR_LINE_FEED2 === state2.dump.charCodeAt(0)) {
        pairBuffer += "?";
      } else {
        pairBuffer += "? ";
      }
    }
    pairBuffer += state2.dump;
    if (explicitPair) {
      pairBuffer += generateNextLine2(state2, level);
    }
    if (!writeNode2(state2, level + 1, objectValue, true, explicitPair)) {
      continue;
    }
    if (state2.dump && CHAR_LINE_FEED2 === state2.dump.charCodeAt(0)) {
      pairBuffer += ":";
    } else {
      pairBuffer += ": ";
    }
    pairBuffer += state2.dump;
    _result += pairBuffer;
  }
  state2.tag = _tag;
  state2.dump = _result || "{}";
}
function detectType2(state2, object, explicit) {
  var _result, typeList, index2, length, type22, style;
  typeList = explicit ? state2.explicitTypes : state2.implicitTypes;
  for (index2 = 0, length = typeList.length; index2 < length; index2 += 1) {
    type22 = typeList[index2];
    if ((type22.instanceOf || type22.predicate) && (!type22.instanceOf || typeof object === "object" && object instanceof type22.instanceOf) && (!type22.predicate || type22.predicate(object))) {
      if (explicit) {
        if (type22.multi && type22.representName) {
          state2.tag = type22.representName(object);
        } else {
          state2.tag = type22.tag;
        }
      } else {
        state2.tag = "?";
      }
      if (type22.represent) {
        style = state2.styleMap[type22.tag] || type22.defaultStyle;
        if (_toString2.call(type22.represent) === "[object Function]") {
          _result = type22.represent(object, style);
        } else if (_hasOwnProperty2.call(type22.represent, style)) {
          _result = type22.represent[style](object, style);
        } else {
          throw new exception2("!<" + type22.tag + '> tag resolver accepts not "' + style + '" style');
        }
        state2.dump = _result;
      }
      return true;
    }
  }
  return false;
}
function writeNode2(state2, level, object, block, compact, iskey, isblockseq) {
  state2.tag = null;
  state2.dump = object;
  if (!detectType2(state2, object, false)) {
    detectType2(state2, object, true);
  }
  var type22 = _toString2.call(state2.dump);
  var inblock = block;
  var tagStr;
  if (block) {
    block = state2.flowLevel < 0 || state2.flowLevel > level;
  }
  var objectOrArray = type22 === "[object Object]" || type22 === "[object Array]", duplicateIndex, duplicate;
  if (objectOrArray) {
    duplicateIndex = state2.duplicates.indexOf(object);
    duplicate = duplicateIndex !== -1;
  }
  if (state2.tag !== null && state2.tag !== "?" || duplicate || state2.indent !== 2 && level > 0) {
    compact = false;
  }
  if (duplicate && state2.usedDuplicates[duplicateIndex]) {
    state2.dump = "*ref_" + duplicateIndex;
  } else {
    if (objectOrArray && duplicate && !state2.usedDuplicates[duplicateIndex]) {
      state2.usedDuplicates[duplicateIndex] = true;
    }
    if (type22 === "[object Object]") {
      if (block && Object.keys(state2.dump).length !== 0) {
        writeBlockMapping2(state2, level, state2.dump, compact);
        if (duplicate) {
          state2.dump = "&ref_" + duplicateIndex + state2.dump;
        }
      } else {
        writeFlowMapping2(state2, level, state2.dump);
        if (duplicate) {
          state2.dump = "&ref_" + duplicateIndex + " " + state2.dump;
        }
      }
    } else if (type22 === "[object Array]") {
      if (block && state2.dump.length !== 0) {
        if (state2.noArrayIndent && !isblockseq && level > 0) {
          writeBlockSequence2(state2, level - 1, state2.dump, compact);
        } else {
          writeBlockSequence2(state2, level, state2.dump, compact);
        }
        if (duplicate) {
          state2.dump = "&ref_" + duplicateIndex + state2.dump;
        }
      } else {
        writeFlowSequence2(state2, level, state2.dump);
        if (duplicate) {
          state2.dump = "&ref_" + duplicateIndex + " " + state2.dump;
        }
      }
    } else if (type22 === "[object String]") {
      if (state2.tag !== "?") {
        writeScalar2(state2, state2.dump, level, iskey, inblock);
      }
    } else if (type22 === "[object Undefined]") {
      return false;
    } else {
      if (state2.skipInvalid)
        return false;
      throw new exception2("unacceptable kind of an object to dump " + type22);
    }
    if (state2.tag !== null && state2.tag !== "?") {
      tagStr = encodeURI(state2.tag[0] === "!" ? state2.tag.slice(1) : state2.tag).replace(/!/g, "%21");
      if (state2.tag[0] === "!") {
        tagStr = "!" + tagStr;
      } else if (tagStr.slice(0, 18) === "tag:yaml.org,2002:") {
        tagStr = "!!" + tagStr.slice(18);
      } else {
        tagStr = "!<" + tagStr + ">";
      }
      state2.dump = tagStr + " " + state2.dump;
    }
  }
  return true;
}
function getDuplicateReferences2(object, state2) {
  var objects = [], duplicatesIndexes = [], index2, length;
  inspectNode2(object, objects, duplicatesIndexes);
  for (index2 = 0, length = duplicatesIndexes.length; index2 < length; index2 += 1) {
    state2.duplicates.push(objects[duplicatesIndexes[index2]]);
  }
  state2.usedDuplicates = new Array(length);
}
function inspectNode2(object, objects, duplicatesIndexes) {
  var objectKeyList, index2, length;
  if (object !== null && typeof object === "object") {
    index2 = objects.indexOf(object);
    if (index2 !== -1) {
      if (duplicatesIndexes.indexOf(index2) === -1) {
        duplicatesIndexes.push(index2);
      }
    } else {
      objects.push(object);
      if (Array.isArray(object)) {
        for (index2 = 0, length = object.length; index2 < length; index2 += 1) {
          inspectNode2(object[index2], objects, duplicatesIndexes);
        }
      } else {
        objectKeyList = Object.keys(object);
        for (index2 = 0, length = objectKeyList.length; index2 < length; index2 += 1) {
          inspectNode2(object[objectKeyList[index2]], objects, duplicatesIndexes);
        }
      }
    }
  }
}
function dump$12(input, options) {
  options = options || {};
  var state2 = new State2(options);
  if (!state2.noRefs)
    getDuplicateReferences2(input, state2);
  var value = input;
  if (state2.replacer) {
    value = state2.replacer.call({ "": value }, "", value);
  }
  if (writeNode2(state2, 0, value, true, true))
    return state2.dump + "\n";
  return "";
}
function renamed2(from, to) {
  return function() {
    throw new Error("Function yaml." + from + " is removed in js-yaml 4. Use yaml." + to + " instead, which is now safe by default.");
  };
}
var isNothing_12, isObject_12, toArray_12, repeat_12, isNegativeZero_12, extend_12, common3, exception2, snippet2, TYPE_CONSTRUCTOR_OPTIONS2, YAML_NODE_KINDS2, type2, schema2, str2, seq2, map2, failsafe2, _null2, bool2, int2, YAML_FLOAT_PATTERN2, SCIENTIFIC_WITHOUT_DOT2, float2, json2, core2, YAML_DATE_REGEXP2, YAML_TIMESTAMP_REGEXP2, timestamp2, merge2, BASE64_MAP2, binary2, _hasOwnProperty$32, _toString$22, omap2, _toString$12, pairs2, _hasOwnProperty$22, set2, _default2, _hasOwnProperty$12, CONTEXT_FLOW_IN2, CONTEXT_FLOW_OUT2, CONTEXT_BLOCK_IN2, CONTEXT_BLOCK_OUT2, CHOMPING_CLIP2, CHOMPING_STRIP2, CHOMPING_KEEP2, PATTERN_NON_PRINTABLE2, PATTERN_NON_ASCII_LINE_BREAKS2, PATTERN_FLOW_INDICATORS2, PATTERN_TAG_HANDLE2, PATTERN_TAG_URI2, simpleEscapeCheck2, simpleEscapeMap2, i6, directiveHandlers2, loadAll_12, load_12, loader2, _toString2, _hasOwnProperty2, CHAR_BOM2, CHAR_TAB2, CHAR_LINE_FEED2, CHAR_CARRIAGE_RETURN2, CHAR_SPACE2, CHAR_EXCLAMATION2, CHAR_DOUBLE_QUOTE2, CHAR_SHARP2, CHAR_PERCENT2, CHAR_AMPERSAND2, CHAR_SINGLE_QUOTE2, CHAR_ASTERISK2, CHAR_COMMA2, CHAR_MINUS2, CHAR_COLON3, CHAR_EQUALS2, CHAR_GREATER_THAN2, CHAR_QUESTION2, CHAR_COMMERCIAL_AT2, CHAR_LEFT_SQUARE_BRACKET2, CHAR_RIGHT_SQUARE_BRACKET2, CHAR_GRAVE_ACCENT2, CHAR_LEFT_CURLY_BRACKET2, CHAR_VERTICAL_LINE2, CHAR_RIGHT_CURLY_BRACKET2, ESCAPE_SEQUENCES2, DEPRECATED_BOOLEANS_SYNTAX2, DEPRECATED_BASE60_SYNTAX2, QUOTING_TYPE_SINGLE2, QUOTING_TYPE_DOUBLE2, STYLE_PLAIN2, STYLE_SINGLE2, STYLE_LITERAL2, STYLE_FOLDED2, STYLE_DOUBLE2, dump_12, dumper2, Type3, Schema8, FAILSAFE_SCHEMA, load2, loadAll2, dump2, types, safeLoad2, safeLoadAll2, safeDump2;
var init_js_yaml2 = __esm({
  "https://cdn.skypack.dev/-/js-yaml@v4.1.1-8B0j8wiUmEXyI4j5ClPv/dist=es2019,mode=imports/optimized/js-yaml.js"() {
    isNothing_12 = isNothing2;
    isObject_12 = isObject4;
    toArray_12 = toArray2;
    repeat_12 = repeat2;
    isNegativeZero_12 = isNegativeZero2;
    extend_12 = extend3;
    common3 = {
      isNothing: isNothing_12,
      isObject: isObject_12,
      toArray: toArray_12,
      repeat: repeat_12,
      isNegativeZero: isNegativeZero_12,
      extend: extend_12
    };
    YAMLException$12.prototype = Object.create(Error.prototype);
    YAMLException$12.prototype.constructor = YAMLException$12;
    YAMLException$12.prototype.toString = function toString3(compact) {
      return this.name + ": " + formatError2(this, compact);
    };
    exception2 = YAMLException$12;
    snippet2 = makeSnippet2;
    TYPE_CONSTRUCTOR_OPTIONS2 = [
      "kind",
      "multi",
      "resolve",
      "construct",
      "instanceOf",
      "predicate",
      "represent",
      "representName",
      "defaultStyle",
      "styleAliases"
    ];
    YAML_NODE_KINDS2 = [
      "scalar",
      "sequence",
      "mapping"
    ];
    type2 = Type$12;
    Schema$12.prototype.extend = function extend22(definition) {
      var implicit = [];
      var explicit = [];
      if (definition instanceof type2) {
        explicit.push(definition);
      } else if (Array.isArray(definition)) {
        explicit = explicit.concat(definition);
      } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) {
        if (definition.implicit)
          implicit = implicit.concat(definition.implicit);
        if (definition.explicit)
          explicit = explicit.concat(definition.explicit);
      } else {
        throw new exception2("Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })");
      }
      implicit.forEach(function(type$1) {
        if (!(type$1 instanceof type2)) {
          throw new exception2("Specified list of YAML types (or a single Type object) contains a non-Type object.");
        }
        if (type$1.loadKind && type$1.loadKind !== "scalar") {
          throw new exception2("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.");
        }
        if (type$1.multi) {
          throw new exception2("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.");
        }
      });
      explicit.forEach(function(type$1) {
        if (!(type$1 instanceof type2)) {
          throw new exception2("Specified list of YAML types (or a single Type object) contains a non-Type object.");
        }
      });
      var result2 = Object.create(Schema$12.prototype);
      result2.implicit = (this.implicit || []).concat(implicit);
      result2.explicit = (this.explicit || []).concat(explicit);
      result2.compiledImplicit = compileList2(result2, "implicit");
      result2.compiledExplicit = compileList2(result2, "explicit");
      result2.compiledTypeMap = compileMap2(result2.compiledImplicit, result2.compiledExplicit);
      return result2;
    };
    schema2 = Schema$12;
    str2 = new type2("tag:yaml.org,2002:str", {
      kind: "scalar",
      construct: function(data3) {
        return data3 !== null ? data3 : "";
      }
    });
    seq2 = new type2("tag:yaml.org,2002:seq", {
      kind: "sequence",
      construct: function(data3) {
        return data3 !== null ? data3 : [];
      }
    });
    map2 = new type2("tag:yaml.org,2002:map", {
      kind: "mapping",
      construct: function(data3) {
        return data3 !== null ? data3 : {};
      }
    });
    failsafe2 = new schema2({
      explicit: [
        str2,
        seq2,
        map2
      ]
    });
    _null2 = new type2("tag:yaml.org,2002:null", {
      kind: "scalar",
      resolve: resolveYamlNull2,
      construct: constructYamlNull2,
      predicate: isNull2,
      represent: {
        canonical: function() {
          return "~";
        },
        lowercase: function() {
          return "null";
        },
        uppercase: function() {
          return "NULL";
        },
        camelcase: function() {
          return "Null";
        },
        empty: function() {
          return "";
        }
      },
      defaultStyle: "lowercase"
    });
    bool2 = new type2("tag:yaml.org,2002:bool", {
      kind: "scalar",
      resolve: resolveYamlBoolean2,
      construct: constructYamlBoolean2,
      predicate: isBoolean2,
      represent: {
        lowercase: function(object) {
          return object ? "true" : "false";
        },
        uppercase: function(object) {
          return object ? "TRUE" : "FALSE";
        },
        camelcase: function(object) {
          return object ? "True" : "False";
        }
      },
      defaultStyle: "lowercase"
    });
    int2 = new type2("tag:yaml.org,2002:int", {
      kind: "scalar",
      resolve: resolveYamlInteger2,
      construct: constructYamlInteger2,
      predicate: isInteger2,
      represent: {
        binary: function(obj) {
          return obj >= 0 ? "0b" + obj.toString(2) : "-0b" + obj.toString(2).slice(1);
        },
        octal: function(obj) {
          return obj >= 0 ? "0o" + obj.toString(8) : "-0o" + obj.toString(8).slice(1);
        },
        decimal: function(obj) {
          return obj.toString(10);
        },
        hexadecimal: function(obj) {
          return obj >= 0 ? "0x" + obj.toString(16).toUpperCase() : "-0x" + obj.toString(16).toUpperCase().slice(1);
        }
      },
      defaultStyle: "decimal",
      styleAliases: {
        binary: [2, "bin"],
        octal: [8, "oct"],
        decimal: [10, "dec"],
        hexadecimal: [16, "hex"]
      }
    });
    YAML_FLOAT_PATTERN2 = new RegExp("^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");
    SCIENTIFIC_WITHOUT_DOT2 = /^[-+]?[0-9]+e/;
    float2 = new type2("tag:yaml.org,2002:float", {
      kind: "scalar",
      resolve: resolveYamlFloat2,
      construct: constructYamlFloat2,
      predicate: isFloat2,
      represent: representYamlFloat2,
      defaultStyle: "lowercase"
    });
    json2 = failsafe2.extend({
      implicit: [
        _null2,
        bool2,
        int2,
        float2
      ]
    });
    core2 = json2;
    YAML_DATE_REGEXP2 = new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$");
    YAML_TIMESTAMP_REGEXP2 = new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");
    timestamp2 = new type2("tag:yaml.org,2002:timestamp", {
      kind: "scalar",
      resolve: resolveYamlTimestamp2,
      construct: constructYamlTimestamp2,
      instanceOf: Date,
      represent: representYamlTimestamp2
    });
    merge2 = new type2("tag:yaml.org,2002:merge", {
      kind: "scalar",
      resolve: resolveYamlMerge2
    });
    BASE64_MAP2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r";
    binary2 = new type2("tag:yaml.org,2002:binary", {
      kind: "scalar",
      resolve: resolveYamlBinary2,
      construct: constructYamlBinary2,
      predicate: isBinary2,
      represent: representYamlBinary2
    });
    _hasOwnProperty$32 = Object.prototype.hasOwnProperty;
    _toString$22 = Object.prototype.toString;
    omap2 = new type2("tag:yaml.org,2002:omap", {
      kind: "sequence",
      resolve: resolveYamlOmap2,
      construct: constructYamlOmap2
    });
    _toString$12 = Object.prototype.toString;
    pairs2 = new type2("tag:yaml.org,2002:pairs", {
      kind: "sequence",
      resolve: resolveYamlPairs2,
      construct: constructYamlPairs2
    });
    _hasOwnProperty$22 = Object.prototype.hasOwnProperty;
    set2 = new type2("tag:yaml.org,2002:set", {
      kind: "mapping",
      resolve: resolveYamlSet2,
      construct: constructYamlSet2
    });
    _default2 = core2.extend({
      implicit: [
        timestamp2,
        merge2
      ],
      explicit: [
        binary2,
        omap2,
        pairs2,
        set2
      ]
    });
    _hasOwnProperty$12 = Object.prototype.hasOwnProperty;
    CONTEXT_FLOW_IN2 = 1;
    CONTEXT_FLOW_OUT2 = 2;
    CONTEXT_BLOCK_IN2 = 3;
    CONTEXT_BLOCK_OUT2 = 4;
    CHOMPING_CLIP2 = 1;
    CHOMPING_STRIP2 = 2;
    CHOMPING_KEEP2 = 3;
    PATTERN_NON_PRINTABLE2 = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
    PATTERN_NON_ASCII_LINE_BREAKS2 = /[\x85\u2028\u2029]/;
    PATTERN_FLOW_INDICATORS2 = /[,\[\]\{\}]/;
    PATTERN_TAG_HANDLE2 = /^(?:!|!!|![a-z\-]+!)$/i;
    PATTERN_TAG_URI2 = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;
    simpleEscapeCheck2 = new Array(256);
    simpleEscapeMap2 = new Array(256);
    for (i6 = 0; i6 < 256; i6++) {
      simpleEscapeCheck2[i6] = simpleEscapeSequence2(i6) ? 1 : 0;
      simpleEscapeMap2[i6] = simpleEscapeSequence2(i6);
    }
    directiveHandlers2 = {
      YAML: function handleYamlDirective2(state2, name2, args) {
        var match, major, minor;
        if (state2.version !== null) {
          throwError2(state2, "duplication of %YAML directive");
        }
        if (args.length !== 1) {
          throwError2(state2, "YAML directive accepts exactly one argument");
        }
        match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]);
        if (match === null) {
          throwError2(state2, "ill-formed argument of the YAML directive");
        }
        major = parseInt(match[1], 10);
        minor = parseInt(match[2], 10);
        if (major !== 1) {
          throwError2(state2, "unacceptable YAML version of the document");
        }
        state2.version = args[0];
        state2.checkLineBreaks = minor < 2;
        if (minor !== 1 && minor !== 2) {
          throwWarning2(state2, "unsupported YAML version of the document");
        }
      },
      TAG: function handleTagDirective2(state2, name2, args) {
        var handle, prefix;
        if (args.length !== 2) {
          throwError2(state2, "TAG directive accepts exactly two arguments");
        }
        handle = args[0];
        prefix = args[1];
        if (!PATTERN_TAG_HANDLE2.test(handle)) {
          throwError2(state2, "ill-formed tag handle (first argument) of the TAG directive");
        }
        if (_hasOwnProperty$12.call(state2.tagMap, handle)) {
          throwError2(state2, 'there is a previously declared suffix for "' + handle + '" tag handle');
        }
        if (!PATTERN_TAG_URI2.test(prefix)) {
          throwError2(state2, "ill-formed tag prefix (second argument) of the TAG directive");
        }
        try {
          prefix = decodeURIComponent(prefix);
        } catch (err2) {
          throwError2(state2, "tag prefix is malformed: " + prefix);
        }
        state2.tagMap[handle] = prefix;
      }
    };
    loadAll_12 = loadAll$12;
    load_12 = load$12;
    loader2 = {
      loadAll: loadAll_12,
      load: load_12
    };
    _toString2 = Object.prototype.toString;
    _hasOwnProperty2 = Object.prototype.hasOwnProperty;
    CHAR_BOM2 = 65279;
    CHAR_TAB2 = 9;
    CHAR_LINE_FEED2 = 10;
    CHAR_CARRIAGE_RETURN2 = 13;
    CHAR_SPACE2 = 32;
    CHAR_EXCLAMATION2 = 33;
    CHAR_DOUBLE_QUOTE2 = 34;
    CHAR_SHARP2 = 35;
    CHAR_PERCENT2 = 37;
    CHAR_AMPERSAND2 = 38;
    CHAR_SINGLE_QUOTE2 = 39;
    CHAR_ASTERISK2 = 42;
    CHAR_COMMA2 = 44;
    CHAR_MINUS2 = 45;
    CHAR_COLON3 = 58;
    CHAR_EQUALS2 = 61;
    CHAR_GREATER_THAN2 = 62;
    CHAR_QUESTION2 = 63;
    CHAR_COMMERCIAL_AT2 = 64;
    CHAR_LEFT_SQUARE_BRACKET2 = 91;
    CHAR_RIGHT_SQUARE_BRACKET2 = 93;
    CHAR_GRAVE_ACCENT2 = 96;
    CHAR_LEFT_CURLY_BRACKET2 = 123;
    CHAR_VERTICAL_LINE2 = 124;
    CHAR_RIGHT_CURLY_BRACKET2 = 125;
    ESCAPE_SEQUENCES2 = {};
    ESCAPE_SEQUENCES2[0] = "\\0";
    ESCAPE_SEQUENCES2[7] = "\\a";
    ESCAPE_SEQUENCES2[8] = "\\b";
    ESCAPE_SEQUENCES2[9] = "\\t";
    ESCAPE_SEQUENCES2[10] = "\\n";
    ESCAPE_SEQUENCES2[11] = "\\v";
    ESCAPE_SEQUENCES2[12] = "\\f";
    ESCAPE_SEQUENCES2[13] = "\\r";
    ESCAPE_SEQUENCES2[27] = "\\e";
    ESCAPE_SEQUENCES2[34] = '\\"';
    ESCAPE_SEQUENCES2[92] = "\\\\";
    ESCAPE_SEQUENCES2[133] = "\\N";
    ESCAPE_SEQUENCES2[160] = "\\_";
    ESCAPE_SEQUENCES2[8232] = "\\L";
    ESCAPE_SEQUENCES2[8233] = "\\P";
    DEPRECATED_BOOLEANS_SYNTAX2 = [
      "y",
      "Y",
      "yes",
      "Yes",
      "YES",
      "on",
      "On",
      "ON",
      "n",
      "N",
      "no",
      "No",
      "NO",
      "off",
      "Off",
      "OFF"
    ];
    DEPRECATED_BASE60_SYNTAX2 = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;
    QUOTING_TYPE_SINGLE2 = 1;
    QUOTING_TYPE_DOUBLE2 = 2;
    STYLE_PLAIN2 = 1;
    STYLE_SINGLE2 = 2;
    STYLE_LITERAL2 = 3;
    STYLE_FOLDED2 = 4;
    STYLE_DOUBLE2 = 5;
    dump_12 = dump$12;
    dumper2 = {
      dump: dump_12
    };
    Type3 = type2;
    Schema8 = schema2;
    FAILSAFE_SCHEMA = failsafe2;
    load2 = loader2.load;
    loadAll2 = loader2.loadAll;
    dump2 = dumper2.dump;
    types = {
      binary: binary2,
      float: float2,
      map: map2,
      null: _null2,
      pairs: pairs2,
      set: set2,
      timestamp: timestamp2,
      bool: bool2,
      int: int2,
      merge: merge2,
      omap: omap2,
      seq: seq2,
      str: str2
    };
    safeLoad2 = renamed2("safeLoad", "load");
    safeLoadAll2 = renamed2("safeLoadAll", "loadAll");
    safeDump2 = renamed2("safeDump", "dump");
  }
});

// https://cdn.skypack.dev/js-yaml@4.1.1
var init_js_yaml_4_1 = __esm({
  "https://cdn.skypack.dev/js-yaml@4.1.1"() {
    init_js_yaml2();
    init_js_yaml2();
  }
});

// core/yaml.ts
function isYamlPath(file) {
  return [".yaml", ".yml"].includes(extname4(file));
}
function readYaml(file) {
  if (existsSync2(file)) {
    const decoder3 = new TextDecoder("utf-8");
    const yml = Deno.readFileSync(file);
    const result2 = parseWithNiceErrors(decoder3.decode(yml));
    try {
      JSON.stringify(result2);
      return result2;
    } catch (e5) {
      if (!(e5 instanceof Error)) throw e5;
      throw new Error(
        `Circular structures not allowed.
File ${file}
${e5.message.split("\n").slice(1).join("\n")}`
      );
    }
  } else {
    throw new Error(`YAML file ${file} not found.`);
  }
}
function readYamlFromString(yml) {
  return parseWithNiceErrors(yml);
}
function readYamlFromMarkdown(markdown) {
  if (markdown) {
    markdown = normalizeNewlines(markdown);
    markdown = markdown.replaceAll(kRegxHTMLComment, "");
    markdown = markdown.replaceAll(kRegexFencedCode, "");
    let yaml = "";
    kRegExYAML.lastIndex = 0;
    let match = kRegExYAML.exec(markdown);
    while (match != null) {
      let yamlBlock = removeYamlDelimiters(match[2]);
      yamlBlock = lines(yamlBlock).map((x3) => x3.trimEnd()).join("\n");
      if (!yamlBlock.match(/^\n\s*\n/) && !yamlBlock.match(/^\n\s*\n---/m) && yamlBlock.trim().length > 0) {
        parseWithNiceErrors(yamlBlock, {
          json: true,
          schema: QuartoJSONSchema2
        });
        yaml += yamlBlock;
      }
      match = kRegExYAML.exec(markdown);
    }
    kRegExYAML.lastIndex = 0;
    const metadata = parseWithNiceErrors(yaml, {
      json: true,
      schema: QuartoJSONSchema2
    });
    return metadata || {};
  } else {
    return {};
  }
}
function partitionYamlFrontMatter(markdown) {
  const mdLines = lines(markdown.trimLeft());
  if (mdLines.length < 3 || !mdLines[0].match(kRegExBeginYAML)) {
    return null;
  } else if (mdLines[1].trim().length === 0 || mdLines[1].match(kRegExEndYAML)) {
    return null;
  } else {
    const endYamlPos = mdLines.findIndex(
      (line, index2) => index2 > 0 && line.match(kRegExEndYAML)
    );
    if (endYamlPos === -1) {
      return null;
    } else {
      return {
        yaml: mdLines.slice(0, endYamlPos + 1).join("\n"),
        markdown: "\n" + mdLines.slice(endYamlPos + 1).join("\n")
      };
    }
  }
}
function removeYamlDelimiters(yaml) {
  return yaml.replace(/^---/, "").replace(/---\s*$/, "");
}
function parseWithNiceErrors(content, options) {
  try {
    return parse3(content, options || { json: true, schema: QuartoJSONSchema2 });
  } catch (e5) {
    if (!(e5 instanceof Error)) {
      throw e5;
    }
    throw improveYamlParseErrorMessage(e5);
  }
}
function improveYamlParseErrorMessage(e5) {
  if (e5.message.match(/unknown tag/)) {
    e5.message = `${e5.message}
Did you try to use a '!' in a YAML string? If so, you need to add explicit quotes to your string.`;
  }
  return e5;
}
var bool3, float3, int3, nil, stringify, parse3, kRegExBeginYAML, kRegExEndYAML, kRegExYAML, kRegxHTMLComment, kRegexFencedCode, YAMLValidationError, QuartoJSONSchema2;
var init_yaml = __esm({
  "core/yaml.ts"() {
    init_fs();
    init_path();
    init_text2();
    init_error2();
    init_front_matter();
    init_mapped_text2();
    init_validated_yaml();
    init_js_yaml_4_1();
    init_js_yaml_4_1();
    init_js_yaml_4_1();
    init_js_yaml_4_1();
    init_js_yaml_4_1();
    init_js_yaml_4_1();
    ({ bool: bool3, float: float3, int: int3, null: nil } = types);
    stringify = dump2;
    parse3 = load2;
    kRegExBeginYAML = /^---[ \t]*$/;
    kRegExEndYAML = /^(?:---|\.\.\.)([ \t]*)$/;
    kRegExYAML = /(^)(---[ \t]*[\r\n]+(?![ \t]*[\r\n]+)[\W\w]*?[\r\n]+(?:---|\.\.\.))([ \t]*)$/gm;
    kRegxHTMLComment = /<!--[\W\w]*?-->/gm;
    kRegexFencedCode = /^([\t >]*`{3,})[^`\n]*\n[\W\w]*?\n\1\s*$/gm;
    YAMLValidationError = class extends ErrorEx {
      constructor(message) {
        super("YAMLValidationError", message, false, false);
      }
    };
    QuartoJSONSchema2 = new Schema8({
      implicit: [nil, bool3, int3, float3],
      include: [FAILSAFE_SCHEMA],
      explicit: [
        new Type3("!expr", {
          kind: "scalar",
          // deno-lint-ignore no-explicit-any
          construct(data3) {
            const result2 = data3 !== null ? data3 : "";
            return {
              value: result2,
              tag: "!expr"
            };
          }
        })
      ]
    });
  }
});

// core/config.ts
function mergeArrayCustomizer(objValue, srcValue) {
  if (isArray(objValue) || isArray(srcValue)) {
    if (!objValue) {
      return srcValue;
    } else if (!srcValue) {
      return objValue;
    } else {
      if (!isArray(objValue)) {
        objValue = [objValue];
      }
      if (!isArray(srcValue)) {
        srcValue = [srcValue];
      }
    }
    const combined = objValue.concat(
      srcValue
    );
    return uniqBy(combined, (value) => {
      if (typeof value === "function") {
        return globalThis.crypto.randomUUID();
      } else {
        return JSON.stringify(value);
      }
    });
  }
}
function camelToKebab(camel) {
  camel = camel.replace(/([A-Z])([A-Z]+)$/g, function(_3, p1, p22) {
    return p1 + p22.toLowerCase();
  });
  camel = camel.replaceAll(/([A-Z])([A-Z]+)([A-Z])/g, function(_3, p1, p22, p32) {
    return p1 + p22.toLowerCase() + p32;
  });
  const kebab = [];
  for (let i6 = 0; i6 < camel.length; i6++) {
    const ch = camel.charAt(i6);
    if (ch === ch.toUpperCase() && !/^\d+/.test(ch)) {
      if (i6 > 0) {
        kebab.push("-");
      }
      kebab.push(ch.toLowerCase());
    } else {
      kebab.push(ch);
    }
  }
  return kebab.join("");
}
function kebabToCamel(kebab, leadingUppercase = false) {
  const camel = [];
  for (let i6 = 0; i6 < kebab.length; i6++) {
    const ch = kebab.charAt(i6);
    if (ch === "-") {
      camel.push(kebab.charAt(++i6).toUpperCase());
    } else if (i6 === 0 && leadingUppercase) {
      camel.push(ch.toUpperCase());
    } else {
      camel.push(ch);
    }
  }
  return camel.join("");
}
var mergeConfigs;
var init_config2 = __esm({
  "core/config.ts"() {
    init_lodash();
    init_function_times();
    mergeConfigs = makeTimedFunction(
      "mergeConfigs",
      function mergeConfigs2(config2, ...configs) {
        config2 = cloneDeep(config2);
        configs = cloneDeep(configs);
        return mergeWith(
          config2,
          ...configs,
          mergeArrayCustomizer
        );
      }
    );
  }
});

// config/constants.ts
function pdfStandardEnv() {
  const val = Deno.env.get("QUARTO_PDF_STANDARD");
  if (val) {
    return val.split(",").map((s5) => s5.trim()).filter((s5) => s5.length > 0);
  }
  return void 0;
}
var kMetadataFormat, kDisplayName, kExtensionName, kTargetFormat, kBaseFormat, kIdentifierDefaults, kRenderDefaults, kExecuteDefaults, kPandocDefaults, kLanguageDefaults, kPandocMetadata, kFigWidth, kFigHeight, kFigFormat, kFigDpi, kFigAsp, kMermaidFormat, kDfPrint, kCache, kFreeze, kEngine, kEval, kEcho, kOutput, kWarning, kError, kInclude, kResources, kFormatResources, kSupporting, kIpynbProduceSourceNotebook, kEnableCrossRef, kFormatLinks, kNotebookLinks, kOtherLinks, kCodeLinks, kNotebookSubarticles, kNotebookView, kNotebookViewStyle, kNotebookPreserveCells, kClearCellOptions, kDownloadUrl, kLightbox, kCanonicalUrl, kMath, kNotebookPreviewOptions, kKeepHidden, kRemoveHidden, kClearHiddenClasses, kUnrollMarkdownCells, kExecuteEnabled, kExecuteIpynb, kExecuteDaemon, kExecuteDaemonRestart, kExecuteDebug, kIpynbFilter, kIpynbFilters, kIpynbShellInteractivity, kIPynbTitleBlockTemplate, kPlotlyConnected, kJatsSubarticleId, kShortcodes, kKeepMd, kKeepTex, kKeepTyp, kPdfStandard, kPdfStandardApplied, kKeepIpynb, kKeepSource, kVariant, kOutputExt, kOutputDivs, kPageWidth, kFigAlign, kFigEnv, kFigPos, kCodeFold, kCodeLineNumbers, kCodeOverflow, kCodeLink, kCodeTools, kTblCap, kTblColwidths, kMergeIncludes, kInlineIncludes, kPreserveYaml, kPreferHtml, kSelfContainedMath, kBodyClasses, kBrand, kLight, kLatexAutoMk, kLatexAutoInstall, kLatexMinRuns, kLatexMaxRuns, kLatexClean, kLatexInputPaths, kLatexMakeIndex, kLatexMakeIndexOpts, kLatexTinyTex, kLatexTlmgrOpts, kLatexOutputDir, kLinkExternalIcon, kLinkExternalNewwindow, kLinkExternalFilter, kQuartoVersion, kQuartoRequired, kPreviewMode, kPreviewModeRaw, kFontPaths, kHtmlTableProcessing, kHtmlPreTagProcessing, kCssPropertyProcessing, kBrandMode, kRespectUserColorScheme, kUseRsvgConvert, kValidateYaml, kIdentifierDefaultsKeys, kExecuteDefaultsKeys, kRenderDefaultsKeys, kTocTitleDocument, kTocTitleWebsite, kRelatedFormatsTitle, kRelatedNotebooksTitle, kOtherLinksTitle, kCodeLinksTitle, kLaunchDevContainerTitle, kLaunchBinderTitle, kSourceNotebookPrefix, kCalloutTipCaption, kCalloutNoteCaption, kCalloutWarningCaption, kCalloutImportantCaption, kCalloutCautionCaption, kCalloutTipPrefix, kCalloutNotePrefix, kCalloutWarningPrefix, kCalloutImportantPrefix, kCalloutCautionPrefix, kSectionTitleAbstract, kSectionTitleFootnotes, kSectionTitleReferences, kSectionTitleAppendices, kSectionTitleReuse, kSectionTitleCopyright, kSectionTitleCitation, kAppendixAttributionBibTex, kAppendixAttributionCiteAs, kAppendixViewLicense, kTitleBlockAuthorSingle, kTitleBlockAuthorPlural, kTitleBlockAffiliationSingle, kTitleBlockAffiliationPlural, kTitleBlockPublished, kTitleBlockModified, kTitleBlockKeywords, kCodeSummary, kCodeLine, kCodeLines, kCodeToolsMenuCaption, kCodeToolsShowAllCode, kCodeToolsHideAllCode, kCodeToolsViewSource, kCodeToolsSourceCode, kSearchNoResultsText, kSearchLabel, kToolsShare, kToolsDownload, kToggleSection, kToggleSidebar, kToggleDarkMode, kToggleReaderMode, kToggleNavigation, kCopyButtonTooltip, kCopyButtonTooltipSuccess, kBackToTop, kRepoActionLinksEdit, kRepoActionLinksSource, kRepoActionLinksIssue, kSearchMatchingDocumentsText, kSearchCopyLinkTitle, kSearchHideMatchesText, kSearchMoreMatchText, kSearchMoreMatchesText, kSearchClearButtonTitle, kSearchTextPlaceholder, kSearchDetatchedCancelButtonTitle, kSearchSubmitButtonTitle, kCrossrefFigTitle, kCrossrefTblTitle, kCrossrefLstTitle, kCrossrefThmTitle, kCrossrefLemTitle, kCrossrefCorTitle, kCrossrefPrfTitle, kCrossrefCnjTitle, kCrossrefDefTitle, kCrossrefExmTitle, kCrossrefExrTitle, kCrossrefFigPrefix, kCrossrefTblPrefix, kCrossrefLstPrefix, kCrossrefChPrefix, kCrossrefApxPrefix, kCrossrefSecPrefix, kCrossrefEqPrefix, kCrossrefThmPrefix, kCrossrefLemPrefix, kCrossrefCorPrefix, kCrossrefPrpPrefix, kCrossrefCnjPrefix, kCrossrefDefPrefix, kCrossrefExmPrefix, kCrossrefExrPrefix, kCrossrefLofTitle, kCrossrefLotTitle, kCrossrefLolTitle, kEnvironmentProofTitle, kEnvironmentRemarkTitle, kEnvironmentSolutionTitle, kListingPageOrderBy, kListingPageFilter, kListingPageOrderByDefault, kListingPageOrderByDateAsc, kListingPageOrderByDateDesc, kListingPageOrderByNumberAsc, kListingPageOrderByNumberDesc, kListingPageFieldDate, kListingPageFieldTitle, kListingPageFieldDescription, kListingPageFieldAuthor, kListingPageFieldFileName, kListingPageFieldFileModified, kListingPageFieldSubtitle, kListingPageFieldReadingTime, kListingPageFieldWordCount, kListingPageFieldCategories, kListingPageMinutesCompact, kListingPageWords, kListingPageCategoryAll, kListingPageNoMatches, kNotebookPreviewDownload, kNotebookPreviewDownloadSrc, kNotebookPreviewBack, kArticleNotebookLabel, kManuscriptMecaBundle, kDraftLabel, kLanguageDefaultsKeys, kTo, kFrom, kReader, kWriter, kOutputFile, kInputFiles, kMarkdownHeadings, kTemplate, kWrap, kColumns, kStandalone, kSelfContained, kEmbedResources, kIncludeBeforeBody, kIncludeAfterBody, kIncludeInHeader, kResourcePath, kCiteproc, kCiteMethod, kFilters, kQuartoFilters, kFilterParams, kPdfEngine, kNotebooks, kPdfEngineOpts, kPdfEngineOpt, kListings, kNumberSections, kSectionNumbering, kNumberOffset, kShiftHeadingLevelBy, kNumberDepth, kTopLevelDivision, kPaperSize, kLogFile, kHighlightStyle, kSyntaxHighlighting, kDefaultImageExtension, kLogo, kLinkColor, kColorLinks, kVariables, kMetadataFile, kMetadataFiles, kSyntaxDefinitions, kSyntaxDefinition, kReferenceDoc, kHtmlMathMethod, kToc, kTocDepth, kTocIndent, kTableOfContents, kSectionDivs, kEPubCoverImage, kReferenceLocation, kCitationLocation, kQuartoVarsKey, kQuartoTemplateParams, kRevealJsScripts, kQuartoInternal, kTitle, kSubtitle, kAuthor, kDate, kDateFormat, kDateModified, kDoi, kAbstract, kAbstractTitle, kDescription, kHideDescription, kTocTitle, kTocLocation, kTocExpand, kLang, kOrder, kDisableArticleLayout, kAuthors, kInstitute, kInstitutes, kServer, kPageTitle, kTitlePrefix, kCsl, kNoCite, kCss, kBibliography, kReferences, kHeaderIncludes, kIncludeBefore, kIncludeAfter, kLinkCitations, kDocumentClass, kClassOption, kSlideLevel, kTheme, kCrossref, kCrossrefChapters, kCrossrefLabels, kCrossrefAppendixTitle, kCrossrefAppendixDelim, kCrossrefChaptersAppendix, kCrossrefChaptersAlpha, kCrossrefChapterId, kGrid, kContentMode, kFigResponsive, kOutputLocation, kCapLoc, kFigCapLoc, kTblCapLoc, kCapTop, kCapBottom, kPositionedRefs, kPandocDefaultsKeys, kCellCollapsed, kCellAutoscroll, kCellDeletable, kCellFormat, kCellName, kCellLinesToNext, kCellLanguage, kCellSlideshow, kCellSlideshowSlideType, kCellRawMimeType, kCellUserExpressions, kCellId, kCellLabel, kCellFigCap, kCellFigSubCap, kCellFigScap, kCellFigColumn, kCellTblColumn, kCellFigLink, kCellFigAlign, kCellFigEnv, kCellFigPos, kCellFigAlt, kCellLstLabel, kCellLstCap, kCellClasses, kCellPanel, kCellColumn, kCellOutWidth, kCellOutHeight, kCellMdIndent, kCellWidth, kCellHeight, kCellColab, kCellColabType, kCellColbOutputId, kLayoutAlign, kLayoutVAlign, kLayoutNcol, kLayoutNrow, kLayout, kCliffyImplicitCwd, kSourceMappingRegexes, kFormatIdentifier, kRenderFileLifetime, kRenderServicesLifetime, kQuartoPre, kQuartoPost;
var init_constants6 = __esm({
  "config/constants.ts"() {
    kMetadataFormat = "format";
    kDisplayName = "display-name";
    kExtensionName = "extension-name";
    kTargetFormat = "target-format";
    kBaseFormat = "base-format";
    kIdentifierDefaults = "indentifier";
    kRenderDefaults = "render";
    kExecuteDefaults = "execute";
    kPandocDefaults = "pandoc";
    kLanguageDefaults = "language";
    kPandocMetadata = "metadata";
    kFigWidth = "fig-width";
    kFigHeight = "fig-height";
    kFigFormat = "fig-format";
    kFigDpi = "fig-dpi";
    kFigAsp = "fig-asp";
    kMermaidFormat = "mermaid-format";
    kDfPrint = "df-print";
    kCache = "cache";
    kFreeze = "freeze";
    kEngine = "engine";
    kEval = "eval";
    kEcho = "echo";
    kOutput = "output";
    kWarning = "warning";
    kError = "error";
    kInclude = "include";
    kResources = "resources";
    kFormatResources = "format-resources";
    kSupporting = "supporting";
    kIpynbProduceSourceNotebook = "produce-source-notebook";
    kEnableCrossRef = "enable-crossref";
    kFormatLinks = "format-links";
    kNotebookLinks = "notebook-links";
    kOtherLinks = "other-links";
    kCodeLinks = "code-links";
    kNotebookSubarticles = "notebook-subarticles";
    kNotebookView = "notebook-view";
    kNotebookViewStyle = "notebook-view-style";
    kNotebookPreserveCells = "notebook-preserve-cells";
    kClearCellOptions = "clear-cell-options";
    kDownloadUrl = "download-url";
    kLightbox = "lightbox";
    kCanonicalUrl = "canonical-url";
    kMath = "math";
    kNotebookPreviewOptions = "notebook-preview-options";
    kKeepHidden = "keep-hidden";
    kRemoveHidden = "remove-hidden";
    kClearHiddenClasses = "clear-hidden-classes";
    kUnrollMarkdownCells = "unroll-markdown-cells";
    kExecuteEnabled = "enabled";
    kExecuteIpynb = "ipynb";
    kExecuteDaemon = "daemon";
    kExecuteDaemonRestart = "daemon-restart";
    kExecuteDebug = "debug";
    kIpynbFilter = "ipynb-filter";
    kIpynbFilters = "ipynb-filters";
    kIpynbShellInteractivity = "ipynb-shell-interactivity";
    kIPynbTitleBlockTemplate = "ipynb-title-block";
    kPlotlyConnected = "plotly-connected";
    kJatsSubarticleId = "jats-subarticle-id";
    kShortcodes = "shortcodes";
    kKeepMd = "keep-md";
    kKeepTex = "keep-tex";
    kKeepTyp = "keep-typ";
    kPdfStandard = "pdf-standard";
    kPdfStandardApplied = "pdf-standard-applied";
    kKeepIpynb = "keep-ipynb";
    kKeepSource = "keep-source";
    kVariant = "variant";
    kOutputExt = "output-ext";
    kOutputDivs = "output-divs";
    kPageWidth = "page-width";
    kFigAlign = "fig-align";
    kFigEnv = "fig-env";
    kFigPos = "fig-pos";
    kCodeFold = "code-fold";
    kCodeLineNumbers = "code-line-numbers";
    kCodeOverflow = "code-overflow";
    kCodeLink = "code-link";
    kCodeTools = "code-tools";
    kTblCap = "tbl-cap";
    kTblColwidths = "tbl-colwidths";
    kMergeIncludes = "merge-includes";
    kInlineIncludes = "inline-includes";
    kPreserveYaml = "preserve-yaml";
    kPreferHtml = "prefer-html";
    kSelfContainedMath = "self-contained-math";
    kBodyClasses = "body-classes";
    kBrand = "brand";
    kLight = "light";
    kLatexAutoMk = "latex-auto-mk";
    kLatexAutoInstall = "latex-auto-install";
    kLatexMinRuns = "latex-min-runs";
    kLatexMaxRuns = "latex-max-runs";
    kLatexClean = "latex-clean";
    kLatexInputPaths = "latex-input-paths";
    kLatexMakeIndex = "latex-makeindex";
    kLatexMakeIndexOpts = "latex-makeindex-opts";
    kLatexTinyTex = "latex-tinytex";
    kLatexTlmgrOpts = "latex-tlmgr-opts";
    kLatexOutputDir = "latex-output-dir";
    kLinkExternalIcon = "link-external-icon";
    kLinkExternalNewwindow = "link-external-newwindow";
    kLinkExternalFilter = "link-external-filter";
    kQuartoVersion = "quarto-version";
    kQuartoRequired = "quarto-required";
    kPreviewMode = "preview-mode";
    kPreviewModeRaw = "raw";
    kFontPaths = "font-paths";
    kHtmlTableProcessing = "html-table-processing";
    kHtmlPreTagProcessing = "html-pre-tag-processing";
    kCssPropertyProcessing = "css-property-processing";
    kBrandMode = "brand-mode";
    kRespectUserColorScheme = "respect-user-color-scheme";
    kUseRsvgConvert = "use-rsvg-convert";
    kValidateYaml = "validate-yaml";
    kIdentifierDefaultsKeys = [
      kTargetFormat,
      kDisplayName,
      kExtensionName
    ];
    kExecuteDefaultsKeys = [
      kFigWidth,
      kFigHeight,
      kFigFormat,
      kFigDpi,
      kFigAsp,
      kMermaidFormat,
      kDfPrint,
      kError,
      kEval,
      kEngine,
      kCache,
      kFreeze,
      kEcho,
      kOutput,
      kWarning,
      kInclude,
      kKeepMd,
      kKeepIpynb,
      kExecuteEnabled,
      kExecuteIpynb,
      kExecuteDaemon,
      kExecuteDaemonRestart,
      kExecuteDebug,
      kIpynbFilter,
      kIpynbFilters,
      kIpynbShellInteractivity,
      kPlotlyConnected
    ];
    kRenderDefaultsKeys = [
      kKeepTex,
      kKeepTyp,
      kKeepSource,
      kKeepHidden,
      kRemoveHidden,
      kClearHiddenClasses,
      kVariant,
      kOutputExt,
      kOutputDivs,
      kPreferHtml,
      kPageWidth,
      kFigAlign,
      kFigPos,
      kFigEnv,
      kCodeFold,
      kCodeLink,
      kCodeLineNumbers,
      kCodeOverflow,
      kCodeTools,
      kShortcodes,
      kTblColwidths,
      kInlineIncludes,
      kPreserveYaml,
      kMergeIncludes,
      kSelfContainedMath,
      kLatexAutoMk,
      kLatexAutoInstall,
      kLatexMinRuns,
      kLatexMaxRuns,
      kLatexClean,
      kLatexInputPaths,
      kLatexMakeIndex,
      kLatexMakeIndexOpts,
      kLatexTlmgrOpts,
      kLatexOutputDir,
      kLatexTinyTex,
      kPdfStandard,
      kLinkExternalIcon,
      kLinkExternalNewwindow,
      kLinkExternalFilter,
      kFormatResources,
      kFormatLinks,
      kIpynbProduceSourceNotebook,
      kNotebookLinks,
      kNotebookSubarticles,
      kNotebookView,
      kNotebookViewStyle,
      kNotebookPreserveCells,
      kClearCellOptions,
      kHtmlTableProcessing,
      kValidateYaml,
      kCanonicalUrl,
      kBodyClasses
    ];
    kTocTitleDocument = "toc-title-document";
    kTocTitleWebsite = "toc-title-website";
    kRelatedFormatsTitle = "related-formats-title";
    kRelatedNotebooksTitle = "related-notebooks-title";
    kOtherLinksTitle = "other-links-title";
    kCodeLinksTitle = "code-links-title";
    kLaunchDevContainerTitle = "launch-dev-container-title";
    kLaunchBinderTitle = "launch-binder-title";
    kSourceNotebookPrefix = "source-notebooks-prefix";
    kCalloutTipCaption = "callout-tip-title";
    kCalloutNoteCaption = "callout-note-title";
    kCalloutWarningCaption = "callout-warning-title";
    kCalloutImportantCaption = "callout-important-title";
    kCalloutCautionCaption = "callout-caution-title";
    kCalloutTipPrefix = "callout-tip-prefix";
    kCalloutNotePrefix = "callout-note-prefix";
    kCalloutWarningPrefix = "callout-warning-prefix";
    kCalloutImportantPrefix = "callout-important-prefix";
    kCalloutCautionPrefix = "callout-caution-prefix";
    kSectionTitleAbstract = "section-title-abstract";
    kSectionTitleFootnotes = "section-title-footnotes";
    kSectionTitleReferences = "section-title-references";
    kSectionTitleAppendices = "section-title-appendices";
    kSectionTitleReuse = "section-title-reuse";
    kSectionTitleCopyright = "section-title-copyright";
    kSectionTitleCitation = "section-title-citation";
    kAppendixAttributionBibTex = "appendix-attribution-bibtex";
    kAppendixAttributionCiteAs = "appendix-attribution-cite-as";
    kAppendixViewLicense = "appendix-view-license";
    kTitleBlockAuthorSingle = "title-block-author-single";
    kTitleBlockAuthorPlural = "title-block-author-plural";
    kTitleBlockAffiliationSingle = "title-block-affiliation-single";
    kTitleBlockAffiliationPlural = "title-block-affiliation-plural";
    kTitleBlockPublished = "title-block-published";
    kTitleBlockModified = "title-block-modified";
    kTitleBlockKeywords = "title-block-keywords";
    kCodeSummary = "code-summary";
    kCodeLine = "code-line";
    kCodeLines = "code-lines";
    kCodeToolsMenuCaption = "code-tools-menu-caption";
    kCodeToolsShowAllCode = "code-tools-show-all-code";
    kCodeToolsHideAllCode = "code-tools-hide-all-code";
    kCodeToolsViewSource = "code-tools-view-source";
    kCodeToolsSourceCode = "code-tools-source-code";
    kSearchNoResultsText = "search-no-results-text";
    kSearchLabel = "search-label";
    kToolsShare = "tools-share";
    kToolsDownload = "tools-download";
    kToggleSection = "toggle-section";
    kToggleSidebar = "toggle-sidebar";
    kToggleDarkMode = "toggle-dark-mode";
    kToggleReaderMode = "toggle-reader-mode";
    kToggleNavigation = "toggle-navigation";
    kCopyButtonTooltip = "copy-button-tooltip";
    kCopyButtonTooltipSuccess = "copy-button-tooltip-success";
    kBackToTop = "back-to-top";
    kRepoActionLinksEdit = "repo-action-links-edit";
    kRepoActionLinksSource = "repo-action-links-source";
    kRepoActionLinksIssue = "repo-action-links-issue";
    kSearchMatchingDocumentsText = "search-matching-documents-text";
    kSearchCopyLinkTitle = "search-copy-link-title";
    kSearchHideMatchesText = "search-hide-matches-text";
    kSearchMoreMatchText = "search-more-match-text";
    kSearchMoreMatchesText = "search-more-matches-text";
    kSearchClearButtonTitle = "search-clear-button-title";
    kSearchTextPlaceholder = "search-text-placeholder";
    kSearchDetatchedCancelButtonTitle = "search-detached-cancel-button-title";
    kSearchSubmitButtonTitle = "search-submit-button-title";
    kCrossrefFigTitle = "crossref-fig-title";
    kCrossrefTblTitle = "crossref-tbl-title";
    kCrossrefLstTitle = "crossref-lst-title";
    kCrossrefThmTitle = "crossref-thm-title";
    kCrossrefLemTitle = "crossref-lem-title";
    kCrossrefCorTitle = "crossref-cor-title";
    kCrossrefPrfTitle = "crossref-prp-title";
    kCrossrefCnjTitle = "crossref-cnj-title";
    kCrossrefDefTitle = "crossref-def-title";
    kCrossrefExmTitle = "crossref-exm-title";
    kCrossrefExrTitle = "crossref-exr-title";
    kCrossrefFigPrefix = "crossref-fig-prefix";
    kCrossrefTblPrefix = "crossref-tbl-prefix";
    kCrossrefLstPrefix = "crossref-lst-prefix";
    kCrossrefChPrefix = "crossref-ch-prefix";
    kCrossrefApxPrefix = "crossref-apx-prefix";
    kCrossrefSecPrefix = "crossref-sec-prefix";
    kCrossrefEqPrefix = "crossref-eq-prefix";
    kCrossrefThmPrefix = "crossref-thm-prefix";
    kCrossrefLemPrefix = "crossref-lem-prefix";
    kCrossrefCorPrefix = "crossref-cor-prefix";
    kCrossrefPrpPrefix = "crossref-prp-prefix";
    kCrossrefCnjPrefix = "crossref-cnj-prefix";
    kCrossrefDefPrefix = "crossref-def-prefix";
    kCrossrefExmPrefix = "crossref-exm-prefix";
    kCrossrefExrPrefix = "crossref-exr-prefix";
    kCrossrefLofTitle = "crossref-lof-title";
    kCrossrefLotTitle = "crossref-lot-title";
    kCrossrefLolTitle = "crossref-lol-title";
    kEnvironmentProofTitle = "environment-proof-title";
    kEnvironmentRemarkTitle = "environment-remark-title";
    kEnvironmentSolutionTitle = "environment-solution-title";
    kListingPageOrderBy = "listing-page-order-by";
    kListingPageFilter = "listing-page-filter";
    kListingPageOrderByDefault = "listing-page-order-by-default";
    kListingPageOrderByDateAsc = "listing-page-order-by-date-asc";
    kListingPageOrderByDateDesc = "listing-page-order-by-date-desc";
    kListingPageOrderByNumberAsc = "listing-page-order-by-number-asc";
    kListingPageOrderByNumberDesc = "listing-page-order-by-number-desc";
    kListingPageFieldDate = "listing-page-field-date";
    kListingPageFieldTitle = "listing-page-field-title";
    kListingPageFieldDescription = "listing-page-field-description";
    kListingPageFieldAuthor = "listing-page-field-author";
    kListingPageFieldFileName = "listing-page-field-filename";
    kListingPageFieldFileModified = "listing-page-field-filemodified";
    kListingPageFieldSubtitle = "listing-page-field-subtitle";
    kListingPageFieldReadingTime = "listing-page-field-readingtime";
    kListingPageFieldWordCount = "listing-page-field-wordcount";
    kListingPageFieldCategories = "listing-page-field-categories";
    kListingPageMinutesCompact = "listing-page-minutes-compact";
    kListingPageWords = "listing-page-words";
    kListingPageCategoryAll = "listing-page-category-all";
    kListingPageNoMatches = "listing-page-no-matches";
    kNotebookPreviewDownload = "notebook-preview-download";
    kNotebookPreviewDownloadSrc = "notebook-preview-download-src";
    kNotebookPreviewBack = "notebook-preview-back";
    kArticleNotebookLabel = "article-notebook-label";
    kManuscriptMecaBundle = "manuscript-meca-bundle";
    kDraftLabel = "draft";
    kLanguageDefaultsKeys = [
      kTocTitleDocument,
      kTocTitleWebsite,
      kRelatedFormatsTitle,
      kOtherLinksTitle,
      kCodeLinksTitle,
      kLaunchDevContainerTitle,
      kLaunchBinderTitle,
      kRelatedNotebooksTitle,
      kSourceNotebookPrefix,
      kCalloutTipCaption,
      kCalloutNoteCaption,
      kCalloutWarningCaption,
      kCalloutImportantCaption,
      kCalloutCautionCaption,
      kCalloutTipPrefix,
      kCalloutNotePrefix,
      kCalloutWarningPrefix,
      kCalloutImportantPrefix,
      kCalloutCautionPrefix,
      kSectionTitleAbstract,
      kSectionTitleFootnotes,
      kSectionTitleReferences,
      kSectionTitleAppendices,
      kSectionTitleReuse,
      kSectionTitleCopyright,
      kSectionTitleCitation,
      kAppendixAttributionBibTex,
      kAppendixAttributionCiteAs,
      kAppendixViewLicense,
      kTitleBlockAuthorSingle,
      kTitleBlockPublished,
      kTitleBlockModified,
      kTitleBlockKeywords,
      kCodeSummary,
      kCodeLine,
      kCodeLines,
      kCodeToolsMenuCaption,
      kCodeToolsShowAllCode,
      kCodeToolsHideAllCode,
      kCodeToolsViewSource,
      kCodeToolsSourceCode,
      kToolsShare,
      kToolsDownload,
      kSearchNoResultsText,
      kSearchLabel,
      kToggleDarkMode,
      kToggleNavigation,
      kToggleReaderMode,
      kToggleSidebar,
      kToggleSection,
      kCopyButtonTooltip,
      kCopyButtonTooltipSuccess,
      kBackToTop,
      kRepoActionLinksEdit,
      kRepoActionLinksSource,
      kRepoActionLinksIssue,
      kSearchMatchingDocumentsText,
      kSearchCopyLinkTitle,
      kSearchHideMatchesText,
      kSearchMoreMatchText,
      kSearchMoreMatchesText,
      kSearchClearButtonTitle,
      kSearchTextPlaceholder,
      kSearchDetatchedCancelButtonTitle,
      kSearchSubmitButtonTitle,
      kCrossrefFigTitle,
      kCrossrefTblTitle,
      kCrossrefLstTitle,
      kCrossrefThmTitle,
      kCrossrefLemTitle,
      kCrossrefCorTitle,
      kCrossrefPrfTitle,
      kCrossrefCnjTitle,
      kCrossrefDefTitle,
      kCrossrefExmTitle,
      kCrossrefExrTitle,
      kCrossrefFigPrefix,
      kCrossrefTblPrefix,
      kCrossrefLstPrefix,
      kCrossrefChPrefix,
      kCrossrefApxPrefix,
      kCrossrefSecPrefix,
      kCrossrefEqPrefix,
      kCrossrefThmPrefix,
      kCrossrefLemPrefix,
      kCrossrefCorPrefix,
      kCrossrefPrpPrefix,
      kCrossrefCnjPrefix,
      kCrossrefDefPrefix,
      kCrossrefExmPrefix,
      kCrossrefExrPrefix,
      kCrossrefLofTitle,
      kCrossrefLotTitle,
      kCrossrefLolTitle,
      kEnvironmentProofTitle,
      kEnvironmentRemarkTitle,
      kEnvironmentSolutionTitle,
      kListingPageFilter,
      kListingPageOrderBy,
      kListingPageOrderByDefault,
      kListingPageOrderByDateAsc,
      kListingPageOrderByDateDesc,
      kListingPageOrderByNumberAsc,
      kListingPageOrderByNumberDesc,
      kListingPageFieldDate,
      kListingPageFieldTitle,
      kListingPageFieldDescription,
      kListingPageFieldAuthor,
      kListingPageFieldFileName,
      kListingPageFieldFileModified,
      kListingPageFieldSubtitle,
      kListingPageFieldReadingTime,
      kListingPageFieldWordCount,
      kListingPageFieldCategories,
      kListingPageMinutesCompact,
      kListingPageWords,
      kListingPageCategoryAll,
      kListingPageNoMatches,
      kTitleBlockAuthorSingle,
      kTitleBlockAuthorPlural,
      kTitleBlockAffiliationSingle,
      kTitleBlockAffiliationPlural,
      kTitleBlockPublished,
      kTitleBlockModified,
      kTitleBlockKeywords,
      kNotebookPreviewDownload,
      kNotebookPreviewDownloadSrc,
      kNotebookPreviewBack,
      kArticleNotebookLabel,
      kDraftLabel,
      kManuscriptMecaBundle
    ];
    kTo = "to";
    kFrom = "from";
    kReader = "reader";
    kWriter = "writer";
    kOutputFile = "output-file";
    kInputFiles = "input-files";
    kMarkdownHeadings = "markdown-headings";
    kTemplate = "template";
    kWrap = "wrap";
    kColumns = "columns";
    kStandalone = "standalone";
    kSelfContained = "self-contained";
    kEmbedResources = "embed-resources";
    kIncludeBeforeBody = "include-before-body";
    kIncludeAfterBody = "include-after-body";
    kIncludeInHeader = "include-in-header";
    kResourcePath = "resource-path";
    kCiteproc = "citeproc";
    kCiteMethod = "cite-method";
    kFilters = "filters";
    kQuartoFilters = "quarto-filters";
    kFilterParams = "filter-params";
    kPdfEngine = "pdf-engine";
    kNotebooks = "notebooks";
    kPdfEngineOpts = "pdf-engine-opts";
    kPdfEngineOpt = "pdf-engine-opt";
    kListings = "listings";
    kNumberSections = "number-sections";
    kSectionNumbering = "section-numbering";
    kNumberOffset = "number-offset";
    kShiftHeadingLevelBy = "shift-heading-level-by";
    kNumberDepth = "number-depth";
    kTopLevelDivision = "top-level-division";
    kPaperSize = "papersize";
    kLogFile = "log-file";
    kHighlightStyle = "highlight-style";
    kSyntaxHighlighting = "syntax-highlighting";
    kDefaultImageExtension = "default-image-extension";
    kLogo = "logo";
    kLinkColor = "linkcolor";
    kColorLinks = "colorlinks";
    kVariables = "variables";
    kMetadataFile = "metadata-file";
    kMetadataFiles = "metadata-files";
    kSyntaxDefinitions = "syntax-definitions";
    kSyntaxDefinition = "syntax-definition";
    kReferenceDoc = "reference-doc";
    kHtmlMathMethod = "html-math-method";
    kToc = "toc";
    kTocDepth = "toc-depth";
    kTocIndent = "toc-indent";
    kTableOfContents = "table-of-contents";
    kSectionDivs = "section-divs";
    kEPubCoverImage = "epub-cover-image";
    kReferenceLocation = "reference-location";
    kCitationLocation = "citation-location";
    kQuartoVarsKey = "_quarto-vars";
    kQuartoTemplateParams = "quarto-template-params";
    kRevealJsScripts = "reveal-jsscripts";
    kQuartoInternal = "quarto-internal";
    kTitle = "title";
    kSubtitle = "subtitle";
    kAuthor = "author";
    kDate = "date";
    kDateFormat = "date-format";
    kDateModified = "date-modified";
    kDoi = "doi";
    kAbstract = "abstract";
    kAbstractTitle = "abstract-title";
    kDescription = "description";
    kHideDescription = "hide-description";
    kTocTitle = "toc-title";
    kTocLocation = "toc-location";
    kTocExpand = "toc-expand";
    kLang = "lang";
    kOrder = "order";
    kDisableArticleLayout = "disable-article-layout";
    kAuthors = "authors";
    kInstitute = "institute";
    kInstitutes = "institutes";
    kServer = "server";
    kPageTitle = "pagetitle";
    kTitlePrefix = "title-prefix";
    kCsl = "csl";
    kNoCite = "nocite";
    kCss = "css";
    kBibliography = "bibliography";
    kReferences = "references";
    kHeaderIncludes = "header-includes";
    kIncludeBefore = "include-before";
    kIncludeAfter = "include-after";
    kLinkCitations = "link-citations";
    kDocumentClass = "documentclass";
    kClassOption = "classoption";
    kSlideLevel = "slide-level";
    kTheme = "theme";
    kCrossref = "crossref";
    kCrossrefChapters = "chapters";
    kCrossrefLabels = "labels";
    kCrossrefAppendixTitle = "appendix-title";
    kCrossrefAppendixDelim = "appendix-delim";
    kCrossrefChaptersAppendix = "chapters-appendix";
    kCrossrefChaptersAlpha = "chapters-alpha";
    kCrossrefChapterId = "chapter-id";
    kGrid = "grid";
    kContentMode = "content-mode";
    kFigResponsive = "fig-responsive";
    kOutputLocation = "output-location";
    kCapLoc = "cap-location";
    kFigCapLoc = "fig-cap-location";
    kTblCapLoc = "tbl-cap-location";
    kCapTop = "top";
    kCapBottom = "bottom";
    kPositionedRefs = "positioned-refs";
    kPandocDefaultsKeys = [
      kTo,
      kFrom,
      kReader,
      kWriter,
      kOutputFile,
      kInputFiles,
      "defaults",
      kTemplate,
      kStandalone,
      kSelfContained,
      kEmbedResources,
      kVariables,
      "metadata",
      kMetadataFiles,
      kMetadataFile,
      kIncludeBeforeBody,
      kIncludeAfterBody,
      kIncludeInHeader,
      kResourcePath,
      kCiteproc,
      kCiteMethod,
      "citation-abbreviations",
      "filters",
      "file-scope",
      "data-dir",
      "verbosity",
      kLogFile,
      kTopLevelDivision,
      "abbreviations",
      kPdfEngine,
      kPdfEngineOpts,
      kPdfEngineOpt,
      kPdfStandard,
      kWrap,
      kColumns,
      "dpi",
      "extract-media",
      kToc,
      kTableOfContents,
      kTocDepth,
      kNumberSections,
      kNumberOffset,
      kShiftHeadingLevelBy,
      kSectionDivs,
      "identifier-prefix",
      kTitlePrefix,
      "eol",
      "strip-comments",
      "indented-code-classes",
      "ascii",
      kDefaultImageExtension,
      kHighlightStyle,
      kSyntaxHighlighting,
      kSyntaxDefinitions,
      kSyntaxDefinition,
      kListings,
      kReferenceDoc,
      kHtmlMathMethod,
      "email-obfuscation",
      "tab-stop",
      "preserve-tabs",
      "incremental",
      kSlideLevel,
      "epub-subdirectory",
      "epub-metadata",
      "epub-fonts",
      "epub-chapter-level",
      kEPubCoverImage,
      "reference-links",
      kReferenceLocation,
      kMarkdownHeadings,
      "track-changes",
      "html-q-tags",
      "css",
      "ipynb-output",
      "request-headers",
      "fail-if-warnings",
      "dump-args",
      "ignore-args",
      "trace"
    ];
    kCellCollapsed = "collapsed";
    kCellAutoscroll = "autoscroll";
    kCellDeletable = "deletable";
    kCellFormat = "format";
    kCellName = "name";
    kCellLinesToNext = "lines_to_next_cell";
    kCellLanguage = "language";
    kCellSlideshow = "slideshow";
    kCellSlideshowSlideType = "slide_type";
    kCellRawMimeType = "raw_mimetype";
    kCellUserExpressions = "user_expressions";
    kCellId = "id";
    kCellLabel = "label";
    kCellFigCap = "fig-cap";
    kCellFigSubCap = "fig-subcap";
    kCellFigScap = "fig-scap";
    kCellFigColumn = "fig-column";
    kCellTblColumn = "tbl-column";
    kCellFigLink = "fig-link";
    kCellFigAlign = "fig-align";
    kCellFigEnv = "fig-env";
    kCellFigPos = "fig-pos";
    kCellFigAlt = "fig-alt";
    kCellLstLabel = "lst-label";
    kCellLstCap = "lst-cap";
    kCellClasses = "classes";
    kCellPanel = "panel";
    kCellColumn = "column";
    kCellOutWidth = "out-width";
    kCellOutHeight = "out-height";
    kCellMdIndent = "md-indent";
    kCellWidth = "width";
    kCellHeight = "height";
    kCellColab = "colab";
    kCellColabType = "colab_type";
    kCellColbOutputId = "outputId";
    kLayoutAlign = "layout-align";
    kLayoutVAlign = "layout-valign";
    kLayoutNcol = "layout-ncol";
    kLayoutNrow = "layout-nrow";
    kLayout = "layout";
    kCliffyImplicitCwd = "5a6d2e4f-f9a2-43bc-8019-8149fbb76c85";
    kSourceMappingRegexes = [
      /^\/\/#\s*sourceMappingURL\=.*\.map$/gm,
      /\/\*\# sourceMappingURL=.* \*\//g
    ];
    kFormatIdentifier = "format-identifier";
    kRenderFileLifetime = "render-file";
    kRenderServicesLifetime = "render-services";
    kQuartoPre = "pre-quarto";
    kQuartoPost = "post-render";
  }
});

// core/schema/validated-yaml.ts
async function readAndValidateYamlFromFile(file, schema4, errorMessage, defaultContents) {
  if (!existsSync2(file)) {
    throw new Error(`YAML file ${file} not found.`);
  }
  let shortFileName = file;
  if (shortFileName.startsWith("/")) {
    shortFileName = relative4(Deno.cwd(), shortFileName);
  }
  let fileContents = Deno.readTextFileSync(file).trimEnd();
  if (fileContents.trim().length === 0 && defaultContents) {
    fileContents = defaultContents;
  }
  const contents = asMappedString(
    fileContents,
    shortFileName
  );
  const {
    yaml,
    yamlValidationErrors
  } = await readAndValidateYamlFromMappedString(contents, schema4);
  if (yamlValidationErrors.length) {
    throw new ValidationError4(errorMessage, yamlValidationErrors);
  }
  return yaml;
}
var init_validated_yaml2 = __esm({
  "core/schema/validated-yaml.ts"() {
    init_fs();
    init_mapped_text2();
    init_path();
    init_validated_yaml();
    init_validated_yaml();
  }
});

// format/markdown/format-markdown-consts.ts
var kGfmCommonmarkExtensions, kGfmCommonmarkVariant, kGfmCommonmarkFormat;
var init_format_markdown_consts = __esm({
  "format/markdown/format-markdown-consts.ts"() {
    kGfmCommonmarkExtensions = [
      "+autolink_bare_uris",
      "+emoji",
      "+footnotes",
      "+gfm_auto_identifiers",
      "+pipe_tables",
      "+strikeout",
      "+task_lists",
      "+tex_math_dollars"
    ];
    kGfmCommonmarkVariant = kGfmCommonmarkExtensions.join("");
    kGfmCommonmarkFormat = `commonmark${kGfmCommonmarkVariant}`;
  }
});

// execute/types.ts
var kQmdExtensions, kMarkdownEngine, kKnitrEngine, kJupyterEngine;
var init_types3 = __esm({
  "execute/types.ts"() {
    kQmdExtensions = [".qmd"];
    kMarkdownEngine = "markdown";
    kKnitrEngine = "knitr";
    kJupyterEngine = "jupyter";
  }
});

// config/metadata.ts
async function includedMetadata(dir, baseMetadata, schema4) {
  const yamlFiles = [];
  const metadataFile = baseMetadata[kMetadataFile];
  if (metadataFile) {
    yamlFiles.push(join4(dir, metadataFile));
  }
  const metadataFiles = baseMetadata[kMetadataFiles];
  if (metadataFiles && Array.isArray(metadataFiles)) {
    metadataFiles.forEach((file) => yamlFiles.push(join4(dir, file)));
  }
  const filesMetadata = await Promise.all(yamlFiles.map(async (yamlFile) => {
    if (existsSync2(yamlFile)) {
      try {
        const yaml = await readAndValidateYamlFromFile(
          yamlFile,
          schema4,
          `Validation of metadata file ${yamlFile} failed.`
        );
        return yaml;
      } catch (e5) {
        error("\nError reading metadata file from " + yamlFile + "\n");
        throw e5;
      }
    } else {
      return void 0;
    }
  }));
  return {
    metadata: mergeFormatMetadata({}, ...filesMetadata),
    files: yamlFiles
  };
}
function formatFromMetadata(baseFormat, to, debug4) {
  const typedFormat = {
    identifier: {},
    render: {},
    execute: {},
    pandoc: {},
    language: {},
    metadata: {}
  };
  let format14 = typedFormat;
  const configFormats = baseFormat.metadata[kMetadataFormat];
  if (configFormats instanceof Object) {
    const configFormat = configFormats[to];
    if (configFormat === "default" || configFormat === true) {
      format14 = metadataAsFormat({});
    } else if (configFormat instanceof Object) {
      format14 = metadataAsFormat(configFormat);
    }
  }
  const mergedFormat = mergeFormatMetadata(
    baseFormat,
    format14
  );
  if (debug4) {
    mergedFormat.execute[kKeepMd] = true;
    mergedFormat.render[kKeepTex] = true;
    mergedFormat.render[kKeepTyp] = true;
  }
  return mergedFormat;
}
function formatKeys(metadata) {
  if (typeof metadata[kMetadataFormat] === "string") {
    return [metadata[kMetadataFormat]];
  } else if (metadata[kMetadataFormat] instanceof Object) {
    return Object.keys(metadata[kMetadataFormat]).filter((key) => {
      const format14 = metadata[kMetadataFormat][key];
      return format14 !== null && format14 !== false;
    });
  } else {
    return [];
  }
}
function isQuartoMetadata(key) {
  return kRenderDefaultsKeys.includes(key) || kExecuteDefaultsKeys.includes(key) || kPandocDefaultsKeys.includes(key) || kLanguageDefaultsKeys.includes(key) || [kKnitrEngine, kJupyterEngine].includes(key);
}
function isIncludeMetadata(key) {
  return [kHeaderIncludes, kIncludeBefore, kIncludeAfter].includes(key);
}
function metadataAsFormat(metadata) {
  const typedFormat = {
    identifier: {},
    render: {},
    execute: {},
    pandoc: {},
    language: {},
    metadata: {}
  };
  const format14 = typedFormat;
  Object.keys(metadata).forEach((key) => {
    if ([
      kIdentifierDefaults,
      kRenderDefaults,
      kExecuteDefaults,
      kPandocDefaults,
      kLanguageDefaults,
      kPandocMetadata
    ].includes(key)) {
      if (typeof metadata[key] == "boolean") {
        if (key === kExecuteDefaults) {
          format14[key] = format14[key] || {};
          format14[kExecuteDefaults][kExecuteEnabled] = metadata[key];
        }
      } else {
        format14[key] = { ...format14[key], ...metadata[key] };
      }
    } else {
      if (kIdentifierDefaultsKeys.includes(key)) {
        format14.identifier[key] = metadata[key];
      } else if (kRenderDefaultsKeys.includes(key)) {
        format14.render[key] = metadata[key];
      } else if (kExecuteDefaultsKeys.includes(key)) {
        format14.execute[key] = metadata[key];
      } else if (kPandocDefaultsKeys.includes(key)) {
        format14.pandoc[key] = metadata[key];
      } else {
        format14.metadata[key] = metadata[key];
      }
    }
  });
  if (typeof format14.metadata[kServer] === "string") {
    format14.metadata[kServer] = {
      type: format14.metadata[kServer]
    };
  }
  const filter3 = format14.execute[kIpynbFilter];
  if (typeof filter3 === "string") {
    typedFormat.execute[kIpynbFilters] = typedFormat.execute[kIpynbFilters] || [];
    typedFormat.execute[kIpynbFilters]?.push(filter3);
    delete typedFormat.execute[kIpynbFilter];
  }
  if (typeof typedFormat.render.variant === "string") {
    typedFormat.render.variant = typedFormat.render.variant.replace(
      /^gfm/,
      kGfmCommonmarkVariant
    );
  }
  return typedFormat;
}
function metadataGetDeep(metadata, property) {
  let values = [];
  each(metadata, (value, key) => {
    if (key === property) {
      values.push(value);
    } else if (isObject(value)) {
      values = values.concat(metadataGetDeep(value, property));
    }
  });
  return values;
}
function mergeFormatMetadata(config2, ...configs) {
  const kUnmergeableKeys = [kTblColwidths];
  const kBooleanDisableArrays = [kCodeLinks, kOtherLinks];
  return mergeConfigsCustomized(
    (objValue, srcValue, key) => {
      if (kUnmergeableKeys.includes(key)) {
        return srcValue;
      } else if (key === kVariant) {
        return mergePandocVariant(objValue, srcValue);
      } else if (kBooleanDisableArrays.includes(key)) {
        return mergeDisablableArray(objValue, srcValue);
      } else {
        return void 0;
      }
    },
    config2,
    ...configs
  );
}
function mergeProjectMetadata(config2, ...configs) {
  const kExandableStringKeys = ["contents"];
  return mergeConfigsCustomized(
    (objValue, srcValue, key) => {
      if (kExandableStringKeys.includes(key) && typeof objValue === "string") {
        return srcValue;
      } else {
        return void 0;
      }
    },
    config2,
    ...configs
  );
}
function mergeConfigsCustomized(customizer, config2, ...configs) {
  config2 = cloneDeep(config2);
  configs = cloneDeep(configs);
  return mergeWith(
    config2,
    ...configs,
    (objValue, srcValue, key) => {
      const custom2 = customizer(objValue, srcValue, key);
      if (custom2 !== void 0) {
        return custom2;
      } else {
        return mergeArrayCustomizer(objValue, srcValue);
      }
    }
  );
}
function mergeDisablableArray(objValue, srcValue) {
  if (Array.isArray(objValue) && Array.isArray(srcValue)) {
    return mergeArrayCustomizer(objValue, srcValue);
  } else {
    if (srcValue === false) {
      return [];
    } else {
      const srcArr = srcValue !== void 0 ? Array.isArray(srcValue) ? srcValue : [srcValue] : [];
      const objArr = objValue !== void 0 ? Array.isArray(objValue) ? objValue : [objValue] : [];
      return mergeArrayCustomizer(objArr, srcArr);
    }
  }
}
function mergePandocVariant(objValue, srcValue) {
  if (typeof objValue === "string" && typeof srcValue === "string" && objValue !== srcValue) {
    const extensions2 = {};
    [...parsePandocVariant(objValue), ...parsePandocVariant(srcValue)].forEach((extension) => {
      extensions2[extension.name] = extension.enabled;
    });
    return Object.keys(extensions2).map(
      (name2) => `${extensions2[name2] ? "+" : "-"}${name2}`
    ).join("");
  } else {
    return void 0;
  }
}
function parsePandocVariant(variant) {
  variant = variant.split("\n").join();
  const extensions2 = [];
  const re3 = /([+-])([a-z_]+)/g;
  let match = re3.exec(variant);
  while (match) {
    extensions2.push({ name: match[2], enabled: match[1] === "+" });
    match = re3.exec(variant);
  }
  return extensions2;
}
var init_metadata = __esm({
  "config/metadata.ts"() {
    init_lodash();
    init_fs();
    init_path();
    init_log();
    init_validated_yaml2();
    init_config2();
    init_constants6();
    init_format_markdown_consts();
    init_types3();
  }
});

// core/flags.ts
function removeFlags(flags, remove) {
  let removeNext = false;
  return flags.reduce((args, arg) => {
    if (!remove.has(arg)) {
      if (!removeNext) {
        args.push(arg);
      }
      removeNext = false;
    } else {
      removeNext = remove.get(arg);
    }
    return args;
  }, new Array());
}
var init_flags = __esm({
  "core/flags.ts"() {
  }
});

// command/render/flags.ts
async function parseRenderFlags(args) {
  const flags = {};
  const argsStack = [...args];
  let arg = argsStack.shift();
  while (arg !== void 0) {
    const equalSignIndex = arg.indexOf("=");
    if (arg.startsWith("--") && equalSignIndex > 0) {
      argsStack.unshift(arg.slice(equalSignIndex + 1));
      arg = arg.slice(0, equalSignIndex);
    }
    switch (arg) {
      case "-t":
      case "--to":
        arg = argsStack.shift();
        if (arg && !arg.startsWith("-")) {
          flags.to = arg;
        }
        break;
      case "-o":
      case "--output":
        arg = argsStack.shift();
        if (!arg || arg.startsWith("-")) {
          flags.output = kStdOut;
        } else {
          if (arg.match(SEP_PATTERN)) {
            throw new Error(
              "--output option cannot specify a relative or absolute path"
            );
          }
          flags.output = arg;
        }
        break;
      case "--output-dir":
        arg = argsStack.shift();
        flags.outputDir = arg;
        break;
      case "--site-url":
        arg = argsStack.shift();
        flags.siteUrl = arg;
        break;
      case "--standalone":
        flags[kStandalone] = true;
        arg = argsStack.shift();
        break;
      case "--self-contained":
        flags[kSelfContained] = true;
        arg = argsStack.shift();
        break;
      case "--embed-resources":
        flags[kEmbedResources] = true;
        arg = argsStack.shift();
        break;
      case "--pdf-engine":
        arg = argsStack.shift();
        flags.pdfEngine = arg;
        break;
      case "--pdf-engine-opt":
        arg = argsStack.shift();
        if (arg) {
          flags.pdfEngineOpts = flags.pdfEngineOpts || [];
          flags.pdfEngineOpts.push(arg);
        }
        break;
      case "--latex-makeindex-opt":
        arg = argsStack.shift();
        if (arg) {
          flags.makeIndexOpts = flags.makeIndexOpts || [];
          flags.makeIndexOpts.push(arg);
        }
        break;
      case "--latex-tlmgr-opt":
        arg = argsStack.shift();
        if (arg) {
          flags.tlmgrOpts = flags.tlmgrOpts || [];
          flags.tlmgrOpts.push(arg);
        }
        break;
      case "--natbib":
        arg = argsStack.shift();
        flags.natbib = true;
        break;
      case "--biblatex":
        arg = argsStack.shift();
        flags.biblatex = true;
        break;
      case `--${kToc}`:
      case `--${kTableOfContents}`:
        arg = argsStack.shift();
        flags.toc = true;
        break;
      case "--listings":
        arg = argsStack.shift();
        flags[kListings] = true;
        break;
      case "--number-sections":
        arg = argsStack.shift();
        flags[kNumberSections] = true;
        break;
      case "--number-offset":
        arg = argsStack.shift();
        flags[kNumberSections] = true;
        flags[kNumberOffset] = parseNumbers("--number-offset", arg);
        break;
      case "--top-level-division":
        arg = argsStack.shift();
        flags[kTopLevelDivision] = arg;
        break;
      case "--shift-heading-level-by":
        arg = argsStack.shift();
        flags[kShiftHeadingLevelBy] = arg;
        break;
      case "--include-in-header":
      case "--include-before-body":
      case "--include-after-body": {
        const include2 = arg.replace("^--", "");
        const includeFlags = flags;
        includeFlags[include2] = includeFlags[include2] || [];
        arg = argsStack.shift();
        includeFlags[include2].push(arg);
        break;
      }
      case "--mathjax":
        flags.mathjax = true;
        arg = argsStack.shift();
        break;
      case "--katex":
        flags.katex = true;
        arg = argsStack.shift();
        break;
      case "--mathml":
        flags.mathml = true;
        arg = argsStack.shift();
        break;
      case "--gladtex":
        flags.gladtex = true;
        arg = argsStack.shift();
        break;
      case "--webtex":
        flags.webtex = true;
        arg = argsStack.shift();
        break;
      case "--execute":
        flags.execute = true;
        arg = argsStack.shift();
        break;
      case "--no-execute":
        flags.execute = false;
        arg = argsStack.shift();
        break;
      case "--execute-params":
        arg = argsStack.shift();
        flags.paramsFile = arg;
        break;
      case "--execute-dir":
        arg = argsStack.shift();
        if (arg) {
          if (isAbsolute4(arg)) {
            flags.executeDir = arg;
          } else {
            flags.executeDir = normalizePath(arg);
          }
        }
        break;
      case "--execute-daemon":
        arg = argsStack.shift();
        flags.executeDaemon = parseInt(arg, 10);
        if (isNaN(flags.executeDaemon)) {
          delete flags.executeDaemon;
        }
        break;
      case "--no-execute-daemon":
        arg = argsStack.shift();
        flags.executeDaemon = 0;
        break;
      case "--execute-daemon-restart":
        arg = argsStack.shift();
        flags.executeDaemonRestart = true;
        break;
      case "--execute-debug":
        arg = argsStack.shift();
        flags.executeDebug = true;
        break;
      case "--use-freezer":
        arg = argsStack.shift();
        flags.useFreezer = true;
        break;
      case "--cache":
        arg = argsStack.shift();
        flags.executeCache = true;
        break;
      case "--no-cache":
        arg = argsStack.shift();
        flags.executeCache = false;
        break;
      case "--cache-refresh":
        arg = argsStack.shift();
        flags.executeCache = "refresh";
        break;
      case "--clean":
        arg = argsStack.shift();
        flags.clean = true;
        break;
      case "--no-clean":
        arg = argsStack.shift();
        flags.clean = false;
        break;
      case "--debug":
        flags.debug = true;
        arg = argsStack.shift();
        break;
      case "-P":
      case "--execute-param":
        arg = argsStack.shift();
        if (arg) {
          const param = parseMetadataFlagValue(arg);
          if (param) {
            if (param.value !== void 0) {
              flags.params = flags.params || {};
              flags.params[param.name] = param.value;
            }
          }
        }
        break;
      case "-M":
      case "--metadata":
        arg = argsStack.shift();
        if (arg) {
          const metadata = parseMetadataFlagValue(arg);
          if (metadata) {
            if (metadata.value !== void 0) {
              if (isQuartoMetadata(metadata.name)) {
                flags.metadata = flags.metadata || {};
                flags.metadata[metadata.name] = metadata.value;
              } else {
                flags.pandocMetadata = flags.pandocMetadata || {};
                flags.pandocMetadata[metadata.name] = metadata.value;
              }
            }
          }
        }
        break;
      case "--metadata-file":
        arg = argsStack.shift();
        if (arg) {
          if (existsSync2(arg)) {
            const metadata = await readYamlFromString(Deno.readTextFileSync(arg));
            flags.metadata = { ...flags.metadata, ...metadata };
          }
        }
        break;
      case "--reference-location":
        arg = argsStack.shift();
        if (arg) {
          flags[kReferenceLocation] = arg;
        }
        break;
      default:
        arg = argsStack.shift();
        break;
    }
  }
  if (flags.clean === void 0) {
    flags.clean = true;
  }
  return flags;
}
function havePandocArg(pandocArgs, arg) {
  return pandocArgs.indexOf(arg) !== -1;
}
function replacePandocArg(pandocArgs, arg, value) {
  const newArgs = [...pandocArgs];
  const argIndex = pandocArgs.indexOf(arg);
  if (argIndex !== -1) {
    newArgs[argIndex + 1] = value;
  } else {
    newArgs.push(arg);
    newArgs.push(value);
  }
  return newArgs;
}
function getPandocArg(pandocArgs, arg) {
  const argIndex = pandocArgs.indexOf(arg);
  if (argIndex !== -1 && argIndex + 1 < pandocArgs.length) {
    return pandocArgs[argIndex + 1];
  } else {
    return void 0;
  }
}
function replacePandocOutputArg(pandocArgs, output) {
  if (havePandocArg(pandocArgs, "--output")) {
    return replacePandocArg(pandocArgs, "--output", output);
  } else if (havePandocArg(pandocArgs, "-o")) {
    return replacePandocArg(pandocArgs, "-o", output);
  } else {
    return pandocArgs;
  }
}
function fixupPandocArgs(pandocArgs, flags) {
  pandocArgs = pandocArgs.reduce((args, arg, index2) => {
    args.push(arg);
    if (flags.output === kStdOut && pandocArgs[index2 + 1] !== kStdOut && (arg === "-o" || arg === "--output")) {
      args.push(kStdOut);
    }
    return args;
  }, new Array());
  const removeArgs = /* @__PURE__ */ new Map();
  removeArgs.set("--output-dir", true);
  removeArgs.set("--site-url", true);
  removeArgs.set("--execute", false);
  removeArgs.set("--no-execute", false);
  removeArgs.set("-P", true);
  removeArgs.set("--execute-param", true);
  removeArgs.set("--execute-params", true);
  removeArgs.set("--execute-dir", true);
  removeArgs.set("--execute-daemon", true);
  removeArgs.set("--no-execute-daemon", false);
  removeArgs.set("--execute-daemon-restart", false);
  removeArgs.set("--execute-debug", false);
  removeArgs.set("--use-freezer", false);
  removeArgs.set("--cache", false);
  removeArgs.set("--no-cache", false);
  removeArgs.set("--cache-refresh", false);
  removeArgs.set("--clean", false);
  removeArgs.set("--no-clean", false);
  removeArgs.set("--debug", false);
  removeArgs.set("--metadata-file", true);
  removeArgs.set("--latex-makeindex-opt", true);
  removeArgs.set("--latex-tlmgr-opt", true);
  removeArgs.set("--log", true);
  removeArgs.set("--l", true);
  removeArgs.set("--log-level", true);
  removeArgs.set("--ll", true);
  removeArgs.set("--log-format", true);
  removeArgs.set("--lf", true);
  removeArgs.set("--quiet", false);
  removeArgs.set("--q", false);
  removeArgs.set("--profile", true);
  pandocArgs = removePandocArgs(pandocArgs, removeArgs);
  return removeQuartoMetadataFlags(pandocArgs);
}
function removePandocArgs(pandocArgs, removeArgs) {
  return removeFlags(pandocArgs, removeArgs);
}
function removePandocToArg(args) {
  const removeArgs = /* @__PURE__ */ new Map();
  removeArgs.set("--to", true);
  removeArgs.set("-t", true);
  return removePandocArgs(args, removeArgs);
}
function removePandocTo(renderOptions) {
  renderOptions = {
    ...renderOptions,
    flags: {
      ...renderOptions.flags || {}
    }
  };
  delete renderOptions.flags?.to;
  if (renderOptions.pandocArgs) {
    renderOptions.pandocArgs = removePandocToArg(renderOptions.pandocArgs);
  }
  return renderOptions;
}
function removeQuartoMetadataFlags(pandocArgs) {
  const args = [];
  for (let i6 = 0; i6 < pandocArgs.length; i6++) {
    const arg = pandocArgs[i6];
    if (arg === "--metadata" || arg === "-M") {
      const flagValue = parseMetadataFlagValue(pandocArgs[i6 + 1] || "");
      if (flagValue !== void 0 && (isQuartoMetadata(flagValue.name) || kQuartoForwardedMetadataFields.includes(flagValue.name))) {
        i6++;
      } else {
        args.push(arg);
      }
    } else {
      args.push(arg);
    }
  }
  return args;
}
function parseMetadataFlagValue(arg) {
  const match = arg.match(/^([^=:]+)[=:](.*)$/);
  if (match) {
    return { name: match[1], value: readYamlFromString(match[2]) };
  }
  return void 0;
}
function resolveParams(params, paramsFile) {
  if (params || paramsFile) {
    params = params || {};
    if (paramsFile) {
      params = mergeConfigs(
        readYaml(paramsFile),
        params
      );
    }
    return params;
  } else {
    return void 0;
  }
}
function parseNumbers(flag, value) {
  if (value) {
    const numbers = value.split(/,/).map((number2) => parseInt(number2.trim(), 10)).filter((number2) => !isNaN(number2));
    if (numbers.length > 0) {
      return numbers;
    }
  }
  throw new Error(
    `Invalid value for ${flag} (should be a comma separated list of numbers)`
  );
}
var kStdOut, kQuartoForwardedMetadataFields;
var init_flags2 = __esm({
  "command/render/flags.ts"() {
    init_fs();
    init_yaml();
    init_config2();
    init_constants6();
    init_metadata();
    init_path();
    init_path2();
    init_flags();
    kStdOut = "-";
    kQuartoForwardedMetadataFields = [kAuthor, kDate];
  }
});

// https://deno.land/x/deno_dom@v0.1.41/build/deno-wasm/deno-wasm.js
function getUint8Memory0() {
  if (cachegetUint8Memory0 === null || cachegetUint8Memory0.buffer !== wasm.memory.buffer) {
    cachegetUint8Memory0 = new Uint8Array(wasm.memory.buffer);
  }
  return cachegetUint8Memory0;
}
function passStringToWasm0(arg, malloc, realloc) {
  if (realloc === void 0) {
    const buf = cachedTextEncoder.encode(arg);
    const ptr2 = malloc(buf.length);
    getUint8Memory0().subarray(ptr2, ptr2 + buf.length).set(buf);
    WASM_VECTOR_LEN = buf.length;
    return ptr2;
  }
  let len = arg.length;
  let ptr = malloc(len);
  const mem = getUint8Memory0();
  let offset3 = 0;
  for (; offset3 < len; offset3++) {
    const code5 = arg.charCodeAt(offset3);
    if (code5 > 127) break;
    mem[ptr + offset3] = code5;
  }
  if (offset3 !== len) {
    if (offset3 !== 0) {
      arg = arg.slice(offset3);
    }
    ptr = realloc(ptr, len, len = offset3 + arg.length * 3);
    const view = getUint8Memory0().subarray(ptr + offset3, ptr + len);
    const ret = encodeString(arg, view);
    offset3 += ret.written;
  }
  WASM_VECTOR_LEN = offset3;
  return ptr;
}
function getInt32Memory0() {
  if (cachegetInt32Memory0 === null || cachegetInt32Memory0.buffer !== wasm.memory.buffer) {
    cachegetInt32Memory0 = new Int32Array(wasm.memory.buffer);
  }
  return cachegetInt32Memory0;
}
function getStringFromWasm0(ptr, len) {
  return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr, ptr + len));
}
function parse4(html) {
  try {
    const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
    var ptr0 = passStringToWasm0(
      html,
      wasm.__wbindgen_malloc,
      wasm.__wbindgen_realloc
    );
    var len0 = WASM_VECTOR_LEN;
    wasm.parse(retptr, ptr0, len0);
    var r0 = getInt32Memory0()[retptr / 4 + 0];
    var r1 = getInt32Memory0()[retptr / 4 + 1];
    return getStringFromWasm0(r0, r1);
  } finally {
    wasm.__wbindgen_add_to_stack_pointer(16);
    wasm.__wbindgen_free(r0, r1);
  }
}
function parse_frag(html, context_local_name) {
  try {
    const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
    var ptr0 = passStringToWasm0(
      html,
      wasm.__wbindgen_malloc,
      wasm.__wbindgen_realloc
    );
    var len0 = WASM_VECTOR_LEN;
    var ptr1 = passStringToWasm0(
      context_local_name,
      wasm.__wbindgen_malloc,
      wasm.__wbindgen_realloc
    );
    var len1 = WASM_VECTOR_LEN;
    wasm.parse_frag(retptr, ptr0, len0, ptr1, len1);
    var r0 = getInt32Memory0()[retptr / 4 + 0];
    var r1 = getInt32Memory0()[retptr / 4 + 1];
    return getStringFromWasm0(r0, r1);
  } finally {
    wasm.__wbindgen_add_to_stack_pointer(16);
    wasm.__wbindgen_free(r0, r1);
  }
}
async function load3(module2, imports2) {
  if (typeof Response === "function" && module2 instanceof Response) {
    if (typeof WebAssembly.instantiateStreaming === "function") {
      try {
        return await WebAssembly.instantiateStreaming(module2, imports2);
      } catch (e5) {
        if (module2.headers.get("Content-Type") != "application/wasm") {
          console.warn(
            "`WebAssembly.instantiateStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",
            e5
          );
        } else {
          throw e5;
        }
      }
    }
    const bytes = await module2.arrayBuffer();
    return await WebAssembly.instantiate(bytes, imports2);
  } else {
    const instance = await WebAssembly.instantiate(module2, imports2);
    if (instance instanceof WebAssembly.Instance) {
      return { instance, module: module2 };
    } else {
      return instance;
    }
  }
}
async function init(input) {
  if (typeof input === "undefined") {
    input = new URL("deno-wasm_bg.wasm", import.meta.url);
  }
  const imports2 = {};
  imports2.env = { now() {
  } };
  input = Uint8Array.from(
    atob(
      " "
    ),
    (c6) => c6.charCodeAt(0)
  );
  const { instance, module: module2 } = await load3(input, imports2);
  wasm = instance.exports;
  init.__wbindgen_wasm_module = module2;
  return wasm;
}
var wasm, WASM_VECTOR_LEN, cachegetUint8Memory0, cachedTextEncoder, encodeString, cachegetInt32Memory0, cachedTextDecoder, deno_wasm_default;
var init_deno_wasm = __esm({
  "https://deno.land/x/deno_dom@v0.1.41/build/deno-wasm/deno-wasm.js"() {
    WASM_VECTOR_LEN = 0;
    cachegetUint8Memory0 = null;
    cachedTextEncoder = new TextEncoder("utf-8");
    encodeString = typeof cachedTextEncoder.encodeInto === "function" ? function(arg, view) {
      return cachedTextEncoder.encodeInto(arg, view);
    } : function(arg, view) {
      const buf = cachedTextEncoder.encode(arg);
      view.set(buf);
      return {
        read: arg.length,
        written: buf.length
      };
    };
    cachegetInt32Memory0 = null;
    cachedTextDecoder = new TextDecoder("utf-8", {
      ignoreBOM: true,
      fatal: true
    });
    cachedTextDecoder.decode();
    deno_wasm_default = init;
  }
});

// https://deno.land/x/deno_dom@v0.1.41/src/parser.ts
function register(func, fragFunc) {
  if (parse5 !== originalParse) {
    return;
  }
  parse5 = func;
  parseFrag = fragFunc;
}
var parse5, parseFrag, originalParse;
var init_parser = __esm({
  "https://deno.land/x/deno_dom@v0.1.41/src/parser.ts"() {
    parse5 = (_html) => {
      console.error("Error: deno-dom: No parser registered");
      Deno.exit(1);
    };
    parseFrag = (_html, _contextLocalName) => {
      console.error("Error: deno-dom: No parser registered");
      Deno.exit(1);
    };
    originalParse = parse5;
  }
});

// https://deno.land/x/deno_dom@v0.1.41/src/constructor-lock.ts
var CTOR_KEY;
var init_constructor_lock = __esm({
  "https://deno.land/x/deno_dom@v0.1.41/src/constructor-lock.ts"() {
    CTOR_KEY = /* @__PURE__ */ Symbol();
  }
});

// https://deno.land/x/deno_dom@v0.1.41/src/dom/html-collection.ts
var HTMLCollectionMutatorSym, HTMLCollectionClass, HTMLCollection;
var init_html_collection = __esm({
  "https://deno.land/x/deno_dom@v0.1.41/src/dom/html-collection.ts"() {
    HTMLCollectionMutatorSym = /* @__PURE__ */ Symbol();
    HTMLCollectionClass = (() => {
      class HTMLCollection2 extends Array {
        // @ts-ignore
        forEach(cb, thisArg = void 0) {
          super.forEach(cb, thisArg);
        }
        item(index2) {
          return this[index2] ?? null;
        }
        [HTMLCollectionMutatorSym]() {
          return {
            push: Array.prototype.push.bind(this),
            splice: Array.prototype.splice.bind(this),
            indexOf: Array.prototype.indexOf.bind(this)
          };
        }
        toString() {
          return "[object HTMLCollection]";
        }
      }
      return HTMLCollection2;
    })();
    for (const staticMethod of [
      "from",
      "isArray",
      "of"
    ]) {
      HTMLCollectionClass[staticMethod] = void 0;
    }
    for (const instanceMethod of [
      "concat",
      "copyWithin",
      "every",
      "fill",
      "filter",
      "find",
      "findIndex",
      "flat",
      "flatMap",
      "includes",
      "indexOf",
      "join",
      "lastIndexOf",
      "map",
      "pop",
      "push",
      "reduce",
      "reduceRight",
      "reverse",
      "shift",
      "slice",
      "some",
      "sort",
      "splice",
      "toLocaleString",
      "unshift",
      // Unlike NodeList, HTMLCollection also doesn't implement these
      "entries",
      "forEach",
      "keys",
      "values"
    ]) {
      HTMLCollectionClass.prototype[instanceMethod] = void 0;
    }
    HTMLCollection = HTMLCollectionClass;
  }
});

// https://deno.land/x/deno_dom@v0.1.41/src/dom/node-list.ts
var nodeListMutatorSym, nodeListCachedMutator, push2, splice, slice, indexOf, filter, NodeListMutatorImpl, NodeListClass, NodeList;
var init_node_list = __esm({
  "https://deno.land/x/deno_dom@v0.1.41/src/dom/node-list.ts"() {
    init_node();
    init_html_collection();
    nodeListMutatorSym = /* @__PURE__ */ Symbol();
    nodeListCachedMutator = /* @__PURE__ */ Symbol();
    ({ push: push2, splice, slice, indexOf, filter } = Array.prototype);
    NodeListMutatorImpl = class {
      constructor(arrayInstance) {
        this.arrayInstance = arrayInstance;
      }
      // There should only ever be one elementView per element. Element views
      // are basically just the source of HTMLCollections/.children properties
      // on elements that are always in sync with their .childNodes counterpart.
      elementViews = [];
      push(...items) {
        for (const view of this.elementViews) {
          for (const item of items) {
            if (item.nodeType === Node2.ELEMENT_NODE) {
              push2.call(view, item);
            }
          }
        }
        return push2.call(this.arrayInstance, ...items);
      }
      splice(index2, deleteCount = 0, ...items) {
        for (const view of this.elementViews) {
          const toDelete = filter.call(
            slice.call(this.arrayInstance, index2, index2 + deleteCount),
            (item) => item.nodeType === Node2.ELEMENT_NODE
          );
          const toInsert = items.filter(
            (item) => item.nodeType === Node2.ELEMENT_NODE
          );
          let elementViewSpliceIndex = -1;
          for (let idx = index2; idx < this.arrayInstance.length; idx++) {
            const item = this.arrayInstance[idx];
            if (item.nodeType === Node2.ELEMENT_NODE) {
              elementViewSpliceIndex = indexOf.call(view, item);
              break;
            }
          }
          if (elementViewSpliceIndex === -1) {
            elementViewSpliceIndex = view.length;
          }
          if (toDelete.length) {
            splice.call(view, elementViewSpliceIndex, toDelete.length);
          }
          splice.call(view, elementViewSpliceIndex, 0, ...toInsert);
        }
        return splice.call(this.arrayInstance, index2, deleteCount, ...items);
      }
      indexOf(item, fromIndex = 0) {
        return indexOf.call(this.arrayInstance, item, fromIndex);
      }
      indexOfElementsView(item, fromIndex = 0) {
        return indexOf.call(this.elementsView(), item, fromIndex);
      }
      // Return the elements-only view for this NodeList. Creates one if
      // it doesn't already exist.
      elementsView() {
        let view = this.elementViews[0];
        if (!view) {
          view = new HTMLCollection();
          this.elementViews.push(view);
          push2.call(
            view,
            ...filter.call(
              this.arrayInstance,
              (item) => item.nodeType === Node2.ELEMENT_NODE
            )
          );
        }
        return view;
      }
    };
    NodeListClass = (() => {
      class NodeList2 extends Array {
        // @ts-ignore
        forEach(cb, thisArg = void 0) {
          super.forEach(cb, thisArg);
        }
        item(index2) {
          return this[index2] ?? null;
        }
        [nodeListMutatorSym]() {
          const cachedMutator = this[nodeListCachedMutator];
          if (cachedMutator) {
            return cachedMutator;
          } else {
            const cachedMutator2 = new NodeListMutatorImpl(this);
            this[nodeListCachedMutator] = cachedMutator2;
            return cachedMutator2;
          }
        }
        toString() {
          return "[object NodeList]";
        }
      }
      return NodeList2;
    })();
    for (const staticMethod of [
      "from",
      "isArray",
      "of"
    ]) {
      NodeListClass[staticMethod] = void 0;
    }
    for (const instanceMethod of [
      "concat",
      "copyWithin",
      "every",
      "fill",
      "filter",
      "find",
      "findIndex",
      "flat",
      "flatMap",
      "includes",
      "indexOf",
      "join",
      "lastIndexOf",
      "map",
      "pop",
      "push",
      "reduce",
      "reduceRight",
      "reverse",
      "shift",
      "slice",
      "some",
      "sort",
      "splice",
      "toLocaleString",
      "unshift"
    ]) {
      NodeListClass.prototype[instanceMethod] = void 0;
    }
    NodeList = NodeListClass;
  }
});

// https://deno.land/x/deno_dom@v0.1.41/src/dom/utils-types.ts
var utils_types_default;
var init_utils_types = __esm({
  "https://deno.land/x/deno_dom@v0.1.41/src/dom/utils-types.ts"() {
    utils_types_default = {
      Element: null,
      Document: null,
      DocumentFragment: null
    };
  }
});

// https://deno.land/x/deno_dom@v0.1.41/src/dom/utils.ts
function getElementsByClassName(element, className, search) {
  for (const child of element.childNodes) {
    if (child.nodeType === 1 /* ELEMENT_NODE */) {
      const classList = className.trim().split(/\s+/);
      let matchesCount = 0;
      for (const singleClassName of classList) {
        if (child.classList.contains(singleClassName)) {
          matchesCount++;
        }
      }
      if (matchesCount === classList.length) {
        search.push(child);
      }
      getElementsByClassName(child, className, search);
    }
  }
  return search;
}
function getOuterHTMLOpeningTag(parentElement) {
  return "<" + parentElement.localName + getElementAttributesString(parentElement) + ">";
}
function getOuterOrInnerHtml(parentElement, asOuterHtml) {
  let outerHTMLOpeningTag = "";
  let outerHTMLClosingTag = "";
  let innerHTML = "";
  if (asOuterHtml) {
    outerHTMLOpeningTag = getOuterHTMLOpeningTag(parentElement);
    outerHTMLClosingTag = `</${parentElement.localName}>`;
    if (voidElements.has(parentElement.localName)) {
      return outerHTMLOpeningTag;
    }
  }
  const initialChildNodes = parentElement.localName === "template" ? parentElement.content.childNodes : parentElement.childNodes;
  const childNodeDepth = [initialChildNodes];
  const indexDepth = [0];
  const closingTagDepth = [outerHTMLClosingTag];
  let depth = 0;
  depthLoop:
    while (depth > -1) {
      const child = childNodeDepth[depth][indexDepth[depth]];
      if (child) {
        switch (child.nodeType) {
          case 1 /* ELEMENT_NODE */: {
            innerHTML += getOuterHTMLOpeningTag(child);
            const childLocalName = child.localName;
            if (!voidElements.has(childLocalName)) {
              if (childLocalName === "template") {
                childNodeDepth.push(
                  child.content.childNodes
                );
              } else {
                childNodeDepth.push(child.childNodes);
              }
              indexDepth.push(0);
              closingTagDepth.push(`</${childLocalName}>`);
              depth++;
              continue depthLoop;
            }
            break;
          }
          case 8 /* COMMENT_NODE */:
            innerHTML += `<!--${child.data}-->`;
            break;
          case 3 /* TEXT_NODE */:
            switch (child.parentNode.localName) {
              case "style":
              case "script":
              case "xmp":
              case "iframe":
              case "noembed":
              case "noframes":
              case "plaintext":
                innerHTML += child.data;
                break;
              default:
                innerHTML += child.data.replace(/&/g, "&amp;").replace(/\xA0/g, "&nbsp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
                break;
            }
            break;
        }
      } else {
        depth--;
        indexDepth.pop();
        childNodeDepth.pop();
        innerHTML += closingTagDepth.pop();
      }
      indexDepth[depth]++;
    }
  return outerHTMLOpeningTag + innerHTML;
}
function getElementAttributesString(element) {
  let out = "";
  for (const attribute of element.getAttributeNames()) {
    out += ` ${attribute.toLowerCase()}`;
    out += `="${element.getAttribute(attribute).replace(/&/g, "&amp;").replace(/\xA0/g, "&nbsp;").replace(/"/g, "&quot;")}"`;
  }
  return out;
}
function insertBeforeAfter(node, nodes, before) {
  const parentNode = node.parentNode;
  const mutator = parentNode._getChildNodesMutator();
  let viablePrevNextSibling = null;
  {
    const difference2 = before ? -1 : 1;
    for (let i6 = mutator.indexOf(node) + difference2; 0 <= i6 && i6 < parentNode.childNodes.length; i6 += difference2) {
      if (!nodes.includes(parentNode.childNodes[i6])) {
        viablePrevNextSibling = parentNode.childNodes[i6];
        break;
      }
    }
  }
  nodes = nodesAndTextNodes(nodes, parentNode);
  let index2;
  if (viablePrevNextSibling) {
    index2 = mutator.indexOf(viablePrevNextSibling) + (before ? 1 : 0);
  } else {
    index2 = before ? 0 : parentNode.childNodes.length;
  }
  mutator.splice(index2, 0, ...nodes);
}
function isDocumentFragment(node) {
  let obj = node;
  if (!(obj && typeof obj === "object")) {
    return false;
  }
  while (true) {
    switch (obj.constructor) {
      case utils_types_default.DocumentFragment:
        return true;
      case Node2:
      case utils_types_default.Element:
        return false;
      // FIXME: We should probably throw here?
      case Object:
      case null:
      case void 0:
        return false;
      default:
        obj = Reflect.getPrototypeOf(obj);
    }
  }
}
function moveDocumentFragmentChildren(fragment, newParent) {
  const childCount = fragment.childNodes.length;
  for (const child of fragment.childNodes) {
    child._setParent(newParent);
  }
  const mutator = fragment._getChildNodesMutator();
  mutator.splice(0, childCount);
}
var voidElements;
var init_utils = __esm({
  "https://deno.land/x/deno_dom@v0.1.41/src/dom/utils.ts"() {
    init_node();
    init_utils_types();
    voidElements = /* @__PURE__ */ new Set([
      "area",
      "base",
      "br",
      "col",
      "embed",
      "hr",
      "img",
      "input",
      "link",
      "meta",
      "param",
      "source",
      "track",
      "wbr"
    ]);
  }
});

// https://deno.land/x/deno_dom@v0.1.41/src/dom/node.ts
var nodesAndTextNodes, Node2, CharacterData, Text2, Comment2;
var init_node = __esm({
  "https://deno.land/x/deno_dom@v0.1.41/src/dom/node.ts"() {
    init_constructor_lock();
    init_node_list();
    init_utils();
    nodesAndTextNodes = (nodes, parentNode) => {
      return nodes.flatMap((n5) => {
        if (isDocumentFragment(n5)) {
          const children = Array.from(n5.childNodes);
          moveDocumentFragmentChildren(n5, parentNode);
          return children;
        } else {
          const node = n5 instanceof Node2 ? n5 : new Text2("" + n5);
          if (n5 === node && parentNode) {
            parentNode._assertNotAncestor(node);
          }
          node._remove(true);
          node._setParent(parentNode, true);
          return [node];
        }
      });
    };
    Node2 = class _Node extends EventTarget {
      constructor(nodeName, nodeType, parentNode, key) {
        if (key !== CTOR_KEY) {
          throw new TypeError("Illegal constructor.");
        }
        super();
        this.nodeName = nodeName;
        this.nodeType = nodeType;
        this.#nodeValue = null;
        this.childNodes = new NodeList();
        this.#childNodesMutator = this.childNodes[nodeListMutatorSym]();
        this.parentElement = parentNode;
        if (parentNode) {
          parentNode.appendChild(this);
        }
      }
      #nodeValue = null;
      childNodes;
      parentNode = null;
      parentElement;
      #childNodesMutator;
      #ownerDocument = null;
      _ancestors = /* @__PURE__ */ new Set();
      // Instance constants defined after Node
      // class body below to avoid clutter
      static ELEMENT_NODE = 1 /* ELEMENT_NODE */;
      static ATTRIBUTE_NODE = 2 /* ATTRIBUTE_NODE */;
      static TEXT_NODE = 3 /* TEXT_NODE */;
      static CDATA_SECTION_NODE = 4 /* CDATA_SECTION_NODE */;
      static ENTITY_REFERENCE_NODE = 5 /* ENTITY_REFERENCE_NODE */;
      static ENTITY_NODE = 6 /* ENTITY_NODE */;
      static PROCESSING_INSTRUCTION_NODE = 7 /* PROCESSING_INSTRUCTION_NODE */;
      static COMMENT_NODE = 8 /* COMMENT_NODE */;
      static DOCUMENT_NODE = 9 /* DOCUMENT_NODE */;
      static DOCUMENT_TYPE_NODE = 10 /* DOCUMENT_TYPE_NODE */;
      static DOCUMENT_FRAGMENT_NODE = 11 /* DOCUMENT_FRAGMENT_NODE */;
      static NOTATION_NODE = 12 /* NOTATION_NODE */;
      _getChildNodesMutator() {
        return this.#childNodesMutator;
      }
      /**
       * Update ancestor chain & owner document for this child
       * and all its children.
       */
      _setParent(newParent, force = false) {
        const sameParent = this.parentNode === newParent;
        const shouldUpdateParentAndAncestors = !sameParent || force;
        if (shouldUpdateParentAndAncestors) {
          this.parentNode = newParent;
          if (newParent) {
            if (!sameParent) {
              if (newParent.nodeType === 1 /* ELEMENT_NODE */) {
                this.parentElement = newParent;
              } else {
                this.parentElement = null;
              }
              this._setOwnerDocument(newParent.#ownerDocument);
            }
            this._ancestors = new Set(newParent._ancestors);
            this._ancestors.add(newParent);
          } else {
            this.parentElement = null;
            this._ancestors.clear();
          }
          for (const child of this.childNodes) {
            child._setParent(this, shouldUpdateParentAndAncestors);
          }
        }
      }
      _assertNotAncestor(child) {
        if (child.contains(this)) {
          throw new DOMException("The new child is an ancestor of the parent");
        }
      }
      _setOwnerDocument(document2) {
        if (this.#ownerDocument !== document2) {
          this.#ownerDocument = document2;
          for (const child of this.childNodes) {
            child._setOwnerDocument(document2);
          }
        }
      }
      contains(child) {
        return child._ancestors.has(this) || child === this;
      }
      get ownerDocument() {
        return this.#ownerDocument;
      }
      get nodeValue() {
        return this.#nodeValue;
      }
      set nodeValue(value) {
      }
      get textContent() {
        let out = "";
        for (const child of this.childNodes) {
          switch (child.nodeType) {
            case 3 /* TEXT_NODE */:
              out += child.nodeValue;
              break;
            case 1 /* ELEMENT_NODE */:
              out += child.textContent;
              break;
          }
        }
        return out;
      }
      set textContent(content) {
        for (const child of this.childNodes) {
          child._setParent(null);
        }
        this._getChildNodesMutator().splice(0, this.childNodes.length);
        this.appendChild(new Text2(content));
      }
      get firstChild() {
        return this.childNodes[0] || null;
      }
      get lastChild() {
        return this.childNodes[this.childNodes.length - 1] || null;
      }
      hasChildNodes() {
        return Boolean(this.childNodes.length);
      }
      cloneNode(deep = false) {
        const copy6 = this._shallowClone();
        copy6._setOwnerDocument(this.ownerDocument);
        if (deep) {
          for (const child of this.childNodes) {
            copy6.appendChild(child.cloneNode(true));
          }
        }
        return copy6;
      }
      _shallowClone() {
        throw new Error("Illegal invocation");
      }
      _remove(skipSetParent = false) {
        const parent = this.parentNode;
        if (parent) {
          const nodeList = parent._getChildNodesMutator();
          const idx = nodeList.indexOf(this);
          nodeList.splice(idx, 1);
          if (!skipSetParent) {
            this._setParent(null);
          }
        }
      }
      appendChild(child) {
        if (isDocumentFragment(child)) {
          const mutator = this._getChildNodesMutator();
          mutator.push(...child.childNodes);
          moveDocumentFragmentChildren(child, this);
          return child;
        } else {
          return child._appendTo(this);
        }
      }
      _appendTo(parentNode) {
        parentNode._assertNotAncestor(this);
        const oldParentNode = this.parentNode;
        if (oldParentNode === parentNode) {
          if (parentNode._getChildNodesMutator().indexOf(this) !== -1) {
            return this;
          }
        } else if (oldParentNode) {
          this._remove();
        }
        this._setParent(parentNode, true);
        parentNode._getChildNodesMutator().push(this);
        return this;
      }
      removeChild(child) {
        if (child && typeof child === "object") {
          if (child.parentNode === this) {
            child._remove();
            return child;
          } else {
            throw new DOMException(
              "Node.removeChild: The node to be removed is not a child of this node"
            );
          }
        } else {
          throw new TypeError("Node.removeChild: Argument 1 is not an object.");
        }
      }
      replaceChild(newChild, oldChild) {
        if (oldChild.parentNode !== this) {
          throw new Error("Old child's parent is not the current node.");
        }
        oldChild._replaceWith(newChild);
        return oldChild;
      }
      insertBefore(newNode, refNode) {
        this._assertNotAncestor(newNode);
        const mutator = this._getChildNodesMutator();
        if (refNode === null) {
          this.appendChild(newNode);
          return newNode;
        }
        const index2 = mutator.indexOf(refNode);
        if (index2 === -1) {
          throw new Error(
            "DOMException: Child to insert before is not a child of this node"
          );
        }
        if (isDocumentFragment(newNode)) {
          mutator.splice(index2, 0, ...newNode.childNodes);
          moveDocumentFragmentChildren(newNode, this);
        } else {
          const oldParentNode = newNode.parentNode;
          const oldMutator = oldParentNode?._getChildNodesMutator();
          if (oldMutator) {
            oldMutator.splice(oldMutator.indexOf(newNode), 1);
          }
          newNode._setParent(this, oldParentNode !== this);
          mutator.splice(index2, 0, newNode);
        }
        return newNode;
      }
      _replaceWith(...nodes) {
        if (this.parentNode) {
          const parentNode = this.parentNode;
          const mutator = parentNode._getChildNodesMutator();
          let viableNextSibling = null;
          {
            const thisIndex = mutator.indexOf(this);
            for (let i6 = thisIndex + 1; i6 < parentNode.childNodes.length; i6++) {
              if (!nodes.includes(parentNode.childNodes[i6])) {
                viableNextSibling = parentNode.childNodes[i6];
                break;
              }
            }
          }
          nodes = nodesAndTextNodes(nodes, parentNode);
          let index2 = viableNextSibling ? mutator.indexOf(viableNextSibling) : parentNode.childNodes.length;
          let deleteNumber;
          if (parentNode.childNodes[index2 - 1] === this) {
            index2--;
            deleteNumber = 1;
          } else {
            deleteNumber = 0;
          }
          mutator.splice(index2, deleteNumber, ...nodes);
          this._setParent(null);
        }
      }
      get nextSibling() {
        const parent = this.parentNode;
        if (!parent) {
          return null;
        }
        const index2 = parent._getChildNodesMutator().indexOf(this);
        const next = parent.childNodes[index2 + 1] || null;
        return next;
      }
      get previousSibling() {
        const parent = this.parentNode;
        if (!parent) {
          return null;
        }
        const index2 = parent._getChildNodesMutator().indexOf(this);
        const prev = parent.childNodes[index2 - 1] || null;
        return prev;
      }
      // Node.compareDocumentPosition()'s bitmask values
      static DOCUMENT_POSITION_DISCONNECTED = 1;
      static DOCUMENT_POSITION_PRECEDING = 2;
      static DOCUMENT_POSITION_FOLLOWING = 4;
      static DOCUMENT_POSITION_CONTAINS = 8;
      static DOCUMENT_POSITION_CONTAINED_BY = 16;
      static DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC = 32;
      /**
       * FIXME: Does not implement attribute node checks
       * ref: https://dom.spec.whatwg.org/#dom-node-comparedocumentposition
       * MDN: https://developer.mozilla.org/en-US/docs/Web/API/Node/compareDocumentPosition
       */
      compareDocumentPosition(other) {
        if (other === this) {
          return 0;
        }
        if (!(other instanceof _Node)) {
          throw new TypeError(
            "Node.compareDocumentPosition: Argument 1 does not implement interface Node."
          );
        }
        let node1Root = other;
        let node2Root = this;
        const node1Hierarchy = [node1Root];
        const node2Hierarchy = [node2Root];
        while (node1Root.parentNode ?? node2Root.parentNode) {
          node1Root = node1Root.parentNode ? (node1Hierarchy.push(node1Root.parentNode), node1Root.parentNode) : node1Root;
          node2Root = node2Root.parentNode ? (node2Hierarchy.push(node2Root.parentNode), node2Root.parentNode) : node2Root;
        }
        if (node1Root !== node2Root) {
          return _Node.DOCUMENT_POSITION_DISCONNECTED | _Node.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC | _Node.DOCUMENT_POSITION_PRECEDING;
        }
        const longerHierarchy = node1Hierarchy.length > node2Hierarchy.length ? node1Hierarchy : node2Hierarchy;
        const shorterHierarchy = longerHierarchy === node1Hierarchy ? node2Hierarchy : node1Hierarchy;
        if (longerHierarchy[longerHierarchy.length - shorterHierarchy.length] === shorterHierarchy[0]) {
          return longerHierarchy === node1Hierarchy ? _Node.DOCUMENT_POSITION_CONTAINED_BY | _Node.DOCUMENT_POSITION_FOLLOWING : _Node.DOCUMENT_POSITION_CONTAINS | _Node.DOCUMENT_POSITION_PRECEDING;
        }
        const longerStart = longerHierarchy.length - shorterHierarchy.length;
        for (let i6 = shorterHierarchy.length - 1; i6 >= 0; i6--) {
          const shorterHierarchyNode = shorterHierarchy[i6];
          const longerHierarchyNode = longerHierarchy[longerStart + i6];
          if (longerHierarchyNode !== shorterHierarchyNode) {
            const siblings2 = shorterHierarchyNode.parentNode._getChildNodesMutator();
            if (siblings2.indexOf(shorterHierarchyNode) < siblings2.indexOf(longerHierarchyNode)) {
              if (shorterHierarchy === node1Hierarchy) {
                return _Node.DOCUMENT_POSITION_PRECEDING;
              } else {
                return _Node.DOCUMENT_POSITION_FOLLOWING;
              }
            } else {
              if (longerHierarchy === node1Hierarchy) {
                return _Node.DOCUMENT_POSITION_PRECEDING;
              } else {
                return _Node.DOCUMENT_POSITION_FOLLOWING;
              }
            }
          }
        }
        return _Node.DOCUMENT_POSITION_FOLLOWING;
      }
      getRootNode(opts = {}) {
        if (this.parentNode) {
          return this.parentNode.getRootNode(opts);
        }
        if (opts.composed && this.host) {
          return this.host.getRootNode(opts);
        }
        return this;
      }
    };
    Node2.prototype.ELEMENT_NODE = 1 /* ELEMENT_NODE */;
    Node2.prototype.ATTRIBUTE_NODE = 2 /* ATTRIBUTE_NODE */;
    Node2.prototype.TEXT_NODE = 3 /* TEXT_NODE */;
    Node2.prototype.CDATA_SECTION_NODE = 4 /* CDATA_SECTION_NODE */;
    Node2.prototype.ENTITY_REFERENCE_NODE = 5 /* ENTITY_REFERENCE_NODE */;
    Node2.prototype.ENTITY_NODE = 6 /* ENTITY_NODE */;
    Node2.prototype.PROCESSING_INSTRUCTION_NODE = 7 /* PROCESSING_INSTRUCTION_NODE */;
    Node2.prototype.COMMENT_NODE = 8 /* COMMENT_NODE */;
    Node2.prototype.DOCUMENT_NODE = 9 /* DOCUMENT_NODE */;
    Node2.prototype.DOCUMENT_TYPE_NODE = 10 /* DOCUMENT_TYPE_NODE */;
    Node2.prototype.DOCUMENT_FRAGMENT_NODE = 11 /* DOCUMENT_FRAGMENT_NODE */;
    Node2.prototype.NOTATION_NODE = 12 /* NOTATION_NODE */;
    CharacterData = class extends Node2 {
      #nodeValue = "";
      constructor(data3, nodeName, nodeType, parentNode, key) {
        super(
          nodeName,
          nodeType,
          parentNode,
          key
        );
        this.#nodeValue = data3;
      }
      get nodeValue() {
        return this.#nodeValue;
      }
      set nodeValue(value) {
        this.#nodeValue = String(value ?? "");
      }
      get data() {
        return this.#nodeValue;
      }
      set data(value) {
        this.nodeValue = value;
      }
      get textContent() {
        return this.#nodeValue;
      }
      set textContent(value) {
        this.nodeValue = value;
      }
      get length() {
        return this.data.length;
      }
      before(...nodes) {
        if (this.parentNode) {
          insertBeforeAfter(this, nodes, true);
        }
      }
      after(...nodes) {
        if (this.parentNode) {
          insertBeforeAfter(this, nodes, false);
        }
      }
      remove() {
        this._remove();
      }
      replaceWith(...nodes) {
        this._replaceWith(...nodes);
      }
      // TODO: Implement NonDocumentTypeChildNode.nextElementSibling, etc
      // ref: https://developer.mozilla.org/en-US/docs/Web/API/CharacterData
    };
    Text2 = class _Text extends CharacterData {
      constructor(text = "") {
        super(
          String(text),
          "#text",
          3 /* TEXT_NODE */,
          null,
          CTOR_KEY
        );
      }
      _shallowClone() {
        return new _Text(this.textContent);
      }
      get textContent() {
        return this.nodeValue;
      }
    };
    Comment2 = class _Comment extends CharacterData {
      constructor(text = "") {
        super(
          String(text),
          "#comment",
          8 /* COMMENT_NODE */,
          null,
          CTOR_KEY
        );
      }
      _shallowClone() {
        return new _Comment(this.textContent);
      }
      get textContent() {
        return this.nodeValue;
      }
    };
  }
});

// https://deno.land/x/deno_dom@v0.1.41/src/dom/element.ts
var DOMTokenList, setNamedNodeMapOwnerElementSym, setAttrValueSym, Attr, setNamedNodeMapValueSym, getNamedNodeMapValueSym, getNamedNodeMapAttrNamesSym, getNamedNodeMapAttrNodeSym, removeNamedNodeMapAttrSym, NamedNodeMap, Element2;
var init_element = __esm({
  "https://deno.land/x/deno_dom@v0.1.41/src/dom/element.ts"() {
    init_constructor_lock();
    init_deserialize();
    init_node();
    init_node_list();
    init_utils();
    init_utils_types();
    DOMTokenList = class _DOMTokenList {
      #_value = "";
      get #value() {
        return this.#_value;
      }
      set #value(value) {
        this.#_value = value;
        this.#onChange(value);
      }
      #set = /* @__PURE__ */ new Set();
      #onChange;
      constructor(onChange, key) {
        if (key !== CTOR_KEY) {
          throw new TypeError("Illegal constructor");
        }
        this.#onChange = onChange;
      }
      static #invalidToken(token) {
        return token === "" || /[\t\n\f\r ]/.test(token);
      }
      #setIndices() {
        const classes = Array.from(this.#set);
        for (let i6 = 0; i6 < classes.length; i6++) {
          this[i6] = classes[i6];
        }
      }
      set value(input) {
        this.#value = input;
        this.#set = new Set(
          input.trim().split(/[\t\n\f\r\s]+/g).filter(Boolean)
        );
        this.#setIndices();
      }
      get value() {
        return this.#_value;
      }
      get length() {
        return this.#set.size;
      }
      *entries() {
        const array = Array.from(this.#set);
        for (let i6 = 0; i6 < array.length; i6++) {
          yield [i6, array[i6]];
        }
      }
      *values() {
        yield* this.#set.values();
      }
      *keys() {
        for (let i6 = 0; i6 < this.#set.size; i6++) {
          yield i6;
        }
      }
      *[Symbol.iterator]() {
        yield* this.#set.values();
      }
      item(index2) {
        index2 = Number(index2);
        if (Number.isNaN(index2) || index2 === Infinity) index2 = 0;
        return this[Math.trunc(index2) % 2 ** 32] ?? null;
      }
      contains(element) {
        return this.#set.has(element);
      }
      add(...elements) {
        for (const element of elements) {
          if (_DOMTokenList.#invalidToken(element)) {
            throw new DOMException(
              "Failed to execute 'add' on 'DOMTokenList': The token provided must not be empty."
            );
          }
          const { size } = this.#set;
          this.#set.add(element);
          if (size < this.#set.size) {
            this[size] = element;
          }
        }
        this.#updateClassString();
      }
      remove(...elements) {
        const { size } = this.#set;
        for (const element of elements) {
          if (_DOMTokenList.#invalidToken(element)) {
            throw new DOMException(
              "Failed to execute 'remove' on 'DOMTokenList': The token provided must not be empty."
            );
          }
          this.#set.delete(element);
        }
        if (size !== this.#set.size) {
          for (let i6 = this.#set.size; i6 < size; i6++) {
            delete this[i6];
          }
          this.#setIndices();
        }
        this.#updateClassString();
      }
      replace(oldToken, newToken) {
        if ([oldToken, newToken].some((v4) => _DOMTokenList.#invalidToken(v4))) {
          throw new DOMException(
            "Failed to execute 'replace' on 'DOMTokenList': The token provided must not be empty."
          );
        }
        if (!this.#set.has(oldToken)) {
          return false;
        }
        if (this.#set.has(newToken)) {
          this.remove(oldToken);
        } else {
          this.#set.delete(oldToken);
          this.#set.add(newToken);
          this.#setIndices();
          this.#updateClassString();
        }
        return true;
      }
      supports() {
        throw new Error("Not implemented");
      }
      toggle(element, force) {
        if (force !== void 0) {
          const operation = force ? "add" : "remove";
          this[operation](element);
          return false;
        } else {
          const contains = this.contains(element);
          const operation = contains ? "remove" : "add";
          this[operation](element);
          return !contains;
        }
      }
      forEach(callback) {
        for (const [i6, value] of this.entries()) {
          callback(value, i6, this);
        }
      }
      #updateClassString() {
        this.#value = Array.from(this.#set).join(" ");
      }
    };
    setNamedNodeMapOwnerElementSym = /* @__PURE__ */ Symbol();
    setAttrValueSym = /* @__PURE__ */ Symbol();
    Attr = class _Attr extends Node2 {
      #namedNodeMap = null;
      #name = "";
      #value = "";
      #ownerElement = null;
      constructor(map3, name2, value, key) {
        if (key !== CTOR_KEY) {
          throw new TypeError("Illegal constructor");
        }
        super(name2, 2 /* ATTRIBUTE_NODE */, null, CTOR_KEY);
        this.#name = name2;
        this.#value = value;
        this.#namedNodeMap = map3;
      }
      [setNamedNodeMapOwnerElementSym](ownerElement) {
        this.#ownerElement = ownerElement;
        this.#namedNodeMap = ownerElement?.attributes ?? null;
        if (ownerElement) {
          this._setOwnerDocument(ownerElement.ownerDocument);
        }
      }
      [setAttrValueSym](value) {
        this.#value = value;
      }
      _shallowClone() {
        const newAttr = new _Attr(null, this.#name, this.#value, CTOR_KEY);
        newAttr._setOwnerDocument(this.ownerDocument);
        return newAttr;
      }
      cloneNode() {
        return super.cloneNode();
      }
      appendChild() {
        throw new DOMException("Cannot add children to an Attribute");
      }
      replaceChild() {
        throw new DOMException("Cannot add children to an Attribute");
      }
      insertBefore() {
        throw new DOMException("Cannot add children to an Attribute");
      }
      removeChild() {
        throw new DOMException(
          "The node to be removed is not a child of this node"
        );
      }
      get name() {
        return this.#name;
      }
      get localName() {
        return this.#name;
      }
      get value() {
        return this.#value;
      }
      set value(value) {
        this.#value = String(value);
        if (this.#namedNodeMap) {
          this.#namedNodeMap[setNamedNodeMapValueSym](
            this.#name,
            this.#value,
            true
          );
        }
      }
      get ownerElement() {
        return this.#ownerElement ?? null;
      }
      get specified() {
        return true;
      }
      // TODO
      get prefix() {
        return null;
      }
    };
    setNamedNodeMapValueSym = /* @__PURE__ */ Symbol();
    getNamedNodeMapValueSym = /* @__PURE__ */ Symbol();
    getNamedNodeMapAttrNamesSym = /* @__PURE__ */ Symbol();
    getNamedNodeMapAttrNodeSym = /* @__PURE__ */ Symbol();
    removeNamedNodeMapAttrSym = /* @__PURE__ */ Symbol();
    NamedNodeMap = class _NamedNodeMap {
      static #indexedAttrAccess = function(map3, index2) {
        if (index2 + 1 > this.length) {
          return void 0;
        }
        const attribute = Object.keys(map3).filter((attribute2) => map3[attribute2] !== void 0)[index2]?.slice(1);
        return this[getNamedNodeMapAttrNodeSym](attribute);
      };
      #onAttrNodeChange;
      constructor(ownerElement, onAttrNodeChange, key) {
        if (key !== CTOR_KEY) {
          throw new TypeError("Illegal constructor.");
        }
        this.#ownerElement = ownerElement;
        this.#onAttrNodeChange = onAttrNodeChange;
      }
      #attrNodeCache = {};
      #map = {};
      #length = 0;
      #capacity = 0;
      #ownerElement = null;
      [getNamedNodeMapAttrNodeSym](attribute) {
        const safeAttrName = "a" + attribute;
        let attrNode = this.#attrNodeCache[safeAttrName];
        if (!attrNode) {
          attrNode = this.#attrNodeCache[safeAttrName] = new Attr(
            this,
            attribute,
            this.#map[safeAttrName],
            CTOR_KEY
          );
          attrNode[setNamedNodeMapOwnerElementSym](this.#ownerElement);
        }
        return attrNode;
      }
      [getNamedNodeMapAttrNamesSym]() {
        const names = [];
        for (const [name2, value] of Object.entries(this.#map)) {
          if (value !== void 0) {
            names.push(name2.slice(1));
          }
        }
        return names;
      }
      [getNamedNodeMapValueSym](attribute) {
        const safeAttrName = "a" + attribute;
        return this.#map[safeAttrName];
      }
      [setNamedNodeMapValueSym](attribute, value, bubble = false) {
        const safeAttrName = "a" + attribute;
        if (this.#map[safeAttrName] === void 0) {
          this.#length++;
          if (this.#length > this.#capacity) {
            this.#capacity = this.#length;
            const index2 = this.#capacity - 1;
            Object.defineProperty(this, String(this.#capacity - 1), {
              get: _NamedNodeMap.#indexedAttrAccess.bind(this, this.#map, index2)
            });
          }
        } else if (this.#attrNodeCache[safeAttrName]) {
          this.#attrNodeCache[safeAttrName][setAttrValueSym](value);
        }
        this.#map[safeAttrName] = value;
        if (bubble) {
          this.#onAttrNodeChange(attribute, value);
        }
      }
      /**
       * Called when an attribute is removed from
       * an element
       */
      [removeNamedNodeMapAttrSym](attribute) {
        const safeAttrName = "a" + attribute;
        if (this.#map[safeAttrName] !== void 0) {
          this.#length--;
          this.#map[safeAttrName] = void 0;
          this.#onAttrNodeChange(attribute, null);
          const attrNode = this.#attrNodeCache[safeAttrName];
          if (attrNode) {
            attrNode[setNamedNodeMapOwnerElementSym](null);
            this.#attrNodeCache[safeAttrName] = void 0;
          }
        }
      }
      *[Symbol.iterator]() {
        for (let i6 = 0; i6 < this.length; i6++) {
          yield this[i6];
        }
      }
      get length() {
        return this.#length;
      }
      // FIXME: This method should accept anything and basically
      // coerce any non numbers (and Infinity/-Infinity) into 0
      item(index2) {
        if (index2 >= this.#length) {
          return null;
        }
        return this[index2];
      }
      getNamedItem(attribute) {
        const safeAttrName = "a" + attribute;
        if (this.#map[safeAttrName] !== void 0) {
          return this[getNamedNodeMapAttrNodeSym](attribute);
        }
        return null;
      }
      setNamedItem(attrNode) {
        if (attrNode.ownerElement) {
          throw new DOMException("Attribute already in use");
        }
        const safeAttrName = "a" + attrNode.name;
        const previousAttr = this.#attrNodeCache[safeAttrName];
        if (previousAttr) {
          previousAttr[setNamedNodeMapOwnerElementSym](null);
          this.#map[safeAttrName] = void 0;
        }
        attrNode[setNamedNodeMapOwnerElementSym](this.#ownerElement);
        this.#attrNodeCache[safeAttrName] = attrNode;
        this[setNamedNodeMapValueSym](attrNode.name, attrNode.value, true);
      }
      removeNamedItem(attribute) {
        const safeAttrName = "a" + attribute;
        if (this.#map[safeAttrName] !== void 0) {
          const attrNode = this[getNamedNodeMapAttrNodeSym](attribute);
          this[removeNamedNodeMapAttrSym](attribute);
          return attrNode;
        }
        throw new DOMException("Node was not found");
      }
    };
    Element2 = class _Element extends Node2 {
      constructor(tagName, parentNode, attributes, key) {
        super(
          tagName,
          1 /* ELEMENT_NODE */,
          parentNode,
          key
        );
        this.tagName = tagName;
        for (const attr of attributes) {
          this.setAttribute(attr[0], attr[1]);
          switch (attr[0]) {
            case "class":
              this.#classList.value = attr[1];
              break;
            case "id":
              this.#currentId = attr[1];
              break;
          }
        }
        this.tagName = this.nodeName = tagName.toUpperCase();
        this.localName = tagName.toLowerCase();
      }
      localName;
      attributes = new NamedNodeMap(this, (attribute, value) => {
        if (value === null) {
          value = "";
        }
        switch (attribute) {
          case "class":
            this.#classList.value = value;
            break;
          case "id":
            this.#currentId = value;
            break;
        }
      }, CTOR_KEY);
      #currentId = "";
      #classList = new DOMTokenList(
        (className) => {
          if (this.hasAttribute("class") || className !== "") {
            this.attributes[setNamedNodeMapValueSym]("class", className);
          }
        },
        CTOR_KEY
      );
      _shallowClone() {
        const attributes = [];
        for (const attribute of this.getAttributeNames()) {
          attributes.push([attribute, this.getAttribute(attribute)]);
        }
        return new _Element(this.nodeName, null, attributes, CTOR_KEY);
      }
      get childElementCount() {
        return this._getChildNodesMutator().elementsView().length;
      }
      get className() {
        return this.getAttribute("class") ?? "";
      }
      set className(className) {
        this.setAttribute("class", className);
        this.#classList.value = className;
      }
      get classList() {
        return this.#classList;
      }
      get outerHTML() {
        return getOuterOrInnerHtml(this, true);
      }
      set outerHTML(html) {
      }
      get innerHTML() {
        return getOuterOrInnerHtml(this, false);
      }
      set innerHTML(html) {
        for (const child of this.childNodes) {
          child._setParent(null);
        }
        const mutator = this._getChildNodesMutator();
        mutator.splice(0, this.childNodes.length);
        if (html.length) {
          const parsed = fragmentNodesFromString(html, this.localName);
          for (const child of parsed.childNodes[0].childNodes) {
            mutator.push(child);
          }
          for (const child of this.childNodes) {
            child._setParent(this);
            child._setOwnerDocument(this.ownerDocument);
          }
        }
      }
      get innerText() {
        return this.textContent;
      }
      set innerText(text) {
        this.textContent = text;
      }
      get children() {
        return this._getChildNodesMutator().elementsView();
      }
      get id() {
        return this.#currentId || "";
      }
      set id(id) {
        this.setAttribute("id", this.#currentId = id);
      }
      getAttributeNames() {
        return this.attributes[getNamedNodeMapAttrNamesSym]();
      }
      getAttribute(name2) {
        return this.attributes[getNamedNodeMapValueSym](name2.toLowerCase()) ?? null;
      }
      setAttribute(rawName, value) {
        const name2 = String(rawName?.toLowerCase());
        const strValue = String(value);
        this.attributes[setNamedNodeMapValueSym](name2, strValue);
        if (name2 === "id") {
          this.#currentId = strValue;
        } else if (name2 === "class") {
          this.#classList.value = strValue;
        }
      }
      removeAttribute(rawName) {
        const name2 = String(rawName?.toLowerCase());
        this.attributes[removeNamedNodeMapAttrSym](name2);
        if (name2 === "class") {
          this.#classList.value = "";
        }
      }
      hasAttribute(name2) {
        return this.attributes[getNamedNodeMapValueSym](
          String(name2?.toLowerCase())
        ) !== void 0;
      }
      hasAttributeNS(_namespace, name2) {
        return this.attributes[getNamedNodeMapValueSym](
          String(name2?.toLowerCase())
        ) !== void 0;
      }
      replaceWith(...nodes) {
        this._replaceWith(...nodes);
      }
      remove() {
        this._remove();
      }
      append(...nodes) {
        const mutator = this._getChildNodesMutator();
        mutator.push(...nodesAndTextNodes(nodes, this));
      }
      prepend(...nodes) {
        const mutator = this._getChildNodesMutator();
        mutator.splice(0, 0, ...nodesAndTextNodes(nodes, this));
      }
      before(...nodes) {
        if (this.parentNode) {
          insertBeforeAfter(this, nodes, true);
        }
      }
      after(...nodes) {
        if (this.parentNode) {
          insertBeforeAfter(this, nodes, false);
        }
      }
      get firstElementChild() {
        const elements = this._getChildNodesMutator().elementsView();
        return elements[0] ?? null;
      }
      get lastElementChild() {
        const elements = this._getChildNodesMutator().elementsView();
        return elements[elements.length - 1] ?? null;
      }
      get nextElementSibling() {
        const parent = this.parentNode;
        if (!parent) {
          return null;
        }
        const mutator = parent._getChildNodesMutator();
        const index2 = mutator.indexOfElementsView(this);
        const elements = mutator.elementsView();
        return elements[index2 + 1] ?? null;
      }
      get previousElementSibling() {
        const parent = this.parentNode;
        if (!parent) {
          return null;
        }
        const mutator = parent._getChildNodesMutator();
        const index2 = mutator.indexOfElementsView(this);
        const elements = mutator.elementsView();
        return elements[index2 - 1] ?? null;
      }
      querySelector(selectors) {
        if (!this.ownerDocument) {
          throw new Error("Element must have an owner document");
        }
        return this.ownerDocument._nwapi.first(selectors, this);
      }
      querySelectorAll(selectors) {
        if (!this.ownerDocument) {
          throw new Error("Element must have an owner document");
        }
        const nodeList = new NodeList();
        const mutator = nodeList[nodeListMutatorSym]();
        for (const match of this.ownerDocument._nwapi.select(selectors, this)) {
          mutator.push(match);
        }
        return nodeList;
      }
      matches(selectorString) {
        return this.ownerDocument._nwapi.match(selectorString, this);
      }
      closest(selectorString) {
        const { match } = this.ownerDocument._nwapi;
        let el = this;
        do {
          if (match(selectorString, el)) {
            return el;
          }
          el = el.parentElement;
        } while (el !== null);
        return null;
      }
      // TODO: DRY!!!
      getElementById(id) {
        for (const child of this.childNodes) {
          if (child.nodeType === 1 /* ELEMENT_NODE */) {
            if (child.id === id) {
              return child;
            }
            const search = child.getElementById(id);
            if (search) {
              return search;
            }
          }
        }
        return null;
      }
      getElementsByTagName(tagName) {
        const fixCaseTagName = tagName.toUpperCase();
        if (fixCaseTagName === "*") {
          return this._getElementsByTagNameWildcard([]);
        } else {
          return this._getElementsByTagName(tagName.toUpperCase(), []);
        }
      }
      _getElementsByTagNameWildcard(search) {
        for (const child of this.childNodes) {
          if (child.nodeType === 1 /* ELEMENT_NODE */) {
            search.push(child);
            child._getElementsByTagNameWildcard(search);
          }
        }
        return search;
      }
      _getElementsByTagName(tagName, search) {
        for (const child of this.childNodes) {
          if (child.nodeType === 1 /* ELEMENT_NODE */) {
            if (child.tagName === tagName) {
              search.push(child);
            }
            child._getElementsByTagName(tagName, search);
          }
        }
        return search;
      }
      getElementsByClassName(className) {
        return getElementsByClassName(this, className, []);
      }
      getElementsByTagNameNS(_namespace, localName) {
        return this.getElementsByTagName(localName);
      }
    };
    utils_types_default.Element = Element2;
  }
});

// https://deno.land/x/deno_dom@v0.1.41/src/dom/selectors/custom-api.ts
var customByTagNameSym, customByClassNameSym;
var init_custom_api = __esm({
  "https://deno.land/x/deno_dom@v0.1.41/src/dom/selectors/custom-api.ts"() {
    customByTagNameSym = /* @__PURE__ */ Symbol();
    customByClassNameSym = /* @__PURE__ */ Symbol();
  }
});

// https://deno.land/x/deno_dom@v0.1.41/src/dom/document-fragment.ts
function documentFragmentGetElementsByTagName(tagName) {
  const search = [];
  if (tagName === "*") {
    return documentFragmentGetElementsByTagNameWildcard(this, search);
  }
  for (const child of this.childNodes) {
    if (child.nodeType === 1 /* ELEMENT_NODE */) {
      if (child.tagName === tagName) {
        search.push(child);
      }
      child._getElementsByTagName(tagName, search);
    }
  }
  return search;
}
function documentFragmentGetElementsByClassName(className) {
  return getElementsByClassName(this, className, []);
}
function documentFragmentGetElementsByTagNameWildcard(fragment, search) {
  for (const child of fragment.childNodes) {
    if (child.nodeType === 1 /* ELEMENT_NODE */) {
      search.push(child);
      child._getElementsByTagNameWildcard(search);
    }
  }
  return search;
}
var DocumentFragment2;
var init_document_fragment = __esm({
  "https://deno.land/x/deno_dom@v0.1.41/src/dom/document-fragment.ts"() {
    init_constructor_lock();
    init_node_list();
    init_node();
    init_custom_api();
    init_utils();
    init_utils_types();
    DocumentFragment2 = class _DocumentFragment extends Node2 {
      constructor() {
        super(
          "#document-fragment",
          11 /* DOCUMENT_FRAGMENT_NODE */,
          null,
          CTOR_KEY
        );
      }
      get childElementCount() {
        return this._getChildNodesMutator().elementsView().length;
      }
      get children() {
        return this._getChildNodesMutator().elementsView();
      }
      get firstElementChild() {
        const elements = this._getChildNodesMutator().elementsView();
        return elements[0] ?? null;
      }
      get lastElementChild() {
        const elements = this._getChildNodesMutator().elementsView();
        return elements[elements.length - 1] ?? null;
      }
      _shallowClone() {
        return new _DocumentFragment();
      }
      append(...nodes) {
        const mutator = this._getChildNodesMutator();
        mutator.push(...nodesAndTextNodes(nodes, this));
      }
      prepend(...nodes) {
        const mutator = this._getChildNodesMutator();
        mutator.splice(0, 0, ...nodesAndTextNodes(nodes, this));
      }
      replaceChildren(...nodes) {
        const mutator = this._getChildNodesMutator();
        for (const child of this.childNodes) {
          child._setParent(null);
        }
        mutator.splice(0, this.childNodes.length);
        mutator.splice(0, 0, ...nodesAndTextNodes(nodes, this));
      }
      // TODO: DRY!!!
      getElementById(id) {
        for (const child of this.childNodes) {
          if (child.nodeType === 1 /* ELEMENT_NODE */) {
            if (child.id === id) {
              return child;
            }
            const search = child.getElementById(id);
            if (search) {
              return search;
            }
          }
        }
        return null;
      }
      querySelector(selectors) {
        if (!this.ownerDocument) {
          throw new Error("DocumentFragment must have an owner document");
        }
        return this.ownerDocument._nwapi.first(selectors, this);
      }
      querySelectorAll(selectors) {
        if (!this.ownerDocument) {
          throw new Error("DocumentFragment must have an owner document");
        }
        const nodeList = new NodeList();
        const mutator = nodeList[nodeListMutatorSym]();
        mutator.push(
          ...this.ownerDocument._nwapi.select(selectors, this)
        );
        return nodeList;
      }
    };
    utils_types_default.DocumentFragment = DocumentFragment2;
    DocumentFragment2.prototype[customByTagNameSym] = documentFragmentGetElementsByTagName;
    DocumentFragment2.prototype[customByClassNameSym] = documentFragmentGetElementsByClassName;
  }
});

// https://deno.land/x/deno_dom@v0.1.41/src/dom/elements/html-template-element.ts
var HTMLTemplateElement;
var init_html_template_element = __esm({
  "https://deno.land/x/deno_dom@v0.1.41/src/dom/elements/html-template-element.ts"() {
    init_element();
    init_document_fragment();
    init_utils();
    init_deserialize();
    init_constructor_lock();
    HTMLTemplateElement = class _HTMLTemplateElement extends Element2 {
      /**
       * This blocks access to the .#contents property when the
       * super() constructor is running which invokes (our
       * overridden) _setParent() method. Without it, we get
       * the following error thrown:
       *
       *   TypeError: Cannot read private member #content from
       *   an object whose class did not declare it
       *
       * FIXME: Maybe find a cleaner way to do this
       */
      __contentIsSet = false;
      #content = null;
      constructor(parentNode, attributes, key, content) {
        super(
          "TEMPLATE",
          parentNode,
          attributes,
          key
        );
        this.#content = content;
        this.__contentIsSet = true;
      }
      get content() {
        return this.#content;
      }
      _setOwnerDocument(document2) {
        super._setOwnerDocument(document2);
        if (this.__contentIsSet) {
          this.content._setOwnerDocument(document2);
        }
      }
      _shallowClone() {
        const frag = new DocumentFragment2();
        const attributes = this.getAttributeNames().map((name2) => [name2, this.getAttribute(name2)]);
        return new _HTMLTemplateElement(null, attributes, CTOR_KEY, frag);
      }
      cloneNode(deep = false) {
        const newNode = super.cloneNode(deep);
        if (deep) {
          const destContent = newNode.content;
          for (const child of this.content.childNodes) {
            destContent.appendChild(child.cloneNode(deep));
          }
        }
        return newNode;
      }
      get innerHTML() {
        return getOuterOrInnerHtml(this, false);
      }
      // Replace children in the `.content`
      set innerHTML(html) {
        const content = this.content;
        for (const child of content.childNodes) {
          child._setParent(null);
        }
        const mutator = content._getChildNodesMutator();
        mutator.splice(0, content.childNodes.length);
        if (html.length) {
          const parsed = fragmentNodesFromString(html, this.localName);
          mutator.push(...parsed.childNodes[0].childNodes);
          for (const child of content.childNodes) {
            child._setParent(content);
            child._setOwnerDocument(content.ownerDocument);
          }
        }
      }
      get outerHTML() {
        return `<template${getElementAttributesString(this)}>${this.innerHTML}</template>`;
      }
    };
  }
});

// https://deno.land/x/deno_dom@v0.1.41/src/dom/selectors/nwsapi.js
function Factory(global2, Export) {
  var version4 = "nwsapi-2.2.0", doc = global2.document, root = doc.documentElement, slice2 = Array.prototype.slice, WSP = "[\\x20\\t\\r\\n\\f]", CFG = {
    // extensions
    operators: "[~*^$|]=|=",
    combinators: "[\\x20\\t>+~](?=[^>+~])"
  }, NOT = {
    // not enclosed in double/single/parens/square
    double_enc: '(?=(?:[^"]*["][^"]*["])*[^"]*$)',
    single_enc: "(?=(?:[^']*['][^']*['])*[^']*$)",
    parens_enc: "(?![^\\x28]*\\x29)",
    square_enc: "(?![^\\x5b]*\\x5d)"
  }, REX = {
    // regular expressions
    HasEscapes: RegExp("\\\\"),
    HexNumbers: RegExp("^[0-9a-fA-F]"),
    EscOrQuote: RegExp("^\\\\|[\\x22\\x27]"),
    RegExpChar: RegExp("(?:(?!\\\\)[\\\\^$.*+?()[\\]{}|\\/])", "g"),
    TrimSpaces: RegExp("[\\r\\n\\f]|^" + WSP + "+|" + WSP + "+$", "g"),
    CommaGroup: RegExp("(\\s*,\\s*)" + NOT.square_enc + NOT.parens_enc, "g"),
    SplitGroup: RegExp("((?:\\x28[^\\x29]*\\x29|\\[[^\\]]*\\]|\\\\.|[^,])+)", "g"),
    FixEscapes: RegExp("\\\\([0-9a-fA-F]{1,6}" + WSP + "?|.)|([\\x22\\x27])", "g"),
    CombineWSP: RegExp("[\\n\\r\\f\\x20]+" + NOT.single_enc + NOT.double_enc, "g"),
    TabCharWSP: RegExp("(\\x20?\\t+\\x20?)" + NOT.single_enc + NOT.double_enc, "g"),
    PseudosWSP: RegExp("\\s+([-+])\\s+" + NOT.square_enc, "g")
  }, STD = {
    combinator: RegExp("\\s?([>+~])\\s?", "g"),
    apimethods: RegExp("^(?:[a-z]+|\\*)\\|", "i"),
    namespaces: RegExp("(\\*|[a-z]+)\\|[-a-z]+", "i")
  }, GROUPS = {
    // pseudo-classes requiring parameters
    linguistic: "(dir|lang)\\x28\\s?([-\\w]{2,})\\s?(?:\\x29|$)",
    logicalsel: "(is|where|matches|not)\\x28\\s?([^()]*|[^\\x28]*\\x28[^\\x29]*\\x29)\\s?(?:\\x29|$)",
    treestruct: "(nth(?:-last)?(?:-child|-of-type))(?:\\x28\\s?(even|odd|(?:[-+]?\\d*)(?:n\\s?[-+]?\\s?\\d*)?)\\s?(?:\\x29|$))",
    // pseudo-classes not requiring parameters
    locationpc: "(any-link|link|visited|target)\\b",
    useraction: "(hover|active|focus|focus-within)\\b",
    structural: "(root|empty|(?:(?:first|last|only)(?:-child|-of-type)))\\b",
    inputstate: "(enabled|disabled|read-only|read-write|placeholder-shown|default)\\b",
    inputvalue: "(checked|indeterminate|required|optional|valid|invalid|in-range|out-of-range)\\b",
    // pseudo-elements starting with single colon (:)
    pseudo_sng: "(after|before|first-letter|first-line)\\b",
    // pseudo-elements starting with double colon (::)
    pseudo_dbl: ":(after|before|first-letter|first-line|selection|placeholder|-webkit-[-a-zA-Z0-9]{2,})\\b"
  }, Patterns = {
    // pseudo-classes
    treestruct: RegExp("^:(?:" + GROUPS.treestruct + ")(.*)", "i"),
    structural: RegExp("^:(?:" + GROUPS.structural + ")(.*)", "i"),
    linguistic: RegExp("^:(?:" + GROUPS.linguistic + ")(.*)", "i"),
    useraction: RegExp("^:(?:" + GROUPS.useraction + ")(.*)", "i"),
    inputstate: RegExp("^:(?:" + GROUPS.inputstate + ")(.*)", "i"),
    inputvalue: RegExp("^:(?:" + GROUPS.inputvalue + ")(.*)", "i"),
    locationpc: RegExp("^:(?:" + GROUPS.locationpc + ")(.*)", "i"),
    logicalsel: RegExp("^:(?:" + GROUPS.logicalsel + ")(.*)", "i"),
    pseudo_dbl: RegExp("^:(?:" + GROUPS.pseudo_dbl + ")(.*)", "i"),
    pseudo_sng: RegExp("^:(?:" + GROUPS.pseudo_sng + ")(.*)", "i"),
    // combinator symbols
    children: RegExp("^" + WSP + "?\\>" + WSP + "?(.*)"),
    adjacent: RegExp("^" + WSP + "?\\+" + WSP + "?(.*)"),
    relative: RegExp("^" + WSP + "?\\~" + WSP + "?(.*)"),
    ancestor: RegExp("^" + WSP + "+(.*)"),
    // universal & namespace
    universal: RegExp("^\\*(.*)"),
    namespace: RegExp("^(\\w+|\\*)?\\|(.*)")
  }, RTL = RegExp("^[\\u0591-\\u08ff\\ufb1d-\\ufdfd\\ufe70-\\ufefc ]+$"), qsNotArgs = "Not enough arguments", qsInvalid = " is not a valid selector", reNthElem = RegExp("(:nth(?:-last)?-child)", "i"), reNthType = RegExp("(:nth(?:-last)?-of-type)", "i"), reOptimizer, reValidator, Config2 = {
    IDS_DUPES: true,
    MIXEDCASE: true,
    LOGERRORS: true,
    VERBOSITY: true
  }, NAMESPACE, QUIRKS_MODE, HTML_DOCUMENT, ATTR_STD_OPS = {
    "=": 1,
    "^=": 1,
    "$=": 1,
    "|=": 1,
    "*=": 1,
    "~=": 1
  }, HTML_TABLE = {
    "accept": 1,
    "accept-charset": 1,
    "align": 1,
    "alink": 1,
    "axis": 1,
    "bgcolor": 1,
    "charset": 1,
    "checked": 1,
    "clear": 1,
    "codetype": 1,
    "color": 1,
    "compact": 1,
    "declare": 1,
    "defer": 1,
    "dir": 1,
    "direction": 1,
    "disabled": 1,
    "enctype": 1,
    "face": 1,
    "frame": 1,
    "hreflang": 1,
    "http-equiv": 1,
    "lang": 1,
    "language": 1,
    "link": 1,
    "media": 1,
    "method": 1,
    "multiple": 1,
    "nohref": 1,
    "noresize": 1,
    "noshade": 1,
    "nowrap": 1,
    "readonly": 1,
    "rel": 1,
    "rev": 1,
    "rules": 1,
    "scope": 1,
    "scrolling": 1,
    "selected": 1,
    "shape": 1,
    "target": 1,
    "text": 1,
    "type": 1,
    "valign": 1,
    "valuetype": 1,
    "vlink": 1
  }, Combinators = {}, Selectors = {}, Operators = {
    "=": {
      p1: "^",
      p2: "$",
      p3: "true"
    },
    "^=": {
      p1: "^",
      p2: "",
      p3: "true"
    },
    "$=": {
      p1: "",
      p2: "$",
      p3: "true"
    },
    "*=": {
      p1: "",
      p2: "",
      p3: "true"
    },
    "|=": {
      p1: "^",
      p2: "(-|$)",
      p3: "true"
    },
    "~=": {
      p1: "(^|\\s)",
      p2: "(\\s|$)",
      p3: "true"
    }
  }, concatCall = function(nodes, callback) {
    var i6 = 0, l6 = nodes.length, list = Array(l6);
    while (l6 > i6) {
      if (false === callback(list[i6] = nodes[i6])) break;
      ++i6;
    }
    return list;
  }, concatList = function(list, nodes) {
    var i6 = -1, l6 = nodes.length;
    while (l6--) {
      list[list.length] = nodes[++i6];
    }
    return list;
  }, documentOrder = function(a5, b3) {
    if (!hasDupes && a5 === b3) {
      hasDupes = true;
      return 0;
    }
    return a5.compareDocumentPosition(b3) & 4 ? -1 : 1;
  }, hasDupes = false, unique = function(nodes) {
    var i6 = 0, j3 = -1, l6 = nodes.length + 1, list = [];
    while (--l6) {
      if (nodes[i6++] === nodes[i6]) continue;
      list[++j3] = nodes[i6 - 1];
    }
    hasDupes = false;
    return list;
  }, hasMixedCaseTagNames = function(context) {
    var ns, api = "getElementsByTagNameNS";
    context = context.ownerDocument || context;
    ns = context.documentElement.namespaceURI || "http://www.w3.org/1999/xhtml";
    return context[api]("*", "*").length - context[api](ns, "*").length > 0;
  }, switchContext = function(context, force) {
    var oldDoc = doc;
    doc = context.ownerDocument || context;
    if (force || oldDoc !== doc) {
      root = doc.documentElement;
      HTML_DOCUMENT = isHTML(doc);
      QUIRKS_MODE = HTML_DOCUMENT && doc.compatMode.indexOf("CSS") < 0;
      NAMESPACE = root && root.namespaceURI;
      Snapshot.doc = doc;
      Snapshot.root = root;
    }
    return Snapshot.from = context;
  }, codePointToUTF16 = function(codePoint) {
    if (codePoint < 1 || codePoint > 1114111 || codePoint > 55295 && codePoint < 57344) {
      return "\\ufffd";
    }
    if (codePoint < 65536) {
      var lowHex = "000" + codePoint.toString(16);
      return "\\u" + lowHex.substr(lowHex.length - 4);
    }
    return "\\u" + ((codePoint - 65536 >> 10) + 55296).toString(16) + "\\u" + ((codePoint - 65536) % 1024 + 56320).toString(16);
  }, stringFromCodePoint = function(codePoint) {
    if (codePoint < 1 || codePoint > 1114111 || codePoint > 55295 && codePoint < 57344) {
      return "\uFFFD";
    }
    if (codePoint < 65536) {
      return String.fromCharCode(codePoint);
    }
    return String.fromCodePoint ? String.fromCodePoint(codePoint) : String.fromCharCode(
      (codePoint - 65536 >> 10) + 55296,
      (codePoint - 65536) % 1024 + 56320
    );
  }, convertEscapes = function(str3) {
    return REX.HasEscapes.test(str3) ? str3.replace(
      REX.FixEscapes,
      function(substring, p1, p22) {
        return p22 ? "\\" + p22 : (
          // javascript strings are UTF-16 encoded
          REX.HexNumbers.test(p1) ? codePointToUTF16(parseInt(p1, 16)) : (
            // \' \"
            REX.EscOrQuote.test(p1) ? substring : (
              // \g \h \. \# etc
              p1
            )
          )
        );
      }
    ) : str3;
  }, unescapeIdentifier = function(str3) {
    return REX.HasEscapes.test(str3) ? str3.replace(
      REX.FixEscapes,
      function(substring, p1, p22) {
        return p22 ? p22 : (
          // javascript strings are UTF-16 encoded
          REX.HexNumbers.test(p1) ? stringFromCodePoint(parseInt(p1, 16)) : (
            // \' \"
            REX.EscOrQuote.test(p1) ? substring : (
              // \g \h \. \# etc
              p1
            )
          )
        );
      }
    ) : str3;
  }, method = {
    "#": "getElementById",
    "*": "getElementsByTagNameNS",
    ".": "getElementsByClassName"
  }, compat = {
    "#": function(c6, n5) {
      REX.HasEscapes.test(n5) && (n5 = unescapeIdentifier(n5));
      return function(e5, f5) {
        return byId(n5, c6);
      };
    },
    "*": function(c6, n5) {
      REX.HasEscapes.test(n5) && (n5 = unescapeIdentifier(n5));
      return function(e5, f5) {
        return byTag(n5, c6);
      };
    },
    ".": function(c6, n5) {
      REX.HasEscapes.test(n5) && (n5 = unescapeIdentifier(n5));
      return function(e5, f5) {
        return byClass(n5, c6);
      };
    }
  }, byIdRaw = function(id, context) {
    var node = context, nodes = [], next = node.firstElementChild;
    while (node = next) {
      node.id == id && (nodes[nodes.length] = node);
      if (next = node.firstElementChild || node.nextElementSibling) continue;
      while (!next && (node = node.parentElement) && node !== context) {
        next = node.nextElementSibling;
      }
    }
    return nodes;
  }, byId = function(id, context) {
    var e5, nodes, api = method["#"];
    if (Config2.IDS_DUPES === false) {
      if (api in context) {
        return (e5 = context[api](id)) ? [e5] : none;
      }
    } else {
      if ("all" in context) {
        if (e5 = context.all[id]) {
          if (e5.nodeType == 1) return e5.getAttribute("id") != id ? [] : [e5];
          else if (id == "length") return (e5 = context[api](id)) ? [e5] : none;
          for (i = 0, l = e5.length, nodes = []; l > i; ++i) {
            if (e5[i].id == id) nodes[nodes.length] = e5[i];
          }
          return nodes && nodes.length ? nodes : [nodes];
        } else return none;
      }
    }
    return byIdRaw(id, context);
  }, byTag = function(tag, context) {
    var e5, nodes, api = method["*"];
    if (api in context) {
      return slice2.call(context[api]("*", tag));
    } else {
      tag = tag.toLowerCase();
      if (e5 = context.firstElementChild) {
        if (!(e5.nextElementSibling || tag == "*" || e5.localName == tag)) {
          return slice2.call(e5[api]("*", tag));
        } else {
          nodes = [];
          do {
            if (tag == "*" || e5.localName == tag) nodes[nodes.length] = e5;
            concatList(nodes, e5[api]("*", tag));
          } while (e5 = e5.nextElementSibling);
        }
      } else nodes = none;
    }
    return nodes;
  }, byClass = function(cls, context) {
    var e5, nodes, api = method["."], reCls;
    if (api in context) {
      return slice2.call(context[api](cls));
    } else {
      if (e5 = context.firstElementChild) {
        reCls = RegExp("(^|\\s)" + cls + "(\\s|$)", QUIRKS_MODE ? "i" : "");
        if (!(e5.nextElementSibling || reCls.test(e5.className))) {
          return slice2.call(e5[api](cls));
        } else {
          nodes = [];
          do {
            if (reCls.test(e5.className)) nodes[nodes.length] = e5;
            concatList(nodes, e5[api](cls));
          } while (e5 = e5.nextElementSibling);
        }
      } else nodes = none;
    }
    return nodes;
  }, hasAttributeNS = function(e5, name2) {
    var i6, l6, attr = e5.getAttributeNames();
    name2 = RegExp(":?" + name2 + "$", HTML_DOCUMENT ? "i" : "");
    for (i6 = 0, l6 = attr.length; l6 > i6; ++i6) {
      if (name2.test(attr[i6])) return true;
    }
    return false;
  }, nthElement = (function() {
    var idx = 0, len = 0, set3 = 0, parent = void 0, parents = Array(), nodes = Array();
    return function(element, dir) {
      if (dir == 2) {
        idx = 0;
        len = 0;
        set3 = 0;
        nodes.length = 0;
        parents.length = 0;
        parent = void 0;
        return -1;
      }
      var e5, i6, j3, k3, l6;
      if (parent === element.parentElement) {
        i6 = set3;
        j3 = idx;
        l6 = len;
      } else {
        l6 = parents.length;
        parent = element.parentElement;
        for (i6 = -1, j3 = 0, k3 = l6 - 1; l6 > j3; ++j3, --k3) {
          if (parents[j3] === parent) {
            i6 = j3;
            break;
          }
          if (parents[k3] === parent) {
            i6 = k3;
            break;
          }
        }
        if (i6 < 0) {
          parents[i6 = l6] = parent;
          l6 = 0;
          nodes[i6] = Array();
          e5 = parent && parent.firstElementChild || element;
          while (e5) {
            nodes[i6][l6] = e5;
            if (e5 === element) j3 = l6;
            e5 = e5.nextElementSibling;
            ++l6;
          }
          set3 = i6;
          idx = 0;
          len = l6;
          if (l6 < 2) return l6;
        } else {
          l6 = nodes[i6].length;
          set3 = i6;
        }
      }
      if (element !== nodes[i6][j3] && element !== nodes[i6][j3 = 0]) {
        for (j3 = 0, e5 = nodes[i6], k3 = l6 - 1; l6 > j3; ++j3, --k3) {
          if (e5[j3] === element) {
            break;
          }
          if (e5[k3] === element) {
            j3 = k3;
            break;
          }
        }
      }
      idx = j3 + 1;
      len = l6;
      return dir ? l6 - j3 : idx;
    };
  })(), nthOfType = (function() {
    var idx = 0, len = 0, set3 = 0, parent = void 0, parents = Array(), nodes = Array();
    return function(element, dir) {
      if (dir == 2) {
        idx = 0;
        len = 0;
        set3 = 0;
        nodes.length = 0;
        parents.length = 0;
        parent = void 0;
        return -1;
      }
      var e5, i6, j3, k3, l6, name2 = element.localName;
      if (nodes[set3] && nodes[set3][name2] && parent === element.parentElement) {
        i6 = set3;
        j3 = idx;
        l6 = len;
      } else {
        l6 = parents.length;
        parent = element.parentElement;
        for (i6 = -1, j3 = 0, k3 = l6 - 1; l6 > j3; ++j3, --k3) {
          if (parents[j3] === parent) {
            i6 = j3;
            break;
          }
          if (parents[k3] === parent) {
            i6 = k3;
            break;
          }
        }
        if (i6 < 0 || !nodes[i6][name2]) {
          parents[i6 = l6] = parent;
          nodes[i6] || (nodes[i6] = Object());
          l6 = 0;
          nodes[i6][name2] = Array();
          e5 = parent && parent.firstElementChild || element;
          while (e5) {
            if (e5 === element) j3 = l6;
            if (e5.localName == name2) {
              nodes[i6][name2][l6] = e5;
              ++l6;
            }
            e5 = e5.nextElementSibling;
          }
          set3 = i6;
          idx = j3;
          len = l6;
          if (l6 < 2) return l6;
        } else {
          l6 = nodes[i6][name2].length;
          set3 = i6;
        }
      }
      if (element !== nodes[i6][name2][j3] && element !== nodes[i6][name2][j3 = 0]) {
        for (j3 = 0, e5 = nodes[i6][name2], k3 = l6 - 1; l6 > j3; ++j3, --k3) {
          if (e5[j3] === element) {
            break;
          }
          if (e5[k3] === element) {
            j3 = k3;
            break;
          }
        }
      }
      idx = j3 + 1;
      len = l6;
      return dir ? l6 - j3 : idx;
    };
  })(), isHTML = function(node) {
    var doc2 = node.ownerDocument || node;
    return doc2.nodeType == 9 && // contentType not in IE <= 11
    "contentType" in doc2 ? doc2.contentType.indexOf("/html") > 0 : doc2.createElement("DiV").localName == "div";
  }, configure = function(option, clear) {
    if (typeof option == "string") {
      return !!Config2[option];
    }
    if (typeof option != "object") {
      return Config2;
    }
    for (var i6 in option) {
      Config2[i6] = !!option[i6];
    }
    if (clear) {
      matchResolvers = {};
      selectResolvers = {};
    }
    setIdentifierSyntax();
    return true;
  }, emit2 = function(message, proto2) {
    var err2;
    if (Config2.VERBOSITY) {
      if (proto2) {
        err2 = new proto2(message);
      } else {
        err2 = new global2.DOMException(message, "SyntaxError");
      }
      throw err2;
    }
    if (Config2.LOGERRORS && console && console.log) {
      console.log(message);
    }
  }, initialize = function(doc2) {
    setIdentifierSyntax();
    lastContext = switchContext(doc2, true);
  }, setIdentifierSyntax = function() {
    var identifier = (
      // doesn't start with a digit
      "(?=[^0-9])(?:-{2}|[a-zA-Z0-9-_]|[^\\x00-\\x9f]|\\\\[^\\r\\n\\f0-9a-fA-F]|\\\\[0-9a-fA-F]{1,6}(?:\\r\\n|\\s)?|\\\\.)+"
    ), pseudonames = "[-\\w]+", pseudoparms = "(?:[-+]?\\d*)(?:n\\s?[-+]?\\s?\\d*)", doublequote = '"[^"\\\\]*(?:\\\\.[^"\\\\]*)*(?:"|$)', singlequote = "'[^'\\\\]*(?:\\\\.[^'\\\\]*)*(?:'|$)", attrparser = identifier + "|" + doublequote + "|" + singlequote, attrvalues = "([\\x22\\x27]?)((?!\\3)*|(?:\\\\?.)*?)(?:\\3|$)", attributes = "\\[(?:\\*\\|)?" + WSP + "?(" + identifier + "(?::" + identifier + ")?)" + WSP + "?(?:(" + CFG.operators + ")" + WSP + "?(?:" + attrparser + "))?" + // attribute case sensitivity
    WSP + "?(i)?" + WSP + "?(?:\\]|$)", attrmatcher = attributes.replace(attrparser, attrvalues), pseudoclass = "(?:\\x28" + WSP + "*(?:" + pseudoparms + "?)?|(?:\\*|\\|)|(?:(?::" + pseudonames + "(?:\\x28" + pseudoparms + "?(?:\\x29|$))?|)|(?:[.#]?" + identifier + ")|(?:" + attributes + "))+|(?:" + WSP + "?," + WSP + "?)|(?:" + WSP + "?)|(?:\\x29|$))*", standardValidator = "(?=" + WSP + "?[^>+~(){}<>])(?:(?:\\*|\\|)|(?:[.#]?" + identifier + ")+|(?:" + attributes + ")+|(?:::?" + pseudonames + pseudoclass + ")|(?:" + WSP + "?" + CFG.combinators + WSP + "?)|(?:" + WSP + "?," + WSP + "?)|(?:" + WSP + "?))+";
    reOptimizer = RegExp(
      "(?:([.:#*]?)(" + identifier + ")(?::[-\\w]+|\\[[^\\]]+(?:\\]|$)|\\x28[^\\x29]+(?:\\x29|$))*)$"
    );
    reValidator = RegExp(standardValidator, "g");
    Patterns.id = RegExp("^#(" + identifier + ")(.*)");
    Patterns.tagName = RegExp("^(" + identifier + ")(.*)");
    Patterns.className = RegExp("^\\.(" + identifier + ")(.*)");
    Patterns.attribute = RegExp("^(?:" + attrmatcher + ")(.*)");
  }, F_INIT = '"use strict";return function Resolver(c,f,x,r)', S_HEAD = "var e,n,o,j=r.length-1,k=-1", M_HEAD = "var e,n,o", S_LOOP = "main:while((e=c[++k]))", N_LOOP = "main:while((e=c.item(++k)))", M_LOOP = "e=c;", S_BODY = "r[++j]=c[k];", N_BODY = "r[++j]=c.item(k);", M_BODY = "", S_TAIL = "continue main;", M_TAIL = "r=true;", S_TEST = "if(f(c[k])){break main;}", N_TEST = "if(f(c.item(k))){break main;}", M_TEST = "f(c);", S_VARS = [], M_VARS = [], compile = function(selector, mode, callback) {
    var factory4, token, head = "", loop = "", macro = "", source2 = "", vars = "";
    switch (mode) {
      case true:
        if (selectLambdas[selector]) {
          return selectLambdas[selector];
        }
        macro = S_BODY + (callback ? S_TEST : "") + S_TAIL;
        head = S_HEAD;
        loop = S_LOOP;
        break;
      case false:
        if (matchLambdas[selector]) {
          return matchLambdas[selector];
        }
        macro = M_BODY + (callback ? M_TEST : "") + M_TAIL;
        head = M_HEAD;
        loop = M_LOOP;
        break;
      case null:
        if (selectLambdas[selector]) {
          return selectLambdas[selector];
        }
        macro = N_BODY + (callback ? N_TEST : "") + S_TAIL;
        head = S_HEAD;
        loop = N_LOOP;
        break;
      default:
        break;
    }
    source2 = compileSelector(selector, macro, mode, callback, false);
    loop += mode || mode === null ? "{" + source2 + "}" : source2;
    if (mode || mode === null && selector.includes(":nth")) {
      loop += reNthElem.test(selector) ? "s.nthElement(null, 2);" : "";
      loop += reNthType.test(selector) ? "s.nthOfType(null, 2);" : "";
    }
    if (S_VARS[0] || M_VARS[0]) {
      vars = "," + (S_VARS.join(",") || M_VARS.join(","));
      S_VARS.length = 0;
      M_VARS.length = 0;
    }
    factory4 = Function("s", F_INIT + "{" + head + vars + ";" + loop + "return r;}")(Snapshot);
    return mode || mode === null ? selectLambdas[selector] = factory4 : matchLambdas[selector] = factory4;
  }, compileSelector = function(expression, source2, mode, callback, not2) {
    var a5, b3, n5, f5, i6, l6, name2, NS, N3 = not2 ? "!" : "", D4 = not2 ? "" : "!", compat2, expr, match2, result2, status, symbol, test, type4, selector = expression, selector_string, vars;
    selector_string = mode ? lastSelected : lastMatched;
    selector = selector.replace(STD.combinator, "$1");
    while (selector) {
      symbol = STD.apimethods.test(selector) ? "|" : selector[0];
      switch (symbol) {
        // universal resolver
        case "*":
          match2 = selector.match(Patterns.universal);
          if (N3 == "!") {
            source2 = "if(" + N3 + "true){" + source2 + "}";
          }
          break;
        // id resolver
        case "#":
          match2 = selector.match(Patterns.id);
          source2 = "if(" + N3 + "(/^" + match2[1] + '$/.test(e.getAttribute("id")))){' + source2 + "}";
          break;
        // class name resolver
        case ".":
          match2 = selector.match(Patterns.className);
          compat2 = (QUIRKS_MODE ? "i" : "") + '.test(e.getAttribute("class"))';
          source2 = "if(" + N3 + "(/(^|\\s)" + match2[1] + "(\\s|$)/" + compat2 + ")){" + source2 + "}";
          break;
        // tag name resolver
        case (/[_a-z]/i.test(symbol) ? symbol : void 0):
          match2 = selector.match(Patterns.tagName);
          source2 = "if(" + N3 + "(e.localName" + (Config2.MIXEDCASE || hasMixedCaseTagNames(doc) ? '=="' + match2[1].toLowerCase() + '"' : '=="' + match2[1].toUpperCase() + '"') + ")){" + source2 + "}";
          break;
        // namespace resolver
        case "|":
          match2 = selector.match(Patterns.namespace);
          if (match2[1] == "*") {
            source2 = "if(" + N3 + "true){" + source2 + "}";
          } else if (!match2[1]) {
            source2 = "if(" + N3 + "(!e.namespaceURI)){" + source2 + "}";
          } else if (typeof match2[1] == "string" && root.prefix == match2[1]) {
            source2 = "if(" + N3 + '(e.namespaceURI=="' + NAMESPACE + '")){' + source2 + "}";
          } else {
            emit2("'" + selector_string + "'" + qsInvalid);
          }
          break;
        // attributes resolver
        case "[":
          match2 = selector.match(Patterns.attribute);
          NS = match2[0].match(STD.namespaces);
          name2 = match2[1];
          expr = name2.split(":");
          expr = expr.length == 2 ? expr[1] : expr[0];
          if (match2[2] && !(test = Operators[match2[2]])) {
            emit2("'" + selector_string + "'" + qsInvalid);
            return "";
          }
          if (match2[4] === "") {
            test = match2[2] == "~=" ? { p1: "^\\s", p2: "+$", p3: "true" } : match2[2] in ATTR_STD_OPS && match2[2] != "~=" ? { p1: "^", p2: "$", p3: "true" } : test;
          } else if (match2[2] == "~=" && match2[4].includes(" ")) {
            source2 = "if(" + N3 + "false){" + source2 + "}";
            break;
          } else if (match2[4]) {
            match2[4] = convertEscapes(match2[4]).replace(REX.RegExpChar, "\\$&");
          }
          type4 = match2[5] == "i" || HTML_DOCUMENT && HTML_TABLE[expr.toLowerCase()] ? "i" : "";
          source2 = "if(" + N3 + "(" + (!match2[2] ? NS ? 's.hasAttributeNS(e,"' + name2 + '")' : 'e.hasAttribute&&e.hasAttribute("' + name2 + '")' : !match2[4] && ATTR_STD_OPS[match2[2]] && match2[2] != "~=" ? 'e.getAttribute&&e.getAttribute("' + name2 + '")==""' : "(/" + test.p1 + match2[4] + test.p2 + "/" + type4 + ').test(e.getAttribute&&e.getAttribute("' + name2 + '"))==' + test.p3) + ")){" + source2 + "}";
          break;
        // *** General sibling combinator
        // E ~ F (F relative sibling of E)
        case "~":
          match2 = selector.match(Patterns.relative);
          source2 = "n=e;while((e=e.previousElementSibling)){" + source2 + "}e=n;";
          break;
        // *** Adjacent sibling combinator
        // E + F (F adiacent sibling of E)
        case "+":
          match2 = selector.match(Patterns.adjacent);
          source2 = "n=e;if((e=e.previousElementSibling)){" + source2 + "}e=n;";
          break;
        // *** Descendant combinator
        // E F (E ancestor of F)
        case "	":
        case " ":
          match2 = selector.match(Patterns.ancestor);
          source2 = "n=e;while((e=e.parentElement)){" + source2 + "}e=n;";
          break;
        // *** Child combinator
        // E > F (F children of E)
        case ">":
          match2 = selector.match(Patterns.children);
          source2 = "n=e;if((e=e.parentElement)){" + source2 + "}e=n;";
          break;
        // *** user supplied combinators extensions
        case (symbol in Combinators ? symbol : void 0):
          match2[match2.length - 1] = "*";
          source2 = Combinators[symbol](match2) + source2;
          break;
        // *** tree-structural pseudo-classes
        // :root, :empty, :first-child, :last-child, :only-child, :first-of-type, :last-of-type, :only-of-type
        case ":":
          if (match2 = selector.match(Patterns.structural)) {
            match2[1] = match2[1].toLowerCase();
            switch (match2[1]) {
              case "root":
                source2 = "if(" + N3 + "(e===s.root)){" + source2 + (mode ? "break main;" : "") + "}";
                break;
              case "empty":
                source2 = "n=e.firstChild;while(n&&!(/1|3/).test(n.nodeType)){n=n.nextSibling}if(" + D4 + "n){" + source2 + "}";
                break;
              // *** child-indexed pseudo-classes
              // :first-child, :last-child, :only-child
              case "only-child":
                source2 = "if(" + N3 + "(!e.nextElementSibling&&!e.previousElementSibling)){" + source2 + "}";
                break;
              case "last-child":
                source2 = "if(" + N3 + "(!e.nextElementSibling)){" + source2 + "}";
                break;
              case "first-child":
                source2 = "if(" + N3 + "(!e.previousElementSibling)){" + source2 + "}";
                break;
              // *** typed child-indexed pseudo-classes
              // :only-of-type, :last-of-type, :first-of-type
              case "only-of-type":
                source2 = "o=e.localName;n=e;while((n=n.nextElementSibling)&&n.localName!=o);if(!n){n=e;while((n=n.previousElementSibling)&&n.localName!=o);}if(" + D4 + "n){" + source2 + "}";
                break;
              case "last-of-type":
                source2 = "n=e;o=e.localName;while((n=n.nextElementSibling)&&n.localName!=o);if(" + D4 + "n){" + source2 + "}";
                break;
              case "first-of-type":
                source2 = "n=e;o=e.localName;while((n=n.previousElementSibling)&&n.localName!=o);if(" + D4 + "n){" + source2 + "}";
                break;
              default:
                emit2("'" + selector_string + "'" + qsInvalid);
                break;
            }
          } else if (match2 = selector.match(Patterns.treestruct)) {
            match2[1] = match2[1].toLowerCase();
            switch (match2[1]) {
              case "nth-child":
              case "nth-of-type":
              case "nth-last-child":
              case "nth-last-of-type":
                expr = /-of-type/i.test(match2[1]);
                if (match2[1] && match2[2]) {
                  type4 = /last/i.test(match2[1]);
                  if (match2[2] == "n") {
                    source2 = "if(" + N3 + "true){" + source2 + "}";
                    break;
                  } else if (match2[2] == "1") {
                    test = type4 ? "next" : "previous";
                    source2 = expr ? "n=e;o=e.localName;while((n=n." + test + "ElementSibling)&&n.localName!=o);if(" + D4 + "n){" + source2 + "}" : "if(" + N3 + "!e." + test + "ElementSibling){" + source2 + "}";
                    break;
                  } else if (match2[2] == "even" || match2[2] == "2n0" || match2[2] == "2n+0" || match2[2] == "2n") {
                    test = "n%2==0";
                  } else if (match2[2] == "odd" || match2[2] == "2n1" || match2[2] == "2n+1") {
                    test = "n%2==1";
                  } else {
                    f5 = /n/i.test(match2[2]);
                    n5 = match2[2].split("n");
                    a5 = parseInt(n5[0], 10) || 0;
                    b3 = parseInt(n5[1], 10) || 0;
                    if (n5[0] == "-") {
                      a5 = -1;
                    }
                    if (n5[0] == "+") {
                      a5 = 1;
                    }
                    test = (b3 ? "(n" + (b3 > 0 ? "-" : "+") + Math.abs(b3) + ")" : "n") + "%" + a5 + "==0";
                    test = a5 >= 1 ? f5 ? "n>" + (b3 - 1) + (Math.abs(a5) != 1 ? "&&" + test : "") : "n==" + a5 : a5 <= -1 ? f5 ? "n<" + (b3 + 1) + (Math.abs(a5) != 1 ? "&&" + test : "") : "n==" + a5 : a5 === 0 ? n5[0] ? "n==" + b3 : "n>" + (b3 - 1) : "false";
                  }
                  expr = expr ? "OfType" : "Element";
                  type4 = type4 ? "true" : "false";
                  source2 = "n=s.nth" + expr + "(e," + type4 + ");if(" + N3 + "(" + test + ")){" + source2 + "}";
                } else {
                  emit2("'" + selector_string + "'" + qsInvalid);
                }
                break;
              default:
                emit2("'" + selector_string + "'" + qsInvalid);
                break;
            }
          } else if (match2 = selector.match(Patterns.logicalsel)) {
            match2[1] = match2[1].toLowerCase();
            switch (match2[1]) {
              case "is":
              case "where":
              case "matches":
                expr = match2[2].replace(REX.CommaGroup, ",").replace(REX.TrimSpaces, "");
                source2 = 'if(s.match("' + expr.replace(/\x22/g, '\\"') + '",e)){' + source2 + "}";
                break;
              case "not":
                expr = match2[2].replace(REX.CommaGroup, ",").replace(REX.TrimSpaces, "");
                source2 = 'if(!s.match("' + expr.replace(/\x22/g, '\\"') + '",e)){' + source2 + "}";
                break;
              default:
                emit2("'" + selector_string + "'" + qsInvalid);
                break;
            }
          } else if (match2 = selector.match(Patterns.linguistic)) {
            match2[1] = match2[1].toLowerCase();
            switch (match2[1]) {
              case "dir":
                source2 = "var p;if(" + N3 + "((/" + match2[2] + '/i.test(e.dir))||(p=s.ancestor("[dir]", e))&&(/' + match2[2] + '/i.test(p.dir))||(e.dir==""||e.dir=="auto")&&(' + (match2[2] == "ltr" ? "!" : "") + RTL + ".test(e.textContent)))){" + source2 + "};";
                break;
              case "lang":
                expr = "(?:^|-)" + match2[2] + "(?:-|$)";
                source2 = "var p;if(" + N3 + '((e.isConnected&&(e.lang==""&&(p=s.ancestor("[lang]",e)))&&(p.lang=="' + match2[2] + '")||/' + expr + "/i.test(e.lang)))){" + source2 + "};";
                break;
              default:
                emit2("'" + selector_string + "'" + qsInvalid);
                break;
            }
          } else if (match2 = selector.match(Patterns.locationpc)) {
            match2[1] = match2[1].toLowerCase();
            switch (match2[1]) {
              case "any-link":
                source2 = "if(" + N3 + '(/^a|area$/i.test(e.localName)&&e.hasAttribute("href")||e.visited)){' + source2 + "}";
                break;
              case "link":
                source2 = "if(" + N3 + '(/^a|area$/i.test(e.localName)&&e.hasAttribute("href"))){' + source2 + "}";
                break;
              case "visited":
                source2 = "if(" + N3 + '(/^a|area$/i.test(e.localName)&&e.hasAttribute("href")&&e.visited)){' + source2 + "}";
                break;
              case "target":
                source2 = "if(" + N3 + "((s.doc.compareDocumentPosition(e)&16)&&s.doc.location.hash&&e.id==s.doc.location.hash.slice(1))){" + source2 + "}";
                break;
              default:
                emit2("'" + selector_string + "'" + qsInvalid);
                break;
            }
          } else if (match2 = selector.match(Patterns.useraction)) {
            match2[1] = match2[1].toLowerCase();
            switch (match2[1]) {
              case "hover":
                source2 = "hasFocus" in doc && doc.hasFocus() ? "if(" + N3 + "(e===s.doc.hoverElement)){" + source2 + "}" : "if(" + D4 + "true){" + source2 + "}";
                break;
              case "active":
                source2 = "hasFocus" in doc && doc.hasFocus() ? "if(" + N3 + "(e===s.doc.activeElement)){" + source2 + "}" : "if(" + D4 + "true){" + source2 + "}";
                break;
              case "focus":
                source2 = "hasFocus" in doc ? "if(" + N3 + '(e===s.doc.activeElement&&s.doc.hasFocus()&&(e.type||e.href||typeof e.tabIndex=="number"))){' + source2 + "}" : "if(" + N3 + "(e===s.doc.activeElement&&(e.type||e.href))){" + source2 + "}";
                break;
              case "focus-within":
                source2 = "hasFocus" in doc ? "n=s.doc.activeElement;while(e){if(e===n||e.parentNode===n)break;}if(" + N3 + '(e===n&&s.doc.hasFocus()&&(e.type||e.href||typeof e.tabIndex=="number"))){' + source2 + "}" : source2;
                break;
              default:
                emit2("'" + selector_string + "'" + qsInvalid);
                break;
            }
          } else if (match2 = selector.match(Patterns.inputstate)) {
            match2[1] = match2[1].toLowerCase();
            switch (match2[1]) {
              case "enabled":
                source2 = "if(" + N3 + '(("form" in e||/^optgroup$/i.test(e.localName))&&"disabled" in e &&e.disabled===false)){' + source2 + "}";
                break;
              case "disabled":
                source2 = "if(" + N3 + '(("form" in e||/^optgroup$/i.test(e.localName))&&"disabled" in e&&(e.disabled===true||(n=s.ancestor("fieldset",e))&&(n=s.first("legend",n))&&!n.contains(e)))){' + source2 + "}";
                break;
              case "read-only":
                source2 = "if(" + N3 + '((/^textarea$/i.test(e.localName)&&(e.readOnly||e.disabled))||("|password|text|".includes("|"+e.type+"|")&&e.readOnly))){' + source2 + "}";
                break;
              case "read-write":
                source2 = "if(" + N3 + '(((/^textarea$/i.test(e.localName)&&!e.readOnly&&!e.disabled)||("|password|text|".includes("|"+e.type+"|")&&!e.readOnly&&!e.disabled))||(e.hasAttribute("contenteditable")||(s.doc.designMode=="on")))){' + source2 + "}";
                break;
              case "placeholder-shown":
                source2 = "if(" + N3 + '((/^input|textarea$/i.test(e.localName))&&e.hasAttribute("placeholder")&&("|textarea|password|number|search|email|text|tel|url|".includes("|"+e.type+"|"))&&(!s.match(":focus",e)))){' + source2 + "}";
                break;
              case "default":
                source2 = "if(" + N3 + '("form" in e && e.form)){var x=0;n=[];if(e.type=="image")n=e.form.getElementsByTagName("input");if(e.type=="submit")n=e.form.elements;while(n[x]&&e!==n[x]){if(n[x].type=="image")break;if(n[x].type=="submit")break;x++;}}if(' + N3 + '(e.form&&(e===n[x]&&"|image|submit|".includes("|"+e.type+"|"))||((/^option$/i.test(e.localName))&&e.defaultSelected)||(("|radio|checkbox|".includes("|"+e.type+"|"))&&e.defaultChecked))){' + source2 + "}";
                break;
              default:
                emit2("'" + selector_string + "'" + qsInvalid);
                break;
            }
          } else if (match2 = selector.match(Patterns.inputvalue)) {
            match2[1] = match2[1].toLowerCase();
            switch (match2[1]) {
              case "checked":
                source2 = "if(" + N3 + '(/^input$/i.test(e.localName)&&("|radio|checkbox|".includes("|"+e.type+"|")&&e.checked)||(/^option$/i.test(e.localName)&&(e.selected||e.checked)))){' + source2 + "}";
                break;
              case "indeterminate":
                source2 = "if(" + N3 + '(/^progress$/i.test(e.localName)&&!e.hasAttribute("value"))||(/^input$/i.test(e.localName)&&("checkbox"==e.type&&e.indeterminate)||("radio"==e.type&&e.name&&!s.first("input[name="+e.name+"]:checked",e.form)))){' + source2 + "}";
                break;
              case "required":
                source2 = "if(" + N3 + "(/^input|select|textarea$/i.test(e.localName)&&e.required)){" + source2 + "}";
                break;
              case "optional":
                source2 = "if(" + N3 + "(/^input|select|textarea$/i.test(e.localName)&&!e.required)){" + source2 + "}";
                break;
              case "invalid":
                source2 = "if(" + N3 + '(((/^form$/i.test(e.localName)&&!e.noValidate)||(e.willValidate&&!e.formNoValidate))&&!e.checkValidity())||(/^fieldset$/i.test(e.localName)&&s.first(":invalid",e))){' + source2 + "}";
                break;
              case "valid":
                source2 = "if(" + N3 + '(((/^form$/i.test(e.localName)&&!e.noValidate)||(e.willValidate&&!e.formNoValidate))&&e.checkValidity())||(/^fieldset$/i.test(e.localName)&&s.first(":valid",e))){' + source2 + "}";
                break;
              case "in-range":
                source2 = "if(" + N3 + '(/^input$/i.test(e.localName))&&(e.willValidate&&!e.formNoValidate)&&(!e.validity.rangeUnderflow&&!e.validity.rangeOverflow)&&("|date|datetime-local|month|number|range|time|week|".includes("|"+e.type+"|"))&&("range"==e.type||e.getAttribute("min")||e.getAttribute("max"))){' + source2 + "}";
                break;
              case "out-of-range":
                source2 = "if(" + N3 + '(/^input$/i.test(e.localName))&&(e.willValidate&&!e.formNoValidate)&&(e.validity.rangeUnderflow||e.validity.rangeOverflow)&&("|date|datetime-local|month|number|range|time|week|".includes("|"+e.type+"|"))&&("range"==e.type||e.getAttribute("min")||e.getAttribute("max"))){' + source2 + "}";
                break;
              default:
                emit2("'" + selector_string + "'" + qsInvalid);
                break;
            }
          } else if (match2 = selector.match(Patterns.pseudo_sng)) {
            source2 = 'if(e.element&&e.type.toLowerCase()==":' + match2[0].toLowerCase() + '"){e=e.element;' + source2 + "}";
          } else if (match2 = selector.match(Patterns.pseudo_dbl)) {
            source2 = 'if(e.element&&e.type.toLowerCase()=="' + match2[0].toLowerCase() + '"){e=e.element;' + source2 + "}";
          } else {
            expr = false;
            status = false;
            for (expr in Selectors) {
              if (match2 = selector.match(Selectors[expr].Expression)) {
                result2 = Selectors[expr].Callback(match2, source2, mode, callback);
                if ("match" in result2) {
                  match2 = result2.match;
                }
                vars = result2.modvar;
                if (mode) {
                  vars && S_VARS.indexOf(vars) < 0 && (S_VARS[S_VARS.length] = vars);
                } else {
                  vars && M_VARS.indexOf(vars) < 0 && (M_VARS[M_VARS.length] = vars);
                }
                source2 = result2.source;
                status = result2.status;
                if (status) {
                  break;
                }
              }
            }
            if (!status) {
              emit2("unknown pseudo-class selector '" + selector + "'");
              return "";
            }
            if (!expr) {
              emit2("unknown token in selector '" + selector + "'");
              return "";
            }
          }
          break;
        default:
          emit2("'" + selector_string + "'" + qsInvalid);
          break;
      }
      if (!match2) {
        emit2("'" + selector_string + "'" + qsInvalid);
        return "";
      }
      selector = match2.pop();
    }
    return source2;
  }, makeref = function(selectors, element) {
    return selectors.replace(
      /:scope/ig,
      element.localName + (element.id ? "#" + element.id : "") + (element.className ? "." + element.classList[0] : "")
    );
  }, ancestor2 = function _closest2(selectors, element, callback) {
    if (/:scope/i.test(selectors)) {
      selectors = makeref(selectors, element);
    }
    while (element) {
      if (match(selectors, element, callback)) break;
      element = element.parentElement;
    }
    return element;
  }, match_assert = function(f5, element, callback) {
    for (var i6 = 0, l6 = f5.length, r5 = false; l6 > i6; ++i6)
      f5[i6](element, callback, null, false) && (r5 = true);
    return r5;
  }, match_collect = function(selectors, callback) {
    for (var i6 = 0, l6 = selectors.length, f5 = []; l6 > i6; ++i6)
      f5[i6] = compile(selectors[i6], false, callback);
    return { factory: f5 };
  }, match = function _matches2(selectors, element, callback) {
    var expressions, parsed;
    if (element && matchResolvers[selectors]) {
      return match_assert(matchResolvers[selectors].factory, element, callback);
    }
    lastMatched = selectors;
    if (arguments.length === 0) {
      emit2(qsNotArgs, TypeError);
      return Config2.VERBOSITY ? void 0 : false;
    } else if (arguments[0] === "") {
      emit2("''" + qsInvalid);
      return Config2.VERBOSITY ? void 0 : false;
    }
    if (typeof selectors != "string") {
      selectors = "" + selectors;
    }
    if (/:scope/i.test(selectors)) {
      selectors = makeref(selectors, element);
    }
    parsed = selectors.replace(/\x00|\\$/g, "\uFFFD").replace(REX.CombineWSP, " ").replace(REX.PseudosWSP, "$1").replace(REX.TabCharWSP, "	").replace(REX.CommaGroup, ",").replace(REX.TrimSpaces, "");
    if ((expressions = parsed.match(reValidator)) && expressions.join("") == parsed) {
      expressions = parsed.match(REX.SplitGroup);
      if (parsed[parsed.length - 1] == ",") {
        emit2(qsInvalid);
        return Config2.VERBOSITY ? void 0 : false;
      }
    } else {
      emit2("'" + selectors + "'" + qsInvalid);
      return Config2.VERBOSITY ? void 0 : false;
    }
    matchResolvers[selectors] = match_collect(expressions, callback);
    return match_assert(matchResolvers[selectors].factory, element, callback);
  }, first = function _querySelector2(selectors, context, callback) {
    if (arguments.length === 0) {
      emit2(qsNotArgs, TypeError);
    }
    return select(
      selectors,
      context,
      typeof callback == "function" ? function firstMatch(element) {
        callback(element);
        return false;
      } : function firstMatch() {
        return false;
      }
    )[0] || null;
  }, select = function _querySelectorAll2(selectors, context, callback) {
    var expressions, nodes, parsed, resolver;
    context || (context = doc);
    if (selectors) {
      if (resolver = selectResolvers[selectors]) {
        if (resolver.context === context && resolver.callback === callback) {
          var f5 = resolver.factory, h5 = resolver.htmlset, n5 = resolver.nodeset, nodes = [];
          if (n5.length > 1) {
            for (var i6 = 0, l6 = n5.length, list; l6 > i6; ++i6) {
              list = compat[n5[i6][0]](context, n5[i6].slice(1))();
              if (f5[i6] !== null) {
                f5[i6](list, callback, context, nodes);
              } else {
                nodes = nodes.concat(list);
              }
            }
            if (l6 > 1 && nodes.length > 1) {
              nodes.sort(documentOrder);
              hasDupes && (nodes = unique(nodes));
            }
          } else {
            if (f5[0]) {
              nodes = f5[0](h5[0](), callback, context, nodes);
            } else {
              nodes = h5[0]();
            }
          }
          return typeof callback == "function" ? concatCall(nodes, callback) : nodes;
        }
      }
    }
    lastSelected = selectors;
    if (arguments.length === 0) {
      emit2(qsNotArgs, TypeError);
      return Config2.VERBOSITY ? void 0 : none;
    } else if (arguments[0] === "") {
      emit2("''" + qsInvalid);
      return Config2.VERBOSITY ? void 0 : none;
    } else if (lastContext !== context) {
      lastContext = switchContext(context);
    }
    if (typeof selectors != "string") {
      selectors = "" + selectors;
    }
    if (/:scope/i.test(selectors)) {
      selectors = makeref(selectors, context);
    }
    parsed = selectors.replace(/\x00|\\$/g, "\uFFFD").replace(REX.CombineWSP, " ").replace(REX.PseudosWSP, "$1").replace(REX.TabCharWSP, "	").replace(REX.CommaGroup, ",").replace(REX.TrimSpaces, "");
    if ((expressions = parsed.match(reValidator)) && expressions.join("") == parsed) {
      expressions = parsed.match(REX.SplitGroup);
      if (parsed[parsed.length - 1] == ",") {
        emit2(qsInvalid);
        return Config2.VERBOSITY ? void 0 : false;
      }
    } else {
      emit2("'" + selectors + "'" + qsInvalid);
      return Config2.VERBOSITY ? void 0 : false;
    }
    selectResolvers[selectors] = collect(expressions, context, callback);
    nodes = selectResolvers[selectors].results;
    return typeof callback == "function" ? concatCall(nodes, callback) : nodes;
  }, optimize = function(selector, token) {
    var index2 = token.index, length = token[1].length + token[2].length;
    return selector.slice(0, index2) + (" >+~".indexOf(selector.charAt(index2 - 1)) > -1 ? ":[".indexOf(selector.charAt(index2 + length + 1)) > -1 ? "*" : "" : "") + selector.slice(index2 + length - (token[1] == "*" ? 1 : 0));
  }, collect = function(selectors, context, callback) {
    var i6, l6, seen = {}, token = ["", "*", "*"], optimized = selectors, factory4 = [], htmlset = [], nodeset = [], results = [], type4;
    for (i6 = 0, l6 = selectors.length; l6 > i6; ++i6) {
      if (!seen[selectors[i6]] && (seen[selectors[i6]] = true)) {
        type4 = selectors[i6].match(reOptimizer);
        if (type4 && type4[1] != ":" && (token = type4)) {
          token[1] || (token[1] = "*");
          optimized[i6] = optimize(optimized[i6], token);
        } else {
          token = ["", "*", "*"];
        }
      }
      nodeset[i6] = token[1] + token[2];
      htmlset[i6] = compat[token[1]](context, token[2]);
      factory4[i6] = compile(optimized[i6], true, null);
      factory4[i6] ? factory4[i6](htmlset[i6](), callback, context, results) : result.concat(htmlset[i6]());
    }
    if (l6 > 1) {
      results.sort(documentOrder);
      hasDupes && (results = unique(results));
    }
    return {
      callback,
      context,
      factory: factory4,
      htmlset,
      nodeset,
      results
    };
  }, _closest, _matches, _querySelector, _querySelectorAll, install7 = function(all2) {
    _closest = Element.prototype.closest;
    _matches = Element.prototype.matches;
    _querySelector = Document.prototype.querySelector;
    _querySelectorAll = Document.prototype.querySelectorAll;
    Element.prototype.closest = function closest2() {
      var ctor = Object.getPrototypeOf(this).__proto__.__proto__.constructor.name;
      if (!("nodeType" in this)) {
        emit2("'closest' called on an object that does not implement interface " + ctor + ".", TypeError);
      }
      return arguments.length < 1 ? ancestor2.apply(this, []) : arguments.length < 2 ? ancestor2.apply(this, [arguments[0], this]) : ancestor2.apply(this, [arguments[0], this, typeof arguments[1] == "function" ? arguments[1] : void 0]);
    };
    Element.prototype.matches = function matches() {
      var ctor = Object.getPrototypeOf(this).__proto__.__proto__.constructor.name;
      if (!("nodeType" in this)) {
        emit2("'matches' called on an object that does not implement interface " + ctor + ".", TypeError);
      }
      return arguments.length < 1 ? match.apply(this, []) : arguments.length < 2 ? match.apply(this, [arguments[0], this]) : match.apply(this, [arguments[0], this, typeof arguments[1] == "function" ? arguments[1] : void 0]);
    };
    Element.prototype.querySelector = Document.prototype.querySelector = DocumentFragment.prototype.querySelector = function querySelector() {
      var ctor = Object.getPrototypeOf(this).__proto__.__proto__.constructor.name;
      if (!("nodeType" in this)) {
        emit2("'querySelector' called on an object that does not implement interface " + ctor + ".", TypeError);
      }
      return arguments.length < 1 ? first.apply(this, []) : arguments.length < 2 ? first.apply(this, [arguments[0], this]) : first.apply(this, [arguments[0], this, typeof arguments[1] == "function" ? arguments[1] : void 0]);
    };
    Element.prototype.querySelectorAll = Document.prototype.querySelectorAll = DocumentFragment.prototype.querySelectorAll = function querySelectorAll() {
      var ctor = Object.getPrototypeOf(this).__proto__.__proto__.constructor.name;
      if (!("nodeType" in this)) {
        emit2("'querySelectorAll' called on an object that does not implement interface " + ctor + ".", TypeError);
      }
      return arguments.length < 1 ? select.apply(this, []) : arguments.length < 2 ? select.apply(this, [arguments[0], this]) : select.apply(this, [arguments[0], this, typeof arguments[1] == "function" ? arguments[1] : void 0]);
    };
    if (all2) {
      document.addEventListener("load", function(e5) {
        var c6, d4, r5, s5, t5 = e5.target;
        if (/iframe/i.test(t5.localName)) {
          c6 = "(" + Export + ")(this, " + Factory + ");";
          d4 = t5.contentDocument;
          s5 = d4.createElement("script");
          s5.textContent = c6 + "NW.Dom.install()";
          r5 = d4.documentElement;
          r5.removeChild(r5.insertBefore(s5, r5.firstChild));
        }
      }, true);
    }
  }, uninstall5 = function() {
    Element.prototype.closest = _closest;
    Element.prototype.matches = _matches;
    Element.prototype.querySelector = Document.prototype.querySelector = DocumentFragment.prototype.querySelector = _querySelector;
    Element.prototype.querySelectorAll = Document.prototype.querySelectorAll = DocumentFragment.prototype.querySelectorAll = _querySelectorAll;
  }, none = Array(), lastContext, lastMatched, lastSelected, matchLambdas = {}, selectLambdas = {}, matchResolvers = {}, selectResolvers = {}, Snapshot = {
    doc,
    from: doc,
    root,
    byTag,
    first,
    match,
    ancestor: ancestor2,
    nthOfType,
    nthElement,
    hasAttributeNS
  }, Dom = {
    // exported cache objects
    lastMatched,
    lastSelected,
    matchLambdas,
    selectLambdas,
    matchResolvers,
    selectResolvers,
    // exported compiler macros
    CFG,
    M_BODY,
    S_BODY,
    M_TEST,
    S_TEST,
    // exported engine methods
    byId,
    byTag,
    byClass,
    match,
    first,
    select,
    closest: ancestor2,
    compile,
    configure,
    emit: emit2,
    Config: Config2,
    Snapshot,
    Version: version4,
    install: install7,
    uninstall: uninstall5,
    Operators,
    Selectors,
    // register a new selector combinator symbol and its related function resolver
    registerCombinator: function(combinator, resolver) {
      var i6 = 0, l6 = combinator.length, symbol;
      for (; l6 > i6; ++i6) {
        if (combinator[i6] != "=") {
          symbol = combinator[i6];
          break;
        }
      }
      if (CFG.combinators.indexOf(symbol) < 0) {
        CFG.combinators = CFG.combinators.replace("](", symbol + "](");
        CFG.combinators = CFG.combinators.replace("])", symbol + "])");
        Combinators[combinator] = resolver;
        setIdentifierSyntax();
      } else {
        console.warn("Warning: the '" + combinator + "' combinator is already registered.");
      }
    },
    // register a new attribute operator symbol and its related function resolver
    registerOperator: function(operator, resolver) {
      var i6 = 0, l6 = operator.length, symbol;
      for (; l6 > i6; ++i6) {
        if (operator[i6] != "=") {
          symbol = operator[i6];
          break;
        }
      }
      if (CFG.operators.indexOf(symbol) < 0 && !Operators[operator]) {
        CFG.operators = CFG.operators.replace("]=", symbol + "]=");
        Operators[operator] = resolver;
        setIdentifierSyntax();
      } else {
        console.warn("Warning: the '" + operator + "' operator is already registered.");
      }
    },
    // register a new selector symbol and its related function resolver
    registerSelector: function(name2, rexp, func) {
      Selectors[name2] || (Selectors[name2] = {
        Expression: rexp,
        Callback: func
      });
    }
  };
  initialize(doc);
  return Dom;
}
var nwsapi_default;
var init_nwsapi = __esm({
  "https://deno.land/x/deno_dom@v0.1.41/src/dom/selectors/nwsapi.js"() {
    nwsapi_default = (document2) => {
      const NW = Factory({ document: document2, DOMException }, "null");
      NW.configure({
        IDS_DUPES: false,
        LOGERRORS: false
      });
      return NW;
    };
  }
});

// https://deno.land/x/deno_dom@v0.1.41/src/dom/selectors/nwsapi-types.ts
var DOM;
var init_nwsapi_types = __esm({
  "https://deno.land/x/deno_dom@v0.1.41/src/dom/selectors/nwsapi-types.ts"() {
    init_nwsapi();
    DOM = nwsapi_default;
  }
});

// https://deno.land/x/deno_dom@v0.1.41/src/dom/selectors/sizzle.js
function SetupSizzle(window2) {
  var i6, support, Expr, getText, isXML, tokenize2, compile, select, outermostContext, sortInput, hasDuplicate, setDocument, document2, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, expando = "sizzle" + 1 * /* @__PURE__ */ new Date(), preferredDoc = window2.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), nonnativeSelectorCache = createCache(), sortOrder = function(a5, b3) {
    if (a5 === b3) {
      hasDuplicate = true;
    }
    return 0;
  }, hasOwn2 = {}.hasOwnProperty, arr = [], pop2 = arr.pop, pushNative = arr.push, push3 = arr.push, slice2 = arr.slice, indexOf2 = function(list, elem) {
    var i7 = 0, len = list.length;
    for (; i7 < len; i7++) {
      if (list[i7] === elem) {
        return i7;
      }
    }
    return -1;
  }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", whitespace = "[\\x20\\t\\r\\n\\f]", identifier = "(?:\\\\[\\da-fA-F]{1,6}" + whitespace + "?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+", attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + // Operator (capture 2)
  "*([*^$|!~]?=)" + whitespace + // "Attribute values must be CSS identifiers [capture 5]
  // or strings [capture 3 or capture 4]"
  `*(?:'((?:\\\\.|[^\\\\'])*)'|"((?:\\\\.|[^\\\\"])*)"|(` + identifier + "))|)" + whitespace + "*\\]", pseudos = ":(" + identifier + `)(?:\\((('((?:\\\\.|[^\\\\'])*)'|"((?:\\\\.|[^\\\\"])*)")|((?:\\\\.|[^\\\\()[\\]]|` + attributes + ")*)|.*)\\)|)", rwhitespace = new RegExp(whitespace + "+", "g"), rtrim = new RegExp(
    "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$",
    "g"
  ), rcomma = new RegExp("^" + whitespace + "*," + whitespace + "*"), rcombinators = new RegExp(
    "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*"
  ), rdescend = new RegExp(whitespace + "|>"), rpseudo = new RegExp(pseudos), ridentifier = new RegExp("^" + identifier + "$"), matchExpr = {
    ID: new RegExp("^#(" + identifier + ")"),
    CLASS: new RegExp("^\\.(" + identifier + ")"),
    TAG: new RegExp("^(" + identifier + "|[*])"),
    ATTR: new RegExp("^" + attributes),
    PSEUDO: new RegExp("^" + pseudos),
    CHILD: new RegExp(
      "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)",
      "i"
    ),
    bool: new RegExp("^(?:" + booleans + ")$", "i"),
    // For use in libraries implementing .is()
    // We use this for POS matching in `select`
    needsContext: new RegExp(
      "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)",
      "i"
    )
  }, rhtml = /HTML$/i, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, runescape = new RegExp(
    "\\\\[\\da-fA-F]{1,6}" + whitespace + "?|\\\\([^\\r\\n\\f])",
    "g"
  ), funescape = function(escape2, nonHex) {
    var high = "0x" + escape2.slice(1) - 65536;
    return nonHex ? (
      // Strip the backslash prefix from a non-hex escape sequence
      nonHex
    ) : (
      // Replace a hexadecimal escape sequence with the encoded Unicode code point
      // Support: IE <=11+
      // For values outside the Basic Multilingual Plane (BMP), manually construct a
      // surrogate pair
      high < 0 ? String.fromCharCode(high + 65536) : String.fromCharCode(high >> 10 | 55296, high & 1023 | 56320)
    );
  }, rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g, fcssescape = function(ch, asCodePoint) {
    if (asCodePoint) {
      if (ch === "\0") {
        return "\uFFFD";
      }
      return ch.slice(0, -1) + "\\" + ch.charCodeAt(ch.length - 1).toString(16) + " ";
    }
    return "\\" + ch;
  }, unloadHandler = function() {
    setDocument();
  }, inDisabledFieldset = addCombinator(
    function(elem) {
      return elem.disabled === true && elem.nodeName.toLowerCase() === "fieldset";
    },
    { dir: "parentNode", next: "legend" }
  );
  try {
    push3.apply(
      arr = slice2.call(preferredDoc.childNodes),
      preferredDoc.childNodes
    );
    arr[preferredDoc.childNodes.length].nodeType;
  } catch (e5) {
    push3 = {
      apply: arr.length ? (
        // Leverage slice if possible
        function(target, els) {
          pushNative.apply(target, slice2.call(els));
        }
      ) : (
        // Support: IE<9
        // Otherwise append directly
        function(target, els) {
          var j3 = target.length, i7 = 0;
          while (target[j3++] = els[i7++]) {
          }
          target.length = j3 - 1;
        }
      )
    };
  }
  function Sizzle(selector, context, results, seed) {
    var m4, i7, elem, nid2, match, groups, newSelector, newContext = context && context.ownerDocument, nodeType = context ? context.nodeType : 9;
    results = results || [];
    if (typeof selector !== "string" || !selector || nodeType !== 1 && nodeType !== 9 && nodeType !== 11) {
      return results;
    }
    if (!seed) {
      setDocument(context);
      context = context || document2;
      if (documentIsHTML) {
        if (nodeType !== 11 && (match = rquickExpr.exec(selector))) {
          if (m4 = match[1]) {
            if (nodeType === 9) {
              if (elem = context.getElementById(m4)) {
                if (elem.id === m4) {
                  results.push(elem);
                  return results;
                }
              } else {
                return results;
              }
            } else {
              if (newContext && (elem = newContext.getElementById(m4)) && contains(context, elem) && elem.id === m4) {
                results.push(elem);
                return results;
              }
            }
          } else if (match[2]) {
            push3.apply(results, context.getElementsByTagName(selector));
            return results;
          } else if ((m4 = match[3]) && support.getElementsByClassName && context.getElementsByClassName) {
            push3.apply(results, context.getElementsByClassName(m4));
            return results;
          }
        }
        if (support.qsa && !nonnativeSelectorCache[selector + " "] && (!rbuggyQSA || !rbuggyQSA.test(selector)) && // Support: IE 8 only
        // Exclude object elements
        (nodeType !== 1 || context.nodeName.toLowerCase() !== "object")) {
          newSelector = selector;
          newContext = context;
          if (nodeType === 1 && (rdescend.test(selector) || rcombinators.test(selector))) {
            newContext = rsibling.test(selector) && testContext(context.parentNode) || context;
            if (newContext !== context || !support.scope) {
              if (nid2 = context.getAttribute("id")) {
                nid2 = nid2.replace(rcssescape, fcssescape);
              } else {
                context.setAttribute("id", nid2 = expando);
              }
            }
            groups = tokenize2(selector);
            i7 = groups.length;
            while (i7--) {
              groups[i7] = (nid2 ? "#" + nid2 : ":scope") + " " + toSelector(groups[i7]);
            }
            newSelector = groups.join(",");
          }
          try {
            push3.apply(results, newContext.querySelectorAll(newSelector));
            return results;
          } catch (qsaError) {
            nonnativeSelectorCache(selector, true);
          } finally {
            if (nid2 === expando) {
              context.removeAttribute("id");
            }
          }
        }
      }
    }
    return select(selector.replace(rtrim, "$1"), context, results, seed);
  }
  function createCache() {
    var keys = [];
    function cache3(key, value) {
      if (keys.push(key + " ") > Expr.cacheLength) {
        delete cache3[keys.shift()];
      }
      return cache3[key + " "] = value;
    }
    return cache3;
  }
  function markFunction(fn) {
    fn[expando] = true;
    return fn;
  }
  function assert10(fn) {
    return true;
    var el = document2.createElement("fieldset");
    try {
      return !!fn(el);
    } catch (e5) {
      return false;
    } finally {
      if (el.parentNode) {
        el.parentNode.removeChild(el);
      }
      el = null;
    }
  }
  function addHandle(attrs, handler) {
    var arr2 = attrs.split("|"), i7 = arr2.length;
    while (i7--) {
      Expr.attrHandle[arr2[i7]] = handler;
    }
  }
  function siblingCheck(a5, b3) {
    var cur = b3 && a5, diff3 = cur && a5.nodeType === 1 && b3.nodeType === 1 && a5.sourceIndex - b3.sourceIndex;
    if (diff3) {
      return diff3;
    }
    if (cur) {
      while (cur = cur.nextSibling) {
        if (cur === b3) {
          return -1;
        }
      }
    }
    return a5 ? 1 : -1;
  }
  function createInputPseudo(type4) {
    return function(elem) {
      var name2 = elem.nodeName.toLowerCase();
      return name2 === "input" && elem.type === type4;
    };
  }
  function createButtonPseudo(type4) {
    return function(elem) {
      var name2 = elem.nodeName.toLowerCase();
      return (name2 === "input" || name2 === "button") && elem.type === type4;
    };
  }
  function createDisabledPseudo(disabled) {
    return function(elem) {
      if ("form" in elem) {
        if (elem.parentNode && elem.disabled === false) {
          if ("label" in elem) {
            if ("label" in elem.parentNode) {
              return elem.parentNode.disabled === disabled;
            } else {
              return elem.disabled === disabled;
            }
          }
          return elem.isDisabled === disabled || // Where there is no isDisabled, check manually
          /* jshint -W018 */
          elem.isDisabled !== !disabled && inDisabledFieldset(elem) === disabled;
        }
        return elem.disabled === disabled;
      } else if ("label" in elem) {
        return elem.disabled === disabled;
      }
      return false;
    };
  }
  function createPositionalPseudo(fn) {
    return markFunction(function(argument) {
      argument = +argument;
      return markFunction(function(seed, matches2) {
        var j3, matchIndexes = fn([], seed.length, argument), i7 = matchIndexes.length;
        while (i7--) {
          if (seed[j3 = matchIndexes[i7]]) {
            seed[j3] = !(matches2[j3] = seed[j3]);
          }
        }
      });
    });
  }
  function testContext(context) {
    return context && typeof context.getElementsByTagName !== "undefined" && context;
  }
  support = Sizzle.support = {};
  isXML = Sizzle.isXML = function(elem) {
    var namespace = elem && elem.namespaceURI, docElem2 = elem && (elem.ownerDocument || elem).documentElement;
    return !rhtml.test(namespace || docElem2 && docElem2.nodeName || "HTML");
  };
  setDocument = Sizzle.setDocument = function(node) {
    var hasCompare, subWindow, doc = node ? node.ownerDocument || node : preferredDoc;
    if (doc == document2 || doc.nodeType !== 9 || !doc.documentElement) {
      return document2;
    }
    document2 = doc;
    docElem = document2.documentElement;
    documentIsHTML = !isXML(document2);
    if (preferredDoc != document2 && (subWindow = document2.defaultView) && subWindow.top !== subWindow) {
      if (subWindow.addEventListener) {
        subWindow.addEventListener("unload", unloadHandler, false);
      } else if (subWindow.attachEvent) {
        subWindow.attachEvent("onunload", unloadHandler);
      }
    }
    support.scope = assert10(function(el) {
      docElem.appendChild(el).appendChild(document2.createElement("div"));
      return typeof el.querySelectorAll !== "undefined" && !el.querySelectorAll(":scope fieldset div").length;
    });
    support.attributes = assert10(function(el) {
      el.className = "i";
      return !el.getAttribute("className");
    });
    support.getElementsByTagName = assert10(function(el) {
      el.appendChild(document2.createComment(""));
      return !el.getElementsByTagName("*").length;
    });
    support.getElementsByClassName = rnative.test(
      document2.getElementsByClassName
    );
    support.getById = assert10(function(el) {
      docElem.appendChild(el).id = expando;
      return !document2.getElementsByName || !document2.getElementsByName(expando).length;
    });
    if (support.getById) {
      Expr.filter["ID"] = function(id) {
        var attrId = id.replace(runescape, funescape);
        return function(elem) {
          return elem.getAttribute("id") === attrId;
        };
      };
      Expr.find["ID"] = function(id, context) {
        if (typeof context.getElementById !== "undefined" && documentIsHTML) {
          var elem = context.getElementById(id);
          return elem ? [elem] : [];
        }
      };
    } else {
      Expr.filter["ID"] = function(id) {
        var attrId = id.replace(runescape, funescape);
        return function(elem) {
          var node2 = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
          return node2 && node2.value === attrId;
        };
      };
      Expr.find["ID"] = function(id, context) {
        if (typeof context.getElementById !== "undefined" && documentIsHTML) {
          var node2, i7, elems, elem = context.getElementById(id);
          if (elem) {
            node2 = elem.getAttributeNode("id");
            if (node2 && node2.value === id) {
              return [elem];
            }
            elems = context.getElementsByName(id);
            i7 = 0;
            while (elem = elems[i7++]) {
              node2 = elem.getAttributeNode("id");
              if (node2 && node2.value === id) {
                return [elem];
              }
            }
          }
          return [];
        }
      };
    }
    Expr.find["TAG"] = support.getElementsByTagName ? function(tag, context) {
      if (typeof context.getElementsByTagName !== "undefined") {
        return context.getElementsByTagName(tag);
      } else if (context[customByTagNameSym]) {
        return context[customByTagNameSym](tag);
      } else if (support.qsa) {
        return context.querySelectorAll(tag);
      }
    } : function(tag, context) {
      var elem, tmp = [], i7 = 0, results = context.getElementsByTagName(tag);
      if (tag === "*") {
        while (elem = results[i7++]) {
          if (elem.nodeType === 1) {
            tmp.push(elem);
          }
        }
        return tmp;
      }
      return results;
    };
    Expr.find["CLASS"] = support.getElementsByClassName && function(className, context) {
      if (typeof context.getElementsByClassName !== "undefined" && documentIsHTML) {
        return context.getElementsByClassName(className);
      } else if (context[customByClassNameSym]) {
        return context[customByClassNameSym](className);
      }
    };
    rbuggyMatches = [];
    rbuggyQSA = [];
    if (support.qsa = rnative.test(document2.querySelectorAll)) {
      assert10(function(el) {
        var input;
        docElem.appendChild(el).innerHTML = "<a id='" + expando + "'></a><select id='" + expando + "-\r\\' msallowcapture=''><option selected=''></option></select>";
        if (el.querySelectorAll("[msallowcapture^='']").length) {
          rbuggyQSA.push("[*^$]=" + whitespace + `*(?:''|"")`);
        }
        if (!el.querySelectorAll("[selected]").length) {
          rbuggyQSA.push("\\[" + whitespace + "*(?:value|" + booleans + ")");
        }
        if (!el.querySelectorAll("[id~=" + expando + "-]").length) {
          rbuggyQSA.push("~=");
        }
        input = document2.createElement("input");
        input.setAttribute("name", "");
        el.appendChild(input);
        if (!el.querySelectorAll("[name='']").length) {
          rbuggyQSA.push(
            "\\[" + whitespace + "*name" + whitespace + "*=" + whitespace + `*(?:''|"")`
          );
        }
        if (!el.querySelectorAll(":checked").length) {
          rbuggyQSA.push(":checked");
        }
        if (!el.querySelectorAll("a#" + expando + "+*").length) {
          rbuggyQSA.push(".#.+[+~]");
        }
        el.querySelectorAll("\\\f");
        rbuggyQSA.push("[\\r\\n\\f]");
      });
      assert10(function(el) {
        el.innerHTML = "<a href='' disabled='disabled'></a><select disabled='disabled'><option/></select>";
        var input = document2.createElement("input");
        input.setAttribute("type", "hidden");
        el.appendChild(input).setAttribute("name", "D");
        if (el.querySelectorAll("[name=d]").length) {
          rbuggyQSA.push("name" + whitespace + "*[*^$|!~]?=");
        }
        if (el.querySelectorAll(":enabled").length !== 2) {
          rbuggyQSA.push(":enabled", ":disabled");
        }
        docElem.appendChild(el).disabled = true;
        if (el.querySelectorAll(":disabled").length !== 2) {
          rbuggyQSA.push(":enabled", ":disabled");
        }
        el.querySelectorAll("*,:x");
        rbuggyQSA.push(",.*:");
      });
    }
    if (support.matchesSelector = rnative.test(
      matches = docElem.matches || docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector
    )) {
      assert10(function(el) {
        support.disconnectedMatch = matches.call(el, "*");
        matches.call(el, "[s!='']:x");
        rbuggyMatches.push("!=", pseudos);
      });
    }
    rbuggyQSA = rbuggyQSA.length && new RegExp(rbuggyQSA.join("|"));
    rbuggyMatches = rbuggyMatches.length && new RegExp(rbuggyMatches.join("|"));
    hasCompare = rnative.test(docElem.compareDocumentPosition);
    contains = hasCompare || rnative.test(docElem.contains) ? function(a5, b3) {
      var adown = a5.nodeType === 9 ? a5.documentElement : a5, bup = b3 && b3.parentNode;
      return a5 === bup || !!(bup && bup.nodeType === 1 && (adown.contains ? adown.contains(bup) : a5.compareDocumentPosition && a5.compareDocumentPosition(bup) & 16));
    } : function(a5, b3) {
      if (b3) {
        while (b3 = b3.parentNode) {
          if (b3 === a5) {
            return true;
          }
        }
      }
      return false;
    };
    sortOrder = hasCompare ? function(a5, b3) {
      if (a5 === b3) {
        hasDuplicate = true;
        return 0;
      }
      var compare2 = !a5.compareDocumentPosition - !b3.compareDocumentPosition;
      if (compare2) {
        return compare2;
      }
      compare2 = (a5.ownerDocument || a5) == (b3.ownerDocument || b3) ? a5.compareDocumentPosition(b3) : (
        // Otherwise we know they are disconnected
        1
      );
      if (compare2 & 1 || !support.sortDetached && b3.compareDocumentPosition(a5) === compare2) {
        if (a5 == document2 || a5.ownerDocument == preferredDoc && contains(preferredDoc, a5)) {
          return -1;
        }
        if (b3 == document2 || b3.ownerDocument == preferredDoc && contains(preferredDoc, b3)) {
          return 1;
        }
        return sortInput ? indexOf2(sortInput, a5) - indexOf2(sortInput, b3) : 0;
      }
      return compare2 & 4 ? -1 : 1;
    } : function(a5, b3) {
      if (a5 === b3) {
        hasDuplicate = true;
        return 0;
      }
      var cur, i7 = 0, aup = a5.parentNode, bup = b3.parentNode, ap = [a5], bp = [b3];
      if (!aup || !bup) {
        return a5 == document2 ? -1 : b3 == document2 ? 1 : (
          /* eslint-enable eqeqeq */
          aup ? -1 : bup ? 1 : sortInput ? indexOf2(sortInput, a5) - indexOf2(sortInput, b3) : 0
        );
      } else if (aup === bup) {
        return siblingCheck(a5, b3);
      }
      cur = a5;
      while (cur = cur.parentNode) {
        ap.unshift(cur);
      }
      cur = b3;
      while (cur = cur.parentNode) {
        bp.unshift(cur);
      }
      while (ap[i7] === bp[i7]) {
        i7++;
      }
      return i7 ? (
        // Do a sibling check if the nodes have a common ancestor
        siblingCheck(ap[i7], bp[i7])
      ) : (
        // Otherwise nodes in our document sort first
        // Support: IE 11+, Edge 17 - 18+
        // IE/Edge sometimes throw a "Permission denied" error when strict-comparing
        // two documents; shallow comparisons work.
        /* eslint-disable eqeqeq */
        ap[i7] == preferredDoc ? -1 : bp[i7] == preferredDoc ? 1 : (
          /* eslint-enable eqeqeq */
          0
        )
      );
    };
    return document2;
  };
  Sizzle.matches = function(expr, elements) {
    return Sizzle(expr, null, null, elements);
  };
  Sizzle.matchesSelector = function(elem, expr) {
    setDocument(elem);
    if (support.matchesSelector && documentIsHTML && !nonnativeSelectorCache[expr + " "] && (!rbuggyMatches || !rbuggyMatches.test(expr)) && (!rbuggyQSA || !rbuggyQSA.test(expr))) {
      try {
        var ret = matches.call(elem, expr);
        if (ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document
        // fragment in IE 9
        elem.document && elem.document.nodeType !== 11) {
          return ret;
        }
      } catch (e5) {
        nonnativeSelectorCache(expr, true);
      }
    }
    return Sizzle(expr, document2, null, [elem]).length > 0;
  };
  Sizzle.contains = function(context, elem) {
    if ((context.ownerDocument || context) != document2) {
      setDocument(context);
    }
    return contains(context, elem);
  };
  Sizzle.attr = function(elem, name2) {
    if ((elem.ownerDocument || elem) != document2) {
      setDocument(elem);
    }
    var fn = Expr.attrHandle[name2.toLowerCase()], val = fn && hasOwn2.call(Expr.attrHandle, name2.toLowerCase()) ? fn(elem, name2, !documentIsHTML) : void 0;
    return val !== void 0 ? val : support.attributes || !documentIsHTML ? elem.getAttribute(name2) : (val = elem.getAttributeNode(name2)) && val.specified ? val.value : null;
  };
  Sizzle.escape = function(sel) {
    return (sel + "").replace(rcssescape, fcssescape);
  };
  Sizzle.error = function(msg5) {
    throw new DOMException(`'${msg5}' is not a valid selector`);
  };
  Sizzle.uniqueSort = function(results) {
    var elem, duplicates = [], j3 = 0, i7 = 0;
    hasDuplicate = !support.detectDuplicates;
    sortInput = !support.sortStable && results.slice(0);
    results.sort(sortOrder);
    if (hasDuplicate) {
      while (elem = results[i7++]) {
        if (elem === results[i7]) {
          j3 = duplicates.push(i7);
        }
      }
      while (j3--) {
        results.splice(duplicates[j3], 1);
      }
    }
    sortInput = null;
    return results;
  };
  getText = Sizzle.getText = function(elem) {
    var node, ret = "", i7 = 0, nodeType = elem.nodeType;
    if (!nodeType) {
      while (node = elem[i7++]) {
        ret += getText(node);
      }
    } else if (nodeType === 1 || nodeType === 9 || nodeType === 11) {
      if (typeof elem.textContent === "string") {
        return elem.textContent;
      } else {
        for (elem = elem.firstChild; elem; elem = elem.nextSibling) {
          ret += getText(elem);
        }
      }
    } else if (nodeType === 3 || nodeType === 4) {
      return elem.nodeValue;
    }
    return ret;
  };
  Expr = Sizzle.selectors = {
    // Can be adjusted by the user
    cacheLength: 50,
    createPseudo: markFunction,
    match: matchExpr,
    attrHandle: {},
    find: {},
    relative: {
      ">": { dir: "parentNode", first: true },
      " ": { dir: "parentNode" },
      "+": { dir: "previousSibling", first: true },
      "~": { dir: "previousSibling" }
    },
    preFilter: {
      ATTR: function(match) {
        match[1] = match[1].replace(runescape, funescape);
        match[3] = (match[3] || match[4] || match[5] || "").replace(
          runescape,
          funescape
        );
        if (match[2] === "~=") {
          match[3] = " " + match[3] + " ";
        }
        return match.slice(0, 4);
      },
      CHILD: function(match) {
        match[1] = match[1].toLowerCase();
        if (match[1].slice(0, 3) === "nth") {
          if (!match[3]) {
            Sizzle.error(match[0]);
          }
          match[4] = +(match[4] ? match[5] + (match[6] || 1) : 2 * (match[3] === "even" || match[3] === "odd"));
          match[5] = +(match[7] + match[8] || match[3] === "odd");
        } else if (match[3]) {
          Sizzle.error(match[0]);
        }
        return match;
      },
      PSEUDO: function(match) {
        var excess, unquoted = !match[6] && match[2];
        if (matchExpr["CHILD"].test(match[0])) {
          return null;
        }
        if (match[3]) {
          match[2] = match[4] || match[5] || "";
        } else if (unquoted && rpseudo.test(unquoted) && // Get excess from tokenize (recursively)
        (excess = tokenize2(unquoted, true)) && // advance to the next closing parenthesis
        (excess = unquoted.indexOf(")", unquoted.length - excess) - unquoted.length)) {
          match[0] = match[0].slice(0, excess);
          match[2] = unquoted.slice(0, excess);
        }
        return match.slice(0, 3);
      }
    },
    filter: {
      TAG: function(nodeNameSelector) {
        var nodeName = nodeNameSelector.replace(runescape, funescape).toLowerCase();
        return nodeNameSelector === "*" ? function() {
          return true;
        } : function(elem) {
          return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
        };
      },
      CLASS: function(className) {
        var pattern = classCache[className + " "];
        return pattern || (pattern = new RegExp(
          "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)"
        )) && classCache(className, function(elem) {
          return pattern.test(
            typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || ""
          );
        });
      },
      ATTR: function(name2, operator, check2) {
        return function(elem) {
          var result2 = Sizzle.attr(elem, name2);
          if (result2 == null) {
            return operator === "!=";
          }
          if (!operator) {
            return true;
          }
          result2 += "";
          return operator === "=" ? result2 === check2 : operator === "!=" ? result2 !== check2 : operator === "^=" ? check2 && result2.indexOf(check2) === 0 : operator === "*=" ? check2 && result2.indexOf(check2) > -1 : operator === "$=" ? check2 && result2.slice(-check2.length) === check2 : operator === "~=" ? (" " + result2.replace(rwhitespace, " ") + " ").indexOf(check2) > -1 : operator === "|=" ? result2 === check2 || result2.slice(0, check2.length + 1) === check2 + "-" : false;
        };
      },
      CHILD: function(type4, what, _argument, first, last) {
        var simple3 = type4.slice(0, 3) !== "nth", forward = type4.slice(-4) !== "last", ofType = what === "of-type";
        return first === 1 && last === 0 ? (
          // Shortcut for :nth-*(n)
          function(elem) {
            return !!elem.parentNode;
          }
        ) : function(elem, _context, xml) {
          var cache3, uniqueCache, outerCache, node, nodeIndex, start, dir = simple3 !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name2 = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType, diff3 = false;
          if (parent) {
            if (simple3) {
              while (dir) {
                node = elem;
                while (node = node[dir]) {
                  if (ofType ? node.nodeName.toLowerCase() === name2 : node.nodeType === 1) {
                    return false;
                  }
                }
                start = dir = type4 === "only" && !start && "nextSibling";
              }
              return true;
            }
            start = [forward ? parent.firstChild : parent.lastChild];
            if (forward && useCache) {
              node = parent;
              outerCache = node[expando] || (node[expando] = {});
              uniqueCache = outerCache[node.uniqueID] || (outerCache[node.uniqueID] = {});
              cache3 = uniqueCache[type4] || [];
              nodeIndex = cache3[0] === dirruns && cache3[1];
              diff3 = nodeIndex && cache3[2];
              node = nodeIndex && parent.childNodes[nodeIndex];
              while (node = ++nodeIndex && node && node[dir] || // Fallback to seeking `elem` from the start
              (diff3 = nodeIndex = 0) || start.pop()) {
                if (node.nodeType === 1 && ++diff3 && node === elem) {
                  uniqueCache[type4] = [dirruns, nodeIndex, diff3];
                  break;
                }
              }
            } else {
              if (useCache) {
                node = elem;
                outerCache = node[expando] || (node[expando] = {});
                uniqueCache = outerCache[node.uniqueID] || (outerCache[node.uniqueID] = {});
                cache3 = uniqueCache[type4] || [];
                nodeIndex = cache3[0] === dirruns && cache3[1];
                diff3 = nodeIndex;
              }
              if (diff3 === false) {
                while (node = ++nodeIndex && node && node[dir] || (diff3 = nodeIndex = 0) || start.pop()) {
                  if ((ofType ? node.nodeName.toLowerCase() === name2 : node.nodeType === 1) && ++diff3) {
                    if (useCache) {
                      outerCache = node[expando] || (node[expando] = {});
                      uniqueCache = outerCache[node.uniqueID] || (outerCache[node.uniqueID] = {});
                      uniqueCache[type4] = [dirruns, diff3];
                    }
                    if (node === elem) {
                      break;
                    }
                  }
                }
              }
            }
            diff3 -= last;
            return diff3 === first || diff3 % first === 0 && diff3 / first >= 0;
          }
        };
      },
      PSEUDO: function(pseudo, argument) {
        var args, fn = Expr.pseudos[pseudo] || Expr.setFilters[pseudo.toLowerCase()] || Sizzle.error("unsupported pseudo: " + pseudo);
        if (fn[expando]) {
          return fn(argument);
        }
        if (fn.length > 1) {
          args = [pseudo, pseudo, "", argument];
          return Expr.setFilters.hasOwnProperty(pseudo.toLowerCase()) ? markFunction(function(seed, matches2) {
            var idx, matched = fn(seed, argument), i7 = matched.length;
            while (i7--) {
              idx = indexOf2(seed, matched[i7]);
              seed[idx] = !(matches2[idx] = matched[i7]);
            }
          }) : function(elem) {
            return fn(elem, 0, args);
          };
        }
        return fn;
      }
    },
    pseudos: {
      // Potentially complex pseudos
      not: markFunction(function(selector) {
        var input = [], results = [], matcher = compile(selector.replace(rtrim, "$1"));
        return matcher[expando] ? markFunction(function(seed, matches2, _context, xml) {
          var elem, unmatched = matcher(seed, null, xml, []), i7 = seed.length;
          while (i7--) {
            if (elem = unmatched[i7]) {
              seed[i7] = !(matches2[i7] = elem);
            }
          }
        }) : function(elem, _context, xml) {
          input[0] = elem;
          matcher(input, null, xml, results);
          input[0] = null;
          return !results.pop();
        };
      }),
      has: markFunction(function(selector) {
        return function(elem) {
          return Sizzle(selector, elem).length > 0;
        };
      }),
      contains: markFunction(function(text) {
        text = text.replace(runescape, funescape);
        return function(elem) {
          return (elem.textContent || getText(elem)).indexOf(text) > -1;
        };
      }),
      // "Whether an element is represented by a :lang() selector
      // is based solely on the element's language value
      // being equal to the identifier C,
      // or beginning with the identifier C immediately followed by "-".
      // The matching of C against the element's language value is performed case-insensitively.
      // The identifier C does not have to be a valid language name."
      // http://www.w3.org/TR/selectors/#lang-pseudo
      lang: markFunction(function(lang) {
        if (!ridentifier.test(lang || "")) {
          Sizzle.error("unsupported lang: " + lang);
        }
        lang = lang.replace(runescape, funescape).toLowerCase();
        return function(elem) {
          var elemLang;
          do {
            if (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) {
              elemLang = elemLang.toLowerCase();
              return elemLang === lang || elemLang.indexOf(lang + "-") === 0;
            }
          } while ((elem = elem.parentNode) && elem.nodeType === 1);
          return false;
        };
      }),
      // Miscellaneous
      target: function(elem) {
        var hash = window2.location && window2.location.hash;
        return hash && hash.slice(1) === elem.id;
      },
      root: function(elem) {
        return elem === docElem;
      },
      focus: function(elem) {
        return elem === document2.activeElement && (!document2.hasFocus || document2.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
      },
      // Boolean properties
      enabled: createDisabledPseudo(false),
      disabled: createDisabledPseudo(true),
      checked: function(elem) {
        var nodeName = elem.nodeName.toLowerCase();
        return nodeName === "input" && !!elem.checked || nodeName === "option" && !!elem.selected;
      },
      selected: function(elem) {
        if (elem.parentNode) {
          elem.parentNode.selectedIndex;
        }
        return elem.selected === true;
      },
      // Contents
      empty: function(elem) {
        for (elem = elem.firstChild; elem; elem = elem.nextSibling) {
          if (elem.nodeType < 6) {
            return false;
          }
        }
        return true;
      },
      parent: function(elem) {
        return !Expr.pseudos["empty"](elem);
      },
      // Element/input types
      header: function(elem) {
        return rheader.test(elem.nodeName);
      },
      input: function(elem) {
        return rinputs.test(elem.nodeName);
      },
      button: function(elem) {
        var name2 = elem.nodeName.toLowerCase();
        return name2 === "input" && elem.type === "button" || name2 === "button";
      },
      text: function(elem) {
        var attr;
        return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && // Support: IE<8
        // New HTML5 attribute values (e.g., "search") appear with elem.type === "text"
        ((attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text");
      },
      // Position-in-collection
      first: createPositionalPseudo(function() {
        return [0];
      }),
      last: createPositionalPseudo(function(_matchIndexes, length) {
        return [length - 1];
      }),
      eq: createPositionalPseudo(function(_matchIndexes, length, argument) {
        return [argument < 0 ? argument + length : argument];
      }),
      even: createPositionalPseudo(function(matchIndexes, length) {
        var i7 = 0;
        for (; i7 < length; i7 += 2) {
          matchIndexes.push(i7);
        }
        return matchIndexes;
      }),
      odd: createPositionalPseudo(function(matchIndexes, length) {
        var i7 = 1;
        for (; i7 < length; i7 += 2) {
          matchIndexes.push(i7);
        }
        return matchIndexes;
      }),
      lt: createPositionalPseudo(function(matchIndexes, length, argument) {
        var i7 = argument < 0 ? argument + length : argument > length ? length : argument;
        for (; --i7 >= 0; ) {
          matchIndexes.push(i7);
        }
        return matchIndexes;
      }),
      gt: createPositionalPseudo(function(matchIndexes, length, argument) {
        var i7 = argument < 0 ? argument + length : argument;
        for (; ++i7 < length; ) {
          matchIndexes.push(i7);
        }
        return matchIndexes;
      })
    }
  };
  Expr.pseudos["nth"] = Expr.pseudos["eq"];
  for (i6 in {
    radio: true,
    checkbox: true,
    file: true,
    password: true,
    image: true
  }) {
    Expr.pseudos[i6] = createInputPseudo(i6);
  }
  for (i6 in { submit: true, reset: true }) {
    Expr.pseudos[i6] = createButtonPseudo(i6);
  }
  function setFilters() {
  }
  setFilters.prototype = Expr.filters = Expr.pseudos;
  Expr.setFilters = new setFilters();
  tokenize2 = Sizzle.tokenize = function(selector, parseOnly) {
    var matched, match, tokens2, type4, soFar, groups, preFilters, cached = tokenCache[selector + " "];
    if (cached) {
      return parseOnly ? 0 : cached.slice(0);
    }
    soFar = selector;
    groups = [];
    preFilters = Expr.preFilter;
    while (soFar) {
      if (!matched || (match = rcomma.exec(soFar))) {
        if (match) {
          soFar = soFar.slice(match[0].length) || soFar;
        }
        groups.push(tokens2 = []);
      }
      matched = false;
      if (match = rcombinators.exec(soFar)) {
        matched = match.shift();
        tokens2.push({
          value: matched,
          // Cast descendant combinators to space
          type: match[0].replace(rtrim, " ")
        });
        soFar = soFar.slice(matched.length);
      }
      for (type4 in Expr.filter) {
        if ((match = matchExpr[type4].exec(soFar)) && (!preFilters[type4] || (match = preFilters[type4](match)))) {
          matched = match.shift();
          tokens2.push({
            value: matched,
            type: type4,
            matches: match
          });
          soFar = soFar.slice(matched.length);
        }
      }
      if (!matched) {
        break;
      }
    }
    return parseOnly ? soFar.length : soFar ? Sizzle.error(selector) : (
      // Cache the tokens
      tokenCache(selector, groups).slice(0)
    );
  };
  function toSelector(tokens2) {
    var i7 = 0, len = tokens2.length, selector = "";
    for (; i7 < len; i7++) {
      selector += tokens2[i7].value;
    }
    return selector;
  }
  function addCombinator(matcher, combinator, base3) {
    var dir = combinator.dir, skip = combinator.next, key = skip || dir, checkNonElements = base3 && key === "parentNode", doneName = done++;
    return combinator.first ? (
      // Check against closest ancestor/preceding element
      function(elem, context, xml) {
        while (elem = elem[dir]) {
          if (elem.nodeType === 1 || checkNonElements) {
            return matcher(elem, context, xml);
          }
        }
        return false;
      }
    ) : (
      // Check against all ancestor/preceding elements
      function(elem, context, xml) {
        var oldCache, uniqueCache, outerCache, newCache = [dirruns, doneName];
        if (xml) {
          while (elem = elem[dir]) {
            if (elem.nodeType === 1 || checkNonElements) {
              if (matcher(elem, context, xml)) {
                return true;
              }
            }
          }
        } else {
          while (elem = elem[dir]) {
            if (elem.nodeType === 1 || checkNonElements) {
              outerCache = elem[expando] || (elem[expando] = {});
              uniqueCache = outerCache[elem.uniqueID] || (outerCache[elem.uniqueID] = {});
              if (skip && skip === elem.nodeName.toLowerCase()) {
                elem = elem[dir] || elem;
              } else if ((oldCache = uniqueCache[key]) && oldCache[0] === dirruns && oldCache[1] === doneName) {
                return newCache[2] = oldCache[2];
              } else {
                uniqueCache[key] = newCache;
                if (newCache[2] = matcher(elem, context, xml)) {
                  return true;
                }
              }
            }
          }
        }
        return false;
      }
    );
  }
  function elementMatcher(matchers) {
    return matchers.length > 1 ? function(elem, context, xml) {
      var i7 = matchers.length;
      while (i7--) {
        if (!matchers[i7](elem, context, xml)) {
          return false;
        }
      }
      return true;
    } : matchers[0];
  }
  function multipleContexts(selector, contexts, results) {
    var i7 = 0, len = contexts.length;
    for (; i7 < len; i7++) {
      Sizzle(selector, contexts[i7], results);
    }
    return results;
  }
  function condense(unmatched, map3, filter3, context, xml) {
    var elem, newUnmatched = [], i7 = 0, len = unmatched.length, mapped = map3 != null;
    for (; i7 < len; i7++) {
      if (elem = unmatched[i7]) {
        if (!filter3 || filter3(elem, context, xml)) {
          newUnmatched.push(elem);
          if (mapped) {
            map3.push(i7);
          }
        }
      }
    }
    return newUnmatched;
  }
  function setMatcher(preFilter, selector, matcher, postFilter, postFinder, postSelector) {
    if (postFilter && !postFilter[expando]) {
      postFilter = setMatcher(postFilter);
    }
    if (postFinder && !postFinder[expando]) {
      postFinder = setMatcher(postFinder, postSelector);
    }
    return markFunction(function(seed, results, context, xml) {
      var temp, i7, elem, preMap = [], postMap = [], preexisting = results.length, elems = seed || multipleContexts(
        selector || "*",
        context.nodeType ? [context] : context,
        []
      ), matcherIn = preFilter && (seed || !selector) ? condense(elems, preMap, preFilter, context, xml) : elems, matcherOut = matcher ? (
        // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
        postFinder || (seed ? preFilter : preexisting || postFilter) ? (
          // ...intermediate processing is necessary
          []
        ) : (
          // ...otherwise use results directly
          results
        )
      ) : matcherIn;
      if (matcher) {
        matcher(matcherIn, matcherOut, context, xml);
      }
      if (postFilter) {
        temp = condense(matcherOut, postMap);
        postFilter(temp, [], context, xml);
        i7 = temp.length;
        while (i7--) {
          if (elem = temp[i7]) {
            matcherOut[postMap[i7]] = !(matcherIn[postMap[i7]] = elem);
          }
        }
      }
      if (seed) {
        if (postFinder || preFilter) {
          if (postFinder) {
            temp = [];
            i7 = matcherOut.length;
            while (i7--) {
              if (elem = matcherOut[i7]) {
                temp.push(matcherIn[i7] = elem);
              }
            }
            postFinder(null, matcherOut = [], temp, xml);
          }
          i7 = matcherOut.length;
          while (i7--) {
            if ((elem = matcherOut[i7]) && (temp = postFinder ? indexOf2(seed, elem) : preMap[i7]) > -1) {
              seed[temp] = !(results[temp] = elem);
            }
          }
        }
      } else {
        matcherOut = condense(
          matcherOut === results ? matcherOut.splice(preexisting, matcherOut.length) : matcherOut
        );
        if (postFinder) {
          postFinder(null, results, matcherOut, xml);
        } else {
          push3.apply(results, matcherOut);
        }
      }
    });
  }
  function matcherFromTokens(tokens2) {
    var checkContext, matcher, j3, len = tokens2.length, leadingRelative = Expr.relative[tokens2[0].type], implicitRelative = leadingRelative || Expr.relative[" "], i7 = leadingRelative ? 1 : 0, matchContext = addCombinator(
      function(elem) {
        return elem === checkContext;
      },
      implicitRelative,
      true
    ), matchAnyContext = addCombinator(
      function(elem) {
        return indexOf2(checkContext, elem) > -1;
      },
      implicitRelative,
      true
    ), matchers = [
      function(elem, context, xml) {
        var ret = !leadingRelative && (xml || context !== outermostContext) || ((checkContext = context).nodeType ? matchContext(elem, context, xml) : matchAnyContext(elem, context, xml));
        checkContext = null;
        return ret;
      }
    ];
    for (; i7 < len; i7++) {
      if (matcher = Expr.relative[tokens2[i7].type]) {
        matchers = [addCombinator(elementMatcher(matchers), matcher)];
      } else {
        matcher = Expr.filter[tokens2[i7].type].apply(null, tokens2[i7].matches);
        if (matcher[expando]) {
          j3 = ++i7;
          for (; j3 < len; j3++) {
            if (Expr.relative[tokens2[j3].type]) {
              break;
            }
          }
          return setMatcher(
            i7 > 1 && elementMatcher(matchers),
            i7 > 1 && toSelector(
              // If the preceding token was a descendant combinator, insert an implicit any-element `*`
              tokens2.slice(0, i7 - 1).concat({ value: tokens2[i7 - 2].type === " " ? "*" : "" })
            ).replace(rtrim, "$1"),
            matcher,
            i7 < j3 && matcherFromTokens(tokens2.slice(i7, j3)),
            j3 < len && matcherFromTokens(tokens2 = tokens2.slice(j3)),
            j3 < len && toSelector(tokens2)
          );
        }
        matchers.push(matcher);
      }
    }
    return elementMatcher(matchers);
  }
  function matcherFromGroupMatchers(elementMatchers, setMatchers) {
    var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function(seed, context, xml, results, outermost) {
      var elem, j3, matcher, matchedCount = 0, i7 = "0", unmatched = seed && [], setMatched = [], contextBackup = outermostContext, elems = seed || byElement && Expr.find["TAG"]("*", outermost), dirrunsUnique = dirruns += contextBackup == null ? 1 : Math.random() || 0.1, len = elems.length;
      if (outermost) {
        outermostContext = context == document2 || context || outermost;
      }
      for (; i7 !== len && (elem = elems[i7]) != null; i7++) {
        if (byElement && elem) {
          j3 = 0;
          if (!context && elem.ownerDocument != document2) {
            setDocument(elem);
            xml = !documentIsHTML;
          }
          while (matcher = elementMatchers[j3++]) {
            if (matcher(elem, context || document2, xml)) {
              results.push(elem);
              break;
            }
          }
          if (outermost) {
            dirruns = dirrunsUnique;
          }
        }
        if (bySet) {
          if (elem = !matcher && elem) {
            matchedCount--;
          }
          if (seed) {
            unmatched.push(elem);
          }
        }
      }
      matchedCount += i7;
      if (bySet && i7 !== matchedCount) {
        j3 = 0;
        while (matcher = setMatchers[j3++]) {
          matcher(unmatched, setMatched, context, xml);
        }
        if (seed) {
          if (matchedCount > 0) {
            while (i7--) {
              if (!(unmatched[i7] || setMatched[i7])) {
                setMatched[i7] = pop2.call(results);
              }
            }
          }
          setMatched = condense(setMatched);
        }
        push3.apply(results, setMatched);
        if (outermost && !seed && setMatched.length > 0 && matchedCount + setMatchers.length > 1) {
          Sizzle.uniqueSort(results);
        }
      }
      if (outermost) {
        dirruns = dirrunsUnique;
        outermostContext = contextBackup;
      }
      return unmatched;
    };
    return bySet ? markFunction(superMatcher) : superMatcher;
  }
  compile = Sizzle.compile = function(selector, match) {
    var i7, setMatchers = [], elementMatchers = [], cached = compilerCache[selector + " "];
    if (!cached) {
      if (!match) {
        match = tokenize2(selector);
      }
      i7 = match.length;
      while (i7--) {
        cached = matcherFromTokens(match[i7]);
        if (cached[expando]) {
          setMatchers.push(cached);
        } else {
          elementMatchers.push(cached);
        }
      }
      cached = compilerCache(
        selector,
        matcherFromGroupMatchers(elementMatchers, setMatchers)
      );
      cached.selector = selector;
    }
    return cached;
  };
  select = Sizzle.select = function(selector, context, results, seed) {
    var i7, tokens2, token, type4, find, compiled = typeof selector === "function" && selector, match = !seed && tokenize2(selector = compiled.selector || selector);
    results = results || [];
    if (match.length === 1) {
      tokens2 = match[0] = match[0].slice(0);
      if (tokens2.length > 2 && (token = tokens2[0]).type === "ID" && context.nodeType === 9 && documentIsHTML && Expr.relative[tokens2[1].type]) {
        context = (Expr.find["ID"](
          token.matches[0].replace(runescape, funescape),
          context
        ) || [])[0];
        if (!context) {
          return results;
        } else if (compiled) {
          context = context.parentNode;
        }
        selector = selector.slice(tokens2.shift().value.length);
      }
      i7 = matchExpr["needsContext"].test(selector) ? 0 : tokens2.length;
      while (i7--) {
        token = tokens2[i7];
        if (Expr.relative[type4 = token.type]) {
          break;
        }
        if (find = Expr.find[type4]) {
          if (seed = find(
            token.matches[0].replace(runescape, funescape),
            rsibling.test(tokens2[0].type) && testContext(context.parentNode) || context
          )) {
            tokens2.splice(i7, 1);
            selector = seed.length && toSelector(tokens2);
            if (!selector) {
              push3.apply(results, seed);
              return results;
            }
            break;
          }
        }
      }
    }
    (compiled || compile(selector, match))(
      seed,
      context,
      !documentIsHTML,
      results,
      !context || rsibling.test(selector) && testContext(context.parentNode) || context
    );
    return results;
  };
  support.sortStable = expando.split("").sort(sortOrder).join("") === expando;
  support.detectDuplicates = !!hasDuplicate;
  setDocument();
  support.sortDetached = assert10(function(el) {
    return el.compareDocumentPosition(document2.createElement("fieldset")) & 1;
  });
  if (!assert10(function(el) {
    el.innerHTML = "<a href='#'></a>";
    return el.firstChild.getAttribute("href") === "#";
  })) {
    addHandle("type|href|height|width", function(elem, name2, isXML2) {
      if (!isXML2) {
        return elem.getAttribute(name2, name2.toLowerCase() === "type" ? 1 : 2);
      }
    });
  }
  if (!support.attributes || !assert10(function(el) {
    el.innerHTML = "<input/>";
    el.firstChild.setAttribute("value", "");
    return el.firstChild.getAttribute("value") === "";
  })) {
    addHandle("value", function(elem, _name, isXML2) {
      if (!isXML2 && elem.nodeName.toLowerCase() === "input") {
        return elem.defaultValue;
      }
    });
  }
  if (!assert10(function(el) {
    return el.getAttribute("disabled") == null;
  })) {
    addHandle(booleans, function(elem, name2, isXML2) {
      var val;
      if (!isXML2) {
        return elem[name2] === true ? name2.toLowerCase() : (val = elem.getAttributeNode(name2)) && val.specified ? val.value : null;
      }
    });
  }
  var _sizzle = window2.Sizzle;
  Sizzle.noConflict = function() {
    if (window2.Sizzle === Sizzle) {
      window2.Sizzle = _sizzle;
    }
    return Sizzle;
  };
  if (typeof define === "function" && define.amd) {
    define(function() {
      return Sizzle;
    });
  } else if (typeof module !== "undefined" && module.exports) {
    module.exports = Sizzle;
  } else {
    window2.Sizzle = Sizzle;
  }
}
var sizzle_default;
var init_sizzle = __esm({
  "https://deno.land/x/deno_dom@v0.1.41/src/dom/selectors/sizzle.js"() {
    init_custom_api();
    sizzle_default = (document2) => {
      const sizzleWindow = {
        document: document2
      };
      SetupSizzle(sizzleWindow);
      const { Sizzle } = sizzleWindow;
      return {
        first(selectors, context) {
          return Sizzle(selectors, context)[0] ?? null;
        },
        select(selectors, context) {
          return Sizzle(selectors, context);
        },
        match(selectors, context) {
          return Sizzle.matchesSelector(context, selectors);
        }
      };
    };
  }
});

// https://deno.land/x/deno_dom@v0.1.41/src/dom/selectors/sizzle-types.ts
var DOM2;
var init_sizzle_types = __esm({
  "https://deno.land/x/deno_dom@v0.1.41/src/dom/selectors/sizzle-types.ts"() {
    init_sizzle();
    DOM2 = sizzle_default;
  }
});

// https://deno.land/x/deno_dom@v0.1.41/src/dom/selectors/selectors.ts
function getSelectorEngine() {
  if (codeGenerationAllowed === null) {
    try {
      new Function("");
      codeGenerationAllowed = true;
    } catch (e5) {
      codeGenerationAllowed = false;
    }
  }
  if (codeGenerationAllowed) {
    return DOM;
  } else {
    return DOM2;
  }
}
var codeGenerationAllowed;
var init_selectors = __esm({
  "https://deno.land/x/deno_dom@v0.1.41/src/dom/selectors/selectors.ts"() {
    init_nwsapi_types();
    init_sizzle_types();
    codeGenerationAllowed = null;
  }
});

// https://deno.land/x/deno_dom@v0.1.41/src/dom/document.ts
var DOMImplementation, DocumentType, Document2, HTMLDocument;
var init_document = __esm({
  "https://deno.land/x/deno_dom@v0.1.41/src/dom/document.ts"() {
    init_constructor_lock();
    init_node();
    init_node_list();
    init_element();
    init_document_fragment();
    init_html_template_element();
    init_selectors();
    init_utils();
    init_utils_types();
    DOMImplementation = class {
      constructor(key) {
        if (key !== CTOR_KEY) {
          throw new TypeError("Illegal constructor.");
        }
      }
      createDocument() {
        throw new Error("Unimplemented");
      }
      createHTMLDocument(titleStr) {
        titleStr += "";
        const doc = new HTMLDocument(CTOR_KEY);
        const docType = new DocumentType("html", "", "", CTOR_KEY);
        doc.appendChild(docType);
        const html = new Element2("html", doc, [], CTOR_KEY);
        html._setOwnerDocument(doc);
        const head = new Element2("head", html, [], CTOR_KEY);
        const body = new Element2("body", html, [], CTOR_KEY);
        const title3 = new Element2("title", head, [], CTOR_KEY);
        const titleText = new Text2(titleStr);
        title3.appendChild(titleText);
        doc.head = head;
        doc.body = body;
        return doc;
      }
      createDocumentType(qualifiedName, publicId, systemId) {
        const doctype = new DocumentType(
          qualifiedName,
          publicId,
          systemId,
          CTOR_KEY
        );
        return doctype;
      }
    };
    DocumentType = class _DocumentType extends Node2 {
      #qualifiedName = "";
      #publicId = "";
      #systemId = "";
      constructor(name2, publicId, systemId, key) {
        super(
          "html",
          10 /* DOCUMENT_TYPE_NODE */,
          null,
          key
        );
        this.#qualifiedName = name2;
        this.#publicId = publicId;
        this.#systemId = systemId;
      }
      get name() {
        return this.#qualifiedName;
      }
      get publicId() {
        return this.#publicId;
      }
      get systemId() {
        return this.#systemId;
      }
      _shallowClone() {
        return new _DocumentType(
          this.#qualifiedName,
          this.#publicId,
          this.#systemId,
          CTOR_KEY
        );
      }
    };
    Document2 = class _Document extends Node2 {
      head = null;
      body = null;
      implementation;
      #lockState = false;
      #documentURI = "about:blank";
      // TODO
      #title = "";
      #nwapi = null;
      constructor() {
        super(
          "#document",
          9 /* DOCUMENT_NODE */,
          null,
          CTOR_KEY
        );
        this.implementation = new DOMImplementation(CTOR_KEY);
      }
      _shallowClone() {
        return new _Document();
      }
      // Expose the document's NWAPI for Element's access to
      // querySelector/querySelectorAll
      get _nwapi() {
        return this.#nwapi || (this.#nwapi = getSelectorEngine()(this));
      }
      get documentURI() {
        return this.#documentURI;
      }
      get title() {
        return this.querySelector("title")?.textContent || "";
      }
      get cookie() {
        return "";
      }
      set cookie(newCookie) {
      }
      get visibilityState() {
        return "visible";
      }
      get hidden() {
        return false;
      }
      get compatMode() {
        return "CSS1Compat";
      }
      get documentElement() {
        for (const node of this.childNodes) {
          if (node.nodeType === 1 /* ELEMENT_NODE */) {
            return node;
          }
        }
        return null;
      }
      get doctype() {
        for (const node of this.childNodes) {
          if (node.nodeType === 10 /* DOCUMENT_TYPE_NODE */) {
            return node;
          }
        }
        return null;
      }
      get childElementCount() {
        let count = 0;
        for (const { nodeType } of this.childNodes) {
          if (nodeType === 1 /* ELEMENT_NODE */) {
            count++;
          }
        }
        return count;
      }
      appendChild(child) {
        super.appendChild(child);
        child._setOwnerDocument(this);
        return child;
      }
      createElement(tagName, options) {
        tagName = tagName.toUpperCase();
        switch (tagName) {
          case "TEMPLATE": {
            const frag = new DocumentFragment2();
            const elm = new HTMLTemplateElement(
              null,
              [],
              CTOR_KEY,
              frag
            );
            elm._setOwnerDocument(this);
            return elm;
          }
          default: {
            const elm = new Element2(tagName, null, [], CTOR_KEY);
            elm._setOwnerDocument(this);
            return elm;
          }
        }
      }
      createElementNS(namespace, qualifiedName, options) {
        if (namespace === "http://www.w3.org/1999/xhtml") {
          return this.createElement(qualifiedName, options);
        } else {
          throw new Error(
            `createElementNS: "${namespace}" namespace unimplemented`
          );
        }
      }
      createTextNode(data3) {
        return new Text2(data3);
      }
      createComment(data3) {
        return new Comment2(data3);
      }
      createDocumentFragment() {
        const fragment = new DocumentFragment2();
        fragment._setOwnerDocument(this);
        return fragment;
      }
      importNode(node, deep = false) {
        const copy6 = node.cloneNode(deep);
        copy6._setOwnerDocument(this);
        return copy6;
      }
      adoptNode(node) {
        if (node instanceof _Document) {
          throw new DOMException(
            "Adopting a Document node is not supported.",
            "NotSupportedError"
          );
        }
        node._setParent(null);
        node._setOwnerDocument(this);
        return node;
      }
      querySelector(selectors) {
        return this._nwapi.first(selectors, this);
      }
      querySelectorAll(selectors) {
        const nodeList = new NodeList();
        const mutator = nodeList[nodeListMutatorSym]();
        for (const match of this._nwapi.select(selectors, this)) {
          mutator.push(match);
        }
        return nodeList;
      }
      // TODO: DRY!!!
      getElementById(id) {
        for (const child of this.childNodes) {
          if (child.nodeType === 1 /* ELEMENT_NODE */) {
            if (child.id === id) {
              return child;
            }
            const search = child.getElementById(id);
            if (search) {
              return search;
            }
          }
        }
        return null;
      }
      getElementsByTagName(tagName) {
        if (tagName === "*") {
          return this.documentElement ? this._getElementsByTagNameWildcard(
            this.documentElement,
            []
          ) : [];
        } else {
          return this._getElementsByTagName(tagName.toUpperCase(), []);
        }
      }
      _getElementsByTagNameWildcard(node, search) {
        for (const child of this.childNodes) {
          if (child.nodeType === 1 /* ELEMENT_NODE */) {
            search.push(child);
            child._getElementsByTagNameWildcard(search);
          }
        }
        return search;
      }
      _getElementsByTagName(tagName, search) {
        for (const child of this.childNodes) {
          if (child.nodeType === 1 /* ELEMENT_NODE */) {
            if (child.tagName === tagName) {
              search.push(child);
            }
            child._getElementsByTagName(tagName, search);
          }
        }
        return search;
      }
      getElementsByTagNameNS(_namespace, localName) {
        return this.getElementsByTagName(localName);
      }
      getElementsByClassName(className) {
        return getElementsByClassName(this, className, []);
      }
      hasFocus() {
        return true;
      }
    };
    HTMLDocument = class _HTMLDocument extends Document2 {
      constructor(key) {
        if (key !== CTOR_KEY) {
          throw new TypeError("Illegal constructor.");
        }
        super();
      }
      _shallowClone() {
        return new _HTMLDocument(CTOR_KEY);
      }
    };
    utils_types_default.Document = Document2;
  }
});

// https://deno.land/x/deno_dom@v0.1.41/src/deserialize.ts
function nodesFromString(html) {
  const parsed = JSON.parse(parse5(html));
  const node = nodeFromArray(parsed, null);
  return node;
}
function fragmentNodesFromString(html, contextLocalName) {
  const parsed = JSON.parse(parseFrag(html, contextLocalName));
  const node = nodeFromArray(parsed, null);
  return node;
}
function nodeFromArray(data3, parentNode) {
  if (data3[1] === "template") {
    const content = nodeFromArray(data3[3], null);
    const contentFrag = new DocumentFragment2();
    const fragMutator = contentFrag._getChildNodesMutator();
    for (const child of content.childNodes) {
      fragMutator.push(child);
      child._setParent(contentFrag);
    }
    return new HTMLTemplateElement(
      parentNode,
      data3[2],
      CTOR_KEY,
      contentFrag
    );
  }
  const elm = new Element2(data3[1], parentNode, data3[2], CTOR_KEY);
  const childNodes = elm._getChildNodesMutator();
  let childNode;
  for (const child of data3.slice(3)) {
    switch (child[0]) {
      case 3 /* TEXT_NODE */:
        childNode = new Text2(child[1]);
        childNode.parentNode = childNode.parentElement = elm;
        childNodes.push(childNode);
        break;
      case 8 /* COMMENT_NODE */:
        childNode = new Comment2(child[1]);
        childNode.parentNode = childNode.parentElement = elm;
        childNodes.push(childNode);
        break;
      case 9 /* DOCUMENT_NODE */:
      case 1 /* ELEMENT_NODE */:
        nodeFromArray(child, elm);
        break;
      case 10 /* DOCUMENT_TYPE_NODE */:
        childNode = new DocumentType(child[1], child[2], child[3], CTOR_KEY);
        childNode.parentNode = childNode.parentElement = elm;
        childNodes.push(childNode);
        break;
    }
  }
  return elm;
}
var init_deserialize = __esm({
  "https://deno.land/x/deno_dom@v0.1.41/src/deserialize.ts"() {
    init_parser();
    init_constructor_lock();
    init_node();
    init_document();
    init_document_fragment();
    init_html_template_element();
    init_element();
  }
});

// https://deno.land/x/deno_dom@v0.1.41/src/dom/dom-parser.ts
var DOMParser;
var init_dom_parser = __esm({
  "https://deno.land/x/deno_dom@v0.1.41/src/dom/dom-parser.ts"() {
    init_constructor_lock();
    init_deserialize();
    init_document();
    DOMParser = class {
      parseFromString(source2, mimeType) {
        if (mimeType !== "text/html") {
          throw new Error(`DOMParser: "${mimeType}" unimplemented`);
        }
        const doc = new HTMLDocument(CTOR_KEY);
        const fakeDoc = nodesFromString(source2);
        let htmlNode = null;
        let hasDoctype = false;
        for (const child of [...fakeDoc.childNodes]) {
          doc.appendChild(child);
          if (child instanceof DocumentType) {
            hasDoctype = true;
          } else if (child.nodeName === "HTML") {
            htmlNode = child;
          }
        }
        if (!hasDoctype) {
          const docType = new DocumentType("html", "", "", CTOR_KEY);
          if (doc.childNodes.length === 0) {
            doc.appendChild(docType);
          } else {
            doc.insertBefore(docType, doc.childNodes[0]);
          }
        }
        if (htmlNode) {
          for (const child of htmlNode.childNodes) {
            switch (child.tagName) {
              case "HEAD":
                doc.head = child;
                break;
              case "BODY":
                doc.body = child;
                break;
            }
          }
        }
        return doc;
      }
    };
  }
});

// https://deno.land/x/deno_dom@v0.1.41/src/api.ts
var oldHasInstance, oldIsArray;
var init_api = __esm({
  "https://deno.land/x/deno_dom@v0.1.41/src/api.ts"() {
    init_deserialize();
    init_node();
    init_element();
    init_document();
    init_document_fragment();
    init_dom_parser();
    init_html_template_element();
    init_selectors();
    init_node();
    init_document();
    init_element();
    init_node_list();
    init_html_collection();
    init_node_list();
    init_html_collection();
    oldHasInstance = Array[Symbol.hasInstance];
    Object.defineProperty(Array, Symbol.hasInstance, {
      value(value) {
        switch (value?.constructor) {
          case HTMLCollection:
          case NodeList:
            return false;
          default:
            return oldHasInstance.call(this, value);
        }
      },
      configurable: true
    });
    oldIsArray = Array.isArray;
    Object.defineProperty(Array, "isArray", {
      value: (value) => {
        switch (value?.constructor) {
          case HTMLCollection:
          case NodeList:
            return false;
          default:
            return oldIsArray.call(Array, value);
        }
      },
      configurable: true
    });
  }
});

// https://deno.land/x/deno_dom@v0.1.41/deno-dom-wasm-noinit.ts
async function initParser() {
  await deno_wasm_default();
  register(parse4, parse_frag);
}
var init_deno_dom_wasm_noinit = __esm({
  "https://deno.land/x/deno_dom@v0.1.41/deno-dom-wasm-noinit.ts"() {
    init_deno_wasm();
    init_parser();
    init_api();
  }
});

// core/deno-dom.ts
async function getDomParser() {
  await initDenoDom();
  return new DOMParser();
}
async function writeDomToHtmlFile(doc, path3, doctype) {
  if (doc.documentElement === null) {
    throw new Error("Document has no root element");
  }
  const output = doctype ? doctype + "\n" + doc.documentElement.outerHTML : doc.documentElement.outerHTML;
  await Deno.writeTextFile(path3, output);
}
async function initDenoDom() {
  if (!s_DenoDomInitialized) {
    try {
      const denoNativePluginPath = Deno.env.get("DENO_DOM_PLUGIN");
      if (denoNativePluginPath) {
        const _symbols = {
          deno_dom_usize_len: { parameters: [], result: "usize" },
          deno_dom_parse_sync: {
            parameters: ["buffer", "usize", "buffer"],
            result: "void"
          },
          deno_dom_parse_frag_sync: {
            parameters: ["buffer", "usize", "buffer", "usize", "buffer"],
            result: "void"
          },
          deno_dom_is_big_endian: { parameters: [], result: "u32" },
          deno_dom_copy_buf: {
            parameters: ["buffer", "buffer"],
            result: "void"
          }
        };
        const symbols = _symbols;
        const dylib = Deno.dlopen(denoNativePluginPath, symbols);
        const utf8Encoder = new TextEncoder();
        const utf8Decoder = new TextDecoder();
        const usizeBytes = Number(dylib.symbols.deno_dom_usize_len());
        const isBigEndian = Boolean(
          dylib.symbols.deno_dom_is_big_endian()
        );
        const dylibParseSync = dylib.symbols.deno_dom_parse_sync.bind(
          dylib.symbols
        );
        const dylibParseFragSync = dylib.symbols.deno_dom_parse_frag_sync.bind(
          dylib.symbols
        );
        const returnBufSizeLenRaw = new ArrayBuffer(usizeBytes * 2);
        const returnBufSizeLen = new Uint8Array(returnBufSizeLenRaw);
        const genericParse = (parser, srcHtml, contextLocalName) => {
          const encodedHtml = utf8Encoder.encode(srcHtml);
          if (contextLocalName) {
            const encodedContextLocalName = utf8Encoder.encode(
              contextLocalName
            );
            parser(
              encodedHtml,
              BigInt(encodedHtml.length),
              encodedContextLocalName,
              BigInt(encodedContextLocalName.length),
              returnBufSizeLen
            );
          } else {
            parser(
              encodedHtml,
              BigInt(encodedHtml.length),
              returnBufSizeLen
            );
          }
          const outBufSize = Number(
            new DataView(returnBufSizeLenRaw).getBigUint64(0, !isBigEndian)
          );
          const outBuf = new Uint8Array(outBufSize);
          dylib.symbols.deno_dom_copy_buf(
            returnBufSizeLen.slice(usizeBytes),
            outBuf
          );
          return utf8Decoder.decode(outBuf);
        };
        const parse24 = (html) => {
          return genericParse(dylibParseSync, html);
        };
        const parseFrag2 = (html, contextLocalName) => {
          return genericParse(dylibParseFragSync, html, contextLocalName);
        };
        debug("Loaded deno-dom-native");
        register(parse24, parseFrag2);
        s_DenoDomInitialized = true;
        return;
      }
    } catch (e5) {
      if (!(e5 instanceof Error)) {
        throw e5;
      }
      debug("Error loading deno-dom-native: " + e5.message);
    }
  }
  if (!s_DenoDomInitialized) {
    await initParser();
    s_DenoDomInitialized = true;
  }
}
var parseHtml, s_DenoDomInitialized;
var init_deno_dom = __esm({
  "core/deno-dom.ts"() {
    init_log();
    init_deno_dom_wasm_noinit();
    init_parser();
    init_dom_parser();
    init_function_times();
    init_api();
    init_dom_parser();
    init_node();
    parseHtml = makeTimedFunctionAsync(
      "parseHtml",
      async function parseHtml2(src2) {
        await initDenoDom();
        const result2 = new DOMParser().parseFromString(src2, "text/html");
        if (!result2) {
          throw new Error("Couldn't parse string into HTML");
        }
        return result2;
      }
    );
    s_DenoDomInitialized = false;
  }
});

// core/pandoc/json.ts
var makeInlinesNode, emph, smallCaps, strikeout, strong, subscript, superscript, underline3;
var init_json = __esm({
  "core/pandoc/json.ts"() {
    makeInlinesNode = (name2) => (content) => {
      return {
        t: name2,
        c: content
      };
    };
    emph = makeInlinesNode("Emph");
    smallCaps = makeInlinesNode("SmallCaps");
    strikeout = makeInlinesNode("Strikeout");
    strong = makeInlinesNode("Strong");
    subscript = makeInlinesNode("Subscript");
    superscript = makeInlinesNode("Superscript");
    underline3 = makeInlinesNode("Underline");
  }
});

// tools/github.ts
function isGitHubActions() {
  return Deno.env.get("GITHUB_ACTIONS") === "true";
}
function isVerboseMode() {
  return Deno.env.get("RUNNER_DEBUG") === "1" || Deno.env.get("QUARTO_TEST_VERBOSE") === "true";
}
async function getLatestRelease(repo) {
  const url = `https://api.github.com/repos/${repo}/releases/latest`;
  const headers = Deno.env.get("GH_TOKEN") ? { headers: { Authorization: "Bearer " + Deno.env.get("GH_TOKEN") } } : void 0;
  const response = await fetch(url, headers);
  if (response.status !== 200) {
    throw new Error(
      `Unable to determine latest release for ${repo}
${response.status} - ${response.statusText}`
    );
  } else {
    return response.json();
  }
}
var init_github = __esm({
  "tools/github.ts"() {
  }
});

// core/log.ts
function appendLogOptions(cmd) {
  const addLogOptions = (cmd2) => {
    return cmd2.option(
      "--log <file>",
      "Path to log file",
      {
        global: true
      }
    ).option(
      "--log-level <level>",
      "Log level (debug, info, warning, error, critical)",
      {
        global: true
      }
    ).option(
      "--log-format <format>",
      "Log format (plain, json-stream)",
      {
        global: true
      }
    ).option(
      "--quiet",
      "Suppress console output.",
      {
        global: true
      }
    );
  };
  const subCommands = cmd.getCommands();
  if (subCommands.length > 0) {
    subCommands.forEach((command) => {
      addLogOptions(command);
    });
    return cmd;
  } else {
    return addLogOptions(cmd);
  }
}
function logOptions(args) {
  const logOptions2 = {};
  logOptions2.log = args.l || args.log || Deno.env.get("QUARTO_LOG");
  if (logOptions2.log) {
    ensureDirSync(dirname4(logOptions2.log));
  }
  let level = args.ll || args["log-level"] || Deno.env.get("QUARTO_LOG_LEVEL");
  if (!level && isGitHubActions() && isVerboseMode()) {
    level = "DEBUG";
  }
  logOptions2.level = level;
  logOptions2.quiet = args.q || args.quiet;
  logOptions2.format = parseFormat(
    args.lf || args["log-format"] || Deno.env.get("QUARTO_LOG_FORMAT")
  );
  return logOptions2;
}
function logLevel() {
  return currentLogLevel;
}
async function initializeLogger(logOptions2) {
  const handlers3 = {};
  const defaultHandlers = [];
  const file = logOptions2.log;
  currentLogLevel = logOptions2.level ? parseLevel(logOptions2.level) : "INFO";
  handlers3["events"] = new LogEventsHandler(logLevel());
  defaultHandlers.push("events");
  if (!logOptions2.quiet) {
    handlers3["console"] = new StdErrOutputHandler(
      logLevel(),
      {
        formatter: (({ msg: msg5 }) => `${msg5}`)
      }
    );
    defaultHandlers.push("console");
  }
  if (file) {
    handlers3["file"] = new LogFileHandler(
      logLevel(),
      {
        filename: file,
        mode: "w",
        format: logOptions2.format
      }
    );
    defaultHandlers.push("file");
  }
  await setup({
    handlers: handlers3,
    loggers: {
      default: {
        level: "DEBUG",
        handlers: defaultHandlers
      }
    }
  });
  onCleanup(cleanupLogger);
  return handlers3;
}
async function cleanupLogger() {
  const logger = getLogger();
  for (const handler of logger.handlers) {
    await handler.destroy();
  }
  logger.handlers = [];
}
function logProgress(message) {
  info(bold3(blue3(message)));
}
function logError(e5, defaultShowStack = true) {
  const err2 = asErrorEx(e5, defaultShowStack);
  let message = err2.printName ? `${err2.name}: ${err2.message}` : err2.message;
  if (e5 instanceof InternalError) {
    message = message + `

This is a bug in quarto. We apologize for the inconvenience.
Please consider reporting it at https://github.com/quarto-dev/quarto-cli. Thank you!`;
  }
  const isDebug = getenv("QUARTO_DEBUG", "false") === "true" || getenv("QUARTO_PRINT_STACK", "false") === "true";
  if (err2.stack && (isDebug || err2.printStack)) {
    if (!message) {
      message = err2.stack;
    } else {
      const stackLines = err2.stack.split("\n");
      const firstAtLineIndex = stackLines.findIndex(
        (line) => /^\s*at /.test(line)
      );
      if (firstAtLineIndex !== -1) {
        const stackTrace = stackLines.slice(firstAtLineIndex).join("\n");
        message = message + "\n\nStack trace:\n" + stackTrace;
      }
    }
  }
  if (message) {
    error(message);
  }
}
function errorOnce(msg5) {
  if (!errors[msg5]) {
    errors[msg5] = true;
    error(msg5);
    return true;
  }
  return false;
}
function warnOnce(msg5) {
  if (!warnings[msg5]) {
    warnings[msg5] = true;
    warn(msg5);
  }
}
function debugOnce(msg5) {
  if (!debugs[msg5]) {
    debugs[msg5] = true;
    debug(msg5);
  }
}
function applyMsgOptions(msg5, options) {
  if (options.indent) {
    const pad = " ".repeat(options.indent);
    msg5 = lines(msg5).map((msg6) => pad + msg6).join("\n");
  }
  if (options.bold) {
    msg5 = bold3(msg5);
  }
  if (options.dim) {
    msg5 = dim2(msg5);
  }
  if (options.format) {
    msg5 = options.format(msg5);
  }
  if (options.stripAnsiCode) {
    msg5 = stripAnsiCode(msg5);
  }
  return msg5;
}
function parseFormat(format14) {
  if (format14) {
    format14 = format14.toLowerCase();
    switch (format14) {
      case "plain":
      case "json-stream":
        return format14;
      default:
        return "plain";
    }
  } else {
    return "plain";
  }
}
function parseLevel(level) {
  const lvl = levelMap[level.toLowerCase()];
  if (lvl) {
    return lvl;
  } else {
    return "WARN";
  }
}
var currentLogLevel, StdErrOutputHandler, LogEventsHandler, LogFileHandler, errors, warnings, debugs, levelMap;
var init_log2 = __esm({
  "core/log.ts"() {
    init_fs();
    init_path();
    init_colors2();
    init_log();
    init_base_handler();
    init_file_handler();
    init_env();
    init_text2();
    init_log();
    init_error2();
    init_cleanup();
    init_process();
    init_resources2();
    init_json();
    init_github();
    currentLogLevel = "INFO";
    StdErrOutputHandler = class extends BaseHandler {
      format(logRecord, prefix = true) {
        const options = {
          newline: true,
          colorize: true,
          ...logRecord.args[0]
        };
        let msg5 = super.format(logRecord);
        if (prefix && logRecord.level >= LogLevels.WARN) {
          msg5 = `${logRecord.levelName}: ${msg5}`;
        }
        switch (logRecord.level) {
          case LogLevels.INFO:
          case LogLevels.DEBUG:
            msg5 = applyMsgOptions(msg5, options);
            break;
          case LogLevels.WARN:
            if (options.colorize) {
              msg5 = yellow3(msg5);
            }
            break;
          case LogLevels.ERROR:
            if (options.colorize) {
              msg5 = brightRed2(msg5);
            }
            break;
          case LogLevels.CRITICAL:
            if (options.colorize) {
              msg5 = bold3(red3(msg5));
            }
            break;
          default:
            break;
        }
        if (options.newline) {
          msg5 = msg5 + "\n";
        }
        return msg5;
      }
      log(msg5) {
        const encoder4 = new TextEncoder();
        const data3 = encoder4.encode(msg5);
        let bytesWritten = 0;
        while (bytesWritten < data3.length) {
          const remaining = data3.subarray(bytesWritten);
          const written = Deno.stderr.writeSync(remaining);
          if (written === 0) {
            break;
          }
          bytesWritten += written;
        }
      }
    };
    LogEventsHandler = class _LogEventsHandler extends StdErrOutputHandler {
      constructor(levelName) {
        super(levelName, {
          formatter: (({ msg: msg5 }) => `${msg5}`)
        });
      }
      handle(logRecord) {
        if (this.level > logRecord.level) return;
        _LogEventsHandler.handlers_.forEach(
          (handler) => handler(logRecord, super.format(logRecord, false))
        );
      }
      static onLog(handler) {
        _LogEventsHandler.handlers_.push(handler);
      }
      static handlers_ = new Array();
    };
    LogFileHandler = class extends FileHandler {
      logger;
      constructor(levelName, options) {
        super(levelName, options);
        this.logger = new FileHandler(levelName, options);
        this.logger.setup();
        this.msgFormat = options.format;
        this.logger.formatter = this.format.bind(this);
      }
      msgFormat;
      flush() {
        this.logger.flush();
      }
      format(logRecord) {
        if (logRecord.msg.startsWith("\r")) {
          return "";
        }
        if (this.msgFormat === void 0 || this.msgFormat === "plain") {
          const options = {
            newline: true,
            ...logRecord.args[0],
            bold: false,
            dim: false,
            stripAnsiCode: true,
            format: void 0
          };
          let msg5 = applyMsgOptions(logRecord.msg, options);
          if (options.newline) {
            msg5 = msg5 + "\n";
          }
          if (logRecord.level >= LogLevels.WARN) {
            return `(${logRecord.levelName}) ${msg5}`;
          } else {
            return msg5;
          }
        } else {
          return JSON.stringify(logRecord, void 0, 0) + "\n";
        }
      }
      async log(msg5) {
        if (msg5 !== "") {
          this.logger.log(msg5);
          this.flush();
        }
      }
    };
    errors = {};
    warnings = {};
    debugs = {};
    levelMap = {
      debug: "DEBUG",
      info: "INFO",
      warning: "WARN",
      warn: "WARN",
      error: "ERROR",
      critical: "CRITICAL"
    };
  }
});

// https://jsr.io/@std/dotenv/0.225.3/parse.ts
function expandCharacters(str3) {
  const charactersMap = {
    "\\n": "\n",
    "\\r": "\r",
    "\\t": "	"
  };
  return str3.replace(
    /\\([nrt])/g,
    ($1) => charactersMap[$1] ?? ""
  );
}
function expand(str3, variablesMap) {
  if (RE_EXPAND_VALUE.test(str3)) {
    return expand(
      str3.replace(RE_EXPAND_VALUE, function(...params) {
        const {
          inBrackets,
          inBracketsDefault,
          notInBrackets,
          notInBracketsDefault
        } = params[params.length - 1];
        const expandValue = inBrackets || notInBrackets;
        const defaultValue = inBracketsDefault || notInBracketsDefault;
        let value = variablesMap[expandValue];
        if (value === void 0) {
          value = Deno.env.get(expandValue);
        }
        return value === void 0 ? expand(defaultValue, variablesMap) : value;
      }),
      variablesMap
    );
  } else {
    return str3;
  }
}
function parse6(text) {
  const env2 = {};
  let match;
  const keysForExpandCheck = [];
  while ((match = RE_KEY_VALUE.exec(text)) !== null) {
    const { key, interpolated, notInterpolated, unquoted } = match?.groups;
    if (!RE_VALID_KEY.test(key)) {
      console.warn(
        `Ignored the key "${key}" as it is not a valid identifier: The key need to match the pattern /^[a-zA-Z_][a-zA-Z0-9_]*$/.`
      );
      continue;
    }
    if (unquoted) {
      keysForExpandCheck.push(key);
    }
    env2[key] = typeof notInterpolated === "string" ? notInterpolated : typeof interpolated === "string" ? expandCharacters(interpolated) : unquoted.trim();
  }
  const variablesMap = { ...env2 };
  keysForExpandCheck.forEach((key) => {
    env2[key] = expand(env2[key], variablesMap);
  });
  return env2;
}
var RE_KEY_VALUE, RE_VALID_KEY, RE_EXPAND_VALUE;
var init_parse4 = __esm({
  "https://jsr.io/@std/dotenv/0.225.3/parse.ts"() {
    RE_KEY_VALUE = /^\s*(?:export\s+)?(?<key>[^\s=#]+?)\s*=[\ \t]*('\r?\n?(?<notInterpolated>(.|\r\n|\n)*?)\r?\n?'|"\r?\n?(?<interpolated>(.|\r\n|\n)*?)\r?\n?"|(?<unquoted>[^\r\n#]*)) *#*.*$/gm;
    RE_VALID_KEY = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
    RE_EXPAND_VALUE = /(\${(?<inBrackets>.+?)(\:-(?<inBracketsDefault>.+))?}|(?<!\\)\$(?<notInBrackets>\w+)(\:-(?<notInBracketsDefault>.+))?)/g;
  }
});

// https://jsr.io/@std/dotenv/0.225.3/stringify.ts
function stringify2(object) {
  const lines2 = [];
  for (const [key, value] of Object.entries(object)) {
    let quote;
    let escapedValue = value ?? "";
    if (key.startsWith("#")) {
      console.warn(
        `key starts with a '#' indicates a comment and is ignored: '${key}'`
      );
      continue;
    } else if (escapedValue.includes("\n") || escapedValue.includes("'")) {
      escapedValue = escapedValue.replaceAll("\n", "\\n");
      quote = `"`;
    } else if (escapedValue.match(/\W/)) {
      quote = "'";
    }
    if (quote) {
      escapedValue = escapedValue.replaceAll(quote, `\\${quote}`);
      escapedValue = `${quote}${escapedValue}${quote}`;
    }
    const line = `${key}=${escapedValue}`;
    lines2.push(line);
  }
  return lines2.join("\n");
}
var init_stringify = __esm({
  "https://jsr.io/@std/dotenv/0.225.3/stringify.ts"() {
  }
});

// https://jsr.io/@std/dotenv/0.225.3/mod.ts
async function load4(options = {}) {
  const {
    envPath = ".env",
    export: _export = false
  } = options;
  const conf = envPath ? await parseFile(envPath) : {};
  if (_export) {
    for (const [key, value] of Object.entries(conf)) {
      if (Deno.env.get(key) !== void 0) continue;
      Deno.env.set(key, value);
    }
  }
  return conf;
}
async function parseFile(filepath) {
  try {
    return parse6(await Deno.readTextFile(filepath));
  } catch (e5) {
    if (e5 instanceof Deno.errors.NotFound) return {};
    throw e5;
  }
}
var init_mod5 = __esm({
  "https://jsr.io/@std/dotenv/0.225.3/mod.ts"() {
    init_parse4();
    init_stringify();
    init_parse4();
  }
});

// quarto-core/profile.ts
function activeProfiles() {
  return readProfile(Deno.env.get(kQuartoProfile));
}
function readProfile(profile) {
  if (profile) {
    return profile.split(/[ ,]+/);
  } else {
    return [];
  }
}
function setProfileFromArg(args) {
  if (args.profile) {
    Deno.env.set(kQuartoProfile, args.profile);
    return true;
  } else {
    return false;
  }
}
function appendProfileArg(cmd) {
  return cmd.option(
    "--profile",
    "Active project profile(s)",
    {
      global: true
    }
  );
}
var kQuartoProfile;
var init_profile = __esm({
  "quarto-core/profile.ts"() {
    kQuartoProfile = "QUARTO_PROFILE";
  }
});

// core/temp.ts
function initSessionTempDir() {
  const tmpEnv = Deno.env.get("TMPDIR");
  if (tmpEnv) {
    try {
      if (!existsSync2(tmpEnv)) {
        ensureDirSync(tmpEnv);
      }
    } catch (err2) {
      if (!(err2 instanceof Error)) throw err2;
      if (err2.message) {
        debug("Error attempting to create TMPDIR: " + err2.message);
      }
    }
  }
  tempDir = Deno.makeTempDirSync({ prefix: "quarto-session" });
}
function cleanupSessionTempDir() {
  if (tempContext) {
    tempContext.cleanup();
    tempContext = void 0;
  }
  if (tempDir) {
    removeIfExists(tempDir);
    tempDir = void 0;
  }
}
function globalTempContext() {
  if (tempContext === void 0) {
    tempContext = createTempContext();
  }
  return tempContext;
}
function createTempContext(options) {
  if (options?.dir) {
    ensureDirSync(options?.dir);
  }
  let dir = Deno.makeTempDirSync({
    dir: tempDir,
    ...options
  });
  const tempContextCleanupHandlers = [];
  const result2 = {
    baseDir: dir,
    createFileFromString: (content, options2) => {
      const file = result2.createFile(options2);
      Deno.writeTextFileSync(file, content);
      return file;
    },
    createFile: (options2) => {
      return Deno.makeTempFileSync({ ...options2, dir });
    },
    createDir: (options2) => {
      return Deno.makeTempDirSync({ ...options2, dir });
    },
    cleanup: () => {
      if (dir) {
        for (let i6 = tempContextCleanupHandlers.length - 1; i6 >= 0; i6--) {
          const handler = tempContextCleanupHandlers[i6];
          try {
            handler();
          } catch (error2) {
            info("Error occurred during tempContext handler cleanup: " + error2);
          }
        }
        safeRemoveIfExists(dir);
        dir = void 0;
      }
    },
    onCleanup(handler) {
      tempContextCleanupHandlers.push(handler);
    }
  };
  return result2;
}
var tempDir, tempContext;
var init_temp = __esm({
  "core/temp.ts"() {
    init_log();
    init_path();
    init_fs();
    init_path2();
    init_platform();
  }
});

// quarto-core/dotenv.ts
async function dotenvQuartoProfile(projectDir) {
  const conf1 = await load4({
    envPath: join4(projectDir, kQuartoEnv)
  });
  const conf2 = await load4({
    envPath: join4(projectDir, kQuartoEnvLocal)
  });
  return conf2[kQuartoProfile] || conf1[kQuartoProfile] || "";
}
async function dotenvSetVariables(projectDir) {
  dotenvVariablesSet.forEach(Deno.env.delete);
  dotenvVariablesSet.splice(0, dotenvVariablesSet.length);
  const dotenvFiles = [
    join4(projectDir, kQuartoEnv),
    ...activeProfiles().reverse().map(
      (profile) => join4(projectDir, `_environment-${profile}`)
    ),
    join4(projectDir, kQuartoEnvLocal)
  ].filter(safeExistsSync).reverse();
  const dotenvVariablesDefined = {};
  for (const dotenvFile of dotenvFiles) {
    const conf = await load4({ envPath: dotenvFile });
    for (const key in conf) {
      if (Deno.env.get(key) === void 0) {
        Deno.env.set(key, conf[key]);
        dotenvVariablesSet.push(key);
      }
      if (dotenvVariablesDefined[key] === void 0) {
        dotenvVariablesDefined[key] = conf[key];
      }
    }
  }
  const dotenvRequired = join4(projectDir, kQuartoEnvRequired);
  if (existsSync2(dotenvRequired)) {
    const definedEnvTempPath = globalTempContext().createFile({
      suffix: ".yml"
    });
    Deno.writeTextFileSync(
      definedEnvTempPath,
      stringify2(dotenvVariablesDefined)
    );
    await load4({
      envPath: definedEnvTempPath
    });
  }
  if (prevDotenvVariablesDefined && !isEqual(dotenvVariablesDefined, prevDotenvVariablesDefined)) {
    fireDotenvChanged();
  }
  prevDotenvVariablesDefined = dotenvVariablesDefined;
  return dotenvFiles;
}
function fireDotenvChanged() {
  listeners.forEach((listener) => listener());
}
function onDotenvChanged(listener) {
  listeners.push(listener);
}
var kQuartoEnv, kQuartoEnvLocal, kQuartoEnvRequired, dotenvVariablesSet, prevDotenvVariablesDefined, listeners;
var init_dotenv = __esm({
  "quarto-core/dotenv.ts"() {
    init_mod5();
    init_stringify();
    init_path();
    init_path2();
    init_lodash();
    init_temp();
    init_fs();
    init_profile();
    kQuartoEnv = "_environment";
    kQuartoEnvLocal = `${kQuartoEnv}.local`;
    kQuartoEnvRequired = `${kQuartoEnv}.required`;
    dotenvVariablesSet = [];
    listeners = new Array();
  }
});

// project/project-profile.ts
async function initializeProfileConfig(dir, config2, schema4) {
  const firstRun = baseQuartoProfile === void 0;
  if (firstRun) {
    baseQuartoProfile = Deno.env.get(kQuartoProfile) || "";
  }
  const profileConfig = isObject(config2[kQuartoProfileConfig]) ? config2[kQuartoProfileConfig] : void 0;
  delete config2[kQuartoProfileConfig];
  let quartoProfile = baseQuartoProfile || await dotenvQuartoProfile(dir) || await localConfigQuartoProfile(dir, schema4) || "";
  if (!quartoProfile) {
    if (Array.isArray(profileConfig?.default)) {
      quartoProfile = profileConfig.default.map((value) => String(value)).join(",");
    } else if (typeof profileConfig?.default === "string") {
      quartoProfile = profileConfig.default;
    }
  }
  const active = readProfile(quartoProfile);
  if (active.length === 0) {
    if (Deno.env.get("RSTUDIO_PRODUCT") === "CONNECT") {
      active.push("connect");
    }
  }
  const groups = readProfileGroups(profileConfig);
  for (const group of groups) {
    if (!group.some((name2) => active.includes(name2))) {
      active.push(group[0]);
    }
  }
  const updatedQuartoProfile = active.join(",");
  if (!firstRun) {
    if (Deno.env.get(kQuartoProfile) !== updatedQuartoProfile) {
      fireActiveProfileChanged(updatedQuartoProfile);
    }
  }
  Deno.env.set(kQuartoProfile, active.join(","));
  return await mergeProfiles(
    dir,
    config2,
    schema4
  );
}
function fireActiveProfileChanged(profile) {
  listeners2.forEach((listener) => listener(profile));
}
function onActiveProfileChanged(listener) {
  listeners2.push(listener);
}
async function localConfigQuartoProfile(dir, schema4) {
  const localConfigPath = localProjectConfigFile(dir);
  if (localConfigPath) {
    const yaml = await readAndValidateYamlFromFile(
      localConfigPath,
      schema4,
      `Validation of configuration profile file ${basename4(localConfigPath)} failed.`,
      "{}"
    );
    const profile = yaml[kQuartoProfileConfig];
    if (Array.isArray(profile?.default)) {
      return profile?.default.join(",");
    } else if (typeof profile?.default === "string") {
      return profile?.default;
    } else {
      return void 0;
    }
  } else {
    return void 0;
  }
}
async function mergeProfiles(dir, config2, schema4) {
  const files = [];
  const mergeProfile = async (profilePath) => {
    try {
      const yaml = await readAndValidateYamlFromFile(
        profilePath,
        schema4,
        `Validation of configuration profile file ${basename4(profilePath)} failed.`,
        "{}"
      );
      config2 = mergeProjectMetadata(config2, yaml);
      files.push(profilePath);
    } catch (e5) {
      error(
        "\nError reading configuration profile file from " + basename4(profilePath) + "\n"
      );
      throw e5;
    }
  };
  for (const profileName of activeProfiles().reverse()) {
    const profilePath = [".yml", ".yaml"].map((ext) => join4(dir, `_quarto-${profileName}${ext}`)).find(safeExistsSync);
    if (profilePath) {
      await mergeProfile(profilePath);
    }
  }
  const localConfigPath = localProjectConfigFile(dir);
  if (localConfigPath) {
    await mergeProfile(localConfigPath);
  }
  return { config: config2, files };
}
function localProjectConfigFile(dir) {
  return [".yml", ".yaml"].map((ext) => join4(dir, `_quarto${ext}.local`)).find(safeExistsSync);
}
function readProfileGroups(profileConfig) {
  const groups = [];
  const configGroup = profileConfig?.group;
  if (Array.isArray(configGroup)) {
    if (configGroup.every((value) => typeof value === "string")) {
      groups.push(configGroup);
    } else if (configGroup.every(Array.isArray)) {
      groups.push(...configGroup);
    }
  }
  return groups;
}
var kQuartoProfileConfig, baseQuartoProfile, listeners2;
var init_project_profile = __esm({
  "project/project-profile.ts"() {
    init_log();
    init_path();
    init_lodash();
    init_validated_yaml2();
    init_metadata();
    init_path2();
    init_profile();
    init_dotenv();
    kQuartoProfileConfig = "profile";
    listeners2 = new Array();
  }
});

// core/quarto.ts
function previewMonitorResources(cleanup2) {
  onActiveProfileChanged(() => {
    terminatePreview("active profile changed", cleanup2);
  });
  onDotenvChanged(() => {
    terminatePreview("environment variables changed", cleanup2);
  });
  if (quartoConfig.isDebug()) {
    const srcDir = quartoSrcDir();
    const watcher = Deno.watchFs([srcDir], { recursive: true });
    const watchForChanges = async () => {
      for await (const event of watcher) {
        if (event.paths.some(
          (path3) => extname4(path3).toLowerCase().startsWith(".ts")
        )) {
          terminatePreview("quarto src code changed", cleanup2);
        }
      }
    };
    watchForChanges();
  }
}
function terminatePreview(reason, cleanup2) {
  info(
    bold3(
      blue3(`
${reason}: preview terminating
`)
    )
  );
  if (cleanup2) {
    cleanup2();
  }
  exitWithCleanup(1);
}
function quartoSrcDir() {
  return normalizePath(join4(quartoConfig.binPath(), "../../../src"));
}
var kLocalDevelopment, dotenvConfig, quartoConfig;
var init_quarto = __esm({
  "core/quarto.ts"() {
    init_fs();
    init_path();
    init_log();
    init_colors2();
    init_mod5();
    init_env();
    init_cleanup();
    init_project_profile();
    init_dotenv();
    init_path2();
    init_platform();
    kLocalDevelopment = "99.9.9";
    quartoConfig = {
      binPath: () => getenv("QUARTO_BIN_PATH"),
      toolsPath: () => join4(getenv("QUARTO_BIN_PATH"), "tools"),
      sharePath: () => getenv("QUARTO_SHARE_PATH"),
      isDebug: () => getenv("QUARTO_DEBUG", "false") === "true",
      version: () => {
        const forceVersion = getenv("QUARTO_FORCE_VERSION", "");
        if (forceVersion !== "") {
          return forceVersion;
        }
        const versionPath = join4(getenv("QUARTO_SHARE_PATH"), "version");
        if (existsSync2(versionPath)) {
          return Deno.readTextFileSync(versionPath);
        } else {
          return kLocalDevelopment;
        }
      },
      cliPath: () => {
        const binPath = quartoConfig.binPath();
        if (!isWindows4) {
          return join4(binPath, "quarto");
        }
        const cliPath = join4(binPath, "quarto.exe");
        if (safeExistsSync(cliPath)) {
          return cliPath;
        }
        return join4(binPath, "quarto.cmd");
      },
      dotenv: async (forceReload) => {
        if (forceReload || !dotenvConfig) {
          const defaultOptions3 = {
            envPath: join4(quartoConfig.sharePath(), "env", "env.defaults")
          };
          dotenvConfig = await load4(defaultOptions3);
          const options = {
            envPath: quartoConfig.isDebug() ? join4(quartoConfig.sharePath(), "..", "..", ".env") : null
          };
          const otherConfig = await load4(options);
          for (const key of Object.keys(otherConfig)) {
            dotenvConfig[key] = otherConfig[key];
          }
        }
        return dotenvConfig;
      }
    };
  }
});

// core/registry.ts
async function registryReadString(root, key, value) {
  if (Array.isArray(root)) {
    for (const r5 of root) {
      const val = await registryReadString(r5, key, value);
      if (val !== void 0) {
        return val;
      }
    }
    return void 0;
  }
  const kTypeString = "REG_SZ";
  const cmd = [
    "reg",
    "query",
    `${root}\\${key}`,
    "/v",
    value
  ];
  let result2;
  try {
    result2 = await execProcess({
      cmd: cmd[0],
      args: cmd.slice(1),
      stdout: "piped",
      stderr: "null"
    });
  } catch (e5) {
    debugOnce(`Fail to read from registry: ${e5}`);
    return void 0;
  }
  if (result2.success && result2.stdout) {
    const typePos = result2.stdout?.indexOf(kTypeString);
    if (typePos !== -1) {
      return result2.stdout.substring(typePos + kTypeString.length).trim();
    }
  }
  return void 0;
}
var kHKeyCurrentUser, kHKeyLocalMachine;
var init_registry = __esm({
  "core/registry.ts"() {
    init_process();
    init_log2();
    kHKeyCurrentUser = "HKCU";
    kHKeyLocalMachine = "HKLM";
  }
});

// core/resources.ts
function resourcePath(resource) {
  const sharePath = quartoConfig.sharePath();
  if (resource) {
    return join4(sharePath, resource);
  } else {
    return sharePath;
  }
}
function formatResourcePath(format14, resource) {
  return join4(resourcePath("formats"), format14, resource);
}
function architectureToolsPath(binary3) {
  const arch3 = Deno.build.arch;
  const archBinaryPath = join4(arch3, binary3);
  return toolsPath(binary3, archBinaryPath);
}
function toolsPath(binary3, defaultPath) {
  const displayWarning = () => {
    warnOnce(
      `Specified ${binaryEnvKey} does not exist, using built in ${binary3}`
    );
  };
  const binaryEnvKey = `QUARTO_${binary3.toUpperCase()}`;
  const binaryPath = Deno.env.get(binaryEnvKey);
  if (binaryPath) {
    if (!existsSync2(binaryPath)) {
      if (isWindows4) {
        const exeExists = !binary3.endsWith(".exe") || [binary3 + ".exe"].some((path3) => {
          return existsSync2(path3);
        });
        if (!exeExists) {
          displayWarning();
        }
      } else {
        displayWarning();
      }
    } else {
      if (Deno.statSync(binaryPath).isFile) {
        return binaryPath;
      } else {
        const fullPath = join4(binaryPath, binary3);
        if (!existsSync2(fullPath)) {
          displayWarning();
        } else {
          return fullPath;
        }
      }
    }
  }
  return join4(quartoConfig.toolsPath(), defaultPath || binary3);
}
function pandocBinaryPath() {
  return isWindows4 ? toolsPath("pandoc") : architectureToolsPath("pandoc");
}
async function rBinaryPath(binary3, forceLookup = false) {
  if (forceLookup) {
    _r_binary_path.delete(binary3);
  }
  const v4 = _r_binary_path.get(binary3);
  if (v4) {
    return v4;
  }
  const setPath = (path4) => {
    _r_binary_path.set(binary3, path4);
    return path4;
  };
  debug(`-- Searching for R binary --`);
  const quartoR = Deno.env.get("QUARTO_R");
  debug(`Looking for '${binary3}' in QUARTO_R: ${quartoR}`);
  if (quartoR) {
    if (existsSync2(quartoR)) {
      const rBinDir = Deno.statSync(quartoR).isDirectory ? quartoR : dirname4(quartoR);
      debug(`Found in ${rBinDir}`);
      return join4(rBinDir, binary3);
    } else {
      warnOnce(`Specified QUARTO_R '${quartoR}' does not exist.`);
    }
  }
  const rHome = Deno.env.get("R_HOME");
  debug(`Looking for '${binary3}' in R_HOME: ${rHome}`);
  if (rHome) {
    let rHomeBin = join4(rHome, "bin", isWindows4 ? binary3 + ".exe" : binary3);
    if (safeExistsSync(rHomeBin)) {
      debug(`Found in ${rHomeBin}`);
      return setPath(rHomeBin);
    }
    if (isWindows4) {
      rHomeBin = join4(rHome, "bin", "x64", binary3);
      if (safeExistsSync(rHomeBin)) {
        debug(`Found in ${rHomeBin}`);
        return setPath(rHomeBin);
      }
    }
  }
  debug(`Looking for '${binary3}' in PATH.`);
  const path3 = await which(binary3);
  if (path3) {
    debug(`Found in PATH at ${path3}`);
    return setPath(path3);
  }
  if (isWindows4) {
    debug(`Looking for '${binary3}' in Windows Registry.`);
    const version4 = await registryReadString(
      [kHKeyCurrentUser, kHKeyLocalMachine],
      "Software\\R-core\\R",
      "Current Version"
    );
    if (version4) {
      const installPath = await registryReadString(
        [kHKeyCurrentUser, kHKeyLocalMachine],
        `Software\\R-core\\R\\${version4}`,
        "InstallPath"
      );
      if (installPath) {
        debug(`Found in Windows Registry at ${join4(installPath, "bin")}`);
        return setPath(join4(installPath, "bin", binary3));
      }
    }
    debug(`Looking for '${binary3}' in Windows PROGRAMFILES.`);
    const progFiles = Deno.env.get("programfiles");
    if (progFiles) {
      for (const entry of Deno.readDirSync(progFiles)) {
        if (entry.isDirectory && entry.name === "R") {
          for (const walk5 of walkSync(join4(progFiles, "R"))) {
            if (walk5.isDirectory && walk5.name === "bin") {
              debug(`Found ${walk5.path}`);
              return setPath(join4(walk5.path, binary3));
            }
          }
        }
      }
    }
  }
  debug(
    `Quarto did not find ${binary3} and will try to use it directly from the path.`
  );
  return setPath(binary3);
}
function projectTypeResourcePath(projectType2) {
  return resourcePath(join4("projects", projectType2));
}
function textHighlightThemePath(theme, style) {
  const names = [
    `${theme}-${style === "dark" ? kDarkSuffix : kLightSuffix}`,
    theme
  ];
  const themePath = names.map((name2) => {
    return resourcePath(join4("pandoc", "highlight-styles", `${name2}.theme`));
  }).find((path3) => existsSync2(path3));
  return themePath;
}
var _r_binary_path, kDarkSuffix, kLightSuffix;
var init_resources2 = __esm({
  "core/resources.ts"() {
    init_log();
    init_fs();
    init_path();
    init_log2();
    init_path2();
    init_quarto();
    init_registry();
    init_platform();
    _r_binary_path = /* @__PURE__ */ new Map();
    kDarkSuffix = "dark";
    kLightSuffix = "light";
  }
});

// core/render.ts
function inputFilesDir(input) {
  const [_3, stem] = dirAndStem(input);
  return stem + "_files";
}
function figuresDir(pandocTo) {
  if (pandocTo === "html4") {
    pandocTo = "html";
  }
  pandocTo = (pandocTo || "html").replace(/[\+\-].*$/, "");
  return "figure-" + pandocTo;
}
function isServerShiny(format14) {
  const server = format14?.metadata[kServer];
  return server?.["type"] === "shiny";
}
function isServerShinyPython(format14, engine) {
  return isServerShiny(format14) && engine === kJupyterEngine;
}
function isServerShinyKnitr(format14, engine) {
  return isServerShiny(format14) && engine === kKnitrEngine;
}
function formatOutputFile(format14) {
  let outputFile5 = format14.pandoc[kOutputFile];
  if (outputFile5) {
    if (format14.render[kOutputExt]) {
      const existingExtension = extname4(outputFile5);
      if (!existingExtension || existingExtension.substring(1) !== format14.render[kOutputExt]) {
        outputFile5 = `${outputFile5}.${format14.render[kOutputExt]}`;
      }
    }
  }
  return outputFile5;
}
var init_render = __esm({
  "core/render.ts"() {
    init_constants6();
    init_types3();
    init_path2();
    init_path();
  }
});

// https://deno.land/x/semver@v1.4.0/mod.ts
function parse7(version4, optionsOrLoose) {
  if (!optionsOrLoose || typeof optionsOrLoose !== "object") {
    optionsOrLoose = {
      loose: !!optionsOrLoose,
      includePrerelease: false
    };
  }
  if (version4 instanceof SemVer) {
    return version4;
  }
  if (typeof version4 !== "string") {
    return null;
  }
  if (version4.length > MAX_LENGTH) {
    return null;
  }
  const r5 = optionsOrLoose.loose ? re[LOOSE] : re[FULL];
  if (!r5.test(version4)) {
    return null;
  }
  try {
    return new SemVer(version4, optionsOrLoose);
  } catch (er) {
    return null;
  }
}
function compareIdentifiers(a5, b3) {
  const anum = numeric.test(a5);
  const bnum = numeric.test(b3);
  if (a5 === null || b3 === null) throw "Comparison against null invalid";
  if (anum && bnum) {
    a5 = +a5;
    b3 = +b3;
  }
  return a5 === b3 ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a5 < b3 ? -1 : 1;
}
function compare(v1, v22, optionsOrLoose) {
  return new SemVer(v1, optionsOrLoose).compare(new SemVer(v22, optionsOrLoose));
}
function gt(v1, v22, optionsOrLoose) {
  return compare(v1, v22, optionsOrLoose) > 0;
}
function lt(v1, v22, optionsOrLoose) {
  return compare(v1, v22, optionsOrLoose) < 0;
}
function eq(v1, v22, optionsOrLoose) {
  return compare(v1, v22, optionsOrLoose) === 0;
}
function neq(v1, v22, optionsOrLoose) {
  return compare(v1, v22, optionsOrLoose) !== 0;
}
function gte(v1, v22, optionsOrLoose) {
  return compare(v1, v22, optionsOrLoose) >= 0;
}
function lte(v1, v22, optionsOrLoose) {
  return compare(v1, v22, optionsOrLoose) <= 0;
}
function cmp(v1, operator, v22, optionsOrLoose) {
  switch (operator) {
    case "===":
      if (typeof v1 === "object") v1 = v1.version;
      if (typeof v22 === "object") v22 = v22.version;
      return v1 === v22;
    case "!==":
      if (typeof v1 === "object") v1 = v1.version;
      if (typeof v22 === "object") v22 = v22.version;
      return v1 !== v22;
    case "":
    case "=":
    case "==":
      return eq(v1, v22, optionsOrLoose);
    case "!=":
      return neq(v1, v22, optionsOrLoose);
    case ">":
      return gt(v1, v22, optionsOrLoose);
    case ">=":
      return gte(v1, v22, optionsOrLoose);
    case "<":
      return lt(v1, v22, optionsOrLoose);
    case "<=":
      return lte(v1, v22, optionsOrLoose);
    default:
      throw new TypeError("Invalid operator: " + operator);
  }
}
function testSet(set3, version4, options) {
  for (let i6 = 0; i6 < set3.length; i6++) {
    if (!set3[i6].test(version4)) {
      return false;
    }
  }
  if (version4.prerelease.length && !options.includePrerelease) {
    for (let i6 = 0; i6 < set3.length; i6++) {
      if (set3[i6].semver === ANY) {
        continue;
      }
      if (set3[i6].semver.prerelease.length > 0) {
        const allowed = set3[i6].semver;
        if (allowed.major === version4.major && allowed.minor === version4.minor && allowed.patch === version4.patch) {
          return true;
        }
      }
    }
    return false;
  }
  return true;
}
function isSatisfiable(comparators, options) {
  let result2 = true;
  const remainingComparators = comparators.slice();
  let testComparator = remainingComparators.pop();
  while (result2 && remainingComparators.length) {
    result2 = remainingComparators.every((otherComparator) => {
      return testComparator?.intersects(otherComparator, options);
    });
    testComparator = remainingComparators.pop();
  }
  return result2;
}
function parseComparator(comp, options) {
  comp = replaceCarets(comp, options);
  comp = replaceTildes(comp, options);
  comp = replaceXRanges(comp, options);
  comp = replaceStars(comp, options);
  return comp;
}
function isX(id) {
  return !id || id.toLowerCase() === "x" || id === "*";
}
function replaceTildes(comp, options) {
  return comp.trim().split(/\s+/).map((comp2) => replaceTilde(comp2, options)).join(" ");
}
function replaceTilde(comp, options) {
  const r5 = options.loose ? re[TILDELOOSE] : re[TILDE];
  return comp.replace(
    r5,
    (_3, M3, m4, p5, pr) => {
      let ret;
      if (isX(M3)) {
        ret = "";
      } else if (isX(m4)) {
        ret = ">=" + M3 + ".0.0 <" + (+M3 + 1) + ".0.0";
      } else if (isX(p5)) {
        ret = ">=" + M3 + "." + m4 + ".0 <" + M3 + "." + (+m4 + 1) + ".0";
      } else if (pr) {
        ret = ">=" + M3 + "." + m4 + "." + p5 + "-" + pr + " <" + M3 + "." + (+m4 + 1) + ".0";
      } else {
        ret = ">=" + M3 + "." + m4 + "." + p5 + " <" + M3 + "." + (+m4 + 1) + ".0";
      }
      return ret;
    }
  );
}
function replaceCarets(comp, options) {
  return comp.trim().split(/\s+/).map((comp2) => replaceCaret(comp2, options)).join(" ");
}
function replaceCaret(comp, options) {
  const r5 = options.loose ? re[CARETLOOSE] : re[CARET];
  return comp.replace(r5, (_3, M3, m4, p5, pr) => {
    let ret;
    if (isX(M3)) {
      ret = "";
    } else if (isX(m4)) {
      ret = ">=" + M3 + ".0.0 <" + (+M3 + 1) + ".0.0";
    } else if (isX(p5)) {
      if (M3 === "0") {
        ret = ">=" + M3 + "." + m4 + ".0 <" + M3 + "." + (+m4 + 1) + ".0";
      } else {
        ret = ">=" + M3 + "." + m4 + ".0 <" + (+M3 + 1) + ".0.0";
      }
    } else if (pr) {
      if (M3 === "0") {
        if (m4 === "0") {
          ret = ">=" + M3 + "." + m4 + "." + p5 + "-" + pr + " <" + M3 + "." + m4 + "." + (+p5 + 1);
        } else {
          ret = ">=" + M3 + "." + m4 + "." + p5 + "-" + pr + " <" + M3 + "." + (+m4 + 1) + ".0";
        }
      } else {
        ret = ">=" + M3 + "." + m4 + "." + p5 + "-" + pr + " <" + (+M3 + 1) + ".0.0";
      }
    } else {
      if (M3 === "0") {
        if (m4 === "0") {
          ret = ">=" + M3 + "." + m4 + "." + p5 + " <" + M3 + "." + m4 + "." + (+p5 + 1);
        } else {
          ret = ">=" + M3 + "." + m4 + "." + p5 + " <" + M3 + "." + (+m4 + 1) + ".0";
        }
      } else {
        ret = ">=" + M3 + "." + m4 + "." + p5 + " <" + (+M3 + 1) + ".0.0";
      }
    }
    return ret;
  });
}
function replaceXRanges(comp, options) {
  return comp.split(/\s+/).map((comp2) => replaceXRange(comp2, options)).join(" ");
}
function replaceXRange(comp, options) {
  comp = comp.trim();
  const r5 = options.loose ? re[XRANGELOOSE] : re[XRANGE];
  return comp.replace(r5, (ret, gtlt, M3, m4, p5, pr) => {
    const xM = isX(M3);
    const xm = xM || isX(m4);
    const xp = xm || isX(p5);
    const anyX = xp;
    if (gtlt === "=" && anyX) {
      gtlt = "";
    }
    if (xM) {
      if (gtlt === ">" || gtlt === "<") {
        ret = "<0.0.0";
      } else {
        ret = "*";
      }
    } else if (gtlt && anyX) {
      if (xm) {
        m4 = 0;
      }
      p5 = 0;
      if (gtlt === ">") {
        gtlt = ">=";
        if (xm) {
          M3 = +M3 + 1;
          m4 = 0;
          p5 = 0;
        } else {
          m4 = +m4 + 1;
          p5 = 0;
        }
      } else if (gtlt === "<=") {
        gtlt = "<";
        if (xm) {
          M3 = +M3 + 1;
        } else {
          m4 = +m4 + 1;
        }
      }
      ret = gtlt + M3 + "." + m4 + "." + p5;
    } else if (xm) {
      ret = ">=" + M3 + ".0.0 <" + (+M3 + 1) + ".0.0";
    } else if (xp) {
      ret = ">=" + M3 + "." + m4 + ".0 <" + M3 + "." + (+m4 + 1) + ".0";
    }
    return ret;
  });
}
function replaceStars(comp, options) {
  return comp.trim().replace(re[STAR], "");
}
function hyphenReplace($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) {
  if (isX(fM)) {
    from = "";
  } else if (isX(fm)) {
    from = ">=" + fM + ".0.0";
  } else if (isX(fp)) {
    from = ">=" + fM + "." + fm + ".0";
  } else {
    from = ">=" + from;
  }
  if (isX(tM)) {
    to = "";
  } else if (isX(tm)) {
    to = "<" + (+tM + 1) + ".0.0";
  } else if (isX(tp)) {
    to = "<" + tM + "." + (+tm + 1) + ".0";
  } else if (tpr) {
    to = "<=" + tM + "." + tm + "." + tp + "-" + tpr;
  } else {
    to = "<=" + to;
  }
  return (from + " " + to).trim();
}
function satisfies(version4, range, optionsOrLoose) {
  try {
    range = new Range2(range, optionsOrLoose);
  } catch (er) {
    return false;
  }
  return range.test(version4);
}
function coerce(version4, optionsOrLoose) {
  if (version4 instanceof SemVer) {
    return version4;
  }
  if (typeof version4 !== "string") {
    return null;
  }
  const match = version4.match(re[COERCE]);
  if (match == null) {
    return null;
  }
  return parse7(
    match[1] + "." + (match[2] || "0") + "." + (match[3] || "0"),
    optionsOrLoose
  );
}
var MAX_LENGTH, MAX_SAFE_COMPONENT_LENGTH, re, src, R, NUMERICIDENTIFIER, NUMERICIDENTIFIERLOOSE, NONNUMERICIDENTIFIER, MAINVERSION, nid, MAINVERSIONLOOSE, nidl, PRERELEASEIDENTIFIER, PRERELEASEIDENTIFIERLOOSE, PRERELEASE, PRERELEASELOOSE, BUILDIDENTIFIER, BUILD, FULL, FULLPLAIN, LOOSEPLAIN, LOOSE, GTLT, XRANGEIDENTIFIERLOOSE, XRANGEIDENTIFIER, XRANGEPLAIN, XRANGEPLAINLOOSE, XRANGE, XRANGELOOSE, COERCE, LONETILDE, TILDETRIM, tildeTrimReplace, TILDE, TILDELOOSE, LONECARET, CARETTRIM, caretTrimReplace, CARET, CARETLOOSE, COMPARATORLOOSE, COMPARATOR, COMPARATORTRIM, comparatorTrimReplace, HYPHENRANGE, HYPHENRANGELOOSE, STAR, SemVer, numeric, ANY, Comparator, Range2, mod_default;
var init_mod6 = __esm({
  "https://deno.land/x/semver@v1.4.0/mod.ts"() {
    MAX_LENGTH = 256;
    MAX_SAFE_COMPONENT_LENGTH = 16;
    re = [];
    src = [];
    R = 0;
    NUMERICIDENTIFIER = R++;
    src[NUMERICIDENTIFIER] = "0|[1-9]\\d*";
    NUMERICIDENTIFIERLOOSE = R++;
    src[NUMERICIDENTIFIERLOOSE] = "[0-9]+";
    NONNUMERICIDENTIFIER = R++;
    src[NONNUMERICIDENTIFIER] = "\\d*[a-zA-Z-][a-zA-Z0-9-]*";
    MAINVERSION = R++;
    nid = src[NUMERICIDENTIFIER];
    src[MAINVERSION] = `(${nid})\\.(${nid})\\.(${nid})`;
    MAINVERSIONLOOSE = R++;
    nidl = src[NUMERICIDENTIFIERLOOSE];
    src[MAINVERSIONLOOSE] = `(${nidl})\\.(${nidl})\\.(${nidl})`;
    PRERELEASEIDENTIFIER = R++;
    src[PRERELEASEIDENTIFIER] = "(?:" + src[NUMERICIDENTIFIER] + "|" + src[NONNUMERICIDENTIFIER] + ")";
    PRERELEASEIDENTIFIERLOOSE = R++;
    src[PRERELEASEIDENTIFIERLOOSE] = "(?:" + src[NUMERICIDENTIFIERLOOSE] + "|" + src[NONNUMERICIDENTIFIER] + ")";
    PRERELEASE = R++;
    src[PRERELEASE] = "(?:-(" + src[PRERELEASEIDENTIFIER] + "(?:\\." + src[PRERELEASEIDENTIFIER] + ")*))";
    PRERELEASELOOSE = R++;
    src[PRERELEASELOOSE] = "(?:-?(" + src[PRERELEASEIDENTIFIERLOOSE] + "(?:\\." + src[PRERELEASEIDENTIFIERLOOSE] + ")*))";
    BUILDIDENTIFIER = R++;
    src[BUILDIDENTIFIER] = "[0-9A-Za-z-]+";
    BUILD = R++;
    src[BUILD] = "(?:\\+(" + src[BUILDIDENTIFIER] + "(?:\\." + src[BUILDIDENTIFIER] + ")*))";
    FULL = R++;
    FULLPLAIN = "v?" + src[MAINVERSION] + src[PRERELEASE] + "?" + src[BUILD] + "?";
    src[FULL] = "^" + FULLPLAIN + "$";
    LOOSEPLAIN = "[v=\\s]*" + src[MAINVERSIONLOOSE] + src[PRERELEASELOOSE] + "?" + src[BUILD] + "?";
    LOOSE = R++;
    src[LOOSE] = "^" + LOOSEPLAIN + "$";
    GTLT = R++;
    src[GTLT] = "((?:<|>)?=?)";
    XRANGEIDENTIFIERLOOSE = R++;
    src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + "|x|X|\\*";
    XRANGEIDENTIFIER = R++;
    src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + "|x|X|\\*";
    XRANGEPLAIN = R++;
    src[XRANGEPLAIN] = "[v=\\s]*(" + src[XRANGEIDENTIFIER] + ")(?:\\.(" + src[XRANGEIDENTIFIER] + ")(?:\\.(" + src[XRANGEIDENTIFIER] + ")(?:" + src[PRERELEASE] + ")?" + src[BUILD] + "?)?)?";
    XRANGEPLAINLOOSE = R++;
    src[XRANGEPLAINLOOSE] = "[v=\\s]*(" + src[XRANGEIDENTIFIERLOOSE] + ")(?:\\.(" + src[XRANGEIDENTIFIERLOOSE] + ")(?:\\.(" + src[XRANGEIDENTIFIERLOOSE] + ")(?:" + src[PRERELEASELOOSE] + ")?" + src[BUILD] + "?)?)?";
    XRANGE = R++;
    src[XRANGE] = "^" + src[GTLT] + "\\s*" + src[XRANGEPLAIN] + "$";
    XRANGELOOSE = R++;
    src[XRANGELOOSE] = "^" + src[GTLT] + "\\s*" + src[XRANGEPLAINLOOSE] + "$";
    COERCE = R++;
    src[COERCE] = "(?:^|[^\\d])(\\d{1," + MAX_SAFE_COMPONENT_LENGTH + "})(?:\\.(\\d{1," + MAX_SAFE_COMPONENT_LENGTH + "}))?(?:\\.(\\d{1," + MAX_SAFE_COMPONENT_LENGTH + "}))?(?:$|[^\\d])";
    LONETILDE = R++;
    src[LONETILDE] = "(?:~>?)";
    TILDETRIM = R++;
    src[TILDETRIM] = "(\\s*)" + src[LONETILDE] + "\\s+";
    re[TILDETRIM] = new RegExp(src[TILDETRIM], "g");
    tildeTrimReplace = "$1~";
    TILDE = R++;
    src[TILDE] = "^" + src[LONETILDE] + src[XRANGEPLAIN] + "$";
    TILDELOOSE = R++;
    src[TILDELOOSE] = "^" + src[LONETILDE] + src[XRANGEPLAINLOOSE] + "$";
    LONECARET = R++;
    src[LONECARET] = "(?:\\^)";
    CARETTRIM = R++;
    src[CARETTRIM] = "(\\s*)" + src[LONECARET] + "\\s+";
    re[CARETTRIM] = new RegExp(src[CARETTRIM], "g");
    caretTrimReplace = "$1^";
    CARET = R++;
    src[CARET] = "^" + src[LONECARET] + src[XRANGEPLAIN] + "$";
    CARETLOOSE = R++;
    src[CARETLOOSE] = "^" + src[LONECARET] + src[XRANGEPLAINLOOSE] + "$";
    COMPARATORLOOSE = R++;
    src[COMPARATORLOOSE] = "^" + src[GTLT] + "\\s*(" + LOOSEPLAIN + ")$|^$";
    COMPARATOR = R++;
    src[COMPARATOR] = "^" + src[GTLT] + "\\s*(" + FULLPLAIN + ")$|^$";
    COMPARATORTRIM = R++;
    src[COMPARATORTRIM] = "(\\s*)" + src[GTLT] + "\\s*(" + LOOSEPLAIN + "|" + src[XRANGEPLAIN] + ")";
    re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], "g");
    comparatorTrimReplace = "$1$2$3";
    HYPHENRANGE = R++;
    src[HYPHENRANGE] = "^\\s*(" + src[XRANGEPLAIN] + ")\\s+-\\s+(" + src[XRANGEPLAIN] + ")\\s*$";
    HYPHENRANGELOOSE = R++;
    src[HYPHENRANGELOOSE] = "^\\s*(" + src[XRANGEPLAINLOOSE] + ")\\s+-\\s+(" + src[XRANGEPLAINLOOSE] + ")\\s*$";
    STAR = R++;
    src[STAR] = "(<|>)?=?\\s*\\*";
    for (let i6 = 0; i6 < R; i6++) {
      if (!re[i6]) {
        re[i6] = new RegExp(src[i6]);
      }
    }
    SemVer = class _SemVer {
      raw;
      loose;
      options;
      major;
      minor;
      patch;
      version;
      build;
      prerelease;
      constructor(version4, optionsOrLoose) {
        if (!optionsOrLoose || typeof optionsOrLoose !== "object") {
          optionsOrLoose = {
            loose: !!optionsOrLoose,
            includePrerelease: false
          };
        }
        if (version4 instanceof _SemVer) {
          if (version4.loose === optionsOrLoose.loose) {
            return version4;
          } else {
            version4 = version4.version;
          }
        } else if (typeof version4 !== "string") {
          throw new TypeError("Invalid Version: " + version4);
        }
        if (version4.length > MAX_LENGTH) {
          throw new TypeError(
            "version is longer than " + MAX_LENGTH + " characters"
          );
        }
        if (!(this instanceof _SemVer)) {
          return new _SemVer(version4, optionsOrLoose);
        }
        this.options = optionsOrLoose;
        this.loose = !!optionsOrLoose.loose;
        const m4 = version4.trim().match(optionsOrLoose.loose ? re[LOOSE] : re[FULL]);
        if (!m4) {
          throw new TypeError("Invalid Version: " + version4);
        }
        this.raw = version4;
        this.major = +m4[1];
        this.minor = +m4[2];
        this.patch = +m4[3];
        if (this.major > Number.MAX_SAFE_INTEGER || this.major < 0) {
          throw new TypeError("Invalid major version");
        }
        if (this.minor > Number.MAX_SAFE_INTEGER || this.minor < 0) {
          throw new TypeError("Invalid minor version");
        }
        if (this.patch > Number.MAX_SAFE_INTEGER || this.patch < 0) {
          throw new TypeError("Invalid patch version");
        }
        if (!m4[4]) {
          this.prerelease = [];
        } else {
          this.prerelease = m4[4].split(".").map((id) => {
            if (/^[0-9]+$/.test(id)) {
              const num = +id;
              if (num >= 0 && num < Number.MAX_SAFE_INTEGER) {
                return num;
              }
            }
            return id;
          });
        }
        this.build = m4[5] ? m4[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;
      }
      compare(other) {
        if (!(other instanceof _SemVer)) {
          other = new _SemVer(other, this.options);
        }
        return this.compareMain(other) || this.comparePre(other);
      }
      compareMain(other) {
        if (!(other instanceof _SemVer)) {
          other = new _SemVer(other, this.options);
        }
        return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch);
      }
      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 i6 = 0;
        do {
          const a5 = this.prerelease[i6];
          const b3 = other.prerelease[i6];
          if (a5 === void 0 && b3 === void 0) {
            return 0;
          } else if (b3 === void 0) {
            return 1;
          } else if (a5 === void 0) {
            return -1;
          } else if (a5 === b3) {
            continue;
          } else {
            return compareIdentifiers(a5, b3);
          }
        } while (++i6);
        return 1;
      }
      compareBuild(other) {
        if (!(other instanceof _SemVer)) {
          other = new _SemVer(other, this.options);
        }
        let i6 = 0;
        do {
          const a5 = this.build[i6];
          const b3 = other.build[i6];
          if (a5 === void 0 && b3 === void 0) {
            return 0;
          } else if (b3 === void 0) {
            return 1;
          } else if (a5 === void 0) {
            return -1;
          } else if (a5 === b3) {
            continue;
          } else {
            return compareIdentifiers(a5, b3);
          }
        } while (++i6);
        return 1;
      }
      inc(release2, identifier) {
        switch (release2) {
          case "premajor":
            this.prerelease.length = 0;
            this.patch = 0;
            this.minor = 0;
            this.major++;
            this.inc("pre", identifier);
            break;
          case "preminor":
            this.prerelease.length = 0;
            this.patch = 0;
            this.minor++;
            this.inc("pre", identifier);
            break;
          case "prepatch":
            this.prerelease.length = 0;
            this.inc("patch", identifier);
            this.inc("pre", identifier);
            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);
            }
            this.inc("pre", identifier);
            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":
            if (this.prerelease.length === 0) {
              this.prerelease = [0];
            } else {
              let i6 = this.prerelease.length;
              while (--i6 >= 0) {
                if (typeof this.prerelease[i6] === "number") {
                  this.prerelease[i6]++;
                  i6 = -2;
                }
              }
              if (i6 === -1) {
                this.prerelease.push(0);
              }
            }
            if (identifier) {
              if (this.prerelease[0] === identifier) {
                if (isNaN(this.prerelease[1])) {
                  this.prerelease = [identifier, 0];
                }
              } else {
                this.prerelease = [identifier, 0];
              }
            }
            break;
          default:
            throw new Error("invalid increment argument: " + release2);
        }
        this.format();
        this.raw = this.version;
        return this;
      }
      toString() {
        return this.version;
      }
    };
    numeric = /^[0-9]+$/;
    ANY = {};
    Comparator = class _Comparator {
      semver;
      operator;
      value;
      loose;
      options;
      constructor(comp, optionsOrLoose) {
        if (!optionsOrLoose || typeof optionsOrLoose !== "object") {
          optionsOrLoose = {
            loose: !!optionsOrLoose,
            includePrerelease: false
          };
        }
        if (comp instanceof _Comparator) {
          if (comp.loose === !!optionsOrLoose.loose) {
            return comp;
          } else {
            comp = comp.value;
          }
        }
        if (!(this instanceof _Comparator)) {
          return new _Comparator(comp, optionsOrLoose);
        }
        this.options = optionsOrLoose;
        this.loose = !!optionsOrLoose.loose;
        this.parse(comp);
        if (this.semver === ANY) {
          this.value = "";
        } else {
          this.value = this.operator + this.semver.version;
        }
      }
      parse(comp) {
        const r5 = this.options.loose ? re[COMPARATORLOOSE] : re[COMPARATOR];
        const m4 = comp.match(r5);
        if (!m4) {
          throw new TypeError("Invalid comparator: " + comp);
        }
        const m1 = m4[1];
        this.operator = m1 !== void 0 ? m1 : "";
        if (this.operator === "=") {
          this.operator = "";
        }
        if (!m4[2]) {
          this.semver = ANY;
        } else {
          this.semver = new SemVer(m4[2], this.options.loose);
        }
      }
      test(version4) {
        if (this.semver === ANY || version4 === ANY) {
          return true;
        }
        if (typeof version4 === "string") {
          version4 = new SemVer(version4, this.options);
        }
        return cmp(version4, this.operator, this.semver, this.options);
      }
      intersects(comp, optionsOrLoose) {
        if (!(comp instanceof _Comparator)) {
          throw new TypeError("a Comparator is required");
        }
        if (!optionsOrLoose || typeof optionsOrLoose !== "object") {
          optionsOrLoose = {
            loose: !!optionsOrLoose,
            includePrerelease: false
          };
        }
        let rangeTmp;
        if (this.operator === "") {
          if (this.value === "") {
            return true;
          }
          rangeTmp = new Range2(comp.value, optionsOrLoose);
          return satisfies(this.value, rangeTmp, optionsOrLoose);
        } else if (comp.operator === "") {
          if (comp.value === "") {
            return true;
          }
          rangeTmp = new Range2(this.value, optionsOrLoose);
          return satisfies(comp.semver, rangeTmp, optionsOrLoose);
        }
        const sameDirectionIncreasing = (this.operator === ">=" || this.operator === ">") && (comp.operator === ">=" || comp.operator === ">");
        const sameDirectionDecreasing = (this.operator === "<=" || this.operator === "<") && (comp.operator === "<=" || comp.operator === "<");
        const sameSemVer = this.semver.version === comp.semver.version;
        const differentDirectionsInclusive = (this.operator === ">=" || this.operator === "<=") && (comp.operator === ">=" || comp.operator === "<=");
        const oppositeDirectionsLessThan = cmp(this.semver, "<", comp.semver, optionsOrLoose) && (this.operator === ">=" || this.operator === ">") && (comp.operator === "<=" || comp.operator === "<");
        const oppositeDirectionsGreaterThan = cmp(this.semver, ">", comp.semver, optionsOrLoose) && (this.operator === "<=" || this.operator === "<") && (comp.operator === ">=" || comp.operator === ">");
        return sameDirectionIncreasing || sameDirectionDecreasing || sameSemVer && differentDirectionsInclusive || oppositeDirectionsLessThan || oppositeDirectionsGreaterThan;
      }
      toString() {
        return this.value;
      }
    };
    Range2 = class _Range {
      range;
      raw;
      loose;
      options;
      includePrerelease;
      set;
      constructor(range, optionsOrLoose) {
        if (!optionsOrLoose || typeof optionsOrLoose !== "object") {
          optionsOrLoose = {
            loose: !!optionsOrLoose,
            includePrerelease: false
          };
        }
        if (range instanceof _Range) {
          if (range.loose === !!optionsOrLoose.loose && range.includePrerelease === !!optionsOrLoose.includePrerelease) {
            return range;
          } else {
            return new _Range(range.raw, optionsOrLoose);
          }
        }
        if (range instanceof Comparator) {
          return new _Range(range.value, optionsOrLoose);
        }
        if (!(this instanceof _Range)) {
          return new _Range(range, optionsOrLoose);
        }
        this.options = optionsOrLoose;
        this.loose = !!optionsOrLoose.loose;
        this.includePrerelease = !!optionsOrLoose.includePrerelease;
        this.raw = range;
        this.set = range.split(/\s*\|\|\s*/).map((range2) => this.parseRange(range2.trim())).filter((c6) => {
          return c6.length;
        });
        if (!this.set.length) {
          throw new TypeError("Invalid SemVer Range: " + range);
        }
        this.format();
      }
      format() {
        this.range = this.set.map((comps) => comps.join(" ").trim()).join("||").trim();
        return this.range;
      }
      parseRange(range) {
        const loose = this.options.loose;
        range = range.trim();
        const hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE];
        range = range.replace(hr, hyphenReplace);
        range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace);
        range = range.replace(re[TILDETRIM], tildeTrimReplace);
        range = range.replace(re[CARETTRIM], caretTrimReplace);
        range = range.split(/\s+/).join(" ");
        const compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR];
        let set3 = range.split(" ").map((comp) => parseComparator(comp, this.options)).join(" ").split(/\s+/);
        if (this.options.loose) {
          set3 = set3.filter((comp) => {
            return !!comp.match(compRe);
          });
        }
        return set3.map((comp) => new Comparator(comp, this.options));
      }
      test(version4) {
        if (typeof version4 === "string") {
          version4 = new SemVer(version4, this.options);
        }
        for (var i6 = 0; i6 < this.set.length; i6++) {
          if (testSet(this.set[i6], version4, this.options)) {
            return true;
          }
        }
        return false;
      }
      intersects(range, optionsOrLoose) {
        if (!(range instanceof _Range)) {
          throw new TypeError("a Range is required");
        }
        return this.set.some((thisComparators) => {
          return isSatisfiable(thisComparators, optionsOrLoose) && range.set.some((rangeComparators) => {
            return isSatisfiable(rangeComparators, optionsOrLoose) && thisComparators.every((thisComparator) => {
              return rangeComparators.every((rangeComparator) => {
                return thisComparator.intersects(
                  rangeComparator,
                  optionsOrLoose
                );
              });
            });
          });
        });
      }
      toString() {
        return this.range;
      }
    };
    mod_default = SemVer;
  }
});

// core/knitr.ts
async function checkRBinary() {
  const rBin = await rBinaryPath("Rscript");
  try {
    const result2 = await execProcess({
      cmd: rBin,
      args: ["--version"],
      stdout: "piped",
      stderr: "piped"
    });
    if (result2.success && (result2.stdout || /R scripting front-end version/.test(result2.stderr ?? ""))) {
      debug(`
++R found at ${rBin} is working.`);
      return rBin;
    } else {
      debug(`
++R found at ${rBin} is not working properly.`);
      return void 0;
    }
  } catch {
    debug(
      `
++ Error while checking R binary found at ${rBin}`
    );
    return void 0;
  }
}
function throwIfX64ROnArm(exitCode) {
  const isX64RCrashOnArm = exitCode === -1073741569 || // STATUS_NOT_SUPPORTED (native ARM hardware)
  exitCode === -1073741819;
  if (isX64RCrashOnArm) {
    throw new WindowsArmX64RError(
      `R process crashed with known error code (${exitCode}).

This typically indicates x64 R running on Windows 11 ARM.
x64 R runs under emulation and is not reliable for Quarto.

To fix this issue:
1. Check your R version with: Rscript -e "R.version$platform"
2. If it shows 'x86_64-w64-mingw32', you need ARM64 R
3. Install native ARM64 R: https://blog.r-project.org/2024/04/23/r-on-64-bit-arm-windows/
4. If needed, set QUARTO_R environment variable to point to ARM64 Rscript

More context on this issue: https://github.com/quarto-dev/quarto-cli/issues/8730`
    );
  }
}
async function knitrCapabilities(rBin) {
  if (!rBin) return void 0;
  try {
    debug(`-- Checking knitr engine capabilities --`);
    const result2 = await execProcess({
      cmd: rBin,
      args: [resourcePath("capabilities/knitr.R")],
      stdout: "piped"
    });
    if (result2.success && result2.stdout) {
      debug(
        "\n++ Parsing results to get informations about knitr capabilities"
      );
      const yamlLines = result2.stdout.replace(/^.*--- YAML_START ---/sm, "").replace(/--- YAML_END ---.*$/sm, "");
      const caps = readYamlFromString(yamlLines);
      const knitrVersion = caps.packages.knitr ? coerce(caps.packages.knitr) : void 0;
      caps.packages.knitrVersOk = knitrVersion ? satisfies(
        knitrVersion,
        Object.values(pkgVersRequirement["knitr"]).join(" ")
      ) : false;
      const rmarkdownVersion = caps.packages.rmarkdown ? coerce(caps.packages.rmarkdown) : void 0;
      caps.packages.rmarkdownVersOk = rmarkdownVersion ? satisfies(
        rmarkdownVersion,
        Object.values(pkgVersRequirement["rmarkdown"]).join(" ")
      ) : false;
      return caps;
    } else {
      debug("\n++ Problem with results of knitr capabilities check.");
      debug(`    Return Code: ${result2.code} (success is ${result2.success})`);
      result2.stdout ? debug(`    with stdout from R:
${result2.stdout}`) : debug("    with no stdout");
      if (result2.stderr) {
        debug(`    with stderr from R:
${result2.stderr}`);
      }
      throwIfX64ROnArm(result2.code);
      return void 0;
    }
  } catch (e5) {
    if (e5 instanceof WindowsArmX64RError) {
      errorOnce(e5.message);
      return void 0;
    }
    debug(
      `
++ Error while running 'capabilities/knitr.R' ${rBin ? "with " + rBin : ""}`
    );
    return void 0;
  }
}
function knitrCapabilitiesMessage(caps, indent = "") {
  const lines2 = [
    `Version: ${caps.versionMajor}.${caps.versionMinor}.${caps.versionPatch}`,
    `Path: ${caps.home}`,
    `LibPaths:`
  ];
  for (const path3 of caps.libPaths) {
    lines2.push(`  - ${path3}`);
  }
  lines2.push(`knitr: ${caps.packages.knitr || "(None)"}`);
  if (caps.packages.knitr && !caps.packages.knitrVersOk) {
    lines2.push(
      `NOTE: knitr version ${caps.packages.knitr} is too old. Please upgrade to ${pkgVersRequirement.knitr.version} or later.`
    );
  }
  lines2.push(`rmarkdown: ${caps.packages.rmarkdown || "(None)"}`);
  if (caps.packages.rmarkdown && !caps.packages.rmarkdownVersOk) {
    lines2.push(
      `NOTE: rmarkdown version ${caps.packages.rmarkdown} is too old. Please upgrade to ${pkgVersRequirement.rmarkdown.version} or later.`
    );
  }
  return lines2.map((line) => `${indent}${line}`).join("\n");
}
function knitrInstallationMessage(indent = "", pkg = "rmarkdown", update = false) {
  const lines2 = [
    `The ${pkg} package is ${update ? "outdated" : "not available"} in this R installation.`
  ];
  if (update) {
    lines2.push(
      "Update with " + bold3(`update.packages("${pkg}")`)
    );
  } else {
    lines2.push(
      "Install with " + bold3(`install.packages("${pkg}")`)
    );
  }
  return lines2.map((line) => `${indent}${line}`).join("\n");
}
function rInstallationMessage(indent = "") {
  const lines2 = [
    "Unable to locate an installed version of R.",
    "Install R from " + bold3("https://cloud.r-project.org/")
  ];
  return lines2.map((line) => `${indent}${line}`).join("\n");
}
var pkgVersRequirement, WindowsArmX64RError;
var init_knitr = __esm({
  "core/knitr.ts"() {
    init_colors2();
    init_process();
    init_resources2();
    init_yaml();
    init_mod6();
    init_log();
    init_log2();
    pkgVersRequirement = {
      knitr: {
        type: ">=",
        version: "1.30"
      },
      rmarkdown: {
        type: ">=",
        version: "2.3"
      }
    };
    WindowsArmX64RError = class extends Error {
      constructor(msg5) {
        super(msg5);
      }
    };
  }
});

// execute/rmd.ts
async function callR(action, params, tempDir2, projectDir, quiet, outputFilter, reportError = true) {
  const cwd2 = withinActiveRenv() ? Deno.cwd() : projectDir ?? Deno.cwd();
  const resultsFile = Deno.makeTempFileSync(
    { dir: tempDir2, prefix: "r-results", suffix: ".json" }
  );
  const input = JSON.stringify({
    action,
    params,
    results: resultsFile,
    wd: cwd2
  });
  const rscriptArgs = Deno.env.get("QUARTO_KNITR_RSCRIPT_ARGS") || "";
  const rscriptArgsArray = rscriptArgs.split(",").filter(
    (a5) => a5.trim() !== ""
  );
  try {
    const result2 = await quarto.system.execProcess(
      {
        cmd: await rBinaryPath("Rscript"),
        args: [
          ...rscriptArgsArray,
          quarto.path.resource("rmd/rmd.R")
        ],
        cwd: cwd2,
        stderr: quiet ? "piped" : "inherit"
      },
      input,
      "stdout>stderr",
      (output) => {
        if (outputFilter) {
          output = outputFilter(output);
        }
        return red3(output);
      }
    );
    if (result2.success) {
      const results = await Deno.readTextFile(resultsFile);
      await Deno.remove(resultsFile);
      const resultsJson = JSON.parse(results);
      return resultsJson;
    } else {
      if (quiet) {
        error(result2.stderr || "");
      }
      if (reportError) {
        await printCallRDiagnostics();
      }
      return Promise.reject();
    }
  } catch (e5) {
    if (!(e5 instanceof Error)) {
      throw e5;
    }
    if (reportError) {
      if (e5?.message) {
        info("");
        error(e5.message);
      }
      await printCallRDiagnostics();
    }
    return Promise.reject();
  }
}
function withinActiveRenv() {
  const kRProfile = ".Rprofile";
  const kREnvActivate = 'source("renv/activate.R")';
  if (existsSync2(".Rprofile")) {
    const profile = Deno.readTextFileSync(kRProfile);
    return profile.includes(kREnvActivate) && !profile.includes("# " + kREnvActivate);
  } else {
    return false;
  }
}
async function printCallRDiagnostics() {
  const rBin = await checkRBinary();
  if (rBin === void 0) {
    info("");
    info(rInstallationMessage());
    info("");
  } else {
    const caps = await knitrCapabilities(rBin);
    if (caps === void 0) {
      info(
        `Problem with running R found at ${rBin} to check environment configurations.`
      );
      info("Please check your installation of R.");
      info("");
    } else {
      if (!caps?.packages.rmarkdown || !caps?.packages.knitr || !caps?.packages.knitrVersOk || !caps?.packages.rmarkdownVersOk) {
        info("R installation:");
        info(knitrCapabilitiesMessage(caps, "  "));
        if (!!!caps?.packages.knitr || !caps?.packages.knitrVersOk) {
          info("");
          info(
            knitrInstallationMessage(
              "",
              "knitr",
              !!caps.packages.knitr && !caps.packages.knitrVersOk
            )
          );
        }
        if (!!!caps?.packages.rmarkdown || !caps?.packages.rmarkdownVersOk) {
          info("");
          info(
            knitrInstallationMessage(
              "",
              "rmarkdown",
              !!caps?.packages.rmarkdown && !caps?.packages.rmarkdownVersOk
            )
          );
        }
        info("");
      }
    }
  }
}
function filterAlwaysAllowHtml(s5) {
  if (s5.indexOf(
    "Functions that produce HTML output found in document targeting"
  ) !== -1) {
    s5 = s5.replace("your rmarkdown file", "your quarto file").replace("always_allow_html: true", "prefer-html: true");
  }
  return s5;
}
function resolveInlineExecute(code5) {
  return quarto.text.executeInlineCodeHandler(
    "r",
    (expr) => `${"`"}r .QuartoInlineRender(${expr})${"`"}`
  )(code5);
}
function isKnitrSpinScript(file) {
  const ext = extname4(file).toLowerCase();
  if (ext == ".r") {
    const text = Deno.readTextFileSync(file);
    return /^\s*#'\s*---[\s\S]+?\s*#'\s*---/.test(text);
  } else {
    return false;
  }
}
async function markdownFromKnitrSpinScript(file) {
  const tempDir2 = quarto.system.tempContext().createDir();
  const result2 = await callR(
    "spin",
    { input: file },
    tempDir2,
    void 0,
    true
  );
  return result2;
}
var quarto, kRmdExtensions, knitrEngineDiscovery;
var init_rmd = __esm({
  "execute/rmd.ts"() {
    init_log();
    init_fs();
    init_path();
    init_colors2();
    init_resources2();
    init_constants6();
    init_knitr();
    init_types3();
    init_mapped_text();
    kRmdExtensions = [".rmd", ".rmarkdown"];
    knitrEngineDiscovery = {
      init: (quartoAPI) => {
        quarto = quartoAPI;
      },
      // Discovery methods
      name: kKnitrEngine,
      defaultExt: ".qmd",
      defaultYaml: () => [],
      defaultContent: () => [
        "```{r}",
        "1 + 1",
        "```"
      ],
      validExtensions: () => kRmdExtensions.concat(kRmdExtensions),
      claimsFile: (file, ext) => {
        return kRmdExtensions.includes(ext.toLowerCase()) || isKnitrSpinScript(file);
      },
      claimsLanguage: (language) => {
        return language.toLowerCase() === "r";
      },
      canFreeze: true,
      generatesFigures: true,
      ignoreDirs: () => {
        return ["renv", "packrat", "rsconnect"];
      },
      checkInstallation: async (conf) => {
        const kIndent2 = "      ";
        const checkCompleteMessage2 = (message) => {
          if (!conf.jsonResult) {
            quarto.console.completeMessage(message);
          }
        };
        const checkInfoMsg2 = (message) => {
          if (!conf.jsonResult) {
            info(message);
          }
        };
        const checkKnitrRender = async () => {
          const json4 = {};
          if (conf.jsonResult) {
            conf.jsonResult.render.knitr = json4;
          }
          const result2 = await quarto.system.checkRender({
            content: `
---
title: "Title"
---

## Header

\`\`\`{r}
1 + 1
\`\`\`
`,
            language: "r",
            services: conf.services
          });
          if (result2.error) {
            if (!conf.jsonResult) {
              throw result2.error;
            } else {
              json4["error"] = result2.error;
            }
          } else {
            json4["ok"] = true;
          }
        };
        const kMessage = "Checking R installation...........";
        let caps;
        let rBin;
        const json3 = {};
        if (conf.jsonResult) {
          conf.jsonResult.tools.knitr = json3;
        }
        const knitrCb = async () => {
          rBin = await checkRBinary();
          caps = await knitrCapabilities(rBin);
        };
        if (conf.jsonResult) {
          await knitrCb();
        } else {
          await quarto.console.withSpinner({
            message: kMessage,
            doneMessage: false
          }, knitrCb);
        }
        if (rBin && caps) {
          checkCompleteMessage2(kMessage + "OK");
          if (conf.jsonResult) {
            json3["capabilities"] = caps;
          } else {
            checkInfoMsg2(knitrCapabilitiesMessage(caps, kIndent2));
          }
          checkInfoMsg2("");
          if (caps.packages.rmarkdownVersOk && caps.packages.knitrVersOk) {
            const kKnitrMessage = "Checking Knitr engine render......";
            if (conf.jsonResult) {
              await checkKnitrRender();
            } else {
              await quarto.console.withSpinner({
                message: kKnitrMessage,
                doneMessage: kKnitrMessage + "OK\n"
              }, async () => {
                await checkKnitrRender();
              });
            }
          } else {
            json3["installed"] = false;
            if (!caps.packages.knitr || !caps.packages.knitrVersOk) {
              const msg5 = knitrInstallationMessage(
                kIndent2,
                "knitr",
                !!caps.packages.knitr && !caps.packages.knitrVersOk
              );
              checkInfoMsg2(msg5);
              json3["how-to-install-knitr"] = msg5;
            }
            if (!caps.packages.rmarkdown || !caps.packages.rmarkdownVersOk) {
              const msg5 = knitrInstallationMessage(
                kIndent2,
                "rmarkdown",
                !!caps.packages.rmarkdown && !caps.packages.rmarkdownVersOk
              );
              checkInfoMsg2(msg5);
              json3["how-to-install-rmarkdown"] = msg5;
            }
            checkInfoMsg2("");
          }
        } else if (rBin === void 0) {
          checkCompleteMessage2(kMessage + "(None)\n");
          const msg5 = rInstallationMessage(kIndent2);
          checkInfoMsg2(msg5);
          json3["installed"] = false;
          checkInfoMsg2("");
        } else if (caps === void 0) {
          json3["installed"] = false;
          checkCompleteMessage2(kMessage + "(None)\n");
          const msgs = [
            `R succesfully found at ${rBin}.`,
            "However, a problem was encountered when checking configurations of packages.",
            "Please check your installation of R."
          ];
          msgs.forEach((msg5) => {
            checkInfoMsg2(msg5);
          });
          json3["error"] = msgs.join("\n");
          checkInfoMsg2("");
        }
      },
      // Launch method that returns an instance with context closure
      launch: (context) => {
        return {
          // Instance properties (required by interface)
          name: kKnitrEngine,
          canFreeze: true,
          // Instance methods
          async markdownForFile(file) {
            const isSpin = isKnitrSpinScript(file);
            if (isSpin) {
              return asMappedString(await markdownFromKnitrSpinScript(file));
            }
            return quarto.mappedString.fromFile(file);
          },
          target: async (file, _quiet, markdown) => {
            const resolvedMarkdown = await context.resolveFullMarkdownForFile(
              knitrEngineDiscovery.launch(context),
              file,
              markdown
            );
            let metadata;
            try {
              metadata = quarto.markdownRegex.extractYaml(resolvedMarkdown.value);
            } catch (e5) {
              if (!(e5 instanceof Error)) throw e5;
              error(`Error reading metadata from ${file}.
${e5.message}`);
              throw e5;
            }
            const target = {
              source: file,
              input: file,
              markdown: resolvedMarkdown,
              metadata
            };
            return Promise.resolve(target);
          },
          partitionedMarkdown: async (file) => {
            if (isKnitrSpinScript(file)) {
              return quarto.markdownRegex.partition(
                await markdownFromKnitrSpinScript(file)
              );
            } else {
              return quarto.markdownRegex.partition(Deno.readTextFileSync(file));
            }
          },
          execute: async (options) => {
            const inputBasename = basename4(options.target.input);
            const inputStem = basename4(inputBasename, extname4(inputBasename));
            const result2 = await callR(
              "execute",
              {
                ...options,
                target: void 0,
                input: options.target.input,
                markdown: resolveInlineExecute(options.target.markdown.value)
              },
              options.tempDir,
              options.project?.isSingleFile ? void 0 : options.projectDir,
              options.quiet,
              // fixup .rmarkdown file references
              (output) => {
                output = output.replaceAll(
                  `${inputStem}.rmarkdown`,
                  () => inputBasename
                );
                const m4 = output.match(/^Quitting from lines (\d+)-(\d+)/m);
                if (m4) {
                  const f1 = quarto.text.lineColToIndex(
                    options.target.markdown.value
                  );
                  const f22 = mappedIndexToLineCol(options.target.markdown);
                  const newLine1 = f22(f1({ line: Number(m4[1]) - 1, column: 0 })).line + 1;
                  const newLine2 = f22(f1({ line: Number(m4[2]) - 1, column: 0 })).line + 1;
                  output = output.replace(
                    /^Quitting from lines (\d+)-(\d+)/m,
                    `

Quitting from lines ${newLine1}-${newLine2}`
                  );
                }
                output = filterAlwaysAllowHtml(output);
                return output;
              }
            );
            const includes = result2.includes;
            if (Array.isArray(includes) && includes.length === 0) {
              result2.includes = {};
            }
            return result2;
          },
          dependencies: (options) => {
            return callR(
              "dependencies",
              { ...options, target: void 0, input: options.target.input },
              options.tempDir,
              options.projectDir,
              options.quiet
            );
          },
          postprocess: async (options) => {
            quarto.text.postProcessRestorePreservedHtml(options);
            if (options.format.render?.[kCodeLink]) {
              if (quarto.format.isServerShiny(options.format)) {
                warn(
                  `'code-link' option will be ignored as it is not supported for 'server: shiny' due to 'downlit' R package limitation (https://github.com/quarto-dev/quarto-cli/issues/9208).`
                );
                return Promise.resolve();
              }
              await callR(
                "postprocess",
                {
                  ...options,
                  target: void 0,
                  preserve: void 0,
                  input: options.target.input
                },
                options.tempDir,
                options.projectDir,
                options.quiet,
                void 0,
                false
              ).then(() => {
                return Promise.resolve();
              }, () => {
                warn(
                  `Unable to perform code-link (code-link requires R packages rmarkdown, downlit, and xml2)`
                );
                return Promise.resolve();
              });
            }
          },
          run: (options) => {
            let running = false;
            return callR(
              "run",
              options,
              options.tempDir,
              options.projectDir,
              void 0,
              // wait for 'listening' to call onReady
              (output) => {
                const kListeningPattern = /(Listening on) (https?:\/\/[^\n]*)/;
                if (!running) {
                  const listeningMatch = output.match(kListeningPattern);
                  if (listeningMatch) {
                    running = true;
                    output = output.replace(kListeningPattern, "");
                    if (options.onReady) {
                      options.onReady();
                    }
                  }
                }
                return output;
              }
            );
          }
        };
      }
    };
  }
});

// core/async.ts
var sleep;
var init_async = __esm({
  "core/async.ts"() {
    sleep = (delay) => {
      return new Promise((resolve16) => {
        setTimeout(resolve16, delay);
      });
    };
  }
});

// core/api/registry.ts
var UnregisteredNamespaceError, RegistryFinalizedError, QuartoAPIRegistry, globalRegistry;
var init_registry2 = __esm({
  "core/api/registry.ts"() {
    UnregisteredNamespaceError = class extends Error {
      constructor(namespace) {
        super(
          `QuartoAPI namespace '${namespace}' has not been registered. Ensure that 'src/core/api/register.ts' is imported before using the API.`
        );
        this.name = "UnregisteredNamespaceError";
      }
    };
    RegistryFinalizedError = class extends Error {
      constructor(namespace) {
        super(
          `Cannot register namespace '${namespace}': Registry has been finalized. All registrations must occur before createAPI() is called.`
        );
        this.name = "RegistryFinalizedError";
      }
    };
    QuartoAPIRegistry = class {
      providers = {};
      implementations = {};
      finalized = false;
      apiInstance = null;
      /**
       * Register a namespace provider function
       * @throws {RegistryFinalizedError} if registry is already finalized
       * @throws {Error} if namespace is already registered
       */
      register(namespace, provider) {
        if (this.finalized) {
          throw new RegistryFinalizedError(namespace);
        }
        if (this.providers[namespace]) {
          throw new Error(
            `QuartoAPI namespace '${namespace}' is already registered`
          );
        }
        this.providers[namespace] = provider;
      }
      /**
       * Create the QuartoAPI instance with eager initialization and validation
       * @returns {QuartoAPI} The complete API object with all namespaces
       * @throws {UnregisteredNamespaceError} if any required namespace is missing
       */
      createAPI() {
        if (this.apiInstance) {
          return this.apiInstance;
        }
        const requiredNamespaces = [
          "markdownRegex",
          "mappedString",
          "jupyter",
          "format",
          "path",
          "system",
          "text",
          "console",
          "crypto"
        ];
        const missingNamespaces = requiredNamespaces.filter(
          (ns) => !this.providers[ns]
        );
        if (missingNamespaces.length > 0) {
          throw new UnregisteredNamespaceError(
            `Missing required namespaces: ${missingNamespaces.join(", ")}`
          );
        }
        for (const namespace of requiredNamespaces) {
          const provider = this.providers[namespace];
          if (provider) {
            this.implementations[namespace] = provider();
          }
        }
        this.finalized = true;
        this.apiInstance = this.implementations;
        return this.apiInstance;
      }
      /**
       * Check if a namespace is registered (useful for optional features)
       */
      isRegistered(namespace) {
        return !!this.providers[namespace];
      }
      /**
       * Clear cached implementations (for testing purposes)
       */
      clearCache() {
        this.implementations = {};
        this.apiInstance = null;
        this.finalized = false;
      }
    };
    globalRegistry = new QuartoAPIRegistry();
  }
});

// core/api/index.ts
function getQuartoAPI() {
  if (_quartoAPI === null) {
    _quartoAPI = globalRegistry.createAPI();
  }
  return _quartoAPI;
}
var _quartoAPI;
var init_api2 = __esm({
  "core/api/index.ts"() {
    init_registry2();
    init_registry2();
    _quartoAPI = null;
  }
});

// execute/jupyter/jupyter-kernel.ts
async function executeKernelOneshot(options) {
  await abortKernel(options);
  if (!options.quiet) {
    messageStartingKernel(options.kernelspec);
  }
  trace(options, "Executing notebook with oneshot kernel");
  const debug4 = !!options.format.execute[kExecuteDebug] || !!Deno.env.get("QUARTO_JUPYTER_DEBUG");
  const result2 = await execJupyter(
    "execute",
    { ...options, debug: debug4 },
    options.kernelspec
  );
  if (!result2.success) {
    return Promise.reject();
  }
}
async function executeKernelKeepalive(options) {
  let serverLogProcess;
  if (options.format.execute[kExecuteDebug]) {
    if (!isWindows4) {
      serverLogProcess = new Deno.Command("tail", {
        args: ["-F", "-n", "0", kernelLogFile()]
      }).spawn();
    }
  }
  if (options.format.execute[kExecuteDaemonRestart]) {
    await abortKernel(options);
  }
  trace(options, "Connecting to kernel");
  const [conn, transport] = await connectToKernel(options);
  trace(options, "Kernel connection successful");
  try {
    trace(options, "Sending execute command to kernel");
    await writeKernelCommand(
      conn,
      "execute",
      transport.secret,
      { ...options }
    );
    trace(options, "Execute command sent, reading response");
    let leftover = "";
    while (true) {
      const buffer2 = new Uint8Array(512);
      const bytesRead = await conn.read(buffer2);
      if (bytesRead === null) {
        break;
      }
      if (bytesRead > 0) {
        const payload = new TextDecoder().decode(
          buffer2.slice(0, bytesRead)
        );
        const jsonMessages = payload.split("\n");
        for (let jsonMessage of jsonMessages) {
          if (!jsonMessage) {
            continue;
          }
          if (leftover) {
            jsonMessage = leftover + jsonMessage;
            leftover = "";
          }
          try {
            const msg5 = JSON.parse(
              jsonMessage
            );
            if (msg5.type === "error") {
              trace(options, "Error response received");
              error(msg5.data, { colorize: false });
              printExecDiagnostics(options.kernelspec, msg5.data);
              return Promise.reject();
            } else if (msg5.type == "restart") {
              trace(options, "Restart request received");
              return executeKernelKeepalive(options);
            } else {
              info(msg5.data, { newline: false });
            }
          } catch {
            leftover = jsonMessage;
          }
        }
      }
    }
    trace(options, "Server request complete\n\n");
  } catch (e5) {
    trace(options, "Error occurred receiving response from server");
    const transportFile = kernelTransportFile(options.target.input);
    if (existsSync2(transportFile)) {
      safeRemoveSync(transportFile);
    }
    throw e5;
  } finally {
    conn.close();
    serverLogProcess?.kill("SIGKILL");
  }
}
async function abortKernel(options) {
  try {
    trace(options, "Checking for existing kernel");
    const [conn, transport] = await connectToKernel(options, false);
    trace(options, "Existing kernel found");
    try {
      trace(options, "Sending kernel abort request");
      await writeKernelCommand(conn, "abort", transport.secret, {});
      trace(options, "Abort request successful");
    } finally {
      const transportFile = kernelTransportFile(options.target.input);
      if (existsSync2(transportFile)) {
        safeRemoveSync(transportFile);
      }
      conn.close();
    }
  } catch {
    trace(options, "No existing kernel found");
  }
}
async function execJupyter(command, options, kernelspec) {
  const quarto5 = getQuartoAPI();
  try {
    const cmd = await quarto5.jupyter.pythonExec(kernelspec);
    const result2 = await quarto5.system.execProcess(
      {
        cmd: cmd[0],
        args: [
          ...cmd.slice(1),
          quarto5.path.resource("jupyter", "jupyter.py")
        ],
        env: {
          // Force default matplotlib backend. something simillar is done here:
          // https://github.com/ipython/ipykernel/blob/d7339c2c70115bbe6042880d29eeb273b5a2e350/ipykernel/kernelapp.py#L549-L554
          // however this respects existing environment variables, which we've seen in at least
          // one case result in an inability to render due to the iTerm2 backend being configured
          // (see https://github.com/quarto-dev/quarto-cli/issues/502). Our current position is
          // that the way to use a different backend w/ Quarto is to call the matplotlib.use()
          // function within the notebook
          "MPLBACKEND": "module://matplotlib_inline.backend_inline",
          "PYDEVD_DISABLE_FILE_VALIDATION": "1"
        },
        stdout: "piped"
      },
      kernelCommand(command, "", options)
    );
    if (!result2.success) {
      await printExecDiagnostics(kernelspec, result2.stderr);
    }
    return result2;
  } catch (e5) {
    if (!(e5 instanceof Error)) throw e5;
    if (e5?.message) {
      info("");
      error(e5.message);
    }
    await printExecDiagnostics(kernelspec);
    return Promise.reject();
  }
}
async function printExecDiagnostics(kernelspec, stderr2) {
  const quarto5 = getQuartoAPI();
  const caps = await quarto5.jupyter.capabilities(kernelspec);
  if (caps && !caps.jupyter_core) {
    info("Python 3 installation:");
    info(quarto5.jupyter.capabilitiesMessage(caps, "  "));
    info("");
    info(quarto5.jupyter.installationMessage(caps));
    info("");
    maybePrintUnactivatedEnvMessage(caps);
  } else if (caps && !haveRequiredPython(caps)) {
    info(pythonVersionMessage());
    info(quarto5.jupyter.capabilitiesMessage(caps, "  "));
  } else if (!caps) {
    info(quarto5.jupyter.pythonInstallationMessage());
    info("");
  } else if (stderr2 && stderr2.indexOf("ModuleNotFoundError") !== -1) {
    maybePrintUnactivatedEnvMessage(caps);
  }
}
function haveRequiredPython(caps) {
  return caps.versionMajor >= 3 && caps.versionMinor >= 6;
}
function pythonVersionMessage() {
  return `Quarto requires Python version 3.6 (or greater). Detected version is:`;
}
function maybePrintUnactivatedEnvMessage(caps) {
  const quarto5 = getQuartoAPI();
  const envMessage = quarto5.jupyter.unactivatedEnvMessage(caps);
  if (envMessage) {
    info(envMessage);
    info("");
  }
}
async function writeKernelCommand(conn, command, secret, options) {
  let messageBytes = new TextEncoder().encode(
    kernelCommand(command, secret, options) + "\n"
  );
  if (messageBytes.length > 1024) {
    const tempFile = Deno.makeTempFileSync();
    Deno.writeFileSync(tempFile, messageBytes);
    const msg5 = kernelCommand("file", secret, { file: tempFile }) + "\n";
    messageBytes = new TextEncoder().encode(msg5);
  }
  const bytesWritten = await conn.write(messageBytes);
  if (bytesWritten !== messageBytes.length) {
    throw new Error("Internal Error");
  }
}
function kernelCommand(command, secret, options) {
  return JSON.stringify(
    { command, secret, options: { ...options, log: kernelLogFile() } }
  );
}
function kernelTransportFile(target) {
  const quarto5 = getQuartoAPI();
  let transportsDir;
  try {
    transportsDir = quarto5.path.runtime("jt");
  } catch (e5) {
    console.error("Could not create runtime directory for jupyter transport.");
    console.error(
      "This is possibly a permission issue in the environment Quarto is running in."
    );
    console.error(
      "Please consult the following documentation for more information:"
    );
    console.error(
      "https://github.com/quarto-dev/quarto-cli/issues/4594#issuecomment-1619177667"
    );
    throw e5;
  }
  const targetFile = quarto5.path.absolute(target);
  const hash = quarto5.crypto.md5Hash(targetFile).slice(0, 20);
  return join4(transportsDir, hash);
}
function kernelLogFile() {
  const quarto5 = getQuartoAPI();
  const logsDir = quarto5.path.dataDir("logs");
  const kernelLog = join4(logsDir, "jupyter-kernel.log");
  if (!existsSync2(kernelLog)) {
    Deno.writeTextFileSync(kernelLog, "");
  }
  return kernelLog;
}
function readKernelTransportFile(transportFile, type4) {
  if (existsSync2(transportFile)) {
    if (type4 === "tcp") {
      try {
        const transport = JSON.parse(Deno.readTextFileSync(transportFile));
        if (transport.port && transport.secret) {
          return {
            ...transport,
            type: type4
          };
        } else {
          throw new Error("Invalid file format");
        }
      } catch (e5) {
        if (!(e5 instanceof Error)) throw e5;
        error(
          "Error reading kernel transport file: " + e5.toString() + "(removing file)"
        );
        safeRemoveSync(transportFile);
        return null;
      }
    } else {
      return {
        port: transportFile,
        secret: "",
        type: type4
      };
    }
  } else {
    return null;
  }
}
async function connectToKernel(options, startIfRequired = true) {
  const debug4 = !!options.format.execute[kExecuteDebug];
  const transportFile = kernelTransportFile(options.target.input);
  const type4 = "tcp";
  const transport = readKernelTransportFile(transportFile, type4);
  if (transport) {
    try {
      return await denoConnectToKernel(transport);
    } catch {
      if (existsSync2(transportFile)) {
        safeRemoveSync(transportFile);
      }
    }
  }
  if (!startIfRequired) {
    return Promise.reject();
  }
  if (!options.quiet) {
    messageStartingKernel(options.kernelspec);
  }
  const kDefaultTimeout = 300;
  const keepAlive = options.format.execute[kExecuteDaemon];
  const timeout = keepAlive === true || keepAlive === null || keepAlive === void 0 ? kDefaultTimeout : keepAlive === false ? 0 : keepAlive;
  const result2 = await execJupyter("start", {
    transport: transportFile,
    timeout,
    type: type4,
    debug: debug4
  }, options.kernelspec);
  if (!result2.success) {
    return Promise.reject();
  }
  for (let i6 = 1; i6 < 20; i6++) {
    await sleep(i6 * 100);
    const kernelTransport = readKernelTransportFile(transportFile, type4);
    if (kernelTransport) {
      try {
        return await denoConnectToKernel(kernelTransport);
      } catch (e5) {
        if (!(e5 instanceof Error)) throw e5;
        safeRemoveSync(transportFile);
        error("Error connecting to Jupyter kernel: " + e5.toString());
        return Promise.reject();
      }
    }
  }
  warn("Unable to start Jupyter kernel for " + options.target.input);
  return Promise.reject();
}
async function denoConnectToKernel(transport) {
  if (transport.type === "tcp") {
    const tcpConnectOptions = {
      transport: transport.type,
      hostname: "127.0.0.1",
      port: transport.port
    };
    return [
      await Deno.connect(
        tcpConnectOptions
      ),
      transport
    ];
  } else {
    const unixConnectOptions = {
      transport: transport.type,
      path: transport.port
    };
    return [
      await Deno.connect(
        unixConnectOptions
      ),
      transport
    ];
  }
}
function messageStartingKernel(kernelspec) {
  info(`
Starting ${kernelspec.name} kernel...`, { newline: false });
}
function trace(options, msg5) {
  if (options.format.execute[kExecuteDebug]) {
    info("- " + msg5, { bold: true });
  }
}
var init_jupyter_kernel = __esm({
  "execute/jupyter/jupyter-kernel.ts"() {
    init_fs();
    init_path();
    init_log();
    init_async();
    init_api2();
    init_constants6();
    init_platform();
  }
});

// core/pandoc/pandoc-attr.ts
function pandocAttrParseText(attr) {
  attr = attr.trim();
  let id = "";
  const classes = [];
  let remainder = "";
  let current3 = "";
  const resolveCurrent = () => {
    const resolve16 = current3;
    current3 = "";
    if (resolve16.length === 0) {
      return true;
    } else if (resolve16.startsWith("#")) {
      if (id.length === 0 && resolve16.length > 1) {
        id = resolve16.substr(1);
        return true;
      } else {
        return false;
      }
    } else if (resolve16.startsWith(".")) {
      if (resolve16.length > 1) {
        classes.push(resolve16.substr(1));
        return true;
      } else {
        return false;
      }
    } else if (resolve16 === "-") {
      classes.push("unnumbered");
      return true;
    } else {
      remainder = resolve16;
      return true;
    }
  };
  for (let i6 = 0; i6 < attr.length; i6++) {
    let inQuotes = false;
    const ch = attr[i6];
    inQuotes = ch === '"' ? !inQuotes : inQuotes;
    if (ch !== " " && !inQuotes) {
      current3 += ch;
    } else if (resolveCurrent()) {
      if (remainder.length > 0) {
        remainder = remainder + attr.substr(i6);
        break;
      }
    } else {
      return null;
    }
  }
  if (resolveCurrent()) {
    if (id.length === 0 && classes.length === 0) {
      remainder = attr;
    }
    return {
      id,
      classes,
      keyvalue: remainder.length > 0 ? pandocAttrKeyvalueFromText(remainder, " ") : []
    };
  } else {
    return null;
  }
}
function pandocAttrKeyvalueFromText(text, separator) {
  if (separator === " ") {
    let convertedText = "";
    let inQuotes = false;
    for (let i6 = 0; i6 < text.length; i6++) {
      let ch = text.charAt(i6);
      if (ch === '"') {
        inQuotes = !inQuotes;
      } else if (ch === " " && !inQuotes) {
        ch = "\n";
      }
      convertedText += ch;
    }
    text = convertedText;
  }
  const lines2 = text.trim().split("\n");
  return lines2.map((line) => {
    const parts = line.trim().split("=");
    return [parts[0], (parts[1] || "").replace(/^"/, "").replace(/"$/, "")];
  });
}
var init_pandoc_attr = __esm({
  "core/pandoc/pandoc-attr.ts"() {
  }
});

// https://jsr.io/@std/encoding/1.0.9/_common64.ts
function calcSizeBase64(originalSize) {
  return ((originalSize + 2) / 3 | 0) * 4;
}
function encode(buffer2, i6, o5, alphabet5, padding3) {
  i6 += 2;
  for (; i6 < buffer2.length; i6 += 3) {
    const x3 = buffer2[i6 - 2] << 16 | buffer2[i6 - 1] << 8 | buffer2[i6];
    buffer2[o5++] = alphabet5[x3 >> 18];
    buffer2[o5++] = alphabet5[x3 >> 12 & 63];
    buffer2[o5++] = alphabet5[x3 >> 6 & 63];
    buffer2[o5++] = alphabet5[x3 & 63];
  }
  switch (i6) {
    case buffer2.length + 1: {
      const x3 = buffer2[i6 - 2] << 16;
      buffer2[o5++] = alphabet5[x3 >> 18];
      buffer2[o5++] = alphabet5[x3 >> 12 & 63];
      buffer2[o5++] = padding3;
      buffer2[o5++] = padding3;
      break;
    }
    case buffer2.length: {
      const x3 = buffer2[i6 - 2] << 16 | buffer2[i6 - 1] << 8;
      buffer2[o5++] = alphabet5[x3 >> 18];
      buffer2[o5++] = alphabet5[x3 >> 12 & 63];
      buffer2[o5++] = alphabet5[x3 >> 6 & 63];
      buffer2[o5++] = padding3;
      break;
    }
  }
  return o5;
}
function decode(buffer2, i6, o5, alphabet5, padding3) {
  for (let x3 = buffer2.length - 2; x3 < buffer2.length; ++x3) {
    if (buffer2[x3] === padding3) {
      for (let y4 = x3 + 1; y4 < buffer2.length; ++y4) {
        if (buffer2[y4] !== padding3) {
          throw new TypeError(
            `Cannot decode input as base64: Invalid character (${String.fromCharCode(buffer2[y4])})`
          );
        }
      }
      buffer2 = buffer2.subarray(0, x3);
      break;
    }
  }
  if ((buffer2.length - o5) % 4 === 1) {
    throw new RangeError(
      `Cannot decode input as base64: Length (${buffer2.length - o5}), excluding padding, must not have a remainder of 1 when divided by 4`
    );
  }
  i6 += 3;
  for (; i6 < buffer2.length; i6 += 4) {
    const x3 = getByte(buffer2[i6 - 3], alphabet5) << 18 | getByte(buffer2[i6 - 2], alphabet5) << 12 | getByte(buffer2[i6 - 1], alphabet5) << 6 | getByte(buffer2[i6], alphabet5);
    buffer2[o5++] = x3 >> 16;
    buffer2[o5++] = x3 >> 8 & 255;
    buffer2[o5++] = x3 & 255;
  }
  switch (i6) {
    case buffer2.length + 1: {
      const x3 = getByte(buffer2[i6 - 3], alphabet5) << 18 | getByte(buffer2[i6 - 2], alphabet5) << 12;
      buffer2[o5++] = x3 >> 16;
      break;
    }
    case buffer2.length: {
      const x3 = getByte(buffer2[i6 - 3], alphabet5) << 18 | getByte(buffer2[i6 - 2], alphabet5) << 12 | getByte(buffer2[i6 - 1], alphabet5) << 6;
      buffer2[o5++] = x3 >> 16;
      buffer2[o5++] = x3 >> 8 & 255;
      break;
    }
  }
  return o5;
}
function getByte(char, alphabet5) {
  const byte = alphabet5[char] ?? 64;
  if (byte === 64) {
    throw new TypeError(
      `Cannot decode input as base64: Invalid character (${String.fromCharCode(char)})`
    );
  }
  return byte;
}
var padding, alphabet, rAlphabet;
var init_common64 = __esm({
  "https://jsr.io/@std/encoding/1.0.9/_common64.ts"() {
    padding = "=".charCodeAt(0);
    alphabet = {
      Base64: new TextEncoder().encode("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),
      Base64Url: new TextEncoder().encode("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_")
    };
    rAlphabet = {
      Base64: new Uint8Array(128).fill(64),
      // alphabet.Base64.length
      Base64Url: new Uint8Array(128).fill(64)
    };
    alphabet.Base64.forEach((byte, i6) => rAlphabet.Base64[byte] = i6);
    alphabet.Base64Url.forEach((byte, i6) => rAlphabet.Base64Url[byte] = i6);
  }
});

// https://jsr.io/@std/encoding/1.0.9/_common_detach.ts
function detach(buffer2, maxSize) {
  const originalSize = buffer2.length;
  if (buffer2.byteOffset) {
    const b3 = new Uint8Array(buffer2.buffer);
    b3.set(buffer2);
    buffer2 = b3.subarray(0, originalSize);
  }
  buffer2 = new Uint8Array(buffer2.buffer.transfer(maxSize));
  buffer2.set(buffer2.subarray(0, originalSize), maxSize - originalSize);
  return [buffer2, maxSize - originalSize];
}
var init_common_detach = __esm({
  "https://jsr.io/@std/encoding/1.0.9/_common_detach.ts"() {
  }
});

// https://jsr.io/@std/encoding/1.0.9/base64.ts
function encodeBase64(data3) {
  if (typeof data3 === "string") {
    data3 = new TextEncoder().encode(data3);
  } else if (data3 instanceof ArrayBuffer) data3 = new Uint8Array(data3).slice();
  else data3 = data3.slice();
  const [output, i6] = detach(
    data3,
    calcSizeBase64(data3.length)
  );
  encode(output, i6, 0, alphabet2, padding2);
  return new TextDecoder().decode(output);
}
function decodeBase64(b64) {
  const output = new TextEncoder().encode(b64);
  return new Uint8Array(output.buffer.transfer(decode(output, 0, 0, rAlphabet2, padding2)));
}
var padding2, alphabet2, rAlphabet2;
var init_base64 = __esm({
  "https://jsr.io/@std/encoding/1.0.9/base64.ts"() {
    init_common64();
    init_common_detach();
    padding2 = "=".charCodeAt(0);
    alphabet2 = new TextEncoder().encode("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
    rAlphabet2 = new Uint8Array(128).fill(64);
    alphabet2.forEach((byte, i6) => rAlphabet2[byte] = i6);
  }
});

// core/lib/yaml-schema/chunk-metadata.ts
function checkForEqualsInChunk(error2, _parse, _schema) {
  if (typeof error2.violatingObject.result !== "string") {
    return error2;
  }
  const badObject = error2.source.value.substring(
    error2.violatingObject.start,
    error2.violatingObject.end
  );
  if (errorKeyword(error2) !== "type") {
    return error2;
  }
  let m4;
  const heading = `${error2.location}: ${quotedStringColor(badObject)} must be a YAML mapping.`;
  const errorMsg = [`${quotedStringColor(badObject)} is a string.`];
  const newError = {
    heading,
    error: errorMsg,
    info: {}
  };
  addFileInfo(newError, error2.source);
  addInstancePathInfo(newError, error2.instancePath);
  if (m4 = badObject.match(/= *TRUE/i)) {
    newError.info["suggestion-fix"] = `Try using ${quotedStringColor(": true")} instead of ${quotedStringColor(m4[0])}.`;
  } else if (m4 = badObject.match(/= *FALSE/i)) {
    newError.info["suggestion-fix"] = `Try using ${quotedStringColor(": false")} instead of ${quotedStringColor(m4[0])}.`;
  } else if (badObject.match("=")) {
    newError.info["suggestion-fix"] = `Try using ${quotedStringColor(":")} instead of ${quotedStringColor("=")}.`;
  } else {
    return error2;
  }
  return {
    ...error2,
    message: tidyverseFormatError(newError)
  };
}
async function getEngineOptionsSchema() {
  const obj = {
    markdown: await markdownEngineSchema(),
    knitr: await knitrEngineSchema(),
    jupyter: await jupyterEngineSchema(),
    julia: await juliaEnginesSchema()
  };
  return obj;
}
var makeEngineSchema, markdownEngineSchema, knitrEngineSchema, jupyterEngineSchema, juliaEnginesSchema;
var init_chunk_metadata = __esm({
  "core/lib/yaml-schema/chunk-metadata.ts"() {
    init_from_yaml();
    init_common4();
    init_errors();
    init_definitions();
    init_errors2();
    init_error2();
    makeEngineSchema = (engine) => idSchema(
      objectRefSchemaFromContextGlob(
        "cell-*",
        (field, _path) => {
          const engineTag = field && field.tags && field.tags.engine;
          switch (typeof engineTag) {
            case "undefined":
              return true;
            case "string":
              return engineTag === engine;
            case "object":
              return engineTag.indexOf(engine) !== -1;
            default:
              throw new InternalError(`bad engine tag ${engineTag}`);
          }
        }
      ),
      `engine-${engine}`
    );
    markdownEngineSchema = defineCached(
      // deno-lint-ignore require-await
      async () => {
        return {
          schema: makeEngineSchema("markdown"),
          errorHandlers: []
        };
      },
      "engine-markdown"
    );
    knitrEngineSchema = defineCached(
      async () => {
        const result2 = await makeEngineSchema("knitr");
        return { schema: result2, errorHandlers: [checkForEqualsInChunk] };
      },
      "engine-knitr"
    );
    jupyterEngineSchema = defineCached(
      // deno-lint-ignore require-await
      async () => {
        return {
          schema: makeEngineSchema("jupyter"),
          errorHandlers: []
        };
      },
      "engine-jupyter"
    );
    juliaEnginesSchema = defineCached(
      // deno-lint-ignore require-await
      async () => {
        return {
          schema: makeEngineSchema("julia"),
          errorHandlers: []
        };
      },
      "engine-julia"
    );
  }
});

// core/lib/guess-chunk-options-format.ts
function guessChunkOptionsFormat(options) {
  const noIndentOrColon = /^[^:\s]+[^:]+$/;
  const chunkLines = lines(options);
  if (chunkLines.filter((l6) => l6.match(noIndentOrColon)).length === 0) {
    return "yaml";
  }
  if (chunkLines.some(
    (l6) => l6.trim() !== "" && !l6.trimRight().endsWith(",") && l6.indexOf("=") === -1
  )) {
    return "yaml";
  }
  return "knitr";
}
var init_guess_chunk_options_format = __esm({
  "core/lib/guess-chunk-options-format.ts"() {
    init_text();
  }
});

// core/lib/partition-cell-options.ts
function mappedSource(source2, substrs) {
  const params = [];
  for (const { range } of substrs) {
    params.push(range);
  }
  return mappedString(source2, params);
}
function partitionCellOptions(language, source2) {
  const commentChars = langCommentChars(language);
  const optionPattern = optionCommentPattern(commentChars[0]);
  const optionSuffix = commentChars[1] || "";
  const optionsSource = [];
  const yamlLines = [];
  for (const line of source2) {
    const optionMatch = line.match(optionPattern);
    if (optionMatch) {
      if (!optionSuffix || line.trimEnd().endsWith(optionSuffix)) {
        let yamlOption = line.substring(optionMatch[0].length);
        if (optionSuffix) {
          yamlOption = yamlOption.trimEnd();
          yamlOption = yamlOption.substring(
            0,
            yamlOption.length - optionSuffix.length
          );
          if (line.endsWith("\r\n")) {
            yamlOption += "\r\n";
          } else if (line.endsWith("\r") || line.endsWith("\n")) {
            yamlOption += line[line.length - 1];
          }
        }
        yamlLines.push(yamlOption);
        optionsSource.push(line);
        continue;
      }
    }
    break;
  }
  if (guessChunkOptionsFormat(yamlLines.join("\n")) === "knitr") {
    return {
      yaml: void 0,
      optionsSource,
      source: source2.slice(yamlLines.length),
      sourceStartLine: yamlLines.length
    };
  }
  let yaml;
  if (yamlLines.length > 0) {
    yaml = readAnnotatedYamlFromMappedString(
      asMappedString(yamlLines.join("\n"))
    ).result;
  }
  return {
    yaml,
    optionsSource,
    source: source2.slice(yamlLines.length),
    sourceStartLine: yamlLines.length
  };
}
async function parseAndValidateCellOptions(mappedYaml, language, validate2 = false, engine = "", lenient = false) {
  if (mappedYaml.value.trim().length === 0) {
    return void 0;
  }
  const engineOptionsSchema = await getEngineOptionsSchema();
  let schema4 = engineOptionsSchema[engine];
  const languages2 = getYamlIntelligenceResource(
    "handlers/languages.yml"
  );
  if (languages2.indexOf(language) !== -1) {
    try {
      schema4 = getYamlIntelligenceResource(
        `handlers/${language}/schema.yml`
      );
    } catch (_e) {
      schema4 = void 0;
    }
  }
  if (schema4 === void 0 || !validate2) {
    return readAnnotatedYamlFromMappedString(mappedYaml, lenient).result;
  }
  const { yaml, yamlValidationErrors } = await readAndValidateYamlFromMappedString(
    mappedYaml,
    schema4,
    void 0,
    lenient
  );
  if (yamlValidationErrors.length > 0) {
    throw new ValidationError4(
      `Validation of YAML metadata for cell with engine ${engine} failed`,
      yamlValidationErrors
    );
  }
  return yaml;
}
function partitionCellOptionsText(language, source2) {
  const commentChars = langCommentChars(language);
  const optionPattern = optionCommentPattern(commentChars[0]);
  const optionSuffix = commentChars[1] || "";
  const optionsSource = [];
  const yamlLines = [];
  let endOfYaml = 0;
  for (const line of rangedLines(source2.value, true)) {
    const optionMatch = line.substring.match(optionPattern);
    if (optionMatch) {
      if (!optionSuffix || line.substring.trimEnd().endsWith(optionSuffix)) {
        let yamlOption = line.substring.substring(optionMatch[0].length);
        if (optionSuffix) {
          yamlOption = yamlOption.trimEnd();
          yamlOption = yamlOption.substring(
            0,
            yamlOption.length - optionSuffix.length
          ).trimEnd();
        }
        endOfYaml = line.range.start + optionMatch[0].length + yamlOption.length;
        const rangedYamlOption = {
          substring: yamlOption,
          range: {
            start: line.range.start + optionMatch[0].length,
            end: endOfYaml
          }
        };
        yamlLines.push(rangedYamlOption);
        if (optionSuffix) {
          if (line.substring.endsWith("\r\n")) {
            yamlLines.push({
              substring: "\r\n",
              range: {
                start: line.range.end - 2,
                end: line.range.end
              }
            });
          } else if (line.substring.endsWith("\r") || line.substring.endsWith("\n")) {
            yamlLines.push({
              substring: line.substring[line.substring.length - 1],
              range: {
                start: line.range.end - 1,
                end: line.range.end
              }
            });
          }
        }
        optionsSource.push(line);
        continue;
      }
    }
    break;
  }
  const mappedYaml = yamlLines.length ? mappedSource(source2, yamlLines) : void 0;
  return {
    // yaml: yaml as Record<string, unknown> | undefined,
    // yamlValidationErrors,
    yaml: mappedYaml,
    optionsSource,
    source: mappedString(source2, [{
      start: endOfYaml,
      end: source2.value.length
    }]),
    // .slice(yamlLines.length),
    sourceStartLine: yamlLines.length
  };
}
async function partitionCellOptionsMapped(language, outerSource, validate2 = false, engine = "", lenient = false) {
  const {
    yaml: mappedYaml,
    optionsSource,
    source: source2,
    sourceStartLine
  } = partitionCellOptionsText(language, outerSource);
  if (language !== "r" || // only skip validation when language === 'r' and guessChunkOptionsFormat == "knitr"
  guessChunkOptionsFormat((mappedYaml || asMappedString("")).value) === "yaml") {
    const yaml = await parseAndValidateCellOptions(
      mappedYaml || asMappedString(""),
      language,
      validate2,
      engine,
      lenient
    );
    return {
      yaml,
      optionsSource,
      source: source2,
      sourceStartLine
    };
  } else {
    return {
      yaml: void 0,
      optionsSource,
      source: source2,
      sourceStartLine
    };
  }
}
function langCommentChars(lang) {
  const chars = kLangCommentChars[lang] || "#";
  if (!Array.isArray(chars)) {
    return [chars];
  } else {
    return chars;
  }
}
function optionCommentPattern(comment) {
  return new RegExp("^" + escapeRegExp(comment) + "\\s*\\| ?");
}
function addLanguageComment(language, comment) {
  kLangCommentChars[language] = comment;
}
function optionCommentPatternFromLanguage(language) {
  return optionCommentPattern(langCommentChars(language)[0]);
}
function escapeRegExp(str3) {
  return str3.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
var kLangCommentChars;
var init_partition_cell_options = __esm({
  "core/lib/partition-cell-options.ts"() {
    init_ranged_text();
    init_mapped_text();
    init_chunk_metadata();
    init_guess_chunk_options_format();
    init_resources();
    init_validated_yaml();
    init_annotated_yaml();
    kLangCommentChars = {
      r: "#",
      python: "#",
      julia: "#",
      scala: "//",
      matlab: "%",
      csharp: "//",
      fsharp: "//",
      c: ["/*", "*/"],
      css: ["/*", "*/"],
      sas: ["*", ";"],
      powershell: "#",
      bash: "#",
      sql: "--",
      mysql: "--",
      psql: "--",
      lua: "--",
      cpp: "//",
      cc: "//",
      stan: "#",
      octave: "#",
      fortran: "!",
      fortran95: "!",
      awk: "#",
      gawk: "#",
      stata: "*",
      java: "//",
      groovy: "//",
      sed: "#",
      perl: "#",
      prql: "#",
      ruby: "#",
      tikz: "%",
      js: "//",
      d3: "//",
      node: "//",
      sass: "//",
      scss: "//",
      coffee: "#",
      go: "//",
      asy: "//",
      haskell: "--",
      dot: "//",
      ojs: "//",
      apl: "\u235D",
      ocaml: ["(*", "*)"],
      q: "/",
      rust: "//"
    };
  }
});

// core/uuid.ts
function shortUuid() {
  return globalThis.crypto.randomUUID().replaceAll("-", "").slice(0, 8);
}
var init_uuid = __esm({
  "core/uuid.ts"() {
  }
});

// core/mime.ts
function extensionForMimeImageType(mimeType, defaultType = "bin") {
  switch (mimeType) {
    case kImagePng:
      return "png";
    case kImageJpeg:
      return "jpeg";
    case kImageSvg:
      return "svg";
    case kApplicationPdf:
      return "pdf";
    default:
      return defaultType;
  }
}
function contentType(path3) {
  return MEDIA_TYPES[extname4(path3.toLowerCase())];
}
function isPdfContent(path3) {
  return !!path3 && contentType(path3) === kApplicationPdf;
}
function isDocxContent(path3) {
  return !!path3 && contentType(path3) === kDocxDocument;
}
function isHtmlContent(path3) {
  return !!path3 && contentType(path3) === kTextHtml;
}
function isTextContent(path3) {
  return !!path3 && (contentType(path3) === kTextMarkdown || contentType(path3) === kTextPlain || contentType(path3) === kTextXml);
}
var kTextHtml, kTextMarkdown, kTextLatex, kTextPlain, kTextXml, kTextCss, kImagePng, kImageJpeg, kImageSvg, kApplicationPdf, kApplicationJavascript, kApplicationJupyterWidgetState, kApplicationJupyterWidgetView, kDocxDocument, kRestructuredText, kApplicationRtf, MEDIA_TYPES;
var init_mime = __esm({
  "core/mime.ts"() {
    init_path();
    kTextHtml = "text/html";
    kTextMarkdown = "text/markdown";
    kTextLatex = "text/latex";
    kTextPlain = "text/plain";
    kTextXml = "text/xml";
    kTextCss = "text/css";
    kImagePng = "image/png";
    kImageJpeg = "image/jpeg";
    kImageSvg = "image/svg+xml";
    kApplicationPdf = "application/pdf";
    kApplicationJavascript = "application/javascript";
    kApplicationJupyterWidgetState = "application/vnd.jupyter.widget-state+json";
    kApplicationJupyterWidgetView = "application/vnd.jupyter.widget-view+json";
    kDocxDocument = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
    kRestructuredText = "text/restructuredtext";
    kApplicationRtf = "application/rtf";
    MEDIA_TYPES = {
      ".md": kTextMarkdown,
      ".markdown": kTextMarkdown,
      ".html": kTextHtml,
      ".htm": kTextHtml,
      ".json": "application/json",
      ".ipynb": "application/x-ipynb+json",
      ".map": "application/json",
      ".txt": kTextPlain,
      ".tex": kTextPlain,
      ".adoc": kTextPlain,
      ".asciidoc": kTextPlain,
      ".xml": kTextXml,
      ".ts": "text/typescript",
      ".tsx": "text/tsx",
      ".js": kApplicationJavascript,
      ".jsx": "text/jsx",
      ".gz": "application/gzip",
      ".css": kTextCss,
      ".wasm": "application/wasm",
      ".mjs": kApplicationJavascript,
      ".svg": kImageSvg,
      ".png": kImagePng,
      ".jpg": kImageJpeg,
      ".jpeg": kImageJpeg,
      ".pdf": kApplicationPdf,
      ".gif": "image/gif",
      ".wav": "audio/wav",
      ".mp4": "video/mp4",
      ".woff": "application/font-woff",
      ".ttf": "application/font-ttf",
      ".eot": "application/vnd.ms-fontobject",
      ".otf": "application/font-otf",
      ".textile": kTextPlain,
      ".texinfo": kTextPlain,
      ".tei": kTextPlain,
      ".rst": kTextPlain,
      ".org": kTextPlain,
      ".opml": kTextPlain,
      ".muse": kTextPlain,
      ".ms": kTextPlain,
      ".native": kTextPlain,
      ".man": kTextPlain,
      ".dokuwiki": kTextPlain,
      ".haddock": kTextPlain,
      ".icml": kTextPlain,
      ".jira": kTextPlain,
      ".mediawiki": kTextPlain,
      ".xwiki": kTextPlain,
      ".zim": kTextPlain,
      ".typ": kTextPlain,
      ".docx": kDocxDocument
    };
  }
});

// core/png.ts
function bytesToUint32(byteArray, start = 0, count) {
  if (count === void 0) {
    count = byteArray.length;
  }
  if (count > 4) {
    throw new Error("Length cannot be greater than 4");
  }
  let position = start;
  let value = 0;
  if (count === 4) {
    let sigValue = byteArray[position];
    if (sigValue > MAX_SIGNIFICANT_SIZE) {
      value += MAX_SIGNIFICANT_SIZE << 24;
      sigValue -= MAX_SIGNIFICANT_SIZE;
    }
    value += sigValue << 24;
    position++;
  }
  for (let i6 = position; i6 < start + count; i6++) {
    value += byteArray[i6] << 8 * (count - (i6 - start) - 1);
  }
  return value;
}
function bytesToString(byteArray, start = 0, count) {
  if (count === void 0) {
    count = byteArray.length;
  }
  let result2 = "";
  for (let i6 = start; i6 < start + count; i6++) {
    const byte = byteArray[i6];
    if (byte === 0) {
      result2 += "00";
    } else if (byte < 10) {
      result2 += `0${byte.toString()}`;
    } else {
      result2 += byte.toString();
    }
  }
  return result2;
}
var PngImage, PngChunk, MAX_SIGNIFICANT_SIZE;
var init_png = __esm({
  "core/png.ts"() {
    PngImage = class {
      content = [];
      width = -1;
      height = -1;
      dpiX = -1;
      dpiY = -1;
      bitDepth = -1;
      colourType = -1;
      compressionMethod = -1;
      filterMethod = -1;
      interlaceMethod = -1;
      constructor(bytes, sizeOnly = true) {
        const magicNumberBytes = bytes.slice(0, 8);
        const magicNumber = bytesToString(magicNumberBytes);
        if (magicNumber !== "13780787113102610") {
          throw new Error("Not a png file");
        }
        let pos = 8;
        while (pos < bytes.length) {
          const chunk = new PngChunk(bytes.slice(pos));
          switch (chunk.type) {
            case "IHDR":
              this.parseIHDRChunk(chunk, sizeOnly);
              break;
            case "pHYs":
              this.parsePHYSChunk(chunk);
              break;
            case "IDAT":
              return;
          }
          pos += chunk.totalLength;
        }
      }
      parseIHDRChunk(chunk, sizeOnly) {
        this.width = bytesToUint32(chunk.data, 0, 4);
        this.height = bytesToUint32(chunk.data, 4, 4);
        if (sizeOnly) {
          return;
        }
        this.bitDepth = chunk.data.slice(8, 9)[0];
        if (this.bitDepth !== 8) throw new Error("bitDepth not supported");
        this.colourType = chunk.data.slice(9, 10)[0];
        if (this.colourType !== 6) throw new Error("colourType not supported");
        this.compressionMethod = chunk.data.slice(10, 11)[0];
        if (this.compressionMethod !== 0) {
          throw new Error("compressionMethod not supported");
        }
        this.filterMethod = chunk.data.slice(11, 12)[0];
        if (this.filterMethod !== 0) throw new Error("filterMethod not supported");
        this.interlaceMethod = chunk.data.slice(12, 13)[0];
        if (this.interlaceMethod !== 0) {
          throw new Error("Interlacing not supported");
        }
      }
      parsePHYSChunk(chunk) {
        const meter = chunk.data[8];
        if (meter === 1) {
          const x3 = bytesToUint32(chunk.data, 0, 4);
          const y4 = bytesToUint32(chunk.data, 4, 4);
          const kMetersPerInch = 0.0254;
          this.dpiX = Math.round(x3 * kMetersPerInch);
          this.dpiY = Math.round(y4 * kMetersPerInch);
        }
      }
    };
    PngChunk = class {
      totalLength;
      dataLength;
      type;
      data;
      crc;
      constructor(bytes) {
        this.dataLength = this.getLength(bytes);
        this.type = this.getType(bytes);
        this.data = this.getData(bytes);
        this.crc = this.getCRC(bytes);
        this.totalLength = this.dataLength + 12;
      }
      getLength(bytes) {
        const lengthBytes = bytes.slice(0, 4);
        return bytesToUint32(lengthBytes);
      }
      getType(bytes) {
        const typeByte = bytes.slice(4, 8);
        return new TextDecoder("ascii").decode(typeByte);
      }
      getData(bytes) {
        return bytes.slice(8, 8 + this.dataLength);
      }
      getCRC(bytes) {
        return bytes.slice(8 + this.dataLength, 8 + this.dataLength + 4);
      }
    };
    MAX_SIGNIFICANT_SIZE = 127;
  }
});

// core/jupyter/tags.ts
function hideCell(cell, options) {
  return shouldHide(cell, options, kInclude);
}
function hideCode(cell, options) {
  return shouldHide(cell, options, kEcho);
}
function hideOutput(cell, options) {
  return shouldHide(cell, options, kOutput);
}
function hideWarnings(cell, options) {
  if (options.execute[kOutput] === false && cell.options[kOutput] !== false) {
    return cell.options[kWarning] || false;
  } else {
    return shouldHide(cell, options, kWarning);
  }
}
function includeCell(cell, options) {
  return shouldInclude(
    cell,
    options,
    kInclude
  );
}
function includeCode(cell, options) {
  return shouldInclude(
    cell,
    options,
    kEcho
  );
}
function echoFenced(cell, options) {
  const fenced = cell.options.echo === "fenced" || cell.options.echo === void 0 && options.execute.echo === "fenced";
  return fenced;
}
function includeOutput(cell, options) {
  return shouldInclude(
    cell,
    options,
    kOutput
  );
}
function includeWarnings(cell, options) {
  if (options.execute[kOutput] === false && cell.options[kOutput] !== false) {
    return cell.options[kWarning] || false;
  } else {
    return shouldInclude(
      cell,
      options,
      kWarning
    );
  }
}
function shouldHide(cell, options, context) {
  if (cell.options[context] !== void 0) {
    return !cell.options[context] && options.keepHidden;
  } else {
    return !options.execute[context] && options.keepHidden;
  }
}
function shouldInclude(cell, options, context) {
  if (cell.options[context] !== void 0) {
    return !!(cell.options[context] || options.keepHidden);
  } else {
    return !!(options.execute[context] || options.keepHidden);
  }
}
var init_tags = __esm({
  "core/jupyter/tags.ts"() {
    init_constants6();
  }
});

// core/pandoc/pandoc-id.ts
function pandocAutoIdentifier(text, asciify) {
  if (asciify) {
    text = pandocAsciify(text);
  }
  return text.replace(/[!"#$%&')*+,\/:;<=>?@\[\\\]^`{|}~]/g, "").replace(/\s/g, "-").toLowerCase().replace(/^[^A-Za-z]+/, "");
}
function gfmAutoIdentifier(text, asciify) {
  if (asciify) {
    text = pandocAsciify(text);
  }
  return text.replace(/[!"#$%&')*+,\.\/:;<=>?@\[\\\]^`{|}~]/g, "").replace(/\s/g, "-").toLowerCase();
}
function pandocAsciify(text) {
  const chars = [];
  const len = text.length;
  let newch;
  for (let i6 = 0; i6 < len; i6++) {
    newch = "";
    const ch = text.charCodeAt(i6);
    switch (ch) {
      case 192:
      case 193:
      case 194:
      case 195:
      case 196:
      case 197:
      case 256:
      case 258:
      case 260:
      case 461:
      case 512:
      case 514:
      case 550:
      case 7680:
      case 7840:
      case 7842:
        newch = "A";
        break;
      case 7682:
      case 7684:
      case 7686:
        newch = "B";
        break;
      case 199:
      case 262:
      case 264:
      case 266:
      case 268:
        newch = "C";
        break;
      case 270:
      case 7690:
      case 7692:
      case 7694:
      case 7696:
      case 7698:
        newch = "D";
        break;
      case 200:
      case 201:
      case 203:
      case 274:
      case 276:
      case 278:
      case 280:
      case 282:
      case 516:
      case 518:
      case 552:
      case 7704:
      case 7706:
      case 7864:
      case 7866:
      case 7868:
        newch = "E";
        break;
      case 7710:
        newch = "F";
        break;
      case 284:
      case 286:
      case 288:
      case 290:
      case 486:
      case 500:
      case 7712:
        newch = "G";
        break;
      case 292:
      case 542:
      case 7714:
      case 7716:
      case 7718:
      case 7720:
      case 7722:
        newch = "H";
        break;
      case 204:
      case 205:
      case 206:
      case 207:
      case 296:
      case 298:
      case 300:
      case 302:
      case 304:
      case 463:
      case 520:
      case 522:
      case 7724:
      case 7880:
      case 7882:
        newch = "I";
        break;
      case 308:
        newch = "J";
        break;
      case 310:
      case 488:
      case 7728:
      case 7730:
      case 7732:
      case 8490:
        newch = "K";
        break;
      case 313:
      case 315:
      case 317:
      case 7734:
      case 7738:
      case 7740:
        newch = "L";
        break;
      case 7742:
      case 7744:
      case 7746:
        newch = "M";
        break;
      case 209:
      case 323:
      case 325:
      case 327:
      case 504:
      case 7748:
      case 7750:
      case 7752:
      case 7754:
        newch = "N";
        break;
      case 210:
      case 211:
      case 212:
      case 213:
      case 214:
      case 332:
      case 334:
      case 336:
      case 416:
      case 465:
      case 490:
      case 524:
      case 526:
      case 558:
      case 7884:
      case 7886:
        newch = "O";
        break;
      case 7764:
      case 7766:
        newch = "P";
        break;
      case 340:
      case 342:
      case 344:
      case 528:
      case 530:
      case 7768:
      case 7770:
      case 7774:
        newch = "R";
        break;
      case 346:
      case 348:
      case 350:
      case 352:
      case 536:
      case 7776:
      case 7778:
        newch = "S";
        break;
      case 354:
      case 356:
      case 538:
      case 7786:
      case 7788:
      case 7790:
      case 7792:
        newch = "T";
        break;
      case 217:
      case 218:
      case 219:
      case 220:
      case 360:
      case 362:
      case 364:
      case 366:
      case 368:
      case 370:
      case 431:
      case 467:
      case 532:
      case 534:
      case 7794:
      case 7796:
      case 7798:
      case 7908:
      case 7910:
        newch = "U";
        break;
      case 7804:
      case 7806:
        newch = "V";
        break;
      case 372:
      case 7808:
      case 7810:
      case 7812:
      case 7814:
      case 7816:
        newch = "W";
        break;
      case 7818:
      case 7820:
        newch = "X";
        break;
      case 221:
      case 374:
      case 376:
      case 562:
      case 7822:
      case 7922:
      case 7924:
      case 7926:
      case 7928:
        newch = "Y";
        break;
      case 377:
      case 379:
      case 381:
      case 7824:
      case 7826:
      case 7828:
        newch = "Z";
        break;
      case 224:
      case 225:
      case 226:
      case 227:
      case 228:
      case 229:
      case 257:
      case 259:
      case 261:
      case 462:
      case 513:
      case 515:
      case 551:
      case 553:
      case 7681:
      case 7841:
      case 7843:
        newch = "a";
        break;
      case 7683:
      case 7685:
      case 7687:
        newch = "b";
        break;
      case 231:
      case 263:
      case 265:
      case 267:
      case 269:
        newch = "c";
        break;
      case 271:
      case 7691:
      case 7693:
      case 7695:
      case 7697:
      case 7699:
        newch = "d";
        break;
      case 232:
      case 233:
      case 234:
      case 235:
      case 275:
      case 277:
      case 279:
      case 281:
      case 283:
      case 517:
      case 519:
      case 7705:
      case 7707:
      case 7865:
      case 7867:
      case 7869:
        newch = "e";
        break;
      case 7711:
        newch = "f";
        break;
      case 285:
      case 287:
      case 289:
      case 291:
      case 487:
      case 501:
      case 7713:
        newch = "g";
        break;
      case 293:
      case 543:
      case 7715:
      case 7717:
      case 7719:
      case 7721:
      case 7723:
      case 7830:
        newch = "h";
        break;
      case 236:
      case 237:
      case 238:
      case 239:
      case 297:
      case 299:
      case 301:
      case 303:
      case 305:
      case 464:
      case 521:
      case 523:
      case 7725:
      case 7881:
      case 7883:
        newch = "i";
        break;
      case 309:
      case 496:
        newch = "j";
        break;
      case 311:
      case 489:
      case 7729:
      case 7731:
      case 7733:
        newch = "k";
        break;
      case 314:
      case 316:
      case 318:
      case 7735:
      case 7739:
      case 7741:
        newch = "l";
        break;
      case 7743:
      case 7745:
      case 7747:
        newch = "m";
        break;
      case 241:
      case 324:
      case 326:
      case 328:
      case 505:
      case 7749:
      case 7751:
      case 7753:
      case 7755:
        newch = "n";
        break;
      case 242:
      case 243:
      case 244:
      case 245:
      case 246:
      case 333:
      case 335:
      case 337:
      case 417:
      case 432:
      case 466:
      case 491:
      case 525:
      case 527:
      case 559:
      case 7885:
      case 7887:
        newch = "o";
        break;
      case 7765:
      case 7767:
        newch = "p";
        break;
      case 341:
      case 343:
      case 345:
      case 529:
      case 531:
      case 7769:
      case 7771:
      case 7775:
        newch = "r";
        break;
      case 347:
      case 349:
      case 351:
      case 353:
      case 537:
      case 7777:
      case 7779:
        newch = "s";
        break;
      case 355:
      case 357:
      case 539:
      case 7787:
      case 7789:
      case 7791:
      case 7793:
      case 7831:
        newch = "t";
        break;
      case 249:
      case 250:
      case 251:
      case 252:
      case 361:
      case 363:
      case 365:
      case 367:
      case 369:
      case 371:
      case 468:
      case 533:
      case 535:
      case 7795:
      case 7797:
      case 7799:
      case 7909:
      case 7911:
        newch = "u";
        break;
      case 7805:
      case 7807:
        newch = "v";
        break;
      case 373:
      case 7809:
      case 7811:
      case 7813:
      case 7815:
      case 7817:
      case 7832:
        newch = "w";
        break;
      case 7819:
      case 7821:
        newch = "x";
        break;
      case 253:
      case 255:
      case 375:
      case 563:
      case 7833:
      case 7923:
      case 7925:
      case 7927:
      case 7929:
        newch = "y";
        break;
      case 378:
      case 380:
      case 382:
      case 7825:
      case 7827:
      case 7829:
        newch = "z";
        break;
      case 894:
        newch = ";";
        break;
      case 8175:
        newch = "`";
        break;
      case 8800:
        newch = "=";
        break;
      case 8814:
        newch = "<";
        break;
      case 8815:
        newch = ">";
        break;
    }
    if (newch) {
      chars.push(newch.charCodeAt(0));
    } else if (ch < 128) {
      chars.push(ch);
    }
  }
  return String.fromCharCode(...chars);
}
var init_pandoc_id = __esm({
  "core/pandoc/pandoc-id.ts"() {
  }
});

// core/http.ts
function isAbsoluteRef(href) {
  return /^(?:http|https)\:\/\/.+/.test(href);
}
function isFileRef(href) {
  return !/^\w+:/.test(href) && !href.startsWith("#");
}
function httpFileRequestHandler(options) {
  async function serveFile(filePath, req) {
    let fileResponse;
    if (options.onFile) {
      fileResponse = await options.onFile(filePath, req);
    }
    if (!fileResponse) {
      fileResponse = {
        contentType: contentType(filePath),
        body: Deno.readFileSync(filePath)
      };
    }
    return httpContentResponse(fileResponse.body, fileResponse.contentType);
  }
  function serveFallback(req, e5, fsPath) {
    const encoder4 = new TextEncoder();
    if (e5 instanceof URIError) {
      return Promise.resolve(
        new Response(encoder4.encode("BadRequest"), { status: 400 })
      );
    } else if (e5 instanceof Deno.errors.NotFound) {
      const url = normalizeURL(req.url);
      const handle404 = options.on404 ? options.on404(url, req) : { print: true, response: { body: encoder4.encode("Not Found") } };
      const ignoreFileNames = [
        "favicon.ico",
        "listings.json",
        /jupyter-.*.js/,
        /apple-touch-icon-/
      ];
      handle404.print = handle404.print && !!options.printUrls && (!fsPath || !ignoreFileNames.find((name2) => {
        return basename4(fsPath).match(name2);
      }) && extname4(fsPath) !== ".map");
      if (handle404.print) {
        printUrl(url, false);
      }
      return Promise.resolve(
        new Response(handle404.response.body, {
          status: 404,
          headers: {
            "Content-Type": kTextHtml
          }
        })
      );
    } else {
      error(`500 (Internal Error): ${e5.message}`, { bold: true });
      return Promise.resolve(
        new Response(encoder4.encode("Internal server error"), {
          status: 500
        })
      );
    }
  }
  return async (req) => {
    if (options.onRequest) {
      const response2 = await options.onRequest(req);
      if (response2) {
        return response2;
      }
    }
    let response;
    let fsPath;
    try {
      const baseDir = pathWithForwardSlashes(options.baseDir);
      const normalizedUrl = normalizeURL(req.url);
      fsPath = pathWithForwardSlashes(baseDir + normalizedUrl);
      if (fsPath.indexOf(baseDir) !== 0) {
        fsPath = baseDir;
      }
      const fileInfo = existsSync2(fsPath) ? Deno.statSync(fsPath) : void 0;
      if (fileInfo && fileInfo.isDirectory) {
        fsPath = join4(fsPath, options.defaultFile || "index.html");
      }
      if (fileInfo?.isDirectory && !normalizedUrl.endsWith("/")) {
        response = serveRedirect(normalizedUrl + "/");
      } else {
        response = await serveFile(fsPath, req);
        if (normalizedUrl === "/" && !isBrowserPreviewable(fsPath)) {
          response.headers.append(
            "content-disposition",
            'attachment; filename="' + options.defaultFile + '"'
          );
        }
        if (options.printUrls === "all") {
          printUrl(normalizedUrl);
        }
      }
    } catch (e5) {
      if (!(e5 instanceof Error)) throw e5;
      if (fsPath) {
        fsPath = normalize4(fsPath);
      }
      response = await serveFallback(
        req,
        e5,
        fsPath
      );
    }
    return response;
  };
}
function httpContentResponse(content, contentType2) {
  if (typeof content === "string") {
    content = new TextEncoder().encode(content);
  }
  const headers = new Headers();
  headers.set("Content-Length", content.byteLength.toString());
  if (contentType2) {
    headers.set("Content-Type", contentType2);
  }
  headers.set("Cache-Control", "no-store, max-age=0");
  return new Response(content, {
    status: 200,
    headers
  });
}
function normalizeURL(url) {
  let normalizedUrl = url;
  try {
    normalizedUrl = decodeURI(normalizedUrl);
  } catch (e5) {
    if (!(e5 instanceof URIError)) {
      throw e5;
    }
  }
  try {
    const absoluteURI = new URL(normalizedUrl);
    normalizedUrl = decodeURI(absoluteURI.pathname);
  } catch (e5) {
    if (!(e5 instanceof TypeError)) {
      throw e5;
    }
  }
  if (normalizedUrl[0] !== "/") {
    throw new URIError("The request URI is malformed.");
  }
  normalizedUrl = posix.normalize(normalizedUrl);
  const startOfParams = normalizedUrl.indexOf("?");
  return startOfParams > -1 ? normalizedUrl.slice(0, startOfParams) : normalizedUrl;
}
function isBrowserPreviewable(file) {
  return isHtmlContent(file) || isPdfContent(file) || isTextContent(file);
}
function maybeDisplaySocketError(e5) {
  if (!(e5 instanceof Deno.errors.NotFound) && !(e5 instanceof Deno.errors.BrokenPipe) && !(e5 instanceof Deno.errors.NotConnected) && !(e5 instanceof Deno.errors.ConnectionAborted) && !(e5 instanceof Deno.errors.ConnectionReset) && !(e5 instanceof Deno.errors.ConnectionRefused) && !(e5 instanceof DOMException)) {
    logError(e5);
  }
}
function serveRedirect(url) {
  const headers = new Headers();
  headers.set("Cache-Control", "no-store, max-age=0");
  headers.set("Location", url);
  return new Response(null, {
    status: 301,
    headers
  });
}
function printUrl(url, found = true) {
  const format14 = !found ? red3 : void 0;
  const urlDisplay = url + (found ? "" : " (404: Not Found)");
  if (isHtmlContent(url) || url.endsWith("/") || extname4(url) === "") {
    info(`GET: ${urlDisplay}`, {
      bold: false,
      format: format14 || green2
    });
  } else if (!found) {
    info(urlDisplay, { dim: found, format: format14, indent: 2 });
  }
}
var init_http = __esm({
  "core/http.ts"() {
    init_fs();
    init_path();
    init_log();
    init_colors2();
    init_mime();
    init_log2();
    init_path2();
  }
});

// core/css.ts
function cssFileResourceReferences(files) {
  return files.reduce((allRefs, file) => {
    if (extname4(file).toLowerCase() === ".css") {
      if (existsSync2(file)) {
        file = normalizePath(file);
        const css = Deno.readTextFileSync(file);
        const cssRefs = cssFileRefs(css).map((ref3) => join4(dirname4(file), ref3));
        allRefs.push(...cssRefs);
        allRefs.push(...cssFileResourceReferences(cssRefs));
      }
    }
    return allRefs;
  }, []);
}
function isCssFile(path3) {
  return extname4(path3).toLowerCase() === ".css";
}
function fixupCssReferences(css, resolveRef) {
  let destCss = css.replaceAll(
    kCssUrlRegex,
    (_match, p1, p22) => {
      const path3 = resolveRef(p22);
      return `url(${p1 || ""}${path3}${p1 || ""})`;
    }
  );
  destCss = destCss.replaceAll(
    kCssImportRegex,
    (_match, p1, p22) => {
      const path3 = resolveRef(p22);
      return `@import ${p1 || ""}${path3}${p1 || ""}`;
    }
  );
  return destCss;
}
function cssFileRefs(css) {
  return cssImports(css).concat(cssResources(css)).filter(isFileRef);
}
function cssResources(css) {
  return matchCss(css, kCssUrlRegex);
}
function cssImports(css) {
  return matchCss(css, kCssImportRegex);
}
function matchCss(css, regex) {
  const matches = [];
  regex.lastIndex = 0;
  let match = regex.exec(css);
  while (match != null) {
    matches.push(match[2]);
    match = regex.exec(css);
  }
  regex.lastIndex = 0;
  return matches;
}
function asCssFont(value) {
  if (!value) {
    return void 0;
  } else {
    const fontFamily = String(value).split(",").map((font) => {
      font = font.trim();
      if (font.includes(" ") && !font.startsWith('"') && !font.startsWith("'")) {
        font = `"${font}"`;
      }
      return font;
    }).filter((font) => font.length > 0).join(", ");
    return `${fontFamily}`;
  }
}
function asCssNumber(value) {
  if (typeof value === "number") {
    return String(value);
  } else if (!value) {
    return void 0;
  } else {
    const str3 = String(value);
    const match = str3.match(/(^[0-9]*)/);
    if (match) {
      return match[1];
    } else {
      return void 0;
    }
  }
}
function asCssSize(value) {
  if (typeof value === "number") {
    if (value === 0) {
      return "0";
    } else {
      return value + "px";
    }
  } else if (!value) {
    return void 0;
  } else {
    const str3 = String(value);
    if (str3 !== "0" && !str3.match(/[^0-9]$/)) {
      return str3 + "px";
    } else {
      return str3;
    }
  }
}
function asCssColor(value) {
  if (typeof value === "string") {
    if (value === "none") {
      return "transparent";
    } else {
      return value;
    }
  }
}
function asBootstrapColor(value) {
  if (typeof value === "string") {
    if (kBootstrapColors.includes(value) || value.match(kBootstrapPaletteRegex)) {
      return `$${value}`;
    } else {
      return asCssColor(value);
    }
  }
}
var kCssUrlRegex, kCssImportRegex, kBootstrapColors, kBootstrapPaletteRegex;
var init_css = __esm({
  "core/css.ts"() {
    init_fs();
    init_path();
    init_http();
    init_path2();
    kCssUrlRegex = /url\((?!['"]?(?:data|https?):)(['"])?([^'"]*?)\1\)/g;
    kCssImportRegex = /@import\s(?!['"](?:data|https?):)(['"])([^'"]*?)\1/g;
    kBootstrapColors = [
      "primary",
      "secondary",
      "success",
      "info",
      "warning",
      "danger",
      "light",
      "dark"
    ];
    kBootstrapPaletteRegex = RegExp(
      `gray-[1-9]00`
    );
  }
});

// core/html.ts
function asHtmlId(text) {
  return pandocAutoIdentifier(text, false);
}
function getDecodedAttribute(element, attrib) {
  const value = element.getAttribute(attrib);
  if (value) {
    try {
      return decodeURI(value);
    } catch (e5) {
      if (e5 instanceof URIError) {
        warn(
          `Invalid URI '${value}' in attribute '${attrib}' of element '${element.tagName}'`
        );
        return value;
      } else {
        throw e5;
      }
    }
  } else {
    return value;
  }
}
function encodeAttributeValue(value) {
  if (typeof value === "string") {
    let result2 = value;
    Object.keys(kAttrReplacements).forEach((key) => {
      result2 = result2.replace(key, kAttrReplacements[key]);
    });
    return result2;
  } else {
    return value;
  }
}
function encodeHtml(value) {
  Object.keys(kTagBrackets).forEach((key) => {
    value = value.replaceAll(key, kTagBrackets[key]);
  });
  return value;
}
function findParent(el, match) {
  let targetEl = el;
  do {
    if (targetEl.parentElement) {
      if (match(targetEl.parentElement)) {
        return targetEl.parentElement;
      } else {
        targetEl = targetEl.parentElement;
      }
    } else {
      return void 0;
    }
  } while (targetEl !== null && targetEl.nodeType === 1);
  return void 0;
}
function discoverResourceRefs(doc) {
  const refs = [];
  Object.keys(kHtmlResourceTags).forEach((tag) => {
    for (const attrib of kHtmlResourceTags[tag]) {
      refs.push(...resolveResourceTag(doc, tag, attrib));
    }
  });
  const styles = doc.querySelectorAll("style");
  for (let i6 = 0; i6 < styles.length; i6++) {
    const style = styles[i6];
    if (style.innerHTML) {
      refs.push(...cssFileRefs(style.innerHTML));
    }
  }
  return Promise.resolve({ resources: refs, supporting: [] });
}
function fixEmptyHrefs(doc) {
  const anchors = doc.querySelectorAll("a");
  for (let i6 = 0; i6 < anchors.length; ++i6) {
    const anchor = anchors[i6];
    if (!anchor.getAttribute("href")) {
      anchor.setAttribute("href", "");
    }
  }
  return Promise.resolve({
    resources: [],
    supporting: []
  });
}
function processFileResourceRefs(doc, tag, attrib, onRef) {
  const tags = doc.querySelectorAll(tag);
  for (let i6 = 0; i6 < tags.length; i6++) {
    const tag2 = tags[i6];
    const href = getDecodedAttribute(tag2, attrib);
    if (href !== null && href.length > 0 && isFileRef(href)) {
      onRef(tag2, href);
    }
  }
}
function resolveResourceTag(doc, tag, attrib) {
  const refs = [];
  processFileResourceRefs(
    doc,
    tag,
    attrib,
    (_tag, ref3) => refs.push(ref3)
  );
  return refs;
}
var kTagBrackets, kAttrReplacements, kHtmlResourceTags;
var init_html = __esm({
  "core/html.ts"() {
    init_pandoc_id();
    init_http();
    init_css();
    init_log();
    kTagBrackets = {
      "<": "&lt;",
      ">": "&gt;"
    };
    kAttrReplacements = {
      '"': "&quot;",
      "'": "&#039;",
      ...kTagBrackets,
      "&": "&amp;"
    };
    kHtmlResourceTags = {
      "a": ["href"],
      "img": ["src", "data-src"],
      "link": ["href"],
      "script": ["src"],
      "embed": ["src"],
      "iframe": ["src"],
      "section": ["data-background-image", "data-background-video"],
      "source": ["src"]
    };
  }
});

// core/jupyter/display-data.ts
function isDisplayData(output) {
  return ["display_data", "execute_result"].includes(output.output_type);
}
function isCaptionableData(output) {
  if (isDisplayData(output)) {
    const displayData = output;
    return !displayData.noCaption;
  } else {
    return false;
  }
}
function displayDataMimeType(output, options) {
  const displayPriority = [
    kTextMarkdown,
    kImageSvg,
    kImagePng,
    kImageJpeg
  ];
  if (options.toHtml) {
    const htmlFormats = [
      kApplicationJupyterWidgetState,
      kApplicationJupyterWidgetView,
      kApplicationJavascript,
      kTextHtml
    ];
    if (options.toMarkdown) {
      displayPriority.unshift(...htmlFormats);
    } else {
      displayPriority.push(...htmlFormats);
    }
    displayPriority.unshift(
      kApplicationJupyterWidgetState,
      kApplicationJupyterWidgetView,
      kApplicationJavascript,
      kTextHtml
    );
  } else if (options.toLatex) {
    displayPriority.push(
      kTextLatex,
      kApplicationPdf
    );
  } else if (options.toMarkdown) {
    displayPriority.push(
      kTextHtml
    );
  }
  if (displayDataHasHtmlTable(output) && !displayPriority.includes(kTextHtml)) {
    displayPriority.push(kTextHtml);
  }
  displayPriority.push(
    kTextPlain
  );
  const availDisplay = Object.keys(output.data);
  for (const display of displayPriority) {
    if (availDisplay.includes(display)) {
      return display;
    }
  }
  return null;
}
function displayDataLatexIsMath(latex) {
  if (latex.length > 0) {
    const first = latex[0];
    const last = latex[latex.length - 1];
    return (
      // Inline or display math
      first.startsWith("$") && last.endsWith("$") || // Latex environment
      first.startsWith("\\begin{") && last.includes("\\end{")
    );
  }
  return false;
}
function displayDataWithMarkdownMath(output) {
  if (Array.isArray(output.data[kTextLatex]) && !output.data[kTextMarkdown]) {
    const latex = output.data[kTextLatex];
    if (displayDataLatexIsMath(latex)) {
      output = {
        ...output,
        data: {
          ...output.data,
          [kTextMarkdown]: latex
        }
      };
      return output;
    }
  }
  return output;
}
function displayDataHasHtmlTable(output) {
  const html = Array.isArray(output.data[kTextHtml]) ? output.data[kTextHtml] : typeof output.data[kTextHtml] === "string" ? [output.data[kTextHtml]] : void 0;
  if (html) {
    const htmlLower = html.map((line) => line.toLowerCase());
    return htmlLower.some((line) => !!line.match(/<[Tt][Aa][Bb][Ll][Ee]/)) && htmlLower.some((line) => !!line.match(/<\/[Tt][Aa][Bb][Ll][Ee]/));
  } else {
    return false;
  }
}
function displayDataIsImage(mimeType) {
  return [kImagePng, kImageJpeg, kImageSvg, kApplicationPdf].includes(mimeType);
}
function displayDataIsTextPlain(mimeType) {
  return [kTextPlain].includes(mimeType);
}
function displayDataIsMarkdown(mimeType) {
  return [kTextMarkdown].includes(mimeType);
}
function displayDataIsLatex(mimeType) {
  return [kTextLatex].includes(mimeType);
}
function displayDataIsHtml(mimeType) {
  return [kTextHtml].includes(mimeType);
}
function displayDataIsJson(mimeType) {
  return [kApplicationJupyterWidgetState, kApplicationJupyterWidgetView].includes(mimeType);
}
function displayDataIsJavascript(mimeType) {
  return [kApplicationJavascript].includes(mimeType);
}
var init_display_data = __esm({
  "core/jupyter/display-data.ts"() {
    init_mime();
  }
});

// core/jupyter/labels.ts
function cellLabel(cell) {
  const label = asHtmlId(
    cell.options[kCellLabel] || cell.metadata[kCellName] || ""
  );
  if (label && !label.startsWith("#")) {
    return "#" + label;
  } else {
    return label;
  }
}
function cellLabelValidator() {
  const cellLabels = /* @__PURE__ */ new Set();
  return function(cell) {
    const label = cellLabel(cell);
    if (label) {
      if (cellLabels.has(label)) {
        throw new Error(
          "Cell label names must be unique (found duplicate '" + label + "')"
        );
      } else {
        cellLabels.add(label);
      }
    }
  };
}
function shouldLabelCellContainer(cell, outputs, options) {
  if (!outputs) {
    return true;
  }
  if (!includeOutput(cell, options)) {
    return true;
  }
  const displayDataOutputs = outputs.filter(isDisplayData);
  if (displayDataOutputs.length === 0) {
    return true;
  }
  if (displayDataOutputs.length > 1 && !Array.isArray(cell.options[kCellFigCap])) {
    return true;
  }
  if (hasTableLabel(cell.options)) {
    return true;
  }
  return false;
}
function hasTableLabel(options) {
  return typeof options[kCellLabel] === "string" && options[kCellLabel]?.startsWith("tbl-");
}
function shouldLabelOutputContainer(output, cellOptions, options) {
  if (isDisplayData(output)) {
    if (hasTableLabel(cellOptions)) {
      return false;
    }
    if (!isCaptionableData(output)) {
      return false;
    }
    const mimeType = displayDataMimeType(
      output,
      options
    );
    if (mimeType) {
      if (displayDataIsImage(mimeType)) {
        return false;
      }
    }
    return true;
  } else {
    return false;
  }
}
function resolveCaptions(cell) {
  if (Array.isArray(cell.options[kCellFigCap])) {
    const figCap = cell.options[kCellFigCap];
    if (cell.outputs && cell.outputs.filter(isCaptionableData).length > 0) {
      return {
        cellCaption: void 0,
        outputCaptions: figCap
      };
    } else {
      return {
        cellCaption: void 0,
        outputCaptions: []
      };
    }
  } else if (cell.options[kCellFigCap]) {
    if (cell.options[kCellFigSubCap] !== void 0) {
      let subCap = cell.options[kCellFigSubCap];
      if (subCap === true) {
        subCap = [""];
      }
      if (!Array.isArray(subCap)) {
        subCap = [String(subCap)];
      }
      return {
        cellCaption: cell.options[kCellFigCap],
        outputCaptions: subCap
      };
    } else {
      return {
        cellCaption: void 0,
        outputCaptions: [cell.options[kCellFigCap]]
      };
    }
  } else {
    return {
      cellCaption: void 0,
      outputCaptions: []
    };
  }
}
var init_labels = __esm({
  "core/jupyter/labels.ts"() {
    init_html();
    init_display_data();
    init_constants6();
    init_tags();
  }
});

// core/jupyter/widgets.ts
function extractJupyterWidgetDependencies(nb) {
  const jsWidgets = haveOutputType(
    nb,
    [kApplicationJavascript, kTextHtml]
  );
  const jupyterWidgets = haveOutputType(
    nb,
    [kApplicationJupyterWidgetView]
  );
  const htmlLibraries = [];
  nb.cells.forEach((cell) => {
    if (cell.cell_type === "code") {
      cell.outputs = cell.outputs?.filter((output) => {
        if (isDisplayData(output)) {
          const displayOutput = output;
          const html = displayOutput.data[kTextHtml];
          const htmlText = Array.isArray(html) ? html.join("") : html;
          if (html && isWidgetIncludeHtml(htmlText)) {
            htmlLibraries.push(htmlLibrariesText(htmlText));
            return false;
          }
        }
        return true;
      });
    }
  });
  return {
    jsWidgets,
    jupyterWidgets,
    htmlLibraries,
    widgetsState: nb.metadata.widgets?.[kApplicationJupyterWidgetState]
  };
}
function includesForJupyterWidgetDependencies(dependencies, tempDir2) {
  let haveJavascriptWidgets = false;
  let haveJupyterWidgets = false;
  const htmlLibraries = [];
  let widgetsState;
  for (const dependency of dependencies) {
    haveJavascriptWidgets = haveJavascriptWidgets || dependency.jsWidgets;
    haveJupyterWidgets = haveJupyterWidgets || dependency.jupyterWidgets;
    for (const htmlLib of dependency.htmlLibraries) {
      if (!htmlLibraries.includes(htmlLib)) {
        htmlLibraries.push(htmlLib);
      }
    }
    if (dependency.widgetsState) {
      if (!widgetsState) {
        widgetsState = dependency.widgetsState;
      } else {
        widgetsState = mergeConfigs(widgetsState, dependency.widgetsState);
      }
    }
  }
  const head = [];
  if (haveJavascriptWidgets || haveJupyterWidgets) {
    head.push(
      '<script src="https://cdn.jsdelivr.net/npm/requirejs@2.3.6/require.min.js" integrity="sha384-c9c+LnTbwQ3aujuU7ULEPVvgLs+Fn6fJUvIGTsuu1ZcCf11fiEubah0ttpca4ntM sha384-6V1/AdqZRWk1KAlWbKBlGhN7VG4iE/yAZcO6NZPMF8od0vukrvr0tg4qY6NSrItx" crossorigin="anonymous"><\/script>'
    );
    head.push(
      '<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js" integrity="sha384-ZvpUoO/+PpLXR1lu4jmpXWu80pZlYUAfxl5NsBMWOEPSjUn/6Z/hRTt8+pR6L4N2" crossorigin="anonymous" data-relocate-top="true"><\/script>'
    );
    head.push(
      `<script type="application/javascript">define('jquery', [],function() {return window.jQuery;})<\/script>`
    );
  }
  head.push(...htmlLibraries);
  if (haveJupyterWidgets) {
    head.push(
      '<script src="https://cdn.jsdelivr.net/npm/@jupyter-widgets/html-manager@*/dist/embed-amd.js" crossorigin="anonymous"><\/script>'
    );
  }
  const afterBody = [];
  if (haveJupyterWidgets && widgetsState) {
    const stateStr = JSON.stringify(widgetsState);
    if (stateStr.includes("<\/script>")) {
      afterBody.push(`<script>
      (() => {
        const scriptTag = document.createElement("script");
        const base64State = "${btoa(encodeURIComponent(stateStr))}";
        scriptTag.type = "${kApplicationJupyterWidgetState}";
        scriptTag.textContent = decodeURIComponent(atob(base64State));
        document.body.appendChild(scriptTag);
      })();
      <\/script>`);
    } else {
      afterBody.push(`<script type=${kApplicationJupyterWidgetState}>`);
      afterBody.push(JSON.stringify(widgetsState));
      afterBody.push("<\/script>");
    }
  }
  const widgetTempFile = (lines2) => {
    const tempFile = Deno.makeTempFileSync(
      { dir: tempDir2, prefix: "jupyter-widgets-", suffix: ".html" }
    );
    Deno.writeTextFileSync(tempFile, lines2.join("\n") + "\n");
    return tempFile;
  };
  const result2 = {
    inHeader: "",
    afterBody: ""
  };
  if (head.length > 0) {
    result2.inHeader = widgetTempFile(head);
  }
  if (afterBody.length > 0) {
    result2.afterBody = widgetTempFile(afterBody);
  }
  return result2;
}
function haveOutputType(nb, mimeTypes) {
  return nb.cells.some((cell) => {
    if (cell.cell_type === "code" && cell.outputs) {
      return cell.outputs.some((output) => {
        if (isDisplayData(output)) {
          const outputTypes = Object.keys(
            output.data
          );
          return outputTypes.some((type4) => mimeTypes.includes(type4));
        } else {
          return false;
        }
      });
    } else {
      return false;
    }
  });
}
function isWidgetIncludeHtml(html) {
  return isPlotlyLibrary(html);
}
function isPlotlyLibrary(html) {
  const hasRequireScript = (html2) => /^\s*<script type="text\/javascript">/.test(html2) && (/require\.undef\(["']plotly["']\)/.test(html2) || /define\('plotly'/.test(html2));
  const hasModuleScript = (html2) => /\s*<script type=\"module\">import .*plotly.*<\/script>/.test(html2);
  const hasEmbedScript = (html2) => /\* plotly\.js v\d+\.\d+\.\d+\s*\n\s*\* Copyright \d{4}-\d{4}, Plotly, Inc\.\s*\n\s*\* All rights reserved\.\s*\n\s*\* Licensed under the MIT license/.test(html2);
  return hasRequireScript(html) || // also handle new module syntax from plotly.py 6+
  hasModuleScript(html) || // detect plotly by its copyright header
  hasEmbedScript(html);
}
function htmlLibrariesText(htmlText) {
  const htmlLines = lines(htmlText);
  const leadingSpace = htmlLines.reduce(
    (leading, line) => {
      const spaces = line.search(/\S/);
      if (spaces !== -1) {
        return Math.min(leading, spaces);
      } else {
        return leading;
      }
    },
    Number.MAX_SAFE_INTEGER
  );
  if (leadingSpace !== Number.MAX_SAFE_INTEGER) {
    return htmlLines.map((line) => {
      if (line.trim().length === 0) {
        return "";
      } else {
        return line.replace(" ".repeat(leadingSpace), "");
      }
    }).join("\n");
  } else {
    return htmlText;
  }
}
var init_widgets = __esm({
  "core/jupyter/widgets.ts"() {
    init_config2();
    init_text();
    init_mime();
    init_display_data();
  }
});

// core/jupyter/preserve.ts
function removeAndPreserveHtml(nb) {
  const htmlPreserve = {};
  nb.cells.forEach((cell) => {
    if (cell.cell_type === "code") {
      cell.outputs?.forEach((output) => {
        if (isDisplayData(output)) {
          const displayOutput = output;
          const html = displayOutput.data[kTextHtml];
          const htmlText = Array.isArray(html) ? html.join("") : html;
          if (html && isPreservedHtml(htmlText)) {
            const key = "preserve" + globalThis.crypto.randomUUID().replaceAll("-", "");
            htmlPreserve[key] = htmlText;
            displayOutput.data[kTextMarkdown] = [key];
            displayOutput.noCaption = true;
            delete displayOutput.data[kTextHtml];
          }
        }
      });
    }
  });
  if (Object.keys(htmlPreserve).length > 0) {
    return htmlPreserve;
  } else {
    return void 0;
  }
}
function restorePreservedHtml(html, preserve) {
  if (preserve) {
    Object.keys(preserve).forEach((key) => {
      const keyLoc = html.indexOf(key);
      html = html.slice(0, keyLoc) + preserve[key] + html.slice(keyLoc + key.length);
    });
  }
  return html;
}
function isPreservedHtml(_html) {
  return false;
}
function postProcessRestorePreservedHtml(options) {
  const outputPath = isAbsolute4(options.output) ? options.output : join4(dirname4(options.target.input), options.output);
  let output = Deno.readTextFileSync(outputPath);
  output = restorePreservedHtml(
    output,
    options.preserve
  );
  Deno.writeTextFileSync(outputPath, output);
}
var init_preserve = __esm({
  "core/jupyter/preserve.ts"() {
    init_path();
    init_mime();
    init_display_data();
  }
});

// core/jupyter/capabilities.ts
async function jupyterCapabilities(kernelspec) {
  const language = kernelspec?.language || kNoLanguage;
  if (!jupyterCapsCache.has(language)) {
    debug(
      "Looking for Python binaries and Jupyter capabilities" + (language === kNoLanguage ? "." : ` for language '${language}'.`)
    );
    let juliaCaps;
    if (language === "julia") {
      juliaCaps = await getVerifiedJuliaCondaJupyterCapabilities();
      if (juliaCaps) {
        debug(
          `Using Jupyter capabilities from Julia conda at '${juliaCaps.executable}'`
        );
        jupyterCapsCache.set(language, juliaCaps);
        return juliaCaps;
      }
    }
    const quartoCaps = await getQuartoJupyterCapabilities();
    if (quartoCaps) {
      debug(
        `Python found using QUARTO_PYTHON at '${quartoCaps.executable}'`
      );
      jupyterCapsCache.set(language, quartoCaps);
      return quartoCaps;
    }
    if (isWindows4 && pyPython()) {
      const pyLauncherCaps = await getPyLauncherJupyterCapabilities();
      if (pyLauncherCaps) {
        debug(
          `Python found via "py.exe" at ${pyLauncherCaps.executable}.`
        );
        jupyterCapsCache.set(language, pyLauncherCaps);
      }
    }
    if (!jupyterCapsCache.has(language)) {
      debug("Looking for Jupyter capabilities from conda 'python' binary");
      const condaCaps = await getJupyterCapabilities(["python"]);
      if (condaCaps?.conda) {
        debug(
          `Python found using conda at '${condaCaps.executable}'`
        );
        jupyterCapsCache.set(language, condaCaps);
      } else {
        const caps = isWindows4 ? await getPyLauncherJupyterCapabilities() : await getJupyterCapabilities(["python3"]);
        if (caps) {
          debug(
            `Python found at '${caps.executable}'`
          );
          jupyterCapsCache.set(language, caps);
        }
      }
      if (!jupyterCapsCache.get(language)?.jupyter_core && juliaCaps) {
        debug(
          `No Jupyter capabilities found for '${language}' in ${jupyterCapsCache.get(language)?.executable}, falling back to Julia conda at '${juliaCaps.executable}'`
        );
        jupyterCapsCache.set(language, juliaCaps);
      }
    }
  }
  return jupyterCapsCache.get(language);
}
async function getVerifiedJuliaCondaJupyterCapabilities() {
  debug("Looking for Jupyter capabilities from Julia conda");
  let juliaHome = Deno.env.get("JULIA_HOME");
  if (!juliaHome) {
    const home = isWindows4 ? Deno.env.get("USERPROFILE") : Deno.env.get("HOME");
    if (home) {
      juliaHome = join4(home, ".julia");
    }
  }
  if (juliaHome) {
    const juliaCondaPath = join4(juliaHome, "conda", "3");
    const bin = isWindows4 ? ["python3.exe", "python.exe"] : [join4("bin", "python3"), join4("bin", "python")];
    for (const pythonBin of bin) {
      const juliaPython = join4(
        juliaCondaPath,
        pythonBin
      );
      if (existsSync2(juliaPython)) {
        debug(`Checking Jupyter capabilities for '${juliaPython}'`);
        const caps = await getJupyterCapabilities([juliaPython]);
        if (caps?.jupyter_core) {
          debug(
            `Python with Jupyter found at '${caps.executable}' from Julia conda`
          );
          return caps;
        }
      }
    }
    for (const path3 of expandGlobSync(join4(juliaCondaPath, "**", "python*"), {
      globstar: true
    })) {
      const file = Deno.statSync(path3.path);
      if (!(file.isFile && file.mode && file.mode & S_IXUSR)) {
        continue;
      }
      debug(`Checking Jupyter capabilities for '${path3.path}'`);
      const caps = await getJupyterCapabilities([path3.path]);
      if (caps?.jupyter_core) {
        debug(
          `Python with Jupyter found at '${caps.executable}' from Julia conda`
        );
        return caps;
      }
    }
  }
}
async function getQuartoJupyterCapabilities() {
  let quartoJupyter = Deno.env.get("QUARTO_PYTHON");
  if (quartoJupyter) {
    debug(`Checking QUARTO_PYTHON set to '${quartoJupyter}'`);
    if (!isAbsolute4(quartoJupyter)) {
      const path3 = await which(quartoJupyter);
      if (path3) {
        quartoJupyter = path3;
        debug(`Resolved QUARTO_PYTHON to '${quartoJupyter}'`);
      }
    }
    if (existsSync2(quartoJupyter)) {
      let quartoJupyterBin = quartoJupyter;
      if (Deno.statSync(quartoJupyter).isDirectory) {
        debug(
          `QUARTO_PYTHON '${quartoJupyter}' is a directory, looking for python binary`
        );
        const bin = ["python3", "python", "python3.exe", "python.exe"].find((bin2) => {
          return existsSync2(join4(quartoJupyter, bin2));
        });
        if (bin) {
          debug(`Found python binary '${bin}' in QUARTO_PYTHON`);
          quartoJupyterBin = join4(quartoJupyter, bin);
        } else {
          quartoJupyterBin = void 0;
        }
      }
      if (quartoJupyterBin) {
        debug(`Checking Jupyter capabilities for '${quartoJupyterBin}'`);
        return getJupyterCapabilities([quartoJupyterBin]);
      }
    } else {
      warnOnce(`Specified QUARTO_PYTHON '${quartoJupyter}' does not exist`);
    }
    warnOnce(
      `No python binary found in specified QUARTO_PYTHON location '${quartoJupyter}'`
    );
    return void 0;
  } else {
    return void 0;
  }
}
async function jupyterCapabilitiesNoConda() {
  const caps = await getQuartoJupyterCapabilities();
  if (caps && !caps.conda) {
    return caps;
  }
  if (isWindows4) {
    return await getPyLauncherJupyterCapabilities();
  } else {
    const caps2 = await getJupyterCapabilities(["python3"]);
    if (caps2) {
      if (caps2?.conda) {
        return await getJupyterCapabilities(["/usr/local/bin/python3"]) || await getJupyterCapabilities(["/usr/bin/python3"]);
      } else {
        return caps2;
      }
    } else {
      return void 0;
    }
  }
}
function isEnvDir(dir) {
  return existsSync2(join4(dir, "pyvenv.cfg")) || existsSync2(join4(dir, "conda-meta"));
}
function pyPython() {
  return Deno.env.get("PY_PYTHON");
}
function getPyLauncherJupyterCapabilities() {
  debug("Using 'py.exe' to get Jupyter capabilities");
  return getJupyterCapabilities(["py"], true);
}
async function getJupyterCapabilities(cmd, pyLauncher = false) {
  try {
    const result2 = await execProcess({
      cmd: cmd[0],
      args: [
        ...cmd.slice(1),
        resourcePath("capabilities/jupyter.py")
      ],
      stdout: "piped",
      stderr: "piped",
      env: {
        ["PYDEVD_DISABLE_FILE_VALIDATION"]: "1"
      }
    });
    if (result2.success && result2.stdout) {
      const caps = readYamlFromString(result2.stdout);
      if (caps.versionMajor >= 3) {
        caps.pyLauncher = pyLauncher;
        return caps;
      } else {
        return void 0;
      }
    } else {
      return void 0;
    }
  } catch {
    return void 0;
  }
}
var kNoLanguage, jupyterCapsCache, S_IXUSR;
var init_capabilities = __esm({
  "core/jupyter/capabilities.ts"() {
    init_path();
    init_fs();
    init_platform();
    init_process();
    init_resources2();
    init_yaml();
    init_path2();
    init_log2();
    init_log();
    kNoLanguage = "(none)";
    jupyterCapsCache = /* @__PURE__ */ new Map();
    S_IXUSR = 64;
  }
});

// core/jupyter/exec.ts
async function pythonExec(kernelspec, binaryOnly = false) {
  const caps = await jupyterCapabilities(kernelspec);
  return pythonExecForCaps(caps, binaryOnly);
}
function pythonExecForCaps(caps, binaryOnly = false) {
  if (caps?.pyLauncher) {
    return ["py"];
  } else if (isWindows4) {
    return [binaryOnly ? "python" : caps?.executable || "python"];
  } else {
    return [binaryOnly ? "python3" : caps?.executable || "python3"];
  }
}
async function jupyterExec(kernelspec) {
  return [
    ...await pythonExec(kernelspec),
    "-m",
    "jupyter"
  ];
}
var init_exec = __esm({
  "core/jupyter/exec.ts"() {
    init_platform();
    init_capabilities();
  }
});

// core/jupyter/kernels.ts
function isJupyterKernelspec(x3) {
  if (x3 && typeof x3 === "object") {
    return typeof x3.name === "string" && typeof x3.language === "string" && typeof x3.display_name === "string";
  } else {
    return false;
  }
}
async function jupyterKernelspecForLanguage(language) {
  const kernelspecs = await jupyterKernelspecs();
  const defaultResolver = () => {
    for (const kernelspec of kernelspecs.values()) {
      if (kernelspec.language === language) {
        return kernelspec;
      }
    }
  };
  const python = () => {
    const env2 = Deno.env.get("VIRTUAL_ENV");
    if (env2) {
      for (const kernelspec of kernelspecs.values()) {
        if (kernelspec.language === "python" && kernelspec.path?.includes(env2)) {
          debug("Preferring a venv-based python kernel at " + kernelspec.path);
          return kernelspec;
        }
      }
    }
    return defaultResolver();
  };
  const resolvers = {
    python
  };
  const resolver = resolvers[language] || defaultResolver;
  return resolver();
}
async function jupyterKernelspec(name2) {
  const kernelspecs = await jupyterKernelspecs();
  return kernelspecs.get(name2);
}
async function jupyterKernelspecs() {
  if (kJupyterKernelspecs) {
    return kJupyterKernelspecs;
  }
  kJupyterKernelspecs = await computeJupyterKernelspecs();
  return kJupyterKernelspecs;
}
async function computeJupyterKernelspecs() {
  try {
    const cmd = await jupyterExec();
    const result2 = await execProcess(
      {
        cmd: cmd[0],
        args: [...cmd.slice(1), "--paths", "--json"],
        stdout: "piped",
        stderr: "piped"
      }
    );
    if (result2.success) {
      const kernelmap = /* @__PURE__ */ new Map();
      const dataPaths = JSON.parse(result2.stdout).data;
      for (const path3 of dataPaths) {
        if (!existsSync2(path3)) {
          continue;
        }
        const kernels = join4(path3, "kernels");
        if (!existsSync2(kernels)) {
          continue;
        }
        for (const walk5 of walkSync(kernels, { maxDepth: 1 })) {
          if (walk5.path === kernels || !walk5.isDirectory) {
            continue;
          }
          const kernelConfig = join4(walk5.path, "kernel.json");
          if (existsSync2(kernelConfig)) {
            const config2 = JSON.parse(Deno.readTextFileSync(kernelConfig));
            const name2 = basename4(walk5.path);
            kernelmap.set(name2, {
              name: name2,
              language: config2.language,
              display_name: config2.display_name,
              path: walk5.path
            });
          }
        }
      }
      if (kernelmap.size > 0) {
        return kernelmap;
      } else {
        return kDefaultKernelspecs;
      }
    } else {
      return kDefaultKernelspecs;
    }
  } catch (e5) {
    if (!(e5 instanceof Error)) throw e5;
    debug("Error reading kernelspecs: " + e5.message);
    return kDefaultKernelspecs;
  }
}
function jupyterDefaultPythonKernelspec() {
  return {
    "display_name": "Python 3",
    "language": "python",
    "name": "python3"
  };
}
var kJupyterKernelspecs, kDefaultKernelspecs;
var init_kernels = __esm({
  "core/jupyter/kernels.ts"() {
    init_path();
    init_fs();
    init_log();
    init_process();
    init_exec();
    kJupyterKernelspecs = void 0;
    kDefaultKernelspecs = /* @__PURE__ */ new Map();
    kDefaultKernelspecs.set("python3", jupyterDefaultPythonKernelspec());
  }
});

// core/pandoc/pandoc-partition.ts
function parsePandocTitle(title3) {
  title3 = title3 ? title3.trim() : title3;
  const match = title3.match(kPandocTitleRegex);
  if (match) {
    const titleRaw = match[1];
    const attrRaw = match[2];
    const parsed = pandocAttrParseText(attrRaw);
    if (parsed) {
      return {
        heading: titleRaw,
        attr: parsed
      };
    } else {
      return {
        heading: titleRaw
      };
    }
  } else {
    return {
      heading: title3.replace(kRemoveHeadingRegex, "").trim()
    };
  }
}
function partitionMarkdown(markdown) {
  const partitioned = partitionYamlFrontMatter(markdown);
  markdown = partitioned ? partitioned.markdown : markdown;
  const { lines: lines2, headingText, headingAttr } = markdownWithExtractedHeading(
    markdown
  );
  const containsRefs = lines2.some(
    (line) => /^:::\s*{#refs([\s}]|.*?})\s*$/.test(line)
  );
  return {
    yaml: partitioned ? readYamlFromMarkdown(partitioned.yaml) : void 0,
    headingText,
    headingAttr,
    containsRefs,
    markdown: lines2.join("\n"),
    srcMarkdownNoYaml: partitioned?.markdown || ""
  };
}
function markdownWithExtractedHeading(markdown) {
  const mdLines = [];
  let headingText;
  let headingAttr;
  let contentBeforeHeading = false;
  for (const line of lines(markdown)) {
    if (!headingText) {
      if (line.match(/^\#{1,}\s/)) {
        const parsedHeading = parsePandocTitle(line);
        headingText = parsedHeading.heading;
        headingAttr = parsedHeading.attr;
        contentBeforeHeading = mdLines.length !== 0;
      } else if (line.match(/^=+\s*$/) || line.match(/^-+\s*$/)) {
        const prevLine = mdLines[mdLines.length - 1];
        if (prevLine) {
          headingText = prevLine;
          mdLines.splice(mdLines.length - 1);
          contentBeforeHeading = mdLines.length !== 0;
        } else {
          mdLines.push(line);
        }
      } else {
        mdLines.push(line);
      }
    } else {
      mdLines.push(line);
    }
  }
  return {
    lines: mdLines,
    headingText,
    headingAttr,
    contentBeforeHeading
  };
}
function languagesWithClasses(markdown) {
  const result2 = /* @__PURE__ */ new Map();
  const kChunkRegex = /^[\t >]*```+\s*\{([a-zA-Z][a-zA-Z0-9_.]*)([^}]*)?\}\s*$/gm;
  kChunkRegex.lastIndex = 0;
  let match = kChunkRegex.exec(markdown);
  while (match) {
    const language = match[1].toLowerCase();
    if (!result2.has(language)) {
      const attrs = match[2];
      const firstClass = attrs?.match(/\.([a-zA-Z][a-zA-Z0-9_-]*)/)?.[1];
      result2.set(language, firstClass);
    }
    match = kChunkRegex.exec(markdown);
  }
  kChunkRegex.lastIndex = 0;
  return result2;
}
function languagesInMarkdown(markdown) {
  return new Set(languagesWithClasses(markdown).keys());
}
var kPandocTitleRegex, kRemoveHeadingRegex;
var init_pandoc_partition = __esm({
  "core/pandoc/pandoc-partition.ts"() {
    init_text2();
    init_yaml();
    init_pandoc_attr();
    kPandocTitleRegex = /^\#{1,}\s(?:(.*)\s)?\{(.*)\}$/;
    kRemoveHeadingRegex = /^#{1,}\s*/;
  }
});

// https://cdn.skypack.dev/-/ansi_up@v6.0.2-g4dqbE85eEEqdCLbVzfu/dist=es2019,mode=imports/optimized/ansi_up.js
function rgx(tmplObj, ...subst) {
  let regexText = tmplObj.raw[0];
  let wsrgx = /^\s+|\s+\n|\s*#[\s\S]*?\n|\n/gm;
  let txt2 = regexText.replace(wsrgx, "");
  return new RegExp(txt2);
}
function rgxG(tmplObj, ...subst) {
  let regexText = tmplObj.raw[0];
  let wsrgx = /^\s+|\s+\n|\s*#[\s\S]*?\n|\n/gm;
  let txt2 = regexText.replace(wsrgx, "");
  return new RegExp(txt2, "g");
}
var __makeTemplateObject, PacketKind, AnsiUp, templateObject_1, templateObject_2, templateObject_3;
var init_ansi_up = __esm({
  "https://cdn.skypack.dev/-/ansi_up@v6.0.2-g4dqbE85eEEqdCLbVzfu/dist=es2019,mode=imports/optimized/ansi_up.js"() {
    __makeTemplateObject = function(cooked, raw) {
      if (Object.defineProperty) {
        Object.defineProperty(cooked, "raw", { value: raw });
      } else {
        cooked.raw = raw;
      }
      return cooked;
    };
    (function(PacketKind2) {
      PacketKind2[PacketKind2["EOS"] = 0] = "EOS";
      PacketKind2[PacketKind2["Text"] = 1] = "Text";
      PacketKind2[PacketKind2["Incomplete"] = 2] = "Incomplete";
      PacketKind2[PacketKind2["ESC"] = 3] = "ESC";
      PacketKind2[PacketKind2["Unknown"] = 4] = "Unknown";
      PacketKind2[PacketKind2["SGR"] = 5] = "SGR";
      PacketKind2[PacketKind2["OSCURL"] = 6] = "OSCURL";
    })(PacketKind || (PacketKind = {}));
    AnsiUp = class {
      constructor() {
        this.VERSION = "6.0.2";
        this.setup_palettes();
        this._use_classes = false;
        this.bold = false;
        this.faint = false;
        this.italic = false;
        this.underline = false;
        this.fg = this.bg = null;
        this._buffer = "";
        this._url_allowlist = { http: 1, https: 1 };
        this._escape_html = true;
        this.boldStyle = "font-weight:bold";
        this.faintStyle = "opacity:0.7";
        this.italicStyle = "font-style:italic";
        this.underlineStyle = "text-decoration:underline";
      }
      set use_classes(arg) {
        this._use_classes = arg;
      }
      get use_classes() {
        return this._use_classes;
      }
      set url_allowlist(arg) {
        this._url_allowlist = arg;
      }
      get url_allowlist() {
        return this._url_allowlist;
      }
      set escape_html(arg) {
        this._escape_html = arg;
      }
      get escape_html() {
        return this._escape_html;
      }
      set boldStyle(arg) {
        this._boldStyle = arg;
      }
      get boldStyle() {
        return this._boldStyle;
      }
      set faintStyle(arg) {
        this._faintStyle = arg;
      }
      get faintStyle() {
        return this._faintStyle;
      }
      set italicStyle(arg) {
        this._italicStyle = arg;
      }
      get italicStyle() {
        return this._italicStyle;
      }
      set underlineStyle(arg) {
        this._underlineStyle = arg;
      }
      get underlineStyle() {
        return this._underlineStyle;
      }
      setup_palettes() {
        this.ansi_colors = [
          [
            { rgb: [0, 0, 0], class_name: "ansi-black" },
            { rgb: [187, 0, 0], class_name: "ansi-red" },
            { rgb: [0, 187, 0], class_name: "ansi-green" },
            { rgb: [187, 187, 0], class_name: "ansi-yellow" },
            { rgb: [0, 0, 187], class_name: "ansi-blue" },
            { rgb: [187, 0, 187], class_name: "ansi-magenta" },
            { rgb: [0, 187, 187], class_name: "ansi-cyan" },
            { rgb: [255, 255, 255], class_name: "ansi-white" }
          ],
          [
            { rgb: [85, 85, 85], class_name: "ansi-bright-black" },
            { rgb: [255, 85, 85], class_name: "ansi-bright-red" },
            { rgb: [0, 255, 0], class_name: "ansi-bright-green" },
            { rgb: [255, 255, 85], class_name: "ansi-bright-yellow" },
            { rgb: [85, 85, 255], class_name: "ansi-bright-blue" },
            { rgb: [255, 85, 255], class_name: "ansi-bright-magenta" },
            { rgb: [85, 255, 255], class_name: "ansi-bright-cyan" },
            { rgb: [255, 255, 255], class_name: "ansi-bright-white" }
          ]
        ];
        this.palette_256 = [];
        this.ansi_colors.forEach((palette) => {
          palette.forEach((rec) => {
            this.palette_256.push(rec);
          });
        });
        let levels = [0, 95, 135, 175, 215, 255];
        for (let r5 = 0; r5 < 6; ++r5) {
          for (let g3 = 0; g3 < 6; ++g3) {
            for (let b3 = 0; b3 < 6; ++b3) {
              let col = { rgb: [levels[r5], levels[g3], levels[b3]], class_name: "truecolor" };
              this.palette_256.push(col);
            }
          }
        }
        let grey_level = 8;
        for (let i6 = 0; i6 < 24; ++i6, grey_level += 10) {
          let gry = { rgb: [grey_level, grey_level, grey_level], class_name: "truecolor" };
          this.palette_256.push(gry);
        }
      }
      escape_txt_for_html(txt) {
        if (!this._escape_html)
          return txt;
        return txt.replace(/[&<>"']/gm, (str3) => {
          if (str3 === "&")
            return "&amp;";
          if (str3 === "<")
            return "&lt;";
          if (str3 === ">")
            return "&gt;";
          if (str3 === '"')
            return "&quot;";
          if (str3 === "'")
            return "&#x27;";
        });
      }
      append_buffer(txt) {
        var str3 = this._buffer + txt;
        this._buffer = str3;
      }
      get_next_packet() {
        var pkt = {
          kind: PacketKind.EOS,
          text: "",
          url: ""
        };
        var len = this._buffer.length;
        if (len == 0)
          return pkt;
        var pos = this._buffer.indexOf("\x1B");
        if (pos == -1) {
          pkt.kind = PacketKind.Text;
          pkt.text = this._buffer;
          this._buffer = "";
          return pkt;
        }
        if (pos > 0) {
          pkt.kind = PacketKind.Text;
          pkt.text = this._buffer.slice(0, pos);
          this._buffer = this._buffer.slice(pos);
          return pkt;
        }
        if (pos == 0) {
          if (len < 3) {
            pkt.kind = PacketKind.Incomplete;
            return pkt;
          }
          var next_char = this._buffer.charAt(1);
          if (next_char != "[" && next_char != "]" && next_char != "(") {
            pkt.kind = PacketKind.ESC;
            pkt.text = this._buffer.slice(0, 1);
            this._buffer = this._buffer.slice(1);
            return pkt;
          }
          if (next_char == "[") {
            if (!this._csi_regex) {
              this._csi_regex = rgx(templateObject_1 || (templateObject_1 = __makeTemplateObject(["\n                        ^                           # beginning of line\n                                                    #\n                                                    # First attempt\n                        (?:                         # legal sequence\n                          \x1B[                      # CSI\n                          ([<-?]?)              # private-mode char\n                          ([d;]*)                    # any digits or semicolons\n                          ([ -/]?               # an intermediate modifier\n                          [@-~])                # the command\n                        )\n                        |                           # alternate (second attempt)\n                        (?:                         # illegal sequence\n                          \x1B[                      # CSI\n                          [ -~]*                # anything legal\n                          ([\0-:])              # anything illegal\n                        )\n                    "], ["\n                        ^                           # beginning of line\n                                                    #\n                                                    # First attempt\n                        (?:                         # legal sequence\n                          \\x1b\\[                      # CSI\n                          ([\\x3c-\\x3f]?)              # private-mode char\n                          ([\\d;]*)                    # any digits or semicolons\n                          ([\\x20-\\x2f]?               # an intermediate modifier\n                          [\\x40-\\x7e])                # the command\n                        )\n                        |                           # alternate (second attempt)\n                        (?:                         # illegal sequence\n                          \\x1b\\[                      # CSI\n                          [\\x20-\\x7e]*                # anything legal\n                          ([\\x00-\\x1f:])              # anything illegal\n                        )\n                    "])));
            }
            let match = this._buffer.match(this._csi_regex);
            if (match === null) {
              pkt.kind = PacketKind.Incomplete;
              return pkt;
            }
            if (match[4]) {
              pkt.kind = PacketKind.ESC;
              pkt.text = this._buffer.slice(0, 1);
              this._buffer = this._buffer.slice(1);
              return pkt;
            }
            if (match[1] != "" || match[3] != "m")
              pkt.kind = PacketKind.Unknown;
            else
              pkt.kind = PacketKind.SGR;
            pkt.text = match[2];
            var rpos = match[0].length;
            this._buffer = this._buffer.slice(rpos);
            return pkt;
          } else if (next_char == "]") {
            if (len < 4) {
              pkt.kind = PacketKind.Incomplete;
              return pkt;
            }
            if (this._buffer.charAt(2) != "8" || this._buffer.charAt(3) != ";") {
              pkt.kind = PacketKind.ESC;
              pkt.text = this._buffer.slice(0, 1);
              this._buffer = this._buffer.slice(1);
              return pkt;
            }
            if (!this._osc_st) {
              this._osc_st = rgxG(templateObject_2 || (templateObject_2 = __makeTemplateObject(["\n                        (?:                         # legal sequence\n                          (\x1B\\)                    # ESC                           |                           # alternate\n                          (\x07)                      # BEL (what xterm did)\n                        )\n                        |                           # alternate (second attempt)\n                        (                           # illegal sequence\n                          [\0-]                 # anything illegal\n                          |                           # alternate\n                          [\b-]                 # anything illegal\n                          |                           # alternate\n                          [-]                 # anything illegal\n                        )\n                    "], ["\n                        (?:                         # legal sequence\n                          (\\x1b\\\\)                    # ESC \\\n                          |                           # alternate\n                          (\\x07)                      # BEL (what xterm did)\n                        )\n                        |                           # alternate (second attempt)\n                        (                           # illegal sequence\n                          [\\x00-\\x06]                 # anything illegal\n                          |                           # alternate\n                          [\\x08-\\x1a]                 # anything illegal\n                          |                           # alternate\n                          [\\x1c-\\x1f]                 # anything illegal\n                        )\n                    "])));
            }
            this._osc_st.lastIndex = 0;
            {
              let match2 = this._osc_st.exec(this._buffer);
              if (match2 === null) {
                pkt.kind = PacketKind.Incomplete;
                return pkt;
              }
              if (match2[3]) {
                pkt.kind = PacketKind.ESC;
                pkt.text = this._buffer.slice(0, 1);
                this._buffer = this._buffer.slice(1);
                return pkt;
              }
            }
            {
              let match2 = this._osc_st.exec(this._buffer);
              if (match2 === null) {
                pkt.kind = PacketKind.Incomplete;
                return pkt;
              }
              if (match2[3]) {
                pkt.kind = PacketKind.ESC;
                pkt.text = this._buffer.slice(0, 1);
                this._buffer = this._buffer.slice(1);
                return pkt;
              }
            }
            if (!this._osc_regex) {
              this._osc_regex = rgx(templateObject_3 || (templateObject_3 = __makeTemplateObject(["\n                        ^                           # beginning of line\n                                                    #\n                        \x1B]8;                    # OSC Hyperlink\n                        [ -:<-~]*       # params (excluding ;)\n                        ;                           # end of params\n                        ([!-~]{0,512})        # URL capture\n                        (?:                         # ST\n                          (?:\x1B\\)                  # ESC                           |                           # alternate\n                          (?:\x07)                    # BEL (what xterm did)\n                        )\n                        ([ -~]+)              # TEXT capture\n                        \x1B]8;;                   # OSC Hyperlink End\n                        (?:                         # ST\n                          (?:\x1B\\)                  # ESC                           |                           # alternate\n                          (?:\x07)                    # BEL (what xterm did)\n                        )\n                    "], ["\n                        ^                           # beginning of line\n                                                    #\n                        \\x1b\\]8;                    # OSC Hyperlink\n                        [\\x20-\\x3a\\x3c-\\x7e]*       # params (excluding ;)\n                        ;                           # end of params\n                        ([\\x21-\\x7e]{0,512})        # URL capture\n                        (?:                         # ST\n                          (?:\\x1b\\\\)                  # ESC \\\n                          |                           # alternate\n                          (?:\\x07)                    # BEL (what xterm did)\n                        )\n                        ([\\x20-\\x7e]+)              # TEXT capture\n                        \\x1b\\]8;;                   # OSC Hyperlink End\n                        (?:                         # ST\n                          (?:\\x1b\\\\)                  # ESC \\\n                          |                           # alternate\n                          (?:\\x07)                    # BEL (what xterm did)\n                        )\n                    "])));
            }
            let match = this._buffer.match(this._osc_regex);
            if (match === null) {
              pkt.kind = PacketKind.ESC;
              pkt.text = this._buffer.slice(0, 1);
              this._buffer = this._buffer.slice(1);
              return pkt;
            }
            pkt.kind = PacketKind.OSCURL;
            pkt.url = match[1];
            pkt.text = match[2];
            var rpos = match[0].length;
            this._buffer = this._buffer.slice(rpos);
            return pkt;
          } else if (next_char == "(") {
            pkt.kind = PacketKind.Unknown;
            this._buffer = this._buffer.slice(3);
            return pkt;
          }
        }
      }
      ansi_to_html(txt) {
        this.append_buffer(txt);
        var blocks = [];
        while (true) {
          var packet = this.get_next_packet();
          if (packet.kind == PacketKind.EOS || packet.kind == PacketKind.Incomplete)
            break;
          if (packet.kind == PacketKind.ESC || packet.kind == PacketKind.Unknown)
            continue;
          if (packet.kind == PacketKind.Text)
            blocks.push(this.transform_to_html(this.with_state(packet)));
          else if (packet.kind == PacketKind.SGR)
            this.process_ansi(packet);
          else if (packet.kind == PacketKind.OSCURL)
            blocks.push(this.process_hyperlink(packet));
        }
        return blocks.join("");
      }
      with_state(pkt) {
        return { bold: this.bold, faint: this.faint, italic: this.italic, underline: this.underline, fg: this.fg, bg: this.bg, text: pkt.text };
      }
      process_ansi(pkt) {
        let sgr_cmds = pkt.text.split(";");
        while (sgr_cmds.length > 0) {
          let sgr_cmd_str = sgr_cmds.shift();
          let num = parseInt(sgr_cmd_str, 10);
          if (isNaN(num) || num === 0) {
            this.fg = null;
            this.bg = null;
            this.bold = false;
            this.faint = false;
            this.italic = false;
            this.underline = false;
          } else if (num === 1) {
            this.bold = true;
          } else if (num === 2) {
            this.faint = true;
          } else if (num === 3) {
            this.italic = true;
          } else if (num === 4) {
            this.underline = true;
          } else if (num === 21) {
            this.bold = false;
          } else if (num === 22) {
            this.faint = false;
            this.bold = false;
          } else if (num === 23) {
            this.italic = false;
          } else if (num === 24) {
            this.underline = false;
          } else if (num === 39) {
            this.fg = null;
          } else if (num === 49) {
            this.bg = null;
          } else if (num >= 30 && num < 38) {
            this.fg = this.ansi_colors[0][num - 30];
          } else if (num >= 40 && num < 48) {
            this.bg = this.ansi_colors[0][num - 40];
          } else if (num >= 90 && num < 98) {
            this.fg = this.ansi_colors[1][num - 90];
          } else if (num >= 100 && num < 108) {
            this.bg = this.ansi_colors[1][num - 100];
          } else if (num === 38 || num === 48) {
            if (sgr_cmds.length > 0) {
              let is_foreground = num === 38;
              let mode_cmd = sgr_cmds.shift();
              if (mode_cmd === "5" && sgr_cmds.length > 0) {
                let palette_index = parseInt(sgr_cmds.shift(), 10);
                if (palette_index >= 0 && palette_index <= 255) {
                  if (is_foreground)
                    this.fg = this.palette_256[palette_index];
                  else
                    this.bg = this.palette_256[palette_index];
                }
              }
              if (mode_cmd === "2" && sgr_cmds.length > 2) {
                let r5 = parseInt(sgr_cmds.shift(), 10);
                let g3 = parseInt(sgr_cmds.shift(), 10);
                let b3 = parseInt(sgr_cmds.shift(), 10);
                if (r5 >= 0 && r5 <= 255 && (g3 >= 0 && g3 <= 255) && (b3 >= 0 && b3 <= 255)) {
                  let c6 = { rgb: [r5, g3, b3], class_name: "truecolor" };
                  if (is_foreground)
                    this.fg = c6;
                  else
                    this.bg = c6;
                }
              }
            }
          }
        }
      }
      transform_to_html(fragment) {
        let txt = fragment.text;
        if (txt.length === 0)
          return txt;
        txt = this.escape_txt_for_html(txt);
        if (!fragment.bold && !fragment.italic && !fragment.underline && fragment.fg === null && fragment.bg === null)
          return txt;
        let styles = [];
        let classes = [];
        let fg = fragment.fg;
        let bg = fragment.bg;
        if (fragment.bold)
          styles.push(this._boldStyle);
        if (fragment.faint)
          styles.push(this._faintStyle);
        if (fragment.italic)
          styles.push(this._italicStyle);
        if (fragment.underline)
          styles.push(this._underlineStyle);
        if (!this._use_classes) {
          if (fg)
            styles.push(`color:rgb(${fg.rgb.join(",")})`);
          if (bg)
            styles.push(`background-color:rgb(${bg.rgb})`);
        } else {
          if (fg) {
            if (fg.class_name !== "truecolor") {
              classes.push(`${fg.class_name}-fg`);
            } else {
              styles.push(`color:rgb(${fg.rgb.join(",")})`);
            }
          }
          if (bg) {
            if (bg.class_name !== "truecolor") {
              classes.push(`${bg.class_name}-bg`);
            } else {
              styles.push(`background-color:rgb(${bg.rgb.join(",")})`);
            }
          }
        }
        let class_string = "";
        let style_string = "";
        if (classes.length)
          class_string = ` class="${classes.join(" ")}"`;
        if (styles.length)
          style_string = ` style="${styles.join(";")}"`;
        return `<span${style_string}${class_string}>${txt}</span>`;
      }
      process_hyperlink(pkt) {
        let parts = pkt.url.split(":");
        if (parts.length < 1)
          return "";
        if (!this._url_allowlist[parts[0]])
          return "";
        let result2 = `<a href="${this.escape_txt_for_html(pkt.url)}">${this.escape_txt_for_html(pkt.text)}</a>`;
        return result2;
      }
    };
  }
});

// https://cdn.skypack.dev/ansi_up@v6.0.2
var init_ansi_up_v6_0 = __esm({
  "https://cdn.skypack.dev/ansi_up@v6.0.2"() {
    init_ansi_up();
    init_ansi_up();
  }
});

// core/ansi-colors.ts
function hasAnsiEscapeCodes(str3) {
  return !!str3.match(/\x1b\[\d+(?:;\d+)*m/);
}
async function convertToHtmlSpans(str3) {
  const a5 = new AnsiUp();
  a5.use_classes = true;
  const html = a5.ansi_to_html(str3);
  const doc = await parseHtml(`<pre>${html}</pre>`);
  for (const node of doc.querySelectorAll("span")) {
    const el = node;
    if (el.getAttribute("style") === "font-weight:bold") {
      el.removeAttribute("style");
      el.classList.add("ansi-bold");
    }
  }
  return doc.querySelector("pre").innerHTML;
}
var init_ansi_colors = __esm({
  "core/ansi-colors.ts"() {
    init_ansi_up_v6_0();
    init_deno_dom();
  }
});

// project/types.ts
var kProjectType, kProjectTitle, kProjectRender, kProjectPreRender, kProjectPostRender, kProjectExecuteDir, kProjectOutputDir, kProjectLibDir, kProjectResources, kProjectWatchInputs, kProject404File, kCollapseLevel, kCollapseBelow, kLogoAlt, kLogoHref, kSidebarMenus;
var init_types4 = __esm({
  "project/types.ts"() {
    kProjectType = "type";
    kProjectTitle = "title";
    kProjectRender = "render";
    kProjectPreRender = "pre-render";
    kProjectPostRender = "post-render";
    kProjectExecuteDir = "execute-dir";
    kProjectOutputDir = "output-dir";
    kProjectLibDir = "lib-dir";
    kProjectResources = "resources";
    kProjectWatchInputs = "watch-inputs";
    kProject404File = "404.html";
    kCollapseLevel = "collapse-level";
    kCollapseBelow = "collapse-below";
    kLogoAlt = "logo-alt";
    kLogoHref = "logo-href";
    kSidebarMenus = "sidebar-menus";
  }
});

// config/format.ts
function isPdfOutput(format14) {
  return isFormatTo(format14, "pdf") || isFormatTo(format14, "beamer");
}
function isLatexOutput(format14) {
  return ["pdf", "latex", "beamer"].some((fmt) => isFormatTo(format14, fmt));
}
function isTypstOutput(format14) {
  return isFormatTo(format14, "typst");
}
function isBeamerOutput(format14) {
  return isFormatTo(format14, "beamer");
}
function isEpubOutput(format14) {
  if (typeof format14 !== "string") {
    format14 = format14?.to || "html";
  }
  return ["epub", "epub2", "epub3"].some((fmt) => isFormatTo(format14, fmt));
}
function isDocxOutput(format14) {
  return isFormatTo(format14, "docx");
}
function isHtmlFileOutput(format14) {
  if (typeof format14 !== "string") {
    format14 = format14?.to || "html";
  }
  return isHtmlDocOutput(format14) || isHtmlSlideOutput(format14);
}
function isHtmlOutput(format14, strict) {
  if (typeof format14 !== "string") {
    format14 = format14?.to;
  }
  format14 = format14 || "html";
  if (isHtmlDocOutput(format14) || isHtmlDashboardOutput(format14)) {
    return true;
  } else if (!strict) {
    return isHtmlSlideOutput(format14) || isEpubOutput(format14);
  } else {
    return false;
  }
}
function isHtmlDocOutput(format14) {
  return ["html", "html4", "html5"].some((fmt) => isFormatTo(format14, fmt));
}
function isHtmlSlideOutput(format14) {
  return [
    "s5",
    "dzslides",
    "slidy",
    "slideous",
    "revealjs"
  ].some((fmt) => isFormatTo(format14, fmt));
}
function isHtmlDashboardOutput(format14) {
  return format14 === "dashboard" || format14?.endsWith("-dashboard");
}
function isJatsOutput(format14) {
  if (typeof format14 !== "string") {
    format14 = format14?.to || "html";
  }
  return [
    "jats",
    "jats_archiving",
    "jats_articleauthoring",
    "jats_publishing"
  ].find((formatStr) => {
    return format14.startsWith(formatStr);
  }) !== void 0;
}
function isPresentationOutput(format14) {
  if (format14.to) {
    return ["s5", "dzslides", "slidy", "slideous", "revealjs", "beamer", "pptx"].some((to) => format14.to?.startsWith(to));
  } else {
    return false;
  }
}
function isRevealjsOutput(format14) {
  if (typeof format14 !== "string") {
    format14 = format14?.to;
  }
  format14 = format14 || "html";
  return format14.startsWith("revealjs");
}
function isNativeOutput(format14) {
  return isFormatTo(format14, "native");
}
function isJsonOutput(format14) {
  return isFormatTo(format14, "json");
}
function isAstOutput(format14) {
  return isNativeOutput(format14) || isJsonOutput(format14);
}
function isIpynbOutput(format14) {
  return isFormatTo(format14, "ipynb");
}
function isFormatTo(format14, to) {
  const formatStr = typeof format14 === "string" ? format14 : format14?.to || "html";
  return formatStr.startsWith(to);
}
function isMarkdownOutput(format14, flavors = [
  "markdown",
  "markdown_github",
  "markdown_mmd",
  "markdown_phpextra",
  "markdown_strict",
  "gfm",
  "commonmark",
  "commonmark_x",
  "markua"
]) {
  const to = format14.identifier[kBaseFormat] || "html";
  return flavors.includes(to) || isIpynbOutput(format14.pandoc);
}
function isHtmlCompatible(format14) {
  return isHtmlOutput(format14.pandoc) || isMarkdownOutput(format14) && format14.render[kPreferHtml] || isIpynbOutput(format14.pandoc);
}
function isJavascriptCompatible(format14) {
  return isHtmlCompatible(format14) && !isEpubOutput(format14.pandoc);
}
var init_format5 = __esm({
  "config/format.ts"() {
    init_constants6();
  }
});

// core/jupyter/jupyter-shared.ts
async function jupyterCapabilitiesJson(caps) {
  const kernels = Array.from((await jupyterKernelspecs()).values());
  return {
    ...caps,
    kernels
  };
}
async function jupyterCapabilitiesMessage(caps, indent = "") {
  const lines2 = [
    `Version: ${caps.versionMajor}.${caps.versionMinor}.${caps.versionPatch}${caps.conda ? " (Conda)" : ""}`,
    `Path: ${caps.executable}`,
    `Jupyter: ${caps.jupyter_core || "(None)"}`
  ];
  if (caps.jupyter_core) {
    const kernels = Array.from((await jupyterKernelspecs()).values()).map((kernel) => kernel.name).join(", ");
    lines2.push(`Kernels: ${kernels}`);
  }
  return lines2.map((line) => `${indent}${line}`).join("\n");
}
function jupyterInstallationMessage(caps, indent = "") {
  const lines2 = [
    "Jupyter is not available in this Python installation.",
    "Install with " + bold3(
      `${caps.conda ? "conda" : pythonExecForCaps(caps, true).join(" ") + " -m pip"} install jupyter`
    )
  ];
  return lines2.map((line) => `${indent}${line}`).join("\n");
}
function jupyterUnactivatedEnvMessage(caps, indent = "") {
  for (const path3 of Deno.readDirSync(Deno.cwd())) {
    if (path3.isDirectory) {
      const targetPath = join4(Deno.cwd(), path3.name);
      try {
        if (isEnvDir(targetPath)) {
          try {
            if (!pathWithForwardSlashes(caps.executable).startsWith(
              pathWithForwardSlashes(targetPath)
            )) {
              return indent + "There is an unactivated Python environment in " + bold3(path3.name) + ". Did you forget to activate it?";
            }
          } catch {
            return void 0;
          }
        }
      } catch (err2) {
        if (!(err2 instanceof Deno.errors.NotFound)) {
          throw err2;
        }
      }
    }
  }
  const kRequirementsTxt = "requirements.txt";
  const kEnvironmentYaml = "environment.yml";
  for (const envFile of [kRequirementsTxt, kEnvironmentYaml]) {
    if (existsSync2(join4(Deno.cwd(), envFile))) {
      return indent + "There is a " + bold3(envFile) + " file in this directory. Is this for a " + (envFile === kRequirementsTxt ? "venv" : "conda env") + " that you need to restore?";
    }
  }
  return void 0;
}
function pythonInstallationMessage(indent = "") {
  const lines2 = [
    "Unable to locate an installed version of Python 3.",
    "Install Python 3 from " + bold3("https://www.python.org/downloads/")
  ];
  return lines2.map((line) => `${indent}${line}`).join("\n");
}
var jupyterCellSrcAsStr, jupyterCellSrcAsLines;
var init_jupyter_shared = __esm({
  "core/jupyter/jupyter-shared.ts"() {
    init_path();
    init_fs();
    init_colors2();
    init_path2();
    init_exec();
    init_kernels();
    init_capabilities();
    init_text();
    jupyterCellSrcAsStr = (cell) => {
      return typeof cell.source === "string" ? cell.source : cell.source.join("");
    };
    jupyterCellSrcAsLines = (cell) => {
      return typeof cell.source === "string" ? lines(cell.source) : cell.source;
    };
  }
});

// core/jupyter/jupyter-fixups.ts
function fixupStreams(nb) {
  for (const cell of nb.cells) {
    if (cell.cell_type !== "code" || cell.outputs === void 0) {
      continue;
    }
    if (cell.outputs.length === 0) {
      continue;
    }
    const newOutputs = [cell.outputs[0]];
    let i6 = 1;
    while (i6 < cell.outputs.length) {
      const prevOutput = newOutputs[newOutputs.length - 1];
      const thisOutput = cell.outputs[i6];
      if (thisOutput.output_type === "stream" && prevOutput.output_type === "stream" && thisOutput.name === prevOutput.name) {
        prevOutput.text = [...prevOutput.text ?? [], ...thisOutput.text ?? []];
      } else {
        newOutputs.push(thisOutput);
      }
      i6++;
    }
    cell.outputs = newOutputs;
  }
  return nb;
}
function fixupBokehCells(nb) {
  for (const cell of nb.cells) {
    if (cell.cell_type === "code") {
      let needsFixup = false;
      for (const output of cell?.outputs ?? []) {
        if (output.data === void 0) {
          continue;
        }
        if (output.data["application/vnd.bokehjs_load.v0+json"]) {
          needsFixup = true;
        }
      }
      if (!needsFixup) {
        continue;
      }
      const asTextHtml = (data3) => {
        if (data3["text/html"]) {
          return data3["text/html"];
        }
        if (data3["application/javascript"]) {
          return [
            "<script>",
            ...data3["application/javascript"],
            "<\/script>"
          ];
        }
        warn(
          "jupyter-fixups: unknown data types " + JSON.stringify(Object.keys(data3))
        );
        warn("will not fixup this bokeh cell.");
        throw new Error("");
      };
      try {
        const oldOutputs = cell.outputs;
        const newOutputs = [
          {
            metadata: {},
            output_type: "display_data",
            data: {
              "text/html": [
                asTextHtml(oldOutputs[0].data),
                asTextHtml(oldOutputs[1].data),
                asTextHtml(oldOutputs[2].data)
              ].flat()
            }
          }
        ];
        for (let i6 = 3; i6 < oldOutputs.length; i6 += 2) {
          newOutputs.push({
            metadata: {},
            output_type: "display_data",
            data: {
              "text/html": [
                asTextHtml(oldOutputs[i6].data),
                asTextHtml(oldOutputs[i6 + 1].data)
              ].flat()
            }
          });
        }
        cell.outputs = newOutputs;
      } catch {
        warn(
          "jupyter-fixup: cells without output data. Will not fixup bokeh cell"
        );
      }
    }
  }
  return nb;
}
function asYamlText(yaml) {
  return stringify(yaml, {
    indent: 2,
    lineWidth: -1,
    sortKeys: false,
    skipInvalid: true
  });
}
function fixupFrontMatter(nb) {
  const nbLines = (lns) => {
    return lns.map((line) => line.endsWith("\n") ? line : `${line}
`);
  };
  let partitioned;
  const frontMatterCellIndex = nb.cells.findIndex((cell) => {
    if (cell.cell_type === "raw" || cell.cell_type === "markdown") {
      partitioned = partitionYamlFrontMatter(jupyterCellSrcAsStr(cell)) || void 0;
      if (partitioned) {
        cell.cell_type = "raw";
        return true;
      } else {
        return false;
      }
    }
  });
  const yaml = partitioned ? readYamlFromMarkdown(partitioned.yaml) : void 0;
  if (yaml?.title) {
    return nb;
  }
  let title3;
  let currentCellIdx = 0;
  for (const cell of nb.cells) {
    if (cell.cell_type === "markdown") {
      const { lines: lines2, headingText, contentBeforeHeading } = markdownWithExtractedHeading(
        nbLines(jupyterCellSrcAsLines(cell)).join("")
      );
      if (headingText && !contentBeforeHeading) {
        title3 = headingText;
        cell.source = nbLines(lines2);
        break;
      } else if (currentCellIdx !== frontMatterCellIndex) {
        break;
      }
    }
    currentCellIdx++;
  }
  if (!title3) {
    return nb;
  }
  if (yaml) {
    yaml[kTitle] = title3;
    const yamlText = asYamlText(yaml);
    const frontMatterCell = nb.cells[frontMatterCellIndex];
    frontMatterCell.source = nbLines(
      lines(`---
${yamlText}---

${partitioned?.markdown || ""}`)
    );
  } else {
    const yamlText = asYamlText({ title: title3 });
    nb.cells.unshift({
      cell_type: "raw",
      source: nbLines(lines(`---
${yamlText}---
`)),
      metadata: {}
    });
  }
  return nb;
}
function fixupJupyterNotebook(nb, fixups) {
  let nbFixups;
  if (fixups === "minimal") {
    nbFixups = minimalFixups;
  } else if (fixups === "default") {
    nbFixups = defaultFixups;
  } else {
    nbFixups = fixups;
  }
  for (const fixup of nbFixups) {
    nb = fixup(nb);
  }
  return nb;
}
var defaultFixups, minimalFixups, bookFixups;
var init_jupyter_fixups = __esm({
  "core/jupyter/jupyter-fixups.ts"() {
    init_yaml();
    init_log();
    init_constants6();
    init_text();
    init_pandoc_partition();
    init_yaml();
    init_jupyter_shared();
    defaultFixups = [
      fixupBokehCells,
      fixupFrontMatter,
      fixupStreams
    ];
    minimalFixups = [
      fixupBokehCells,
      fixupStreams
    ];
    bookFixups = minimalFixups;
  }
});

// core/execute-inline.ts
function executeInlineCodeHandler(language, exec2) {
  const exprPattern = new RegExp(
    "(^|[^`])`{" + language + "}[ 	]([^`]+)`",
    "g"
  );
  return (code5) => {
    return code5.replaceAll(exprPattern, (match, prefix, expr) => {
      const result2 = exec2(expr.trim());
      if (result2) {
        return `${prefix}${result2}`;
      } else {
        return match;
      }
    });
  };
}
function executeInlineCodeHandlerMapped(language, exec2) {
  const exprPattern = new RegExp(
    "(^|[^`])`{" + language + "}[ 	]([^`]+)`",
    "g"
  );
  return (code5) => {
    let matches;
    const result2 = [];
    let prevIndex = 0;
    while (matches = exprPattern.exec(code5.value)) {
      result2.push(mappedSubstring(code5, prevIndex, matches.index));
      const matchMapped = mappedSubstring(
        code5,
        matches.index,
        matches.index + matches[0].length
      );
      const prefixMapped = mappedSubstring(
        code5,
        matches.index,
        matches.index + matches[1].length
      );
      const exprStr = matches[2];
      const exprResult = exec2(exprStr.trim());
      if (exprResult) {
        result2.push(prefixMapped);
        result2.push(asMappedString(exprResult));
      } else {
        result2.push(matchMapped);
      }
      prevIndex = matches.index + matches[0].length;
    }
    result2.push(mappedSubstring(code5, prevIndex));
    return mappedConcat(result2);
  };
}
var init_execute_inline = __esm({
  "core/execute-inline.ts"() {
    init_mapped_text();
  }
});

// core/jupyter/jupyter-inline.ts
function userExpressionsFromCell(cell) {
  const userExpressions = (cell.metadata[kCellUserExpressions] || []).reduce((userExpressions2, userExpression) => {
    userExpressions2.set(userExpression.expression, userExpression.result);
    return userExpressions2;
  }, /* @__PURE__ */ new Map());
  return userExpressions;
}
function asEscapedMarkdown(s5) {
  const singleQuote = "'", doubleQuote = '"';
  if (s5.startsWith(singleQuote) && s5.endsWith(singleQuote) || s5.startsWith(doubleQuote) && s5.endsWith(doubleQuote)) {
    s5 = s5.slice(1, -1);
    return s5.replace(/\\/g, "\\\\").replace(/([\\`*_{}\[\]()>#+-.!])/g, "\\$1");
  } else {
    return s5;
  }
}
function resolveUserExpressions(source2, userExpressions, options) {
  const executeInlineCode = executeInlineCodeHandler(
    options.language,
    (expr) => {
      if (options.execute.cache === true || options.execute.cache === "refresh") {
        throw new Error(
          `Inline expression encountered (${expr}). Inline expressions cannot be used with Jupyter Cache.`
        );
      }
      const result2 = userExpressions.get(expr);
      if (result2) {
        const mimeType = displayDataMimeType(result2, options);
        if (mimeType) {
          let data3 = result2.data[mimeType];
          if (Array.isArray(data3)) {
            data3 = data3.map(String).join("");
          }
          switch (mimeType) {
            case kTextHtml:
              return `${"`"}${data3}${"`"}{=html}`;
            case kTextLatex:
              return `${"`"}${data3}${"`"}{=tex}`;
            case kTextMarkdown:
              return `${data3}`;
            case kTextPlain:
            default:
              return asEscapedMarkdown(`${data3}`);
          }
        }
      }
    }
  );
  for (let i6 = 0; i6 < source2.length; i6++) {
    source2[i6] = executeInlineCode(source2[i6]);
  }
}
var init_jupyter_inline = __esm({
  "core/jupyter/jupyter-inline.ts"() {
    init_constants6();
    init_execute_inline();
    init_mime();
    init_display_data();
  }
});

// core/jupyter/jupyter.ts
function isJupyterNotebook(file) {
  return kJupyterNotebookExtensions.includes(extname4(file).toLowerCase());
}
async function quartoMdToJupyter(markdown, includeIds, project) {
  const [kernelspec, metadata] = await jupyterKernelspecFromMarkdown(
    markdown,
    project
  );
  const nb = {
    cells: [],
    metadata: {
      kernelspec,
      ...metadata
    },
    nbformat: 4,
    nbformat_minor: includeIds ? 5 : 4
  };
  const yamlRegEx = /^---\s*$/;
  /^\s*```+\s*\{([a-zA-Z0-9_]+)( *[ ,].*)?\}\s*$/;
  const startCodeCellRegEx = new RegExp(
    "^(\\s*)(```+)\\s*\\{" + kernelspec.language.toLowerCase() + "( *[ ,].*)?\\}\\s*$"
  );
  const startCodeRegEx = /^(\s*)```/;
  const endCodeRegEx = (indent = "", backtickCount2 = 0) => {
    return new RegExp("^" + indent + "`".repeat(backtickCount2) + "\\s*$");
  };
  const inputContent = markdown;
  let codeIndent = "";
  const lineBuffer = [];
  const flushLineBuffer = (cell_type, frontMatter) => {
    if (lineBuffer.length) {
      if (lineBuffer[0] === "") {
        lineBuffer.splice(0, 1);
      }
      if (lineBuffer[lineBuffer.length - 1] === "") {
        lineBuffer.splice(lineBuffer.length - 1, 1);
      }
      if (cell_type !== "code") {
        codeIndent = "";
      }
      const cell = {
        cell_type,
        metadata: codeIndent.length > 0 ? { [kCellMdIndent]: codeIndent } : {},
        source: lineBuffer.map((line, index2) => {
          if (codeIndent.length > 0) {
            line = line.replace(codeIndent, "");
          }
          return line + (index2 < lineBuffer.length - 1 ? "\n" : "");
        })
      };
      if (includeIds) {
        cell.id = shortUuid();
      }
      if (cell_type === "raw" && frontMatter) {
        const yaml = readYamlFromMarkdown(jupyterCellSrcAsStr(cell));
        if (yaml.jupyter) {
          delete yaml.jupyter;
          if (Object.keys(yaml).length > 0) {
            const yamlFrontMatter = trimEmptyLines(lines(stringify(yaml, {
              indent: 2,
              lineWidth: -1,
              sortKeys: false,
              skipInvalid: true
            })));
            cell.source = [
              "---\n",
              ...yamlFrontMatter.map((line) => line + "\n"),
              "---"
            ];
          } else {
            cell.source = [];
          }
        }
      } else if (cell_type === "code") {
        const cellSrcLines2 = typeof cell.source === "string" ? lines(cell.source) : cell.source;
        const { yaml, source: source2 } = partitionCellOptions(
          kernelspec.language.toLowerCase(),
          cellSrcLines2
        );
        if (yaml && !Array.isArray(yaml) && typeof yaml === "object") {
          if (includeIds && yaml[kCellLabel] && !yaml[kCellId]) {
            yaml[kCellId] = jupyterAutoIdentifier(String(yaml[kCellLabel]));
          }
          const yamlKeys = Object.keys(yaml);
          yamlKeys.forEach((key) => {
            if (key === kCellId) {
              if (includeIds) {
                cell.id = String(yaml[key]);
              }
              delete yaml[key];
            } else {
              if (!kJupyterCellOptionKeys.includes(key)) {
                cell.metadata[key] = yaml[key];
                delete yaml[key];
              }
            }
          });
          if (Object.keys(yaml).length < yamlKeys.length) {
            const yamlOutput = jupyterCellOptionsAsComment(
              kernelspec.language.toLowerCase(),
              yaml
            );
            cell.source = yamlOutput.concat(source2);
          }
        }
        cell.execution_count = null;
        cell.outputs = [];
      }
      const cellSrcLines = typeof cell.source === "string" ? lines(cell.source) : cell.source;
      cell.source = trimEmptyLines(cellSrcLines);
      if (cell.source.length > 0) {
        nb.cells.push(cell);
      }
      lineBuffer.splice(0, lineBuffer.length);
    }
  };
  let parsedFrontMatter = false, inYaml = false, inCodeCell = false, inCode = false, backtickCount = 0;
  let currentLine = 0;
  const contentLines = lines(inputContent);
  for (currentLine = 0; currentLine < contentLines.length; ++currentLine) {
    const line = contentLines[currentLine];
    if (yamlRegEx.test(line) && !inCodeCell && !inCode && contentLines[currentLine + 1]?.trim() !== "") {
      if (inYaml) {
        lineBuffer.push(line);
        flushLineBuffer("raw", !parsedFrontMatter);
        parsedFrontMatter = true;
        inYaml = false;
      } else {
        flushLineBuffer("markdown");
        lineBuffer.push(line);
        inYaml = true;
      }
    } else if (!inCodeCell && startCodeCellRegEx.test(line)) {
      flushLineBuffer("markdown");
      inCodeCell = true;
      codeIndent = line.match(startCodeCellRegEx)[1];
      backtickCount = line.match(startCodeCellRegEx)[2].length;
    } else if (inCodeCell && endCodeRegEx(codeIndent, backtickCount).test(line)) {
      if (inCodeCell) {
        inCodeCell = false;
        flushLineBuffer("code");
        codeIndent = "";
      } else {
        inCode = !inCode;
        codeIndent = "";
        lineBuffer.push(line);
      }
    } else if (!inCodeCell && startCodeRegEx.test(line)) {
      codeIndent = line.match(startCodeRegEx)[1];
      inCode = true;
      lineBuffer.push(line);
    } else {
      lineBuffer.push(line);
    }
  }
  flushLineBuffer("markdown");
  return nb;
}
async function jupyterKernelspecFromMarkdown(markdown, project) {
  const config2 = project?.config;
  const yaml = config2 ? mergeConfigs(config2, readYamlFromMarkdown(markdown)) : readYamlFromMarkdown(markdown);
  const yamlJupyter = yaml.jupyter;
  if (!yamlJupyter) {
    const languages2 = languagesInMarkdown(markdown);
    languages2.add("python");
    for (const language of languages2) {
      const kernelspec = await jupyterKernelspecForLanguage(language);
      if (kernelspec) {
        return [kernelspec, {}];
      }
    }
    const kernelspecs = await jupyterKernelspecs();
    return Promise.reject(
      new Error(
        `No kernel found for any language checked (${Array.from(languages2).join(", ")}) in any of the kernelspecs checked (${Array.from(kernelspecs.values()).map((k3) => k3.name).join(", ")}).`
      )
    );
  } else if (typeof yamlJupyter === "string") {
    const kernel = yamlJupyter;
    const kernelspec = await jupyterKernelspec(kernel);
    if (kernelspec) {
      return [kernelspec, {}];
    } else {
      return Promise.reject(
        new Error(
          `Jupyter kernel '${kernel}' not found. Known kernels: ${Array.from((await jupyterKernelspecs()).values()).map((kernel2) => kernel2.name).join(", ")}. Run 'quarto check jupyter' with your python environment activated to check python version used.`
        )
      );
    }
  } else if (typeof yamlJupyter === "object") {
    const jupyter = { ...yamlJupyter };
    if (isJupyterKernelspec(jupyter.kernelspec)) {
      const kernelspec = jupyter.kernelspec;
      delete jupyter.kernelspec;
      return [kernelspec, jupyter];
    } else if (typeof jupyter.kernel === "string") {
      const kernelspec = await jupyterKernelspec(jupyter.kernel);
      if (kernelspec) {
        delete jupyter.kernel;
        return [kernelspec, jupyter];
      } else {
        return Promise.reject(
          new Error(
            `Jupyter kernel '${jupyter.kernel}' not found. Known kernels: ${Array.from((await jupyterKernelspecs()).values()).map((kernel) => kernel.name).join(", ")}. Run 'quarto check jupyter' with your python environment activated to check python version used.`
          )
        );
      }
    } else {
      return Promise.reject(
        new Error(
          "Invalid Jupyter kernelspec (must include name, language, & display_name)"
        )
      );
    }
  } else {
    return Promise.reject(
      new Error(
        "Invalid jupyter YAML metadata found in file (must be string or object)"
      )
    );
  }
}
function jupyterFromFile(input) {
  const nbContents = Deno.readTextFileSync(input);
  return jupyterFromJSON(nbContents);
}
function jupyterFromJSON(nbContents) {
  const nbJSON = JSON.parse(nbContents);
  const nb = nbJSON;
  if (!nb.metadata.kernelspec?.language) {
    if (nb.metadata.kernelspec) {
      nb.metadata.kernelspec.language = nbJSON.metadata.language_info?.name;
      if (!nb.metadata.kernelspec.language && nb.metadata.kernelspec.name?.includes("python")) {
        nb.metadata.kernelspec.language = "python";
      }
    } else {
      nb.metadata.kernelspec = jupyterDefaultPythonKernelspec();
    }
  }
  if (!nb.metadata.kernelspec.language) {
    throw new Error("No language set for Jupyter notebook");
  }
  if (!nb.cells) {
    throw new Error("No cells available in Jupyter notebook");
  }
  return nb;
}
function jupyterAutoIdentifier(label) {
  label = pandocAsciify(label);
  label = label.replace(/\s/g, "-").replace(/[^a-zA-Z0-9-_]/g, "").replace(/^[^A-Za-z]+/, "");
  if (label.length > 0) {
    return label.slice(0, 64);
  } else {
    return shortUuid();
  }
}
function jupyterAssets(input, to) {
  input = normalizePath(input);
  const files_dir = join4(dirname4(input), inputFilesDir(input));
  const figures_dir = join4(files_dir, figuresDir(to));
  ensureDirSync(figures_dir);
  let supporting_dir = files_dir;
  for (const walk5 of walkSync(join4(files_dir), { maxDepth: 1 })) {
    if (walk5.path !== files_dir && walk5.path !== figures_dir) {
      supporting_dir = figures_dir;
      break;
    }
  }
  const base_dir = dirname4(input);
  return {
    base_dir,
    files_dir: pathWithForwardSlashes(relative4(base_dir, files_dir)),
    figures_dir: pathWithForwardSlashes(relative4(base_dir, figures_dir)),
    supporting_dir: pathWithForwardSlashes(relative4(base_dir, supporting_dir))
  };
}
async function jupyterToMarkdown(nb, options) {
  const project = options.executeOptions.project;
  const projType = project?.config?.project?.[kProjectType];
  if (projType === "book") {
    nb = fixupJupyterNotebook(nb, bookFixups);
  } else if (project?.isSingleFile) {
    nb = fixupJupyterNotebook(nb, options.fixups || "default");
  } else if (project?.config?.title !== void 0 && (projType === "default" || projType === void 0)) {
    nb = fixupJupyterNotebook(nb, minimalFixups);
  } else {
    nb = fixupJupyterNotebook(nb, options.fixups || "default");
  }
  const isHtml = options.toHtml && !options.toIpynb;
  const dependencies = isHtml ? extractJupyterWidgetDependencies(nb) : void 0;
  const htmlPreserve = isHtml ? removeAndPreserveHtml(nb) : void 0;
  const cellOutputs = [];
  const validateCellLabel = cellLabelValidator();
  let codeCellIndex = 0;
  let frontMatter = void 0;
  for (let i6 = 0; i6 < nb.cells.length; i6++) {
    const md = [];
    const cell = jupyterCellWithOptions(
      i6,
      nb.metadata.kernelspec.language.toLowerCase(),
      nb.cells[i6]
    );
    validateCellLabel(cell);
    const slideType = options.toPresentation ? cell.metadata[kCellSlideshow]?.[kCellSlideshowSlideType] : void 0;
    if (slideType) {
      if (slideType === "skip") {
        continue;
      } else if (slideType == "slide" || slideType === "subslide") {
        md.push("\n---\n\n");
      } else if (slideType == "fragment") {
        md.push("\n. . .\n\n");
      } else if (slideType == "notes") {
        md.push("\n:::::::::: notes\n\n");
      }
    }
    switch (cell.cell_type) {
      case "markdown":
        {
          const markdownOptions = {
            ...options
          };
          if (frontMatter === void 0) {
            frontMatter = partitionYamlFrontMatter(
              jupyterCellSrcAsStr(cell)
            )?.yaml;
            if (frontMatter) {
              markdownOptions.preserveCellMetadata = false;
            }
          }
          md.push(...mdFromContentCell(cell, markdownOptions));
        }
        break;
      case "raw":
        md.push(...mdFromRawCell(cell, options));
        break;
      case "code":
        md.push(...await mdFromCodeCell(cell, ++codeCellIndex, options));
        break;
      default:
        throw new Error("Unexpected cell type " + cell.cell_type);
    }
    if (slideType === "notes") {
      md.push("\n::::::::::\n");
    }
    md.push("\n");
    cellOutputs.push({
      id: cell.id,
      markdown: md.join(""),
      metadata: cell.metadata,
      options: cell.options
    });
  }
  let notebookOutputs = void 0;
  if (options.toIpynb) {
    const md = [];
    md.push("---\n");
    const widgets = nb.metadata.widgets ? encodeBase64(JSON.stringify(nb.metadata.widgets)) : void 0;
    const jupyterMetadata = {
      jupyter: {
        ...nb.metadata,
        widgets
      }
    };
    const yamlText = stringify(jupyterMetadata, {
      indent: 2,
      lineWidth: -1,
      sortKeys: false,
      skipInvalid: true
    });
    md.push(yamlText);
    md.push("---\n");
    notebookOutputs = {
      suffix: md.join("")
    };
  }
  return {
    cellOutputs,
    notebookOutputs,
    dependencies,
    htmlPreserve
  };
}
function jupyterCellWithOptions(index2, language, cell) {
  const { yaml, optionsSource, source: source2 } = partitionCellOptions(
    language,
    jupyterCellSrcAsLines(cell)
  );
  const metadataOptions = kJupyterCellOptionKeys.reduce((options2, key) => {
    if (cell.metadata[key] !== void 0) {
      options2[key] = cell.metadata[key];
    }
    return options2;
  }, {});
  const explicitOptions = {
    ...metadataOptions,
    ...yaml
  };
  [kLayout, kTblColwidths].forEach((option) => {
    if (explicitOptions[option] && typeof explicitOptions[option] !== "string") {
      explicitOptions[option] = JSON.stringify(explicitOptions[option]);
    }
  });
  const tags = cell.metadata.tags;
  const tagOptions = tagsToOptions(tags || []);
  const options = {
    ...tagOptions,
    ...explicitOptions
  };
  const cellId = (cell2) => {
    if (options && options[kCellLabel] && typeof options[kCellLabel] === "string") {
      return `cell-${options[kCellLabel]}`;
    } else if (cell2.id) {
      return cell2.id;
    } else {
      return `cell-${index2}`;
    }
  };
  const validMetadata = {};
  for (const key of Object.keys(cell.metadata)) {
    const value = cell.metadata[key];
    let jsonEncodedKeyIndex = 0;
    if (value !== void 0) {
      if (!value && typeof value === "object") {
        validMetadata[key] = null;
      } else if (value && typeof value === "object" && !Array.isArray(value)) {
        validMetadata[`quarto-private-${++jsonEncodedKeyIndex}`] = JSON.stringify({ key, value });
      } else if (typeof value === "string" || typeof value === "number" || typeof value === "boolean" || Array.isArray(value)) {
        validMetadata[key] = value;
      } else {
        error(
          `Invalid metadata type for key ${key}: ${typeof value}. Entry will not be serialized.`
        );
      }
    }
  }
  return {
    ...cell,
    metadata: validMetadata,
    id: cellId(cell),
    source: source2,
    optionsSource,
    options
  };
}
function jupyterCellOptionsAsComment(language, options, stringifyOptions) {
  if (Object.keys(options).length > 0) {
    const cellYaml = stringify(options, {
      indent: 2,
      lineWidth: -1,
      sortKeys: false,
      skipInvalid: true,
      ...stringifyOptions
    });
    const commentChars = langCommentChars2(language);
    const yamlOutput = trimEmptyLines(lines(cellYaml)).map((line) => {
      line = optionCommentPrefix(commentChars[0]) + line + optionCommentSuffix(commentChars[1]);
      return line + "\n";
    });
    return yamlOutput;
  } else {
    return [];
  }
}
function mdFromContentCell(cell, options) {
  const contentCellEnvelope = createCellEnvelope(["cell", "markdown"], options);
  const source2 = typeof cell.source === "string" ? [cell.source] : [...cell.source];
  if (options && source2) {
    const userExpressions = userExpressionsFromCell(cell);
    resolveUserExpressions(source2, userExpressions, options);
  }
  if (options && cell.attachments && source2) {
    Object.keys(cell.attachments).forEach((file, index2) => {
      const attachment = cell.attachments[file];
      for (const mimeType of Object.keys(attachment)) {
        if (extensionForMimeImageType(mimeType, void 0)) {
          const imageFile = options.assets.figures_dir + `/${cell.id}-${index2 + 1}-${file}`;
          const outputFile5 = join4(options.assets.base_dir, imageFile);
          ensureDirSync(dirname4(outputFile5));
          const data3 = attachment[mimeType];
          const imageText = Array.isArray(data3) ? data3.join("") : data3;
          if (!imageText.trimStart().startsWith("<svg")) {
            const imageData = decodeBase64(imageText.replaceAll("\n", ""));
            Deno.writeFileSync(outputFile5, imageData);
          } else {
            Deno.writeTextFileSync(outputFile5, imageText);
          }
          for (let i6 = 0; i6 < source2.length; i6++) {
            source2[i6] = source2[i6].replaceAll(
              `attachment:${file}`,
              () => imageFile
            );
          }
          break;
        }
      }
    });
  }
  return contentCellEnvelope(cell.id, mdEnsureTrailingNewline(source2));
}
function mdFormatOutput(format14, source2) {
  const ticks = ticksForCode(source2);
  return mdEnclosedOutput(ticks + "{=" + format14 + "}", source2, ticks);
}
function mdRawOutput(mimeType, source2) {
  switch (mimeType) {
    case kTextHtml:
      return mdHtmlOutput(source2);
    case kTextLatex:
      return mdLatexOutput(source2);
    case kRestructuredText:
      return mdFormatOutput("rst", source2);
    case kApplicationRtf:
      return mdFormatOutput("rtf", source2);
    case kApplicationJavascript:
      return mdScriptOutput(mimeType, source2);
  }
}
function mdFromRawCell(cell, options) {
  const rawCellEnvelope = createCellEnvelope(["cell", "raw"], options);
  const mimeType = cell.metadata?.[kCellRawMimeType];
  if (mimeType) {
    const rawOutput = mdRawOutput(mimeType, jupyterCellSrcAsLines(cell));
    if (rawOutput) {
      return rawCellEnvelope(cell.id, rawOutput);
    }
  }
  return mdFromContentCell(
    cell,
    options ? {
      ...options,
      preserveCellMetadata: false
    } : void 0
  );
}
function mdEnsureTrailingNewline(source2) {
  if (source2.length > 0 && !source2[source2.length - 1].endsWith("\n")) {
    return source2.slice(0, source2.length - 1).concat(
      [source2[source2.length - 1] + "\n"]
    );
  } else {
    return source2;
  }
}
function createCellEnvelope(classes, options) {
  return (id, source2) => {
    if (options && options.preserveCellMetadata) {
      const wrappedSource = [...source2];
      wrappedSource.unshift(
        `:::{#${id} ${classes.map((clz) => `.${clz}`).join(" ")}}
`
      );
      wrappedSource.push(`:::`);
      return mdEnsureTrailingNewline(wrappedSource);
    } else {
      return source2;
    }
  };
}
function tagsToOptions(tags) {
  const result2 = {};
  tags.forEach((tag) => {
    const mapping = tagMapping[tag];
    if (mapping) {
      const keys = Object.keys(mapping);
      keys.forEach((key) => {
        result2[key] = mapping[key];
      });
    }
  });
  return result2;
}
function optionCommentPrefix(comment) {
  return comment + "| ";
}
function optionCommentSuffix(comment) {
  if (comment) {
    return " " + comment;
  } else {
    return "";
  }
}
function langCommentChars2(lang) {
  const chars = kLangCommentChars2[lang] || "#";
  if (!Array.isArray(chars)) {
    return [chars];
  } else {
    return chars;
  }
}
function cleanJupyterOutputDisplayData(output) {
  const rawOutput = output;
  const outputData = {};
  for (const [key, value] of Object.entries(
    rawOutput.data
  )) {
    const strValue = typeof value === "string" ? [value] : Array.isArray(value) && value.every((x3) => typeof x3 === "string") ? value : void 0;
    if (strValue === void 0) {
      outputData[key] = value;
    } else {
      outputData[key] = strValue;
    }
  }
  return {
    ...output,
    data: outputData,
    metadata: rawOutput.metadata,
    noCaption: rawOutput.noCaption
  };
}
async function mdFromCodeCell(cell, cellIndex, options) {
  if (!includeCell(cell, options)) {
    return [];
  }
  const haveImage = !!cell.outputs?.some((output) => isImage(output, options));
  const outputs = (cell.outputs || []).filter((output) => {
    if (output.output_type === "stream" && output.name === "stderr" && !includeWarnings(cell, options)) {
      return false;
    }
    if (isDiscardableTextExecuteResult(output, haveImage)) {
      return false;
    }
    return true;
  }).map((output) => {
    if (!options.toLatex && isDisplayData(output) && output.data[kTextLatex]) {
      return displayDataWithMarkdownMath(output);
    } else {
      return output;
    }
  });
  if (!cell.source.length && !outputs.length) {
    return [];
  }
  const asis = (
    // specified as an explicit option for this cell
    cell.options[kOutput] === "asis" || // specified globally with no output override for this cell
    options.execute[kOutput] === "asis" && cell.options[kOutput] === void 0
  );
  const md = [];
  const divMd = [`::: {`];
  const kCellOptionsFilter = kJupyterCellInternalOptionKeys.concat(
    kJupyterCellStandardMetadataKeys,
    kJupyterCellThirdPartyMetadataKeys
  );
  const label = cellLabel(cell);
  const labelCellContainer = shouldLabelCellContainer(cell, outputs, options);
  if (label && labelCellContainer) {
    divMd.push(`${label} `);
  } else if ((isIpynbOutput(options.executeOptions.format.pandoc) || isJatsOutput(options.executeOptions.format.pandoc) || isHtmlOutput(options.executeOptions.format.pandoc)) && cell.id) {
    divMd.push(`#${cell.id} `);
  }
  let { cellCaption, outputCaptions } = resolveCaptions(cell);
  outputCaptions = outputCaptions.map(
    (caption) => caption.trim().replaceAll("\n", " ")
  );
  divMd.push(`.cell `);
  if (hideCell(cell, options)) {
    divMd.push(`.hidden `);
  }
  const cellClasses = cell.options[kCellClasses] || new Array();
  const classes = Array.isArray(cellClasses) ? cellClasses : [cellClasses];
  if (typeof cell.options[kCellPanel] === "string") {
    classes.push(`panel-${cell.options[kCellPanel]}`);
  }
  if (typeof cell.options[kCellColumn] === "string") {
    classes.push(`column-${cell.options[kCellColumn]}`);
  }
  if (typeof cell.options[kCellFigColumn] === "string") {
    classes.push(`fig-column-${cell.options[kCellFigColumn]}`);
  }
  if (typeof cell.options[kCellTblColumn] === "string") {
    classes.push(`tbl-column-${cell.options[kCellTblColumn]}`);
  }
  if (typeof cell.options[kCapLoc] === "string") {
    classes.push(`caption-${cell.options[kFigCapLoc]}`);
  }
  if (typeof cell.options[kFigCapLoc] === "string") {
    classes.push(`fig-cap-location-${cell.options[kFigCapLoc]}`);
  }
  if (typeof cell.options[kTblCapLoc] === "string") {
    classes.push(`tbl-cap-location-${cell.options[kTblCapLoc]}`);
  }
  if (classes.length > 0) {
    const classText = classes.map((clz) => {
      clz = toString(clz);
      return clz.startsWith(".") ? clz : "." + clz;
    }).join(" ");
    divMd.push(classText + " ");
  }
  const cellOptions = {
    ...cell.metadata,
    ...cell.options
  };
  let forwardedAttrs = false;
  for (const key of Object.keys(cellOptions)) {
    if (!kCellOptionsFilter.includes(key.toLowerCase())) {
      let value = cellOptions[key];
      if (value !== void 0) {
        if (typeof value !== "string") {
          value = JSON.stringify(value);
        }
        value = value.replaceAll("'", `\\'`);
        divMd.push(`${key}='${value}' `);
        forwardedAttrs = true;
      }
    }
  }
  const needCell = label && labelCellContainer || // isTRUE(nzchar(label))
  classes.length > 0 || // length(classes) > 1
  forwardedAttrs || // isTRUE(nzchar(forwardAttr))
  (cellCaption !== void 0 || outputCaptions.length > 0);
  if (typeof cell.execution_count === "number") {
    divMd.push(`execution_count=${cell.execution_count} `);
  }
  const divBeginMd = divMd.join("").replace(/ $/, "").concat("}\n");
  if (includeCode(cell, options) || options.preserveCodeCellYaml) {
    const fenced = echoFenced(cell, options);
    const ticks = "`".repeat(
      Math.max(countTicks(jupyterCellSrcAsLines(cell)) + 1, fenced ? 4 : 3)
    );
    md.push(ticks + " {");
    if (!options.preserveCodeCellYaml) {
      if (typeof cell.options[kCellLstLabel] === "string") {
        let label2 = cell.options[kCellLstLabel];
        if (!label2.startsWith("#")) {
          label2 = "#" + label2;
        }
        md.push(label2 + " ");
      }
      if (!fenced) {
        md.push("." + (cellOptions.language || options.language));
      }
      md.push(" .cell-code");
      if (hideCode(cell, options)) {
        md.push(" .hidden");
      }
      if (cell.options[kCodeOverflow] === "wrap") {
        md.push(" .code-overflow-wrap");
      } else if (cell.options[kCodeOverflow] === "scroll") {
        md.push(" .code-overflow-scroll");
      }
      if (typeof cell.options[kCellLstCap] === "string") {
        md.push(` lst-cap="${cell.options[kCellLstCap]}"`);
      }
      if (typeof cell.options[kCodeFold] !== "undefined") {
        md.push(` code-fold="${cell.options[kCodeFold]}"`);
      }
      if (typeof cell.options[kCodeSummary] !== "undefined") {
        md.push(` code-summary="${cell.options[kCodeSummary]}"`);
      }
      if (typeof cell.options[kCodeLineNumbers] !== "undefined") {
        md.push(` code-line-numbers="${cell.options[kCodeLineNumbers]}"`);
      }
    }
    md.push("}\n");
    let source2 = typeof cell.source === "string" ? [cell.source] : [...cell.source];
    if (fenced) {
      const optionsSource = cell.optionsSource.filter(
        (line) => line.search(/\|\s+echo:\s+fenced\s*$/) === -1
      );
      if (optionsSource.length > 0) {
        source2 = trimEmptyLines(source2, "trailing");
      } else {
        source2 = trimEmptyLines(source2, "all");
      }
      source2.unshift(...optionsSource);
      source2.unshift("```{{" + options.language + "}}\n");
      source2.push("\n```\n");
    } else if (cell.optionsSource.length > 0) {
      source2 = trimEmptyLines(source2, "leading");
    }
    if (options.preserveCodeCellYaml) {
      md.push(...cell.optionsSource);
    }
    md.push(...source2, "\n");
    md.push(ticks + "\n");
  }
  if (includeOutput(cell, options)) {
    const labelName = label ? label.replace(/^#/, "").replaceAll(":", "-") : "cell-" + (cellIndex + 1);
    const outputName = `${options.outputPrefix ? options.outputPrefix + "-" : ""}${pandocAutoIdentifier(labelName, true)}-output`;
    let nextOutputSuffix = 1;
    const sortedOutputs = outputs.map((value, index2) => ({
      index: index2,
      output: value
    })).sort((a5, b3) => {
      const aIdx = a5.output.metadata?.[kQuartoOutputOrder] !== void 0 ? a5.output.metadata?.[kQuartoOutputOrder] : Number.MAX_SAFE_INTEGER;
      const bIdx = b3.output.metadata?.[kQuartoOutputOrder] !== void 0 ? b3.output.metadata?.[kQuartoOutputOrder] : Number.MAX_SAFE_INTEGER;
      return aIdx - bIdx;
    });
    for (const { index: index2, output } of sortedOutputs) {
      const outputLabel = label && labelCellContainer && isDisplayData(output) ? label + "-" + nextOutputSuffix++ : label;
      if (output.metadata?.[kQuartoOutputDisplay] === false) {
        continue;
      }
      if (!asis) {
        md.push("\n::: {");
        if (outputLabel && shouldLabelOutputContainer(output, cell.options, options)) {
          md.push(outputLabel + " ");
        }
        md.push(".cell-output ");
        if (output.output_type === "stream") {
          const stream = output;
          md.push(`.cell-output-${stream.name}`);
        } else {
          md.push(`.${outputTypeCssClass(output.output_type)}`);
        }
        if (isMarkdown(output, options)) {
          md.push(` .${outputTypeCssClass("markdown")}`);
        }
        if (hideOutput(cell, options) || isWarningOutput(output) && hideWarnings(cell, options)) {
          md.push(` .hidden`);
        }
        if (typeof output.execution_count === "number") {
          md.push(` execution_count=${output.execution_count}`);
        }
        if (cell.options[kHtmlTableProcessing] === "none") {
          md.push(" html-table-processing=none");
        }
        md.push("}\n");
      }
      if (options.toLatex && !options.figPos && !cell.options[kCellFigPos] && !hasLayoutOptions(cell) && includeCode(cell, options)) {
        cell.options[kCellFigPos] = "H";
      }
      const figureOptions = {};
      const broadcastFigureOption = (name2) => {
        const value = cell.options[name2];
        if (value) {
          if (Array.isArray(value)) {
            return value[index2];
          } else {
            return value;
          }
        } else {
          return null;
        }
      };
      figureOptions[kCellFigAlign] = broadcastFigureOption(kCellFigAlign);
      figureOptions[kCellFigScap] = broadcastFigureOption(kCellFigScap);
      figureOptions[kCellFigLink] = broadcastFigureOption(kCellFigLink);
      figureOptions[kCellFigEnv] = broadcastFigureOption(kCellFigEnv);
      figureOptions[kCellFigPos] = broadcastFigureOption(kCellFigPos);
      figureOptions[kCellFigAlt] = broadcastFigureOption(kCellFigAlt);
      if (output.output_type === "stream") {
        const stream = output;
        if (asis && stream.name === "stdout") {
          let text = [];
          if (typeof stream.text === "string") {
            text = [stream.text];
          } else {
            text = stream.text;
          }
          md.push(text.join(""));
        } else {
          md.push(await mdOutputStream(stream, options));
        }
      } else if (output.output_type === "error") {
        md.push(await mdOutputError(output, options));
      } else if (isDisplayData(output)) {
        const fixedOutput = cleanJupyterOutputDisplayData(output);
        if (Object.keys(fixedOutput.data).length > 0) {
          const caption = isCaptionableData(output) ? outputCaptions.shift() || null : null;
          md.push(
            await mdOutputDisplayData(
              outputLabel,
              caption,
              outputName + "-" + (index2 + 1),
              fixedOutput,
              options,
              figureOptions
            )
          );
          if (caption && !isImage(output, options)) {
            md.push(`
${caption}
`);
          }
        }
      } else {
        throw new Error("Unexpected output type " + output.output_type);
      }
      if (!asis) {
        md.push(`:::
`);
      }
    }
  } else if (cell.outputs) {
    cell.outputs.filter(isDisplayData).filter(
      (output) => output.metadata.ojs_define
    ).forEach((ojs_define) => {
      const ojs_html = ojs_define.data[kTextHtml];
      md.push("\n" + mdHtmlOutput(ojs_html));
    });
  }
  if (md.length > 0 && (needCell || !asis)) {
    md.unshift(divBeginMd);
    if (cellCaption) {
      md.push("\n" + cellCaption + "\n");
    }
    md.push(":::\n");
  }
  md.push("\n".repeat(cell.metadata.lines_to_next_cell || 1));
  if (cell.options[kCellMdIndent]) {
    const indent = String(cell.options[kCellMdIndent]);
    const mdWithIndent = md.join("").split("\n").map((line) => indent + line).join("\n");
    md.splice(0, md.length - 1);
    md.push(...mdWithIndent);
  }
  return md;
}
function isDiscardableTextExecuteResult(output, haveImage) {
  if (output.output_type === "execute_result") {
    const data3 = output.data;
    if (Object.keys(data3).length === 1) {
      const textPlain = data3?.[kTextPlain];
      if (textPlain && textPlain.length) {
        if (haveImage && textPlain.length === 1) {
          return /^([<(\[]).*?([>)\]])$/.test(textPlain[0].trim());
        } else {
          return [
            "[<matplotlib",
            "<matplotlib",
            "<seaborn.",
            "<ggplot:"
          ].some((startsWith) => textPlain[0].startsWith(startsWith));
        }
      }
    }
  }
  return false;
}
function hasLayoutOptions(cell) {
  return Object.keys(cell.options).some((key) => key.startsWith("layout"));
}
function isDisplayDataType(output, options, checkFn) {
  if (isDisplayData(output)) {
    const mimeType = displayDataMimeType(
      output,
      options
    );
    if (mimeType) {
      if (checkFn(mimeType)) {
        return true;
      }
    }
  }
  return false;
}
function isImage(output, options) {
  return isDisplayDataType(output, options, displayDataIsImage);
}
function isMarkdown(output, options) {
  return isDisplayDataType(output, options, displayDataIsMarkdown);
}
async function mdOutputStream(output, options) {
  let text = [];
  if (typeof output.text === "string") {
    text = [output.text];
  } else {
    text = output.text;
  }
  if (output.name === "stderr") {
    if (text[0]) {
      const firstLine = text[0].replace(
        /<ipython-input.*?>:\d+:\s+/,
        ""
      );
      text = [firstLine, ...text.slice(1)];
    }
  }
  if (options.toHtml && text.some(hasAnsiEscapeCodes)) {
    const linesHTML = await convertToHtmlSpans(text.join("\n"));
    return mdMarkdownOutput(
      [
        "\n::: {.ansi-escaped-output}\n```{=html}\n<pre>",
        linesHTML,
        "</pre>\n```\n:::\n"
      ]
    );
  } else {
    return mdCodeOutput(text.map(stripAnsiCode));
  }
}
async function mdOutputError(output, options) {
  const traceback = output.traceback.join("\n");
  if (!options.toHtml || !hasAnsiEscapeCodes(output.evalue) && !hasAnsiEscapeCodes(traceback)) {
    if (output.traceback.length > 0) {
      return mdCodeOutput([
        output.ename + ": " + output.evalue + "\n" + traceback
      ]);
    } else {
      return mdCodeOutput([
        output.ename + ": " + output.evalue
      ]);
    }
  }
  const tracebackHtml = await convertToHtmlSpans(traceback);
  return mdMarkdownOutput(
    [
      "\n::: {.ansi-escaped-output}\n```{=html}\n<pre>",
      tracebackHtml,
      "</pre>\n```\n:::\n"
    ]
  );
}
async function mdOutputDisplayData(label, caption, filename, output, options, figureOptions) {
  const mimeType = displayDataMimeType(output, options);
  if (mimeType) {
    if (displayDataIsImage(mimeType)) {
      return mdImageOutput(
        label,
        caption,
        filename,
        mimeType,
        output,
        options,
        figureOptions
      );
    } else if (displayDataIsMarkdown(mimeType)) {
      return mdMarkdownOutput(output.data[mimeType]);
    } else if (displayDataIsLatex(mimeType)) {
      return mdLatexOutput(output.data[mimeType]);
    } else if (displayDataIsHtml(mimeType)) {
      return mdHtmlOutput(output.data[mimeType]);
    } else if (displayDataIsJson(mimeType)) {
      const json3 = output.data[mimeType];
      json3[kQuartoMimeType] = mimeType;
      return mdJsonOutput(
        mimeType,
        json3,
        options
      );
    } else if (displayDataIsJavascript(mimeType)) {
      return mdScriptOutput(mimeType, output.data[mimeType]);
    } else if (displayDataIsTextPlain(mimeType)) {
      const data3 = output.data[mimeType];
      if (!Array.isArray(data3) || data3.some((s5) => typeof s5 !== "string")) {
        return await mdWarningOutput(
          `Unable to process text plain output data 
which does not appear to be plain text: ${JSON.stringify(data3)}`,
          options
        );
      }
      const lines2 = data3;
      if (lines2.length === 1 && lines2[0].startsWith("'<table") && lines2[0].endsWith("</table>'")) {
        lines2[0] = lines2[0].slice(1, -1);
        return mdMarkdownOutput(lines2);
      } else {
        if (options.toHtml) {
          if (lines2.some(hasAnsiEscapeCodes)) {
            const html = await Promise.all(
              lines2.map(convertToHtmlSpans)
            );
            return mdMarkdownOutput(
              [
                "\n::: {.ansi-escaped-output}\n```{=html}\n<pre>",
                ...html,
                "</pre>\n```\n:::\n"
              ]
            );
          } else {
            return mdCodeOutput(lines2);
          }
        } else {
          return mdCodeOutput(lines2.map(stripAnsiCode));
        }
      }
    }
  }
  return await mdWarningOutput(
    "Unable to display output for mime type(s): " + Object.keys(output.data).join(", "),
    options
  );
}
function mdImageOutput(label, caption, filename, mimeType, output, options, figureOptions) {
  const data3 = output.data[mimeType];
  const metadata = output.metadata[mimeType];
  function metadataValue(key, defaultValue) {
    if (metadata) {
      return metadata[key] ? metadata[key] : defaultValue;
    }
    return defaultValue;
  }
  let width = metadataValue(kCellOutWidth) ?? metadataValue(kCellWidth, 0);
  let height = metadataValue(kCellOutHeight) ?? metadataValue(kCellHeight, 0);
  const alt = caption || "";
  const ext = extensionForMimeImageType(mimeType);
  const imageFile = options.assets.figures_dir + "/" + filename + "." + ext;
  const imageText = Array.isArray(data3) ? data3.join("") : data3.trim();
  const outputFile5 = join4(options.assets.base_dir, imageFile);
  if (
    // base64 decode if it's not svg
    mimeType !== kImageSvg || // or if it is encoded svg; this could happen when used in embed context,
    // as Pandoc will generate ipynb with base64 encoded svg data
    // https://github.com/quarto-dev/quarto-cli/issues/9793
    !/<svg/.test(imageText)
  ) {
    const imageData = decodeBase64(imageText.replaceAll("\n", ""));
    if (mimeType === kImagePng && options.figFormat === "retina" && options.figDpi) {
      const png = new PngImage(imageData);
      if (png.dpiX === options.figDpi * 2 && png.dpiY === options.figDpi * 2) {
        width = Math.round(png.width / 2);
        height = Math.round(png.height / 2);
      }
    }
    Deno.writeFileSync(outputFile5, imageData);
  } else {
    Deno.writeTextFileSync(outputFile5, imageText);
  }
  const kFigOptions = [
    kCellFigAlign,
    kCellFigEnv,
    kCellFigAlt,
    kCellFigPos,
    kCellFigScap
  ];
  let image2 = `![${alt}](${imageFile})`;
  if (label || width || height || Object.keys(figureOptions).some((option) => kFigOptions.includes(option))) {
    image2 += "{";
    if (label) {
      image2 += `${label} `;
    }
    if (width) {
      image2 += `width=${width} `;
    }
    if (height) {
      image2 += `height=${height} `;
    }
    kFigOptions.forEach(
      (attrib) => {
        const value = figureOptions[attrib];
        if (value) {
          image2 += `${attrib}='${value.replaceAll("'", "\\'")}' `;
        }
      }
    );
    image2 = image2.trimRight() + "}";
  }
  if (figureOptions[kCellFigLink]) {
    image2 = `[${image2}](${figureOptions[kCellFigLink]})`;
  }
  return mdMarkdownOutput([image2]);
}
function mdMarkdownOutput(md) {
  return md.join("") + "\n";
}
function mdLatexOutput(latex) {
  return mdFormatOutput("tex", latex);
}
function mdHtmlOutput(html) {
  return mdFormatOutput("html", html);
}
function mdJsonOutput(mimeType, json3, options) {
  if (options.toIpynb) {
    return mdCodeOutput([JSON.stringify(json3)], "json");
  } else {
    return mdScriptOutput(mimeType, [JSON.stringify(json3)]);
  }
}
function mdScriptOutput(mimeType, script) {
  const scriptTag = [
    `<script type="${mimeType}">
`,
    ...script,
    "\n<\/script>"
  ];
  return mdHtmlOutput(scriptTag);
}
function mdCodeOutput(code5, clz) {
  const ticks = ticksForCode(code5);
  const open = ticks + (clz ? `{.${clz}}` : "");
  return mdEnclosedOutput(open, code5, ticks);
}
function mdEnclosedOutput(begin, text, end) {
  const output = text.join("");
  const md = [
    begin + "\n",
    output + (output.endsWith("\n") ? "" : "\n"),
    end + "\n"
  ];
  return md.join("");
}
async function mdWarningOutput(msg5, options) {
  return await mdOutputStream({
    output_type: "stream",
    name: "stderr",
    text: [msg5]
  }, options);
}
function isWarningOutput(output) {
  if (output.output_type === "stream") {
    const stream = output;
    return stream.name === "stderr";
  } else {
    return false;
  }
}
function outputTypeCssClass(output_type) {
  if (["display_data", "execute_result"].includes(output_type)) {
    output_type = "display";
  }
  return `cell-output-${output_type}`;
}
function executeResultIncludes(tempDir2, widgetDependencies) {
  if (widgetDependencies) {
    const includes = {};
    const includeFiles = includesForJupyterWidgetDependencies(
      [widgetDependencies],
      tempDir2
    );
    if (includeFiles.inHeader) {
      includes[kIncludeInHeader] = [includeFiles.inHeader];
    }
    if (includeFiles.afterBody) {
      includes[kIncludeAfterBody] = [includeFiles.afterBody];
    }
    return includes;
  } else {
    return void 0;
  }
}
function executeResultEngineDependencies(widgetDependencies) {
  if (widgetDependencies) {
    return [widgetDependencies];
  } else {
    return void 0;
  }
}
var kQuartoMimeType, kQuartoOutputOrder, kQuartoOutputDisplay, kJupyterNotebookExtensions, kJupyterCellInternalOptionKeys, kJupyterCellOptionKeys, kJupyterCellStandardMetadataKeys, kJupyterCellThirdPartyMetadataKeys, countTicks, ticksForCode, kHideCell, kHideCode, kHideOutput, kHideWarnings, kShowCode, kShowOutput, kShowWarnings, kRemoveCell, tagMapping, kLangCommentChars2;
var init_jupyter = __esm({
  "core/jupyter/jupyter.ts"() {
    init_fs();
    init_path();
    init_colors2();
    init_base64();
    init_yaml();
    init_partition_cell_options();
    init_lodash();
    init_uuid();
    init_mime();
    init_png();
    init_tags();
    init_labels();
    init_display_data();
    init_widgets();
    init_preserve();
    init_pandoc_id();
    init_constants6();
    init_kernels();
    init_render();
    init_text();
    init_yaml();
    init_pandoc_partition();
    init_path2();
    init_ansi_colors();
    init_types4();
    init_config2();
    init_base64();
    init_format5();
    init_jupyter_fixups();
    init_jupyter_inline();
    init_jupyter_shared();
    init_log();
    kQuartoMimeType = "quarto_mimetype";
    kQuartoOutputOrder = "quarto_order";
    kQuartoOutputDisplay = "quarto_display";
    kJupyterNotebookExtensions = [
      ".ipynb"
    ];
    kJupyterCellInternalOptionKeys = [
      kEval,
      kEcho,
      kWarning,
      kError,
      kOutput,
      kInclude,
      kCellLabel,
      kCellClasses,
      kCellPanel,
      kCellColumn,
      kCellFigCap,
      kCellFigSubCap,
      kCellFigScap,
      kFigCapLoc,
      kTblCapLoc,
      kCapLoc,
      kCellFigColumn,
      kCellTblColumn,
      kCellFigLink,
      kCellFigAlign,
      kCellFigAlt,
      kCellFigEnv,
      kCellFigPos,
      kCellLstLabel,
      kCellLstCap,
      kCellOutWidth,
      kCellOutHeight,
      kCellMdIndent,
      kCodeFold,
      kCodeLineNumbers,
      kCodeSummary,
      kCodeOverflow,
      kHtmlTableProcessing
    ];
    kJupyterCellOptionKeys = kJupyterCellInternalOptionKeys.concat([
      kLayoutAlign,
      kLayoutVAlign,
      kLayoutNcol,
      kLayoutNrow,
      kLayout,
      kTblCap,
      kTblColwidths
    ]);
    kJupyterCellStandardMetadataKeys = [
      kCellCollapsed,
      kCellAutoscroll,
      kCellDeletable,
      kCellFormat,
      kCellName
    ];
    kJupyterCellThirdPartyMetadataKeys = [
      // colab
      kCellId,
      kCellColab,
      kCellColabType,
      kCellColbOutputId,
      // jupytext
      kCellLinesToNext,
      // nbdev
      kCellLanguage
    ];
    countTicks = (code5) => {
      const countLeadingTicks = (s5) => {
        const m4 = s5.match(/^\s*`+/);
        if (m4) {
          return m4[0].length;
        } else {
          return 0;
        }
      };
      return Math.max(0, ...code5.map((s5) => countLeadingTicks(s5)));
    };
    ticksForCode = (code5) => {
      const n5 = Math.max(3, countTicks(code5) + 1);
      return "`".repeat(n5);
    };
    kHideCell = "hide-cell";
    kHideCode = "hide-code";
    kHideOutput = "hide-output";
    kHideWarnings = "hide-warnings";
    kShowCode = "show-code";
    kShowOutput = "show-output";
    kShowWarnings = "show-warnings";
    kRemoveCell = "remove-cell";
    tagMapping = {
      [kHideCell]: {
        include: false
      },
      [kHideCode]: {
        echo: false
      },
      [kHideOutput]: {
        output: false
      },
      [kHideWarnings]: {
        warning: false
      },
      [kShowCode]: {
        echo: true
      },
      [kShowOutput]: {
        output: true
      },
      [kShowWarnings]: {
        warning: true
      },
      [kRemoveCell]: {
        include: false
      }
    };
    kLangCommentChars2 = {
      r: "#",
      python: "#",
      julia: "#",
      scala: "//",
      matlab: "%",
      csharp: "//",
      fsharp: "//",
      c: ["/*", "*/"],
      css: ["/*", "*/"],
      sas: ["*", ";"],
      powershell: "#",
      bash: "#",
      sql: "--",
      mysql: "--",
      psql: "--",
      lua: "--",
      cpp: "//",
      cc: "//",
      stan: "#",
      octave: "#",
      fortran: "!",
      fortran95: "!",
      awk: "#",
      gawk: "#",
      stata: "*",
      java: "//",
      groovy: "//",
      sed: "#",
      perl: "#",
      ruby: "#",
      tikz: "%",
      js: "//",
      d3: "//",
      node: "//",
      sass: "//",
      coffee: "#",
      go: "//",
      asy: "//",
      haskell: "--",
      dot: "//",
      mermaid: "%%",
      apl: "\u235D",
      ocaml: ["(*", "*)"],
      q: "/",
      rust: "//"
    };
  }
});

// core/jupyter/percent.ts
function isJupyterPercentScript(file, extensions2) {
  const ext = extname4(file).toLowerCase();
  const availableExtensions = extensions2 ?? kJupyterPercentScriptExtensions;
  if (availableExtensions.includes(ext)) {
    const text = Deno.readTextFileSync(file);
    const cms = kLangCommentChars[kLanguageExtensions[ext]];
    const pat = new RegExp(`^\\s*${cms}\\s*%%+\\s+\\[(markdown|raw)\\]`, "m");
    return !!text.match(pat);
  } else {
    return false;
  }
}
function markdownFromJupyterPercentScript(file) {
  const ext = extname4(file).toLowerCase();
  const language = kLanguageExtensions[ext];
  const cms = kLangCommentChars[language];
  if (!language) {
    throw new Error(`Could not determine language from file extension ${ext}`);
  }
  const cells = [];
  const activeCell = () => cells[cells.length - 1];
  for (const line of lines(Deno.readTextFileSync(file).trim())) {
    const header = percentCellHeader(line, language);
    if (header) {
      cells.push({ header, lines: [] });
    } else {
      activeCell()?.lines.push(line);
    }
  }
  const isTripleQuote = (line) => !!line.match(/^"{3,}\s*$/);
  const asCell = (lines2) => lines2.join("\n") + "\n\n";
  const stripPrefix = (line) => line.replace(new RegExp(`^${cms}\\s?`), "");
  const cellContent = (cellLines) => {
    if (cellLines.length > 2 && isTripleQuote(cellLines[0]) && isTripleQuote(cellLines[cellLines.length - 1])) {
      return asCell(cellLines.slice(1, cellLines.length - 1));
    } else {
      return asCell(cellLines.map(stripPrefix));
    }
  };
  return cells.reduce((markdown, cell) => {
    const cellLines = trimEmptyLines(cell.lines);
    if (cell.header.type === "code") {
      if (cell.header.metadata) {
        const yamlText = asYamlText(cell.header.metadata);
        cellLines.unshift(...lines(yamlText).map((line) => `${cms}| ${line}`));
      }
      markdown += asCell(["```{" + language + "}", ...cellLines, "```"]);
    } else if (cell.header.type === "markdown") {
      markdown += cellContent(cellLines);
    } else if (cell.header.type == "raw") {
      let rawContent = cellContent(cellLines);
      const format14 = cell.header?.metadata?.["format"];
      const mimeType = cell.header.metadata?.[kCellRawMimeType];
      if (typeof mimeType === "string") {
        const rawBlock = mdRawOutput(mimeType, lines(rawContent));
        rawContent = rawBlock || rawContent;
      } else if (typeof format14 === "string") {
        rawContent = mdFormatOutput(format14, lines(rawContent));
      }
      markdown += rawContent;
    }
    return markdown;
  }, "");
}
function percentCellHeader(line, language) {
  const cms = kLangCommentChars[language];
  const match = line.match(
    new RegExp(`^\\s*${cms}\\s*%%+\\s*(?:\\[(markdown|raw)\\])?\\s*(.*)?$`)
  );
  if (match) {
    const type4 = match[1] || "code";
    const attribs = match[2] || "";
    if (["code", "raw", "markdown"].includes(type4)) {
      return {
        type: type4,
        metadata: parsePercentAttribs(attribs)
      };
    } else {
      throw new Error(`Invalid cell type: ${type4}`);
    }
  }
}
function parsePercentAttribs(attribs) {
  const match = attribs.match(/[\w\-]+=.*$/);
  if (match) {
    const keyValue = pandocAttrKeyvalueFromText(match[0], " ");
    const metadata = {};
    keyValue.forEach((value) => {
      metadata[value[0]] = value[1];
    });
    return metadata;
  }
}
var kJupyterPercentScriptExtensions, kLanguageExtensions;
var init_percent = __esm({
  "core/jupyter/percent.ts"() {
    init_path();
    init_pandoc_attr();
    init_constants6();
    init_jupyter();
    init_text();
    init_jupyter_fixups();
    init_partition_cell_options();
    kJupyterPercentScriptExtensions = [
      ".py",
      ".jl",
      ".r",
      ".q"
    ];
    kLanguageExtensions = {
      ".jl": "julia",
      ".r": "r",
      ".py": "python",
      ".q": "q"
    };
  }
});

// execute/jupyter/jupyter.ts
async function ensureYamlKernelspec(target, kernelspec) {
  const markdown = target.markdown.value;
  const yamlJupyter = quarto2.markdownRegex.extractYaml(markdown)?.jupyter;
  if (yamlJupyter && typeof yamlJupyter !== "boolean") {
    const [yamlKernelspec, _3] = await quarto2.jupyter.kernelspecFromMarkdown(
      markdown
    );
    if (yamlKernelspec.name !== kernelspec?.name) {
      const nb = quarto2.jupyter.fromJSON(Deno.readTextFileSync(target.source));
      nb.metadata.kernelspec = yamlKernelspec;
      Deno.writeTextFileSync(target.source, JSON.stringify(nb, null, 2));
      return yamlKernelspec;
    }
  }
}
function fixupShinyliveCodeCells(nb) {
  if (nb.metadata.kernelspec.language === "python") {
    nb.cells.forEach((cell) => {
      if (cell.cell_type === "code" && cell.metadata.tags?.includes("shinylive")) {
        cell.cell_type = "markdown";
        cell.metadata = {};
        cell.source = [
          "```{shinylive-python}\n",
          ...cell.source,
          "\n```"
        ];
        delete cell.execution_count;
        delete cell.outputs;
      }
    });
  }
}
async function createNotebookforTarget(target, project) {
  const nb = await quarto2.jupyter.quartoMdToJupyter(
    target.markdown.value,
    true,
    project
  );
  Deno.writeTextFileSync(target.input, JSON.stringify(nb, null, 2));
  return nb;
}
async function disableDaemonForNotebook(target) {
  const kShellMagics = [
    "cd",
    "cat",
    "cp",
    "env",
    "ls",
    "man",
    "mkdir",
    "more",
    "mv",
    "pwd",
    "rm",
    "rmdir"
  ];
  const nb = await quarto2.markdownRegex.breakQuartoMd(target.markdown);
  for (const cell of nb.cells) {
    if (isObject(cell.cell_type)) {
      const language = cell.cell_type.language;
      if (language === "python") {
        if (cell.source.value.startsWith("!")) {
          return true;
        }
        return kShellMagics.some(
          (cmd) => cell.source.value.includes("%" + cmd + " ") || cell.source.value.includes("!" + cmd + " ") || cell.source.value.startsWith(cmd + " ")
        );
      }
    }
  }
  return false;
}
function cleanupNotebook(target, format14, project) {
  const data3 = target.data;
  const cached = project.fileInformationCache.get(target.source);
  if (cached && data3.transient && format14.execute[kKeepIpynb]) {
    if (cached.target && cached.target.data) {
      cached.target.data.transient = false;
    }
  }
}
var quarto2, jupyterEngineDiscovery;
var init_jupyter2 = __esm({
  "execute/jupyter/jupyter.ts"() {
    init_path();
    init_mod6();
    init_fs();
    init_log();
    init_lodash();
    init_constants6();
    init_jupyter_kernel();
    init_types3();
    init_percent();
    jupyterEngineDiscovery = {
      init: (quartoAPI) => {
        quarto2 = quartoAPI;
      },
      name: kJupyterEngine,
      defaultExt: ".qmd",
      defaultYaml: (kernel) => [
        `jupyter: ${kernel || "python3"}`
      ],
      defaultContent: (kernel) => {
        kernel = kernel || "python3";
        const lang = kernel.startsWith("python") ? "python" : kernel.startsWith("julia") ? "julia" : void 0;
        if (lang) {
          return [
            "```{" + lang + "}",
            "1 + 1",
            "```"
          ];
        } else {
          return [];
        }
      },
      validExtensions: () => [
        ...quarto2.jupyter.notebookExtensions,
        ...kJupyterPercentScriptExtensions,
        ...kQmdExtensions
      ],
      claimsFile: (file, ext) => {
        return quarto2.jupyter.notebookExtensions.includes(ext.toLowerCase()) || quarto2.jupyter.isPercentScript(file);
      },
      claimsLanguage: (language) => {
        return language.toLowerCase() === "julia";
      },
      canFreeze: true,
      generatesFigures: true,
      ignoreDirs: () => {
        return ["venv", "env"];
      },
      checkInstallation: async (conf) => {
        const kIndent2 = "      ";
        const checkCompleteMessage2 = (message) => {
          if (!conf.jsonResult) {
            quarto2.console.completeMessage(message);
          }
        };
        const checkInfoMsg2 = (message) => {
          if (!conf.jsonResult) {
            info(message);
          }
        };
        const checkJupyterRender = async () => {
          const json3 = {};
          if (conf.jsonResult) {
            conf.jsonResult.render.jupyter = json3;
          }
          const result2 = await quarto2.system.checkRender({
            content: `
---
title: "Title"
---

## Header

\`\`\`{python}
1 + 1
\`\`\`
`,
            language: "python",
            services: conf.services
          });
          if (result2.error) {
            if (!conf.jsonResult) {
              throw result2.error;
            } else {
              json3["error"] = result2.error;
            }
          } else {
            json3["ok"] = true;
          }
        };
        const kMessage = "Checking Python 3 installation....";
        const jupyterJson = {};
        if (conf.jsonResult) {
          conf.jsonResult.tools.jupyter = jupyterJson;
        }
        let caps;
        if (conf.jsonResult) {
          caps = await quarto2.jupyter.capabilities();
        } else {
          await quarto2.console.withSpinner({
            message: kMessage,
            doneMessage: false
          }, async () => {
            caps = await quarto2.jupyter.capabilities();
          });
        }
        if (caps) {
          checkCompleteMessage2(kMessage + "OK");
          if (conf.jsonResult) {
            jupyterJson["capabilities"] = await quarto2.jupyter.capabilitiesJson(
              caps
            );
          } else {
            checkInfoMsg2(await quarto2.jupyter.capabilitiesMessage(caps, kIndent2));
          }
          checkInfoMsg2("");
          if (caps.jupyter_core) {
            if (await quarto2.jupyter.kernelspecForLanguage("python")) {
              const kJupyterMessage = "Checking Jupyter engine render....";
              if (conf.jsonResult) {
                await checkJupyterRender();
              } else {
                await quarto2.console.withSpinner({
                  message: kJupyterMessage,
                  doneMessage: kJupyterMessage + "OK\n"
                }, async () => {
                  await checkJupyterRender();
                });
              }
            } else {
              jupyterJson["kernels"] = [];
              checkInfoMsg2(
                kIndent2 + "NOTE: No Jupyter kernel for Python found"
              );
              checkInfoMsg2("");
            }
          } else {
            const installMessage = quarto2.jupyter.installationMessage(
              caps,
              kIndent2
            );
            checkInfoMsg2(installMessage);
            checkInfoMsg2("");
            jupyterJson["installed"] = false;
            jupyterJson["how-to-install"] = installMessage;
            const envMessage = quarto2.jupyter.unactivatedEnvMessage(caps, kIndent2);
            if (envMessage) {
              checkInfoMsg2(envMessage);
              checkInfoMsg2("");
              jupyterJson["env"] = {
                "warning": envMessage
              };
            }
          }
        } else {
          checkCompleteMessage2(kMessage + "(None)\n");
          const msg5 = quarto2.jupyter.pythonInstallationMessage(kIndent2);
          jupyterJson["installed"] = false;
          jupyterJson["how-to-install-python"] = msg5;
          checkInfoMsg2(msg5);
          checkInfoMsg2("");
        }
      },
      // Launch method will return an instance with context
      launch: (context) => {
        return {
          name: jupyterEngineDiscovery.name,
          canFreeze: jupyterEngineDiscovery.canFreeze,
          markdownForFile: (file) => {
            if (quarto2.jupyter.isJupyterNotebook(file)) {
              const nbJSON = Deno.readTextFileSync(file);
              const nb = quarto2.jupyter.fromJSON(nbJSON);
              return Promise.resolve(
                quarto2.mappedString.fromString(
                  quarto2.jupyter.markdownFromNotebookJSON(nb)
                )
              );
            } else if (quarto2.jupyter.isPercentScript(file)) {
              return Promise.resolve(
                quarto2.mappedString.fromString(
                  quarto2.jupyter.percentScriptToMarkdown(file)
                )
              );
            } else {
              return Promise.resolve(quarto2.mappedString.fromFile(file));
            }
          },
          target: async (file, quiet, markdown) => {
            if (!markdown) {
              markdown = await context.resolveFullMarkdownForFile(void 0, file);
            }
            let nb;
            if (quarto2.jupyter.isJupyterNotebook(file)) {
              const nbJSON = Deno.readTextFileSync(file);
              const nbRaw = JSON.parse(nbJSON);
              if (nbRaw.metadata.kernelspec && nbRaw.metadata.kernelspec.language === void 0 && nbRaw.metadata.language_info?.name) {
                nbRaw.metadata.kernelspec.language = nbRaw.metadata.language_info.name;
              }
              nb = nbRaw;
            }
            const isPercentScript = quarto2.jupyter.isPercentScript(file);
            const metadata = quarto2.markdownRegex.extractYaml(markdown.value);
            if (quarto2.path.isQmdFile(file) || isPercentScript) {
              const [fileDir, fileStem] = quarto2.path.dirAndStem(file);
              let counter2 = void 0;
              let notebook = join4(
                fileDir,
                `${fileStem}.quarto_ipynb${counter2 ? "_" + String(counter2) : ""}`
              );
              while (existsSync2(notebook)) {
                if (!counter2) {
                  counter2 = 1;
                } else {
                  ++counter2;
                }
                notebook = join4(
                  fileDir,
                  `${fileStem}.quarto_ipynb${counter2 ? "_" + String(counter2) : ""}`
                );
              }
              const target = {
                source: file,
                input: notebook,
                markdown,
                metadata,
                data: { transient: true, kernelspec: {} }
              };
              nb = await createNotebookforTarget(target);
              target.data.kernelspec = nb.metadata.kernelspec;
              return target;
            } else if (quarto2.jupyter.isJupyterNotebook(file)) {
              return {
                source: file,
                input: file,
                markdown,
                metadata,
                data: { transient: false, kernelspec: nb?.metadata.kernelspec }
              };
            } else {
              return void 0;
            }
          },
          partitionedMarkdown: async (file, format14) => {
            if (quarto2.jupyter.isJupyterNotebook(file)) {
              return quarto2.markdownRegex.partition(
                await quarto2.jupyter.markdownFromNotebookFile(file, format14)
              );
            } else if (quarto2.jupyter.isPercentScript(file)) {
              return quarto2.markdownRegex.partition(
                quarto2.jupyter.percentScriptToMarkdown(file)
              );
            } else {
              return quarto2.markdownRegex.partition(Deno.readTextFileSync(file));
            }
          },
          filterFormat: (source2, options, format14) => {
            if (quarto2.format.isServerShinyPython(format14, kJupyterEngine) && format14.render[kKeepHidden] !== true) {
              format14 = {
                ...format14,
                render: {
                  ...format14.render
                },
                metadata: {
                  ...format14.metadata
                }
              };
              format14.render[kKeepHidden] = true;
              format14.metadata[kRemoveHidden] = "all";
            }
            if (quarto2.jupyter.isJupyterNotebook(source2)) {
              let executeEnabled;
              if (options.devServerReload) {
                executeEnabled = false;
              } else if (typeof format14.execute[kExecuteIpynb] === "boolean") {
                executeEnabled = format14.execute[kExecuteIpynb];
              } else if (typeof format14.execute[kExecuteEnabled] == "boolean") {
                executeEnabled = format14.execute[kExecuteEnabled];
              } else {
                executeEnabled = false;
              }
              if (executeEnabled !== void 0) {
                return {
                  ...format14,
                  execute: {
                    ...format14.execute,
                    [kExecuteEnabled]: executeEnabled
                  }
                };
              } else {
                return format14;
              }
            } else {
              return format14;
            }
          },
          execute: async (options) => {
            if ((quarto2.path.isQmdFile(options.target.source) || quarto2.jupyter.isPercentScript(options.target.source)) && !existsSync2(options.target.input)) {
              await createNotebookforTarget(options.target);
            }
            let kernelspec = options.target.data.kernelspec;
            const execute = options.format.execute[kExecuteEnabled] !== false;
            if (execute) {
              if (quarto2.jupyter.isJupyterNotebook(options.target.source)) {
                kernelspec = await ensureYamlKernelspec(options.target, kernelspec) || kernelspec;
              }
              const execOptions = {
                ...options,
                target: {
                  ...options.target,
                  input: quarto2.path.absolute(options.target.input)
                }
              };
              let executeDaemon = options.format.execute[kExecuteDaemon];
              if (executeDaemon === null || executeDaemon === void 0) {
                if (await disableDaemonForNotebook(options.target)) {
                  executeDaemon = false;
                } else {
                  executeDaemon = quarto2.system.isInteractiveSession() && !quarto2.system.runningInCI();
                }
              }
              const jupyterExecOptions = {
                kernelspec,
                python_cmd: await quarto2.jupyter.pythonExec(kernelspec),
                supervisor_pid: options.previewServer ? Deno.pid : void 0,
                ...execOptions
              };
              if (executeDaemon === false || executeDaemon === 0) {
                await executeKernelOneshot(jupyterExecOptions);
              } else {
                await executeKernelKeepalive(jupyterExecOptions);
              }
            }
            const nbContents = await quarto2.jupyter.notebookFiltered(
              options.target.input,
              quarto2.jupyter.isJupyterNotebook(options.target.source) ? options.format.execute[kIpynbFilters] || [] : []
            );
            const nb = quarto2.jupyter.fromJSON(nbContents);
            fixupShinyliveCodeCells(nb);
            const assets = quarto2.jupyter.assets(
              options.target.input,
              options.format.pandoc.to
            );
            const preserveCellMetadata = options.format.render[kNotebookPreserveCells] === true || quarto2.format.isHtmlDashboardOutput(
              options.format.identifier[kBaseFormat]
            ) && !quarto2.path.isQmdFile(options.target.source);
            const result2 = await quarto2.jupyter.toMarkdown(
              nb,
              {
                executeOptions: options,
                language: nb.metadata.kernelspec.language.toLowerCase(),
                assets,
                execute: options.format.execute,
                keepHidden: options.format.render[kKeepHidden],
                toHtml: quarto2.format.isHtmlCompatible(options.format),
                toLatex: quarto2.format.isLatexOutput(options.format.pandoc),
                toMarkdown: quarto2.format.isMarkdownOutput(options.format),
                toIpynb: quarto2.format.isIpynbOutput(options.format.pandoc),
                toPresentation: quarto2.format.isPresentationOutput(
                  options.format.pandoc
                ),
                figFormat: options.format.execute[kFigFormat],
                figDpi: options.format.execute[kFigDpi],
                figPos: options.format.render[kFigPos],
                preserveCellMetadata,
                preserveCodeCellYaml: options.format.render[kIpynbProduceSourceNotebook] === true
              }
            );
            let includes;
            let engineDependencies;
            if (options.dependencies) {
              includes = quarto2.jupyter.resultIncludes(
                options.tempDir,
                result2.dependencies
              );
            } else {
              const dependencies = quarto2.jupyter.resultEngineDependencies(
                result2.dependencies
              );
              if (dependencies) {
                engineDependencies = {
                  [kJupyterEngine]: dependencies
                };
              }
            }
            cleanupNotebook(options.target, options.format, context);
            const outputs = result2.cellOutputs.map((output) => output.markdown);
            if (result2.notebookOutputs) {
              if (result2.notebookOutputs.prefix) {
                outputs.unshift(result2.notebookOutputs.prefix);
              }
              if (result2.notebookOutputs.suffix) {
                outputs.push(result2.notebookOutputs.suffix);
              }
            }
            const markdown = outputs.join("");
            return {
              engine: kJupyterEngine,
              markdown,
              supporting: [join4(assets.base_dir, assets.supporting_dir)],
              filters: [],
              pandoc: result2.pandoc,
              includes,
              engineDependencies,
              preserve: result2.htmlPreserve,
              postProcess: result2.htmlPreserve && Object.keys(result2.htmlPreserve).length > 0
            };
          },
          executeTargetSkipped: (target, format14) => {
            cleanupNotebook(target, format14, context);
          },
          dependencies: (options) => {
            const includes = {};
            if (options.dependencies) {
              const includeFiles = quarto2.jupyter.widgetDependencyIncludes(
                options.dependencies,
                options.tempDir
              );
              if (includeFiles.inHeader) {
                includes[kIncludeInHeader] = [includeFiles.inHeader];
              }
              if (includeFiles.afterBody) {
                includes[kIncludeAfterBody] = [includeFiles.afterBody];
              }
            }
            return Promise.resolve({
              includes
            });
          },
          postprocess: (options) => {
            quarto2.text.postProcessRestorePreservedHtml(options);
            return Promise.resolve();
          },
          canKeepSource: (target) => {
            return !quarto2.jupyter.isJupyterNotebook(target.source);
          },
          intermediateFiles: (input) => {
            const files = [];
            const [fileDir, fileStem] = quarto2.path.dirAndStem(input);
            if (!quarto2.jupyter.isJupyterNotebook(input)) {
              files.push(join4(fileDir, fileStem + ".ipynb"));
            } else if ([...kQmdExtensions, ...kJupyterPercentScriptExtensions].some(
              (ext) => {
                return existsSync2(join4(fileDir, fileStem + ext));
              }
            )) {
              files.push(input);
            }
            return files;
          },
          run: async (options) => {
            const asSemVer = (version4) => {
              const v4 = version4.split(".");
              if (v4.length > 3) {
                return `${v4[0]}.${v4[1]}.${v4[2]}`;
              } else {
                return version4;
              }
            };
            const kShinyVersion = ">=0.6";
            let shinyError;
            const caps = await quarto2.jupyter.capabilities();
            if (!caps?.shiny) {
              shinyError = "The shiny package is required for documents with server: shiny";
            } else if (!satisfies(asSemVer(caps.shiny), asSemVer(kShinyVersion))) {
              shinyError = `The shiny package version must be ${kShinyVersion} for documents with server: shiny`;
            }
            if (shinyError) {
              shinyError += "\n\nInstall the latest version of shiny with pip install --upgrade shiny\n";
              error(shinyError);
              throw new Error();
            }
            const [_dir] = quarto2.path.dirAndStem(options.input);
            const appFile = "app.py";
            const cmd = [
              ...await quarto2.jupyter.pythonExec(),
              "-m",
              "shiny",
              "run",
              appFile,
              "--host",
              options.host,
              "--port",
              String(options.port)
            ];
            if (options.reload) {
              cmd.push("--reload");
              cmd.push(`--reload-includes=*.py`);
            }
            const readyPattern = /(http:\/\/(?:localhost|127\.0\.0\.1)\:\d+\/?[^\s]*)/;
            const server = quarto2.system.runExternalPreviewServer({
              cmd,
              readyPattern,
              cwd: dirname4(options.input)
            });
            await server.start();
            quarto2.system.onCleanup(async () => {
              await server.stop();
            });
            if (options.onReady) {
              options.onReady();
            }
            return server.serve();
          },
          postRender: async (file) => {
            if (quarto2.format.isServerShiny(file.format)) {
              const [dir] = quarto2.path.dirAndStem(file.input);
              const filesDir = join4(dir, quarto2.path.inputFilesDir(file.input));
              const extraResources = file.resourceFiles.filter((resource) => !resource.startsWith(filesDir)).map((resource) => relative4(dir, resource));
              const appScriptDir = context ? context.getOutputDirectory() : dir;
              const appScript = join4(appScriptDir, `app.py`);
              if (existsSync2(appScript)) {
                const staticAssets = [
                  quarto2.path.inputFilesDir(file.input),
                  ...extraResources
                ];
                const parentDirAssets = staticAssets.filter(
                  (asset) => asset.startsWith("..")
                );
                if (parentDirAssets.length > 0) {
                  error(
                    `References to files in parent directories found in document with server: shiny (${basename4(file.input)}): ${JSON.stringify(parentDirAssets)}. All resource files referenced by Shiny documents must exist in the same directory as the source file.`
                  );
                  throw new Error();
                }
                let appContents = Deno.readTextFileSync(appScript);
                appContents = appContents.replace(
                  "##STATIC_ASSETS_PLACEHOLDER##",
                  JSON.stringify(staticAssets)
                );
                Deno.writeTextFileSync(appScript, appContents);
              }
            }
          }
        };
      }
    };
  }
});

// execute/markdown.ts
var kMdExtensions, quarto3, markdownEngineDiscovery;
var init_markdown = __esm({
  "execute/markdown.ts"() {
    init_path();
    init_types3();
    kMdExtensions = [".md", ".markdown"];
    markdownEngineDiscovery = {
      init: (quartoAPI) => {
        quarto3 = quartoAPI;
      },
      name: kMarkdownEngine,
      defaultExt: ".qmd",
      defaultYaml: () => [],
      defaultContent: () => [],
      validExtensions: () => kQmdExtensions.concat(kMdExtensions),
      claimsFile: (_file, ext) => {
        return kMdExtensions.includes(ext.toLowerCase());
      },
      claimsLanguage: (_language) => {
        return false;
      },
      canFreeze: false,
      generatesFigures: false,
      /**
       * Launch a dynamic execution engine with project context
       */
      launch: (context) => {
        return {
          name: markdownEngineDiscovery.name,
          canFreeze: markdownEngineDiscovery.canFreeze,
          markdownForFile(file) {
            return Promise.resolve(quarto3.mappedString.fromFile(file));
          },
          target: (file, _quiet, markdown) => {
            const md = markdown ?? quarto3.mappedString.fromFile(file);
            const target = {
              source: file,
              input: file,
              markdown: md,
              metadata: quarto3.markdownRegex.extractYaml(md.value)
            };
            return Promise.resolve(target);
          },
          partitionedMarkdown: (file) => {
            return Promise.resolve(
              quarto3.markdownRegex.partition(Deno.readTextFileSync(file))
            );
          },
          execute: (options) => {
            const markdown = options.target.markdown.value;
            if (extname4(options.target.input).toLowerCase() === ".md") {
              const languages2 = quarto3.markdownRegex.getLanguages(markdown);
              if (languages2.size > 0) {
                throw new Error(
                  "You must use the .qmd extension for documents with executable code."
                );
              }
            }
            return Promise.resolve({
              engine: kMarkdownEngine,
              markdown,
              supporting: [],
              filters: []
            });
          },
          dependencies: (_options) => {
            return Promise.resolve({
              includes: {}
            });
          },
          postprocess: (_options) => Promise.resolve()
        };
      }
    };
  }
});

// core/lib/parse-shortcode.ts
function isBlockShortcode(content, lenient) {
  const m4 = content.match(/^\s*{{< (?!\/\*)(.+?)(?<!\*\/) >}}\s*$/);
  if (m4) {
    try {
      return parseShortcode(m4[1]);
    } catch (_e) {
      if (lenient) {
        return false;
      }
      throw _e;
    }
  }
}
function parseShortcodeCapture(capture) {
  const nameMatch = capture.match(/^\/?[a-zA-Z0-9_]+/);
  if (!nameMatch) {
    return;
  }
  const params = [];
  const namedParams = {};
  const rawParams = [];
  const name2 = nameMatch[0];
  let paramStr = capture.slice(name2.length).trim();
  while (paramStr.length) {
    let paramMatch;
    paramMatch = paramStr.match(/^[a-zA-Z0-9_-]+="[^"]*"/);
    if (!paramMatch) {
      paramMatch = paramStr.match(/^[a-zA-Z0-9_-]+='[^']*'/);
    }
    if (!paramMatch) {
      paramMatch = paramStr.match(/^[a-zA-Z0-9_-]+=[^"'\s]+/);
    }
    if (paramMatch) {
      const [name3, value] = paramMatch[0].split("=");
      namedParams[name3] = value;
      rawParams.push({
        name: name3,
        value
      });
      paramStr = paramStr.slice(paramMatch[0].length).trim();
      continue;
    }
    paramMatch = paramStr.match(/^[^"'\s]+/);
    if (paramMatch) {
      params.push(paramMatch[0]);
      rawParams.push({
        value: paramMatch[0]
      });
      paramStr = paramStr.slice(paramMatch[0].length).trim();
      continue;
    }
    paramMatch = paramStr.match(/^"[^"]*"/) || paramStr.match(/^'[^']*'/);
    if (paramMatch) {
      params.push(paramMatch[0].slice(1, -1));
      rawParams.push({
        value: paramMatch[0].slice(1, -1)
      });
      paramStr = paramStr.slice(paramMatch[0].length).trim();
      continue;
    }
    throw new InvalidShortcodeError("invalid shortcode: " + capture);
  }
  return { name: name2, params, namedParams, rawParams };
}
function parseShortcode(shortCodeCapture) {
  const result2 = parseShortcodeCapture(shortCodeCapture);
  if (!result2) {
    throw new InvalidShortcodeError("invalid shortcode: " + shortCodeCapture);
  }
  return result2;
}
var InvalidShortcodeError;
var init_parse_shortcode = __esm({
  "core/lib/parse-shortcode.ts"() {
    init_text();
    InvalidShortcodeError = class extends Error {
      constructor(msg5) {
        super(msg5);
      }
    };
  }
});

// core/lib/break-quarto-md.ts
async function breakQuartoMd(src2, validate2 = false, lenient = false, startCodeCellRegex) {
  if (typeof src2 === "string") {
    src2 = asMappedString(src2);
  }
  const fileName = src2.fileName;
  const nb = {
    cells: []
  };
  const yamlRegEx = /^---\s*$/;
  const startCodeCellRegEx = startCodeCellRegex || new RegExp(
    "^\\s*(```+)\\s*\\{([=A-Za-z][=A-Za-z0-9._]*)( *[ ,].*)?\\}\\s*$"
  );
  const startCodeRegEx = /^```/;
  const endCodeRegEx = /^\s*(```+)\s*$/;
  let language = "";
  let directiveParams = void 0;
  let cellStartLine = 0;
  let codeStartRange;
  let codeEndRange;
  const lineBuffer = [];
  const flushLineBuffer = async (cell_type, index2) => {
    if (lineBuffer.length || cell_type === "code") {
      const mappedChunks = [];
      for (const line of lineBuffer) {
        mappedChunks.push(line.range);
      }
      const source2 = mappedString(
        src2,
        mappedChunks,
        fileName
      );
      const makeCellType = () => {
        if (cell_type === "code") {
          return { language };
        } else if (cell_type === "directive") {
          return {
            language: "_directive",
            name: directiveParams.name,
            shortcode: directiveParams
          };
        } else {
          return cell_type;
        }
      };
      const cell = {
        // deno-lint-ignore camelcase
        cell_type: makeCellType(),
        source: source2,
        sourceOffset: 0,
        sourceStartLine: 0,
        sourceVerbatim: source2,
        cellStartLine
      };
      cellStartLine = index2 + 1;
      if (cell_type === "code") {
        const { yaml, sourceStartLine } = await partitionCellOptionsMapped(
          language,
          cell.source,
          validate2,
          "",
          lenient
        );
        const breaks = Array.from(lineOffsets(cell.source.value));
        let strUpToLastBreak = "";
        if (sourceStartLine > 0) {
          cell.sourceWithYaml = cell.source;
          cell.source = mappedSubstring(cell.source, breaks[sourceStartLine]);
          if (breaks.length > 1) {
            const lastBreak = breaks[Math.min(sourceStartLine - 1, breaks.length - 1)];
            strUpToLastBreak = cell.source.value.substring(0, lastBreak);
          } else {
            strUpToLastBreak = cell.source.value;
          }
        } else {
          cell.sourceWithYaml = cell.source;
        }
        const prefix = "```{" + language + "}\n";
        cell.sourceOffset = strUpToLastBreak.length + prefix.length;
        cell.sourceVerbatim = mappedString(src2, [
          codeStartRange.range,
          ...mappedChunks,
          codeEndRange.range
        ], fileName);
        cell.options = yaml;
        cell.sourceStartLine = sourceStartLine;
      } else if (cell_type === "directive") {
        cell.source = mappedString(src2, mappedChunks.slice(1, -1), fileName);
      }
      nb.cells.push(cell);
      lineBuffer.splice(0, lineBuffer.length);
    }
  };
  const tickCount = (s5) => Array.from(s5.split(" ")[0] || "").filter((c6) => c6 === "`").length;
  let inYaml = false, inCodeCell = false, inCode = 0;
  const inPlainText = () => !inCodeCell && !inCode && !inYaml;
  const isYamlDelimiter = (line, index2, skipHRs) => {
    if (!yamlRegEx.test(line)) {
      return false;
    }
    if (skipHRs && index2 > 0 && srcLines[index2 - 1].substring.trim() === "" && index2 < srcLines.length - 1 && srcLines[index2 + 1].substring.trim() === "") {
      return false;
    }
    return true;
  };
  const srcLines = rangedLines(src2.value, true);
  for (let i6 = 0; i6 < srcLines.length; ++i6) {
    const line = srcLines[i6];
    const directiveMatch = isBlockShortcode(line.substring, true);
    if (isYamlDelimiter(line.substring, i6, !inYaml) && !inCodeCell && !inCode) {
      if (inYaml) {
        lineBuffer.push(line);
        await flushLineBuffer("raw", i6);
        inYaml = false;
      } else {
        await flushLineBuffer("markdown", i6);
        lineBuffer.push(line);
        inYaml = true;
      }
    } else if (inPlainText() && directiveMatch) {
      await flushLineBuffer("markdown", i6);
      directiveParams = directiveMatch;
      lineBuffer.push(line);
      await flushLineBuffer("directive", i6);
    } else if (startCodeCellRegEx.test(line.substring) && inPlainText()) {
      const m4 = line.substring.match(startCodeCellRegEx);
      language = m4[2];
      await flushLineBuffer("markdown", i6);
      inCodeCell = true;
      inCode = m4[1].length;
      codeStartRange = line;
    } else if (endCodeRegEx.test(line.substring) && (inCode && line.substring.match(endCodeRegEx)[1].length === inCode)) {
      if (inCodeCell) {
        codeEndRange = line;
        inCodeCell = false;
        inCode = 0;
        await flushLineBuffer("code", i6);
      } else {
        inCode = 0;
        lineBuffer.push(line);
      }
    } else if (startCodeRegEx.test(line.substring) && inCode === 0) {
      inCode = tickCount(line.substring);
      lineBuffer.push(line);
    } else {
      lineBuffer.push(line);
    }
  }
  await flushLineBuffer("markdown", srcLines.length);
  return nb;
}
var init_break_quarto_md = __esm({
  "core/lib/break-quarto-md.ts"() {
    init_text();
    init_ranged_text();
    init_mapped_text();
    init_partition_cell_options();
    init_parse_shortcode();
  }
});

// config/types.ts
function isPandocFilter(filter3) {
  return filter3.path !== void 0;
}
function isFilterEntryPoint(filter3) {
  if (typeof filter3 === "string") {
    return false;
  }
  return filter3.at !== void 0;
}
var kDependencies, kSassBundles, kHtmlPostprocessors, kHtmlFinalizers, kBodyEnvelope, kTextHighlightingMode, kQuartoCssVariables, kMarkdownAfterBody;
var init_types5 = __esm({
  "config/types.ts"() {
    kDependencies = "dependencies";
    kSassBundles = "sass-bundles";
    kHtmlPostprocessors = "html-postprocessors";
    kHtmlFinalizers = "html-finalizers";
    kBodyEnvelope = "body-envelope";
    kTextHighlightingMode = "text-highlighting-mode";
    kQuartoCssVariables = "css-variables";
    kMarkdownAfterBody = "render-after-body";
  }
});

// core/pandoc/codegen.ts
function pandocRawStr(content) {
  return {
    ...basePandocNode,
    emit: (ls) => ls.push(content)
  };
}
function pandocHtmlBlock(elementName) {
  return function(opts) {
    let { id, classes, attrs, contents } = opts || {};
    if (classes === void 0) {
      classes = [];
    }
    if (attrs === void 0) {
      attrs = [];
    }
    contents = contents || [];
    function attrString() {
      const strs = [];
      if (id) {
        strs.push(`id="${id}"`);
      }
      if (classes && classes.length) {
        strs.push(`class="${classes.join(" ")}"`);
      }
      if (attrs) {
        strs.push(...attrs.map((attr) => `data-${attr}`));
      }
      return strs.join(" ");
    }
    return {
      ...basePandocNode,
      push: function(s5) {
        if (this !== s5) {
          contents.push(s5);
        }
      },
      unshift: function(s5) {
        if (this !== s5) {
          contents.unshift(s5);
        }
      },
      emit: function(ls) {
        ls.push(`
<${elementName} ${attrString()}>`);
        if (elementName !== "pre") {
          ls.push("\n");
        }
        for (const entry of contents) {
          entry.emit(ls);
        }
        if (elementName !== "pre") {
          ls.push("\n");
        }
        ls.push(`</${elementName}>
`);
      }
    };
  };
}
function pandocList(opts) {
  let { contents, skipFirstLineBreak } = opts || {};
  contents = contents || [];
  return {
    ...basePandocNode,
    push: function(s5) {
      if (this !== s5) {
        contents.push(s5);
      }
    },
    unshift: function(s5) {
      if (this !== s5) {
        contents.unshift(s5);
      }
    },
    emit: function(ls) {
      const lb = skipFirstLineBreak ? "" : "\n";
      ls.push(`${lb}
`);
      for (const entry of contents) {
        entry.emit(ls);
      }
      if (!asMappedString(ls[ls.length - 1] || "\n").value.endsWith("\n")) {
        ls.push(`
`);
      }
      ls.push(`
`);
    }
  };
}
function pandocBlock(delimiterCharacter) {
  return function(opts) {
    let { id, classes, attrs, language, skipFirstLineBreak, contents } = opts || {};
    if (classes === void 0) {
      classes = [];
    }
    if (attrs === void 0) {
      attrs = [];
    }
    contents = contents || [];
    function attrString() {
      const strs = [];
      if (language) {
        strs.push(language);
      }
      if (id) {
        strs.push(`#${id}`);
      }
      if (classes) {
        strs.push(...classes.map((c6) => `.${c6}`));
      }
      if (attrs) {
        strs.push(...attrs);
      }
      if (strs.length) {
        return `{${strs.join(" ")}}`;
      } else {
        return "{}";
      }
    }
    return {
      ...basePandocNode,
      push: function(s5) {
        if (this !== s5) {
          contents.push(s5);
        }
      },
      unshift: function(s5) {
        if (this !== s5) {
          contents.unshift(s5);
        }
      },
      emit: function(ls) {
        const innerLs = [];
        const lb = skipFirstLineBreak ? "" : "\n";
        for (const entry of contents) {
          entry.emit(innerLs);
        }
        if (!asMappedString(innerLs[innerLs.length - 1] || "\n").value.endsWith(
          "\n"
        )) {
          innerLs.push(`
`);
        }
        const longestStreak = Math.max(...innerLs.map((eitherS) => {
          const s5 = asMappedString(eitherS).value;
          return s5.match(new RegExp(`${delimiterCharacter}+`, "g"))?.[0]?.length || 0;
        }));
        const delimiter6 = delimiterCharacter.repeat(
          Math.max(3, longestStreak + 1)
        );
        ls.push(`${lb}${delimiter6}${attrString()}
`);
        ls.push(...innerLs);
        ls.push(`${delimiter6}
`);
      }
    };
  };
}
function pandocNativeStr(content) {
  return {
    ...basePandocNode,
    emit: (ls) => {
      const maxBackticks = content.match(/`+/g)?.[0].length || 0;
      const backticks = "`".repeat(maxBackticks + 1);
      const escapedContent = content.replaceAll(
        '"',
        '\\"'
      ).replaceAll("\n", "\\n");
      ls.push(
        `${backticks}${'Str "'}${escapedContent}${'"'}${backticks}{=pandoc-native}`
      );
    }
  };
}
var basePandocNode, pandocDiv, pandocCode, pandocFigure, pandocFigCaption;
var init_codegen = __esm({
  "core/pandoc/codegen.ts"() {
    init_mapped_text();
    basePandocNode = {
      emit: (_ls) => {
        throw new Error("unimplemented");
      },
      mappedString() {
        const ls = [];
        this.emit(ls);
        return mappedConcat(ls);
      },
      push: () => {
        throw new Error("unimplemented");
      },
      unshift: () => {
        throw new Error("unimplemented");
      }
    };
    pandocDiv = pandocBlock(":");
    pandocCode = pandocBlock("`");
    pandocFigure = pandocHtmlBlock("figure");
    pandocFigCaption = pandocHtmlBlock("figcaption");
  }
});

// https://deno.land/x/events@v1.0.0/mod.ts
var EventEmitter, mod_default2;
var init_mod7 = __esm({
  "https://deno.land/x/events@v1.0.0/mod.ts"() {
    EventEmitter = class {
      events = /* @__PURE__ */ new Map();
      maxListeners;
      #defaultMaxListeners = 10;
      get defaultMaxListeners() {
        return this.#defaultMaxListeners;
      }
      set defaultMaxListeners(n5) {
        if (Number.isInteger(n5) || n5 < 0) {
          const error2 = new RangeError(
            'The value of "defaultMaxListeners" is out of range. It must be a non-negative integer. Received ' + n5 + "."
          );
          throw error2;
        }
        this.#defaultMaxListeners = n5;
      }
      addListener(eventName, listener) {
        return this.on(eventName, listener);
      }
      emit(eventName, ...args) {
        const listeners4 = this.events.get(eventName);
        if (listeners4 === void 0) {
          if (eventName === "error") {
            const error2 = args[0];
            if (error2 instanceof Error) throw error2;
            throw new Error("Unhandled error.");
          }
          return false;
        }
        const copyListeners = [...listeners4];
        for (const listener of copyListeners) {
          listener.apply(this, args);
        }
        return true;
      }
      setMaxListeners(n5) {
        if (!Number.isInteger(n5) || n5 < 0) {
          throw new RangeError(
            'The value of "n" is out of range. It must be a non-negative integer. Received ' + n5 + "."
          );
        }
        this.maxListeners = n5;
        return this;
      }
      getMaxListeners() {
        if (this.maxListeners === void 0) {
          return this.defaultMaxListeners;
        }
        return this.maxListeners;
      }
      listenerCount(eventName) {
        const events = this.events.get(eventName);
        return events === void 0 ? 0 : events.length;
      }
      eventNames() {
        return Reflect.ownKeys(this.events);
      }
      listeners(eventName) {
        const listeners4 = this.events.get(eventName);
        return listeners4 === void 0 ? [] : listeners4;
      }
      off(eventName, listener) {
        return this.removeListener(eventName, listener);
      }
      on(eventName, listener, prepend) {
        if (this.events.has(eventName) === false) {
          this.events.set(eventName, []);
        }
        const events = this.events.get(eventName);
        if (prepend) {
          events.unshift(listener);
        } else {
          events.push(listener);
        }
        if (eventName !== "newListener" && this.events.has("newListener")) {
          this.emit("newListener", eventName, listener);
        }
        const maxListener = this.getMaxListeners();
        const eventLength = events.length;
        if (maxListener > 0 && eventLength > maxListener && !events.warned) {
          events.warned = true;
          const warning = new Error(
            `Possible EventEmitter memory leak detected.
         ${this.listenerCount(eventName)} ${eventName.toString()} listeners.
         Use emitter.setMaxListeners() to increase limit`
          );
          warning.name = "MaxListenersExceededWarning";
          console.warn(warning);
        }
        return this;
      }
      removeAllListeners(eventName) {
        const events = this.events;
        if (!events.has("removeListener")) {
          if (arguments.length === 0) {
            this.events = /* @__PURE__ */ new Map();
          } else if (events.has(eventName)) {
            events.delete(eventName);
          }
          return this;
        }
        if (arguments.length === 0) {
          for (const key of events.keys()) {
            if (key === "removeListener") continue;
            this.removeAllListeners(key);
          }
          this.removeAllListeners("removeListener");
          this.events = /* @__PURE__ */ new Map();
          return this;
        }
        const listeners4 = events.get(eventName);
        if (listeners4 !== void 0) {
          listeners4.map((listener) => {
            this.removeListener(eventName, listener);
          });
        }
        return this;
      }
      removeListener(eventName, listener) {
        const events = this.events;
        if (events.size === 0) return this;
        const list = events.get(eventName);
        if (list === void 0) return this;
        const index2 = list.findIndex((item) => item === listener || item.listener === listener);
        if (index2 === -1) return this;
        list.splice(index2, 1);
        if (list.length === 0) this.events.delete(eventName);
        if (events.has("removeListener")) {
          this.emit("removeListener", eventName, listener);
        }
        return this;
      }
      once(eventName, listener) {
        this.on(eventName, this.onceWrap(eventName, listener));
        return this;
      }
      onceWrap(eventName, listener) {
        const wrapper = function(...args) {
          this.context.removeListener(this.eventName, this.wrapedListener);
          this.listener.apply(this.context, args);
        };
        const wrapperContext = {
          eventName,
          listener,
          wrapedListener: wrapper,
          context: this
        };
        const wrapped = wrapper.bind(
          wrapperContext
        );
        wrapperContext.wrapedListener = wrapped;
        wrapped.listener = listener;
        return wrapped;
      }
      prependListener(eventName, listener) {
        return this.on(eventName, listener, true);
      }
      prependOnceListener(eventName, listener) {
        this.prependListener(eventName, this.onceWrap(eventName, listener));
        return this;
      }
      rawListeners(eventName) {
        const events = this.events;
        if (events === void 0) return [];
        const listeners4 = events.get(eventName);
        if (listeners4 === void 0) return [];
        return [...listeners4];
      }
    };
    mod_default2 = EventEmitter;
  }
});

// core/deno/next-tick.ts
var nextTick;
var init_next_tick = __esm({
  "core/deno/next-tick.ts"() {
    nextTick = (callback) => {
      setTimeout(callback, 16);
    };
  }
});

// core/cri/deno-cri/api.js
function arrayToObject(parameters) {
  const keyValue = {};
  parameters.forEach((parameter) => {
    const name2 = parameter.name;
    delete parameter.name;
    keyValue[name2] = parameter;
  });
  return keyValue;
}
function decorate(to, category, object) {
  to.category = category;
  Object.keys(object).forEach((field) => {
    if (field === "name") {
      return;
    }
    if (category === "type" && field === "properties" || field === "parameters") {
      to[field] = arrayToObject(object[field]);
    } else {
      to[field] = object[field];
    }
  });
}
function addCommand(chrome, domainName, command) {
  const commandName = `${domainName}.${command.name}`;
  const handler = (params, sessionId, callback) => {
    return chrome.send(commandName, params, sessionId, callback);
  };
  decorate(handler, "command", command);
  chrome[commandName] = chrome[domainName][command.name] = handler;
}
function addEvent(chrome, domainName, event) {
  const eventName = `${domainName}.${event.name}`;
  const handler = (sessionId, handler2) => {
    if (typeof sessionId === "function") {
      handler2 = sessionId;
      sessionId = void 0;
    }
    const rawEventName = sessionId ? `${eventName}.${sessionId}` : eventName;
    if (typeof handler2 === "function") {
      chrome.on(rawEventName, handler2);
      return () => chrome.removeListener(rawEventName, handler2);
    } else {
      return new Promise((fulfill, _reject) => {
        chrome.once(rawEventName, fulfill);
      });
    }
  };
  decorate(handler, "event", event);
  chrome[eventName] = chrome[domainName][event.name] = handler;
}
function addType(chrome, domainName, type4) {
  const typeName2 = `${domainName}.${type4.id}`;
  const help = {};
  decorate(help, "type", type4);
  chrome[typeName2] = chrome[domainName][type4.id] = help;
}
function prepare(object, protocol) {
  object.protocol = protocol;
  protocol.domains.forEach((domain2) => {
    const domainName = domain2.domain;
    object[domainName] = {};
    (domain2.commands || []).forEach((command) => {
      addCommand(object, domainName, command);
    });
    (domain2.events || []).forEach((event) => {
      addEvent(object, domainName, event);
    });
    (domain2.types || []).forEach((type4) => {
      addType(object, domainName, type4);
    });
    object[domainName].on = (eventName, handler) => {
      return object[domainName][eventName](handler);
    };
  });
}
var init_api3 = __esm({
  "core/cri/deno-cri/api.js"() {
  }
});

// core/cri/deno-cri/defaults.js
var HOST, PORT;
var init_defaults = __esm({
  "core/cri/deno-cri/defaults.js"() {
    HOST = "localhost";
    PORT = 9222;
  }
});

// core/cri/deno-cri/external-request.js
async function externalRequest(options) {
  const url = `${options.protocol}:/${options.host}:${options.port}${options.path}`;
  const fetchOpts = {};
  if (options.method) {
    fetchOpts.method = options.method;
  }
  const response = await fetch(url, options);
  const text = await response.text();
  if (response.status !== 200) {
    throw new Error(text);
  }
  return text;
}
var init_external_request = __esm({
  "core/cri/deno-cri/external-request.js"() {
  }
});

// core/cri/deno-cri/devtools.js
function devToolsInterface(options, callback) {
  options.host = options.host || HOST;
  options.port = options.port || PORT;
  options.secure = !!options.secure;
  options.useHostName = !!options.useHostName;
  options.alterPath = options.alterPath || ((path3) => path3);
  const newOptions = { ...options };
  newOptions.path = options.alterPath(options.path);
  newOptions.protocol = options.secure ? "https" : "http";
  return externalRequest(newOptions, callback);
}
async function Protocol(options) {
  options.path = "/json/protocol";
  const result2 = await devToolsInterface(options);
  return JSON.parse(result2);
}
async function List(options) {
  options.path = "/json/list";
  const result2 = await devToolsInterface(options);
  return JSON.parse(result2);
}
async function New(options) {
  options.path = "/json/new";
  if (Object.prototype.hasOwnProperty.call(options, "url")) {
    options.path += `?${options.url}`;
  }
  options = {
    ...options,
    method: "PUT"
  };
  const result2 = await devToolsInterface(options);
  return JSON.parse(result2);
}
var init_devtools = __esm({
  "core/cri/deno-cri/devtools.js"() {
    init_defaults();
    init_external_request();
  }
});

// core/cri/deno-cri/chrome.js
async function tryUntilTimeout(cb, timeout = 3e3) {
  const interval = 50;
  let soFar = 0;
  let lastE;
  do {
    try {
      const result2 = await cb();
      return result2;
    } catch (e5) {
      lastE = e5;
      soFar += interval;
      await new Promise((resolve16) => setTimeout(resolve16, interval));
    }
  } while (soFar < timeout);
  throw lastE;
}
var ProtocolError, Chrome;
var init_chrome = __esm({
  "core/cri/deno-cri/chrome.js"() {
    init_mod7();
    init_next_tick();
    init_api3();
    init_defaults();
    init_devtools();
    ProtocolError = class extends Error {
      constructor(request2, response) {
        let { message } = response;
        if (response.data) {
          message += ` (${response.data})`;
        }
        super(message);
        this.request = request2;
        this.response = response;
      }
    };
    Chrome = class extends mod_default2 {
      constructor(options, notifier) {
        super();
        const defaultTarget = async (targets) => {
          let target;
          if (!targets.length) {
            target = await New(options);
            if (!target.id) {
              throw new Error("No inspectable targets and unable to create one");
            }
          } else {
            let backup;
            target = targets.find((target2) => {
              if (target2.webSocketDebuggerUrl) {
                backup = backup || target2;
                return target2.type === "page";
              } else {
                return false;
              }
            });
            target = target || backup;
          }
          if (target) {
            return target;
          } else {
            throw new Error("No inspectable targets");
          }
        };
        options = options || {};
        this.host = options.host || HOST;
        this.port = options.port || PORT;
        this.secure = !!options.secure;
        this.useHostName = !!options.useHostName;
        this.alterPath = options.alterPath || ((path3) => path3);
        this.protocol = options.protocol;
        this.local = !!options.local;
        this.target = options.target || defaultTarget;
        this._notifier = notifier;
        this._callbacks = {};
        this._nextCommandId = 1;
        this.webSocketUrl = void 0;
        this._start();
      }
      // avoid misinterpreting protocol's members as custom util.inspect functions
      inspect(_depth, options) {
        options.customInspect = false;
        return Deno.inspect(this, options);
      }
      send(method, params, sessionId, callback) {
        const optionals = Array.from(arguments).slice(1);
        params = optionals.find((x3) => typeof x3 === "object");
        sessionId = optionals.find((x3) => typeof x3 === "string");
        callback = optionals.find((x3) => typeof x3 === "function");
        if (typeof callback === "function") {
          this._enqueueCommand(method, params, sessionId, callback);
          return void 0;
        } else {
          return new Promise((fulfill, reject2) => {
            this._enqueueCommand(method, params, sessionId, (error2, response) => {
              if (error2) {
                const request2 = { method, params, sessionId };
                reject2(
                  error2 instanceof Error ? error2 : new ProtocolError(request2, response)
                );
              } else {
                fulfill(response);
              }
            });
          });
        }
      }
      close(callback) {
        const closeWebSocket = (callback2) => {
          if (this._ws.readyState === 3) {
            callback2();
          } else {
            const onclose = this._ws.onclose;
            this._ws.onclose = () => {
              callback2();
              this._ws.onclose = onclose;
              this._ws.onclose && this._ws.onclose();
            };
            this._ws.close();
          }
        };
        if (typeof callback === "function") {
          closeWebSocket(callback);
          return void 0;
        } else {
          return new Promise((fulfill, _reject) => {
            closeWebSocket(fulfill);
          });
        }
      }
      // initiate the connection process
      async _start() {
        const options = {
          host: this.host,
          port: this.port,
          secure: this.secure,
          useHostName: this.useHostName,
          alterPath: this.alterPath
        };
        try {
          const url = await this._fetchDebuggerURL(options);
          const urlObject = new URL(url);
          urlObject.pathname = options.alterPath(urlObject.pathname);
          this.webSocketUrl = urlObject.href;
          options.host = urlObject.hostname;
          options.port = urlObject.port || options.port;
          const protocol = await this._fetchProtocol(options);
          prepare(this, protocol);
          await this._connectToWebSocket();
          nextTick(() => {
            this._notifier.emit("connect", this);
          });
        } catch (err2) {
          this._notifier.emit("error", err2);
        }
      }
      // fetch the WebSocket URL according to 'target'
      async _fetchDebuggerURL(options) {
        const userTarget = this.target;
        switch (typeof userTarget) {
          case "string": {
            let idOrUrl = userTarget;
            if (idOrUrl.startsWith("/")) {
              idOrUrl = `ws://${this.host}:${this.port}${idOrUrl}`;
            }
            if (idOrUrl.match(/^wss?:/i)) {
              return idOrUrl;
            } else {
              const targets = await tryUntilTimeout(async () => {
                return await List(options);
              });
              const object = targets.find((target) => target.id === idOrUrl);
              return object.webSocketDebuggerUrl;
            }
          }
          case "object": {
            const object = userTarget;
            return object.webSocketDebuggerUrl;
          }
          case "function": {
            const func = userTarget;
            const targets = await List(options);
            const result2 = await func(targets);
            const object = typeof result2 === "number" ? targets[result2] : result2;
            return object.webSocketDebuggerUrl;
          }
          default:
            throw new Error(`Invalid target argument "${this.target}"`);
        }
      }
      // fetch the protocol according to 'protocol' and 'local'
      async _fetchProtocol(options) {
        if (this.protocol) {
          return this.protocol;
        } else {
          options.local = this.local;
          return await Protocol(options);
        }
      }
      // establish the WebSocket connection and start processing user commands
      _connectToWebSocket() {
        return new Promise((fulfill, reject2) => {
          try {
            if (this.secure) {
              this.webSocketUrl = this.webSocketUrl.replace(/^ws:/i, "wss:");
            }
            this._ws = new WebSocket(this.webSocketUrl);
          } catch (err2) {
            reject2(err2);
            return;
          }
          this._ws.onopen = () => {
            fulfill();
          };
          this._ws.onmessage = (data3) => {
            const message = JSON.parse(data3.data);
            this._handleMessage(message);
          };
          this._ws.onclose = (_code) => {
            this.emit("disconnect");
          };
          this._ws.onerror = (err2) => {
            reject2(err2);
          };
        });
      }
      // handle the messages read from the WebSocket
      _handleMessage(message) {
        if (message.id) {
          const callback = this._callbacks[message.id];
          if (!callback) {
            return;
          }
          if (message.error) {
            callback(true, message.error);
          } else {
            callback(false, message.result || {});
          }
          delete this._callbacks[message.id];
          if (Object.keys(this._callbacks).length === 0) {
            this.emit("ready");
          }
        } else if (message.method) {
          const { method, params, sessionId } = message;
          this.emit("event", message);
          this.emit(method, params, sessionId);
          this.emit(`${method}.${sessionId}`, params, sessionId);
        }
      }
      // send a command to the remote endpoint and register a callback for the reply
      _enqueueCommand(method, params, sessionId, callback) {
        const id = this._nextCommandId++;
        const message = {
          id,
          method,
          sessionId,
          params: params || {}
        };
        this._ws.send(JSON.stringify(message));
        this._callbacks[id] = callback;
      }
    };
  }
});

// core/cri/deno-cri/index.js
function CDP(options, callback) {
  if (typeof options === "function") {
    callback = options;
    options = void 0;
  }
  const notifier = new mod_default2();
  if (typeof callback === "function") {
    nextTick(() => {
      new Chrome(options, notifier);
    });
    return notifier.once("connect", callback);
  } else {
    return new Promise((fulfill, reject2) => {
      notifier.once("connect", fulfill);
      notifier.once("error", reject2);
      new Chrome(options, notifier);
    });
  }
}
var deno_cri_default;
var init_deno_cri = __esm({
  "core/cri/deno-cri/index.js"() {
    init_mod7();
    init_chrome();
    init_devtools();
    init_next_tick();
    deno_cri_default = CDP;
  }
});

// core/appdirs.ts
function quartoDataDir(subdir, roaming = false) {
  return quartoDir(userDataDir, subdir, roaming);
}
function quartoCacheDir(subdir) {
  return quartoDir(userCacheDir, subdir);
}
function quartoRuntimeDir(subdir) {
  return quartoDir(userRuntimeDir, subdir);
}
function quartoDir(sourceFn, subdir, roaming) {
  const dir = sourceFn("quarto", roaming);
  const fullDir = subdir ? join4(dir, subdir) : dir;
  ensureDirSync(fullDir);
  return fullDir;
}
function userDataDir(appName, roaming = false) {
  switch (os) {
    case "darwin":
      return darwinUserDataDir(appName);
    case "windows":
      return windowsUserDataDir(appName, roaming);
    default:
      return xdgUserDataDir(appName);
  }
}
function userCacheDir(appName) {
  switch (os) {
    case "darwin":
      return darwinUserCacheDir(appName);
    case "windows":
      return windowsUserDataDir(appName);
    default:
      return xdgUserCacheDir(appName);
  }
}
function userRuntimeDir(appName) {
  switch (os) {
    case "darwin":
      return darwinUserCacheDir(appName);
    case "windows":
      return windowsUserDataDir(appName);
    default:
      return xdgUserRuntimeDir(appName);
  }
}
function darwinUserDataDir(appName) {
  return join4(
    Deno.env.get("HOME") || "",
    "Library",
    "Application Support",
    appName
  );
}
function darwinUserCacheDir(appName) {
  return join4(
    Deno.env.get("HOME") || "",
    "Library",
    "Caches",
    appName
  );
}
function xdgUserDataDir(appName) {
  const dataHome = Deno.env.get("XDG_DATA_HOME") || join4(Deno.env.get("HOME") || "", ".local", "share");
  return join4(dataHome, appName);
}
function xdgUserCacheDir(appName) {
  const cacheHome = Deno.env.get("XDG_CACHE_HOME") || join4(Deno.env.get("HOME") || "", ".cache");
  return join4(cacheHome, appName);
}
function xdgUserRuntimeDir(appName) {
  const runtimeDir = Deno.env.get("XDG_RUNTIME_DIR");
  if (runtimeDir) {
    return runtimeDir;
  } else {
    return xdgUserDataDir(appName);
  }
}
function windowsUserDataDir(appName, roaming = false) {
  const dir = (roaming ? Deno.env.get("APPDATA") : Deno.env.get("LOCALAPPDATA")) || "";
  return join4(dir, appName);
}
var init_appdirs = __esm({
  "core/appdirs.ts"() {
    init_path();
    init_fs();
    init_platform();
  }
});

// core/windows.ts
async function readRegistryKey(registryPath, keyname) {
  const defaultKeyname = keyname === "(Default)";
  const args = ["query", registryPath];
  if (defaultKeyname) {
    args.push("/ve");
  } else {
    args.push("/v");
    args.push(keyname);
  }
  const safeArgs = requireQuoting(args);
  const result2 = await safeWindowsExec(
    "reg.exe",
    safeArgs.args,
    (cmd) => {
      return execProcess({
        cmd: cmd[0],
        args: cmd.slice(1),
        stdout: "piped",
        stderr: "piped"
      });
    }
  );
  if (result2.success) {
    const output = result2.stdout;
    const regexStr = (defaultKeyname ? "" : ` *${keyname}`) + ` *(?:REG_SZ|REG_MULTI_SZ|REG_EXPAND_SZ|REG_DWORD|REG_BINARY|REG_NONE) *(.*)$`;
    const match = output?.match(RegExp(regexStr, "m"));
    if (match) {
      return match[1];
    } else {
      return void 0;
    }
  } else {
    return void 0;
  }
}
async function cacheCodePage() {
  if (!existsSync2(tokenPath)) {
    const value = await registryReadString(
      [kHKeyLocalMachine, kHKeyCurrentUser],
      "SYSTEM\\CurrentControlSet\\Control\\Nls\\CodePage",
      "ACP"
    );
    if (value) {
      Deno.writeTextFileSync(tokenPath, value);
    }
  }
}
function clearCodePageCache() {
  if (existsSync2(tokenPath)) {
    safeRemoveSync(tokenPath);
  }
}
function readCodePageCache() {
  const codepage = Deno.readTextFileSync(tokenPath);
  if (codepage) {
    return codepage;
  } else {
    return void 0;
  }
}
function readCodePage() {
  const readCache = () => {
    const codepage = readCodePageCache();
    if (codepage) {
      return codepage;
    }
  };
  try {
    return readCache();
  } catch {
    try {
      cacheCodePage();
      return readCache();
    } catch {
      return void 0;
    }
  }
}
function requireQuoting(args) {
  let requireQuoting2 = false;
  if (isWindows4) {
    const shellCharReg = new RegExp("[ <>()|\\:&;#?*']");
    args = args.map((a5) => {
      if (shellCharReg.test(a5)) {
        requireQuoting2 = true;
        return `"${a5}"`;
      } else {
        return a5;
      }
    });
  }
  return {
    status: requireQuoting2,
    args
  };
}
async function safeWindowsExec(program, args, fnExec) {
  const tempFile = Deno.makeTempFileSync(
    { prefix: "quarto-safe-exec", suffix: ".bat" }
  );
  try {
    Deno.writeTextFileSync(
      tempFile,
      ["@echo off", "chcp 65001 >nul", [program, ...args].join(" ")].join("\r\n")
    );
    return await fnExec(["cmd", "/c", tempFile]);
  } finally {
    removeIfExists(tempFile);
  }
}
var tokenPath;
var init_windows = __esm({
  "core/windows.ts"() {
    init_fs();
    init_path();
    init_appdirs();
    init_path2();
    init_process();
    init_registry();
    init_platform();
    tokenPath = join4(quartoCacheDir(), "codepage");
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/Errors.js
var CustomError, TimeoutError, puppeteerErrors;
var init_Errors = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/Errors.js"() {
    CustomError = class extends Error {
      constructor(message) {
        super(message);
        this.name = this.constructor.name;
        Error.captureStackTrace(this, this.constructor);
      }
    };
    TimeoutError = class extends CustomError {
    };
    puppeteerErrors = {
      TimeoutError
    };
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/DeviceDescriptors.js
var devices, devicesMap;
var init_DeviceDescriptors = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/DeviceDescriptors.js"() {
    devices = [
      {
        name: "Blackberry PlayBook",
        userAgent: "Mozilla/5.0 (PlayBook; U; RIM Tablet OS 2.1.0; en-US) AppleWebKit/536.2+ (KHTML like Gecko) Version/7.2.1.0 Safari/536.2+",
        viewport: {
          width: 600,
          height: 1024,
          deviceScaleFactor: 1,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Blackberry PlayBook landscape",
        userAgent: "Mozilla/5.0 (PlayBook; U; RIM Tablet OS 2.1.0; en-US) AppleWebKit/536.2+ (KHTML like Gecko) Version/7.2.1.0 Safari/536.2+",
        viewport: {
          width: 1024,
          height: 600,
          deviceScaleFactor: 1,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "BlackBerry Z30",
        userAgent: "Mozilla/5.0 (BB10; Touch) AppleWebKit/537.10+ (KHTML, like Gecko) Version/10.0.9.2372 Mobile Safari/537.10+",
        viewport: {
          width: 360,
          height: 640,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "BlackBerry Z30 landscape",
        userAgent: "Mozilla/5.0 (BB10; Touch) AppleWebKit/537.10+ (KHTML, like Gecko) Version/10.0.9.2372 Mobile Safari/537.10+",
        viewport: {
          width: 640,
          height: 360,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "Galaxy Note 3",
        userAgent: "Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30",
        viewport: {
          width: 360,
          height: 640,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Galaxy Note 3 landscape",
        userAgent: "Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30",
        viewport: {
          width: 640,
          height: 360,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "Galaxy Note II",
        userAgent: "Mozilla/5.0 (Linux; U; Android 4.1; en-us; GT-N7100 Build/JRO03C) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30",
        viewport: {
          width: 360,
          height: 640,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Galaxy Note II landscape",
        userAgent: "Mozilla/5.0 (Linux; U; Android 4.1; en-us; GT-N7100 Build/JRO03C) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30",
        viewport: {
          width: 640,
          height: 360,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "Galaxy S III",
        userAgent: "Mozilla/5.0 (Linux; U; Android 4.0; en-us; GT-I9300 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30",
        viewport: {
          width: 360,
          height: 640,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Galaxy S III landscape",
        userAgent: "Mozilla/5.0 (Linux; U; Android 4.0; en-us; GT-I9300 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30",
        viewport: {
          width: 640,
          height: 360,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "Galaxy S5",
        userAgent: "Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",
        viewport: {
          width: 360,
          height: 640,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Galaxy S5 landscape",
        userAgent: "Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",
        viewport: {
          width: 640,
          height: 360,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPad",
        userAgent: "Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1",
        viewport: {
          width: 768,
          height: 1024,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPad landscape",
        userAgent: "Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1",
        viewport: {
          width: 1024,
          height: 768,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPad Mini",
        userAgent: "Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1",
        viewport: {
          width: 768,
          height: 1024,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPad Mini landscape",
        userAgent: "Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1",
        viewport: {
          width: 1024,
          height: 768,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPad Pro",
        userAgent: "Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1",
        viewport: {
          width: 1024,
          height: 1366,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPad Pro landscape",
        userAgent: "Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1",
        viewport: {
          width: 1366,
          height: 1024,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPhone 4",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 7_1_2 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Version/7.0 Mobile/11D257 Safari/9537.53",
        viewport: {
          width: 320,
          height: 480,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPhone 4 landscape",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 7_1_2 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Version/7.0 Mobile/11D257 Safari/9537.53",
        viewport: {
          width: 480,
          height: 320,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPhone 5",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1",
        viewport: {
          width: 320,
          height: 568,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPhone 5 landscape",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1",
        viewport: {
          width: 568,
          height: 320,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPhone 6",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",
        viewport: {
          width: 375,
          height: 667,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPhone 6 landscape",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",
        viewport: {
          width: 667,
          height: 375,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPhone 6 Plus",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",
        viewport: {
          width: 414,
          height: 736,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPhone 6 Plus landscape",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",
        viewport: {
          width: 736,
          height: 414,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPhone 7",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",
        viewport: {
          width: 375,
          height: 667,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPhone 7 landscape",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",
        viewport: {
          width: 667,
          height: 375,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPhone 7 Plus",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",
        viewport: {
          width: 414,
          height: 736,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPhone 7 Plus landscape",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",
        viewport: {
          width: 736,
          height: 414,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPhone 8",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",
        viewport: {
          width: 375,
          height: 667,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPhone 8 landscape",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",
        viewport: {
          width: 667,
          height: 375,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPhone 8 Plus",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",
        viewport: {
          width: 414,
          height: 736,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPhone 8 Plus landscape",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",
        viewport: {
          width: 736,
          height: 414,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPhone SE",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1",
        viewport: {
          width: 320,
          height: 568,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPhone SE landscape",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1",
        viewport: {
          width: 568,
          height: 320,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPhone X",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",
        viewport: {
          width: 375,
          height: 812,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPhone X landscape",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",
        viewport: {
          width: 812,
          height: 375,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPhone XR",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 12_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 414,
          height: 896,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPhone XR landscape",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 12_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 896,
          height: 414,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPhone 11",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 414,
          height: 828,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPhone 11 landscape",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 828,
          height: 414,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPhone 11 Pro",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 375,
          height: 812,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPhone 11 Pro landscape",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 812,
          height: 375,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "iPhone 11 Pro Max",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 414,
          height: 896,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "iPhone 11 Pro Max landscape",
        userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Mobile/15E148 Safari/604.1",
        viewport: {
          width: 896,
          height: 414,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "JioPhone 2",
        userAgent: "Mozilla/5.0 (Mobile; LYF/F300B/LYF-F300B-001-01-15-130718-i;Android; rv:48.0) Gecko/48.0 Firefox/48.0 KAIOS/2.5",
        viewport: {
          width: 240,
          height: 320,
          deviceScaleFactor: 1,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "JioPhone 2 landscape",
        userAgent: "Mozilla/5.0 (Mobile; LYF/F300B/LYF-F300B-001-01-15-130718-i;Android; rv:48.0) Gecko/48.0 Firefox/48.0 KAIOS/2.5",
        viewport: {
          width: 320,
          height: 240,
          deviceScaleFactor: 1,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "Kindle Fire HDX",
        userAgent: "Mozilla/5.0 (Linux; U; en-us; KFAPWI Build/JDQ39) AppleWebKit/535.19 (KHTML, like Gecko) Silk/3.13 Safari/535.19 Silk-Accelerated=true",
        viewport: {
          width: 800,
          height: 1280,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Kindle Fire HDX landscape",
        userAgent: "Mozilla/5.0 (Linux; U; en-us; KFAPWI Build/JDQ39) AppleWebKit/535.19 (KHTML, like Gecko) Silk/3.13 Safari/535.19 Silk-Accelerated=true",
        viewport: {
          width: 1280,
          height: 800,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "LG Optimus L70",
        userAgent: "Mozilla/5.0 (Linux; U; Android 4.4.2; en-us; LGMS323 Build/KOT49I.MS32310c) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/75.0.3765.0 Mobile Safari/537.36",
        viewport: {
          width: 384,
          height: 640,
          deviceScaleFactor: 1.25,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "LG Optimus L70 landscape",
        userAgent: "Mozilla/5.0 (Linux; U; Android 4.4.2; en-us; LGMS323 Build/KOT49I.MS32310c) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/75.0.3765.0 Mobile Safari/537.36",
        viewport: {
          width: 640,
          height: 384,
          deviceScaleFactor: 1.25,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "Microsoft Lumia 550",
        userAgent: "Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 550) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Mobile Safari/537.36 Edge/14.14263",
        viewport: {
          width: 640,
          height: 360,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Microsoft Lumia 950",
        userAgent: "Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 950) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Mobile Safari/537.36 Edge/14.14263",
        viewport: {
          width: 360,
          height: 640,
          deviceScaleFactor: 4,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Microsoft Lumia 950 landscape",
        userAgent: "Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 950) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Mobile Safari/537.36 Edge/14.14263",
        viewport: {
          width: 640,
          height: 360,
          deviceScaleFactor: 4,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "Nexus 10",
        userAgent: "Mozilla/5.0 (Linux; Android 6.0.1; Nexus 10 Build/MOB31T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Safari/537.36",
        viewport: {
          width: 800,
          height: 1280,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Nexus 10 landscape",
        userAgent: "Mozilla/5.0 (Linux; Android 6.0.1; Nexus 10 Build/MOB31T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Safari/537.36",
        viewport: {
          width: 1280,
          height: 800,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "Nexus 4",
        userAgent: "Mozilla/5.0 (Linux; Android 4.4.2; Nexus 4 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",
        viewport: {
          width: 384,
          height: 640,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Nexus 4 landscape",
        userAgent: "Mozilla/5.0 (Linux; Android 4.4.2; Nexus 4 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",
        viewport: {
          width: 640,
          height: 384,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "Nexus 5",
        userAgent: "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",
        viewport: {
          width: 360,
          height: 640,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Nexus 5 landscape",
        userAgent: "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",
        viewport: {
          width: 640,
          height: 360,
          deviceScaleFactor: 3,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "Nexus 5X",
        userAgent: "Mozilla/5.0 (Linux; Android 8.0.0; Nexus 5X Build/OPR4.170623.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",
        viewport: {
          width: 412,
          height: 732,
          deviceScaleFactor: 2.625,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Nexus 5X landscape",
        userAgent: "Mozilla/5.0 (Linux; Android 8.0.0; Nexus 5X Build/OPR4.170623.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",
        viewport: {
          width: 732,
          height: 412,
          deviceScaleFactor: 2.625,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "Nexus 6",
        userAgent: "Mozilla/5.0 (Linux; Android 7.1.1; Nexus 6 Build/N6F26U) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",
        viewport: {
          width: 412,
          height: 732,
          deviceScaleFactor: 3.5,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Nexus 6 landscape",
        userAgent: "Mozilla/5.0 (Linux; Android 7.1.1; Nexus 6 Build/N6F26U) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",
        viewport: {
          width: 732,
          height: 412,
          deviceScaleFactor: 3.5,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "Nexus 6P",
        userAgent: "Mozilla/5.0 (Linux; Android 8.0.0; Nexus 6P Build/OPP3.170518.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",
        viewport: {
          width: 412,
          height: 732,
          deviceScaleFactor: 3.5,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Nexus 6P landscape",
        userAgent: "Mozilla/5.0 (Linux; Android 8.0.0; Nexus 6P Build/OPP3.170518.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",
        viewport: {
          width: 732,
          height: 412,
          deviceScaleFactor: 3.5,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "Nexus 7",
        userAgent: "Mozilla/5.0 (Linux; Android 6.0.1; Nexus 7 Build/MOB30X) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Safari/537.36",
        viewport: {
          width: 600,
          height: 960,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Nexus 7 landscape",
        userAgent: "Mozilla/5.0 (Linux; Android 6.0.1; Nexus 7 Build/MOB30X) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Safari/537.36",
        viewport: {
          width: 960,
          height: 600,
          deviceScaleFactor: 2,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "Nokia Lumia 520",
        userAgent: "Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 520)",
        viewport: {
          width: 320,
          height: 533,
          deviceScaleFactor: 1.5,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Nokia Lumia 520 landscape",
        userAgent: "Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 520)",
        viewport: {
          width: 533,
          height: 320,
          deviceScaleFactor: 1.5,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "Nokia N9",
        userAgent: "Mozilla/5.0 (MeeGo; NokiaN9) AppleWebKit/534.13 (KHTML, like Gecko) NokiaBrowser/8.5.0 Mobile Safari/534.13",
        viewport: {
          width: 480,
          height: 854,
          deviceScaleFactor: 1,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Nokia N9 landscape",
        userAgent: "Mozilla/5.0 (MeeGo; NokiaN9) AppleWebKit/534.13 (KHTML, like Gecko) NokiaBrowser/8.5.0 Mobile Safari/534.13",
        viewport: {
          width: 854,
          height: 480,
          deviceScaleFactor: 1,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "Pixel 2",
        userAgent: "Mozilla/5.0 (Linux; Android 8.0; Pixel 2 Build/OPD3.170816.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",
        viewport: {
          width: 411,
          height: 731,
          deviceScaleFactor: 2.625,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Pixel 2 landscape",
        userAgent: "Mozilla/5.0 (Linux; Android 8.0; Pixel 2 Build/OPD3.170816.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",
        viewport: {
          width: 731,
          height: 411,
          deviceScaleFactor: 2.625,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      },
      {
        name: "Pixel 2 XL",
        userAgent: "Mozilla/5.0 (Linux; Android 8.0.0; Pixel 2 XL Build/OPD1.170816.004) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",
        viewport: {
          width: 411,
          height: 823,
          deviceScaleFactor: 3.5,
          isMobile: true,
          hasTouch: true,
          isLandscape: false
        }
      },
      {
        name: "Pixel 2 XL landscape",
        userAgent: "Mozilla/5.0 (Linux; Android 8.0.0; Pixel 2 XL Build/OPD1.170816.004) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",
        viewport: {
          width: 823,
          height: 411,
          deviceScaleFactor: 3.5,
          isMobile: true,
          hasTouch: true,
          isLandscape: true
        }
      }
    ];
    devicesMap = {};
    for (const device of devices) {
      devicesMap[device.name] = device;
    }
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/AriaQueryHandler.js
async function queryAXTree(client, element, accessibleName, role) {
  const { nodes } = await client.send("Accessibility.queryAXTree", {
    objectId: element._remoteObject.objectId,
    accessibleName,
    role
  });
  const filteredNodes = nodes.filter((node) => node.role.value !== "text");
  return filteredNodes;
}
function parseAriaSelector(selector) {
  const normalize14 = (value) => value.replace(/ +/g, " ").trim();
  const knownAttributes = /* @__PURE__ */ new Set(["name", "role"]);
  const queryOptions = {};
  const attributeRegexp = /\[\s*(?<attribute>\w+)\s*=\s*"(?<value>\\.|[^"\\]*)"\s*\]/g;
  const defaultName2 = selector.replace(
    attributeRegexp,
    (_3, attribute, value) => {
      attribute = attribute.trim();
      if (!knownAttributes.has(attribute)) {
        throw new Error(`Unknown aria attribute "${attribute}" in selector`);
      }
      queryOptions[attribute] = normalize14(value);
      return "";
    }
  );
  if (defaultName2 && !queryOptions.name) {
    queryOptions.name = normalize14(defaultName2);
  }
  return queryOptions;
}
var queryOne, waitFor, queryAll, queryAllArray, ariaHandler;
var init_AriaQueryHandler = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/AriaQueryHandler.js"() {
    queryOne = async (element, selector) => {
      const exeCtx = element.executionContext();
      const { name: name2, role } = parseAriaSelector(selector);
      const res = await queryAXTree(exeCtx._client, element, name2, role);
      if (res.length < 1) {
        return null;
      }
      return exeCtx._adoptBackendNodeId(res[0].backendDOMNodeId);
    };
    waitFor = async (domWorld, selector, options) => {
      const binding2 = {
        name: "ariaQuerySelector",
        pptrFunction: async (selector2) => {
          const document2 = await domWorld._document();
          const element = await queryOne(document2, selector2);
          return element;
        }
      };
      return domWorld.waitForSelectorInPage(
        (_3, selector2) => globalThis.ariaQuerySelector(selector2),
        selector,
        options,
        binding2
      );
    };
    queryAll = async (element, selector) => {
      const exeCtx = element.executionContext();
      const { name: name2, role } = parseAriaSelector(selector);
      const res = await queryAXTree(exeCtx._client, element, name2, role);
      return Promise.all(
        res.map((axNode) => exeCtx._adoptBackendNodeId(axNode.backendDOMNodeId))
      );
    };
    queryAllArray = async (element, selector) => {
      const elementHandles = await queryAll(element, selector);
      const exeCtx = element.executionContext();
      const jsHandle = exeCtx.evaluateHandle(
        (...elements) => elements,
        ...elementHandles
      );
      return jsHandle;
    };
    ariaHandler = {
      queryOne,
      waitFor,
      queryAll,
      queryAllArray
    };
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/QueryHandler.js
function makeQueryHandler(handler) {
  const internalHandler = {};
  if (handler.queryOne) {
    internalHandler.queryOne = async (element, selector) => {
      const jsHandle = await element.evaluateHandle(handler.queryOne, selector);
      const elementHandle = jsHandle.asElement();
      if (elementHandle) {
        return elementHandle;
      }
      await jsHandle.dispose();
      return null;
    };
    internalHandler.waitFor = (domWorld, selector, options) => domWorld.waitForSelectorInPage(handler.queryOne, selector, options);
  }
  if (handler.queryAll) {
    internalHandler.queryAll = async (element, selector) => {
      const jsHandle = await element.evaluateHandle(handler.queryAll, selector);
      const properties = await jsHandle.getProperties();
      await jsHandle.dispose();
      const result2 = [];
      for (const property of properties.values()) {
        const elementHandle = property.asElement();
        if (elementHandle) {
          result2.push(elementHandle);
        }
      }
      return result2;
    };
    internalHandler.queryAllArray = async (element, selector) => {
      const resultHandle = await element.evaluateHandle(
        handler.queryAll,
        selector
      );
      const arrayHandle = await resultHandle.evaluateHandle(
        (res) => Array.from(res)
      );
      return arrayHandle;
    };
  }
  return internalHandler;
}
function registerCustomQueryHandler(name2, handler) {
  if (_queryHandlers.get(name2)) {
    throw new Error(`A custom query handler named "${name2}" already exists`);
  }
  const isValidName2 = /^[a-zA-Z]+$/.test(name2);
  if (!isValidName2) {
    throw new Error(`Custom query handler names may only contain [a-zA-Z]`);
  }
  const internalHandler = makeQueryHandler(handler);
  _queryHandlers.set(name2, internalHandler);
}
function unregisterCustomQueryHandler(name2) {
  if (_queryHandlers.has(name2) && !_builtInHandlers.has(name2)) {
    _queryHandlers.delete(name2);
  }
}
function customQueryHandlerNames() {
  return [..._queryHandlers.keys()].filter(
    (name2) => !_builtInHandlers.has(name2)
  );
}
function clearCustomQueryHandlers() {
  customQueryHandlerNames().forEach(unregisterCustomQueryHandler);
}
function getQueryHandlerAndSelector(selector) {
  const hasCustomQueryHandler = /^[a-zA-Z]+\//.test(selector);
  if (!hasCustomQueryHandler) {
    return { updatedSelector: selector, queryHandler: _defaultHandler };
  }
  const index2 = selector.indexOf("/");
  const name2 = selector.slice(0, index2);
  const updatedSelector = selector.slice(index2 + 1);
  const queryHandler = _queryHandlers.get(name2);
  if (!queryHandler) {
    throw new Error(
      `Query set to use "${name2}", but no query handler of that name was found`
    );
  }
  return {
    updatedSelector,
    queryHandler
  };
}
var _defaultHandler, pierceHandler, _builtInHandlers, _queryHandlers;
var init_QueryHandler = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/QueryHandler.js"() {
    init_AriaQueryHandler();
    _defaultHandler = makeQueryHandler({
      queryOne: (element, selector) => element.querySelector(selector),
      queryAll: (element, selector) => element.querySelectorAll(selector)
    });
    pierceHandler = makeQueryHandler({
      queryOne: (element, selector) => {
        let found = null;
        const search = (root) => {
          const iter = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT);
          do {
            const currentNode = iter.currentNode;
            if (currentNode.shadowRoot) {
              search(currentNode.shadowRoot);
            }
            if (currentNode instanceof ShadowRoot) {
              continue;
            }
            if (!found && currentNode.matches(selector)) {
              found = currentNode;
            }
          } while (!found && iter.nextNode());
        };
        if (element instanceof Document) {
          element = element.documentElement;
        }
        search(element);
        return found;
      },
      queryAll: (element, selector) => {
        const result2 = [];
        const collect = (root) => {
          const iter = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT);
          do {
            const currentNode = iter.currentNode;
            if (currentNode.shadowRoot) {
              collect(currentNode.shadowRoot);
            }
            if (currentNode instanceof ShadowRoot) {
              continue;
            }
            if (currentNode.matches(selector)) {
              result2.push(currentNode);
            }
          } while (iter.nextNode());
        };
        if (element instanceof Document) {
          element = element.documentElement;
        }
        collect(element);
        return result2;
      }
    });
    _builtInHandlers = /* @__PURE__ */ new Map([
      ["aria", ariaHandler],
      ["pierce", pierceHandler]
    ]);
    _queryHandlers = new Map(_builtInHandlers);
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/assert.js
var assert3;
var init_assert2 = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/assert.js"() {
    assert3 = (value, message) => {
      if (!value) {
        throw new Error(message);
      }
    };
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/Debug.js
var debug2;
var init_Debug = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/Debug.js"() {
    debug2 = (prefix) => {
      return (...logArgs) => {
        const debugLevel = globalThis.__PUPPETEER_DEBUG;
        if (!debugLevel) {
          return;
        }
        const everythingShouldBeLogged = debugLevel === "*";
        const prefixMatchesDebugLevel = everythingShouldBeLogged || /**
               * If the debug level is `foo*`, that means we match any prefix that
               * starts with `foo`. If the level is `foo`, we match only the prefix
               * `foo`.
               */
        (debugLevel.endsWith("*") ? prefix.startsWith(debugLevel) : prefix === debugLevel);
        if (!prefixMatchesDebugLevel) {
          return;
        }
        console.log(`${prefix}:`, ...logArgs);
      };
    };
  }
});

// https://deno.land/std@0.196.0/encoding/base64.ts
function encode2(data3) {
  const uint8 = typeof data3 === "string" ? new TextEncoder().encode(data3) : data3 instanceof Uint8Array ? data3 : new Uint8Array(data3);
  let result2 = "", i6;
  const l6 = uint8.length;
  for (i6 = 2; i6 < l6; i6 += 3) {
    result2 += base64abc[uint8[i6 - 2] >> 2];
    result2 += base64abc[(uint8[i6 - 2] & 3) << 4 | uint8[i6 - 1] >> 4];
    result2 += base64abc[(uint8[i6 - 1] & 15) << 2 | uint8[i6] >> 6];
    result2 += base64abc[uint8[i6] & 63];
  }
  if (i6 === l6 + 1) {
    result2 += base64abc[uint8[i6 - 2] >> 2];
    result2 += base64abc[(uint8[i6 - 2] & 3) << 4];
    result2 += "==";
  }
  if (i6 === l6) {
    result2 += base64abc[uint8[i6 - 2] >> 2];
    result2 += base64abc[(uint8[i6 - 2] & 3) << 4 | uint8[i6 - 1] >> 4];
    result2 += base64abc[(uint8[i6 - 1] & 15) << 2];
    result2 += "=";
  }
  return result2;
}
function decode2(b64) {
  const binString = atob(b64);
  const size = binString.length;
  const bytes = new Uint8Array(size);
  for (let i6 = 0; i6 < size; i6++) {
    bytes[i6] = binString.charCodeAt(i6);
  }
  return bytes;
}
var base64abc;
var init_base642 = __esm({
  "https://deno.land/std@0.196.0/encoding/base64.ts"() {
    base64abc = [
      "A",
      "B",
      "C",
      "D",
      "E",
      "F",
      "G",
      "H",
      "I",
      "J",
      "K",
      "L",
      "M",
      "N",
      "O",
      "P",
      "Q",
      "R",
      "S",
      "T",
      "U",
      "V",
      "W",
      "X",
      "Y",
      "Z",
      "a",
      "b",
      "c",
      "d",
      "e",
      "f",
      "g",
      "h",
      "i",
      "j",
      "k",
      "l",
      "m",
      "n",
      "o",
      "p",
      "q",
      "r",
      "s",
      "t",
      "u",
      "v",
      "w",
      "x",
      "y",
      "z",
      "0",
      "1",
      "2",
      "3",
      "4",
      "5",
      "6",
      "7",
      "8",
      "9",
      "+",
      "/"
    ];
  }
});

// https://deno.land/std@0.217.0/bytes/concat.ts
function concat(buf) {
  let length = 0;
  for (const b3 of buf) {
    length += b3.length;
  }
  const output = new Uint8Array(length);
  let index2 = 0;
  for (const b3 of buf) {
    output.set(b3, index2);
    index2 += b3.length;
  }
  return output;
}
var init_concat = __esm({
  "https://deno.land/std@0.217.0/bytes/concat.ts"() {
  }
});

// https://deno.land/std@0.217.0/bytes/copy.ts
function copy3(src2, dst, off2 = 0) {
  off2 = Math.max(0, Math.min(off2, dst.byteLength));
  const dstBytesAvailable = dst.byteLength - off2;
  if (src2.byteLength > dstBytesAvailable) {
    src2 = src2.subarray(0, dstBytesAvailable);
  }
  dst.set(src2, off2);
  return src2.byteLength;
}
var init_copy2 = __esm({
  "https://deno.land/std@0.217.0/bytes/copy.ts"() {
  }
});

// https://deno.land/std@0.217.0/bytes/ends_with.ts
var init_ends_with = __esm({
  "https://deno.land/std@0.217.0/bytes/ends_with.ts"() {
  }
});

// https://deno.land/std@0.217.0/bytes/equals.ts
var init_equals = __esm({
  "https://deno.land/std@0.217.0/bytes/equals.ts"() {
  }
});

// https://deno.land/std@0.217.0/bytes/index_of_needle.ts
var init_index_of_needle = __esm({
  "https://deno.land/std@0.217.0/bytes/index_of_needle.ts"() {
  }
});

// https://deno.land/std@0.217.0/bytes/includes_needle.ts
var init_includes_needle = __esm({
  "https://deno.land/std@0.217.0/bytes/includes_needle.ts"() {
    init_index_of_needle();
  }
});

// https://deno.land/std@0.217.0/bytes/last_index_of_needle.ts
var init_last_index_of_needle = __esm({
  "https://deno.land/std@0.217.0/bytes/last_index_of_needle.ts"() {
  }
});

// https://deno.land/std@0.217.0/bytes/repeat.ts
var init_repeat = __esm({
  "https://deno.land/std@0.217.0/bytes/repeat.ts"() {
    init_copy2();
  }
});

// https://deno.land/std@0.217.0/bytes/starts_with.ts
var init_starts_with = __esm({
  "https://deno.land/std@0.217.0/bytes/starts_with.ts"() {
  }
});

// https://deno.land/std@0.217.0/bytes/mod.ts
var init_mod8 = __esm({
  "https://deno.land/std@0.217.0/bytes/mod.ts"() {
    init_concat();
    init_copy2();
    init_ends_with();
    init_equals();
    init_includes_needle();
    init_index_of_needle();
    init_last_index_of_needle();
    init_repeat();
    init_starts_with();
  }
});

// https://deno.land/std@0.204.0/path/_os.ts
var osType, isWindows5;
var init_os2 = __esm({
  "https://deno.land/std@0.204.0/path/_os.ts"() {
    osType = (() => {
      const { Deno: Deno6 } = globalThis;
      if (typeof Deno6?.build?.os === "string") {
        return Deno6.build.os;
      }
      const { navigator: navigator2 } = globalThis;
      if (navigator2?.appVersion?.includes?.("Win")) {
        return "windows";
      }
      return "linux";
    })();
    isWindows5 = osType === "windows";
  }
});

// https://deno.land/std@0.204.0/path/_common/assert_path.ts
function assertPath2(path3) {
  if (typeof path3 !== "string") {
    throw new TypeError(
      `Path must be a string. Received ${JSON.stringify(path3)}`
    );
  }
}
var init_assert_path2 = __esm({
  "https://deno.land/std@0.204.0/path/_common/assert_path.ts"() {
  }
});

// https://deno.land/std@0.204.0/path/_common/basename.ts
var init_basename5 = __esm({
  "https://deno.land/std@0.204.0/path/_common/basename.ts"() {
    init_assert_path2();
  }
});

// https://deno.land/std@0.204.0/path/_common/constants.ts
var CHAR_UPPERCASE_A2, CHAR_LOWERCASE_A2, CHAR_UPPERCASE_Z2, CHAR_LOWERCASE_Z2, CHAR_DOT2, CHAR_FORWARD_SLASH2, CHAR_BACKWARD_SLASH2, CHAR_COLON4;
var init_constants7 = __esm({
  "https://deno.land/std@0.204.0/path/_common/constants.ts"() {
    CHAR_UPPERCASE_A2 = 65;
    CHAR_LOWERCASE_A2 = 97;
    CHAR_UPPERCASE_Z2 = 90;
    CHAR_LOWERCASE_Z2 = 122;
    CHAR_DOT2 = 46;
    CHAR_FORWARD_SLASH2 = 47;
    CHAR_BACKWARD_SLASH2 = 92;
    CHAR_COLON4 = 58;
  }
});

// https://deno.land/std@0.204.0/path/_common/strip_trailing_separators.ts
function stripTrailingSeparators2(segment, isSep) {
  if (segment.length <= 1) {
    return segment;
  }
  let end = segment.length;
  for (let i6 = segment.length - 1; i6 > 0; i6--) {
    if (isSep(segment.charCodeAt(i6))) {
      end = i6;
    } else {
      break;
    }
  }
  return segment.slice(0, end);
}
var init_strip_trailing_separators2 = __esm({
  "https://deno.land/std@0.204.0/path/_common/strip_trailing_separators.ts"() {
  }
});

// https://deno.land/std@0.204.0/path/windows/_util.ts
function isPosixPathSeparator3(code5) {
  return code5 === CHAR_FORWARD_SLASH2;
}
function isPathSeparator2(code5) {
  return code5 === CHAR_FORWARD_SLASH2 || code5 === CHAR_BACKWARD_SLASH2;
}
function isWindowsDeviceRoot2(code5) {
  return code5 >= CHAR_LOWERCASE_A2 && code5 <= CHAR_LOWERCASE_Z2 || code5 >= CHAR_UPPERCASE_A2 && code5 <= CHAR_UPPERCASE_Z2;
}
var init_util4 = __esm({
  "https://deno.land/std@0.204.0/path/windows/_util.ts"() {
    init_constants7();
  }
});

// https://deno.land/std@0.204.0/path/windows/basename.ts
var init_basename6 = __esm({
  "https://deno.land/std@0.204.0/path/windows/basename.ts"() {
    init_basename5();
    init_constants7();
    init_strip_trailing_separators2();
    init_util4();
  }
});

// https://deno.land/std@0.204.0/path/_common/dirname.ts
function assertArg5(path3) {
  assertPath2(path3);
  if (path3.length === 0) return ".";
}
var init_dirname5 = __esm({
  "https://deno.land/std@0.204.0/path/_common/dirname.ts"() {
    init_assert_path2();
  }
});

// https://deno.land/std@0.204.0/path/windows/dirname.ts
function dirname5(path3) {
  assertArg5(path3);
  const len = path3.length;
  let rootEnd = -1;
  let end = -1;
  let matchedSlash = true;
  let offset3 = 0;
  const code5 = path3.charCodeAt(0);
  if (len > 1) {
    if (isPathSeparator2(code5)) {
      rootEnd = offset3 = 1;
      if (isPathSeparator2(path3.charCodeAt(1))) {
        let j3 = 2;
        let last = j3;
        for (; j3 < len; ++j3) {
          if (isPathSeparator2(path3.charCodeAt(j3))) break;
        }
        if (j3 < len && j3 !== last) {
          last = j3;
          for (; j3 < len; ++j3) {
            if (!isPathSeparator2(path3.charCodeAt(j3))) break;
          }
          if (j3 < len && j3 !== last) {
            last = j3;
            for (; j3 < len; ++j3) {
              if (isPathSeparator2(path3.charCodeAt(j3))) break;
            }
            if (j3 === len) {
              return path3;
            }
            if (j3 !== last) {
              rootEnd = offset3 = j3 + 1;
            }
          }
        }
      }
    } else if (isWindowsDeviceRoot2(code5)) {
      if (path3.charCodeAt(1) === CHAR_COLON4) {
        rootEnd = offset3 = 2;
        if (len > 2) {
          if (isPathSeparator2(path3.charCodeAt(2))) rootEnd = offset3 = 3;
        }
      }
    }
  } else if (isPathSeparator2(code5)) {
    return path3;
  }
  for (let i6 = len - 1; i6 >= offset3; --i6) {
    if (isPathSeparator2(path3.charCodeAt(i6))) {
      if (!matchedSlash) {
        end = i6;
        break;
      }
    } else {
      matchedSlash = false;
    }
  }
  if (end === -1) {
    if (rootEnd === -1) return ".";
    else end = rootEnd;
  }
  return stripTrailingSeparators2(path3.slice(0, end), isPosixPathSeparator3);
}
var init_dirname6 = __esm({
  "https://deno.land/std@0.204.0/path/windows/dirname.ts"() {
    init_dirname5();
    init_constants7();
    init_strip_trailing_separators2();
    init_util4();
  }
});

// https://deno.land/std@0.204.0/path/windows/extname.ts
var init_extname4 = __esm({
  "https://deno.land/std@0.204.0/path/windows/extname.ts"() {
    init_constants7();
    init_assert_path2();
    init_util4();
  }
});

// https://deno.land/std@0.204.0/path/_common/format.ts
var init_format6 = __esm({
  "https://deno.land/std@0.204.0/path/_common/format.ts"() {
  }
});

// https://deno.land/std@0.204.0/path/windows/format.ts
var init_format7 = __esm({
  "https://deno.land/std@0.204.0/path/windows/format.ts"() {
    init_format6();
  }
});

// https://deno.land/std@0.204.0/path/_common/from_file_url.ts
var init_from_file_url5 = __esm({
  "https://deno.land/std@0.204.0/path/_common/from_file_url.ts"() {
  }
});

// https://deno.land/std@0.204.0/path/windows/from_file_url.ts
var init_from_file_url6 = __esm({
  "https://deno.land/std@0.204.0/path/windows/from_file_url.ts"() {
    init_from_file_url5();
  }
});

// https://deno.land/std@0.204.0/path/windows/is_absolute.ts
var init_is_absolute4 = __esm({
  "https://deno.land/std@0.204.0/path/windows/is_absolute.ts"() {
    init_constants7();
    init_assert_path2();
    init_util4();
  }
});

// https://deno.land/std@0.204.0/assert/assertion_error.ts
var AssertionError3;
var init_assertion_error2 = __esm({
  "https://deno.land/std@0.204.0/assert/assertion_error.ts"() {
    AssertionError3 = class extends Error {
      name = "AssertionError";
      constructor(message) {
        super(message);
      }
    };
  }
});

// https://deno.land/std@0.204.0/assert/assert.ts
function assert4(expr, msg5 = "") {
  if (!expr) {
    throw new AssertionError3(msg5);
  }
}
var init_assert3 = __esm({
  "https://deno.land/std@0.204.0/assert/assert.ts"() {
    init_assertion_error2();
  }
});

// https://deno.land/std@0.204.0/path/_common/normalize.ts
function assertArg8(path3) {
  assertPath2(path3);
  if (path3.length === 0) return ".";
}
var init_normalize5 = __esm({
  "https://deno.land/std@0.204.0/path/_common/normalize.ts"() {
    init_assert_path2();
  }
});

// https://deno.land/std@0.204.0/path/_common/normalize_string.ts
function normalizeString2(path3, allowAboveRoot, separator, isPathSeparator5) {
  let res = "";
  let lastSegmentLength = 0;
  let lastSlash = -1;
  let dots = 0;
  let code5;
  for (let i6 = 0, len = path3.length; i6 <= len; ++i6) {
    if (i6 < len) code5 = path3.charCodeAt(i6);
    else if (isPathSeparator5(code5)) break;
    else code5 = CHAR_FORWARD_SLASH2;
    if (isPathSeparator5(code5)) {
      if (lastSlash === i6 - 1 || dots === 1) {
      } else if (lastSlash !== i6 - 1 && dots === 2) {
        if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== CHAR_DOT2 || res.charCodeAt(res.length - 2) !== CHAR_DOT2) {
          if (res.length > 2) {
            const lastSlashIndex = res.lastIndexOf(separator);
            if (lastSlashIndex === -1) {
              res = "";
              lastSegmentLength = 0;
            } else {
              res = res.slice(0, lastSlashIndex);
              lastSegmentLength = res.length - 1 - res.lastIndexOf(separator);
            }
            lastSlash = i6;
            dots = 0;
            continue;
          } else if (res.length === 2 || res.length === 1) {
            res = "";
            lastSegmentLength = 0;
            lastSlash = i6;
            dots = 0;
            continue;
          }
        }
        if (allowAboveRoot) {
          if (res.length > 0) res += `${separator}..`;
          else res = "..";
          lastSegmentLength = 2;
        }
      } else {
        if (res.length > 0) res += separator + path3.slice(lastSlash + 1, i6);
        else res = path3.slice(lastSlash + 1, i6);
        lastSegmentLength = i6 - lastSlash - 1;
      }
      lastSlash = i6;
      dots = 0;
    } else if (code5 === CHAR_DOT2 && dots !== -1) {
      ++dots;
    } else {
      dots = -1;
    }
  }
  return res;
}
var init_normalize_string2 = __esm({
  "https://deno.land/std@0.204.0/path/_common/normalize_string.ts"() {
    init_constants7();
  }
});

// https://deno.land/std@0.204.0/path/windows/normalize.ts
function normalize5(path3) {
  assertArg8(path3);
  const len = path3.length;
  let rootEnd = 0;
  let device;
  let isAbsolute12 = false;
  const code5 = path3.charCodeAt(0);
  if (len > 1) {
    if (isPathSeparator2(code5)) {
      isAbsolute12 = true;
      if (isPathSeparator2(path3.charCodeAt(1))) {
        let j3 = 2;
        let last = j3;
        for (; j3 < len; ++j3) {
          if (isPathSeparator2(path3.charCodeAt(j3))) break;
        }
        if (j3 < len && j3 !== last) {
          const firstPart = path3.slice(last, j3);
          last = j3;
          for (; j3 < len; ++j3) {
            if (!isPathSeparator2(path3.charCodeAt(j3))) break;
          }
          if (j3 < len && j3 !== last) {
            last = j3;
            for (; j3 < len; ++j3) {
              if (isPathSeparator2(path3.charCodeAt(j3))) break;
            }
            if (j3 === len) {
              return `\\\\${firstPart}\\${path3.slice(last)}\\`;
            } else if (j3 !== last) {
              device = `\\\\${firstPart}\\${path3.slice(last, j3)}`;
              rootEnd = j3;
            }
          }
        }
      } else {
        rootEnd = 1;
      }
    } else if (isWindowsDeviceRoot2(code5)) {
      if (path3.charCodeAt(1) === CHAR_COLON4) {
        device = path3.slice(0, 2);
        rootEnd = 2;
        if (len > 2) {
          if (isPathSeparator2(path3.charCodeAt(2))) {
            isAbsolute12 = true;
            rootEnd = 3;
          }
        }
      }
    }
  } else if (isPathSeparator2(code5)) {
    return "\\";
  }
  let tail;
  if (rootEnd < len) {
    tail = normalizeString2(
      path3.slice(rootEnd),
      !isAbsolute12,
      "\\",
      isPathSeparator2
    );
  } else {
    tail = "";
  }
  if (tail.length === 0 && !isAbsolute12) tail = ".";
  if (tail.length > 0 && isPathSeparator2(path3.charCodeAt(len - 1))) {
    tail += "\\";
  }
  if (device === void 0) {
    if (isAbsolute12) {
      if (tail.length > 0) return `\\${tail}`;
      else return "\\";
    } else if (tail.length > 0) {
      return tail;
    } else {
      return "";
    }
  } else if (isAbsolute12) {
    if (tail.length > 0) return `${device}\\${tail}`;
    else return `${device}\\`;
  } else if (tail.length > 0) {
    return device + tail;
  } else {
    return device;
  }
}
var init_normalize6 = __esm({
  "https://deno.land/std@0.204.0/path/windows/normalize.ts"() {
    init_normalize5();
    init_constants7();
    init_normalize_string2();
    init_util4();
  }
});

// https://deno.land/std@0.204.0/path/windows/join.ts
function join7(...paths) {
  if (paths.length === 0) return ".";
  let joined;
  let firstPart = null;
  for (let i6 = 0; i6 < paths.length; ++i6) {
    const path3 = paths[i6];
    assertPath2(path3);
    if (path3.length > 0) {
      if (joined === void 0) joined = firstPart = path3;
      else joined += `\\${path3}`;
    }
  }
  if (joined === void 0) return ".";
  let needsReplace = true;
  let slashCount = 0;
  assert4(firstPart !== null);
  if (isPathSeparator2(firstPart.charCodeAt(0))) {
    ++slashCount;
    const firstLen = firstPart.length;
    if (firstLen > 1) {
      if (isPathSeparator2(firstPart.charCodeAt(1))) {
        ++slashCount;
        if (firstLen > 2) {
          if (isPathSeparator2(firstPart.charCodeAt(2))) ++slashCount;
          else {
            needsReplace = false;
          }
        }
      }
    }
  }
  if (needsReplace) {
    for (; slashCount < joined.length; ++slashCount) {
      if (!isPathSeparator2(joined.charCodeAt(slashCount))) break;
    }
    if (slashCount >= 2) joined = `\\${joined.slice(slashCount)}`;
  }
  return normalize5(joined);
}
var init_join4 = __esm({
  "https://deno.land/std@0.204.0/path/windows/join.ts"() {
    init_assert3();
    init_assert_path2();
    init_util4();
    init_normalize6();
  }
});

// https://deno.land/std@0.204.0/path/windows/parse.ts
var init_parse5 = __esm({
  "https://deno.land/std@0.204.0/path/windows/parse.ts"() {
    init_constants7();
    init_assert_path2();
    init_util4();
  }
});

// https://deno.land/std@0.204.0/path/windows/resolve.ts
function resolve5(...pathSegments) {
  let resolvedDevice = "";
  let resolvedTail = "";
  let resolvedAbsolute = false;
  for (let i6 = pathSegments.length - 1; i6 >= -1; i6--) {
    let path3;
    const { Deno: Deno6 } = globalThis;
    if (i6 >= 0) {
      path3 = pathSegments[i6];
    } else if (!resolvedDevice) {
      if (typeof Deno6?.cwd !== "function") {
        throw new TypeError("Resolved a drive-letter-less path without a CWD.");
      }
      path3 = Deno6.cwd();
    } else {
      if (typeof Deno6?.env?.get !== "function" || typeof Deno6?.cwd !== "function") {
        throw new TypeError("Resolved a relative path without a CWD.");
      }
      path3 = Deno6.cwd();
      if (path3 === void 0 || path3.slice(0, 3).toLowerCase() !== `${resolvedDevice.toLowerCase()}\\`) {
        path3 = `${resolvedDevice}\\`;
      }
    }
    assertPath2(path3);
    const len = path3.length;
    if (len === 0) continue;
    let rootEnd = 0;
    let device = "";
    let isAbsolute12 = false;
    const code5 = path3.charCodeAt(0);
    if (len > 1) {
      if (isPathSeparator2(code5)) {
        isAbsolute12 = true;
        if (isPathSeparator2(path3.charCodeAt(1))) {
          let j3 = 2;
          let last = j3;
          for (; j3 < len; ++j3) {
            if (isPathSeparator2(path3.charCodeAt(j3))) break;
          }
          if (j3 < len && j3 !== last) {
            const firstPart = path3.slice(last, j3);
            last = j3;
            for (; j3 < len; ++j3) {
              if (!isPathSeparator2(path3.charCodeAt(j3))) break;
            }
            if (j3 < len && j3 !== last) {
              last = j3;
              for (; j3 < len; ++j3) {
                if (isPathSeparator2(path3.charCodeAt(j3))) break;
              }
              if (j3 === len) {
                device = `\\\\${firstPart}\\${path3.slice(last)}`;
                rootEnd = j3;
              } else if (j3 !== last) {
                device = `\\\\${firstPart}\\${path3.slice(last, j3)}`;
                rootEnd = j3;
              }
            }
          }
        } else {
          rootEnd = 1;
        }
      } else if (isWindowsDeviceRoot2(code5)) {
        if (path3.charCodeAt(1) === CHAR_COLON4) {
          device = path3.slice(0, 2);
          rootEnd = 2;
          if (len > 2) {
            if (isPathSeparator2(path3.charCodeAt(2))) {
              isAbsolute12 = true;
              rootEnd = 3;
            }
          }
        }
      }
    } else if (isPathSeparator2(code5)) {
      rootEnd = 1;
      isAbsolute12 = true;
    }
    if (device.length > 0 && resolvedDevice.length > 0 && device.toLowerCase() !== resolvedDevice.toLowerCase()) {
      continue;
    }
    if (resolvedDevice.length === 0 && device.length > 0) {
      resolvedDevice = device;
    }
    if (!resolvedAbsolute) {
      resolvedTail = `${path3.slice(rootEnd)}\\${resolvedTail}`;
      resolvedAbsolute = isAbsolute12;
    }
    if (resolvedAbsolute && resolvedDevice.length > 0) break;
  }
  resolvedTail = normalizeString2(
    resolvedTail,
    !resolvedAbsolute,
    "\\",
    isPathSeparator2
  );
  return resolvedDevice + (resolvedAbsolute ? "\\" : "") + resolvedTail || ".";
}
var init_resolve5 = __esm({
  "https://deno.land/std@0.204.0/path/windows/resolve.ts"() {
    init_constants7();
    init_normalize_string2();
    init_assert_path2();
    init_util4();
  }
});

// https://deno.land/std@0.204.0/path/_common/relative.ts
var init_relative5 = __esm({
  "https://deno.land/std@0.204.0/path/_common/relative.ts"() {
    init_assert_path2();
  }
});

// https://deno.land/std@0.204.0/path/windows/relative.ts
var init_relative6 = __esm({
  "https://deno.land/std@0.204.0/path/windows/relative.ts"() {
    init_constants7();
    init_resolve5();
    init_relative5();
  }
});

// https://deno.land/std@0.204.0/path/_common/to_file_url.ts
var init_to_file_url5 = __esm({
  "https://deno.land/std@0.204.0/path/_common/to_file_url.ts"() {
  }
});

// https://deno.land/std@0.204.0/path/windows/to_file_url.ts
var init_to_file_url6 = __esm({
  "https://deno.land/std@0.204.0/path/windows/to_file_url.ts"() {
    init_to_file_url5();
    init_is_absolute4();
  }
});

// https://deno.land/std@0.204.0/path/windows/to_namespaced_path.ts
var init_to_namespaced_path4 = __esm({
  "https://deno.land/std@0.204.0/path/windows/to_namespaced_path.ts"() {
    init_constants7();
    init_util4();
    init_resolve5();
  }
});

// https://deno.land/std@0.204.0/path/_common/common.ts
var init_common5 = __esm({
  "https://deno.land/std@0.204.0/path/_common/common.ts"() {
  }
});

// https://deno.land/std@0.204.0/path/windows/separator.ts
var init_separator = __esm({
  "https://deno.land/std@0.204.0/path/windows/separator.ts"() {
  }
});

// https://deno.land/std@0.204.0/path/windows/common.ts
var init_common6 = __esm({
  "https://deno.land/std@0.204.0/path/windows/common.ts"() {
    init_common5();
    init_separator();
  }
});

// https://deno.land/std@0.204.0/path/_interface.ts
var init_interface = __esm({
  "https://deno.land/std@0.204.0/path/_interface.ts"() {
  }
});

// https://deno.land/std@0.204.0/path/_common/glob_to_reg_exp.ts
var init_glob_to_reg_exp2 = __esm({
  "https://deno.land/std@0.204.0/path/_common/glob_to_reg_exp.ts"() {
  }
});

// https://deno.land/std@0.204.0/path/posix/_util.ts
function isPosixPathSeparator4(code5) {
  return code5 === CHAR_FORWARD_SLASH2;
}
var init_util5 = __esm({
  "https://deno.land/std@0.204.0/path/posix/_util.ts"() {
    init_constants7();
  }
});

// https://deno.land/std@0.204.0/path/posix/normalize.ts
function normalize6(path3) {
  assertArg8(path3);
  const isAbsolute12 = isPosixPathSeparator4(path3.charCodeAt(0));
  const trailingSeparator = isPosixPathSeparator4(
    path3.charCodeAt(path3.length - 1)
  );
  path3 = normalizeString2(path3, !isAbsolute12, "/", isPosixPathSeparator4);
  if (path3.length === 0 && !isAbsolute12) path3 = ".";
  if (path3.length > 0 && trailingSeparator) path3 += "/";
  if (isAbsolute12) return `/${path3}`;
  return path3;
}
var init_normalize7 = __esm({
  "https://deno.land/std@0.204.0/path/posix/normalize.ts"() {
    init_normalize5();
    init_normalize_string2();
    init_util5();
  }
});

// https://deno.land/std@0.204.0/path/posix/join.ts
function join8(...paths) {
  if (paths.length === 0) return ".";
  let joined;
  for (let i6 = 0, len = paths.length; i6 < len; ++i6) {
    const path3 = paths[i6];
    assertPath2(path3);
    if (path3.length > 0) {
      if (!joined) joined = path3;
      else joined += `/${path3}`;
    }
  }
  if (!joined) return ".";
  return normalize6(joined);
}
var init_join5 = __esm({
  "https://deno.land/std@0.204.0/path/posix/join.ts"() {
    init_assert_path2();
    init_normalize7();
  }
});

// https://deno.land/std@0.204.0/path/posix/separator.ts
var init_separator2 = __esm({
  "https://deno.land/std@0.204.0/path/posix/separator.ts"() {
  }
});

// https://deno.land/std@0.204.0/path/_common/is_glob.ts
var init_is_glob3 = __esm({
  "https://deno.land/std@0.204.0/path/_common/is_glob.ts"() {
  }
});

// https://deno.land/std@0.204.0/path/posix/glob.ts
var init_glob2 = __esm({
  "https://deno.land/std@0.204.0/path/posix/glob.ts"() {
    init_glob_to_reg_exp2();
    init_normalize7();
    init_join5();
    init_separator2();
    init_is_glob3();
  }
});

// https://deno.land/std@0.204.0/path/windows/glob.ts
var init_glob3 = __esm({
  "https://deno.land/std@0.204.0/path/windows/glob.ts"() {
    init_glob_to_reg_exp2();
    init_normalize6();
    init_join4();
    init_separator();
    init_is_glob3();
  }
});

// https://deno.land/std@0.204.0/path/glob.ts
var init_glob4 = __esm({
  "https://deno.land/std@0.204.0/path/glob.ts"() {
    init_os2();
    init_glob2();
    init_glob3();
    init_is_glob3();
  }
});

// https://deno.land/std@0.204.0/path/windows/mod.ts
var init_mod9 = __esm({
  "https://deno.land/std@0.204.0/path/windows/mod.ts"() {
    init_basename6();
    init_dirname6();
    init_extname4();
    init_format7();
    init_from_file_url6();
    init_is_absolute4();
    init_join4();
    init_normalize6();
    init_parse5();
    init_relative6();
    init_resolve5();
    init_to_file_url6();
    init_to_namespaced_path4();
    init_common6();
    init_separator();
    init_interface();
    init_glob4();
  }
});

// https://deno.land/std@0.204.0/path/posix/basename.ts
var init_basename7 = __esm({
  "https://deno.land/std@0.204.0/path/posix/basename.ts"() {
    init_basename5();
    init_strip_trailing_separators2();
    init_util5();
  }
});

// https://deno.land/std@0.204.0/path/posix/dirname.ts
function dirname6(path3) {
  assertArg5(path3);
  let end = -1;
  let matchedNonSeparator = false;
  for (let i6 = path3.length - 1; i6 >= 1; --i6) {
    if (isPosixPathSeparator4(path3.charCodeAt(i6))) {
      if (matchedNonSeparator) {
        end = i6;
        break;
      }
    } else {
      matchedNonSeparator = true;
    }
  }
  if (end === -1) {
    return isPosixPathSeparator4(path3.charCodeAt(0)) ? "/" : ".";
  }
  return stripTrailingSeparators2(
    path3.slice(0, end),
    isPosixPathSeparator4
  );
}
var init_dirname7 = __esm({
  "https://deno.land/std@0.204.0/path/posix/dirname.ts"() {
    init_dirname5();
    init_strip_trailing_separators2();
    init_util5();
  }
});

// https://deno.land/std@0.204.0/path/posix/extname.ts
var init_extname5 = __esm({
  "https://deno.land/std@0.204.0/path/posix/extname.ts"() {
    init_constants7();
    init_assert_path2();
    init_util5();
  }
});

// https://deno.land/std@0.204.0/path/posix/format.ts
var init_format8 = __esm({
  "https://deno.land/std@0.204.0/path/posix/format.ts"() {
    init_format6();
  }
});

// https://deno.land/std@0.204.0/path/posix/from_file_url.ts
var init_from_file_url7 = __esm({
  "https://deno.land/std@0.204.0/path/posix/from_file_url.ts"() {
    init_from_file_url5();
  }
});

// https://deno.land/std@0.204.0/path/posix/is_absolute.ts
var init_is_absolute5 = __esm({
  "https://deno.land/std@0.204.0/path/posix/is_absolute.ts"() {
    init_assert_path2();
    init_util5();
  }
});

// https://deno.land/std@0.204.0/path/posix/parse.ts
var init_parse6 = __esm({
  "https://deno.land/std@0.204.0/path/posix/parse.ts"() {
    init_constants7();
    init_strip_trailing_separators2();
    init_assert_path2();
    init_util5();
  }
});

// https://deno.land/std@0.204.0/path/posix/resolve.ts
function resolve6(...pathSegments) {
  let resolvedPath = "";
  let resolvedAbsolute = false;
  for (let i6 = pathSegments.length - 1; i6 >= -1 && !resolvedAbsolute; i6--) {
    let path3;
    if (i6 >= 0) path3 = pathSegments[i6];
    else {
      const { Deno: Deno6 } = globalThis;
      if (typeof Deno6?.cwd !== "function") {
        throw new TypeError("Resolved a relative path without a CWD.");
      }
      path3 = Deno6.cwd();
    }
    assertPath2(path3);
    if (path3.length === 0) {
      continue;
    }
    resolvedPath = `${path3}/${resolvedPath}`;
    resolvedAbsolute = isPosixPathSeparator4(path3.charCodeAt(0));
  }
  resolvedPath = normalizeString2(
    resolvedPath,
    !resolvedAbsolute,
    "/",
    isPosixPathSeparator4
  );
  if (resolvedAbsolute) {
    if (resolvedPath.length > 0) return `/${resolvedPath}`;
    else return "/";
  } else if (resolvedPath.length > 0) return resolvedPath;
  else return ".";
}
var init_resolve6 = __esm({
  "https://deno.land/std@0.204.0/path/posix/resolve.ts"() {
    init_normalize_string2();
    init_assert_path2();
    init_util5();
  }
});

// https://deno.land/std@0.204.0/path/posix/relative.ts
var init_relative7 = __esm({
  "https://deno.land/std@0.204.0/path/posix/relative.ts"() {
    init_util5();
    init_resolve6();
    init_relative5();
  }
});

// https://deno.land/std@0.204.0/path/posix/to_file_url.ts
var init_to_file_url7 = __esm({
  "https://deno.land/std@0.204.0/path/posix/to_file_url.ts"() {
    init_to_file_url5();
    init_is_absolute5();
  }
});

// https://deno.land/std@0.204.0/path/posix/to_namespaced_path.ts
var init_to_namespaced_path5 = __esm({
  "https://deno.land/std@0.204.0/path/posix/to_namespaced_path.ts"() {
  }
});

// https://deno.land/std@0.204.0/path/posix/common.ts
var init_common7 = __esm({
  "https://deno.land/std@0.204.0/path/posix/common.ts"() {
    init_common5();
    init_separator2();
  }
});

// https://deno.land/std@0.204.0/path/posix/mod.ts
var init_mod10 = __esm({
  "https://deno.land/std@0.204.0/path/posix/mod.ts"() {
    init_basename7();
    init_dirname7();
    init_extname5();
    init_format8();
    init_from_file_url7();
    init_is_absolute5();
    init_join5();
    init_normalize7();
    init_parse6();
    init_relative7();
    init_resolve6();
    init_to_file_url7();
    init_to_namespaced_path5();
    init_common7();
    init_separator2();
    init_interface();
    init_glob4();
  }
});

// https://deno.land/std@0.204.0/path/basename.ts
var init_basename8 = __esm({
  "https://deno.land/std@0.204.0/path/basename.ts"() {
    init_os2();
    init_basename7();
    init_basename6();
  }
});

// https://deno.land/std@0.204.0/path/dirname.ts
function dirname7(path3) {
  return isWindows5 ? dirname5(path3) : dirname6(path3);
}
var init_dirname8 = __esm({
  "https://deno.land/std@0.204.0/path/dirname.ts"() {
    init_os2();
    init_dirname7();
    init_dirname6();
  }
});

// https://deno.land/std@0.204.0/path/extname.ts
var init_extname6 = __esm({
  "https://deno.land/std@0.204.0/path/extname.ts"() {
    init_os2();
    init_extname5();
    init_extname5();
  }
});

// https://deno.land/std@0.204.0/path/format.ts
var init_format9 = __esm({
  "https://deno.land/std@0.204.0/path/format.ts"() {
    init_os2();
    init_format8();
    init_format7();
  }
});

// https://deno.land/std@0.204.0/path/from_file_url.ts
var init_from_file_url8 = __esm({
  "https://deno.land/std@0.204.0/path/from_file_url.ts"() {
    init_os2();
    init_from_file_url7();
    init_from_file_url6();
  }
});

// https://deno.land/std@0.204.0/path/is_absolute.ts
var init_is_absolute6 = __esm({
  "https://deno.land/std@0.204.0/path/is_absolute.ts"() {
    init_os2();
    init_is_absolute5();
    init_is_absolute4();
  }
});

// https://deno.land/std@0.204.0/path/join.ts
function join9(...paths) {
  return isWindows5 ? join7(...paths) : join8(...paths);
}
var init_join6 = __esm({
  "https://deno.land/std@0.204.0/path/join.ts"() {
    init_os2();
    init_join5();
    init_join4();
  }
});

// https://deno.land/std@0.204.0/path/normalize.ts
var init_normalize8 = __esm({
  "https://deno.land/std@0.204.0/path/normalize.ts"() {
    init_os2();
    init_normalize7();
    init_normalize6();
  }
});

// https://deno.land/std@0.204.0/path/parse.ts
var init_parse7 = __esm({
  "https://deno.land/std@0.204.0/path/parse.ts"() {
    init_os2();
    init_parse6();
    init_parse5();
  }
});

// https://deno.land/std@0.204.0/path/relative.ts
var init_relative8 = __esm({
  "https://deno.land/std@0.204.0/path/relative.ts"() {
    init_os2();
    init_relative7();
    init_relative6();
  }
});

// https://deno.land/std@0.204.0/path/resolve.ts
function resolve7(...pathSegments) {
  return isWindows5 ? resolve5(...pathSegments) : resolve6(...pathSegments);
}
var init_resolve7 = __esm({
  "https://deno.land/std@0.204.0/path/resolve.ts"() {
    init_os2();
    init_resolve6();
    init_resolve5();
  }
});

// https://deno.land/std@0.204.0/path/to_file_url.ts
var init_to_file_url8 = __esm({
  "https://deno.land/std@0.204.0/path/to_file_url.ts"() {
    init_os2();
    init_to_file_url7();
    init_to_file_url6();
  }
});

// https://deno.land/std@0.204.0/path/to_namespaced_path.ts
var init_to_namespaced_path6 = __esm({
  "https://deno.land/std@0.204.0/path/to_namespaced_path.ts"() {
    init_os2();
    init_to_namespaced_path5();
    init_to_namespaced_path4();
  }
});

// https://deno.land/std@0.204.0/path/separator.ts
var init_separator3 = __esm({
  "https://deno.land/std@0.204.0/path/separator.ts"() {
    init_os2();
  }
});

// https://deno.land/std@0.204.0/path/common.ts
var init_common8 = __esm({
  "https://deno.land/std@0.204.0/path/common.ts"() {
    init_common5();
    init_separator3();
  }
});

// https://deno.land/std@0.204.0/path/mod.ts
var init_mod11 = __esm({
  "https://deno.land/std@0.204.0/path/mod.ts"() {
    init_os2();
    init_mod9();
    init_mod10();
    init_basename8();
    init_dirname8();
    init_extname6();
    init_format9();
    init_from_file_url8();
    init_is_absolute6();
    init_join6();
    init_normalize8();
    init_parse7();
    init_relative8();
    init_resolve7();
    init_to_file_url8();
    init_to_namespaced_path6();
    init_common8();
    init_separator3();
    init_interface();
    init_glob4();
  }
});

// https://deno.land/std@0.217.0/assert/assertion_error.ts
var AssertionError4;
var init_assertion_error3 = __esm({
  "https://deno.land/std@0.217.0/assert/assertion_error.ts"() {
    AssertionError4 = class extends Error {
      /** Constructs a new instance. */
      constructor(message) {
        super(message);
        this.name = "AssertionError";
      }
    };
  }
});

// https://deno.land/std@0.217.0/assert/assert.ts
function assert5(expr, msg5 = "") {
  if (!expr) {
    throw new AssertionError4(msg5);
  }
}
var init_assert4 = __esm({
  "https://deno.land/std@0.217.0/assert/assert.ts"() {
    init_assertion_error3();
  }
});

// https://deno.land/std@0.217.0/io/buf_reader.ts
var DEFAULT_BUF_SIZE, MIN_BUF_SIZE, MAX_CONSECUTIVE_EMPTY_READS, CR, LF2, BufferFullError, PartialReadError, BufReader;
var init_buf_reader = __esm({
  "https://deno.land/std@0.217.0/io/buf_reader.ts"() {
    init_assert4();
    init_copy2();
    DEFAULT_BUF_SIZE = 4096;
    MIN_BUF_SIZE = 16;
    MAX_CONSECUTIVE_EMPTY_READS = 100;
    CR = "\r".charCodeAt(0);
    LF2 = "\n".charCodeAt(0);
    BufferFullError = class extends Error {
      constructor(partial) {
        super("Buffer full");
        this.partial = partial;
      }
      name = "BufferFullError";
    };
    PartialReadError = class extends Error {
      name = "PartialReadError";
      partial;
      constructor() {
        super("Encountered UnexpectedEof, data only partially read");
      }
    };
    BufReader = class _BufReader {
      #buf;
      #rd;
      // Reader provided by caller.
      #r = 0;
      // buf read position.
      #w = 0;
      // buf write position.
      #eof = false;
      // private lastByte: number;
      // private lastCharSize: number;
      /** return new BufReader unless r is BufReader */
      static create(r5, size = DEFAULT_BUF_SIZE) {
        return r5 instanceof _BufReader ? r5 : new _BufReader(r5, size);
      }
      constructor(rd, size = DEFAULT_BUF_SIZE) {
        if (size < MIN_BUF_SIZE) {
          size = MIN_BUF_SIZE;
        }
        this.#reset(new Uint8Array(size), rd);
      }
      /** Returns the size of the underlying buffer in bytes. */
      size() {
        return this.#buf.byteLength;
      }
      buffered() {
        return this.#w - this.#r;
      }
      // Reads a new chunk into the buffer.
      #fill = async () => {
        if (this.#r > 0) {
          this.#buf.copyWithin(0, this.#r, this.#w);
          this.#w -= this.#r;
          this.#r = 0;
        }
        if (this.#w >= this.#buf.byteLength) {
          throw Error("bufio: tried to fill full buffer");
        }
        for (let i6 = MAX_CONSECUTIVE_EMPTY_READS; i6 > 0; i6--) {
          const rr = await this.#rd.read(this.#buf.subarray(this.#w));
          if (rr === null) {
            this.#eof = true;
            return;
          }
          assert5(rr >= 0, "negative read");
          this.#w += rr;
          if (rr > 0) {
            return;
          }
        }
        throw new Error(
          `No progress after ${MAX_CONSECUTIVE_EMPTY_READS} read() calls`
        );
      };
      /** Discards any buffered data, resets all state, and switches
       * the buffered reader to read from r.
       */
      reset(r5) {
        this.#reset(this.#buf, r5);
      }
      #reset = (buf, rd) => {
        this.#buf = buf;
        this.#rd = rd;
        this.#eof = false;
      };
      /** reads data into p.
       * It returns the number of bytes read into p.
       * The bytes are taken from at most one Read on the underlying Reader,
       * hence n may be less than len(p).
       * To read exactly len(p) bytes, use io.ReadFull(b, p).
       */
      async read(p5) {
        let rr = p5.byteLength;
        if (p5.byteLength === 0) return rr;
        if (this.#r === this.#w) {
          if (p5.byteLength >= this.#buf.byteLength) {
            const rr2 = await this.#rd.read(p5);
            const nread = rr2 ?? 0;
            assert5(nread >= 0, "negative read");
            return rr2;
          }
          this.#r = 0;
          this.#w = 0;
          rr = await this.#rd.read(this.#buf);
          if (rr === 0 || rr === null) return rr;
          assert5(rr >= 0, "negative read");
          this.#w += rr;
        }
        const copied = copy3(this.#buf.subarray(this.#r, this.#w), p5, 0);
        this.#r += copied;
        return copied;
      }
      /** reads exactly `p.length` bytes into `p`.
       *
       * If successful, `p` is returned.
       *
       * If the end of the underlying stream has been reached, and there are no more
       * bytes available in the buffer, `readFull()` returns `null` instead.
       *
       * An error is thrown if some bytes could be read, but not enough to fill `p`
       * entirely before the underlying stream reported an error or EOF. Any error
       * thrown will have a `partial` property that indicates the slice of the
       * buffer that has been successfully filled with data.
       *
       * Ported from https://golang.org/pkg/io/#ReadFull
       */
      async readFull(p5) {
        let bytesRead = 0;
        while (bytesRead < p5.length) {
          try {
            const rr = await this.read(p5.subarray(bytesRead));
            if (rr === null) {
              if (bytesRead === 0) {
                return null;
              } else {
                throw new PartialReadError();
              }
            }
            bytesRead += rr;
          } catch (err2) {
            if (err2 instanceof PartialReadError) {
              err2.partial = p5.subarray(0, bytesRead);
            }
            throw err2;
          }
        }
        return p5;
      }
      /** Returns the next byte [0, 255] or `null`. */
      async readByte() {
        while (this.#r === this.#w) {
          if (this.#eof) return null;
          await this.#fill();
        }
        const c6 = this.#buf[this.#r];
        this.#r++;
        return c6;
      }
      /** readString() reads until the first occurrence of delim in the input,
       * returning a string containing the data up to and including the delimiter.
       * If ReadString encounters an error before finding a delimiter,
       * it returns the data read before the error and the error itself
       * (often `null`).
       * ReadString returns err !== null if and only if the returned data does not end
       * in delim.
       * For simple uses, a Scanner may be more convenient.
       */
      async readString(delim) {
        if (delim.length !== 1) {
          throw new Error("Delimiter should be a single character");
        }
        const buffer2 = await this.readSlice(delim.charCodeAt(0));
        if (buffer2 === null) return null;
        return new TextDecoder().decode(buffer2);
      }
      /** `readLine()` is a low-level line-reading primitive. Most callers should
       * use `readString('\n')` instead or use a Scanner.
       *
       * `readLine()` tries to return a single line, not including the end-of-line
       * bytes. If the line was too long for the buffer then `more` is set and the
       * beginning of the line is returned. The rest of the line will be returned
       * from future calls. `more` will be false when returning the last fragment
       * of the line. The returned buffer is only valid until the next call to
       * `readLine()`.
       *
       * The text returned from ReadLine does not include the line end ("\r\n" or
       * "\n").
       *
       * When the end of the underlying stream is reached, the final bytes in the
       * stream are returned. No indication or error is given if the input ends
       * without a final line end. When there are no more trailing bytes to read,
       * `readLine()` returns `null`.
       *
       * Calling `unreadByte()` after `readLine()` will always unread the last byte
       * read (possibly a character belonging to the line end) even if that byte is
       * not part of the line returned by `readLine()`.
       */
      async readLine() {
        let line = null;
        try {
          line = await this.readSlice(LF2);
        } catch (err2) {
          let partial;
          if (err2 instanceof PartialReadError) {
            partial = err2.partial;
            assert5(
              partial instanceof Uint8Array,
              "bufio: caught error from `readSlice()` without `partial` property"
            );
          }
          if (!(err2 instanceof BufferFullError)) {
            throw err2;
          }
          partial = err2.partial;
          if (!this.#eof && partial && partial.byteLength > 0 && partial[partial.byteLength - 1] === CR) {
            assert5(this.#r > 0, "bufio: tried to rewind past start of buffer");
            this.#r--;
            partial = partial.subarray(0, partial.byteLength - 1);
          }
          if (partial) {
            return { line: partial, more: !this.#eof };
          }
        }
        if (line === null) {
          return null;
        }
        if (line.byteLength === 0) {
          return { line, more: false };
        }
        if (line[line.byteLength - 1] === LF2) {
          let drop = 1;
          if (line.byteLength > 1 && line[line.byteLength - 2] === CR) {
            drop = 2;
          }
          line = line.subarray(0, line.byteLength - drop);
        }
        return { line, more: false };
      }
      /** `readSlice()` reads until the first occurrence of `delim` in the input,
       * returning a slice pointing at the bytes in the buffer. The bytes stop
       * being valid at the next read.
       *
       * If `readSlice()` encounters an error before finding a delimiter, or the
       * buffer fills without finding a delimiter, it throws an error with a
       * `partial` property that contains the entire buffer.
       *
       * If `readSlice()` encounters the end of the underlying stream and there are
       * any bytes left in the buffer, the rest of the buffer is returned. In other
       * words, EOF is always treated as a delimiter. Once the buffer is empty,
       * it returns `null`.
       *
       * Because the data returned from `readSlice()` will be overwritten by the
       * next I/O operation, most clients should use `readString()` instead.
       */
      async readSlice(delim) {
        let s5 = 0;
        let slice2;
        while (true) {
          let i6 = this.#buf.subarray(this.#r + s5, this.#w).indexOf(delim);
          if (i6 >= 0) {
            i6 += s5;
            slice2 = this.#buf.subarray(this.#r, this.#r + i6 + 1);
            this.#r += i6 + 1;
            break;
          }
          if (this.#eof) {
            if (this.#r === this.#w) {
              return null;
            }
            slice2 = this.#buf.subarray(this.#r, this.#w);
            this.#r = this.#w;
            break;
          }
          if (this.buffered() >= this.#buf.byteLength) {
            this.#r = this.#w;
            const oldbuf = this.#buf;
            const newbuf = this.#buf.slice(0);
            this.#buf = newbuf;
            throw new BufferFullError(oldbuf);
          }
          s5 = this.#w - this.#r;
          try {
            await this.#fill();
          } catch (err2) {
            if (err2 instanceof PartialReadError) {
              err2.partial = slice2;
            }
            throw err2;
          }
        }
        return slice2;
      }
      /** `peek()` returns the next `n` bytes without advancing the reader. The
       * bytes stop being valid at the next read call.
       *
       * When the end of the underlying stream is reached, but there are unread
       * bytes left in the buffer, those bytes are returned. If there are no bytes
       * left in the buffer, it returns `null`.
       *
       * If an error is encountered before `n` bytes are available, `peek()` throws
       * an error with the `partial` property set to a slice of the buffer that
       * contains the bytes that were available before the error occurred.
       */
      async peek(n5) {
        if (n5 < 0) {
          throw Error("negative count");
        }
        let avail = this.#w - this.#r;
        while (avail < n5 && avail < this.#buf.byteLength && !this.#eof) {
          try {
            await this.#fill();
          } catch (err2) {
            if (err2 instanceof PartialReadError) {
              err2.partial = this.#buf.subarray(this.#r, this.#w);
            }
            throw err2;
          }
          avail = this.#w - this.#r;
        }
        if (avail === 0 && this.#eof) {
          return null;
        } else if (avail < n5 && this.#eof) {
          return this.#buf.subarray(this.#r, this.#r + avail);
        } else if (avail < n5) {
          throw new BufferFullError(this.#buf.subarray(this.#r, this.#w));
        }
        return this.#buf.subarray(this.#r, this.#r + n5);
      }
    };
  }
});

// https://deno.land/std@0.217.0/io/buf_writer.ts
var init_buf_writer = __esm({
  "https://deno.land/std@0.217.0/io/buf_writer.ts"() {
    init_copy2();
  }
});

// https://deno.land/std@0.217.0/io/buffer.ts
var MIN_READ, MAX_SIZE;
var init_buffer = __esm({
  "https://deno.land/std@0.217.0/io/buffer.ts"() {
    init_assert4();
    init_copy2();
    MIN_READ = 32 * 1024;
    MAX_SIZE = 2 ** 32 - 2;
  }
});

// https://deno.land/std@0.217.0/io/_constants.ts
var DEFAULT_BUFFER_SIZE2;
var init_constants8 = __esm({
  "https://deno.land/std@0.217.0/io/_constants.ts"() {
    DEFAULT_BUFFER_SIZE2 = 32 * 1024;
  }
});

// https://deno.land/std@0.217.0/io/copy.ts
var init_copy3 = __esm({
  "https://deno.land/std@0.217.0/io/copy.ts"() {
    init_constants8();
  }
});

// https://deno.land/std@0.217.0/io/copy_n.ts
var DEFAULT_BUFFER_SIZE3;
var init_copy_n = __esm({
  "https://deno.land/std@0.217.0/io/copy_n.ts"() {
    init_assert4();
    DEFAULT_BUFFER_SIZE3 = 32 * 1024;
  }
});

// https://deno.land/std@0.217.0/io/iterate_reader.ts
var init_iterate_reader = __esm({
  "https://deno.land/std@0.217.0/io/iterate_reader.ts"() {
    init_constants8();
  }
});

// https://deno.land/std@0.217.0/io/limited_reader.ts
var init_limited_reader = __esm({
  "https://deno.land/std@0.217.0/io/limited_reader.ts"() {
  }
});

// https://deno.land/std@0.217.0/io/multi_reader.ts
var init_multi_reader = __esm({
  "https://deno.land/std@0.217.0/io/multi_reader.ts"() {
  }
});

// https://deno.land/std@0.217.0/io/read_all.ts
var init_read_all = __esm({
  "https://deno.land/std@0.217.0/io/read_all.ts"() {
    init_concat();
    init_constants8();
  }
});

// https://deno.land/std@0.217.0/io/read_delim.ts
var init_read_delim = __esm({
  "https://deno.land/std@0.217.0/io/read_delim.ts"() {
    init_concat();
  }
});

// https://deno.land/std@0.217.0/io/read_short.ts
var init_read_short = __esm({
  "https://deno.land/std@0.217.0/io/read_short.ts"() {
  }
});

// https://deno.land/std@0.217.0/io/read_int.ts
var init_read_int = __esm({
  "https://deno.land/std@0.217.0/io/read_int.ts"() {
    init_read_short();
  }
});

// https://deno.land/std@0.217.0/io/read_lines.ts
async function* readLines(reader, decoderOpts) {
  const bufReader = new BufReader(reader);
  let chunks = [];
  const decoder3 = new TextDecoder(decoderOpts?.encoding, decoderOpts);
  while (true) {
    const res = await bufReader.readLine();
    if (!res) {
      if (chunks.length > 0) {
        yield decoder3.decode(concat(chunks));
      }
      break;
    }
    chunks.push(res.line);
    if (!res.more) {
      yield decoder3.decode(concat(chunks));
      chunks = [];
    }
  }
}
var init_read_lines = __esm({
  "https://deno.land/std@0.217.0/io/read_lines.ts"() {
    init_buf_reader();
    init_concat();
  }
});

// https://deno.land/std@0.217.0/io/read_long.ts
var MAX_SAFE_INTEGER;
var init_read_long = __esm({
  "https://deno.land/std@0.217.0/io/read_long.ts"() {
    init_read_int();
    MAX_SAFE_INTEGER = BigInt(Number.MAX_SAFE_INTEGER);
  }
});

// https://deno.land/std@0.217.0/io/read_range.ts
var DEFAULT_BUFFER_SIZE4;
var init_read_range = __esm({
  "https://deno.land/std@0.217.0/io/read_range.ts"() {
    init_copy2();
    init_assert4();
    DEFAULT_BUFFER_SIZE4 = 32 * 1024;
  }
});

// https://deno.land/std@0.217.0/io/read_string_delim.ts
var init_read_string_delim = __esm({
  "https://deno.land/std@0.217.0/io/read_string_delim.ts"() {
    init_read_delim();
  }
});

// https://deno.land/std@0.217.0/io/write_all.ts
var init_write_all2 = __esm({
  "https://deno.land/std@0.217.0/io/write_all.ts"() {
  }
});

// https://deno.land/std@0.217.0/io/reader_from_stream_reader.ts
var init_reader_from_stream_reader = __esm({
  "https://deno.land/std@0.217.0/io/reader_from_stream_reader.ts"() {
    init_buffer();
    init_write_all2();
  }
});

// https://deno.land/std@0.217.0/io/slice_long_to_bytes.ts
var init_slice_long_to_bytes = __esm({
  "https://deno.land/std@0.217.0/io/slice_long_to_bytes.ts"() {
  }
});

// https://deno.land/std@0.217.0/io/string_reader.ts
var init_string_reader = __esm({
  "https://deno.land/std@0.217.0/io/string_reader.ts"() {
    init_buffer();
  }
});

// https://deno.land/std@0.217.0/io/string_writer.ts
var decoder;
var init_string_writer = __esm({
  "https://deno.land/std@0.217.0/io/string_writer.ts"() {
    decoder = new TextDecoder();
  }
});

// https://deno.land/std@0.217.0/io/_common.ts
var init_common9 = __esm({
  "https://deno.land/std@0.217.0/io/_common.ts"() {
  }
});

// https://deno.land/std@0.217.0/io/to_readable_stream.ts
var init_to_readable_stream = __esm({
  "https://deno.land/std@0.217.0/io/to_readable_stream.ts"() {
    init_constants8();
    init_common9();
  }
});

// https://deno.land/std@0.217.0/io/to_writable_stream.ts
var init_to_writable_stream = __esm({
  "https://deno.land/std@0.217.0/io/to_writable_stream.ts"() {
    init_write_all2();
    init_common9();
  }
});

// https://deno.land/std@0.217.0/io/types.ts
var init_types6 = __esm({
  "https://deno.land/std@0.217.0/io/types.ts"() {
  }
});

// https://deno.land/std@0.217.0/io/mod.ts
var init_mod12 = __esm({
  "https://deno.land/std@0.217.0/io/mod.ts"() {
    init_buf_reader();
    init_buf_writer();
    init_buffer();
    init_copy3();
    init_copy_n();
    init_iterate_reader();
    init_limited_reader();
    init_multi_reader();
    init_read_all();
    init_read_delim();
    init_read_int();
    init_read_lines();
    init_read_long();
    init_read_range();
    init_read_short();
    init_read_string_delim();
    init_reader_from_stream_reader();
    init_slice_long_to_bytes();
    init_string_reader();
    init_string_writer();
    init_to_readable_stream();
    init_to_writable_stream();
    init_types6();
    init_write_all2();
  }
});

// https://deno.land/std@0.217.0/fs/exists.ts
async function exists(path3, options) {
  try {
    const stat = await Deno.stat(path3);
    if (options && (options.isReadable || options.isDirectory || options.isFile)) {
      if (options.isDirectory && options.isFile) {
        throw new TypeError(
          "ExistsOptions.options.isDirectory and ExistsOptions.options.isFile must not be true together."
        );
      }
      if (options.isDirectory && !stat.isDirectory || options.isFile && !stat.isFile) {
        return false;
      }
      if (options.isReadable) {
        if (stat.mode === null) {
          return true;
        }
        if (Deno.uid() === stat.uid) {
          return (stat.mode & 256) === 256;
        } else if (Deno.gid() === stat.gid) {
          return (stat.mode & 32) === 32;
        }
        return (stat.mode & 4) === 4;
      }
    }
    return true;
  } catch (error2) {
    if (error2 instanceof Deno.errors.NotFound) {
      return false;
    }
    if (error2 instanceof Deno.errors.PermissionDenied) {
      if ((await Deno.permissions.query({ name: "read", path: path3 })).state === "granted") {
        return !options?.isReadable;
      }
    }
    throw error2;
  }
}
function existsSync3(path3, options) {
  try {
    const stat = Deno.statSync(path3);
    if (options && (options.isReadable || options.isDirectory || options.isFile)) {
      if (options.isDirectory && options.isFile) {
        throw new TypeError(
          "ExistsOptions.options.isDirectory and ExistsOptions.options.isFile must not be true together."
        );
      }
      if (options.isDirectory && !stat.isDirectory || options.isFile && !stat.isFile) {
        return false;
      }
      if (options.isReadable) {
        if (stat.mode === null) {
          return true;
        }
        if (Deno.uid() === stat.uid) {
          return (stat.mode & 256) === 256;
        } else if (Deno.gid() === stat.gid) {
          return (stat.mode & 32) === 32;
        }
        return (stat.mode & 4) === 4;
      }
    }
    return true;
  } catch (error2) {
    if (error2 instanceof Deno.errors.NotFound) {
      return false;
    }
    if (error2 instanceof Deno.errors.PermissionDenied) {
      if (Deno.permissions.querySync({ name: "read", path: path3 }).state === "granted") {
        return !options?.isReadable;
      }
    }
    throw error2;
  }
}
var init_exists3 = __esm({
  "https://deno.land/std@0.217.0/fs/exists.ts"() {
  }
});

// https://deno.land/std@0.217.0/path/_os.ts
var osType2, isWindows6;
var init_os3 = __esm({
  "https://deno.land/std@0.217.0/path/_os.ts"() {
    osType2 = (() => {
      const { Deno: Deno6 } = globalThis;
      if (typeof Deno6?.build?.os === "string") {
        return Deno6.build.os;
      }
      const { navigator: navigator2 } = globalThis;
      if (navigator2?.appVersion?.includes?.("Win")) {
        return "windows";
      }
      return "linux";
    })();
    isWindows6 = osType2 === "windows";
  }
});

// https://deno.land/std@0.217.0/path/_common/assert_path.ts
function assertPath3(path3) {
  if (typeof path3 !== "string") {
    throw new TypeError(
      `Path must be a string. Received ${JSON.stringify(path3)}`
    );
  }
}
var init_assert_path3 = __esm({
  "https://deno.land/std@0.217.0/path/_common/assert_path.ts"() {
  }
});

// https://deno.land/std@0.217.0/path/_common/basename.ts
function stripSuffix3(name2, suffix) {
  if (suffix.length >= name2.length) {
    return name2;
  }
  const lenDiff = name2.length - suffix.length;
  for (let i6 = suffix.length - 1; i6 >= 0; --i6) {
    if (name2.charCodeAt(lenDiff + i6) !== suffix.charCodeAt(i6)) {
      return name2;
    }
  }
  return name2.slice(0, -suffix.length);
}
function lastPathSegment3(path3, isSep, start = 0) {
  let matchedNonSeparator = false;
  let end = path3.length;
  for (let i6 = path3.length - 1; i6 >= start; --i6) {
    if (isSep(path3.charCodeAt(i6))) {
      if (matchedNonSeparator) {
        start = i6 + 1;
        break;
      }
    } else if (!matchedNonSeparator) {
      matchedNonSeparator = true;
      end = i6 + 1;
    }
  }
  return path3.slice(start, end);
}
function assertArgs5(path3, suffix) {
  assertPath3(path3);
  if (path3.length === 0) return path3;
  if (typeof suffix !== "string") {
    throw new TypeError(
      `Suffix must be a string. Received ${JSON.stringify(suffix)}`
    );
  }
}
var init_basename9 = __esm({
  "https://deno.land/std@0.217.0/path/_common/basename.ts"() {
    init_assert_path3();
  }
});

// https://deno.land/std@0.217.0/path/_common/strip_trailing_separators.ts
function stripTrailingSeparators3(segment, isSep) {
  if (segment.length <= 1) {
    return segment;
  }
  let end = segment.length;
  for (let i6 = segment.length - 1; i6 > 0; i6--) {
    if (isSep(segment.charCodeAt(i6))) {
      end = i6;
    } else {
      break;
    }
  }
  return segment.slice(0, end);
}
var init_strip_trailing_separators3 = __esm({
  "https://deno.land/std@0.217.0/path/_common/strip_trailing_separators.ts"() {
  }
});

// https://deno.land/std@0.217.0/path/_common/constants.ts
var CHAR_UPPERCASE_A3, CHAR_LOWERCASE_A3, CHAR_UPPERCASE_Z3, CHAR_LOWERCASE_Z3, CHAR_DOT3, CHAR_FORWARD_SLASH3, CHAR_BACKWARD_SLASH3, CHAR_COLON5;
var init_constants9 = __esm({
  "https://deno.land/std@0.217.0/path/_common/constants.ts"() {
    CHAR_UPPERCASE_A3 = 65;
    CHAR_LOWERCASE_A3 = 97;
    CHAR_UPPERCASE_Z3 = 90;
    CHAR_LOWERCASE_Z3 = 122;
    CHAR_DOT3 = 46;
    CHAR_FORWARD_SLASH3 = 47;
    CHAR_BACKWARD_SLASH3 = 92;
    CHAR_COLON5 = 58;
  }
});

// https://deno.land/std@0.217.0/path/posix/_util.ts
function isPosixPathSeparator5(code5) {
  return code5 === CHAR_FORWARD_SLASH3;
}
var init_util6 = __esm({
  "https://deno.land/std@0.217.0/path/posix/_util.ts"() {
    init_constants9();
  }
});

// https://deno.land/std@0.217.0/path/posix/basename.ts
function basename7(path3, suffix = "") {
  assertArgs5(path3, suffix);
  const lastSegment = lastPathSegment3(path3, isPosixPathSeparator5);
  const strippedSegment = stripTrailingSeparators3(
    lastSegment,
    isPosixPathSeparator5
  );
  return suffix ? stripSuffix3(strippedSegment, suffix) : strippedSegment;
}
var init_basename10 = __esm({
  "https://deno.land/std@0.217.0/path/posix/basename.ts"() {
    init_basename9();
    init_strip_trailing_separators3();
    init_util6();
  }
});

// https://deno.land/std@0.217.0/path/windows/_util.ts
function isPathSeparator3(code5) {
  return code5 === CHAR_FORWARD_SLASH3 || code5 === CHAR_BACKWARD_SLASH3;
}
function isWindowsDeviceRoot3(code5) {
  return code5 >= CHAR_LOWERCASE_A3 && code5 <= CHAR_LOWERCASE_Z3 || code5 >= CHAR_UPPERCASE_A3 && code5 <= CHAR_UPPERCASE_Z3;
}
var init_util7 = __esm({
  "https://deno.land/std@0.217.0/path/windows/_util.ts"() {
    init_constants9();
  }
});

// https://deno.land/std@0.217.0/path/windows/basename.ts
function basename8(path3, suffix = "") {
  assertArgs5(path3, suffix);
  let start = 0;
  if (path3.length >= 2) {
    const drive = path3.charCodeAt(0);
    if (isWindowsDeviceRoot3(drive)) {
      if (path3.charCodeAt(1) === CHAR_COLON5) start = 2;
    }
  }
  const lastSegment = lastPathSegment3(path3, isPathSeparator3, start);
  const strippedSegment = stripTrailingSeparators3(lastSegment, isPathSeparator3);
  return suffix ? stripSuffix3(strippedSegment, suffix) : strippedSegment;
}
var init_basename11 = __esm({
  "https://deno.land/std@0.217.0/path/windows/basename.ts"() {
    init_basename9();
    init_constants9();
    init_strip_trailing_separators3();
    init_util7();
  }
});

// https://deno.land/std@0.217.0/path/basename.ts
function basename9(path3, suffix = "") {
  return isWindows6 ? basename8(path3, suffix) : basename7(path3, suffix);
}
var init_basename12 = __esm({
  "https://deno.land/std@0.217.0/path/basename.ts"() {
    init_os3();
    init_basename10();
    init_basename11();
  }
});

// https://deno.land/std@0.217.0/path/_common/normalize.ts
function assertArg9(path3) {
  assertPath3(path3);
  if (path3.length === 0) return ".";
}
var init_normalize9 = __esm({
  "https://deno.land/std@0.217.0/path/_common/normalize.ts"() {
    init_assert_path3();
  }
});

// https://deno.land/std@0.217.0/path/_common/normalize_string.ts
function normalizeString3(path3, allowAboveRoot, separator, isPathSeparator5) {
  let res = "";
  let lastSegmentLength = 0;
  let lastSlash = -1;
  let dots = 0;
  let code5;
  for (let i6 = 0, len = path3.length; i6 <= len; ++i6) {
    if (i6 < len) code5 = path3.charCodeAt(i6);
    else if (isPathSeparator5(code5)) break;
    else code5 = CHAR_FORWARD_SLASH3;
    if (isPathSeparator5(code5)) {
      if (lastSlash === i6 - 1 || dots === 1) {
      } else if (lastSlash !== i6 - 1 && dots === 2) {
        if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== CHAR_DOT3 || res.charCodeAt(res.length - 2) !== CHAR_DOT3) {
          if (res.length > 2) {
            const lastSlashIndex = res.lastIndexOf(separator);
            if (lastSlashIndex === -1) {
              res = "";
              lastSegmentLength = 0;
            } else {
              res = res.slice(0, lastSlashIndex);
              lastSegmentLength = res.length - 1 - res.lastIndexOf(separator);
            }
            lastSlash = i6;
            dots = 0;
            continue;
          } else if (res.length === 2 || res.length === 1) {
            res = "";
            lastSegmentLength = 0;
            lastSlash = i6;
            dots = 0;
            continue;
          }
        }
        if (allowAboveRoot) {
          if (res.length > 0) res += `${separator}..`;
          else res = "..";
          lastSegmentLength = 2;
        }
      } else {
        if (res.length > 0) res += separator + path3.slice(lastSlash + 1, i6);
        else res = path3.slice(lastSlash + 1, i6);
        lastSegmentLength = i6 - lastSlash - 1;
      }
      lastSlash = i6;
      dots = 0;
    } else if (code5 === CHAR_DOT3 && dots !== -1) {
      ++dots;
    } else {
      dots = -1;
    }
  }
  return res;
}
var init_normalize_string3 = __esm({
  "https://deno.land/std@0.217.0/path/_common/normalize_string.ts"() {
    init_constants9();
  }
});

// https://deno.land/std@0.217.0/path/posix/normalize.ts
function normalize7(path3) {
  assertArg9(path3);
  const isAbsolute12 = isPosixPathSeparator5(path3.charCodeAt(0));
  const trailingSeparator = isPosixPathSeparator5(
    path3.charCodeAt(path3.length - 1)
  );
  path3 = normalizeString3(path3, !isAbsolute12, "/", isPosixPathSeparator5);
  if (path3.length === 0 && !isAbsolute12) path3 = ".";
  if (path3.length > 0 && trailingSeparator) path3 += "/";
  if (isAbsolute12) return `/${path3}`;
  return path3;
}
var init_normalize10 = __esm({
  "https://deno.land/std@0.217.0/path/posix/normalize.ts"() {
    init_normalize9();
    init_normalize_string3();
    init_util6();
  }
});

// https://deno.land/std@0.217.0/path/posix/join.ts
function join10(...paths) {
  if (paths.length === 0) return ".";
  let joined;
  for (let i6 = 0, len = paths.length; i6 < len; ++i6) {
    const path3 = paths[i6];
    assertPath3(path3);
    if (path3.length > 0) {
      if (!joined) joined = path3;
      else joined += `/${path3}`;
    }
  }
  if (!joined) return ".";
  return normalize7(joined);
}
var init_join7 = __esm({
  "https://deno.land/std@0.217.0/path/posix/join.ts"() {
    init_assert_path3();
    init_normalize10();
  }
});

// https://deno.land/std@0.217.0/path/windows/normalize.ts
function normalize8(path3) {
  assertArg9(path3);
  const len = path3.length;
  let rootEnd = 0;
  let device;
  let isAbsolute12 = false;
  const code5 = path3.charCodeAt(0);
  if (len > 1) {
    if (isPathSeparator3(code5)) {
      isAbsolute12 = true;
      if (isPathSeparator3(path3.charCodeAt(1))) {
        let j3 = 2;
        let last = j3;
        for (; j3 < len; ++j3) {
          if (isPathSeparator3(path3.charCodeAt(j3))) break;
        }
        if (j3 < len && j3 !== last) {
          const firstPart = path3.slice(last, j3);
          last = j3;
          for (; j3 < len; ++j3) {
            if (!isPathSeparator3(path3.charCodeAt(j3))) break;
          }
          if (j3 < len && j3 !== last) {
            last = j3;
            for (; j3 < len; ++j3) {
              if (isPathSeparator3(path3.charCodeAt(j3))) break;
            }
            if (j3 === len) {
              return `\\\\${firstPart}\\${path3.slice(last)}\\`;
            } else if (j3 !== last) {
              device = `\\\\${firstPart}\\${path3.slice(last, j3)}`;
              rootEnd = j3;
            }
          }
        }
      } else {
        rootEnd = 1;
      }
    } else if (isWindowsDeviceRoot3(code5)) {
      if (path3.charCodeAt(1) === CHAR_COLON5) {
        device = path3.slice(0, 2);
        rootEnd = 2;
        if (len > 2) {
          if (isPathSeparator3(path3.charCodeAt(2))) {
            isAbsolute12 = true;
            rootEnd = 3;
          }
        }
      }
    }
  } else if (isPathSeparator3(code5)) {
    return "\\";
  }
  let tail;
  if (rootEnd < len) {
    tail = normalizeString3(
      path3.slice(rootEnd),
      !isAbsolute12,
      "\\",
      isPathSeparator3
    );
  } else {
    tail = "";
  }
  if (tail.length === 0 && !isAbsolute12) tail = ".";
  if (tail.length > 0 && isPathSeparator3(path3.charCodeAt(len - 1))) {
    tail += "\\";
  }
  if (device === void 0) {
    if (isAbsolute12) {
      if (tail.length > 0) return `\\${tail}`;
      else return "\\";
    } else if (tail.length > 0) {
      return tail;
    } else {
      return "";
    }
  } else if (isAbsolute12) {
    if (tail.length > 0) return `${device}\\${tail}`;
    else return `${device}\\`;
  } else if (tail.length > 0) {
    return device + tail;
  } else {
    return device;
  }
}
var init_normalize11 = __esm({
  "https://deno.land/std@0.217.0/path/windows/normalize.ts"() {
    init_normalize9();
    init_constants9();
    init_normalize_string3();
    init_util7();
  }
});

// https://deno.land/std@0.217.0/path/windows/join.ts
function join11(...paths) {
  if (paths.length === 0) return ".";
  let joined;
  let firstPart = null;
  for (let i6 = 0; i6 < paths.length; ++i6) {
    const path3 = paths[i6];
    assertPath3(path3);
    if (path3.length > 0) {
      if (joined === void 0) joined = firstPart = path3;
      else joined += `\\${path3}`;
    }
  }
  if (joined === void 0) return ".";
  let needsReplace = true;
  let slashCount = 0;
  assert5(firstPart !== null);
  if (isPathSeparator3(firstPart.charCodeAt(0))) {
    ++slashCount;
    const firstLen = firstPart.length;
    if (firstLen > 1) {
      if (isPathSeparator3(firstPart.charCodeAt(1))) {
        ++slashCount;
        if (firstLen > 2) {
          if (isPathSeparator3(firstPart.charCodeAt(2))) ++slashCount;
          else {
            needsReplace = false;
          }
        }
      }
    }
  }
  if (needsReplace) {
    for (; slashCount < joined.length; ++slashCount) {
      if (!isPathSeparator3(joined.charCodeAt(slashCount))) break;
    }
    if (slashCount >= 2) joined = `\\${joined.slice(slashCount)}`;
  }
  return normalize8(joined);
}
var init_join8 = __esm({
  "https://deno.land/std@0.217.0/path/windows/join.ts"() {
    init_assert4();
    init_assert_path3();
    init_util7();
    init_normalize11();
  }
});

// https://deno.land/std@0.217.0/path/join.ts
function join12(...paths) {
  return isWindows6 ? join11(...paths) : join10(...paths);
}
var init_join9 = __esm({
  "https://deno.land/std@0.217.0/path/join.ts"() {
    init_os3();
    init_join7();
    init_join8();
  }
});

// https://deno.land/std@0.217.0/path/posix/resolve.ts
function resolve8(...pathSegments) {
  let resolvedPath = "";
  let resolvedAbsolute = false;
  for (let i6 = pathSegments.length - 1; i6 >= -1 && !resolvedAbsolute; i6--) {
    let path3;
    if (i6 >= 0) path3 = pathSegments[i6];
    else {
      const { Deno: Deno6 } = globalThis;
      if (typeof Deno6?.cwd !== "function") {
        throw new TypeError("Resolved a relative path without a CWD.");
      }
      path3 = Deno6.cwd();
    }
    assertPath3(path3);
    if (path3.length === 0) {
      continue;
    }
    resolvedPath = `${path3}/${resolvedPath}`;
    resolvedAbsolute = isPosixPathSeparator5(path3.charCodeAt(0));
  }
  resolvedPath = normalizeString3(
    resolvedPath,
    !resolvedAbsolute,
    "/",
    isPosixPathSeparator5
  );
  if (resolvedAbsolute) {
    if (resolvedPath.length > 0) return `/${resolvedPath}`;
    else return "/";
  } else if (resolvedPath.length > 0) return resolvedPath;
  else return ".";
}
var init_resolve8 = __esm({
  "https://deno.land/std@0.217.0/path/posix/resolve.ts"() {
    init_normalize_string3();
    init_assert_path3();
    init_util6();
  }
});

// https://deno.land/std@0.217.0/path/windows/resolve.ts
function resolve9(...pathSegments) {
  let resolvedDevice = "";
  let resolvedTail = "";
  let resolvedAbsolute = false;
  for (let i6 = pathSegments.length - 1; i6 >= -1; i6--) {
    let path3;
    const { Deno: Deno6 } = globalThis;
    if (i6 >= 0) {
      path3 = pathSegments[i6];
    } else if (!resolvedDevice) {
      if (typeof Deno6?.cwd !== "function") {
        throw new TypeError("Resolved a drive-letter-less path without a CWD.");
      }
      path3 = Deno6.cwd();
    } else {
      if (typeof Deno6?.env?.get !== "function" || typeof Deno6?.cwd !== "function") {
        throw new TypeError("Resolved a relative path without a CWD.");
      }
      path3 = Deno6.cwd();
      if (path3 === void 0 || path3.slice(0, 3).toLowerCase() !== `${resolvedDevice.toLowerCase()}\\`) {
        path3 = `${resolvedDevice}\\`;
      }
    }
    assertPath3(path3);
    const len = path3.length;
    if (len === 0) continue;
    let rootEnd = 0;
    let device = "";
    let isAbsolute12 = false;
    const code5 = path3.charCodeAt(0);
    if (len > 1) {
      if (isPathSeparator3(code5)) {
        isAbsolute12 = true;
        if (isPathSeparator3(path3.charCodeAt(1))) {
          let j3 = 2;
          let last = j3;
          for (; j3 < len; ++j3) {
            if (isPathSeparator3(path3.charCodeAt(j3))) break;
          }
          if (j3 < len && j3 !== last) {
            const firstPart = path3.slice(last, j3);
            last = j3;
            for (; j3 < len; ++j3) {
              if (!isPathSeparator3(path3.charCodeAt(j3))) break;
            }
            if (j3 < len && j3 !== last) {
              last = j3;
              for (; j3 < len; ++j3) {
                if (isPathSeparator3(path3.charCodeAt(j3))) break;
              }
              if (j3 === len) {
                device = `\\\\${firstPart}\\${path3.slice(last)}`;
                rootEnd = j3;
              } else if (j3 !== last) {
                device = `\\\\${firstPart}\\${path3.slice(last, j3)}`;
                rootEnd = j3;
              }
            }
          }
        } else {
          rootEnd = 1;
        }
      } else if (isWindowsDeviceRoot3(code5)) {
        if (path3.charCodeAt(1) === CHAR_COLON5) {
          device = path3.slice(0, 2);
          rootEnd = 2;
          if (len > 2) {
            if (isPathSeparator3(path3.charCodeAt(2))) {
              isAbsolute12 = true;
              rootEnd = 3;
            }
          }
        }
      }
    } else if (isPathSeparator3(code5)) {
      rootEnd = 1;
      isAbsolute12 = true;
    }
    if (device.length > 0 && resolvedDevice.length > 0 && device.toLowerCase() !== resolvedDevice.toLowerCase()) {
      continue;
    }
    if (resolvedDevice.length === 0 && device.length > 0) {
      resolvedDevice = device;
    }
    if (!resolvedAbsolute) {
      resolvedTail = `${path3.slice(rootEnd)}\\${resolvedTail}`;
      resolvedAbsolute = isAbsolute12;
    }
    if (resolvedAbsolute && resolvedDevice.length > 0) break;
  }
  resolvedTail = normalizeString3(
    resolvedTail,
    !resolvedAbsolute,
    "\\",
    isPathSeparator3
  );
  return resolvedDevice + (resolvedAbsolute ? "\\" : "") + resolvedTail || ".";
}
var init_resolve9 = __esm({
  "https://deno.land/std@0.217.0/path/windows/resolve.ts"() {
    init_constants9();
    init_normalize_string3();
    init_assert_path3();
    init_util7();
  }
});

// https://deno.land/std@0.217.0/path/resolve.ts
function resolve10(...pathSegments) {
  return isWindows6 ? resolve9(...pathSegments) : resolve8(...pathSegments);
}
var init_resolve10 = __esm({
  "https://deno.land/std@0.217.0/path/resolve.ts"() {
    init_os3();
    init_resolve8();
    init_resolve9();
  }
});

// https://deno.land/std@0.217.0/fs/_get_file_info_type.ts
function getFileInfoType3(fileInfo) {
  return fileInfo.isFile ? "file" : fileInfo.isDirectory ? "dir" : fileInfo.isSymlink ? "symlink" : void 0;
}
var init_get_file_info_type2 = __esm({
  "https://deno.land/std@0.217.0/fs/_get_file_info_type.ts"() {
  }
});

// https://deno.land/std@0.217.0/fs/ensure_dir.ts
async function ensureDir2(dir) {
  try {
    const fileInfo = await Deno.lstat(dir);
    if (!fileInfo.isDirectory) {
      throw new Error(
        `Ensure path exists, expected 'dir', got '${getFileInfoType3(fileInfo)}'`
      );
    }
    return;
  } catch (err2) {
    if (!(err2 instanceof Deno.errors.NotFound)) {
      throw err2;
    }
  }
  try {
    await Deno.mkdir(dir, { recursive: true });
  } catch (err2) {
    if (!(err2 instanceof Deno.errors.AlreadyExists)) {
      throw err2;
    }
    const fileInfo = await Deno.lstat(dir);
    if (!fileInfo.isDirectory) {
      throw new Error(
        `Ensure path exists, expected 'dir', got '${getFileInfoType3(fileInfo)}'`
      );
    }
  }
}
var init_ensure_dir2 = __esm({
  "https://deno.land/std@0.217.0/fs/ensure_dir.ts"() {
    init_get_file_info_type2();
  }
});

// https://deno.land/std@0.217.0/path/_common/from_file_url.ts
function assertArg10(url) {
  url = url instanceof URL ? url : new URL(url);
  if (url.protocol !== "file:") {
    throw new TypeError("Must be a file URL.");
  }
  return url;
}
var init_from_file_url9 = __esm({
  "https://deno.land/std@0.217.0/path/_common/from_file_url.ts"() {
  }
});

// https://deno.land/std@0.217.0/path/posix/from_file_url.ts
function fromFileUrl7(url) {
  url = assertArg10(url);
  return decodeURIComponent(
    url.pathname.replace(/%(?![0-9A-Fa-f]{2})/g, "%25")
  );
}
var init_from_file_url10 = __esm({
  "https://deno.land/std@0.217.0/path/posix/from_file_url.ts"() {
    init_from_file_url9();
  }
});

// https://deno.land/std@0.217.0/path/windows/from_file_url.ts
function fromFileUrl8(url) {
  url = assertArg10(url);
  let path3 = decodeURIComponent(
    url.pathname.replace(/\//g, "\\").replace(/%(?![0-9A-Fa-f]{2})/g, "%25")
  ).replace(/^\\*([A-Za-z]:)(\\|$)/, "$1\\");
  if (url.hostname !== "") {
    path3 = `\\\\${url.hostname}${path3}`;
  }
  return path3;
}
var init_from_file_url11 = __esm({
  "https://deno.land/std@0.217.0/path/windows/from_file_url.ts"() {
    init_from_file_url9();
  }
});

// https://deno.land/std@0.217.0/path/from_file_url.ts
function fromFileUrl9(url) {
  return isWindows6 ? fromFileUrl8(url) : fromFileUrl7(url);
}
var init_from_file_url12 = __esm({
  "https://deno.land/std@0.217.0/path/from_file_url.ts"() {
    init_os3();
    init_from_file_url10();
    init_from_file_url11();
  }
});

// https://deno.land/std@0.217.0/fs/_to_path_string.ts
function toPathString3(pathUrl) {
  return pathUrl instanceof URL ? fromFileUrl9(pathUrl) : pathUrl;
}
var init_to_path_string2 = __esm({
  "https://deno.land/std@0.217.0/fs/_to_path_string.ts"() {
    init_from_file_url12();
  }
});

// https://deno.land/std@0.217.0/path/constants.ts
var SEPARATOR4;
var init_constants10 = __esm({
  "https://deno.land/std@0.217.0/path/constants.ts"() {
    init_os3();
    SEPARATOR4 = isWindows6 ? "\\" : "/";
  }
});

// https://deno.land/std@0.217.0/fs/_is_subdir.ts
function isSubdir3(src2, dest, sep6 = SEPARATOR4) {
  if (src2 === dest) {
    return false;
  }
  src2 = toPathString3(src2);
  const srcArray = src2.split(sep6);
  dest = toPathString3(dest);
  const destArray = dest.split(sep6);
  return srcArray.every((current3, i6) => destArray[i6] === current3);
}
var init_is_subdir2 = __esm({
  "https://deno.land/std@0.217.0/fs/_is_subdir.ts"() {
    init_constants10();
    init_to_path_string2();
  }
});

// https://deno.land/std@0.217.0/fs/copy.ts
async function ensureValidCopy2(src2, dest, options) {
  let destStat;
  try {
    destStat = await Deno.lstat(dest);
  } catch (err2) {
    if (err2 instanceof Deno.errors.NotFound) {
      return;
    }
    throw err2;
  }
  if (options.isFolder && !destStat.isDirectory) {
    throw new Error(
      `Cannot overwrite non-directory '${dest}' with directory '${src2}'.`
    );
  }
  if (!options.overwrite) {
    throw new Deno.errors.AlreadyExists(`'${dest}' already exists.`);
  }
  return destStat;
}
async function copyFile2(src2, dest, options) {
  await ensureValidCopy2(src2, dest, options);
  await Deno.copyFile(src2, dest);
  if (options.preserveTimestamps) {
    const statInfo = await Deno.stat(src2);
    assert5(statInfo.atime instanceof Date, `statInfo.atime is unavailable`);
    assert5(statInfo.mtime instanceof Date, `statInfo.mtime is unavailable`);
    await Deno.utime(dest, statInfo.atime, statInfo.mtime);
  }
}
async function copySymLink2(src2, dest, options) {
  await ensureValidCopy2(src2, dest, options);
  const originSrcFilePath = await Deno.readLink(src2);
  const type4 = getFileInfoType3(await Deno.lstat(src2));
  if (isWindows7) {
    await Deno.symlink(originSrcFilePath, dest, {
      type: type4 === "dir" ? "dir" : "file"
    });
  } else {
    await Deno.symlink(originSrcFilePath, dest);
  }
  if (options.preserveTimestamps) {
    const statInfo = await Deno.lstat(src2);
    assert5(statInfo.atime instanceof Date, `statInfo.atime is unavailable`);
    assert5(statInfo.mtime instanceof Date, `statInfo.mtime is unavailable`);
    await Deno.utime(dest, statInfo.atime, statInfo.mtime);
  }
}
async function copyDir2(src2, dest, options) {
  const destStat = await ensureValidCopy2(src2, dest, {
    ...options,
    isFolder: true
  });
  if (!destStat) {
    await ensureDir2(dest);
  }
  if (options.preserveTimestamps) {
    const srcStatInfo = await Deno.stat(src2);
    assert5(srcStatInfo.atime instanceof Date, `statInfo.atime is unavailable`);
    assert5(srcStatInfo.mtime instanceof Date, `statInfo.mtime is unavailable`);
    await Deno.utime(dest, srcStatInfo.atime, srcStatInfo.mtime);
  }
  src2 = toPathString3(src2);
  dest = toPathString3(dest);
  const promises2 = [];
  for await (const entry of Deno.readDir(src2)) {
    const srcPath = join12(src2, entry.name);
    const destPath = join12(dest, basename9(srcPath));
    if (entry.isSymlink) {
      promises2.push(copySymLink2(srcPath, destPath, options));
    } else if (entry.isDirectory) {
      promises2.push(copyDir2(srcPath, destPath, options));
    } else if (entry.isFile) {
      promises2.push(copyFile2(srcPath, destPath, options));
    }
  }
  await Promise.all(promises2);
}
async function copy4(src2, dest, options = {}) {
  src2 = resolve10(toPathString3(src2));
  dest = resolve10(toPathString3(dest));
  if (src2 === dest) {
    throw new Error("Source and destination cannot be the same.");
  }
  const srcStat = await Deno.lstat(src2);
  if (srcStat.isDirectory && isSubdir3(src2, dest)) {
    throw new Error(
      `Cannot copy '${src2}' to a subdirectory of itself, '${dest}'.`
    );
  }
  if (srcStat.isSymlink) {
    await copySymLink2(src2, dest, options);
  } else if (srcStat.isDirectory) {
    await copyDir2(src2, dest, options);
  } else if (srcStat.isFile) {
    await copyFile2(src2, dest, options);
  }
}
var isWindows7;
var init_copy4 = __esm({
  "https://deno.land/std@0.217.0/fs/copy.ts"() {
    init_basename12();
    init_join9();
    init_resolve10();
    init_ensure_dir2();
    init_assert4();
    init_get_file_info_type2();
    init_to_path_string2();
    init_is_subdir2();
    isWindows7 = Deno.build.os === "windows";
  }
});

// https://deno.land/std@0.217.0/fmt/printf.ts
function sprintf2(format14, ...args) {
  const printf = new Printf(format14, ...args);
  return printf.doPrintf();
}
var State3, WorP, F, Flags, min, UNICODE_REPLACEMENT_CHARACTER, DEFAULT_PRECISION, FLOAT_REGEXP, Printf;
var init_printf2 = __esm({
  "https://deno.land/std@0.217.0/fmt/printf.ts"() {
    State3 = {
      PASSTHROUGH: 0,
      PERCENT: 1,
      POSITIONAL: 2,
      PRECISION: 3,
      WIDTH: 4
    };
    WorP = {
      WIDTH: 0,
      PRECISION: 1
    };
    F = {
      sign: 1,
      mantissa: 2,
      fractional: 3,
      esign: 4,
      exponent: 5
    };
    Flags = class {
      plus;
      dash;
      sharp;
      space;
      zero;
      lessthan;
      width = -1;
      precision = -1;
    };
    min = Math.min;
    UNICODE_REPLACEMENT_CHARACTER = "\uFFFD";
    DEFAULT_PRECISION = 6;
    FLOAT_REGEXP = /(-?)(\d)\.?(\d*)e([+-])(\d+)/;
    Printf = class {
      format;
      args;
      i;
      state = State3.PASSTHROUGH;
      verb = "";
      buf = "";
      argNum = 0;
      flags = new Flags();
      haveSeen;
      // barf, store precision and width errors for later processing ...
      tmpError;
      constructor(format14, ...args) {
        this.format = format14;
        this.args = args;
        this.haveSeen = Array.from({ length: args.length });
        this.i = 0;
      }
      doPrintf() {
        for (; this.i < this.format.length; ++this.i) {
          const c6 = this.format[this.i];
          switch (this.state) {
            case State3.PASSTHROUGH:
              if (c6 === "%") {
                this.state = State3.PERCENT;
              } else {
                this.buf += c6;
              }
              break;
            case State3.PERCENT:
              if (c6 === "%") {
                this.buf += c6;
                this.state = State3.PASSTHROUGH;
              } else {
                this.handleFormat();
              }
              break;
            default:
              throw Error("Should be unreachable, certainly a bug in the lib.");
          }
        }
        let extras = false;
        let err2 = "%!(EXTRA";
        for (let i6 = 0; i6 !== this.haveSeen.length; ++i6) {
          if (!this.haveSeen[i6]) {
            extras = true;
            err2 += ` '${Deno.inspect(this.args[i6])}'`;
          }
        }
        err2 += ")";
        if (extras) {
          this.buf += err2;
        }
        return this.buf;
      }
      // %[<positional>]<flag>...<verb>
      handleFormat() {
        this.flags = new Flags();
        const flags = this.flags;
        for (; this.i < this.format.length; ++this.i) {
          const c6 = this.format[this.i];
          switch (this.state) {
            case State3.PERCENT:
              switch (c6) {
                case "[":
                  this.handlePositional();
                  this.state = State3.POSITIONAL;
                  break;
                case "+":
                  flags.plus = true;
                  break;
                case "<":
                  flags.lessthan = true;
                  break;
                case "-":
                  flags.dash = true;
                  flags.zero = false;
                  break;
                case "#":
                  flags.sharp = true;
                  break;
                case " ":
                  flags.space = true;
                  break;
                case "0":
                  flags.zero = !flags.dash;
                  break;
                default:
                  if ("1" <= c6 && c6 <= "9" || c6 === "." || c6 === "*") {
                    if (c6 === ".") {
                      this.flags.precision = 0;
                      this.state = State3.PRECISION;
                      this.i++;
                    } else {
                      this.state = State3.WIDTH;
                    }
                    this.handleWidthAndPrecision(flags);
                  } else {
                    this.handleVerb();
                    return;
                  }
              }
              break;
            case State3.POSITIONAL:
              if (c6 === "*") {
                const worp = this.flags.precision === -1 ? WorP.WIDTH : WorP.PRECISION;
                this.handleWidthOrPrecisionRef(worp);
                this.state = State3.PERCENT;
                break;
              } else {
                this.handleVerb();
                return;
              }
            default:
              throw new Error(`Should not be here ${this.state}, library bug!`);
          }
        }
      }
      /**
       * Handle width or precision
       * @param wOrP
       */
      handleWidthOrPrecisionRef(wOrP) {
        if (this.argNum >= this.args.length) {
          return;
        }
        const arg = this.args[this.argNum];
        this.haveSeen[this.argNum] = true;
        if (typeof arg === "number") {
          switch (wOrP) {
            case WorP.WIDTH:
              this.flags.width = arg;
              break;
            default:
              this.flags.precision = arg;
          }
        } else {
          const tmp = wOrP === WorP.WIDTH ? "WIDTH" : "PREC";
          this.tmpError = `%!(BAD ${tmp} '${this.args[this.argNum]}')`;
        }
        this.argNum++;
      }
      /**
       * Handle width and precision
       * @param flags
       */
      handleWidthAndPrecision(flags) {
        const fmt = this.format;
        for (; this.i !== this.format.length; ++this.i) {
          const c6 = fmt[this.i];
          switch (this.state) {
            case State3.WIDTH:
              switch (c6) {
                case ".":
                  this.flags.precision = 0;
                  this.state = State3.PRECISION;
                  break;
                case "*":
                  this.handleWidthOrPrecisionRef(WorP.WIDTH);
                  break;
                default: {
                  const val = parseInt(c6);
                  if (isNaN(val)) {
                    this.i--;
                    this.state = State3.PERCENT;
                    return;
                  }
                  flags.width = flags.width === -1 ? 0 : flags.width;
                  flags.width *= 10;
                  flags.width += val;
                }
              }
              break;
            case State3.PRECISION: {
              if (c6 === "*") {
                this.handleWidthOrPrecisionRef(WorP.PRECISION);
                break;
              }
              const val = parseInt(c6);
              if (isNaN(val)) {
                this.i--;
                this.state = State3.PERCENT;
                return;
              }
              flags.precision *= 10;
              flags.precision += val;
              break;
            }
            default:
              throw new Error("can't be here. bug.");
          }
        }
      }
      /** Handle positional */
      handlePositional() {
        if (this.format[this.i] !== "[") {
          throw new Error("Can't happen? Bug.");
        }
        let positional = 0;
        const format14 = this.format;
        this.i++;
        let err2 = false;
        for (; this.i !== this.format.length; ++this.i) {
          if (format14[this.i] === "]") {
            break;
          }
          positional *= 10;
          const val = parseInt(format14[this.i]);
          if (isNaN(val)) {
            this.tmpError = "%!(BAD INDEX)";
            err2 = true;
          }
          positional += val;
        }
        if (positional - 1 >= this.args.length) {
          this.tmpError = "%!(BAD INDEX)";
          err2 = true;
        }
        this.argNum = err2 ? this.argNum : positional - 1;
      }
      /** Handle less than */
      handleLessThan() {
        const arg = this.args[this.argNum];
        if ((arg || {}).constructor.name !== "Array") {
          throw new Error(`arg ${arg} is not an array. Todo better error handling`);
        }
        let str3 = "[ ";
        for (let i6 = 0; i6 !== arg.length; ++i6) {
          if (i6 !== 0) str3 += ", ";
          str3 += this._handleVerb(arg[i6]);
        }
        return str3 + " ]";
      }
      /** Handle verb */
      handleVerb() {
        const verb = this.format[this.i];
        this.verb = verb;
        if (this.tmpError) {
          this.buf += this.tmpError;
          this.tmpError = void 0;
          if (this.argNum < this.haveSeen.length) {
            this.haveSeen[this.argNum] = true;
          }
        } else if (this.args.length <= this.argNum) {
          this.buf += `%!(MISSING '${verb}')`;
        } else {
          const arg = this.args[this.argNum];
          this.haveSeen[this.argNum] = true;
          if (this.flags.lessthan) {
            this.buf += this.handleLessThan();
          } else {
            this.buf += this._handleVerb(arg);
          }
        }
        this.argNum++;
        this.state = State3.PASSTHROUGH;
      }
      // deno-lint-ignore no-explicit-any
      _handleVerb(arg) {
        switch (this.verb) {
          case "t":
            return this.pad(arg.toString());
          case "b":
            return this.fmtNumber(arg, 2);
          case "c":
            return this.fmtNumberCodePoint(arg);
          case "d":
            return this.fmtNumber(arg, 10);
          case "o":
            return this.fmtNumber(arg, 8);
          case "x":
            return this.fmtHex(arg);
          case "X":
            return this.fmtHex(arg, true);
          case "e":
            return this.fmtFloatE(arg);
          case "E":
            return this.fmtFloatE(arg, true);
          case "f":
          case "F":
            return this.fmtFloatF(arg);
          case "g":
            return this.fmtFloatG(arg);
          case "G":
            return this.fmtFloatG(arg, true);
          case "s":
            return this.fmtString(arg);
          case "T":
            return this.fmtString(typeof arg);
          case "v":
            return this.fmtV(arg);
          case "j":
            return this.fmtJ(arg);
          case "i":
            return this.fmtI(arg, false);
          case "I":
            return this.fmtI(arg, true);
          default:
            return `%!(BAD VERB '${this.verb}')`;
        }
      }
      /**
       * Pad a string
       * @param s text to pad
       */
      pad(s5) {
        const padding3 = this.flags.zero ? "0" : " ";
        if (this.flags.dash) {
          return s5.padEnd(this.flags.width, padding3);
        }
        return s5.padStart(this.flags.width, padding3);
      }
      /**
       * Pad a number
       * @param nStr
       * @param neg
       */
      padNum(nStr, neg) {
        let sign;
        if (neg) {
          sign = "-";
        } else if (this.flags.plus || this.flags.space) {
          sign = this.flags.plus ? "+" : " ";
        } else {
          sign = "";
        }
        const zero2 = this.flags.zero;
        if (!zero2) {
          nStr = sign + nStr;
        }
        const pad = zero2 ? "0" : " ";
        const len = zero2 ? this.flags.width - sign.length : this.flags.width;
        if (this.flags.dash) {
          nStr = nStr.padEnd(len, pad);
        } else {
          nStr = nStr.padStart(len, pad);
        }
        if (zero2) {
          nStr = sign + nStr;
        }
        return nStr;
      }
      /**
       * Format a number
       * @param n
       * @param radix
       * @param upcase
       */
      fmtNumber(n5, radix, upcase = false) {
        let num = Math.abs(n5).toString(radix);
        const prec = this.flags.precision;
        if (prec !== -1) {
          this.flags.zero = false;
          num = n5 === 0 && prec === 0 ? "" : num;
          while (num.length < prec) {
            num = "0" + num;
          }
        }
        let prefix = "";
        if (this.flags.sharp) {
          switch (radix) {
            case 2:
              prefix += "0b";
              break;
            case 8:
              prefix += num.startsWith("0") ? "" : "0";
              break;
            case 16:
              prefix += "0x";
              break;
            default:
              throw new Error("cannot handle base: " + radix);
          }
        }
        num = num.length === 0 ? num : prefix + num;
        if (upcase) {
          num = num.toUpperCase();
        }
        return this.padNum(num, n5 < 0);
      }
      /**
       * Format number with code points
       * @param n
       */
      fmtNumberCodePoint(n5) {
        let s5 = "";
        try {
          s5 = String.fromCodePoint(n5);
        } catch {
          s5 = UNICODE_REPLACEMENT_CHARACTER;
        }
        return this.pad(s5);
      }
      /**
       * Format special float
       * @param n
       */
      fmtFloatSpecial(n5) {
        if (isNaN(n5)) {
          this.flags.zero = false;
          return this.padNum("NaN", false);
        }
        if (n5 === Number.POSITIVE_INFINITY) {
          this.flags.zero = false;
          this.flags.plus = true;
          return this.padNum("Inf", false);
        }
        if (n5 === Number.NEGATIVE_INFINITY) {
          this.flags.zero = false;
          return this.padNum("Inf", true);
        }
        return "";
      }
      /**
       * Round fraction to precision
       * @param fractional
       * @param precision
       * @returns tuple of fractional and round
       */
      roundFractionToPrecision(fractional, precision) {
        let round = false;
        if (fractional.length > precision) {
          fractional = "1" + fractional;
          let tmp = parseInt(fractional.slice(0, precision + 2)) / 10;
          tmp = Math.round(tmp);
          fractional = Math.floor(tmp).toString();
          round = fractional[0] === "2";
          fractional = fractional.slice(1);
        } else {
          while (fractional.length < precision) {
            fractional += "0";
          }
        }
        return [fractional, round];
      }
      /**
       * Format float E
       * @param n
       * @param upcase
       */
      fmtFloatE(n5, upcase = false) {
        const special = this.fmtFloatSpecial(n5);
        if (special !== "") {
          return special;
        }
        const m4 = n5.toExponential().match(FLOAT_REGEXP);
        if (!m4) {
          throw Error("can't happen, bug");
        }
        let fractional = m4[F.fractional];
        const precision = this.flags.precision !== -1 ? this.flags.precision : DEFAULT_PRECISION;
        let rounding = false;
        [fractional, rounding] = this.roundFractionToPrecision(
          fractional,
          precision
        );
        let e5 = m4[F.exponent];
        let esign = m4[F.esign];
        let mantissa = parseInt(m4[F.mantissa]);
        if (rounding) {
          mantissa += 1;
          if (10 <= mantissa) {
            mantissa = 1;
            const r5 = parseInt(esign + e5) + 1;
            e5 = r5.toString();
            esign = r5 < 0 ? "-" : "+";
          }
        }
        e5 = e5.length === 1 ? "0" + e5 : e5;
        const val = `${mantissa}.${fractional}${upcase ? "E" : "e"}${esign}${e5}`;
        return this.padNum(val, n5 < 0);
      }
      /**
       * Format float F
       * @param n
       */
      fmtFloatF(n5) {
        const special = this.fmtFloatSpecial(n5);
        if (special !== "") {
          return special;
        }
        function expandNumber(n6) {
          if (Number.isSafeInteger(n6)) {
            return n6.toString() + ".";
          }
          const t5 = n6.toExponential().split("e");
          let m4 = t5[0].replace(".", "");
          const e5 = parseInt(t5[1]);
          if (e5 < 0) {
            let nStr = "0.";
            for (let i6 = 0; i6 !== Math.abs(e5) - 1; ++i6) {
              nStr += "0";
            }
            return nStr += m4;
          } else {
            const splIdx = e5 + 1;
            while (m4.length < splIdx) {
              m4 += "0";
            }
            return m4.slice(0, splIdx) + "." + m4.slice(splIdx);
          }
        }
        const val = expandNumber(Math.abs(n5));
        const arr = val.split(".");
        let dig = arr[0];
        let fractional = arr[1];
        const precision = this.flags.precision !== -1 ? this.flags.precision : DEFAULT_PRECISION;
        let round = false;
        [fractional, round] = this.roundFractionToPrecision(fractional, precision);
        if (round) {
          dig = (parseInt(dig) + 1).toString();
        }
        return this.padNum(`${dig}.${fractional}`, n5 < 0);
      }
      /**
       * Format float G
       * @param n
       * @param upcase
       */
      fmtFloatG(n5, upcase = false) {
        const special = this.fmtFloatSpecial(n5);
        if (special !== "") {
          return special;
        }
        let P3 = this.flags.precision !== -1 ? this.flags.precision : DEFAULT_PRECISION;
        P3 = P3 === 0 ? 1 : P3;
        const m4 = n5.toExponential().match(FLOAT_REGEXP);
        if (!m4) {
          throw Error("can't happen");
        }
        const X2 = parseInt(m4[F.exponent]) * (m4[F.esign] === "-" ? -1 : 1);
        let nStr = "";
        if (P3 > X2 && X2 >= -4) {
          this.flags.precision = P3 - (X2 + 1);
          nStr = this.fmtFloatF(n5);
          if (!this.flags.sharp) {
            nStr = nStr.replace(/\.?0*$/, "");
          }
        } else {
          this.flags.precision = P3 - 1;
          nStr = this.fmtFloatE(n5);
          if (!this.flags.sharp) {
            nStr = nStr.replace(/\.?0*e/, upcase ? "E" : "e");
          }
        }
        return nStr;
      }
      /**
       * Format string
       * @param s
       */
      fmtString(s5) {
        if (this.flags.precision !== -1) {
          s5 = s5.slice(0, this.flags.precision);
        }
        return this.pad(s5);
      }
      /**
       * Format hex
       * @param val
       * @param upper
       */
      fmtHex(val, upper = false) {
        switch (typeof val) {
          case "number":
            return this.fmtNumber(val, 16, upper);
          case "string": {
            const sharp = this.flags.sharp && val.length !== 0;
            let hex = sharp ? "0x" : "";
            const prec = this.flags.precision;
            const end = prec !== -1 ? min(prec, val.length) : val.length;
            for (let i6 = 0; i6 !== end; ++i6) {
              if (i6 !== 0 && this.flags.space) {
                hex += sharp ? " 0x" : " ";
              }
              const c6 = (val.charCodeAt(i6) & 255).toString(16);
              hex += c6.length === 1 ? `0${c6}` : c6;
            }
            if (upper) {
              hex = hex.toUpperCase();
            }
            return this.pad(hex);
          }
          default:
            throw new Error(
              "currently only number and string are implemented for hex"
            );
        }
      }
      /**
       * Format value
       * @param val
       */
      fmtV(val) {
        if (this.flags.sharp) {
          const options = this.flags.precision !== -1 ? { depth: this.flags.precision } : {};
          return this.pad(Deno.inspect(val, options));
        } else {
          const p5 = this.flags.precision;
          return p5 === -1 ? val.toString() : val.toString().slice(0, p5);
        }
      }
      /**
       * Format JSON
       * @param val
       */
      fmtJ(val) {
        return JSON.stringify(val);
      }
      /**
       * Format inspect
       * @param val
       * @param compact Whether or not the output should be compact.
       */
      fmtI(val, compact) {
        return Deno.inspect(val, {
          colors: !Deno?.noColor,
          compact,
          depth: Infinity,
          iterableLimit: Infinity
        });
      }
    };
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/vendor/std.ts
var init_std = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/vendor/std.ts"() {
    init_base642();
    init_mod8();
    init_mod11();
    init_mod12();
    init_exists3();
    init_copy4();
    init_printf2();
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/helper.js
function getExceptionMessage(exceptionDetails) {
  if (exceptionDetails.exception) {
    return exceptionDetails.exception.description || exceptionDetails.exception.value;
  }
  let message = exceptionDetails.text;
  if (exceptionDetails.stackTrace) {
    for (const callframe of exceptionDetails.stackTrace.callFrames) {
      const location = callframe.url + ":" + callframe.lineNumber + ":" + callframe.columnNumber;
      const functionName = callframe.functionName || "<anonymous>";
      message += `
    at ${functionName} (${location})`;
    }
  }
  return message;
}
function valueFromRemoteObject(remoteObject) {
  assert3(!remoteObject.objectId, "Cannot extract value when objectId is given");
  if (remoteObject.unserializableValue) {
    if (remoteObject.type === "bigint" && typeof BigInt !== "undefined") {
      return BigInt(remoteObject.unserializableValue.replace("n", ""));
    }
    switch (remoteObject.unserializableValue) {
      case "-0":
        return -0;
      case "NaN":
        return NaN;
      case "Infinity":
        return Infinity;
      case "-Infinity":
        return -Infinity;
      default:
        throw new Error(
          "Unsupported unserializable value: " + remoteObject.unserializableValue
        );
    }
  }
  return remoteObject.value;
}
async function releaseObject(client, remoteObject) {
  if (!remoteObject.objectId) {
    return;
  }
  await client.send("Runtime.releaseObject", { objectId: remoteObject.objectId }).catch((error2) => {
    debugError(error2);
  });
}
function addEventListener2(emitter, eventName, handler) {
  emitter.on(eventName, handler);
  return { emitter, eventName, handler };
}
function removeEventListeners(listeners4) {
  for (const listener of listeners4) {
    listener.emitter.removeListener(listener.eventName, listener.handler);
  }
  listeners4.length = 0;
}
function isString(obj) {
  return typeof obj === "string" || obj instanceof String;
}
function isNumber(obj) {
  return typeof obj === "number" || obj instanceof Number;
}
async function waitForEvent(emitter, eventName, predicate, timeout, abortPromise) {
  let eventTimeout, resolveCallback, rejectCallback;
  const promise = new Promise((resolve16, reject2) => {
    resolveCallback = resolve16;
    rejectCallback = reject2;
  });
  const listener = addEventListener2(emitter, eventName, async (event) => {
    if (!await predicate(event)) {
      return;
    }
    resolveCallback(event);
  });
  if (timeout) {
    eventTimeout = setTimeout(() => {
      rejectCallback(
        new TimeoutError("Timeout exceeded while waiting for event")
      );
    }, timeout);
  }
  function cleanup2() {
    removeEventListeners([listener]);
    clearTimeout(eventTimeout);
  }
  const result2 = await Promise.race([promise, abortPromise]).then((r5) => {
    cleanup2();
    return r5;
  }, (error2) => {
    cleanup2();
    throw error2;
  });
  if (result2 instanceof Error) {
    throw result2;
  }
  return result2;
}
function evaluationString(fun, ...args) {
  if (isString(fun)) {
    assert3(args.length === 0, "Cannot evaluate a string with arguments");
    return fun;
  }
  function serializeArgument(arg) {
    if (Object.is(arg, void 0)) {
      return "undefined";
    }
    return JSON.stringify(arg);
  }
  return `(${fun})(${args.map(serializeArgument).join(",")})`;
}
function pageBindingInitString(type4, name2) {
  function addPageBinding(type5, bindingName) {
    const win2 = window;
    const binding2 = win2[bindingName];
    win2[bindingName] = (...args) => {
      const me2 = window[bindingName];
      let callbacks = me2.callbacks;
      if (!callbacks) {
        callbacks = /* @__PURE__ */ new Map();
        me2.callbacks = callbacks;
      }
      const seq3 = (me2.lastSeq || 0) + 1;
      me2.lastSeq = seq3;
      const promise = new Promise(
        (resolve16, reject2) => callbacks.set(seq3, { resolve: resolve16, reject: reject2 })
      );
      binding2(JSON.stringify({ type: type5, name: bindingName, seq: seq3, args }));
      return promise;
    };
  }
  return evaluationString(addPageBinding, type4, name2);
}
function pageBindingDeliverResultString(name2, seq3, result2) {
  function deliverResult(name3, seq4, result3) {
    window[name3].callbacks.get(seq4).resolve(result3);
    window[name3].callbacks.delete(seq4);
  }
  return evaluationString(deliverResult, name2, seq3, result2);
}
function pageBindingDeliverErrorString(name2, seq3, message, stack) {
  function deliverError(name3, seq4, message2, stack2) {
    const error2 = new Error(message2);
    error2.stack = stack2;
    window[name3].callbacks.get(seq4).reject(error2);
    window[name3].callbacks.delete(seq4);
  }
  return evaluationString(deliverError, name2, seq3, message, stack);
}
function pageBindingDeliverErrorValueString(name2, seq3, value) {
  function deliverErrorValue(name3, seq4, value2) {
    window[name3].callbacks.get(seq4).reject(value2);
    window[name3].callbacks.delete(seq4);
  }
  return evaluationString(deliverErrorValue, name2, seq3, value);
}
function makePredicateString(predicate, predicateQueryHandler2) {
  function checkWaitForOptions2(node, waitForVisible, waitForHidden) {
    if (!node) {
      return waitForHidden;
    }
    if (!waitForVisible && !waitForHidden) {
      return node;
    }
    const element = node.nodeType === Node.TEXT_NODE ? node.parentElement : node;
    const style = window.getComputedStyle(element);
    const isVisible = style && style.visibility !== "hidden" && hasVisibleBoundingBox();
    const success = waitForVisible === isVisible || waitForHidden === !isVisible;
    return success ? node : null;
    function hasVisibleBoundingBox() {
      const rect = element.getBoundingClientRect();
      return !!(rect.top || rect.bottom || rect.width || rect.height);
    }
  }
  const predicateQueryHandlerDef = predicateQueryHandler2 ? `const predicateQueryHandler = ${predicateQueryHandler2};` : "";
  return `
    (() => {
      ${predicateQueryHandlerDef}
      const checkWaitForOptions = ${checkWaitForOptions2};
      return (${predicate})(...args)
    })() `;
}
async function waitWithTimeout(promise, taskName, timeout) {
  let reject2;
  const timeoutError = new TimeoutError(
    `waiting for ${taskName} failed: timeout ${timeout}ms exceeded`
  );
  const timeoutPromise = new Promise((resolve16, x3) => reject2 = x3);
  let timeoutTimer = null;
  if (timeout) {
    timeoutTimer = setTimeout(() => reject2(timeoutError), timeout);
  }
  try {
    return await Promise.race([promise, timeoutPromise]);
  } finally {
    if (timeoutTimer) {
      clearTimeout(timeoutTimer);
    }
  }
}
async function readProtocolStream(client, handle, path3) {
  let eof = false;
  let fileHandle;
  if (path3) {
    fileHandle = await Deno.open(path3, { create: true, write: true });
  }
  const arrs = [];
  while (!eof) {
    const response = await client.send("IO.read", { handle });
    eof = response.eof;
    const arr = response.base64Encoded ? decode2(response.data) : new TextEncoder().encode(response.data);
    arrs.push(arr);
    if (path3) {
      await Deno.writeAll(fileHandle, arr);
    }
  }
  if (fileHandle) {
    fileHandle.close();
  }
  await client.send("IO.close", { handle });
  let resultArr = null;
  try {
    resultArr = concat(...arrs);
  } finally {
    return resultArr;
  }
}
var debugError, helper;
var init_helper = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/helper.js"() {
    init_Errors();
    init_Debug();
    init_assert2();
    init_std();
    debugError = debug2("puppeteer:error");
    helper = {
      evaluationString,
      pageBindingInitString,
      pageBindingDeliverResultString,
      pageBindingDeliverErrorString,
      pageBindingDeliverErrorValueString,
      makePredicateString,
      readProtocolStream,
      waitWithTimeout,
      waitForEvent,
      isString,
      isNumber,
      addEventListener: addEventListener2,
      removeEventListeners,
      valueFromRemoteObject,
      getExceptionMessage,
      releaseObject
    };
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/vendor/mitt/src/index.js
function mitt(all2) {
  all2 = all2 || /* @__PURE__ */ new Map();
  return {
    /**
         * A Map of event names to registered handler functions.
         */
    all: all2,
    /**
         * Register an event handler for the given type.
         * @param {string|symbol} type Type of event to listen for, or `"*"` for all events
         * @param {Function} handler Function to call in response to given event
         * @memberOf mitt
         */
    on(type4, handler) {
      const handlers3 = all2.get(type4);
      const added = handlers3 && handlers3.push(handler);
      if (!added) {
        all2.set(type4, [handler]);
      }
    },
    /**
         * Remove an event handler for the given type.
         * @param {string|symbol} type Type of event to unregister `handler` from, or `"*"`
         * @param {Function} handler Handler function to remove
         * @memberOf mitt
         */
    off(type4, handler) {
      const handlers3 = all2.get(type4);
      if (handlers3) {
        handlers3.splice(handlers3.indexOf(handler) >>> 0, 1);
      }
    },
    /**
         * Invoke all handlers for the given type.
         * If present, `"*"` handlers are invoked after type-matched handlers.
         *
         * Note: Manually firing "*" handlers is not supported.
         *
         * @param {string|symbol} type The event type to invoke
         * @param {Any} [evt] Any value (object is recommended and powerful), passed to each handler
         * @memberOf mitt
         */
    emit(type4, evt) {
      (all2.get(type4) || []).slice().map((handler) => {
        handler(evt);
      });
      (all2.get("*") || []).slice().map((handler) => {
        handler(type4, evt);
      });
    }
  };
}
var init_src = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/vendor/mitt/src/index.js"() {
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/EventEmitter.js
var EventEmitter2;
var init_EventEmitter = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/EventEmitter.js"() {
    init_src();
    EventEmitter2 = class {
      /**
         * @internal
         */
      constructor() {
        this.eventsMap = /* @__PURE__ */ new Map();
        this.emitter = mitt(this.eventsMap);
      }
      /**
         * Bind an event listener to fire when an event occurs.
         * @param event - the event type you'd like to listen to. Can be a string or symbol.
         * @param handler  - the function to be called when the event occurs.
         * @returns `this` to enable you to chain calls.
         */
      on(event, handler) {
        this.emitter.on(event, handler);
        return this;
      }
      /**
         * Remove an event listener from firing.
         * @param event - the event type you'd like to stop listening to.
         * @param handler  - the function that should be removed.
         * @returns `this` to enable you to chain calls.
         */
      off(event, handler) {
        this.emitter.off(event, handler);
        return this;
      }
      /**
         * Remove an event listener.
         * @deprecated please use `off` instead.
         */
      removeListener(event, handler) {
        this.off(event, handler);
        return this;
      }
      /**
         * Add an event listener.
         * @deprecated please use `on` instead.
         */
      addListener(event, handler) {
        this.on(event, handler);
        return this;
      }
      /**
         * Emit an event and call any associated listeners.
         *
         * @param event - the event you'd like to emit
         * @param eventData - any data you'd like to emit with the event
         * @returns `true` if there are any listeners, `false` if there are not.
         */
      emit(event, eventData) {
        this.emitter.emit(event, eventData);
        return this.eventListenersCount(event) > 0;
      }
      /**
         * Like `on` but the listener will only be fired once and then it will be removed.
         * @param event - the event you'd like to listen to
         * @param handler - the handler function to run when the event occurs
         * @returns `this` to enable you to chain calls.
         */
      once(event, handler) {
        const onceHandler = (eventData) => {
          handler(eventData);
          this.off(event, onceHandler);
        };
        return this.on(event, onceHandler);
      }
      /**
         * Gets the number of listeners for a given event.
         *
         * @param event - the event to get the listener count for
         * @returns the number of listeners bound to the given event
         */
      listenerCount(event) {
        return this.eventListenersCount(event);
      }
      /**
         * Removes all listeners. If given an event argument, it will remove only
         * listeners for that event.
         * @param event - the event to remove listeners for.
         * @returns `this` to enable you to chain calls.
         */
      removeAllListeners(event) {
        if (event) {
          this.eventsMap.delete(event);
        } else {
          this.eventsMap.clear();
        }
        return this;
      }
      eventListenersCount(event) {
        return this.eventsMap.has(event) ? this.eventsMap.get(event).length : 0;
      }
    };
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/Connection.js
function createProtocolError(error2, method, object) {
  let message = `Protocol error (${method}): ${object.error.message}`;
  if ("data" in object.error) {
    message += ` ${object.error.data}`;
  }
  return rewriteError(error2, message);
}
function rewriteError(error2, message) {
  error2.message = message;
  return error2;
}
var debugProtocolSend, debugProtocolReceive, ConnectionEmittedEvents, Connection, CDPSessionEmittedEvents, CDPSession;
var init_Connection = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/Connection.js"() {
    init_assert2();
    init_Debug();
    init_EventEmitter();
    debugProtocolSend = debug2("puppeteer:protocol:SEND \u25BA");
    debugProtocolReceive = debug2("puppeteer:protocol:RECV \u25C0");
    ConnectionEmittedEvents = {
      Disconnected: /* @__PURE__ */ Symbol("Connection.Disconnected")
    };
    Connection = class extends EventEmitter2 {
      constructor(url, transport, delay = 0) {
        super();
        this._lastId = 0;
        this._sessions = /* @__PURE__ */ new Map();
        this._closed = false;
        this._callbacks = /* @__PURE__ */ new Map();
        this._url = url;
        this._delay = delay;
        this._transport = transport;
        this._transport.onmessage = this._onMessage.bind(this);
        this._transport.onclose = this._onClose.bind(this);
      }
      static fromSession(session) {
        return session._connection;
      }
      /**
         * @param sessionId - The session id
         * @returns The current CDP session if it exists
         */
      session(sessionId) {
        return this._sessions.get(sessionId) || null;
      }
      url() {
        return this._url;
      }
      send(method, ...paramArgs) {
        const params = paramArgs.length ? paramArgs[0] : void 0;
        const id = this._rawSend({ method, params });
        return new Promise((resolve16, reject2) => {
          this._callbacks.set(id, { resolve: resolve16, reject: reject2, error: new Error(), method });
        });
      }
      _rawSend(message) {
        const id = ++this._lastId;
        const stringifiedMessage = JSON.stringify(
          Object.assign({}, message, { id })
        );
        debugProtocolSend(stringifiedMessage);
        this._transport.send(stringifiedMessage);
        return id;
      }
      async _onMessage(message) {
        if (this._delay) {
          await new Promise((f5) => setTimeout(f5, this._delay));
        }
        debugProtocolReceive(message);
        const object = JSON.parse(message);
        if (object.method === "Target.attachedToTarget") {
          const sessionId = object.params.sessionId;
          const session = new CDPSession(
            this,
            object.params.targetInfo.type,
            sessionId
          );
          this._sessions.set(sessionId, session);
        } else if (object.method === "Target.detachedFromTarget") {
          const session = this._sessions.get(object.params.sessionId);
          if (session) {
            session._onClosed();
            this._sessions.delete(object.params.sessionId);
          }
        }
        if (object.sessionId) {
          const session = this._sessions.get(object.sessionId);
          if (session) {
            session._onMessage(object);
          }
        } else if (object.id) {
          const callback = this._callbacks.get(object.id);
          if (callback) {
            this._callbacks.delete(object.id);
            if (object.error) {
              callback.reject(
                createProtocolError(callback.error, callback.method, object)
              );
            } else {
              callback.resolve(object.result);
            }
          }
        } else {
          this.emit(object.method, object.params);
        }
      }
      _onClose() {
        if (this._closed) {
          return;
        }
        this._closed = true;
        this._transport.onmessage = null;
        this._transport.onclose = null;
        for (const callback of this._callbacks.values()) {
          callback.reject(
            rewriteError(
              callback.error,
              `Protocol error (${callback.method}): Target closed.`
            )
          );
        }
        this._callbacks.clear();
        for (const session of this._sessions.values()) {
          session._onClosed();
        }
        this._sessions.clear();
        this.emit(ConnectionEmittedEvents.Disconnected);
      }
      async dispose() {
        this._onClose();
        await this._transport.close();
      }
      /**
         * @param targetInfo - The target info
         * @returns The CDP session that is created
         */
      async createSession(targetInfo) {
        const { sessionId } = await this.send("Target.attachToTarget", {
          targetId: targetInfo.targetId,
          flatten: true
        });
        return this._sessions.get(sessionId);
      }
    };
    CDPSessionEmittedEvents = {
      Disconnected: /* @__PURE__ */ Symbol("CDPSession.Disconnected")
    };
    CDPSession = class extends EventEmitter2 {
      /**
         * @internal
         */
      constructor(connection, targetType, sessionId) {
        super();
        this._callbacks = /* @__PURE__ */ new Map();
        this._connection = connection;
        this._targetType = targetType;
        this._sessionId = sessionId;
      }
      send(method, ...paramArgs) {
        if (!this._connection) {
          return Promise.reject(
            new Error(
              `Protocol error (${method}): Session closed. Most likely the ${this._targetType} has been closed.`
            )
          );
        }
        const params = paramArgs.length ? paramArgs[0] : void 0;
        const id = this._connection._rawSend({
          sessionId: this._sessionId,
          method,
          /* TODO(jacktfranklin@): once this Firefox bug is solved
                 * we no longer need the `|| {}` check
                 * https://bugzilla.mozilla.org/show_bug.cgi?id=1631570
                 */
          params: params || {}
        });
        return new Promise((resolve16, reject2) => {
          this._callbacks.set(id, { resolve: resolve16, reject: reject2, error: new Error(), method });
        });
      }
      /**
         * @internal
         */
      _onMessage(object) {
        if (object.id && this._callbacks.has(object.id)) {
          const callback = this._callbacks.get(object.id);
          this._callbacks.delete(object.id);
          if (object.error) {
            callback.reject(
              createProtocolError(callback.error, callback.method, object)
            );
          } else {
            callback.resolve(object.result);
          }
        } else {
          assert3(!object.id);
          this.emit(object.method, object.params);
        }
      }
      /**
         * Detaches the cdpSession from the target. Once detached, the cdpSession object
         * won't emit any events and can't be used to send messages.
         */
      async detach() {
        if (!this._connection) {
          throw new Error(
            `Session already detached. Most likely the ${this._targetType} has been closed.`
          );
        }
        await this._connection.send("Target.detachFromTarget", {
          sessionId: this._sessionId
        });
      }
      /**
         * @internal
         */
      _onClosed() {
        for (const callback of this._callbacks.values()) {
          callback.reject(
            rewriteError(
              callback.error,
              `Protocol error (${callback.method}): Target closed.`
            )
          );
        }
        this._callbacks.clear();
        this._connection = null;
        this.emit(CDPSessionEmittedEvents.Disconnected);
      }
    };
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/Dialog.js
var Dialog;
var init_Dialog = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/Dialog.js"() {
    init_assert2();
    Dialog = class {
      /**
         * @internal
         */
      constructor(client, type4, message, defaultValue = "") {
        this._handled = false;
        this._client = client;
        this._type = type4;
        this._message = message;
        this._defaultValue = defaultValue;
      }
      /**
         * @returns The type of the dialog.
         */
      type() {
        return this._type;
      }
      /**
         * @returns The message displayed in the dialog.
         */
      message() {
        return this._message;
      }
      /**
         * @returns The default value of the prompt, or an empty string if the dialog
         * is not a `prompt`.
         */
      defaultValue() {
        return this._defaultValue;
      }
      /**
         * @param promptText - optional text that will be entered in the dialog
         * prompt. Has no effect if the dialog's type is not `prompt`.
         *
         * @returns A promise that resolves when the dialog has been accepted.
         */
      async accept(promptText) {
        assert3(!this._handled, "Cannot accept dialog which is already handled!");
        this._handled = true;
        await this._client.send("Page.handleJavaScriptDialog", {
          accept: true,
          promptText
        });
      }
      /**
         * @returns A promise which will resolve once the dialog has been dismissed
         */
      async dismiss() {
        assert3(!this._handled, "Cannot dismiss dialog which is already handled!");
        this._handled = true;
        await this._client.send("Page.handleJavaScriptDialog", {
          accept: false
        });
      }
    };
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/EmulationManager.js
var EmulationManager;
var init_EmulationManager = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/EmulationManager.js"() {
    EmulationManager = class {
      constructor(client) {
        this._emulatingMobile = false;
        this._hasTouch = false;
        this._client = client;
      }
      async emulateViewport(viewport) {
        const mobile = viewport.isMobile || false;
        const width = viewport.width;
        const height = viewport.height;
        const deviceScaleFactor = viewport.deviceScaleFactor || 1;
        const screenOrientation = viewport.isLandscape ? { angle: 90, type: "landscapePrimary" } : { angle: 0, type: "portraitPrimary" };
        const hasTouch = viewport.hasTouch || false;
        await Promise.all([
          this._client.send("Emulation.setDeviceMetricsOverride", {
            mobile,
            width,
            height,
            deviceScaleFactor,
            screenOrientation
          }),
          this._client.send("Emulation.setTouchEmulationEnabled", {
            enabled: hasTouch
          })
        ]);
        const reloadNeeded = this._emulatingMobile !== mobile || this._hasTouch !== hasTouch;
        this._emulatingMobile = mobile;
        this._hasTouch = hasTouch;
        return reloadNeeded;
      }
    };
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/JSHandle.js
function createJSHandle(context, remoteObject) {
  const frame = context.frame();
  if (remoteObject.subtype === "node" && frame) {
    const frameManager = frame._frameManager;
    return new ElementHandle(
      context,
      context._client,
      remoteObject,
      frameManager.page(),
      frameManager
    );
  }
  return new JSHandle(context, context._client, remoteObject);
}
function computeQuadArea(quad) {
  let area = 0;
  for (let i6 = 0; i6 < quad.length; ++i6) {
    const p1 = quad[i6];
    const p22 = quad[(i6 + 1) % quad.length];
    area += (p1.x * p22.y - p22.x * p1.y) / 2;
  }
  return Math.abs(area);
}
var JSHandle, ElementHandle;
var init_JSHandle = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/JSHandle.js"() {
    init_assert2();
    init_helper();
    init_QueryHandler();
    init_std();
    JSHandle = class {
      /**
         * @internal
         */
      constructor(context, client, remoteObject) {
        this._disposed = false;
        this._context = context;
        this._client = client;
        this._remoteObject = remoteObject;
      }
      /** Returns the execution context the handle belongs to.
         */
      executionContext() {
        return this._context;
      }
      /**
         * This method passes this handle as the first argument to `pageFunction`.
         * If `pageFunction` returns a Promise, then `handle.evaluate` would wait
         * for the promise to resolve and return its value.
         *
         * @example
         * ```js
         * const tweetHandle = await page.$('.tweet .retweets');
         * expect(await tweetHandle.evaluate(node => node.innerText)).toBe('10');
         * ```
         */
      async evaluate(pageFunction, ...args) {
        return await this.executionContext().evaluate(pageFunction, this, ...args);
      }
      /**
         * This method passes this handle as the first argument to `pageFunction`.
         *
         * @remarks
         *
         * The only difference between `jsHandle.evaluate` and
         * `jsHandle.evaluateHandle` is that `jsHandle.evaluateHandle`
         * returns an in-page object (JSHandle).
         *
         * If the function passed to `jsHandle.evaluateHandle` returns a Promise,
         * then `evaluateHandle.evaluateHandle` waits for the promise to resolve and
         * returns its value.
         *
         * See {@link Page.evaluateHandle} for more details.
         */
      async evaluateHandle(pageFunction, ...args) {
        return await this.executionContext().evaluateHandle(
          pageFunction,
          this,
          ...args
        );
      }
      /** Fetches a single property from the referenced object.
         */
      async getProperty(propertyName) {
        const objectHandle = await this.evaluateHandle((object, propertyName2) => {
          const result3 = { __proto__: null };
          result3[propertyName2] = object[propertyName2];
          return result3;
        }, propertyName);
        const properties = await objectHandle.getProperties();
        const result2 = properties.get(propertyName) || null;
        await objectHandle.dispose();
        return result2;
      }
      /**
         * The method returns a map with property names as keys and JSHandle
         * instances for the property values.
         *
         * @example
         * ```js
         * const listHandle = await page.evaluateHandle(() => document.body.children);
         * const properties = await listHandle.getProperties();
         * const children = [];
         * for (const property of properties.values()) {
         *   const element = property.asElement();
         *   if (element)
         *     children.push(element);
         * }
         * children; // holds elementHandles to all children of document.body
         * ```
         */
      async getProperties() {
        const response = await this._client.send("Runtime.getProperties", {
          objectId: this._remoteObject.objectId,
          ownProperties: true
        });
        const result2 = /* @__PURE__ */ new Map();
        for (const property of response.result) {
          if (!property.enumerable) {
            continue;
          }
          result2.set(property.name, createJSHandle(this._context, property.value));
        }
        return result2;
      }
      /**
         * Returns a JSON representation of the object.
         *
         * @remarks
         *
         * The JSON is generated by running {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify | JSON.stringify}
         * on the object in page and consequent {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse | JSON.parse} in puppeteer.
         * **NOTE** The method throws if the referenced object is not stringifiable.
         */
      async jsonValue() {
        if (this._remoteObject.objectId) {
          const response = await this._client.send("Runtime.callFunctionOn", {
            functionDeclaration: "function() { return this; }",
            objectId: this._remoteObject.objectId,
            returnByValue: true,
            awaitPromise: true
          });
          return helper.valueFromRemoteObject(response.result);
        }
        return helper.valueFromRemoteObject(this._remoteObject);
      }
      /**
         * Returns either `null` or the object handle itself, if the object handle is
         * an instance of {@link ElementHandle}.
         */
      asElement() {
        return null;
      }
      /**
         * Stops referencing the element handle, and resolves when the object handle is
         * successfully disposed of.
         */
      async dispose() {
        if (this._disposed) {
          return;
        }
        this._disposed = true;
        await helper.releaseObject(this._client, this._remoteObject);
      }
      /**
         * Returns a string representation of the JSHandle.
         *
         * @remarks Useful during debugging.
         */
      toString() {
        if (this._remoteObject.objectId) {
          const type4 = this._remoteObject.subtype || this._remoteObject.type;
          return "JSHandle@" + type4;
        }
        return "JSHandle:" + helper.valueFromRemoteObject(this._remoteObject);
      }
    };
    ElementHandle = class extends JSHandle {
      /**
         * @internal
         */
      constructor(context, client, remoteObject, page, frameManager) {
        super(context, client, remoteObject);
        this._client = client;
        this._remoteObject = remoteObject;
        this._page = page;
        this._frameManager = frameManager;
      }
      asElement() {
        return this;
      }
      /**
         * Resolves to the content frame for element handles referencing
         * iframe nodes, or null otherwise
         */
      async contentFrame() {
        const nodeInfo = await this._client.send("DOM.describeNode", {
          objectId: this._remoteObject.objectId
        });
        if (typeof nodeInfo.node.frameId !== "string") {
          return null;
        }
        return this._frameManager.frame(nodeInfo.node.frameId);
      }
      async _scrollIntoViewIfNeeded() {
        const error2 = await this.evaluate(
          async (element, pageJavascriptEnabled) => {
            if (!element.isConnected) {
              return "Node is detached from document";
            }
            if (element.nodeType !== Node.ELEMENT_NODE) {
              return "Node is not of type HTMLElement";
            }
            if (!pageJavascriptEnabled) {
              element.scrollIntoView({
                block: "center",
                inline: "center",
                // @ts-expect-error Chrome still supports behavior: instant but
                // it's not in the spec so TS shouts We don't want to make this
                // breaking change in Puppeteer yet so we'll ignore the line.
                behavior: "instant"
              });
              return false;
            }
            const visibleRatio = await new Promise((resolve16) => {
              const observer = new IntersectionObserver((entries) => {
                resolve16(entries[0].intersectionRatio);
                observer.disconnect();
              });
              observer.observe(element);
            });
            if (visibleRatio !== 1) {
              element.scrollIntoView({
                block: "center",
                inline: "center",
                // @ts-expect-error Chrome still supports behavior: instant but
                // it's not in the spec so TS shouts We don't want to make this
                // breaking change in Puppeteer yet so we'll ignore the line.
                behavior: "instant"
              });
            }
            return false;
          },
          this._page.isJavaScriptEnabled()
        );
        if (error2) {
          throw new Error(error2);
        }
      }
      async _clickablePoint() {
        const [result2, layoutMetrics] = await Promise.all([
          this._client.send("DOM.getContentQuads", {
            objectId: this._remoteObject.objectId
          }).catch(debugError),
          this._client.send("Page.getLayoutMetrics")
        ]);
        if (!result2 || !result2.quads.length) {
          throw new Error("Node is either not visible or not an HTMLElement");
        }
        const { clientWidth, clientHeight } = layoutMetrics.layoutViewport;
        const quads = result2.quads.map((quad2) => this._fromProtocolQuad(quad2)).map(
          (quad2) => this._intersectQuadWithViewport(quad2, clientWidth, clientHeight)
        ).filter((quad2) => computeQuadArea(quad2) > 1);
        if (!quads.length) {
          throw new Error("Node is either not visible or not an HTMLElement");
        }
        const quad = quads[0];
        let x3 = 0;
        let y4 = 0;
        for (const point of quad) {
          x3 += point.x;
          y4 += point.y;
        }
        return {
          x: x3 / 4,
          y: y4 / 4
        };
      }
      _getBoxModel() {
        const params = {
          objectId: this._remoteObject.objectId
        };
        return this._client.send("DOM.getBoxModel", params).catch((error2) => debugError(error2));
      }
      _fromProtocolQuad(quad) {
        return [
          { x: quad[0], y: quad[1] },
          { x: quad[2], y: quad[3] },
          { x: quad[4], y: quad[5] },
          { x: quad[6], y: quad[7] }
        ];
      }
      _intersectQuadWithViewport(quad, width, height) {
        return quad.map((point) => ({
          x: Math.min(Math.max(point.x, 0), width),
          y: Math.min(Math.max(point.y, 0), height)
        }));
      }
      /**
         * This method scrolls element into view if needed, and then
         * uses {@link Page.mouse} to hover over the center of the element.
         * If the element is detached from DOM, the method throws an error.
         */
      async hover() {
        await this._scrollIntoViewIfNeeded();
        const { x: x3, y: y4 } = await this._clickablePoint();
        await this._page.mouse.move(x3, y4);
      }
      /**
         * This method scrolls element into view if needed, and then
         * uses {@link Page.mouse} to click in the center of the element.
         * If the element is detached from DOM, the method throws an error.
         */
      async click(options = {}) {
        await this._scrollIntoViewIfNeeded();
        const { x: x3, y: y4 } = await this._clickablePoint();
        await this._page.mouse.click(x3, y4, options);
      }
      /**
         * Triggers a `change` and `input` event once all the provided options have been
         * selected. If there's no `<select>` element matching `selector`, the method
         * throws an error.
         *
         * @example
         * ```js
         * handle.select('blue'); // single selection
         * handle.select('red', 'green', 'blue'); // multiple selections
         * ```
         * @param values - Values of options to select. If the `<select>` has the
         *    `multiple` attribute, all values are considered, otherwise only the first
         *    one is taken into account.
         */
      async select(...values) {
        for (const value of values) {
          assert3(
            helper.isString(value),
            'Values must be strings. Found value "' + value + '" of type "' + typeof value + '"'
          );
        }
        return this.evaluate((element, values2) => {
          if (element.nodeName.toLowerCase() !== "select") {
            throw new Error("Element is not a <select> element.");
          }
          const options = Array.from(element.options);
          element.value = void 0;
          for (const option of options) {
            option.selected = values2.includes(option.value);
            if (option.selected && !element.multiple) {
              break;
            }
          }
          element.dispatchEvent(new Event("input", { bubbles: true }));
          element.dispatchEvent(new Event("change", { bubbles: true }));
          return options.filter((option) => option.selected).map((option) => option.value);
        }, values);
      }
      /**
         * This method expects `elementHandle` to point to an
         * {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input | input element}.
         * @param filePaths - Sets the value of the file input to these paths.
         *    If some of the  `filePaths` are relative paths, then they are resolved
         *    relative to the {@link https://nodejs.org/api/process.html#process_process_cwd | current working directory}
         */
      async uploadFile(...filePaths) {
        const isMultiple = await this.evaluate((element) => element.multiple);
        assert3(
          filePaths.length <= 1 || isMultiple,
          "Multiple file uploads only work with <input type=file multiple>"
        );
        const files = await Promise.all(filePaths.map(async (filePath) => {
          const resolvedPath = resolve7(filePath);
          try {
            await Deno.stat(filePath);
          } catch (error2) {
            if (error2 instanceof Deno.errors.NotFound) {
              throw new Error(`${filePath} does not exist or is not readable`);
            }
          }
          return resolvedPath;
        }));
        const { objectId } = this._remoteObject;
        const { node } = await this._client.send("DOM.describeNode", { objectId });
        const { backendNodeId } = node;
        if (files.length === 0) {
          await this.evaluate((element) => {
            element.files = new DataTransfer().files;
            element.dispatchEvent(new Event("input", { bubbles: true }));
            element.dispatchEvent(new Event("change", { bubbles: true }));
          });
        } else {
          await this._client.send("DOM.setFileInputFiles", {
            objectId,
            files,
            backendNodeId
          });
        }
      }
      /**
         * This method scrolls element into view if needed, and then uses
         * {@link Touchscreen.tap} to tap in the center of the element.
         * If the element is detached from DOM, the method throws an error.
         */
      async tap() {
        await this._scrollIntoViewIfNeeded();
        const { x: x3, y: y4 } = await this._clickablePoint();
        await this._page.touchscreen.tap(x3, y4);
      }
      /**
         * Calls {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus | focus} on the element.
         */
      async focus() {
        await this.evaluate((element) => element.focus());
      }
      /**
         * Focuses the element, and then sends a `keydown`, `keypress`/`input`, and
         * `keyup` event for each character in the text.
         *
         * To press a special key, like `Control` or `ArrowDown`,
         * use {@link ElementHandle.press}.
         *
         * @example
         * ```js
         * await elementHandle.type('Hello'); // Types instantly
         * await elementHandle.type('World', {delay: 100}); // Types slower, like a user
         * ```
         *
         * @example
         * An example of typing into a text field and then submitting the form:
         *
         * ```js
         * const elementHandle = await page.$('input');
         * await elementHandle.type('some text');
         * await elementHandle.press('Enter');
         * ```
         */
      async type(text, options) {
        await this.focus();
        await this._page.keyboard.type(text, options);
      }
      /**
         * Focuses the element, and then uses {@link Keyboard.down} and {@link Keyboard.up}.
         *
         * @remarks
         * If `key` is a single character and no modifier keys besides `Shift`
         * are being held down, a `keypress`/`input` event will also be generated.
         * The `text` option can be specified to force an input event to be generated.
         *
         * **NOTE** Modifier keys DO affect `elementHandle.press`. Holding down `Shift`
         * will type the text in upper case.
         *
         * @param key - Name of key to press, such as `ArrowLeft`.
         *    See {@link KeyInput} for a list of all key names.
         */
      async press(key, options) {
        await this.focus();
        await this._page.keyboard.press(key, options);
      }
      /**
         * This method returns the bounding box of the element (relative to the main frame),
         * or `null` if the element is not visible.
         */
      async boundingBox() {
        const result2 = await this._getBoxModel();
        if (!result2) {
          return null;
        }
        const quad = result2.model.border;
        const x3 = Math.min(quad[0], quad[2], quad[4], quad[6]);
        const y4 = Math.min(quad[1], quad[3], quad[5], quad[7]);
        const width = Math.max(quad[0], quad[2], quad[4], quad[6]) - x3;
        const height = Math.max(quad[1], quad[3], quad[5], quad[7]) - y4;
        return { x: x3, y: y4, width, height };
      }
      /**
         * This method returns boxes of the element, or `null` if the element is not visible.
         *
         * @remarks
         *
         * Boxes are represented as an array of points;
         * Each Point is an object `{x, y}`. Box points are sorted clock-wise.
         */
      async boxModel() {
        const result2 = await this._getBoxModel();
        if (!result2) {
          return null;
        }
        const { content, padding: padding3, border: border2, margin, width, height } = result2.model;
        return {
          content: this._fromProtocolQuad(content),
          padding: this._fromProtocolQuad(padding3),
          border: this._fromProtocolQuad(border2),
          margin: this._fromProtocolQuad(margin),
          width,
          height
        };
      }
      /**
         * This method scrolls element into view if needed, and then uses
         * {@link Page.screenshot} to take a screenshot of the element.
         * If the element is detached from DOM, the method throws an error.
         */
      async screenshot(options = {}) {
        let needsViewportReset = false;
        let boundingBox = await this.boundingBox();
        assert3(boundingBox, "Node is either not visible or not an HTMLElement");
        const viewport = this._page.viewport();
        if (viewport && (boundingBox.width > viewport.width || boundingBox.height > viewport.height)) {
          const newViewport = {
            width: Math.max(viewport.width, Math.ceil(boundingBox.width)),
            height: Math.max(viewport.height, Math.ceil(boundingBox.height))
          };
          await this._page.setViewport(Object.assign({}, viewport, newViewport));
          needsViewportReset = true;
        }
        await this._scrollIntoViewIfNeeded();
        boundingBox = await this.boundingBox();
        assert3(boundingBox, "Node is either not visible or not an HTMLElement");
        assert3(boundingBox.width !== 0, "Node has 0 width.");
        assert3(boundingBox.height !== 0, "Node has 0 height.");
        const { layoutViewport: { pageX, pageY } } = await this._client.send(
          "Page.getLayoutMetrics"
        );
        const clip = Object.assign({}, boundingBox);
        clip.x += pageX;
        clip.y += pageY;
        const imageData = await this._page.screenshot(Object.assign({}, {
          clip
        }, options));
        if (needsViewportReset) {
          await this._page.setViewport(viewport);
        }
        return imageData;
      }
      /**
         * Runs `element.querySelector` within the page. If no element matches the selector,
         * the return value resolves to `null`.
         */
      async $(selector) {
        const { updatedSelector, queryHandler } = getQueryHandlerAndSelector(
          selector
        );
        return queryHandler.queryOne(this, updatedSelector);
      }
      /**
         * Runs `element.querySelectorAll` within the page. If no elements match the selector,
         * the return value resolves to `[]`.
         */
      async $$(selector) {
        const { updatedSelector, queryHandler } = getQueryHandlerAndSelector(
          selector
        );
        return queryHandler.queryAll(this, updatedSelector);
      }
      /**
         * This method runs `document.querySelector` within the element and passes it as
         * the first argument to `pageFunction`. If there's no element matching `selector`,
         * the method throws an error.
         *
         * If `pageFunction` returns a Promise, then `frame.$eval` would wait for the promise
         * to resolve and return its value.
         *
         * @example
         * ```js
         * const tweetHandle = await page.$('.tweet');
         * expect(await tweetHandle.$eval('.like', node => node.innerText)).toBe('100');
         * expect(await tweetHandle.$eval('.retweets', node => node.innerText)).toBe('10');
         * ```
         */
      async $eval(selector, pageFunction, ...args) {
        const elementHandle = await this.$(selector);
        if (!elementHandle) {
          throw new Error(
            `Error: failed to find element matching selector "${selector}"`
          );
        }
        const result2 = await elementHandle.evaluate(pageFunction, ...args);
        await elementHandle.dispose();
        return result2;
      }
      /**
         * This method runs `document.querySelectorAll` within the element and passes it as
         * the first argument to `pageFunction`. If there's no element matching `selector`,
         * the method throws an error.
         *
         * If `pageFunction` returns a Promise, then `frame.$$eval` would wait for the
         * promise to resolve and return its value.
         *
         * @example
         * ```html
         * <div class="feed">
         *   <div class="tweet">Hello!</div>
         *   <div class="tweet">Hi!</div>
         * </div>
         * ```
         *
         * @example
         * ```js
         * const feedHandle = await page.$('.feed');
         * expect(await feedHandle.$$eval('.tweet', nodes => nodes.map(n => n.innerText)))
         *  .toEqual(['Hello!', 'Hi!']);
         * ```
         */
      async $$eval(selector, pageFunction, ...args) {
        const { updatedSelector, queryHandler } = getQueryHandlerAndSelector(
          selector
        );
        const arrayHandle = await queryHandler.queryAllArray(this, updatedSelector);
        const result2 = await arrayHandle.evaluate(pageFunction, ...args);
        await arrayHandle.dispose();
        return result2;
      }
      /**
         * The method evaluates the XPath expression relative to the elementHandle.
         * If there are no such elements, the method will resolve to an empty array.
         * @param expression - Expression to {@link https://developer.mozilla.org/en-US/docs/Web/API/Document/evaluate | evaluate}
         */
      async $x(expression) {
        const arrayHandle = await this.evaluateHandle((element, expression2) => {
          const document2 = element.ownerDocument || element;
          const iterator = document2.evaluate(
            expression2,
            element,
            null,
            XPathResult.ORDERED_NODE_ITERATOR_TYPE
          );
          const array = [];
          let item;
          while (item = iterator.iterateNext()) {
            array.push(item);
          }
          return array;
        }, expression);
        const properties = await arrayHandle.getProperties();
        await arrayHandle.dispose();
        const result2 = [];
        for (const property of properties.values()) {
          const elementHandle = property.asElement();
          if (elementHandle) {
            result2.push(elementHandle);
          }
        }
        return result2;
      }
      /**
         * Resolves to true if the element is visible in the current viewport.
         */
      async isIntersectingViewport() {
        return await this.evaluate(async (element) => {
          const visibleRatio = await new Promise((resolve16) => {
            const observer = new IntersectionObserver((entries) => {
              resolve16(entries[0].intersectionRatio);
              observer.disconnect();
            });
            observer.observe(element);
          });
          return visibleRatio > 0;
        });
      }
    };
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/ExecutionContext.js
var EVALUATION_SCRIPT_URL, SOURCE_URL_REGEX, ExecutionContext;
var init_ExecutionContext = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/ExecutionContext.js"() {
    init_assert2();
    init_helper();
    init_JSHandle();
    EVALUATION_SCRIPT_URL = "__puppeteer_evaluation_script__";
    SOURCE_URL_REGEX = /^[\040\t]*\/\/[@#] sourceURL=\s*(\S*?)\s*$/m;
    ExecutionContext = class {
      /**
         * @internal
         */
      constructor(client, contextPayload, world) {
        this._client = client;
        this._world = world;
        this._contextId = contextPayload.id;
        this._contextName = contextPayload.name;
      }
      /**
         * @remarks
         *
         * Not every execution context is associated with a frame. For
         * example, workers and extensions have execution contexts that are not
         * associated with frames.
         *
         * @returns The frame associated with this execution context.
         */
      frame() {
        return this._world ? this._world.frame() : null;
      }
      /**
         * @remarks
         * If the function passed to the `executionContext.evaluate` returns a
         * Promise, then `executionContext.evaluate` would wait for the promise to
         * resolve and return its value. If the function passed to the
         * `executionContext.evaluate` returns a non-serializable value, then
         * `executionContext.evaluate` resolves to `undefined`. DevTools Protocol also
         * supports transferring some additional values that are not serializable by
         * `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`, and bigint literals.
         *
         *
         * @example
         * ```js
         * const executionContext = await page.mainFrame().executionContext();
         * const result = await executionContext.evaluate(() => Promise.resolve(8 * 7))* ;
         * console.log(result); // prints "56"
         * ```
         *
         * @example
         * A string can also be passed in instead of a function.
         *
         * ```js
         * console.log(await executionContext.evaluate('1 + 2')); // prints "3"
         * ```
         *
         * @example
         * {@link JSHandle} instances can be passed as arguments to the
         * `executionContext.* evaluate`:
         * ```js
         * const oneHandle = await executionContext.evaluateHandle(() => 1);
         * const twoHandle = await executionContext.evaluateHandle(() => 2);
         * const result = await executionContext.evaluate(
         *    (a, b) => a + b, oneHandle, * twoHandle
         * );
         * await oneHandle.dispose();
         * await twoHandle.dispose();
         * console.log(result); // prints '3'.
         * ```
         * @param pageFunction - a function to be evaluated in the `executionContext`
         * @param args - argument to pass to the page function
         *
         * @returns A promise that resolves to the return value of the given function.
         */
      async evaluate(pageFunction, ...args) {
        return await this._evaluateInternal(true, pageFunction, ...args);
      }
      /**
         * @remarks
         * The only difference between `executionContext.evaluate` and
         * `executionContext.evaluateHandle` is that `executionContext.evaluateHandle`
         * returns an in-page object (a {@link JSHandle}).
         * If the function passed to the `executionContext.evaluateHandle` returns a
         * Promise, then `executionContext.evaluateHandle` would wait for the
         * promise to resolve and return its value.
         *
         * @example
         * ```js
         * const context = await page.mainFrame().executionContext();
         * const aHandle = await context.evaluateHandle(() => Promise.resolve(self));
         * aHandle; // Handle for the global object.
         * ```
         *
         * @example
         * A string can also be passed in instead of a function.
         *
         * ```js
         * // Handle for the '3' * object.
         * const aHandle = await context.evaluateHandle('1 + 2');
         * ```
         *
         * @example
         * JSHandle instances can be passed as arguments
         * to the `executionContext.* evaluateHandle`:
         *
         * ```js
         * const aHandle = await context.evaluateHandle(() => document.body);
         * const resultHandle = await context.evaluateHandle(body => body.innerHTML, * aHandle);
         * console.log(await resultHandle.jsonValue()); // prints body's innerHTML
         * await aHandle.dispose();
         * await resultHandle.dispose();
         * ```
         *
         * @param pageFunction - a function to be evaluated in the `executionContext`
         * @param args - argument to pass to the page function
         *
         * @returns A promise that resolves to the return value of the given function
         * as an in-page object (a {@link JSHandle}).
         */
      async evaluateHandle(pageFunction, ...args) {
        return this._evaluateInternal(false, pageFunction, ...args);
      }
      async _evaluateInternal(returnByValue, pageFunction, ...args) {
        const suffix = `//# sourceURL=${EVALUATION_SCRIPT_URL}`;
        if (helper.isString(pageFunction)) {
          const contextId = this._contextId;
          const expression = pageFunction;
          const expressionWithSourceUrl = SOURCE_URL_REGEX.test(expression) ? expression : expression + "\n" + suffix;
          const { exceptionDetails: exceptionDetails2, result: remoteObject2 } = await this._client.send("Runtime.evaluate", {
            expression: expressionWithSourceUrl,
            contextId,
            returnByValue,
            awaitPromise: true,
            userGesture: true
          }).catch(rewriteError2);
          if (exceptionDetails2) {
            throw new Error(
              "Evaluation failed: " + helper.getExceptionMessage(exceptionDetails2)
            );
          }
          return returnByValue ? helper.valueFromRemoteObject(remoteObject2) : createJSHandle(this, remoteObject2);
        }
        if (typeof pageFunction !== "function") {
          throw new Error(
            `Expected to get |string| or |function| as the first argument, but got "${pageFunction}" instead.`
          );
        }
        let functionText = pageFunction.toString();
        try {
          new Function("(" + functionText + ")");
        } catch (error2) {
          if (functionText.startsWith("async ")) {
            functionText = "async function " + functionText.substring("async ".length);
          } else {
            functionText = "function " + functionText;
          }
          try {
            new Function("(" + functionText + ")");
          } catch (error3) {
            throw new Error("Passed function is not well-serializable!");
          }
        }
        let callFunctionOnPromise;
        try {
          callFunctionOnPromise = this._client.send("Runtime.callFunctionOn", {
            functionDeclaration: functionText + "\n" + suffix + "\n",
            executionContextId: this._contextId,
            arguments: args.map(convertArgument.bind(this)),
            returnByValue,
            awaitPromise: true,
            userGesture: true
          });
        } catch (error2) {
          if (error2 instanceof TypeError && error2.message.startsWith("Converting circular structure to JSON")) {
            error2.message += " Are you passing a nested JSHandle?";
          }
          throw error2;
        }
        const { exceptionDetails, result: remoteObject } = await callFunctionOnPromise.catch(rewriteError2);
        if (exceptionDetails) {
          throw new Error(
            "Evaluation failed: " + helper.getExceptionMessage(exceptionDetails)
          );
        }
        return returnByValue ? helper.valueFromRemoteObject(remoteObject) : createJSHandle(this, remoteObject);
        function convertArgument(arg) {
          if (typeof arg === "bigint") {
            return { unserializableValue: `${arg.toString()}n` };
          }
          if (Object.is(arg, -0)) {
            return { unserializableValue: "-0" };
          }
          if (Object.is(arg, Infinity)) {
            return { unserializableValue: "Infinity" };
          }
          if (Object.is(arg, -Infinity)) {
            return { unserializableValue: "-Infinity" };
          }
          if (Object.is(arg, NaN)) {
            return { unserializableValue: "NaN" };
          }
          const objectHandle = arg && arg instanceof JSHandle ? arg : null;
          if (objectHandle) {
            if (objectHandle._context !== this) {
              throw new Error(
                "JSHandles can be evaluated only in the context they were created!"
              );
            }
            if (objectHandle._disposed) {
              throw new Error("JSHandle is disposed!");
            }
            if (objectHandle._remoteObject.unserializableValue) {
              return {
                unserializableValue: objectHandle._remoteObject.unserializableValue
              };
            }
            if (!objectHandle._remoteObject.objectId) {
              return { value: objectHandle._remoteObject.value };
            }
            return { objectId: objectHandle._remoteObject.objectId };
          }
          return { value: arg };
        }
        function rewriteError2(error2) {
          if (error2.message.includes("Object reference chain is too long")) {
            return { result: { type: "undefined" } };
          }
          if (error2.message.includes("Object couldn't be returned by value")) {
            return { result: { type: "undefined" } };
          }
          if (error2.message.endsWith("Cannot find context with specified id") || error2.message.endsWith("Inspected target navigated or closed")) {
            throw new Error(
              "Execution context was destroyed, most likely because of a navigation."
            );
          }
          throw error2;
        }
      }
      /**
         * This method iterates the JavaScript heap and finds all the objects with the
         * given prototype.
         * @remarks
         * @example
         * ```js
         * // Create a Map object
         * await page.evaluate(() => window.map = new Map());
         * // Get a handle to the Map object prototype
         * const mapPrototype = await page.evaluateHandle(() => Map.prototype);
         * // Query all map instances into an array
         * const mapInstances = await page.queryObjects(mapPrototype);
         * // Count amount of map objects in heap
         * const count = await page.evaluate(maps => maps.length, mapInstances);
         * await mapInstances.dispose();
         * await mapPrototype.dispose();
         * ```
         *
         * @param prototypeHandle - a handle to the object prototype
         *
         * @returns A handle to an array of objects with the given prototype.
         */
      async queryObjects(prototypeHandle) {
        assert3(!prototypeHandle._disposed, "Prototype JSHandle is disposed!");
        assert3(
          prototypeHandle._remoteObject.objectId,
          "Prototype JSHandle must not be referencing primitive value"
        );
        const response = await this._client.send("Runtime.queryObjects", {
          prototypeObjectId: prototypeHandle._remoteObject.objectId
        });
        return createJSHandle(this, response.objects);
      }
      /**
         * @internal
         */
      async _adoptBackendNodeId(backendNodeId) {
        const { object } = await this._client.send("DOM.resolveNode", {
          backendNodeId,
          executionContextId: this._contextId
        });
        return createJSHandle(this, object);
      }
      /**
         * @internal
         */
      async _adoptElementHandle(elementHandle) {
        assert3(
          elementHandle.executionContext() !== this,
          "Cannot adopt handle that already belongs to this execution context"
        );
        assert3(this._world, "Cannot adopt handle without DOMWorld");
        const nodeInfo = await this._client.send("DOM.describeNode", {
          objectId: elementHandle._remoteObject.objectId
        });
        return this._adoptBackendNodeId(nodeInfo.node.backendNodeId);
      }
    };
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/HTTPRequest.js
function headersArray(headers) {
  const result2 = [];
  for (const name2 in headers) {
    if (!Object.is(headers[name2], void 0)) {
      result2.push({ name: name2, value: headers[name2] + "" });
    }
  }
  return result2;
}
var HTTPRequest, errorReasons, STATUS_TEXTS;
var init_HTTPRequest = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/HTTPRequest.js"() {
    init_assert2();
    init_helper();
    init_std();
    HTTPRequest = class {
      /**
         * @internal
         */
      constructor(client, frame, interceptionId, allowInterception, event, redirectChain) {
        this._failureText = null;
        this._response = null;
        this._fromMemoryCache = false;
        this._interceptionHandled = false;
        this._headers = {};
        this._client = client;
        this._requestId = event.requestId;
        this._isNavigationRequest = event.requestId === event.loaderId && event.type === "Document";
        this._interceptionId = interceptionId;
        this._allowInterception = allowInterception;
        this._url = event.request.url;
        this._resourceType = event.type.toLowerCase();
        this._method = event.request.method;
        this._postData = event.request.postData;
        this._frame = frame;
        this._redirectChain = redirectChain;
        for (const key of Object.keys(event.request.headers)) {
          this._headers[key.toLowerCase()] = event.request.headers[key];
        }
      }
      /**
         * @returns the URL of the request
         */
      url() {
        return this._url;
      }
      /**
         * Contains the request's resource type as it was perceived by the rendering
         * engine.
         */
      resourceType() {
        return this._resourceType;
      }
      /**
         * @returns the method used (`GET`, `POST`, etc.)
         */
      method() {
        return this._method;
      }
      /**
         * @returns the request's post body, if any.
         */
      postData() {
        return this._postData;
      }
      /**
         * @returns an object with HTTP headers associated with the request. All
         * header names are lower-case.
         */
      headers() {
        return this._headers;
      }
      /**
         * @returns the response for this request, if a response has been received.
         */
      response() {
        return this._response;
      }
      /**
         * @returns the frame that initiated the request.
         */
      frame() {
        return this._frame;
      }
      /**
         * @returns true if the request is the driver of the current frame's navigation.
         */
      isNavigationRequest() {
        return this._isNavigationRequest;
      }
      /**
         * @remarks
         *
         * `redirectChain` is shared between all the requests of the same chain.
         *
         * For example, if the website `http://example.com` has a single redirect to
         * `https://example.com`, then the chain will contain one request:
         *
         * ```js
         * const response = await page.goto('http://example.com');
         * const chain = response.request().redirectChain();
         * console.log(chain.length); // 1
         * console.log(chain[0].url()); // 'http://example.com'
         * ```
         *
         * If the website `https://google.com` has no redirects, then the chain will be empty:
         *
         * ```js
         * const response = await page.goto('https://google.com');
         * const chain = response.request().redirectChain();
         * console.log(chain.length); // 0
         * ```
         *
         * @returns the chain of requests - if a server responds with at least a
         * single redirect, this chain will contain all requests that were redirected.
         */
      redirectChain() {
        return this._redirectChain.slice();
      }
      /**
         * Access information about the request's failure.
         *
         * @remarks
         *
         * @example
         *
         * Example of logging all failed requests:
         *
         * ```js
         * page.on('requestfailed', request => {
         *   console.log(request.url() + ' ' + request.failure().errorText);
         * });
         * ```
         *
         * @returns `null` unless the request failed. If the request fails this can
         * return an object with `errorText` containing a human-readable error
         * message, e.g. `net::ERR_FAILED`. It is not guaranteeded that there will be
         * failure text if the request fails.
         */
      failure() {
        if (!this._failureText) {
          return null;
        }
        return {
          errorText: this._failureText
        };
      }
      /**
         * Continues request with optional request overrides.
         *
         * @remarks
         *
         * To use this, request
         * interception should be enabled with {@link Page.setRequestInterception}.
         *
         * Exception is immediately thrown if the request interception is not enabled.
         *
         * @example
         * ```js
         * await page.setRequestInterception(true);
         * page.on('request', request => {
         *   // Override headers
         *   const headers = Object.assign({}, request.headers(), {
         *     foo: 'bar', // set "foo" header
         *     origin: undefined, // remove "origin" header
         *   });
         *   request.continue({headers});
         * });
         * ```
         *
         * @param overrides - optional overrides to apply to the request.
         */
      async continue(overrides = {}) {
        if (this._url.startsWith("data:")) {
          return;
        }
        assert3(this._allowInterception, "Request Interception is not enabled!");
        assert3(!this._interceptionHandled, "Request is already handled!");
        const { url, method, postData, headers } = overrides;
        this._interceptionHandled = true;
        const postDataBinaryBase64 = postData ? encode2(postData) : void 0;
        await this._client.send("Fetch.continueRequest", {
          requestId: this._interceptionId,
          url,
          method,
          postData: postDataBinaryBase64,
          headers: headers ? headersArray(headers) : void 0
        }).catch((error2) => {
          debugError(error2);
        });
      }
      /**
         * Fulfills a request with the given response.
         *
         * @remarks
         *
         * To use this, request
         * interception should be enabled with {@link Page.setRequestInterception}.
         *
         * Exception is immediately thrown if the request interception is not enabled.
         *
         * @example
         * An example of fulfilling all requests with 404 responses:
         * ```js
         * await page.setRequestInterception(true);
         * page.on('request', request => {
         *   request.respond({
         *     status: 404,
         *     contentType: 'text/plain',
         *     body: 'Not Found!'
         *   });
         * });
         * ```
         *
         * NOTE: Mocking responses for dataURL requests is not supported.
         * Calling `request.respond` for a dataURL request is a noop.
         *
         * @param response - the response to fulfill the request with.
         */
      async respond(response) {
        if (this._url.startsWith("data:")) {
          return;
        }
        assert3(this._allowInterception, "Request Interception is not enabled!");
        assert3(!this._interceptionHandled, "Request is already handled!");
        this._interceptionHandled = true;
        const responseBody = response.body && helper.isString(response.body) ? new TextEncoder().encode(response.body) : response.body || null;
        const responseHeaders = {};
        if (response.headers) {
          for (const header of Object.keys(response.headers)) {
            responseHeaders[header.toLowerCase()] = String(
              response.headers[header]
            );
          }
        }
        if (response.contentType) {
          responseHeaders["content-type"] = response.contentType;
        }
        if (responseBody && !("content-length" in responseHeaders)) {
          responseHeaders["content-length"] = String(
            responseBody.byteLength
          );
        }
        await this._client.send("Fetch.fulfillRequest", {
          requestId: this._interceptionId,
          responseCode: response.status || 200,
          responsePhrase: STATUS_TEXTS[response.status || 200],
          responseHeaders: headersArray(responseHeaders),
          body: responseBody ? encode2(responseBody) : void 0
        }).catch((error2) => {
          debugError(error2);
        });
      }
      /**
         * Aborts a request.
         *
         * @remarks
         * To use this, request interception should be enabled with
         * {@link Page.setRequestInterception}. If it is not enabled, this method will
         * throw an exception immediately.
         *
         * @param errorCode - optional error code to provide.
         */
      async abort(errorCode = "failed") {
        if (this._url.startsWith("data:")) {
          return;
        }
        const errorReason = errorReasons[errorCode];
        assert3(errorReason, "Unknown error code: " + errorCode);
        assert3(this._allowInterception, "Request Interception is not enabled!");
        assert3(!this._interceptionHandled, "Request is already handled!");
        this._interceptionHandled = true;
        await this._client.send("Fetch.failRequest", {
          requestId: this._interceptionId,
          errorReason
        }).catch((error2) => {
          debugError(error2);
        });
      }
    };
    errorReasons = {
      aborted: "Aborted",
      accessdenied: "AccessDenied",
      addressunreachable: "AddressUnreachable",
      blockedbyclient: "BlockedByClient",
      blockedbyresponse: "BlockedByResponse",
      connectionaborted: "ConnectionAborted",
      connectionclosed: "ConnectionClosed",
      connectionfailed: "ConnectionFailed",
      connectionrefused: "ConnectionRefused",
      connectionreset: "ConnectionReset",
      internetdisconnected: "InternetDisconnected",
      namenotresolved: "NameNotResolved",
      timedout: "TimedOut",
      failed: "Failed"
    };
    STATUS_TEXTS = {
      "100": "Continue",
      "101": "Switching Protocols",
      "102": "Processing",
      "103": "Early Hints",
      "200": "OK",
      "201": "Created",
      "202": "Accepted",
      "203": "Non-Authoritative Information",
      "204": "No Content",
      "205": "Reset Content",
      "206": "Partial Content",
      "207": "Multi-Status",
      "208": "Already Reported",
      "226": "IM Used",
      "300": "Multiple Choices",
      "301": "Moved Permanently",
      "302": "Found",
      "303": "See Other",
      "304": "Not Modified",
      "305": "Use Proxy",
      "306": "Switch Proxy",
      "307": "Temporary Redirect",
      "308": "Permanent Redirect",
      "400": "Bad Request",
      "401": "Unauthorized",
      "402": "Payment Required",
      "403": "Forbidden",
      "404": "Not Found",
      "405": "Method Not Allowed",
      "406": "Not Acceptable",
      "407": "Proxy Authentication Required",
      "408": "Request Timeout",
      "409": "Conflict",
      "410": "Gone",
      "411": "Length Required",
      "412": "Precondition Failed",
      "413": "Payload Too Large",
      "414": "URI Too Long",
      "415": "Unsupported Media Type",
      "416": "Range Not Satisfiable",
      "417": "Expectation Failed",
      "418": "I'm a teapot",
      "421": "Misdirected Request",
      "422": "Unprocessable Entity",
      "423": "Locked",
      "424": "Failed Dependency",
      "425": "Too Early",
      "426": "Upgrade Required",
      "428": "Precondition Required",
      "429": "Too Many Requests",
      "431": "Request Header Fields Too Large",
      "451": "Unavailable For Legal Reasons",
      "500": "Internal Server Error",
      "501": "Not Implemented",
      "502": "Bad Gateway",
      "503": "Service Unavailable",
      "504": "Gateway Timeout",
      "505": "HTTP Version Not Supported",
      "506": "Variant Also Negotiates",
      "507": "Insufficient Storage",
      "508": "Loop Detected",
      "510": "Not Extended",
      "511": "Network Authentication Required"
    };
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/SecurityDetails.js
var SecurityDetails;
var init_SecurityDetails = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/SecurityDetails.js"() {
    SecurityDetails = class {
      /**
         * @internal
         */
      constructor(securityPayload) {
        this._subjectName = securityPayload.subjectName;
        this._issuer = securityPayload.issuer;
        this._validFrom = securityPayload.validFrom;
        this._validTo = securityPayload.validTo;
        this._protocol = securityPayload.protocol;
        this._sanList = securityPayload.sanList;
      }
      /**
         * @returns The name of the issuer of the certificate.
         */
      issuer() {
        return this._issuer;
      }
      /**
         * @returns {@link https://en.wikipedia.org/wiki/Unix_time | Unix timestamp}
         * marking the start of the certificate's validity.
         */
      validFrom() {
        return this._validFrom;
      }
      /**
         * @returns {@link https://en.wikipedia.org/wiki/Unix_time | Unix timestamp}
         * marking the end of the certificate's validity.
         */
      validTo() {
        return this._validTo;
      }
      /**
         * @returns The security protocol being used, e.g. "TLS 1.2".
         */
      protocol() {
        return this._protocol;
      }
      /**
         * @returns The name of the subject to which the certificate was issued.
         */
      subjectName() {
        return this._subjectName;
      }
      /**
         * @returns The list of {@link https://en.wikipedia.org/wiki/Subject_Alternative_Name | subject alternative names (SANs)} of the certificate.
         */
      subjectAlternativeNames() {
        return this._sanList;
      }
    };
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/HTTPResponse.js
var HTTPResponse;
var init_HTTPResponse = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/HTTPResponse.js"() {
    init_SecurityDetails();
    HTTPResponse = class {
      /**
         * @internal
         */
      constructor(client, request2, responsePayload) {
        this._contentPromise = null;
        this._headers = {};
        this._client = client;
        this._request = request2;
        this._bodyLoadedPromise = new Promise((fulfill) => {
          this._bodyLoadedPromiseFulfill = fulfill;
        });
        this._remoteAddress = {
          ip: responsePayload.remoteIPAddress,
          port: responsePayload.remotePort
        };
        this._status = responsePayload.status;
        this._statusText = responsePayload.statusText;
        this._url = request2.url();
        this._fromDiskCache = !!responsePayload.fromDiskCache;
        this._fromServiceWorker = !!responsePayload.fromServiceWorker;
        for (const key of Object.keys(responsePayload.headers)) {
          this._headers[key.toLowerCase()] = responsePayload.headers[key];
        }
        this._securityDetails = responsePayload.securityDetails ? new SecurityDetails(responsePayload.securityDetails) : null;
      }
      /**
         * @internal
         */
      _resolveBody(err2) {
        return this._bodyLoadedPromiseFulfill(err2);
      }
      /**
         * @returns The IP address and port number used to connect to the remote
         * server.
         */
      remoteAddress() {
        return this._remoteAddress;
      }
      /**
         * @returns The URL of the response.
         */
      url() {
        return this._url;
      }
      /**
         * @returns True if the response was successful (status in the range 200-299).
         */
      ok() {
        return this._status === 0 || this._status >= 200 && this._status <= 299;
      }
      /**
         * @returns The status code of the response (e.g., 200 for a success).
         */
      status() {
        return this._status;
      }
      /**
         * @returns  The status text of the response (e.g. usually an "OK" for a
         * success).
         */
      statusText() {
        return this._statusText;
      }
      /**
         * @returns An object with HTTP headers associated with the response. All
         * header names are lower-case.
         */
      headers() {
        return this._headers;
      }
      /**
         * @returns {@link SecurityDetails} if the response was received over the
         * secure connection, or `null` otherwise.
         */
      securityDetails() {
        return this._securityDetails;
      }
      /**
         * @returns Promise which resolves to an arraybuffer with response body.
         */
      arrayBuffer() {
        if (!this._contentPromise) {
          this._contentPromise = this._bodyLoadedPromise.then(async (error2) => {
            if (error2) {
              throw error2;
            }
            const response = await this._client.send("Network.getResponseBody", {
              requestId: this._request._requestId
            });
            return response.base64Encoded ? base64Decode(response.body) : new TextEncoder().encode(response.body);
          });
        }
        return this._contentPromise;
      }
      /**
         * @returns Promise which resolves to a text representation of response body.
         */
      async text() {
        const content = await this.arrayBuffer();
        return new TextDecoder().decode(content);
      }
      /**
         *
         * @returns Promise which resolves to a JSON representation of response body.
         *
         * @remarks
         *
         * This method will throw if the response body is not parsable via
         * `JSON.parse`.
         */
      async json() {
        const content = await this.text();
        return JSON.parse(content);
      }
      /**
         * @returns A matching {@link HTTPRequest} object.
         */
      request() {
        return this._request;
      }
      /**
         * @returns True if the response was served from either the browser's disk
         * cache or memory cache.
         */
      fromCache() {
        return this._fromDiskCache || this._request._fromMemoryCache;
      }
      /**
         * @returns True if the response was served by a service worker.
         */
      fromServiceWorker() {
        return this._fromServiceWorker;
      }
      /**
         * @returns A {@link Frame} that initiated this response, or `null` if
         * navigating to error pages.
         */
      frame() {
        return this._request.frame();
      }
    };
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/NetworkManager.js
var NetworkManagerEmittedEvents, NetworkManager;
var init_NetworkManager = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/NetworkManager.js"() {
    init_EventEmitter();
    init_assert2();
    init_helper();
    init_HTTPRequest();
    init_HTTPResponse();
    NetworkManagerEmittedEvents = {
      Request: /* @__PURE__ */ Symbol("NetworkManager.Request"),
      RequestServedFromCache: /* @__PURE__ */ Symbol("NetworkManager.RequestServedFromCache"),
      Response: /* @__PURE__ */ Symbol("NetworkManager.Response"),
      RequestFailed: /* @__PURE__ */ Symbol("NetworkManager.RequestFailed"),
      RequestFinished: /* @__PURE__ */ Symbol("NetworkManager.RequestFinished")
    };
    NetworkManager = class extends EventEmitter2 {
      constructor(client, ignoreHTTPSErrors, frameManager) {
        super();
        this._requestIdToRequest = /* @__PURE__ */ new Map();
        this._requestIdToRequestWillBeSentEvent = /* @__PURE__ */ new Map();
        this._extraHTTPHeaders = {};
        this._credentials = null;
        this._attemptedAuthentications = /* @__PURE__ */ new Set();
        this._userRequestInterceptionEnabled = false;
        this._userRequestInterceptionCacheSafe = false;
        this._protocolRequestInterceptionEnabled = false;
        this._userCacheDisabled = false;
        this._requestIdToInterceptionId = /* @__PURE__ */ new Map();
        this._emulatedNetworkConditions = {
          offline: false,
          upload: -1,
          download: -1,
          latency: 0
        };
        this._client = client;
        this._ignoreHTTPSErrors = ignoreHTTPSErrors;
        this._frameManager = frameManager;
        this._client.on("Fetch.requestPaused", this._onRequestPaused.bind(this));
        this._client.on("Fetch.authRequired", this._onAuthRequired.bind(this));
        this._client.on(
          "Network.requestWillBeSent",
          this._onRequestWillBeSent.bind(this)
        );
        this._client.on(
          "Network.requestServedFromCache",
          this._onRequestServedFromCache.bind(this)
        );
        this._client.on(
          "Network.responseReceived",
          this._onResponseReceived.bind(this)
        );
        this._client.on(
          "Network.loadingFinished",
          this._onLoadingFinished.bind(this)
        );
        this._client.on("Network.loadingFailed", this._onLoadingFailed.bind(this));
      }
      async initialize() {
        await this._client.send("Network.enable");
        if (this._ignoreHTTPSErrors) {
          await this._client.send("Security.setIgnoreCertificateErrors", {
            ignore: true
          });
        }
      }
      async authenticate(credentials) {
        this._credentials = credentials;
        await this._updateProtocolRequestInterception();
      }
      async setExtraHTTPHeaders(extraHTTPHeaders) {
        this._extraHTTPHeaders = {};
        for (const key of Object.keys(extraHTTPHeaders)) {
          const value = extraHTTPHeaders[key];
          assert3(
            helper.isString(value),
            `Expected value of header "${key}" to be String, but "${typeof value}" is found.`
          );
          this._extraHTTPHeaders[key.toLowerCase()] = value;
        }
        await this._client.send("Network.setExtraHTTPHeaders", {
          headers: this._extraHTTPHeaders
        });
      }
      extraHTTPHeaders() {
        return Object.assign({}, this._extraHTTPHeaders);
      }
      async setOfflineMode(value) {
        this._emulatedNetworkConditions.offline = value;
        await this._updateNetworkConditions();
      }
      async emulateNetworkConditions(networkConditions2) {
        this._emulatedNetworkConditions.upload = networkConditions2 ? networkConditions2.upload : -1;
        this._emulatedNetworkConditions.download = networkConditions2 ? networkConditions2.download : -1;
        this._emulatedNetworkConditions.latency = networkConditions2 ? networkConditions2.latency : 0;
        await this._updateNetworkConditions();
      }
      async _updateNetworkConditions() {
        await this._client.send("Network.emulateNetworkConditions", {
          offline: this._emulatedNetworkConditions.offline,
          latency: this._emulatedNetworkConditions.latency,
          uploadThroughput: this._emulatedNetworkConditions.upload,
          downloadThroughput: this._emulatedNetworkConditions.download
        });
      }
      async setUserAgent(userAgent) {
        await this._client.send("Network.setUserAgentOverride", { userAgent });
      }
      async setCacheEnabled(enabled5) {
        this._userCacheDisabled = !enabled5;
        await this._updateProtocolCacheDisabled();
      }
      async setRequestInterception(value, cacheSafe = false) {
        this._userRequestInterceptionEnabled = value;
        this._userRequestInterceptionCacheSafe = cacheSafe;
        await this._updateProtocolRequestInterception();
      }
      async _updateProtocolRequestInterception() {
        const enabled5 = this._userRequestInterceptionEnabled || !!this._credentials;
        if (enabled5 === this._protocolRequestInterceptionEnabled) {
          return;
        }
        this._protocolRequestInterceptionEnabled = enabled5;
        if (enabled5) {
          await Promise.all([
            this._updateProtocolCacheDisabled(),
            this._client.send("Fetch.enable", {
              handleAuthRequests: true,
              patterns: [{ urlPattern: "*" }]
            })
          ]);
        } else {
          await Promise.all([
            this._updateProtocolCacheDisabled(),
            this._client.send("Fetch.disable")
          ]);
        }
      }
      async _updateProtocolCacheDisabled() {
        await this._client.send("Network.setCacheDisabled", {
          cacheDisabled: this._userCacheDisabled || this._userRequestInterceptionEnabled && !this._userRequestInterceptionCacheSafe
        });
      }
      _onRequestWillBeSent(event) {
        if (this._userRequestInterceptionEnabled && !event.request.url.startsWith("data:")) {
          const requestId = event.requestId;
          const interceptionId = this._requestIdToInterceptionId.get(requestId);
          if (interceptionId) {
            this._onRequest(event, interceptionId);
            this._requestIdToInterceptionId.delete(requestId);
          } else {
            this._requestIdToRequestWillBeSentEvent.set(event.requestId, event);
          }
          return;
        }
        this._onRequest(event, null);
      }
      _onAuthRequired(event) {
        let response = "Default";
        if (this._attemptedAuthentications.has(event.requestId)) {
          response = "CancelAuth";
        } else if (this._credentials) {
          response = "ProvideCredentials";
          this._attemptedAuthentications.add(event.requestId);
        }
        const { username, password } = this._credentials || {
          username: void 0,
          password: void 0
        };
        this._client.send("Fetch.continueWithAuth", {
          requestId: event.requestId,
          authChallengeResponse: { response, username, password }
        }).catch(debugError);
      }
      _onRequestPaused(event) {
        if (!this._userRequestInterceptionEnabled && this._protocolRequestInterceptionEnabled) {
          this._client.send("Fetch.continueRequest", {
            requestId: event.requestId
          }).catch(debugError);
        }
        const requestId = event.networkId;
        const interceptionId = event.requestId;
        if (requestId && this._requestIdToRequestWillBeSentEvent.has(requestId)) {
          const requestWillBeSentEvent = this._requestIdToRequestWillBeSentEvent.get(requestId);
          this._onRequest(requestWillBeSentEvent, interceptionId);
          this._requestIdToRequestWillBeSentEvent.delete(requestId);
        } else {
          this._requestIdToInterceptionId.set(requestId, interceptionId);
        }
      }
      _onRequest(event, interceptionId) {
        let redirectChain = [];
        if (event.redirectResponse) {
          const request3 = this._requestIdToRequest.get(event.requestId);
          if (request3) {
            this._handleRequestRedirect(request3, event.redirectResponse);
            redirectChain = request3._redirectChain;
          }
        }
        const frame = event.frameId ? this._frameManager.frame(event.frameId) : null;
        const request2 = new HTTPRequest(
          this._client,
          frame,
          interceptionId,
          this._userRequestInterceptionEnabled,
          event,
          redirectChain
        );
        this._requestIdToRequest.set(event.requestId, request2);
        this.emit(NetworkManagerEmittedEvents.Request, request2);
      }
      _onRequestServedFromCache(event) {
        const request2 = this._requestIdToRequest.get(event.requestId);
        if (request2) {
          request2._fromMemoryCache = true;
        }
        this.emit(NetworkManagerEmittedEvents.RequestServedFromCache, request2);
      }
      _handleRequestRedirect(request2, responsePayload) {
        const response = new HTTPResponse(this._client, request2, responsePayload);
        request2._response = response;
        request2._redirectChain.push(request2);
        response._resolveBody(
          new Error("Response body is unavailable for redirect responses")
        );
        this._requestIdToRequest.delete(request2._requestId);
        this._attemptedAuthentications.delete(request2._interceptionId);
        this.emit(NetworkManagerEmittedEvents.Response, response);
        this.emit(NetworkManagerEmittedEvents.RequestFinished, request2);
      }
      _onResponseReceived(event) {
        const request2 = this._requestIdToRequest.get(event.requestId);
        if (!request2) {
          return;
        }
        const response = new HTTPResponse(this._client, request2, event.response);
        request2._response = response;
        this.emit(NetworkManagerEmittedEvents.Response, response);
      }
      _onLoadingFinished(event) {
        const request2 = this._requestIdToRequest.get(event.requestId);
        if (!request2) {
          return;
        }
        if (request2.response()) {
          request2.response()._resolveBody(null);
        }
        this._requestIdToRequest.delete(request2._requestId);
        this._attemptedAuthentications.delete(request2._interceptionId);
        this.emit(NetworkManagerEmittedEvents.RequestFinished, request2);
      }
      _onLoadingFailed(event) {
        const request2 = this._requestIdToRequest.get(event.requestId);
        if (!request2) {
          return;
        }
        request2._failureText = event.errorText;
        const response = request2.response();
        if (response) {
          response._resolveBody(null);
        }
        this._requestIdToRequest.delete(request2._requestId);
        this._attemptedAuthentications.delete(request2._interceptionId);
        this.emit(NetworkManagerEmittedEvents.RequestFailed, request2);
      }
    };
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/LifecycleWatcher.js
var puppeteerToProtocolLifecycle, LifecycleWatcher;
var init_LifecycleWatcher = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/LifecycleWatcher.js"() {
    init_assert2();
    init_helper();
    init_Errors();
    init_FrameManager();
    init_NetworkManager();
    init_Connection();
    puppeteerToProtocolLifecycle = /* @__PURE__ */ new Map([
      ["load", "load"],
      ["domcontentloaded", "DOMContentLoaded"],
      ["networkidle0", "networkIdle"],
      ["networkidle2", "networkAlmostIdle"]
    ]);
    LifecycleWatcher = class {
      constructor(frameManager, frame, waitUntil, timeout) {
        if (Array.isArray(waitUntil)) {
          waitUntil = waitUntil.slice();
        } else if (typeof waitUntil === "string") {
          waitUntil = [waitUntil];
        }
        this._expectedLifecycle = waitUntil.map((value) => {
          const protocolEvent = puppeteerToProtocolLifecycle.get(value);
          assert3(protocolEvent, "Unknown value for options.waitUntil: " + value);
          return protocolEvent;
        });
        this._frameManager = frameManager;
        this._frame = frame;
        this._initialLoaderId = frame._loaderId;
        this._timeout = timeout;
        this._navigationRequest = null;
        this._eventListeners = [
          helper.addEventListener(
            frameManager._client,
            CDPSessionEmittedEvents.Disconnected,
            () => this._terminate(
              new Error("Navigation failed because browser has disconnected!")
            )
          ),
          helper.addEventListener(
            this._frameManager,
            FrameManagerEmittedEvents.LifecycleEvent,
            this._checkLifecycleComplete.bind(this)
          ),
          helper.addEventListener(
            this._frameManager,
            FrameManagerEmittedEvents.FrameNavigatedWithinDocument,
            this._navigatedWithinDocument.bind(this)
          ),
          helper.addEventListener(
            this._frameManager,
            FrameManagerEmittedEvents.FrameDetached,
            this._onFrameDetached.bind(this)
          ),
          helper.addEventListener(
            this._frameManager.networkManager(),
            NetworkManagerEmittedEvents.Request,
            this._onRequest.bind(this)
          )
        ];
        this._sameDocumentNavigationPromise = new Promise((fulfill) => {
          this._sameDocumentNavigationCompleteCallback = fulfill;
        });
        this._lifecyclePromise = new Promise((fulfill) => {
          this._lifecycleCallback = fulfill;
        });
        this._newDocumentNavigationPromise = new Promise((fulfill) => {
          this._newDocumentNavigationCompleteCallback = fulfill;
        });
        this._timeoutPromise = this._createTimeoutPromise();
        this._terminationPromise = new Promise((fulfill) => {
          this._terminationCallback = fulfill;
        });
        this._checkLifecycleComplete();
      }
      _onRequest(request2) {
        if (request2.frame() !== this._frame || !request2.isNavigationRequest()) {
          return;
        }
        this._navigationRequest = request2;
      }
      _onFrameDetached(frame) {
        if (this._frame === frame) {
          this._terminationCallback.call(
            null,
            new Error("Navigating frame was detached")
          );
          return;
        }
        this._checkLifecycleComplete();
      }
      navigationResponse() {
        return this._navigationRequest ? this._navigationRequest.response() : null;
      }
      _terminate(error2) {
        this._terminationCallback.call(null, error2);
      }
      sameDocumentNavigationPromise() {
        return this._sameDocumentNavigationPromise;
      }
      newDocumentNavigationPromise() {
        return this._newDocumentNavigationPromise;
      }
      lifecyclePromise() {
        return this._lifecyclePromise;
      }
      timeoutOrTerminationPromise() {
        return Promise.race([this._timeoutPromise, this._terminationPromise]);
      }
      _createTimeoutPromise() {
        if (!this._timeout) {
          return new Promise(() => {
          });
        }
        const errorMessage = "Navigation timeout of " + this._timeout + " ms exceeded";
        return new Promise((fulfill) => this._maximumTimer = setTimeout(fulfill, this._timeout)).then(
          () => new TimeoutError(errorMessage)
        );
      }
      _navigatedWithinDocument(frame) {
        if (frame !== this._frame) {
          return;
        }
        this._hasSameDocumentNavigation = true;
        this._checkLifecycleComplete();
      }
      _checkLifecycleComplete() {
        if (!checkLifecycle(this._frame, this._expectedLifecycle)) {
          return;
        }
        this._lifecycleCallback();
        if (this._frame._loaderId === this._initialLoaderId && !this._hasSameDocumentNavigation) {
          return;
        }
        if (this._hasSameDocumentNavigation) {
          this._sameDocumentNavigationCompleteCallback();
        }
        if (this._frame._loaderId !== this._initialLoaderId) {
          this._newDocumentNavigationCompleteCallback();
        }
        function checkLifecycle(frame, expectedLifecycle) {
          for (const event of expectedLifecycle) {
            if (!frame._lifecycleEvents.has(event)) {
              return false;
            }
          }
          for (const child of frame.childFrames()) {
            if (!checkLifecycle(child, expectedLifecycle)) {
              return false;
            }
          }
          return true;
        }
      }
      dispose() {
        helper.removeEventListeners(this._eventListeners);
        clearTimeout(this._maximumTimer);
      }
    };
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/DOMWorld.js
async function waitForPredicatePageFunction(predicateBody, polling, timeout, ...args) {
  const predicate = new Function("...args", predicateBody);
  let timedOut = false;
  if (timeout) {
    setTimeout(() => timedOut = true, timeout);
  }
  if (polling === "raf") {
    return await pollRaf();
  }
  if (polling === "mutation") {
    return await pollMutation();
  }
  if (typeof polling === "number") {
    return await pollInterval(polling);
  }
  async function pollMutation() {
    const success = await predicate(...args);
    if (success) {
      return Promise.resolve(success);
    }
    let fulfill;
    const result2 = new Promise((x3) => fulfill = x3);
    const observer = new MutationObserver(async () => {
      if (timedOut) {
        observer.disconnect();
        fulfill();
      }
      const success2 = await predicate(...args);
      if (success2) {
        observer.disconnect();
        fulfill(success2);
      }
    });
    observer.observe(document, {
      childList: true,
      subtree: true,
      attributes: true
    });
    return result2;
  }
  async function pollRaf() {
    let fulfill;
    const result2 = new Promise((x3) => fulfill = x3);
    await onRaf();
    return result2;
    async function onRaf() {
      if (timedOut) {
        fulfill();
        return;
      }
      const success = await predicate(...args);
      if (success) {
        fulfill(success);
      } else {
        requestAnimationFrame(onRaf);
      }
    }
  }
  async function pollInterval(pollInterval2) {
    let fulfill;
    const result2 = new Promise((x3) => fulfill = x3);
    await onTimeout();
    return result2;
    async function onTimeout() {
      if (timedOut) {
        fulfill();
        return;
      }
      const success = await predicate(...args);
      if (success) {
        fulfill(success);
      } else {
        setTimeout(onTimeout, pollInterval2);
      }
    }
  }
}
var DOMWorld, WaitTask;
var init_DOMWorld = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/DOMWorld.js"() {
    init_assert2();
    init_helper();
    init_LifecycleWatcher();
    init_Errors();
    init_QueryHandler();
    DOMWorld = class _DOMWorld {
      constructor(frameManager, frame, timeoutSettings) {
        this._documentPromise = null;
        this._contextPromise = null;
        this._contextResolveCallback = null;
        this._detached = false;
        this._waitTasks = /* @__PURE__ */ new Set();
        this._boundFunctions = /* @__PURE__ */ new Map();
        this._ctxBindings = /* @__PURE__ */ new Set();
        this._settingUpBinding = null;
        this._frameManager = frameManager;
        this._frame = frame;
        this._timeoutSettings = timeoutSettings;
        this._setContext(null);
        frameManager._client.on(
          "Runtime.bindingCalled",
          (event) => this._onBindingCalled(event)
        );
      }
      frame() {
        return this._frame;
      }
      async _setContext(context) {
        if (context) {
          this._ctxBindings.clear();
          this._contextResolveCallback.call(null, context);
          this._contextResolveCallback = null;
          for (const waitTask of this._waitTasks) {
            waitTask.rerun();
          }
        } else {
          this._documentPromise = null;
          this._contextPromise = new Promise((fulfill) => {
            this._contextResolveCallback = fulfill;
          });
        }
      }
      _hasContext() {
        return !this._contextResolveCallback;
      }
      _detach() {
        this._detached = true;
        for (const waitTask of this._waitTasks) {
          waitTask.terminate(
            new Error("waitForFunction failed: frame got detached.")
          );
        }
      }
      executionContext() {
        if (this._detached) {
          throw new Error(
            `Execution context is not available in detached frame "${this._frame.url()}" (are you trying to evaluate?)`
          );
        }
        return this._contextPromise;
      }
      async evaluateHandle(pageFunction, ...args) {
        const context = await this.executionContext();
        return context.evaluateHandle(pageFunction, ...args);
      }
      async evaluate(pageFunction, ...args) {
        const context = await this.executionContext();
        return context.evaluate(pageFunction, ...args);
      }
      async $(selector) {
        const document2 = await this._document();
        const value = await document2.$(selector);
        return value;
      }
      async _document() {
        if (this._documentPromise) {
          return this._documentPromise;
        }
        this._documentPromise = this.executionContext().then(async (context) => {
          const document2 = await context.evaluateHandle("document");
          return document2.asElement();
        });
        return this._documentPromise;
      }
      async $x(expression) {
        const document2 = await this._document();
        const value = await document2.$x(expression);
        return value;
      }
      async $eval(selector, pageFunction, ...args) {
        const document2 = await this._document();
        return document2.$eval(selector, pageFunction, ...args);
      }
      async $$eval(selector, pageFunction, ...args) {
        const document2 = await this._document();
        const value = await document2.$$eval(selector, pageFunction, ...args);
        return value;
      }
      async $$(selector) {
        const document2 = await this._document();
        const value = await document2.$$(selector);
        return value;
      }
      async content() {
        return await this.evaluate(() => {
          let retVal = "";
          if (document.doctype) {
            retVal = new XMLSerializer().serializeToString(document.doctype);
          }
          if (document.documentElement) {
            retVal += document.documentElement.outerHTML;
          }
          return retVal;
        });
      }
      async setContent(html, options = {}) {
        const {
          waitUntil = ["load"],
          timeout = this._timeoutSettings.navigationTimeout()
        } = options;
        await this.evaluate((html2) => {
          document.open();
          document.write(html2);
          document.close();
        }, html);
        const watcher = new LifecycleWatcher(
          this._frameManager,
          this._frame,
          waitUntil,
          timeout
        );
        const error2 = await Promise.race([
          watcher.timeoutOrTerminationPromise(),
          watcher.lifecyclePromise()
        ]);
        watcher.dispose();
        if (error2) {
          throw error2;
        }
      }
      /**
         * Adds a script tag into the current context.
         *
         * @remarks
         *
         * You can pass a URL, filepath or string of contents. Note that when running Puppeteer
         * in a browser environment you cannot pass a filepath and should use either
         * `url` or `content`.
         */
      async addScriptTag(options) {
        const { url = null, path: path3 = null, content = null, type: type4 = "" } = options;
        if (url !== null) {
          try {
            const context = await this.executionContext();
            return (await context.evaluateHandle(addScriptUrl, url, type4)).asElement();
          } catch (error2) {
            throw new Error(`Loading script from ${url} failed`);
          }
        }
        if (path3 !== null) {
          let contents = await Deno.readTextFile(path3);
          contents += "//# sourceURL=" + path3.replace(/\n/g, "");
          const context = await this.executionContext();
          return (await context.evaluateHandle(addScriptContent, contents, type4)).asElement();
        }
        if (content !== null) {
          const context = await this.executionContext();
          return (await context.evaluateHandle(addScriptContent, content, type4)).asElement();
        }
        throw new Error(
          "Provide an object with a `url`, `path` or `content` property"
        );
        async function addScriptUrl(url2, type5) {
          const script = document.createElement("script");
          script.src = url2;
          if (type5) {
            script.type = type5;
          }
          const promise = new Promise((res, rej) => {
            script.onload = res;
            script.onerror = rej;
          });
          document.head.appendChild(script);
          await promise;
          return script;
        }
        function addScriptContent(content2, type5 = "text/javascript") {
          const script = document.createElement("script");
          script.type = type5;
          script.text = content2;
          let error2 = null;
          script.onerror = (e5) => error2 = e5;
          document.head.appendChild(script);
          if (error2) {
            throw error2;
          }
          return script;
        }
      }
      /**
         * Adds a style tag into the current context.
         *
         * @remarks
         *
         * You can pass a URL, filepath or string of contents. Note that when running Puppeteer
         * in a browser environment you cannot pass a filepath and should use either
         * `url` or `content`.
         *
         */
      async addStyleTag(options) {
        const { url = null, path: path3 = null, content = null } = options;
        if (url !== null) {
          try {
            const context = await this.executionContext();
            return (await context.evaluateHandle(addStyleUrl, url)).asElement();
          } catch (error2) {
            throw new Error(`Loading style from ${url} failed`);
          }
        }
        if (path3 !== null) {
          let contents = await Deno.readTextFile(path3);
          contents += "/*# sourceURL=" + path3.replace(/\n/g, "") + "*/";
          const context = await this.executionContext();
          return (await context.evaluateHandle(addStyleContent, contents)).asElement();
        }
        if (content !== null) {
          const context = await this.executionContext();
          return (await context.evaluateHandle(addStyleContent, content)).asElement();
        }
        throw new Error(
          "Provide an object with a `url`, `path` or `content` property"
        );
        async function addStyleUrl(url2) {
          const link2 = document.createElement("link");
          link2.rel = "stylesheet";
          link2.href = url2;
          const promise = new Promise((res, rej) => {
            link2.onload = res;
            link2.onerror = rej;
          });
          document.head.appendChild(link2);
          await promise;
          return link2;
        }
        async function addStyleContent(content2) {
          const style = document.createElement("style");
          style.type = "text/css";
          style.appendChild(document.createTextNode(content2));
          const promise = new Promise((res, rej) => {
            style.onload = res;
            style.onerror = rej;
          });
          document.head.appendChild(style);
          await promise;
          return style;
        }
      }
      async click(selector, options) {
        const handle = await this.$(selector);
        assert3(handle, "No node found for selector: " + selector);
        await handle.click(options);
        await handle.dispose();
      }
      async focus(selector) {
        const handle = await this.$(selector);
        assert3(handle, "No node found for selector: " + selector);
        await handle.focus();
        await handle.dispose();
      }
      async hover(selector) {
        const handle = await this.$(selector);
        assert3(handle, "No node found for selector: " + selector);
        await handle.hover();
        await handle.dispose();
      }
      async select(selector, ...values) {
        const handle = await this.$(selector);
        assert3(handle, "No node found for selector: " + selector);
        const result2 = await handle.select(...values);
        await handle.dispose();
        return result2;
      }
      async tap(selector) {
        const handle = await this.$(selector);
        await handle.tap();
        await handle.dispose();
      }
      async type(selector, text, options) {
        const handle = await this.$(selector);
        assert3(handle, "No node found for selector: " + selector);
        await handle.type(text, options);
        await handle.dispose();
      }
      async waitForSelector(selector, options) {
        const { updatedSelector, queryHandler } = getQueryHandlerAndSelector(
          selector
        );
        return queryHandler.waitFor(this, updatedSelector, options);
      }
      /**
         * @internal
         */
      async addBindingToContext(context, name2) {
        if (this._ctxBindings.has(
          _DOMWorld.bindingIdentifier(name2, context._contextId)
        )) {
          return;
        }
        if (this._settingUpBinding) {
          await this._settingUpBinding;
          return this.addBindingToContext(context, name2);
        }
        const bind = async (name3) => {
          const expression = helper.pageBindingInitString("internal", name3);
          try {
            await context._client.send("Runtime.addBinding", {
              name: name3,
              //  @typescript-eslint/ban-ts-comment
              // @ts-ignore The protocol definition is not up to date.
              executionContextName: context._contextName
            });
            await context.evaluate(expression);
          } catch (error2) {
            const ctxDestroyed = error2.message.includes(
              "Execution context was destroyed"
            );
            const ctxNotFound = error2.message.includes(
              "Cannot find context with specified id"
            );
            if (ctxDestroyed || ctxNotFound) {
              return;
            } else {
              debugError(error2);
              return;
            }
          }
          this._ctxBindings.add(
            _DOMWorld.bindingIdentifier(name3, context._contextId)
          );
        };
        this._settingUpBinding = bind(name2);
        await this._settingUpBinding;
        this._settingUpBinding = null;
      }
      async _onBindingCalled(event) {
        let payload;
        if (!this._hasContext()) {
          return;
        }
        const context = await this.executionContext();
        try {
          payload = JSON.parse(event.payload);
        } catch {
          return;
        }
        const { type: type4, name: name2, seq: seq3, args } = payload;
        if (type4 !== "internal" || !this._ctxBindings.has(
          _DOMWorld.bindingIdentifier(name2, context._contextId)
        )) {
          return;
        }
        if (context._contextId !== event.executionContextId) {
          return;
        }
        try {
          const result2 = await this._boundFunctions.get(name2)(...args);
          await context.evaluate(deliverResult, name2, seq3, result2);
        } catch (error2) {
          if (error2.message.includes("Protocol error")) {
            return;
          }
          debugError(error2);
        }
        function deliverResult(name3, seq4, result2) {
          globalThis[name3].callbacks.get(seq4).resolve(result2);
          globalThis[name3].callbacks.delete(seq4);
        }
      }
      /**
         * @internal
         */
      async waitForSelectorInPage(queryOne2, selector, options, binding2) {
        const {
          visible: waitForVisible = false,
          hidden: waitForHidden = false,
          timeout = this._timeoutSettings.timeout()
        } = options;
        const polling = waitForVisible || waitForHidden ? "raf" : "mutation";
        const title3 = `selector \`${selector}\`${waitForHidden ? " to be hidden" : ""}`;
        async function predicate(selector2, waitForVisible2, waitForHidden2) {
          const node = predicateQueryHandler ? await predicateQueryHandler(document, selector2) : document.querySelector(selector2);
          return checkWaitForOptions(node, waitForVisible2, waitForHidden2);
        }
        const waitTaskOptions = {
          domWorld: this,
          predicateBody: helper.makePredicateString(predicate, queryOne2),
          title: title3,
          polling,
          timeout,
          args: [selector, waitForVisible, waitForHidden],
          binding: binding2
        };
        const waitTask = new WaitTask(waitTaskOptions);
        const jsHandle = await waitTask.promise;
        const elementHandle = jsHandle.asElement();
        if (!elementHandle) {
          await jsHandle.dispose();
          return null;
        }
        return elementHandle;
      }
      async waitForXPath(xpath, options) {
        const {
          visible: waitForVisible = false,
          hidden: waitForHidden = false,
          timeout = this._timeoutSettings.timeout()
        } = options;
        const polling = waitForVisible || waitForHidden ? "raf" : "mutation";
        const title3 = `XPath \`${xpath}\`${waitForHidden ? " to be hidden" : ""}`;
        function predicate(xpath2, waitForVisible2, waitForHidden2) {
          const node = document.evaluate(
            xpath2,
            document,
            null,
            XPathResult.FIRST_ORDERED_NODE_TYPE,
            null
          ).singleNodeValue;
          return checkWaitForOptions(node, waitForVisible2, waitForHidden2);
        }
        const waitTaskOptions = {
          domWorld: this,
          predicateBody: helper.makePredicateString(predicate),
          title: title3,
          polling,
          timeout,
          args: [xpath, waitForVisible, waitForHidden]
        };
        const waitTask = new WaitTask(waitTaskOptions);
        const jsHandle = await waitTask.promise;
        const elementHandle = jsHandle.asElement();
        if (!elementHandle) {
          await jsHandle.dispose();
          return null;
        }
        return elementHandle;
      }
      waitForFunction(pageFunction, options = {}, ...args) {
        const { polling = "raf", timeout = this._timeoutSettings.timeout() } = options;
        const waitTaskOptions = {
          domWorld: this,
          predicateBody: pageFunction,
          title: "function",
          polling,
          timeout,
          args
        };
        const waitTask = new WaitTask(waitTaskOptions);
        return waitTask.promise;
      }
      async title() {
        return this.evaluate(() => document.title);
      }
    };
    DOMWorld.bindingIdentifier = (name2, contextId) => `${name2}_${contextId}`;
    WaitTask = class {
      constructor(options) {
        this._runCount = 0;
        this._terminated = false;
        if (helper.isString(options.polling)) {
          assert3(
            options.polling === "raf" || options.polling === "mutation",
            "Unknown polling option: " + options.polling
          );
        } else if (helper.isNumber(options.polling)) {
          assert3(
            options.polling > 0,
            "Cannot poll with non-positive interval: " + options.polling
          );
        } else {
          throw new Error("Unknown polling options: " + options.polling);
        }
        function getPredicateBody(predicateBody) {
          if (helper.isString(predicateBody)) {
            return `return (${predicateBody});`;
          }
          return `return (${predicateBody})(...args);`;
        }
        this._domWorld = options.domWorld;
        this._polling = options.polling;
        this._timeout = options.timeout;
        this._predicateBody = getPredicateBody(options.predicateBody);
        this._args = options.args;
        this._binding = options.binding;
        this._runCount = 0;
        this._domWorld._waitTasks.add(this);
        if (this._binding) {
          this._domWorld._boundFunctions.set(
            this._binding.name,
            this._binding.pptrFunction
          );
        }
        this.promise = new Promise((resolve16, reject2) => {
          this._resolve = resolve16;
          this._reject = reject2;
        });
        if (options.timeout) {
          const timeoutError = new TimeoutError(
            `waiting for ${options.title} failed: timeout ${options.timeout}ms exceeded`
          );
          this._timeoutTimer = setTimeout(
            () => this.terminate(timeoutError),
            options.timeout
          );
        }
        this.rerun();
      }
      terminate(error2) {
        this._terminated = true;
        this._reject(error2);
        this._cleanup();
      }
      async rerun() {
        const runCount = ++this._runCount;
        let success = null;
        let error2 = null;
        const context = await this._domWorld.executionContext();
        if (this._terminated || runCount !== this._runCount) {
          return;
        }
        if (this._binding) {
          await this._domWorld.addBindingToContext(context, this._binding.name);
        }
        if (this._terminated || runCount !== this._runCount) {
          return;
        }
        try {
          success = await context.evaluateHandle(
            waitForPredicatePageFunction,
            this._predicateBody,
            this._polling,
            this._timeout,
            ...this._args
          );
        } catch (error_) {
          error2 = error_;
        }
        if (this._terminated || runCount !== this._runCount) {
          if (success) {
            await success.dispose();
          }
          return;
        }
        if (!error2 && await this._domWorld.evaluate((s5) => !s5, success).catch(() => true)) {
          await success.dispose();
          return;
        }
        if (error2) {
          if (error2.message.includes("TypeError: binding is not a function")) {
            return this.rerun();
          }
          if (error2.message.includes(
            "Execution context is not available in detached frame"
          )) {
            this.terminate(
              new Error("waitForFunction failed: frame got detached.")
            );
            return;
          }
          if (error2.message.includes("Execution context was destroyed")) {
            return;
          }
          if (error2.message.includes("Cannot find context with specified id")) {
            return;
          }
          this._reject(error2);
        } else {
          this._resolve(success);
        }
        this._cleanup();
      }
      _cleanup() {
        clearTimeout(this._timeoutTimer);
        this._domWorld._waitTasks.delete(this);
      }
    };
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/FrameManager.js
function assertNoLegacyNavigationOptions(options) {
  assert3(
    options["networkIdleTimeout"] === void 0,
    "ERROR: networkIdleTimeout option is no longer supported."
  );
  assert3(
    options["networkIdleInflight"] === void 0,
    "ERROR: networkIdleInflight option is no longer supported."
  );
  assert3(
    options.waitUntil !== "networkidle",
    'ERROR: "networkidle" option is no longer supported. Use "networkidle2" instead'
  );
}
var UTILITY_WORLD_NAME, FrameManagerEmittedEvents, FrameManager, Frame;
var init_FrameManager = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/FrameManager.js"() {
    init_Debug();
    init_EventEmitter();
    init_assert2();
    init_helper();
    init_ExecutionContext();
    init_LifecycleWatcher();
    init_DOMWorld();
    init_NetworkManager();
    UTILITY_WORLD_NAME = "__puppeteer_utility_world__";
    FrameManagerEmittedEvents = {
      FrameAttached: /* @__PURE__ */ Symbol("FrameManager.FrameAttached"),
      FrameNavigated: /* @__PURE__ */ Symbol("FrameManager.FrameNavigated"),
      FrameDetached: /* @__PURE__ */ Symbol("FrameManager.FrameDetached"),
      LifecycleEvent: /* @__PURE__ */ Symbol("FrameManager.LifecycleEvent"),
      FrameNavigatedWithinDocument: /* @__PURE__ */ Symbol(
        "FrameManager.FrameNavigatedWithinDocument"
      ),
      ExecutionContextCreated: /* @__PURE__ */ Symbol("FrameManager.ExecutionContextCreated"),
      ExecutionContextDestroyed: /* @__PURE__ */ Symbol("FrameManager.ExecutionContextDestroyed")
    };
    FrameManager = class extends EventEmitter2 {
      constructor(client, page, ignoreHTTPSErrors, timeoutSettings) {
        super();
        this._frames = /* @__PURE__ */ new Map();
        this._contextIdToContext = /* @__PURE__ */ new Map();
        this._isolatedWorlds = /* @__PURE__ */ new Set();
        this._client = client;
        this._page = page;
        this._networkManager = new NetworkManager(client, ignoreHTTPSErrors, this);
        this._timeoutSettings = timeoutSettings;
        this._client.on(
          "Page.frameAttached",
          (event) => this._onFrameAttached(event.frameId, event.parentFrameId)
        );
        this._client.on(
          "Page.frameNavigated",
          (event) => this._onFrameNavigated(event.frame)
        );
        this._client.on(
          "Page.navigatedWithinDocument",
          (event) => this._onFrameNavigatedWithinDocument(event.frameId, event.url)
        );
        this._client.on(
          "Page.frameDetached",
          (event) => this._onFrameDetached(event.frameId)
        );
        this._client.on(
          "Page.frameStoppedLoading",
          (event) => this._onFrameStoppedLoading(event.frameId)
        );
        this._client.on(
          "Runtime.executionContextCreated",
          (event) => this._onExecutionContextCreated(event.context)
        );
        this._client.on(
          "Runtime.executionContextDestroyed",
          (event) => this._onExecutionContextDestroyed(event.executionContextId)
        );
        this._client.on(
          "Runtime.executionContextsCleared",
          () => this._onExecutionContextsCleared()
        );
        this._client.on(
          "Page.lifecycleEvent",
          (event) => this._onLifecycleEvent(event)
        );
        this._client.on(
          "Target.attachedToTarget",
          async (event) => this._onFrameMoved(event)
        );
      }
      async initialize() {
        const result2 = await Promise.all([
          this._client.send("Page.enable"),
          this._client.send("Page.getFrameTree")
        ]);
        const { frameTree } = result2[1];
        this._handleFrameTree(frameTree);
        await Promise.all([
          this._client.send("Page.setLifecycleEventsEnabled", { enabled: true }),
          this._client.send("Runtime.enable").then(() => this._ensureIsolatedWorld(UTILITY_WORLD_NAME)),
          this._networkManager.initialize()
        ]);
      }
      networkManager() {
        return this._networkManager;
      }
      async navigateFrame(frame, url, options = {}) {
        assertNoLegacyNavigationOptions(options);
        const {
          referer = this._networkManager.extraHTTPHeaders()["referer"],
          waitUntil = ["load"],
          timeout = this._timeoutSettings.navigationTimeout()
        } = options;
        const watcher = new LifecycleWatcher(this, frame, waitUntil, timeout);
        let ensureNewDocumentNavigation = false;
        let error2 = await Promise.race([
          navigate2(this._client, url, referer, frame._id),
          watcher.timeoutOrTerminationPromise()
        ]);
        if (!error2) {
          error2 = await Promise.race([
            watcher.timeoutOrTerminationPromise(),
            ensureNewDocumentNavigation ? watcher.newDocumentNavigationPromise() : watcher.sameDocumentNavigationPromise()
          ]);
        }
        watcher.dispose();
        if (error2) {
          throw error2;
        }
        return watcher.navigationResponse();
        async function navigate2(client, url2, referrer, frameId) {
          try {
            const response = await client.send("Page.navigate", {
              url: url2,
              referrer,
              frameId
            });
            ensureNewDocumentNavigation = !!response.loaderId;
            return response.errorText ? new Error(`${response.errorText} at ${url2}`) : null;
          } catch (error3) {
            return error3;
          }
        }
      }
      async waitForFrameNavigation(frame, options = {}) {
        assertNoLegacyNavigationOptions(options);
        const {
          waitUntil = ["load"],
          timeout = this._timeoutSettings.navigationTimeout()
        } = options;
        const watcher = new LifecycleWatcher(this, frame, waitUntil, timeout);
        const error2 = await Promise.race([
          watcher.timeoutOrTerminationPromise(),
          watcher.sameDocumentNavigationPromise(),
          watcher.newDocumentNavigationPromise()
        ]);
        watcher.dispose();
        if (error2) {
          throw error2;
        }
        return watcher.navigationResponse();
      }
      async _onFrameMoved(event) {
        if (event.targetInfo.type !== "iframe") {
          return;
        }
        debug2("puppeteer:frame")(
          `The frame '${event.targetInfo.targetId}' moved to another session. Out-of-process iframes (OOPIF) are not supported by Puppeteer yet. https://github.com/puppeteer/puppeteer/issues/2548`
        );
      }
      _onLifecycleEvent(event) {
        const frame = this._frames.get(event.frameId);
        if (!frame) {
          return;
        }
        frame._onLifecycleEvent(event.loaderId, event.name);
        this.emit(FrameManagerEmittedEvents.LifecycleEvent, frame);
      }
      _onFrameStoppedLoading(frameId) {
        const frame = this._frames.get(frameId);
        if (!frame) {
          return;
        }
        frame._onLoadingStopped();
        this.emit(FrameManagerEmittedEvents.LifecycleEvent, frame);
      }
      _handleFrameTree(frameTree) {
        if (frameTree.frame.parentId) {
          this._onFrameAttached(frameTree.frame.id, frameTree.frame.parentId);
        }
        this._onFrameNavigated(frameTree.frame);
        if (!frameTree.childFrames) {
          return;
        }
        for (const child of frameTree.childFrames) {
          this._handleFrameTree(child);
        }
      }
      page() {
        return this._page;
      }
      mainFrame() {
        return this._mainFrame;
      }
      frames() {
        return Array.from(this._frames.values());
      }
      frame(frameId) {
        return this._frames.get(frameId) || null;
      }
      _onFrameAttached(frameId, parentFrameId) {
        if (this._frames.has(frameId)) {
          return;
        }
        assert3(parentFrameId);
        const parentFrame = this._frames.get(parentFrameId);
        const frame = new Frame(this, parentFrame, frameId);
        this._frames.set(frame._id, frame);
        this.emit(FrameManagerEmittedEvents.FrameAttached, frame);
      }
      _onFrameNavigated(framePayload) {
        const isMainFrame = !framePayload.parentId;
        let frame = isMainFrame ? this._mainFrame : this._frames.get(framePayload.id);
        assert3(
          isMainFrame || frame,
          "We either navigate top level or have old version of the navigated frame"
        );
        if (frame) {
          for (const child of frame.childFrames()) {
            this._removeFramesRecursively(child);
          }
        }
        if (isMainFrame) {
          if (frame) {
            this._frames.delete(frame._id);
            frame._id = framePayload.id;
          } else {
            frame = new Frame(this, null, framePayload.id);
          }
          this._frames.set(framePayload.id, frame);
          this._mainFrame = frame;
        }
        frame._navigated(framePayload);
        this.emit(FrameManagerEmittedEvents.FrameNavigated, frame);
      }
      async _ensureIsolatedWorld(name2) {
        if (this._isolatedWorlds.has(name2)) {
          return;
        }
        this._isolatedWorlds.add(name2);
        await this._client.send("Page.addScriptToEvaluateOnNewDocument", {
          source: `//# sourceURL=${EVALUATION_SCRIPT_URL}`,
          worldName: name2
        });
        await Promise.all(
          this.frames().map(
            (frame) => this._client.send("Page.createIsolatedWorld", {
              frameId: frame._id,
              worldName: name2,
              grantUniveralAccess: true
            }).catch(debugError)
          )
        );
      }
      _onFrameNavigatedWithinDocument(frameId, url) {
        const frame = this._frames.get(frameId);
        if (!frame) {
          return;
        }
        frame._navigatedWithinDocument(url);
        this.emit(FrameManagerEmittedEvents.FrameNavigatedWithinDocument, frame);
        this.emit(FrameManagerEmittedEvents.FrameNavigated, frame);
      }
      _onFrameDetached(frameId) {
        const frame = this._frames.get(frameId);
        if (frame) {
          this._removeFramesRecursively(frame);
        }
      }
      _onExecutionContextCreated(contextPayload) {
        const auxData = contextPayload.auxData;
        const frameId = auxData ? auxData.frameId : null;
        const frame = this._frames.get(frameId) || null;
        let world = null;
        if (frame) {
          if (contextPayload.auxData && !!contextPayload.auxData["isDefault"]) {
            world = frame._mainWorld;
          } else if (contextPayload.name === UTILITY_WORLD_NAME && !frame._secondaryWorld._hasContext()) {
            world = frame._secondaryWorld;
          }
        }
        const context = new ExecutionContext(this._client, contextPayload, world);
        if (world) {
          world._setContext(context);
        }
        this._contextIdToContext.set(contextPayload.id, context);
      }
      _onExecutionContextDestroyed(executionContextId) {
        const context = this._contextIdToContext.get(executionContextId);
        if (!context) {
          return;
        }
        this._contextIdToContext.delete(executionContextId);
        if (context._world) {
          context._world._setContext(null);
        }
      }
      _onExecutionContextsCleared() {
        for (const context of this._contextIdToContext.values()) {
          if (context._world) {
            context._world._setContext(null);
          }
        }
        this._contextIdToContext.clear();
      }
      executionContextById(contextId) {
        const context = this._contextIdToContext.get(contextId);
        assert3(context, "INTERNAL ERROR: missing context with id = " + contextId);
        return context;
      }
      _removeFramesRecursively(frame) {
        for (const child of frame.childFrames()) {
          this._removeFramesRecursively(child);
        }
        frame._detach();
        this._frames.delete(frame._id);
        this.emit(FrameManagerEmittedEvents.FrameDetached, frame);
      }
    };
    Frame = class {
      /**
         * @internal
         */
      constructor(frameManager, parentFrame, frameId) {
        this._url = "";
        this._detached = false;
        this._loaderId = "";
        this._lifecycleEvents = /* @__PURE__ */ new Set();
        this._frameManager = frameManager;
        this._parentFrame = parentFrame;
        this._url = "";
        this._id = frameId;
        this._detached = false;
        this._loaderId = "";
        this._mainWorld = new DOMWorld(
          frameManager,
          this,
          frameManager._timeoutSettings
        );
        this._secondaryWorld = new DOMWorld(
          frameManager,
          this,
          frameManager._timeoutSettings
        );
        this._childFrames = /* @__PURE__ */ new Set();
        if (this._parentFrame) {
          this._parentFrame._childFrames.add(this);
        }
      }
      /**
         * @remarks
         *
         * `frame.goto` will throw an error if:
         * - there's an SSL error (e.g. in case of self-signed certificates).
         *
         * - target URL is invalid.
         *
         * - the `timeout` is exceeded during navigation.
         *
         * - the remote server does not respond or is unreachable.
         *
         * - the main resource failed to load.
         *
         * `frame.goto` will not throw an error when any valid HTTP status code is
         * returned by the remote server, including 404 "Not Found" and 500 "Internal
         * Server Error".  The status code for such responses can be retrieved by
         * calling {@link HTTPResponse.status}.
         *
         * NOTE: `frame.goto` either throws an error or returns a main resource
         * response. The only exceptions are navigation to `about:blank` or
         * navigation to the same URL with a different hash, which would succeed and
         * return `null`.
         *
         * NOTE: Headless mode doesn't support navigation to a PDF document. See
         * the {@link https://bugs.chromium.org/p/chromium/issues/detail?id=761295 | upstream
         * issue}.
         *
         * @param url - the URL to navigate the frame to. This should include the
         * scheme, e.g. `https://`.
         * @param options - navigation options. `waitUntil` is useful to define when
         * the navigation should be considered successful - see the docs for
         * {@link PuppeteerLifeCycleEvent} for more details.
         *
         * @returns A promise which resolves to the main resource response. In case of
         * multiple redirects, the navigation will resolve with the response of the
         * last redirect.
         */
      async goto(url, options = {}) {
        return await this._frameManager.navigateFrame(this, url, options);
      }
      /**
         * @remarks
         *
         * This resolves when the frame navigates to a new URL. It is useful for when
         * you run code which will indirectly cause the frame to navigate. Consider
         * this example:
         *
         * ```js
         * const [response] = await Promise.all([
         *   // The navigation promise resolves after navigation has finished
         *   frame.waitForNavigation(),
         *   // Clicking the link will indirectly cause a navigation
         *   frame.click('a.my-link'),
         * ]);
         * ```
         *
         * Usage of the {@link https://developer.mozilla.org/en-US/docs/Web/API/History_API | History API} to change the URL is considered a navigation.
         *
         * @param options - options to configure when the navigation is consided finished.
         * @returns a promise that resolves when the frame navigates to a new URL.
         */
      async waitForNavigation(options = {}) {
        return await this._frameManager.waitForFrameNavigation(this, options);
      }
      /**
         * @returns a promise that resolves to the frame's default execution context.
         */
      executionContext() {
        return this._mainWorld.executionContext();
      }
      /**
         * @remarks
         *
         * The only difference between {@link Frame.evaluate} and
         * `frame.evaluateHandle` is that `evaluateHandle` will return the value
         * wrapped in an in-page object.
         *
         * This method behaves identically to {@link Page.evaluateHandle} except it's
         * run within the context of the `frame`, rather than the entire page.
         *
         * @param pageFunction - a function that is run within the frame
         * @param args - arguments to be passed to the pageFunction
         */
      async evaluateHandle(pageFunction, ...args) {
        return this._mainWorld.evaluateHandle(pageFunction, ...args);
      }
      /**
         * @remarks
         *
         * This method behaves identically to {@link Page.evaluate} except it's run
         * within the context of the `frame`, rather than the entire page.
         *
         * @param pageFunction - a function that is run within the frame
         * @param args - arguments to be passed to the pageFunction
         */
      async evaluate(pageFunction, ...args) {
        return this._mainWorld.evaluate(pageFunction, ...args);
      }
      /**
         * This method queries the frame for the given selector.
         *
         * @param selector - a selector to query for.
         * @returns A promise which resolves to an `ElementHandle` pointing at the
         * element, or `null` if it was not found.
         */
      async $(selector) {
        return this._mainWorld.$(selector);
      }
      /**
         * This method evaluates the given XPath expression and returns the results.
         *
         * @param expression - the XPath expression to evaluate.
         */
      async $x(expression) {
        return this._mainWorld.$x(expression);
      }
      /**
         * @remarks
         *
         * This method runs `document.querySelector` within
         * the frame and passes it as the first argument to `pageFunction`.
         *
         * If `pageFunction` returns a Promise, then `frame.$eval` would wait for
         * the promise to resolve and return its value.
         *
         * @example
         *
         * ```js
         * const searchValue = await frame.$eval('#search', el => el.value);
         * ```
         *
         * @param selector - the selector to query for
         * @param pageFunction - the function to be evaluated in the frame's context
         * @param args - additional arguments to pass to `pageFuncton`
         */
      async $eval(selector, pageFunction, ...args) {
        return this._mainWorld.$eval(selector, pageFunction, ...args);
      }
      /**
         * @remarks
         *
         * This method runs `Array.from(document.querySelectorAll(selector))` within
         * the frame and passes it as the first argument to `pageFunction`.
         *
         * If `pageFunction` returns a Promise, then `frame.$$eval` would wait for
         * the promise to resolve and return its value.
         *
         * @example
         *
         * ```js
         * const divsCounts = await frame.$$eval('div', divs => divs.length);
         * ```
         *
         * @param selector - the selector to query for
         * @param pageFunction - the function to be evaluated in the frame's context
         * @param args - additional arguments to pass to `pageFuncton`
         */
      async $$eval(selector, pageFunction, ...args) {
        return this._mainWorld.$$eval(selector, pageFunction, ...args);
      }
      /**
         * This runs `document.querySelectorAll` in the frame and returns the result.
         *
         * @param selector - a selector to search for
         * @returns An array of element handles pointing to the found frame elements.
         */
      async $$(selector) {
        return this._mainWorld.$$(selector);
      }
      /**
         * @returns the full HTML contents of the frame, including the doctype.
         */
      async content() {
        return this._secondaryWorld.content();
      }
      /**
         * Set the content of the frame.
         *
         * @param html - HTML markup to assign to the page.
         * @param options - options to configure how long before timing out and at
         * what point to consider the content setting successful.
         */
      async setContent(html, options = {}) {
        return this._secondaryWorld.setContent(html, options);
      }
      /**
         * @remarks
         *
         * If the name is empty, it returns the `id` attribute instead.
         *
         * Note: This value is calculated once when the frame is created, and will not
         * update if the attribute is changed later.
         *
         * @returns the frame's `name` attribute as specified in the tag.
         */
      name() {
        return this._name || "";
      }
      /**
         * @returns the frame's URL.
         */
      url() {
        return this._url;
      }
      /**
         * @returns the parent `Frame`, if any. Detached and main frames return `null`.
         */
      parentFrame() {
        return this._parentFrame;
      }
      /**
         * @returns an array of child frames.
         */
      childFrames() {
        return Array.from(this._childFrames);
      }
      /**
         * @returns `true` if the frame has been detached, or `false` otherwise.
         */
      isDetached() {
        return this._detached;
      }
      /**
         * Adds a `<script>` tag into the page with the desired url or content.
         *
         * @param options - configure the script to add to the page.
         *
         * @returns a promise that resolves to the added tag when the script's
         * `onload` event fires or when the script content was injected into the
         * frame.
         */
      async addScriptTag(options) {
        return this._mainWorld.addScriptTag(options);
      }
      /**
         * Adds a `<link rel="stylesheet">` tag into the page with the desired url or
         * a `<style type="text/css">` tag with the content.
         *
         * @param options - configure the CSS to add to the page.
         *
         * @returns a promise that resolves to the added tag when the stylesheets's
         * `onload` event fires or when the CSS content was injected into the
         * frame.
         */
      async addStyleTag(options) {
        return this._mainWorld.addStyleTag(options);
      }
      /**
         *
         * This method clicks the first element found that matches `selector`.
         *
         * @remarks
         *
         * This method scrolls the element into view if needed, and then uses
         * {@link Page.mouse} to click in the center of the element. If there's no
         * element matching `selector`, the method throws an error.
         *
         * Bear in mind that if `click()` triggers a navigation event and there's a
         * separate `page.waitForNavigation()` promise to be resolved, you may end up
         * with a race condition that yields unexpected results. The correct pattern
         * for click and wait for navigation is the following:
         *
         * ```javascript
         * const [response] = await Promise.all([
         *   page.waitForNavigation(waitOptions),
         *   frame.click(selector, clickOptions),
         * ]);
         * ```
         * @param selector - the selector to search for to click. If there are
         * multiple elements, the first will be clicked.
         */
      async click(selector, options = {}) {
        return this._secondaryWorld.click(selector, options);
      }
      /**
         * This method fetches an element with `selector` and focuses it.
         *
         * @remarks
         * If there's no element matching `selector`, the method throws an error.
         *
         * @param selector - the selector for the element to focus. If there are
         * multiple elements, the first will be focused.
         */
      async focus(selector) {
        return this._secondaryWorld.focus(selector);
      }
      /**
         * This method fetches an element with `selector`, scrolls it into view if
         * needed, and then uses {@link Page.mouse} to hover over the center of the
         * element.
         *
         * @remarks
         * If there's no element matching `selector`, the method throws an
         *
         * @param selector - the selector for the element to hover. If there are
         * multiple elements, the first will be hovered.
         */
      async hover(selector) {
        return this._secondaryWorld.hover(selector);
      }
      /**
         * Triggers a `change` and `input` event once all the provided options have
         * been selected.
         *
         * @remarks
         *
         * If there's no `<select>` element matching `selector`, the
         * method throws an error.
         *
         * @example
         * ```js
         * frame.select('select#colors', 'blue'); // single selection
         * frame.select('select#colors', 'red', 'green', 'blue'); // multiple selections
         * ```
         *
         * @param selector - a selector to query the frame for
         * @param values - an array of values to select. If the `<select>` has the
         * `multiple` attribute, all values are considered, otherwise only the first
         * one is taken into account.
         * @returns the list of values that were successfully selected.
         */
      select(selector, ...values) {
        return this._secondaryWorld.select(selector, ...values);
      }
      /**
         * This method fetches an element with `selector`, scrolls it into view if
         * needed, and then uses {@link Page.touchscreen} to tap in the center of the
         * element.
         *
         * @remarks
         *
         * If there's no element matching `selector`, the method throws an error.
         *
         * @param selector - the selector to tap.
         * @returns a promise that resolves when the element has been tapped.
         */
      async tap(selector) {
        return this._secondaryWorld.tap(selector);
      }
      /**
         * Sends a `keydown`, `keypress`/`input`, and `keyup` event for each character
         * in the text.
         *
         * @remarks
         * To press a special key, like `Control` or `ArrowDown`, use
         * {@link Keyboard.press}.
         *
         * @example
         * ```js
         * await frame.type('#mytextarea', 'Hello'); // Types instantly
         * await frame.type('#mytextarea', 'World', {delay: 100}); // Types slower, like a user
         * ```
         *
         * @param selector - the selector for the element to type into. If there are
         * multiple the first will be used.
         * @param text - text to type into the element
         * @param options - takes one option, `delay`, which sets the time to wait
         * between key presses in milliseconds. Defaults to `0`.
         *
         * @returns a promise that resolves when the typing is complete.
         */
      async type(selector, text, options) {
        return this._mainWorld.type(selector, text, options);
      }
      /**
         * @remarks
         *
         * This method behaves differently depending on the first parameter. If it's a
         * `string`, it will be treated as a `selector` or `xpath` (if the string
         * starts with `//`). This method then is a shortcut for
         * {@link Frame.waitForSelector} or {@link Frame.waitForXPath}.
         *
         * If the first argument is a function this method is a shortcut for
         * {@link Frame.waitForFunction}.
         *
         * If the first argument is a `number`, it's treated as a timeout in
         * milliseconds and the method returns a promise which resolves after the
         * timeout.
         *
         * @param selectorOrFunctionOrTimeout - a selector, predicate or timeout to
         * wait for.
         * @param options - optional waiting parameters.
         * @param args - arguments to pass to `pageFunction`.
         *
         * @deprecated Don't use this method directly. Instead use the more explicit
         * methods available: {@link Frame.waitForSelector},
         * {@link Frame.waitForXPath}, {@link Frame.waitForFunction} or
         * {@link Frame.waitForTimeout}.
         */
      waitFor(selectorOrFunctionOrTimeout, options = {}, ...args) {
        const xPathPattern = "//";
        console.warn(
          "waitFor is deprecated and will be removed in a future release. See https://github.com/puppeteer/puppeteer/issues/6214 for details and how to migrate your code."
        );
        if (helper.isString(selectorOrFunctionOrTimeout)) {
          const string2 = selectorOrFunctionOrTimeout;
          if (string2.startsWith(xPathPattern)) {
            return this.waitForXPath(string2, options);
          }
          return this.waitForSelector(string2, options);
        }
        if (helper.isNumber(selectorOrFunctionOrTimeout)) {
          return new Promise(
            (fulfill) => setTimeout(fulfill, selectorOrFunctionOrTimeout)
          );
        }
        if (typeof selectorOrFunctionOrTimeout === "function") {
          return this.waitForFunction(
            selectorOrFunctionOrTimeout,
            options,
            ...args
          );
        }
        return Promise.reject(
          new Error(
            "Unsupported target type: " + typeof selectorOrFunctionOrTimeout
          )
        );
      }
      /**
         * Causes your script to wait for the given number of milliseconds.
         *
         * @remarks
         * It's generally recommended to not wait for a number of seconds, but instead
         * use {@link Frame.waitForSelector}, {@link Frame.waitForXPath} or
         * {@link Frame.waitForFunction} to wait for exactly the conditions you want.
         *
         * @example
         *
         * Wait for 1 second:
         *
         * ```
         * await frame.waitForTimeout(1000);
         * ```
         *
         * @param milliseconds - the number of milliseconds to wait.
         */
      waitForTimeout(milliseconds) {
        return new Promise((resolve16) => {
          setTimeout(resolve16, milliseconds);
        });
      }
      /**
         * @remarks
         *
         *
         * Wait for the `selector` to appear in page. If at the moment of calling the
         * method the `selector` already exists, the method will return immediately.
         * If the selector doesn't appear after the `timeout` milliseconds of waiting,
         * the function will throw.
         *
         * This method works across navigations.
         *
         * @example
         * ```js
         * const puppeteer = require('puppeteer');
         *
         * (async () => {
         *   const browser = await puppeteer.launch();
         *   const page = await browser.newPage();
         *   let currentURL;
         *   page.mainFrame()
         *   .waitForSelector('img')
         *   .then(() => console.log('First URL with image: ' + currentURL));
         *
         *   for (currentURL of ['https://example.com', 'https://google.com', 'https://bbc.com']) {
         *     await page.goto(currentURL);
         *   }
         *   await browser.close();
         * })();
         * ```
         * @param selector - the selector to wait for.
         * @param options - options to define if the element should be visible and how
         * long to wait before timing out.
         * @returns a promise which resolves when an element matching the selector
         * string is added to the DOM.
         */
      async waitForSelector(selector, options = {}) {
        const handle = await this._secondaryWorld.waitForSelector(
          selector,
          options
        );
        if (!handle) {
          return null;
        }
        const mainExecutionContext = await this._mainWorld.executionContext();
        const result2 = await mainExecutionContext._adoptElementHandle(handle);
        await handle.dispose();
        return result2;
      }
      /**
         * @remarks
         * Wait for the `xpath` to appear in page. If at the moment of calling the
         * method the `xpath` already exists, the method will return immediately. If
         * the xpath doesn't appear after the `timeout` milliseconds of waiting, the
         * function will throw.
         *
         * For a code example, see the example for {@link Frame.waitForSelector}. That
         * function behaves identically other than taking a CSS selector rather than
         * an XPath.
         *
         * @param xpath - the XPath expression to wait for.
         * @param options  - options to configure the visiblity of the element and how
         * long to wait before timing out.
         */
      async waitForXPath(xpath, options = {}) {
        const handle = await this._secondaryWorld.waitForXPath(xpath, options);
        if (!handle) {
          return null;
        }
        const mainExecutionContext = await this._mainWorld.executionContext();
        const result2 = await mainExecutionContext._adoptElementHandle(handle);
        await handle.dispose();
        return result2;
      }
      /**
         * @remarks
         *
         * @example
         *
         * The `waitForFunction` can be used to observe viewport size change:
         * ```js
         * const puppeteer = require('puppeteer');
         *
         * (async () => {
         * .  const browser = await puppeteer.launch();
         * .  const page = await browser.newPage();
         * .  const watchDog = page.mainFrame().waitForFunction('window.innerWidth < 100');
         * .  page.setViewport({width: 50, height: 50});
         * .  await watchDog;
         * .  await browser.close();
         * })();
         * ```
         *
         * To pass arguments from Node.js to the predicate of `page.waitForFunction` function:
         *
         * ```js
         * const selector = '.foo';
         * await frame.waitForFunction(
         *   selector => !!document.querySelector(selector),
         *   {}, // empty options object
         *   selector
         *);
         * ```
         *
         * @param pageFunction - the function to evaluate in the frame context.
         * @param options - options to configure the polling method and timeout.
         * @param args - arguments to pass to the `pageFunction`.
         * @returns the promise which resolve when the `pageFunction` returns a truthy value.
         */
      waitForFunction(pageFunction, options = {}, ...args) {
        return this._mainWorld.waitForFunction(pageFunction, options, ...args);
      }
      /**
         * @returns the frame's title.
         */
      async title() {
        return this._secondaryWorld.title();
      }
      /**
         * @internal
         */
      _navigated(framePayload) {
        this._name = framePayload.name;
        this._url = `${framePayload.url}${framePayload.urlFragment || ""}`;
      }
      /**
         * @internal
         */
      _navigatedWithinDocument(url) {
        this._url = url;
      }
      /**
         * @internal
         */
      _onLifecycleEvent(loaderId, name2) {
        if (name2 === "init") {
          this._loaderId = loaderId;
          this._lifecycleEvents.clear();
        }
        this._lifecycleEvents.add(name2);
      }
      /**
         * @internal
         */
      _onLoadingStopped() {
        this._lifecycleEvents.add("DOMContentLoaded");
        this._lifecycleEvents.add("load");
      }
      /**
         * @internal
         */
      _detach() {
        this._detached = true;
        this._mainWorld._detach();
        this._secondaryWorld._detach();
        if (this._parentFrame) {
          this._parentFrame._childFrames.delete(this);
        }
        this._parentFrame = null;
      }
    };
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/USKeyboardLayout.js
var keyDefinitions;
var init_USKeyboardLayout = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/USKeyboardLayout.js"() {
    keyDefinitions = {
      "0": { keyCode: 48, key: "0", code: "Digit0" },
      "1": { keyCode: 49, key: "1", code: "Digit1" },
      "2": { keyCode: 50, key: "2", code: "Digit2" },
      "3": { keyCode: 51, key: "3", code: "Digit3" },
      "4": { keyCode: 52, key: "4", code: "Digit4" },
      "5": { keyCode: 53, key: "5", code: "Digit5" },
      "6": { keyCode: 54, key: "6", code: "Digit6" },
      "7": { keyCode: 55, key: "7", code: "Digit7" },
      "8": { keyCode: 56, key: "8", code: "Digit8" },
      "9": { keyCode: 57, key: "9", code: "Digit9" },
      Power: { key: "Power", code: "Power" },
      Eject: { key: "Eject", code: "Eject" },
      Abort: { keyCode: 3, code: "Abort", key: "Cancel" },
      Help: { keyCode: 6, code: "Help", key: "Help" },
      Backspace: { keyCode: 8, code: "Backspace", key: "Backspace" },
      Tab: { keyCode: 9, code: "Tab", key: "Tab" },
      Numpad5: {
        keyCode: 12,
        shiftKeyCode: 101,
        key: "Clear",
        code: "Numpad5",
        shiftKey: "5",
        location: 3
      },
      NumpadEnter: {
        keyCode: 13,
        code: "NumpadEnter",
        key: "Enter",
        text: "\r",
        location: 3
      },
      Enter: { keyCode: 13, code: "Enter", key: "Enter", text: "\r" },
      "\r": { keyCode: 13, code: "Enter", key: "Enter", text: "\r" },
      "\n": { keyCode: 13, code: "Enter", key: "Enter", text: "\r" },
      ShiftLeft: { keyCode: 16, code: "ShiftLeft", key: "Shift", location: 1 },
      ShiftRight: { keyCode: 16, code: "ShiftRight", key: "Shift", location: 2 },
      ControlLeft: {
        keyCode: 17,
        code: "ControlLeft",
        key: "Control",
        location: 1
      },
      ControlRight: {
        keyCode: 17,
        code: "ControlRight",
        key: "Control",
        location: 2
      },
      AltLeft: { keyCode: 18, code: "AltLeft", key: "Alt", location: 1 },
      AltRight: { keyCode: 18, code: "AltRight", key: "Alt", location: 2 },
      Pause: { keyCode: 19, code: "Pause", key: "Pause" },
      CapsLock: { keyCode: 20, code: "CapsLock", key: "CapsLock" },
      Escape: { keyCode: 27, code: "Escape", key: "Escape" },
      Convert: { keyCode: 28, code: "Convert", key: "Convert" },
      NonConvert: { keyCode: 29, code: "NonConvert", key: "NonConvert" },
      Space: { keyCode: 32, code: "Space", key: " " },
      Numpad9: {
        keyCode: 33,
        shiftKeyCode: 105,
        key: "PageUp",
        code: "Numpad9",
        shiftKey: "9",
        location: 3
      },
      PageUp: { keyCode: 33, code: "PageUp", key: "PageUp" },
      Numpad3: {
        keyCode: 34,
        shiftKeyCode: 99,
        key: "PageDown",
        code: "Numpad3",
        shiftKey: "3",
        location: 3
      },
      PageDown: { keyCode: 34, code: "PageDown", key: "PageDown" },
      End: { keyCode: 35, code: "End", key: "End" },
      Numpad1: {
        keyCode: 35,
        shiftKeyCode: 97,
        key: "End",
        code: "Numpad1",
        shiftKey: "1",
        location: 3
      },
      Home: { keyCode: 36, code: "Home", key: "Home" },
      Numpad7: {
        keyCode: 36,
        shiftKeyCode: 103,
        key: "Home",
        code: "Numpad7",
        shiftKey: "7",
        location: 3
      },
      ArrowLeft: { keyCode: 37, code: "ArrowLeft", key: "ArrowLeft" },
      Numpad4: {
        keyCode: 37,
        shiftKeyCode: 100,
        key: "ArrowLeft",
        code: "Numpad4",
        shiftKey: "4",
        location: 3
      },
      Numpad8: {
        keyCode: 38,
        shiftKeyCode: 104,
        key: "ArrowUp",
        code: "Numpad8",
        shiftKey: "8",
        location: 3
      },
      ArrowUp: { keyCode: 38, code: "ArrowUp", key: "ArrowUp" },
      ArrowRight: { keyCode: 39, code: "ArrowRight", key: "ArrowRight" },
      Numpad6: {
        keyCode: 39,
        shiftKeyCode: 102,
        key: "ArrowRight",
        code: "Numpad6",
        shiftKey: "6",
        location: 3
      },
      Numpad2: {
        keyCode: 40,
        shiftKeyCode: 98,
        key: "ArrowDown",
        code: "Numpad2",
        shiftKey: "2",
        location: 3
      },
      ArrowDown: { keyCode: 40, code: "ArrowDown", key: "ArrowDown" },
      Select: { keyCode: 41, code: "Select", key: "Select" },
      Open: { keyCode: 43, code: "Open", key: "Execute" },
      PrintScreen: { keyCode: 44, code: "PrintScreen", key: "PrintScreen" },
      Insert: { keyCode: 45, code: "Insert", key: "Insert" },
      Numpad0: {
        keyCode: 45,
        shiftKeyCode: 96,
        key: "Insert",
        code: "Numpad0",
        shiftKey: "0",
        location: 3
      },
      Delete: { keyCode: 46, code: "Delete", key: "Delete" },
      NumpadDecimal: {
        keyCode: 46,
        shiftKeyCode: 110,
        code: "NumpadDecimal",
        key: "\0",
        shiftKey: ".",
        location: 3
      },
      Digit0: { keyCode: 48, code: "Digit0", shiftKey: ")", key: "0" },
      Digit1: { keyCode: 49, code: "Digit1", shiftKey: "!", key: "1" },
      Digit2: { keyCode: 50, code: "Digit2", shiftKey: "@", key: "2" },
      Digit3: { keyCode: 51, code: "Digit3", shiftKey: "#", key: "3" },
      Digit4: { keyCode: 52, code: "Digit4", shiftKey: "$", key: "4" },
      Digit5: { keyCode: 53, code: "Digit5", shiftKey: "%", key: "5" },
      Digit6: { keyCode: 54, code: "Digit6", shiftKey: "^", key: "6" },
      Digit7: { keyCode: 55, code: "Digit7", shiftKey: "&", key: "7" },
      Digit8: { keyCode: 56, code: "Digit8", shiftKey: "*", key: "8" },
      Digit9: { keyCode: 57, code: "Digit9", shiftKey: "(", key: "9" },
      KeyA: { keyCode: 65, code: "KeyA", shiftKey: "A", key: "a" },
      KeyB: { keyCode: 66, code: "KeyB", shiftKey: "B", key: "b" },
      KeyC: { keyCode: 67, code: "KeyC", shiftKey: "C", key: "c" },
      KeyD: { keyCode: 68, code: "KeyD", shiftKey: "D", key: "d" },
      KeyE: { keyCode: 69, code: "KeyE", shiftKey: "E", key: "e" },
      KeyF: { keyCode: 70, code: "KeyF", shiftKey: "F", key: "f" },
      KeyG: { keyCode: 71, code: "KeyG", shiftKey: "G", key: "g" },
      KeyH: { keyCode: 72, code: "KeyH", shiftKey: "H", key: "h" },
      KeyI: { keyCode: 73, code: "KeyI", shiftKey: "I", key: "i" },
      KeyJ: { keyCode: 74, code: "KeyJ", shiftKey: "J", key: "j" },
      KeyK: { keyCode: 75, code: "KeyK", shiftKey: "K", key: "k" },
      KeyL: { keyCode: 76, code: "KeyL", shiftKey: "L", key: "l" },
      KeyM: { keyCode: 77, code: "KeyM", shiftKey: "M", key: "m" },
      KeyN: { keyCode: 78, code: "KeyN", shiftKey: "N", key: "n" },
      KeyO: { keyCode: 79, code: "KeyO", shiftKey: "O", key: "o" },
      KeyP: { keyCode: 80, code: "KeyP", shiftKey: "P", key: "p" },
      KeyQ: { keyCode: 81, code: "KeyQ", shiftKey: "Q", key: "q" },
      KeyR: { keyCode: 82, code: "KeyR", shiftKey: "R", key: "r" },
      KeyS: { keyCode: 83, code: "KeyS", shiftKey: "S", key: "s" },
      KeyT: { keyCode: 84, code: "KeyT", shiftKey: "T", key: "t" },
      KeyU: { keyCode: 85, code: "KeyU", shiftKey: "U", key: "u" },
      KeyV: { keyCode: 86, code: "KeyV", shiftKey: "V", key: "v" },
      KeyW: { keyCode: 87, code: "KeyW", shiftKey: "W", key: "w" },
      KeyX: { keyCode: 88, code: "KeyX", shiftKey: "X", key: "x" },
      KeyY: { keyCode: 89, code: "KeyY", shiftKey: "Y", key: "y" },
      KeyZ: { keyCode: 90, code: "KeyZ", shiftKey: "Z", key: "z" },
      MetaLeft: { keyCode: 91, code: "MetaLeft", key: "Meta", location: 1 },
      MetaRight: { keyCode: 92, code: "MetaRight", key: "Meta", location: 2 },
      ContextMenu: { keyCode: 93, code: "ContextMenu", key: "ContextMenu" },
      NumpadMultiply: {
        keyCode: 106,
        code: "NumpadMultiply",
        key: "*",
        location: 3
      },
      NumpadAdd: { keyCode: 107, code: "NumpadAdd", key: "+", location: 3 },
      NumpadSubtract: {
        keyCode: 109,
        code: "NumpadSubtract",
        key: "-",
        location: 3
      },
      NumpadDivide: { keyCode: 111, code: "NumpadDivide", key: "/", location: 3 },
      F1: { keyCode: 112, code: "F1", key: "F1" },
      F2: { keyCode: 113, code: "F2", key: "F2" },
      F3: { keyCode: 114, code: "F3", key: "F3" },
      F4: { keyCode: 115, code: "F4", key: "F4" },
      F5: { keyCode: 116, code: "F5", key: "F5" },
      F6: { keyCode: 117, code: "F6", key: "F6" },
      F7: { keyCode: 118, code: "F7", key: "F7" },
      F8: { keyCode: 119, code: "F8", key: "F8" },
      F9: { keyCode: 120, code: "F9", key: "F9" },
      F10: { keyCode: 121, code: "F10", key: "F10" },
      F11: { keyCode: 122, code: "F11", key: "F11" },
      F12: { keyCode: 123, code: "F12", key: "F12" },
      F13: { keyCode: 124, code: "F13", key: "F13" },
      F14: { keyCode: 125, code: "F14", key: "F14" },
      F15: { keyCode: 126, code: "F15", key: "F15" },
      F16: { keyCode: 127, code: "F16", key: "F16" },
      F17: { keyCode: 128, code: "F17", key: "F17" },
      F18: { keyCode: 129, code: "F18", key: "F18" },
      F19: { keyCode: 130, code: "F19", key: "F19" },
      F20: { keyCode: 131, code: "F20", key: "F20" },
      F21: { keyCode: 132, code: "F21", key: "F21" },
      F22: { keyCode: 133, code: "F22", key: "F22" },
      F23: { keyCode: 134, code: "F23", key: "F23" },
      F24: { keyCode: 135, code: "F24", key: "F24" },
      NumLock: { keyCode: 144, code: "NumLock", key: "NumLock" },
      ScrollLock: { keyCode: 145, code: "ScrollLock", key: "ScrollLock" },
      AudioVolumeMute: {
        keyCode: 173,
        code: "AudioVolumeMute",
        key: "AudioVolumeMute"
      },
      AudioVolumeDown: {
        keyCode: 174,
        code: "AudioVolumeDown",
        key: "AudioVolumeDown"
      },
      AudioVolumeUp: { keyCode: 175, code: "AudioVolumeUp", key: "AudioVolumeUp" },
      MediaTrackNext: {
        keyCode: 176,
        code: "MediaTrackNext",
        key: "MediaTrackNext"
      },
      MediaTrackPrevious: {
        keyCode: 177,
        code: "MediaTrackPrevious",
        key: "MediaTrackPrevious"
      },
      MediaStop: { keyCode: 178, code: "MediaStop", key: "MediaStop" },
      MediaPlayPause: {
        keyCode: 179,
        code: "MediaPlayPause",
        key: "MediaPlayPause"
      },
      Semicolon: { keyCode: 186, code: "Semicolon", shiftKey: ":", key: ";" },
      Equal: { keyCode: 187, code: "Equal", shiftKey: "+", key: "=" },
      NumpadEqual: { keyCode: 187, code: "NumpadEqual", key: "=", location: 3 },
      Comma: { keyCode: 188, code: "Comma", shiftKey: "<", key: "," },
      Minus: { keyCode: 189, code: "Minus", shiftKey: "_", key: "-" },
      Period: { keyCode: 190, code: "Period", shiftKey: ">", key: "." },
      Slash: { keyCode: 191, code: "Slash", shiftKey: "?", key: "/" },
      Backquote: { keyCode: 192, code: "Backquote", shiftKey: "~", key: "`" },
      BracketLeft: { keyCode: 219, code: "BracketLeft", shiftKey: "{", key: "[" },
      Backslash: { keyCode: 220, code: "Backslash", shiftKey: "|", key: "\\" },
      BracketRight: { keyCode: 221, code: "BracketRight", shiftKey: "}", key: "]" },
      Quote: { keyCode: 222, code: "Quote", shiftKey: '"', key: "'" },
      AltGraph: { keyCode: 225, code: "AltGraph", key: "AltGraph" },
      Props: { keyCode: 247, code: "Props", key: "CrSel" },
      Cancel: { keyCode: 3, key: "Cancel", code: "Abort" },
      Clear: { keyCode: 12, key: "Clear", code: "Numpad5", location: 3 },
      Shift: { keyCode: 16, key: "Shift", code: "ShiftLeft", location: 1 },
      Control: { keyCode: 17, key: "Control", code: "ControlLeft", location: 1 },
      Alt: { keyCode: 18, key: "Alt", code: "AltLeft", location: 1 },
      Accept: { keyCode: 30, key: "Accept" },
      ModeChange: { keyCode: 31, key: "ModeChange" },
      " ": { keyCode: 32, key: " ", code: "Space" },
      Print: { keyCode: 42, key: "Print" },
      Execute: { keyCode: 43, key: "Execute", code: "Open" },
      "\0": { keyCode: 46, key: "\0", code: "NumpadDecimal", location: 3 },
      a: { keyCode: 65, key: "a", code: "KeyA" },
      b: { keyCode: 66, key: "b", code: "KeyB" },
      c: { keyCode: 67, key: "c", code: "KeyC" },
      d: { keyCode: 68, key: "d", code: "KeyD" },
      e: { keyCode: 69, key: "e", code: "KeyE" },
      f: { keyCode: 70, key: "f", code: "KeyF" },
      g: { keyCode: 71, key: "g", code: "KeyG" },
      h: { keyCode: 72, key: "h", code: "KeyH" },
      i: { keyCode: 73, key: "i", code: "KeyI" },
      j: { keyCode: 74, key: "j", code: "KeyJ" },
      k: { keyCode: 75, key: "k", code: "KeyK" },
      l: { keyCode: 76, key: "l", code: "KeyL" },
      m: { keyCode: 77, key: "m", code: "KeyM" },
      n: { keyCode: 78, key: "n", code: "KeyN" },
      o: { keyCode: 79, key: "o", code: "KeyO" },
      p: { keyCode: 80, key: "p", code: "KeyP" },
      q: { keyCode: 81, key: "q", code: "KeyQ" },
      r: { keyCode: 82, key: "r", code: "KeyR" },
      s: { keyCode: 83, key: "s", code: "KeyS" },
      t: { keyCode: 84, key: "t", code: "KeyT" },
      u: { keyCode: 85, key: "u", code: "KeyU" },
      v: { keyCode: 86, key: "v", code: "KeyV" },
      w: { keyCode: 87, key: "w", code: "KeyW" },
      x: { keyCode: 88, key: "x", code: "KeyX" },
      y: { keyCode: 89, key: "y", code: "KeyY" },
      z: { keyCode: 90, key: "z", code: "KeyZ" },
      Meta: { keyCode: 91, key: "Meta", code: "MetaLeft", location: 1 },
      "*": { keyCode: 106, key: "*", code: "NumpadMultiply", location: 3 },
      "+": { keyCode: 107, key: "+", code: "NumpadAdd", location: 3 },
      "-": { keyCode: 109, key: "-", code: "NumpadSubtract", location: 3 },
      "/": { keyCode: 111, key: "/", code: "NumpadDivide", location: 3 },
      ";": { keyCode: 186, key: ";", code: "Semicolon" },
      "=": { keyCode: 187, key: "=", code: "Equal" },
      ",": { keyCode: 188, key: ",", code: "Comma" },
      ".": { keyCode: 190, key: ".", code: "Period" },
      "`": { keyCode: 192, key: "`", code: "Backquote" },
      "[": { keyCode: 219, key: "[", code: "BracketLeft" },
      "\\": { keyCode: 220, key: "\\", code: "Backslash" },
      "]": { keyCode: 221, key: "]", code: "BracketRight" },
      "'": { keyCode: 222, key: "'", code: "Quote" },
      Attn: { keyCode: 246, key: "Attn" },
      CrSel: { keyCode: 247, key: "CrSel", code: "Props" },
      ExSel: { keyCode: 248, key: "ExSel" },
      EraseEof: { keyCode: 249, key: "EraseEof" },
      Play: { keyCode: 250, key: "Play" },
      ZoomOut: { keyCode: 251, key: "ZoomOut" },
      ")": { keyCode: 48, key: ")", code: "Digit0" },
      "!": { keyCode: 49, key: "!", code: "Digit1" },
      "@": { keyCode: 50, key: "@", code: "Digit2" },
      "#": { keyCode: 51, key: "#", code: "Digit3" },
      $: { keyCode: 52, key: "$", code: "Digit4" },
      "%": { keyCode: 53, key: "%", code: "Digit5" },
      "^": { keyCode: 54, key: "^", code: "Digit6" },
      "&": { keyCode: 55, key: "&", code: "Digit7" },
      "(": { keyCode: 57, key: "(", code: "Digit9" },
      A: { keyCode: 65, key: "A", code: "KeyA" },
      B: { keyCode: 66, key: "B", code: "KeyB" },
      C: { keyCode: 67, key: "C", code: "KeyC" },
      D: { keyCode: 68, key: "D", code: "KeyD" },
      E: { keyCode: 69, key: "E", code: "KeyE" },
      F: { keyCode: 70, key: "F", code: "KeyF" },
      G: { keyCode: 71, key: "G", code: "KeyG" },
      H: { keyCode: 72, key: "H", code: "KeyH" },
      I: { keyCode: 73, key: "I", code: "KeyI" },
      J: { keyCode: 74, key: "J", code: "KeyJ" },
      K: { keyCode: 75, key: "K", code: "KeyK" },
      L: { keyCode: 76, key: "L", code: "KeyL" },
      M: { keyCode: 77, key: "M", code: "KeyM" },
      N: { keyCode: 78, key: "N", code: "KeyN" },
      O: { keyCode: 79, key: "O", code: "KeyO" },
      P: { keyCode: 80, key: "P", code: "KeyP" },
      Q: { keyCode: 81, key: "Q", code: "KeyQ" },
      R: { keyCode: 82, key: "R", code: "KeyR" },
      S: { keyCode: 83, key: "S", code: "KeyS" },
      T: { keyCode: 84, key: "T", code: "KeyT" },
      U: { keyCode: 85, key: "U", code: "KeyU" },
      V: { keyCode: 86, key: "V", code: "KeyV" },
      W: { keyCode: 87, key: "W", code: "KeyW" },
      X: { keyCode: 88, key: "X", code: "KeyX" },
      Y: { keyCode: 89, key: "Y", code: "KeyY" },
      Z: { keyCode: 90, key: "Z", code: "KeyZ" },
      ":": { keyCode: 186, key: ":", code: "Semicolon" },
      "<": { keyCode: 188, key: "<", code: "Comma" },
      _: { keyCode: 189, key: "_", code: "Minus" },
      ">": { keyCode: 190, key: ">", code: "Period" },
      "?": { keyCode: 191, key: "?", code: "Slash" },
      "~": { keyCode: 192, key: "~", code: "Backquote" },
      "{": { keyCode: 219, key: "{", code: "BracketLeft" },
      "|": { keyCode: 220, key: "|", code: "Backslash" },
      "}": { keyCode: 221, key: "}", code: "BracketRight" },
      '"': { keyCode: 222, key: '"', code: "Quote" },
      SoftLeft: { key: "SoftLeft", code: "SoftLeft", location: 4 },
      SoftRight: { key: "SoftRight", code: "SoftRight", location: 4 },
      Camera: { keyCode: 44, key: "Camera", code: "Camera", location: 4 },
      Call: { key: "Call", code: "Call", location: 4 },
      EndCall: { keyCode: 95, key: "EndCall", code: "EndCall", location: 4 },
      VolumeDown: {
        keyCode: 182,
        key: "VolumeDown",
        code: "VolumeDown",
        location: 4
      },
      VolumeUp: { keyCode: 183, key: "VolumeUp", code: "VolumeUp", location: 4 }
    };
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/Input.js
var Keyboard, Mouse, Touchscreen;
var init_Input = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/Input.js"() {
    init_assert2();
    init_USKeyboardLayout();
    Keyboard = class {
      /** @internal */
      constructor(client) {
        this._modifiers = 0;
        this._pressedKeys = /* @__PURE__ */ new Set();
        this._client = client;
      }
      /**
         * Dispatches a `keydown` event.
         *
         * @remarks
         * If `key` is a single character and no modifier keys besides `Shift`
         * are being held down, a `keypress`/`input` event will also generated.
         * The `text` option can be specified to force an input event to be generated.
         * If `key` is a modifier key, `Shift`, `Meta`, `Control`, or `Alt`,
         * subsequent key presses will be sent with that modifier active.
         * To release the modifier key, use {@link Keyboard.up}.
         *
         * After the key is pressed once, subsequent calls to
         * {@link Keyboard.down} will have
         * {@link https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/repeat | repeat}
         * set to true. To release the key, use {@link Keyboard.up}.
         *
         * Modifier keys DO influence {@link Keyboard.down}.
         * Holding down `Shift` will type the text in upper case.
         *
         * @param key - Name of key to press, such as `ArrowLeft`.
         * See {@link KeyInput} for a list of all key names.
         *
         * @param options - An object of options. Accepts text which, if specified,
         * generates an input event with this text.
         */
      async down(key, options = { text: void 0 }) {
        const description = this._keyDescriptionForString(key);
        const autoRepeat = this._pressedKeys.has(description.code);
        this._pressedKeys.add(description.code);
        this._modifiers |= this._modifierBit(description.key);
        const text = options.text === void 0 ? description.text : options.text;
        await this._client.send("Input.dispatchKeyEvent", {
          type: text ? "keyDown" : "rawKeyDown",
          modifiers: this._modifiers,
          windowsVirtualKeyCode: description.keyCode,
          code: description.code,
          key: description.key,
          text,
          unmodifiedText: text,
          autoRepeat,
          location: description.location,
          isKeypad: description.location === 3
        });
      }
      _modifierBit(key) {
        if (key === "Alt") {
          return 1;
        }
        if (key === "Control") {
          return 2;
        }
        if (key === "Meta") {
          return 4;
        }
        if (key === "Shift") {
          return 8;
        }
        return 0;
      }
      _keyDescriptionForString(keyString) {
        const shift = this._modifiers & 8;
        const description = {
          key: "",
          keyCode: 0,
          code: "",
          text: "",
          location: 0
        };
        const definition = keyDefinitions[keyString];
        assert3(definition, `Unknown key: "${keyString}"`);
        if (definition.key) {
          description.key = definition.key;
        }
        if (shift && definition.shiftKey) {
          description.key = definition.shiftKey;
        }
        if (definition.keyCode) {
          description.keyCode = definition.keyCode;
        }
        if (shift && definition.shiftKeyCode) {
          description.keyCode = definition.shiftKeyCode;
        }
        if (definition.code) {
          description.code = definition.code;
        }
        if (definition.location) {
          description.location = definition.location;
        }
        if (description.key.length === 1) {
          description.text = description.key;
        }
        if (definition.text) {
          description.text = definition.text;
        }
        if (shift && definition.shiftText) {
          description.text = definition.shiftText;
        }
        if (this._modifiers & ~8) {
          description.text = "";
        }
        return description;
      }
      /**
         * Dispatches a `keyup` event.
         *
         * @param key - Name of key to release, such as `ArrowLeft`.
         * See {@link KeyInput | KeyInput}
         * for a list of all key names.
         */
      async up(key) {
        const description = this._keyDescriptionForString(key);
        this._modifiers &= ~this._modifierBit(description.key);
        this._pressedKeys.delete(description.code);
        await this._client.send("Input.dispatchKeyEvent", {
          type: "keyUp",
          modifiers: this._modifiers,
          key: description.key,
          windowsVirtualKeyCode: description.keyCode,
          code: description.code,
          location: description.location
        });
      }
      /**
         * Dispatches a `keypress` and `input` event.
         * This does not send a `keydown` or `keyup` event.
         *
         * @remarks
         * Modifier keys DO NOT effect {@link Keyboard.sendCharacter | Keyboard.sendCharacter}.
         * Holding down `Shift` will not type the text in upper case.
         *
         * @example
         * ```js
         * page.keyboard.sendCharacter('嗨');
         * ```
         *
         * @param char - Character to send into the page.
         */
      async sendCharacter(char) {
        await this._client.send("Input.insertText", { text: char });
      }
      charIsKey(char) {
        return !!keyDefinitions[char];
      }
      /**
         * Sends a `keydown`, `keypress`/`input`,
         * and `keyup` event for each character in the text.
         *
         * @remarks
         * To press a special key, like `Control` or `ArrowDown`,
         * use {@link Keyboard.press}.
         *
         * Modifier keys DO NOT effect `keyboard.type`.
         * Holding down `Shift` will not type the text in upper case.
         *
         * @example
         * ```js
         * await page.keyboard.type('Hello'); // Types instantly
         * await page.keyboard.type('World', {delay: 100}); // Types slower, like a user
         * ```
         *
         * @param text - A text to type into a focused element.
         * @param options - An object of options. Accepts delay which,
         * if specified, is the time to wait between `keydown` and `keyup` in milliseconds.
         * Defaults to 0.
         */
      async type(text, options = {}) {
        const delay = options.delay || null;
        for (const char of text) {
          if (this.charIsKey(char)) {
            await this.press(char, { delay });
          } else {
            if (delay) {
              await new Promise((f5) => setTimeout(f5, delay));
            }
            await this.sendCharacter(char);
          }
        }
      }
      /**
         * Shortcut for {@link Keyboard.down}
         * and {@link Keyboard.up}.
         *
         * @remarks
         * If `key` is a single character and no modifier keys besides `Shift`
         * are being held down, a `keypress`/`input` event will also generated.
         * The `text` option can be specified to force an input event to be generated.
         *
         * Modifier keys DO effect {@link Keyboard.press}.
         * Holding down `Shift` will type the text in upper case.
         *
         * @param key - Name of key to press, such as `ArrowLeft`.
         * See {@link KeyInput} for a list of all key names.
         *
         * @param options - An object of options. Accepts text which, if specified,
         * generates an input event with this text. Accepts delay which,
         * if specified, is the time to wait between `keydown` and `keyup` in milliseconds.
         * Defaults to 0.
         */
      async press(key, options = {}) {
        const { delay = null } = options;
        await this.down(key, options);
        if (delay) {
          await new Promise((f5) => setTimeout(f5, options.delay));
        }
        await this.up(key);
      }
    };
    Mouse = class {
      /**
         * @internal
         */
      constructor(client, keyboard) {
        this._x = 0;
        this._y = 0;
        this._button = "none";
        this._client = client;
        this._keyboard = keyboard;
      }
      /**
         * Dispatches a `mousemove` event.
         * @param x - Horizontal position of the mouse.
         * @param y - Vertical position of the mouse.
         * @param options - Optional object. If specified, the `steps` property
         * sends intermediate `mousemove` events when set to `1` (default).
         */
      async move(x3, y4, options = {}) {
        const { steps = 1 } = options;
        const fromX = this._x, fromY = this._y;
        this._x = x3;
        this._y = y4;
        for (let i6 = 1; i6 <= steps; i6++) {
          await this._client.send("Input.dispatchMouseEvent", {
            type: "mouseMoved",
            button: this._button,
            x: fromX + (this._x - fromX) * (i6 / steps),
            y: fromY + (this._y - fromY) * (i6 / steps),
            modifiers: this._keyboard._modifiers
          });
        }
      }
      /**
         * Shortcut for `mouse.move`, `mouse.down` and `mouse.up`.
         * @param x - Horizontal position of the mouse.
         * @param y - Vertical position of the mouse.
         * @param options - Optional `MouseOptions`.
         */
      async click(x3, y4, options = {}) {
        const { delay = null } = options;
        if (delay !== null) {
          await this.move(x3, y4);
          await this.down(options);
          await new Promise((f5) => setTimeout(f5, delay));
          await this.up(options);
        } else {
          await this.move(x3, y4);
          await this.down(options);
          await this.up(options);
        }
      }
      /**
         * Dispatches a `mousedown` event.
         * @param options - Optional `MouseOptions`.
         */
      async down(options = {}) {
        const { button = "left", clickCount = 1 } = options;
        this._button = button;
        await this._client.send("Input.dispatchMouseEvent", {
          type: "mousePressed",
          button,
          x: this._x,
          y: this._y,
          modifiers: this._keyboard._modifiers,
          clickCount
        });
      }
      /**
         * Dispatches a `mouseup` event.
         * @param options - Optional `MouseOptions`.
         */
      async up(options = {}) {
        const { button = "left", clickCount = 1 } = options;
        this._button = "none";
        await this._client.send("Input.dispatchMouseEvent", {
          type: "mouseReleased",
          button,
          x: this._x,
          y: this._y,
          modifiers: this._keyboard._modifiers,
          clickCount
        });
      }
      /**
         * Dispatches a `mousewheel` event.
         * @param options - Optional: `MouseWheelOptions`.
         *
         * @example
         * An example of zooming into an element:
         * ```js
         * await page.goto('https://mdn.mozillademos.org/en-US/docs/Web/API/Element/wheel_event$samples/Scaling_an_element_via_the_wheel?revision=1587366');
         *
         * const elem = await page.$('div');
         * const boundingBox = await elem.boundingBox();
         * await page.mouse.move(
         *   boundingBox.x + boundingBox.width / 2,
         *   boundingBox.y + boundingBox.height / 2
         * );
         *
         * await page.mouse.wheel({ deltaY: -100 })
         * ```
         */
      async wheel(options = {}) {
        const { deltaX = 0, deltaY = 0 } = options;
        await this._client.send("Input.dispatchMouseEvent", {
          type: "mouseWheel",
          x: this._x,
          y: this._y,
          deltaX,
          deltaY,
          modifiers: this._keyboard._modifiers,
          pointerType: "mouse"
        });
      }
    };
    Touchscreen = class {
      /**
         * @internal
         */
      constructor(client, keyboard) {
        this._client = client;
        this._keyboard = keyboard;
      }
      /**
         * Dispatches a `touchstart` and `touchend` event.
         * @param x - Horizontal position of the tap.
         * @param y - Vertical position of the tap.
         */
      async tap(x3, y4) {
        const touchPoints = [{ x: Math.round(x3), y: Math.round(y4) }];
        await this._client.send("Input.dispatchTouchEvent", {
          type: "touchStart",
          touchPoints,
          modifiers: this._keyboard._modifiers
        });
        await this._client.send("Input.dispatchTouchEvent", {
          type: "touchEnd",
          touchPoints: [],
          modifiers: this._keyboard._modifiers
        });
      }
    };
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/Tracing.js
var Tracing;
var init_Tracing = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/Tracing.js"() {
    init_assert2();
    init_helper();
    Tracing = class {
      /**
         * @internal
         */
      constructor(client) {
        this._recording = false;
        this._path = "";
        this._client = client;
      }
      /**
         * Starts a trace for the current page.
         * @remarks
         * Only one trace can be active at a time per browser.
         * @param options - Optional `TracingOptions`.
         */
      async start(options = {}) {
        assert3(
          !this._recording,
          "Cannot start recording trace while already recording trace."
        );
        const defaultCategories = [
          "-*",
          "devtools.timeline",
          "v8.execute",
          "disabled-by-default-devtools.timeline",
          "disabled-by-default-devtools.timeline.frame",
          "toplevel",
          "blink.console",
          "blink.user_timing",
          "latencyInfo",
          "disabled-by-default-devtools.timeline.stack",
          "disabled-by-default-v8.cpu_profiler",
          "disabled-by-default-v8.cpu_profiler.hires"
        ];
        const { path: path3 = null, screenshots = false, categories = defaultCategories } = options;
        if (screenshots) {
          categories.push("disabled-by-default-devtools.screenshot");
        }
        this._path = path3;
        this._recording = true;
        await this._client.send("Tracing.start", {
          transferMode: "ReturnAsStream",
          categories: categories.join(",")
        });
      }
      /**
         * Stops a trace started with the `start` method.
         * @returns Promise which resolves to buffer with trace data.
         */
      async stop() {
        let fulfill;
        let reject2;
        const contentPromise = new Promise((x3, y4) => {
          fulfill = x3;
          reject2 = y4;
        });
        this._client.once("Tracing.tracingComplete", (event) => {
          helper.readProtocolStream(this._client, event.stream, this._path).then(fulfill, reject2);
        });
        await this._client.send("Tracing.end");
        this._recording = false;
        return contentPromise;
      }
    };
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/Coverage.js
function convertToDisjointRanges(nestedRanges) {
  const points = [];
  for (const range of nestedRanges) {
    points.push({ offset: range.startOffset, type: 0, range });
    points.push({ offset: range.endOffset, type: 1, range });
  }
  points.sort((a5, b3) => {
    if (a5.offset !== b3.offset) {
      return a5.offset - b3.offset;
    }
    if (a5.type !== b3.type) {
      return b3.type - a5.type;
    }
    const aLength = a5.range.endOffset - a5.range.startOffset;
    const bLength = b3.range.endOffset - b3.range.startOffset;
    if (a5.type === 0) {
      return bLength - aLength;
    }
    return aLength - bLength;
  });
  const hitCountStack = [];
  const results = [];
  let lastOffset = 0;
  for (const point of points) {
    if (hitCountStack.length && lastOffset < point.offset && hitCountStack[hitCountStack.length - 1] > 0) {
      const lastResult = results.length ? results[results.length - 1] : null;
      if (lastResult && lastResult.end === lastOffset) {
        lastResult.end = point.offset;
      } else {
        results.push({ start: lastOffset, end: point.offset });
      }
    }
    lastOffset = point.offset;
    if (point.type === 0) {
      hitCountStack.push(point.range.count);
    } else {
      hitCountStack.pop();
    }
  }
  return results.filter((range) => range.end - range.start > 1);
}
var Coverage, JSCoverage, CSSCoverage;
var init_Coverage = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/Coverage.js"() {
    init_assert2();
    init_helper();
    init_ExecutionContext();
    Coverage = class {
      constructor(client) {
        this._jsCoverage = new JSCoverage(client);
        this._cssCoverage = new CSSCoverage(client);
      }
      /**
         * @param options - defaults to
         * `{ resetOnNavigation : true, reportAnonymousScripts : false }`
         * @returns Promise that resolves when coverage is started.
         *
         * @remarks
         * Anonymous scripts are ones that don't have an associated url. These are
         * scripts that are dynamically created on the page using `eval` or
         * `new Function`. If `reportAnonymousScripts` is set to `true`, anonymous
         * scripts will have `__puppeteer_evaluation_script__` as their URL.
         */
      async startJSCoverage(options = {}) {
        return await this._jsCoverage.start(options);
      }
      /**
         * @returns Promise that resolves to the array of coverage reports for
         * all scripts.
         *
         * @remarks
         * JavaScript Coverage doesn't include anonymous scripts by default.
         * However, scripts with sourceURLs are reported.
         */
      async stopJSCoverage() {
        return await this._jsCoverage.stop();
      }
      /**
         * @param options - defaults to `{ resetOnNavigation : true }`
         * @returns Promise that resolves when coverage is started.
         */
      async startCSSCoverage(options = {}) {
        return await this._cssCoverage.start(options);
      }
      /**
         * @returns Promise that resolves to the array of coverage reports
         * for all stylesheets.
         * @remarks
         * CSS Coverage doesn't include dynamically injected style tags
         * without sourceURLs.
         */
      async stopCSSCoverage() {
        return await this._cssCoverage.stop();
      }
    };
    JSCoverage = class {
      constructor(client) {
        this._enabled = false;
        this._scriptURLs = /* @__PURE__ */ new Map();
        this._scriptSources = /* @__PURE__ */ new Map();
        this._eventListeners = [];
        this._resetOnNavigation = false;
        this._reportAnonymousScripts = false;
        this._client = client;
      }
      async start(options = {}) {
        assert3(!this._enabled, "JSCoverage is already enabled");
        const { resetOnNavigation = true, reportAnonymousScripts = false } = options;
        this._resetOnNavigation = resetOnNavigation;
        this._reportAnonymousScripts = reportAnonymousScripts;
        this._enabled = true;
        this._scriptURLs.clear();
        this._scriptSources.clear();
        this._eventListeners = [
          helper.addEventListener(
            this._client,
            "Debugger.scriptParsed",
            this._onScriptParsed.bind(this)
          ),
          helper.addEventListener(
            this._client,
            "Runtime.executionContextsCleared",
            this._onExecutionContextsCleared.bind(this)
          )
        ];
        await Promise.all([
          this._client.send("Profiler.enable"),
          this._client.send("Profiler.startPreciseCoverage", {
            callCount: false,
            detailed: true
          }),
          this._client.send("Debugger.enable"),
          this._client.send("Debugger.setSkipAllPauses", { skip: true })
        ]);
      }
      _onExecutionContextsCleared() {
        if (!this._resetOnNavigation) {
          return;
        }
        this._scriptURLs.clear();
        this._scriptSources.clear();
      }
      async _onScriptParsed(event) {
        if (event.url === EVALUATION_SCRIPT_URL) {
          return;
        }
        if (!event.url && !this._reportAnonymousScripts) {
          return;
        }
        try {
          const response = await this._client.send("Debugger.getScriptSource", {
            scriptId: event.scriptId
          });
          this._scriptURLs.set(event.scriptId, event.url);
          this._scriptSources.set(event.scriptId, response.scriptSource);
        } catch (error2) {
          debugError(error2);
        }
      }
      async stop() {
        assert3(this._enabled, "JSCoverage is not enabled");
        this._enabled = false;
        const result2 = await Promise.all([
          this._client.send("Profiler.takePreciseCoverage"),
          this._client.send("Profiler.stopPreciseCoverage"),
          this._client.send("Profiler.disable"),
          this._client.send("Debugger.disable")
        ]);
        helper.removeEventListeners(this._eventListeners);
        const coverage = [];
        const profileResponse = result2[0];
        for (const entry of profileResponse.result) {
          let url = this._scriptURLs.get(entry.scriptId);
          if (!url && this._reportAnonymousScripts) {
            url = "debugger://VM" + entry.scriptId;
          }
          const text = this._scriptSources.get(entry.scriptId);
          if (text === void 0 || url === void 0) {
            continue;
          }
          const flattenRanges = [];
          for (const func of entry.functions) {
            flattenRanges.push(...func.ranges);
          }
          const ranges = convertToDisjointRanges(flattenRanges);
          coverage.push({ url, ranges, text });
        }
        return coverage;
      }
    };
    CSSCoverage = class {
      constructor(client) {
        this._enabled = false;
        this._stylesheetURLs = /* @__PURE__ */ new Map();
        this._stylesheetSources = /* @__PURE__ */ new Map();
        this._eventListeners = [];
        this._resetOnNavigation = false;
        this._reportAnonymousScripts = false;
        this._client = client;
      }
      async start(options = {}) {
        assert3(!this._enabled, "CSSCoverage is already enabled");
        const { resetOnNavigation = true } = options;
        this._resetOnNavigation = resetOnNavigation;
        this._enabled = true;
        this._stylesheetURLs.clear();
        this._stylesheetSources.clear();
        this._eventListeners = [
          helper.addEventListener(
            this._client,
            "CSS.styleSheetAdded",
            this._onStyleSheet.bind(this)
          ),
          helper.addEventListener(
            this._client,
            "Runtime.executionContextsCleared",
            this._onExecutionContextsCleared.bind(this)
          )
        ];
        await Promise.all([
          this._client.send("DOM.enable"),
          this._client.send("CSS.enable"),
          this._client.send("CSS.startRuleUsageTracking")
        ]);
      }
      _onExecutionContextsCleared() {
        if (!this._resetOnNavigation) {
          return;
        }
        this._stylesheetURLs.clear();
        this._stylesheetSources.clear();
      }
      async _onStyleSheet(event) {
        const header = event.header;
        if (!header.sourceURL) {
          return;
        }
        try {
          const response = await this._client.send("CSS.getStyleSheetText", {
            styleSheetId: header.styleSheetId
          });
          this._stylesheetURLs.set(header.styleSheetId, header.sourceURL);
          this._stylesheetSources.set(header.styleSheetId, response.text);
        } catch (error2) {
          debugError(error2);
        }
      }
      async stop() {
        assert3(this._enabled, "CSSCoverage is not enabled");
        this._enabled = false;
        const ruleTrackingResponse = await this._client.send(
          "CSS.stopRuleUsageTracking"
        );
        await Promise.all([
          this._client.send("CSS.disable"),
          this._client.send("DOM.disable")
        ]);
        helper.removeEventListeners(this._eventListeners);
        const styleSheetIdToCoverage = /* @__PURE__ */ new Map();
        for (const entry of ruleTrackingResponse.ruleUsage) {
          let ranges = styleSheetIdToCoverage.get(entry.styleSheetId);
          if (!ranges) {
            ranges = [];
            styleSheetIdToCoverage.set(entry.styleSheetId, ranges);
          }
          ranges.push({
            startOffset: entry.startOffset,
            endOffset: entry.endOffset,
            count: entry.used ? 1 : 0
          });
        }
        const coverage = [];
        for (const styleSheetId of this._stylesheetURLs.keys()) {
          const url = this._stylesheetURLs.get(styleSheetId);
          const text = this._stylesheetSources.get(styleSheetId);
          const ranges = convertToDisjointRanges(
            styleSheetIdToCoverage.get(styleSheetId) || []
          );
          coverage.push({ url, ranges, text });
        }
        return coverage;
      }
    };
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/WebWorker.js
var WebWorker;
var init_WebWorker = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/WebWorker.js"() {
    init_EventEmitter();
    init_helper();
    init_ExecutionContext();
    init_JSHandle();
    WebWorker = class extends EventEmitter2 {
      /**
         *
         * @internal
         */
      constructor(client, url, consoleAPICalled, exceptionThrown) {
        super();
        this._client = client;
        this._url = url;
        this._executionContextPromise = new Promise((x3) => this._executionContextCallback = x3);
        let jsHandleFactory;
        this._client.once("Runtime.executionContextCreated", async (event) => {
          jsHandleFactory = (remoteObject) => new JSHandle(executionContext, client, remoteObject);
          const executionContext = new ExecutionContext(
            client,
            event.context,
            null
          );
          this._executionContextCallback(executionContext);
        });
        this._client.send("Runtime.enable").catch(debugError);
        this._client.on(
          "Runtime.consoleAPICalled",
          (event) => consoleAPICalled(
            event.type,
            event.args.map(jsHandleFactory),
            event.stackTrace
          )
        );
        this._client.on(
          "Runtime.exceptionThrown",
          (exception3) => exceptionThrown(exception3.exceptionDetails)
        );
      }
      /**
         * @returns The URL of this web worker.
         */
      url() {
        return this._url;
      }
      /**
         * Returns the ExecutionContext the WebWorker runs in
         * @returns The ExecutionContext the web worker runs in.
         */
      async executionContext() {
        return this._executionContextPromise;
      }
      /**
         * If the function passed to the `worker.evaluate` returns a Promise, then
         * `worker.evaluate` would wait for the promise to resolve and return its
         * value. If the function passed to the `worker.evaluate` returns a
         * non-serializable value, then `worker.evaluate` resolves to `undefined`.
         * DevTools Protocol also supports transferring some additional values that
         * are not serializable by `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`, and
         * bigint literals.
         * Shortcut for `await worker.executionContext()).evaluate(pageFunction, ...args)`.
         *
         * @param pageFunction - Function to be evaluated in the worker context.
         * @param args - Arguments to pass to `pageFunction`.
         * @returns Promise which resolves to the return value of `pageFunction`.
         */
      async evaluate(pageFunction, ...args) {
        return (await this._executionContextPromise).evaluate(
          pageFunction,
          ...args
        );
      }
      /**
         * The only difference between `worker.evaluate` and `worker.evaluateHandle`
         * is that `worker.evaluateHandle` returns in-page object (JSHandle). If the
         * function passed to the `worker.evaluateHandle` returns a [Promise], then
         * `worker.evaluateHandle` would wait for the promise to resolve and return
         * its value. Shortcut for
         * `await worker.executionContext()).evaluateHandle(pageFunction, ...args)`
         *
         * @param pageFunction - Function to be evaluated in the page context.
         * @param args - Arguments to pass to `pageFunction`.
         * @returns Promise which resolves to the return value of `pageFunction`.
         */
      async evaluateHandle(pageFunction, ...args) {
        return (await this._executionContextPromise).evaluateHandle(
          pageFunction,
          ...args
        );
      }
    };
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/Accessibility.js
var Accessibility, AXNode;
var init_Accessibility = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/Accessibility.js"() {
    Accessibility = class {
      /**
         * @internal
         */
      constructor(client) {
        this._client = client;
      }
      /**
         * Captures the current state of the accessibility tree.
         * The returned object represents the root accessible node of the page.
         *
         * @remarks
         *
         * **NOTE** The Chromium accessibility tree contains nodes that go unused on
         * most platforms and by most screen readers. Puppeteer will discard them as
         * well for an easier to process tree, unless `interestingOnly` is set to
         * `false`.
         *
         * @example
         * An example of dumping the entire accessibility tree:
         * ```js
         * const snapshot = await page.accessibility.snapshot();
         * console.log(snapshot);
         * ```
         *
         * @example
         * An example of logging the focused node's name:
         * ```js
         * const snapshot = await page.accessibility.snapshot();
         * const node = findFocusedNode(snapshot);
         * console.log(node && node.name);
         *
         * function findFocusedNode(node) {
         *   if (node.focused)
         *     return node;
         *   for (const child of node.children || []) {
         *     const foundNode = findFocusedNode(child);
         *     return foundNode;
         *   }
         *   return null;
         * }
         * ```
         *
         * @returns An AXNode object representing the snapshot.
         *
         */
      async snapshot(options = {}) {
        const { interestingOnly = true, root = null } = options;
        const { nodes } = await this._client.send("Accessibility.getFullAXTree");
        let backendNodeId = null;
        if (root) {
          const { node } = await this._client.send("DOM.describeNode", {
            objectId: root._remoteObject.objectId
          });
          backendNodeId = node.backendNodeId;
        }
        const defaultRoot = AXNode.createTree(nodes);
        let needle = defaultRoot;
        if (backendNodeId) {
          needle = defaultRoot.find(
            (node) => node.payload.backendDOMNodeId === backendNodeId
          );
          if (!needle) {
            return null;
          }
        }
        if (!interestingOnly) {
          return this.serializeTree(needle)[0];
        }
        const interestingNodes = /* @__PURE__ */ new Set();
        this.collectInterestingNodes(interestingNodes, defaultRoot, false);
        if (!interestingNodes.has(needle)) {
          return null;
        }
        return this.serializeTree(needle, interestingNodes)[0];
      }
      serializeTree(node, interestingNodes) {
        const children = [];
        for (const child of node.children) {
          children.push(...this.serializeTree(child, interestingNodes));
        }
        if (interestingNodes && !interestingNodes.has(node)) {
          return children;
        }
        const serializedNode = node.serialize();
        if (children.length) {
          serializedNode.children = children;
        }
        return [serializedNode];
      }
      collectInterestingNodes(collection, node, insideControl) {
        if (node.isInteresting(insideControl)) {
          collection.add(node);
        }
        if (node.isLeafNode()) {
          return;
        }
        insideControl = insideControl || node.isControl();
        for (const child of node.children) {
          this.collectInterestingNodes(collection, child, insideControl);
        }
      }
    };
    AXNode = class _AXNode {
      constructor(payload) {
        this.children = [];
        this._richlyEditable = false;
        this._editable = false;
        this._focusable = false;
        this._hidden = false;
        this.payload = payload;
        this._name = this.payload.name ? this.payload.name.value : "";
        this._role = this.payload.role ? this.payload.role.value : "Unknown";
        this._ignored = this.payload.ignored;
        for (const property of this.payload.properties || []) {
          if (property.name === "editable") {
            this._richlyEditable = property.value.value === "richtext";
            this._editable = true;
          }
          if (property.name === "focusable") {
            this._focusable = property.value.value;
          }
          if (property.name === "hidden") {
            this._hidden = property.value.value;
          }
        }
      }
      _isPlainTextField() {
        if (this._richlyEditable) {
          return false;
        }
        if (this._editable) {
          return true;
        }
        return this._role === "textbox" || this._role === "searchbox";
      }
      _isTextOnlyObject() {
        const role = this._role;
        return role === "LineBreak" || role === "text" || role === "InlineTextBox";
      }
      _hasFocusableChild() {
        if (this._cachedHasFocusableChild === void 0) {
          this._cachedHasFocusableChild = false;
          for (const child of this.children) {
            if (child._focusable || child._hasFocusableChild()) {
              this._cachedHasFocusableChild = true;
              break;
            }
          }
        }
        return this._cachedHasFocusableChild;
      }
      find(predicate) {
        if (predicate(this)) {
          return this;
        }
        for (const child of this.children) {
          const result2 = child.find(predicate);
          if (result2) {
            return result2;
          }
        }
        return null;
      }
      isLeafNode() {
        if (!this.children.length) {
          return true;
        }
        if (this._isPlainTextField() || this._isTextOnlyObject()) {
          return true;
        }
        switch (this._role) {
          case "doc-cover":
          case "graphics-symbol":
          case "img":
          case "Meter":
          case "scrollbar":
          case "slider":
          case "separator":
          case "progressbar":
            return true;
          default:
            break;
        }
        if (this._hasFocusableChild()) {
          return false;
        }
        if (this._focusable && this._name) {
          return true;
        }
        if (this._role === "heading" && this._name) {
          return true;
        }
        return false;
      }
      isControl() {
        switch (this._role) {
          case "button":
          case "checkbox":
          case "ColorWell":
          case "combobox":
          case "DisclosureTriangle":
          case "listbox":
          case "menu":
          case "menubar":
          case "menuitem":
          case "menuitemcheckbox":
          case "menuitemradio":
          case "radio":
          case "scrollbar":
          case "searchbox":
          case "slider":
          case "spinbutton":
          case "switch":
          case "tab":
          case "textbox":
          case "tree":
          case "treeitem":
            return true;
          default:
            return false;
        }
      }
      isInteresting(insideControl) {
        const role = this._role;
        if (role === "Ignored" || this._hidden || this._ignored) {
          return false;
        }
        if (this._focusable || this._richlyEditable) {
          return true;
        }
        if (this.isControl()) {
          return true;
        }
        if (insideControl) {
          return false;
        }
        return this.isLeafNode() && !!this._name;
      }
      serialize() {
        const properties = /* @__PURE__ */ new Map();
        for (const property of this.payload.properties || []) {
          properties.set(property.name.toLowerCase(), property.value.value);
        }
        if (this.payload.name) {
          properties.set("name", this.payload.name.value);
        }
        if (this.payload.value) {
          properties.set("value", this.payload.value.value);
        }
        if (this.payload.description) {
          properties.set("description", this.payload.description.value);
        }
        const node = {
          role: this._role
        };
        const userStringProperties = [
          "name",
          "value",
          "description",
          "keyshortcuts",
          "roledescription",
          "valuetext"
        ];
        const getUserStringPropertyValue = (key) => properties.get(key);
        for (const userStringProperty of userStringProperties) {
          if (!properties.has(userStringProperty)) {
            continue;
          }
          node[userStringProperty] = getUserStringPropertyValue(userStringProperty);
        }
        const booleanProperties = [
          "disabled",
          "expanded",
          "focused",
          "modal",
          "multiline",
          "multiselectable",
          "readonly",
          "required",
          "selected"
        ];
        const getBooleanPropertyValue = (key) => properties.get(key);
        for (const booleanProperty of booleanProperties) {
          if (booleanProperty === "focused" && this._role === "WebArea") {
            continue;
          }
          const value = getBooleanPropertyValue(booleanProperty);
          if (!value) {
            continue;
          }
          node[booleanProperty] = getBooleanPropertyValue(booleanProperty);
        }
        const tristateProperties = ["checked", "pressed"];
        for (const tristateProperty of tristateProperties) {
          if (!properties.has(tristateProperty)) {
            continue;
          }
          const value = properties.get(tristateProperty);
          node[tristateProperty] = value === "mixed" ? "mixed" : value === "true" ? true : false;
        }
        const numericalProperties = [
          "level",
          "valuemax",
          "valuemin"
        ];
        const getNumericalPropertyValue = (key) => properties.get(key);
        for (const numericalProperty of numericalProperties) {
          if (!properties.has(numericalProperty)) {
            continue;
          }
          node[numericalProperty] = getNumericalPropertyValue(numericalProperty);
        }
        const tokenProperties = [
          "autocomplete",
          "haspopup",
          "invalid",
          "orientation"
        ];
        const getTokenPropertyValue = (key) => properties.get(key);
        for (const tokenProperty of tokenProperties) {
          const value = getTokenPropertyValue(tokenProperty);
          if (!value || value === "false") {
            continue;
          }
          node[tokenProperty] = getTokenPropertyValue(tokenProperty);
        }
        return node;
      }
      static createTree(payloads) {
        const nodeById = /* @__PURE__ */ new Map();
        for (const payload of payloads) {
          nodeById.set(payload.nodeId, new _AXNode(payload));
        }
        for (const node of nodeById.values()) {
          for (const childId of node.payload.childIds || []) {
            node.children.push(nodeById.get(childId));
          }
        }
        return nodeById.values().next().value;
      }
    };
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/TimeoutSettings.js
var DEFAULT_TIMEOUT, TimeoutSettings;
var init_TimeoutSettings = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/TimeoutSettings.js"() {
    DEFAULT_TIMEOUT = 3e4;
    TimeoutSettings = class {
      constructor() {
        this._defaultTimeout = null;
        this._defaultNavigationTimeout = null;
      }
      setDefaultTimeout(timeout) {
        this._defaultTimeout = timeout;
      }
      setDefaultNavigationTimeout(timeout) {
        this._defaultNavigationTimeout = timeout;
      }
      navigationTimeout() {
        if (this._defaultNavigationTimeout !== null) {
          return this._defaultNavigationTimeout;
        }
        if (this._defaultTimeout !== null) {
          return this._defaultTimeout;
        }
        return DEFAULT_TIMEOUT;
      }
      timeout() {
        if (this._defaultTimeout !== null) {
          return this._defaultTimeout;
        }
        return DEFAULT_TIMEOUT;
      }
    };
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/FileChooser.js
var FileChooser;
var init_FileChooser = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/FileChooser.js"() {
    init_assert2();
    FileChooser = class {
      /**
         * @internal
         */
      constructor(element, event) {
        this._handled = false;
        this._element = element;
        this._multiple = event.mode !== "selectSingle";
      }
      /**
         * Whether file chooser allow for {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#attr-multiple | multiple} file selection.
         */
      isMultiple() {
        return this._multiple;
      }
      /**
         * Accept the file chooser request with given paths.
         * @param filePaths - If some of the  `filePaths` are relative paths,
         * then they are resolved relative to the {@link https://nodejs.org/api/process.html#process_process_cwd | current working directory}.
         */
      async accept(filePaths) {
        assert3(
          !this._handled,
          "Cannot accept FileChooser which is already handled!"
        );
        this._handled = true;
        await this._element.uploadFile(...filePaths);
      }
      /**
         * Closes the file chooser without selecting any files.
         */
      cancel() {
        assert3(
          !this._handled,
          "Cannot cancel FileChooser which is already handled!"
        );
        this._handled = true;
      }
    };
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/ConsoleMessage.js
var ConsoleMessage;
var init_ConsoleMessage = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/ConsoleMessage.js"() {
    ConsoleMessage = class {
      /**
         * @public
         */
      constructor(type4, text, args, stackTraceLocations) {
        this._type = type4;
        this._text = text;
        this._args = args;
        this._stackTraceLocations = stackTraceLocations;
      }
      /**
         * @returns The type of the console message.
         */
      type() {
        return this._type;
      }
      /**
         * @returns The text of the console message.
         */
      text() {
        return this._text;
      }
      /**
         * @returns An array of arguments passed to the console.
         */
      args() {
        return this._args;
      }
      /**
         * @returns The location of the console message.
         */
      location() {
        return this._stackTraceLocations.length ? this._stackTraceLocations[0] : {};
      }
      /**
         * @returns The array of locations on the stack of the console message.
         */
      stackTrace() {
        return this._stackTraceLocations;
      }
    };
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/PDFOptions.js
var paperFormats;
var init_PDFOptions = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/PDFOptions.js"() {
    paperFormats = {
      letter: { width: 8.5, height: 11 },
      legal: { width: 8.5, height: 14 },
      tabloid: { width: 11, height: 17 },
      ledger: { width: 17, height: 11 },
      a0: { width: 33.1, height: 46.8 },
      a1: { width: 23.4, height: 33.1 },
      a2: { width: 16.54, height: 23.4 },
      a3: { width: 11.7, height: 16.54 },
      a4: { width: 8.27, height: 11.7 },
      a5: { width: 5.83, height: 8.27 },
      a6: { width: 4.13, height: 5.83 }
    };
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/Page.js
function convertPrintParameterToInches(parameter) {
  if (typeof parameter === "undefined") {
    return void 0;
  }
  let pixels;
  if (helper.isNumber(parameter)) {
    pixels = /** @type {number} */
    parameter;
  } else if (helper.isString(parameter)) {
    const text = (
      /** @type {string} */
      parameter
    );
    let unit = text.substring(text.length - 2).toLowerCase();
    let valueText = "";
    if (unitToPixels.hasOwnProperty(unit)) {
      valueText = text.substring(0, text.length - 2);
    } else {
      unit = "px";
      valueText = text;
    }
    const value = Number(valueText);
    assert3(!isNaN(value), "Failed to parse parameter value: " + text);
    pixels = value * unitToPixels[unit];
  } else {
    throw new Error(
      "page.pdf() Cannot handle parameter type: " + typeof parameter
    );
  }
  return pixels / 96;
}
var ScreenshotTaskQueue, Page, supportedMetrics, unitToPixels;
var init_Page = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/Page.js"() {
    init_EventEmitter();
    init_Connection();
    init_Dialog();
    init_EmulationManager();
    init_FrameManager();
    init_Input();
    init_Tracing();
    init_assert2();
    init_helper();
    init_Coverage();
    init_WebWorker();
    init_JSHandle();
    init_NetworkManager();
    init_Accessibility();
    init_TimeoutSettings();
    init_FileChooser();
    init_ConsoleMessage();
    init_PDFOptions();
    init_std();
    ScreenshotTaskQueue = class {
      constructor() {
        this._chain = Promise.resolve(void 0);
      }
      postTask(task) {
        const result2 = this._chain.then(task);
        this._chain = result2.catch(() => {
        });
        return result2;
      }
    };
    Page = class _Page extends EventEmitter2 {
      /**
         * @internal
         */
      constructor(client, target, ignoreHTTPSErrors) {
        super();
        this._closed = false;
        this._timeoutSettings = new TimeoutSettings();
        this._pageBindings = /* @__PURE__ */ new Map();
        this._javascriptEnabled = true;
        this._workers = /* @__PURE__ */ new Map();
        this._fileChooserInterceptors = /* @__PURE__ */ new Set();
        this._client = client;
        this._target = target;
        this._keyboard = new Keyboard(client);
        this._mouse = new Mouse(client, this._keyboard);
        this._touchscreen = new Touchscreen(client, this._keyboard);
        this._accessibility = new Accessibility(client);
        this._frameManager = new FrameManager(
          client,
          this,
          ignoreHTTPSErrors,
          this._timeoutSettings
        );
        this._emulationManager = new EmulationManager(client);
        this._tracing = new Tracing(client);
        this._coverage = new Coverage(client);
        this._screenshotTaskQueue = new ScreenshotTaskQueue();
        this._viewport = null;
        client.on("Target.attachedToTarget", (event) => {
          if (event.targetInfo.type !== "worker") {
            client.send("Target.detachFromTarget", {
              sessionId: event.sessionId
            }).catch(debugError);
            return;
          }
          const session = Connection.fromSession(client).session(event.sessionId);
          const worker = new WebWorker(
            session,
            event.targetInfo.url,
            this._addConsoleMessage.bind(this),
            this._handleException.bind(this)
          );
          this._workers.set(event.sessionId, worker);
          this.emit(
            "workercreated",
            /* WorkerCreated */
            worker
          );
        });
        client.on("Target.detachedFromTarget", (event) => {
          const worker = this._workers.get(event.sessionId);
          if (!worker) {
            return;
          }
          this._workers.delete(event.sessionId);
          this.emit(
            "workerdestroyed",
            /* WorkerDestroyed */
            worker
          );
        });
        this._frameManager.on(
          FrameManagerEmittedEvents.FrameAttached,
          (event) => this.emit(
            "frameattached",
            /* FrameAttached */
            event
          )
        );
        this._frameManager.on(
          FrameManagerEmittedEvents.FrameDetached,
          (event) => this.emit(
            "framedetached",
            /* FrameDetached */
            event
          )
        );
        this._frameManager.on(
          FrameManagerEmittedEvents.FrameNavigated,
          (event) => this.emit(
            "framenavigated",
            /* FrameNavigated */
            event
          )
        );
        const networkManager = this._frameManager.networkManager();
        networkManager.on(
          NetworkManagerEmittedEvents.Request,
          (event) => this.emit(
            "request",
            /* Request */
            event
          )
        );
        networkManager.on(
          NetworkManagerEmittedEvents.RequestServedFromCache,
          (event) => this.emit(
            "requestservedfromcache",
            /* RequestServedFromCache */
            event
          )
        );
        networkManager.on(
          NetworkManagerEmittedEvents.Response,
          (event) => this.emit(
            "response",
            /* Response */
            event
          )
        );
        networkManager.on(
          NetworkManagerEmittedEvents.RequestFailed,
          (event) => this.emit(
            "requestfailed",
            /* RequestFailed */
            event
          )
        );
        networkManager.on(
          NetworkManagerEmittedEvents.RequestFinished,
          (event) => this.emit(
            "requestfinished",
            /* RequestFinished */
            event
          )
        );
        this._fileChooserInterceptors = /* @__PURE__ */ new Set();
        client.on(
          "Page.domContentEventFired",
          () => this.emit(
            "domcontentloaded"
            /* DOMContentLoaded */
          )
        );
        client.on("Page.loadEventFired", () => this.emit(
          "load"
          /* Load */
        ));
        client.on("Runtime.consoleAPICalled", (event) => this._onConsoleAPI(event));
        client.on("Runtime.bindingCalled", (event) => this._onBindingCalled(event));
        client.on("Page.javascriptDialogOpening", (event) => this._onDialog(event));
        client.on(
          "Runtime.exceptionThrown",
          (exception3) => this._handleException(exception3.exceptionDetails)
        );
        client.on("Inspector.targetCrashed", () => this._onTargetCrashed());
        client.on("Performance.metrics", (event) => this._emitMetrics(event));
        client.on("Log.entryAdded", (event) => this._onLogEntryAdded(event));
        client.on("Page.fileChooserOpened", (event) => this._onFileChooser(event));
        this._target._isClosedPromise.then(() => {
          this.emit(
            "close"
            /* Close */
          );
          this._closed = true;
        });
      }
      /**
         * @internal
         */
      static async create(client, target, ignoreHTTPSErrors, defaultViewport) {
        const page = new _Page(client, target, ignoreHTTPSErrors);
        await page._initialize();
        if (defaultViewport) {
          await page.setViewport(defaultViewport);
        }
        return page;
      }
      async _initialize() {
        await Promise.all([
          this._frameManager.initialize(),
          this._client.send("Target.setAutoAttach", {
            autoAttach: true,
            waitForDebuggerOnStart: false,
            flatten: true
          }),
          this._client.send("Performance.enable"),
          this._client.send("Log.enable")
        ]);
      }
      async _onFileChooser(event) {
        if (!this._fileChooserInterceptors.size) {
          return;
        }
        const frame = this._frameManager.frame(event.frameId);
        const context = await frame.executionContext();
        const element = await context._adoptBackendNodeId(event.backendNodeId);
        const interceptors = Array.from(this._fileChooserInterceptors);
        this._fileChooserInterceptors.clear();
        const fileChooser = new FileChooser(element, event);
        for (const interceptor of interceptors) {
          interceptor.call(null, fileChooser);
        }
      }
      /**
         * @returns `true` if the page has JavaScript enabled, `false` otherwise.
         */
      isJavaScriptEnabled() {
        return this._javascriptEnabled;
      }
      /**
         * Listen to page events.
         */
      on(eventName, handler) {
        return super.on(eventName, handler);
      }
      once(eventName, handler) {
        return super.once(eventName, handler);
      }
      /**
         * @param options - Optional waiting parameters
         * @returns Resolves after a page requests a file picker.
         */
      async waitForFileChooser(options = {}) {
        if (!this._fileChooserInterceptors.size) {
          await this._client.send("Page.setInterceptFileChooserDialog", {
            enabled: true
          });
        }
        const { timeout = this._timeoutSettings.timeout() } = options;
        let callback;
        const promise = new Promise((x3) => callback = x3);
        this._fileChooserInterceptors.add(callback);
        return helper.waitWithTimeout(promise, "waiting for file chooser", timeout).catch((error2) => {
          this._fileChooserInterceptors.delete(callback);
          throw error2;
        });
      }
      /**
         * Sets the page's geolocation.
         *
         * @remarks
         * Consider using {@link BrowserContext.overridePermissions} to grant
         * permissions for the page to read its geolocation.
         *
         * @example
         * ```js
         * await page.setGeolocation({latitude: 59.95, longitude: 30.31667});
         * ```
         */
      async setGeolocation(options) {
        const { longitude, latitude, accuracy = 0 } = options;
        if (longitude < -180 || longitude > 180) {
          throw new Error(
            `Invalid longitude "${longitude}": precondition -180 <= LONGITUDE <= 180 failed.`
          );
        }
        if (latitude < -90 || latitude > 90) {
          throw new Error(
            `Invalid latitude "${latitude}": precondition -90 <= LATITUDE <= 90 failed.`
          );
        }
        if (accuracy < 0) {
          throw new Error(
            `Invalid accuracy "${accuracy}": precondition 0 <= ACCURACY failed.`
          );
        }
        await this._client.send("Emulation.setGeolocationOverride", {
          longitude,
          latitude,
          accuracy
        });
      }
      /**
         * @returns A target this page was created from.
         */
      target() {
        return this._target;
      }
      /**
         * @returns The browser this page belongs to.
         */
      browser() {
        return this._target.browser();
      }
      /**
         * @returns The browser context that the page belongs to
         */
      browserContext() {
        return this._target.browserContext();
      }
      _onTargetCrashed() {
        this.emit("error", new Error("Page crashed!"));
      }
      _onLogEntryAdded(event) {
        const { level, text, args, source: source2, url, lineNumber } = event.entry;
        if (args) {
          args.map((arg) => helper.releaseObject(this._client, arg));
        }
        if (source2 !== "worker") {
          this.emit(
            "console",
            /* Console */
            new ConsoleMessage(level, text, [], [{ url, lineNumber }])
          );
        }
      }
      /**
         * @returns The page's main frame.
         */
      mainFrame() {
        return this._frameManager.mainFrame();
      }
      get keyboard() {
        return this._keyboard;
      }
      get touchscreen() {
        return this._touchscreen;
      }
      get coverage() {
        return this._coverage;
      }
      get tracing() {
        return this._tracing;
      }
      get accessibility() {
        return this._accessibility;
      }
      /**
         * @returns An array of all frames attached to the page.
         */
      frames() {
        return this._frameManager.frames();
      }
      /**
         * @returns all of the dedicated
         * {@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API | WebWorkers}
         * associated with the page.
         */
      workers() {
        return Array.from(this._workers.values());
      }
      /**
         * @param value - Whether to enable request interception.
         * @param cacheSafe - Whether to trust browser caching. If set to false,
         * enabling request interception disables page caching. Defaults to false.
         *
         * @remarks
         * Activating request interception enables {@link HTTPRequest.abort},
         * {@link HTTPRequest.continue} and {@link HTTPRequest.respond} methods.  This
         * provides the capability to modify network requests that are made by a page.
         *
         * Once request interception is enabled, every request will stall unless it's
         * continued, responded or aborted; or completed using the browser cache.
         *
         * @example
         * An example of a naïve request interceptor that aborts all image requests:
         * ```js
         * const puppeteer = require('puppeteer');
         * (async () => {
         *   const browser = await puppeteer.launch();
         *   const page = await browser.newPage();
         *   await page.setRequestInterception(true);
         *   page.on('request', interceptedRequest => {
         *     if (interceptedRequest.url().endsWith('.png') ||
         *         interceptedRequest.url().endsWith('.jpg'))
         *       interceptedRequest.abort();
         *     else
         *       interceptedRequest.continue();
         *     });
         *   await page.goto('https://example.com');
         *   await browser.close();
         * })();
         * ```
         */
      async setRequestInterception(value, cacheSafe = false) {
        return this._frameManager.networkManager().setRequestInterception(value, cacheSafe);
      }
      /**
         * @param enabled - When `true`, enables offline mode for the page.
         */
      setOfflineMode(enabled5) {
        return this._frameManager.networkManager().setOfflineMode(enabled5);
      }
      emulateNetworkConditions(networkConditions2) {
        return this._frameManager.networkManager().emulateNetworkConditions(networkConditions2);
      }
      /**
         * @param timeout - Maximum navigation time in milliseconds.
         */
      setDefaultNavigationTimeout(timeout) {
        this._timeoutSettings.setDefaultNavigationTimeout(timeout);
      }
      /**
         * @param timeout - Maximum time in milliseconds.
         */
      setDefaultTimeout(timeout) {
        this._timeoutSettings.setDefaultTimeout(timeout);
      }
      /**
         * Runs `document.querySelector` within the page. If no element matches the
         * selector, the return value resolves to `null`.
         *
         * @remarks
         * Shortcut for {@link Frame.$ | Page.mainFrame().$(selector) }.
         *
         * @param selector - A
         * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | selector}
         * to query page for.
         */
      async $(selector) {
        return this.mainFrame().$(selector);
      }
      /**
         * @remarks
         *
         * The only difference between {@link Page.evaluate | page.evaluate} and
         * `page.evaluateHandle` is that `evaluateHandle` will return the value
         * wrapped in an in-page object.
         *
         * If the function passed to `page.evaluteHandle` returns a Promise, the
         * function will wait for the promise to resolve and return its value.
         *
         * You can pass a string instead of a function (although functions are
         * recommended as they are easier to debug and use with TypeScript):
         *
         * @example
         * ```
         * const aHandle = await page.evaluateHandle('document')
         * ```
         *
         * @example
         * {@link JSHandle} instances can be passed as arguments to the `pageFunction`:
         * ```
         * const aHandle = await page.evaluateHandle(() => document.body);
         * const resultHandle = await page.evaluateHandle(body => body.innerHTML, aHandle);
         * console.log(await resultHandle.jsonValue());
         * await resultHandle.dispose();
         * ```
         *
         * Most of the time this function returns a {@link JSHandle},
         * but if `pageFunction` returns a reference to an element,
         * you instead get an {@link ElementHandle} back:
         *
         * @example
         * ```
         * const button = await page.evaluateHandle(() => document.querySelector('button'));
         * // can call `click` because `button` is an `ElementHandle`
         * await button.click();
         * ```
         *
         * The TypeScript definitions assume that `evaluateHandle` returns
         *  a `JSHandle`, but if you know it's going to return an
         * `ElementHandle`, pass it as the generic argument:
         *
         * ```
         * const button = await page.evaluateHandle<ElementHandle>(...);
         * ```
         *
         * @param pageFunction - a function that is run within the page
         * @param args - arguments to be passed to the pageFunction
         */
      async evaluateHandle(pageFunction, ...args) {
        const context = await this.mainFrame().executionContext();
        return context.evaluateHandle(pageFunction, ...args);
      }
      /**
         * This method iterates the JavaScript heap and finds all objects with the
         * given prototype.
         *
         * @remarks
         *
         * @example
         *
         * ```js
         * // Create a Map object
         * await page.evaluate(() => window.map = new Map());
         * // Get a handle to the Map object prototype
         * const mapPrototype = await page.evaluateHandle(() => Map.prototype);
         * // Query all map instances into an array
         * const mapInstances = await page.queryObjects(mapPrototype);
         * // Count amount of map objects in heap
         * const count = await page.evaluate(maps => maps.length, mapInstances);
         * await mapInstances.dispose();
         * await mapPrototype.dispose();
         * ```
         * @param prototypeHandle - a handle to the object prototype.
         */
      async queryObjects(prototypeHandle) {
        const context = await this.mainFrame().executionContext();
        return context.queryObjects(prototypeHandle);
      }
      /**
         * This method runs `document.querySelector` within the page and passes the
         * result as the first argument to the `pageFunction`.
         *
         * @remarks
         *
         * If no element is found matching `selector`, the method will throw an error.
         *
         * If `pageFunction` returns a promise `$eval` will wait for the promise to
         * resolve and then return its value.
         *
         * @example
         *
         * ```
         * const searchValue = await page.$eval('#search', el => el.value);
         * const preloadHref = await page.$eval('link[rel=preload]', el => el.href);
         * const html = await page.$eval('.main-container', el => el.outerHTML);
         * ```
         *
         * If you are using TypeScript, you may have to provide an explicit type to the
         * first argument of the `pageFunction`.
         * By default it is typed as `Element`, but you may need to provide a more
         * specific sub-type:
         *
         * @example
         *
         * ```
         * // if you don't provide HTMLInputElement here, TS will error
         * // as `value` is not on `Element`
         * const searchValue = await page.$eval('#search', (el: HTMLInputElement) => el.value);
         * ```
         *
         * The compiler should be able to infer the return type
         * from the `pageFunction` you provide. If it is unable to, you can use the generic
         * type to tell the compiler what return type you expect from `$eval`:
         *
         * @example
         *
         * ```
         * // The compiler can infer the return type in this case, but if it can't
         * // or if you want to be more explicit, provide it as the generic type.
         * const searchValue = await page.$eval<string>(
         *  '#search', (el: HTMLInputElement) => el.value
         * );
         * ```
         *
         * @param selector - the
         * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | selector}
         * to query for
         * @param pageFunction - the function to be evaluated in the page context.
         * Will be passed the result of `document.querySelector(selector)` as its
         * first argument.
         * @param args - any additional arguments to pass through to `pageFunction`.
         *
         * @returns The result of calling `pageFunction`. If it returns an element it
         * is wrapped in an {@link ElementHandle}, else the raw value itself is
         * returned.
         */
      async $eval(selector, pageFunction, ...args) {
        return this.mainFrame().$eval(selector, pageFunction, ...args);
      }
      /**
         * This method runs `Array.from(document.querySelectorAll(selector))` within
         * the page and passes the result as the first argument to the `pageFunction`.
         *
         * @remarks
         *
         * If `pageFunction` returns a promise `$$eval` will wait for the promise to
         * resolve and then return its value.
         *
         * @example
         *
         * ```
         * // get the amount of divs on the page
         * const divCount = await page.$$eval('div', divs => divs.length);
         *
         * // get the text content of all the `.options` elements:
         * const options = await page.$$eval('div > span.options', options => {
         *   return options.map(option => option.textContent)
         * });
         * ```
         *
         * If you are using TypeScript, you may have to provide an explicit type to the
         * first argument of the `pageFunction`.
         * By default it is typed as `Element[]`, but you may need to provide a more
         * specific sub-type:
         *
         * @example
         *
         * ```
         * // if you don't provide HTMLInputElement here, TS will error
         * // as `value` is not on `Element`
         * await page.$$eval('input', (elements: HTMLInputElement[]) => {
         *   return elements.map(e => e.value);
         * });
         * ```
         *
         * The compiler should be able to infer the return type
         * from the `pageFunction` you provide. If it is unable to, you can use the generic
         * type to tell the compiler what return type you expect from `$$eval`:
         *
         * @example
         *
         * ```
         * // The compiler can infer the return type in this case, but if it can't
         * // or if you want to be more explicit, provide it as the generic type.
         * const allInputValues = await page.$$eval<string[]>(
         *  'input', (elements: HTMLInputElement[]) => elements.map(e => e.textContent)
         * );
         * ```
         *
         * @param selector - the
         * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | selector}
         * to query for
         * @param pageFunction - the function to be evaluated in the page context. Will
         * be passed the result of `Array.from(document.querySelectorAll(selector))`
         * as its first argument.
         * @param args - any additional arguments to pass through to `pageFunction`.
         *
         * @returns The result of calling `pageFunction`. If it returns an element it
         * is wrapped in an {@link ElementHandle}, else the raw value itself is
         * returned.
         */
      async $$eval(selector, pageFunction, ...args) {
        return this.mainFrame().$$eval(selector, pageFunction, ...args);
      }
      async $$(selector) {
        return this.mainFrame().$$(selector);
      }
      async $x(expression) {
        return this.mainFrame().$x(expression);
      }
      /**
         * If no URLs are specified, this method returns cookies for the current page
         * URL. If URLs are specified, only cookies for those URLs are returned.
         */
      async cookies(...urls) {
        const originalCookies = (await this._client.send("Network.getCookies", {
          urls: urls.length ? urls : [this.url()]
        })).cookies;
        const unsupportedCookieAttributes = ["priority"];
        const filterUnsupportedAttributes = (cookie) => {
          for (const attr of unsupportedCookieAttributes) {
            delete cookie[attr];
          }
          return cookie;
        };
        return originalCookies.map(filterUnsupportedAttributes);
      }
      async deleteCookie(...cookies) {
        const pageURL = this.url();
        for (const cookie of cookies) {
          const item = Object.assign({}, cookie);
          if (!cookie.url && pageURL.startsWith("http")) {
            item.url = pageURL;
          }
          await this._client.send("Network.deleteCookies", item);
        }
      }
      async setCookie(...cookies) {
        const pageURL = this.url();
        const startsWithHTTP = pageURL.startsWith("http");
        const items = cookies.map((cookie) => {
          const item = Object.assign({}, cookie);
          if (!item.url && startsWithHTTP) {
            item.url = pageURL;
          }
          assert3(
            item.url !== "about:blank",
            `Blank page can not have cookie "${item.name}"`
          );
          assert3(
            !String.prototype.startsWith.call(item.url || "", "data:"),
            `Data URL page can not have cookie "${item.name}"`
          );
          return item;
        });
        await this.deleteCookie(...items);
        if (items.length) {
          await this._client.send("Network.setCookies", { cookies: items });
        }
      }
      async addScriptTag(options) {
        return this.mainFrame().addScriptTag(options);
      }
      async addStyleTag(options) {
        return this.mainFrame().addStyleTag(options);
      }
      async exposeFunction(name2, puppeteerFunction) {
        if (this._pageBindings.has(name2)) {
          throw new Error(
            `Failed to add page binding with name ${name2}: window['${name2}'] already exists!`
          );
        }
        this._pageBindings.set(name2, puppeteerFunction);
        const expression = helper.pageBindingInitString("exposedFun", name2);
        await this._client.send("Runtime.addBinding", { name: name2 });
        await this._client.send("Page.addScriptToEvaluateOnNewDocument", {
          source: expression
        });
        await Promise.all(
          this.frames().map(
            (frame) => frame.evaluate(expression).catch(debugError)
          )
        );
      }
      async authenticate(credentials) {
        return this._frameManager.networkManager().authenticate(credentials);
      }
      async setExtraHTTPHeaders(headers) {
        return this._frameManager.networkManager().setExtraHTTPHeaders(headers);
      }
      async setUserAgent(userAgent) {
        return this._frameManager.networkManager().setUserAgent(userAgent);
      }
      async metrics() {
        const response = await this._client.send("Performance.getMetrics");
        return this._buildMetricsObject(response.metrics);
      }
      _emitMetrics(event) {
        this.emit(
          "metrics",
          /* Metrics */
          {
            title: event.title,
            metrics: this._buildMetricsObject(event.metrics)
          }
        );
      }
      _buildMetricsObject(metrics) {
        const result2 = {};
        for (const metric of metrics || []) {
          if (supportedMetrics.has(metric.name)) {
            result2[metric.name] = metric.value;
          }
        }
        return result2;
      }
      _handleException(exceptionDetails) {
        const message = helper.getExceptionMessage(exceptionDetails);
        const err2 = new Error(message);
        err2.stack = "";
        this.emit(
          "pageerror",
          /* PageError */
          err2
        );
      }
      async _onConsoleAPI(event) {
        if (event.executionContextId === 0) {
          return;
        }
        const context = this._frameManager.executionContextById(
          event.executionContextId
        );
        const values = event.args.map((arg) => createJSHandle(context, arg));
        this._addConsoleMessage(event.type, values, event.stackTrace);
      }
      async _onBindingCalled(event) {
        let payload;
        try {
          payload = JSON.parse(event.payload);
        } catch {
          return;
        }
        const { type: type4, name: name2, seq: seq3, args } = payload;
        if (type4 !== "exposedFun" || !this._pageBindings.has(name2)) {
          return;
        }
        let expression = null;
        try {
          const result2 = await this._pageBindings.get(name2)(...args);
          expression = helper.pageBindingDeliverResultString(name2, seq3, result2);
        } catch (error2) {
          if (error2 instanceof Error) {
            expression = helper.pageBindingDeliverErrorString(
              name2,
              seq3,
              error2.message,
              error2.stack
            );
          } else {
            expression = helper.pageBindingDeliverErrorValueString(
              name2,
              seq3,
              error2
            );
          }
        }
        this._client.send("Runtime.evaluate", {
          expression,
          contextId: event.executionContextId
        }).catch(debugError);
      }
      _addConsoleMessage(type4, args, stackTrace) {
        if (!this.listenerCount(
          "console"
          /* Console */
        )) {
          args.forEach((arg) => arg.dispose());
          return;
        }
        const textTokens = [];
        for (const arg of args) {
          const remoteObject = arg._remoteObject;
          if (remoteObject.objectId) {
            textTokens.push(arg.toString());
          } else {
            textTokens.push(helper.valueFromRemoteObject(remoteObject));
          }
        }
        const stackTraceLocations = [];
        if (stackTrace) {
          for (const callFrame of stackTrace.callFrames) {
            stackTraceLocations.push({
              url: callFrame.url,
              lineNumber: callFrame.lineNumber,
              columnNumber: callFrame.columnNumber
            });
          }
        }
        const message = new ConsoleMessage(
          type4,
          textTokens.join(" "),
          args,
          stackTraceLocations
        );
        this.emit(
          "console",
          /* Console */
          message
        );
      }
      _onDialog(event) {
        let dialogType = null;
        const validDialogTypes = /* @__PURE__ */ new Set([
          "alert",
          "confirm",
          "prompt",
          "beforeunload"
        ]);
        if (validDialogTypes.has(event.type)) {
          dialogType = event.type;
        }
        assert3(dialogType, "Unknown javascript dialog type: " + event.type);
        const dialog = new Dialog(
          this._client,
          dialogType,
          event.message,
          event.defaultPrompt
        );
        this.emit(
          "dialog",
          /* Dialog */
          dialog
        );
      }
      /**
         * Resets default white background
         */
      async _resetDefaultBackgroundColor() {
        await this._client.send("Emulation.setDefaultBackgroundColorOverride");
      }
      /**
         * Hides default white background
         */
      async _setTransparentBackgroundColor() {
        await this._client.send("Emulation.setDefaultBackgroundColorOverride", {
          color: { r: 0, g: 0, b: 0, a: 0 }
        });
      }
      url() {
        return this.mainFrame().url();
      }
      async content() {
        return await this._frameManager.mainFrame().content();
      }
      async setContent(html, options = {}) {
        await this._frameManager.mainFrame().setContent(html, options);
      }
      async goto(url, options = {}) {
        return await this._frameManager.mainFrame().goto(url, options);
      }
      async reload(options) {
        const result2 = await Promise.all([
          this.waitForNavigation(options),
          this._client.send("Page.reload")
        ]);
        return result2[0];
      }
      async waitForNavigation(options = {}) {
        return await this._frameManager.mainFrame().waitForNavigation(options);
      }
      _sessionClosePromise() {
        if (!this._disconnectPromise) {
          this._disconnectPromise = new Promise(
            (fulfill) => this._client.once(
              CDPSessionEmittedEvents.Disconnected,
              () => fulfill(new Error("Target closed"))
            )
          );
        }
        return this._disconnectPromise;
      }
      async waitForRequest(urlOrPredicate, options = {}) {
        const { timeout = this._timeoutSettings.timeout() } = options;
        return helper.waitForEvent(
          this._frameManager.networkManager(),
          NetworkManagerEmittedEvents.Request,
          (request2) => {
            if (helper.isString(urlOrPredicate)) {
              return urlOrPredicate === request2.url();
            }
            if (typeof urlOrPredicate === "function") {
              return !!urlOrPredicate(request2);
            }
            return false;
          },
          timeout,
          this._sessionClosePromise()
        );
      }
      async waitForResponse(urlOrPredicate, options = {}) {
        const { timeout = this._timeoutSettings.timeout() } = options;
        return helper.waitForEvent(
          this._frameManager.networkManager(),
          NetworkManagerEmittedEvents.Response,
          async (response) => {
            if (helper.isString(urlOrPredicate)) {
              return urlOrPredicate === response.url();
            }
            if (typeof urlOrPredicate === "function") {
              return !!await urlOrPredicate(response);
            }
            return false;
          },
          timeout,
          this._sessionClosePromise()
        );
      }
      async goBack(options = {}) {
        return this._go(-1, options);
      }
      async goForward(options = {}) {
        return this._go(1, options);
      }
      async _go(delta, options) {
        const history = await this._client.send("Page.getNavigationHistory");
        const entry = history.entries[history.currentIndex + delta];
        if (!entry) {
          return null;
        }
        const result2 = await Promise.all([
          this.waitForNavigation(options),
          this._client.send("Page.navigateToHistoryEntry", { entryId: entry.id })
        ]);
        return result2[0];
      }
      async bringToFront() {
        await this._client.send("Page.bringToFront");
      }
      async emulate(options) {
        await Promise.all([
          this.setViewport(options.viewport),
          this.setUserAgent(options.userAgent)
        ]);
      }
      async setJavaScriptEnabled(enabled5) {
        if (this._javascriptEnabled === enabled5) {
          return;
        }
        this._javascriptEnabled = enabled5;
        await this._client.send("Emulation.setScriptExecutionDisabled", {
          value: !enabled5
        });
      }
      async setBypassCSP(enabled5) {
        await this._client.send("Page.setBypassCSP", { enabled: enabled5 });
      }
      async emulateMediaType(type4) {
        assert3(
          type4 === "screen" || type4 === "print" || type4 === null,
          "Unsupported media type: " + type4
        );
        await this._client.send("Emulation.setEmulatedMedia", {
          media: type4 || ""
        });
      }
      async emulateMediaFeatures(features2) {
        if (features2 === null) {
          await this._client.send("Emulation.setEmulatedMedia", { features: null });
        }
        if (Array.isArray(features2)) {
          features2.every((mediaFeature) => {
            const name2 = mediaFeature.name;
            assert3(
              /^(?:prefers-(?:color-scheme|reduced-motion)|color-gamut)$/.test(
                name2
              ),
              "Unsupported media feature: " + name2
            );
            return true;
          });
          await this._client.send("Emulation.setEmulatedMedia", {
            features: features2
          });
        }
      }
      async emulateTimezone(timezoneId) {
        try {
          await this._client.send("Emulation.setTimezoneOverride", {
            timezoneId: timezoneId || ""
          });
        } catch (error2) {
          if (error2.message.includes("Invalid timezone")) {
            throw new Error(`Invalid timezone ID: ${timezoneId}`);
          }
          throw error2;
        }
      }
      /**
         * Emulates the idle state.
         * If no arguments set, clears idle state emulation.
         *
         * @example
         * ```js
         * // set idle emulation
         * await page.emulateIdleState({isUserActive: true, isScreenUnlocked: false});
         *
         * // do some checks here
         * ...
         *
         * // clear idle emulation
         * await page.emulateIdleState();
         * ```
         *
         * @param overrides - Mock idle state. If not set, clears idle overrides
         * @param isUserActive - Mock isUserActive
         * @param isScreenUnlocked - Mock isScreenUnlocked
         */
      async emulateIdleState(overrides) {
        if (overrides) {
          await this._client.send("Emulation.setIdleOverride", {
            isUserActive: overrides.isUserActive,
            isScreenUnlocked: overrides.isScreenUnlocked
          });
        } else {
          await this._client.send("Emulation.clearIdleOverride");
        }
      }
      /**
         * Simulates the given vision deficiency on the page.
         *
         * @example
         * ```js
         * const puppeteer = require('puppeteer');
         *
         * (async () => {
         *   const browser = await puppeteer.launch();
         *   const page = await browser.newPage();
         *   await page.goto('https://v8.dev/blog/10-years');
         *
         *   await page.emulateVisionDeficiency('achromatopsia');
         *   await page.screenshot({ path: 'achromatopsia.png' });
         *
         *   await page.emulateVisionDeficiency('deuteranopia');
         *   await page.screenshot({ path: 'deuteranopia.png' });
         *
         *   await page.emulateVisionDeficiency('blurredVision');
         *   await page.screenshot({ path: 'blurred-vision.png' });
         *
         *   await browser.close();
         * })();
         * ```
         *
         * @param type - the type of deficiency to simulate, or `'none'` to reset.
         */
      async emulateVisionDeficiency(type4) {
        const visionDeficiencies = /* @__PURE__ */ new Set([
          "none",
          "achromatopsia",
          "blurredVision",
          "deuteranopia",
          "protanopia",
          "tritanopia"
        ]);
        try {
          assert3(
            !type4 || visionDeficiencies.has(type4),
            `Unsupported vision deficiency: ${type4}`
          );
          await this._client.send("Emulation.setEmulatedVisionDeficiency", {
            type: type4 || "none"
          });
        } catch (error2) {
          throw error2;
        }
      }
      async setViewport(viewport) {
        const needsReload = await this._emulationManager.emulateViewport(viewport);
        this._viewport = viewport;
        if (needsReload) {
          await this.reload();
        }
      }
      viewport() {
        return this._viewport;
      }
      /**
         * @remarks
         *
         * Evaluates a function in the page's context and returns the result.
         *
         * If the function passed to `page.evaluteHandle` returns a Promise, the
         * function will wait for the promise to resolve and return its value.
         *
         * @example
         *
         * ```js
         * const result = await frame.evaluate(() => {
         *   return Promise.resolve(8 * 7);
         * });
         * console.log(result); // prints "56"
         * ```
         *
         * You can pass a string instead of a function (although functions are
         * recommended as they are easier to debug and use with TypeScript):
         *
         * @example
         * ```
         * const aHandle = await page.evaluate('1 + 2');
         * ```
         *
         * To get the best TypeScript experience, you should pass in as the
         * generic the type of `pageFunction`:
         *
         * ```
         * const aHandle = await page.evaluate<() => number>(() => 2);
         * ```
         *
         * @example
         *
         * {@link ElementHandle} instances (including {@link JSHandle}s) can be passed
         * as arguments to the `pageFunction`:
         *
         * ```
         * const bodyHandle = await page.$('body');
         * const html = await page.evaluate(body => body.innerHTML, bodyHandle);
         * await bodyHandle.dispose();
         * ```
         *
         * @param pageFunction - a function that is run within the page
         * @param args - arguments to be passed to the pageFunction
         *
         * @returns the return value of `pageFunction`.
         */
      async evaluate(pageFunction, ...args) {
        return this._frameManager.mainFrame().evaluate(pageFunction, ...args);
      }
      async evaluateOnNewDocument(pageFunction, ...args) {
        const source2 = helper.evaluationString(pageFunction, ...args);
        await this._client.send("Page.addScriptToEvaluateOnNewDocument", {
          source: source2
        });
      }
      async setCacheEnabled(enabled5 = true) {
        await this._frameManager.networkManager().setCacheEnabled(enabled5);
      }
      async screenshot(options = {}) {
        let screenshotType = null;
        if (options.type) {
          assert3(
            options.type === "png" || options.type === "jpeg",
            "Unknown options.type value: " + options.type
          );
          screenshotType = options.type;
        } else if (options.path) {
          const filePath = options.path;
          const extension = filePath.slice(filePath.lastIndexOf(".") + 1).toLowerCase();
          if (extension === "png") {
            screenshotType = "png";
          } else if (extension === "jpg" || extension === "jpeg") {
            screenshotType = "jpeg";
          }
          assert3(
            screenshotType,
            `Unsupported screenshot type for extension \`.${extension}\``
          );
        }
        if (!screenshotType) {
          screenshotType = "png";
        }
        if (options.quality) {
          assert3(
            screenshotType === "jpeg",
            "options.quality is unsupported for the " + screenshotType + " screenshots"
          );
          assert3(
            typeof options.quality === "number",
            "Expected options.quality to be a number but found " + typeof options.quality
          );
          assert3(
            Number.isInteger(options.quality),
            "Expected options.quality to be an integer"
          );
          assert3(
            options.quality >= 0 && options.quality <= 100,
            "Expected options.quality to be between 0 and 100 (inclusive), got " + options.quality
          );
        }
        assert3(
          !options.clip || !options.fullPage,
          "options.clip and options.fullPage are exclusive"
        );
        if (options.clip) {
          assert3(
            typeof options.clip.x === "number",
            "Expected options.clip.x to be a number but found " + typeof options.clip.x
          );
          assert3(
            typeof options.clip.y === "number",
            "Expected options.clip.y to be a number but found " + typeof options.clip.y
          );
          assert3(
            typeof options.clip.width === "number",
            "Expected options.clip.width to be a number but found " + typeof options.clip.width
          );
          assert3(
            typeof options.clip.height === "number",
            "Expected options.clip.height to be a number but found " + typeof options.clip.height
          );
          assert3(
            options.clip.width !== 0,
            "Expected options.clip.width not to be 0."
          );
          assert3(
            options.clip.height !== 0,
            "Expected options.clip.height not to be 0."
          );
        }
        return this._screenshotTaskQueue.postTask(
          () => this._screenshotTask(screenshotType, options)
        );
      }
      async _screenshotTask(format14, options) {
        await this._client.send("Target.activateTarget", {
          targetId: this._target._targetId
        });
        let clip = options.clip ? processClip(options.clip) : void 0;
        let { captureBeyondViewport = true } = options;
        captureBeyondViewport = typeof captureBeyondViewport === "boolean" ? captureBeyondViewport : true;
        if (options.fullPage) {
          const metrics = await this._client.send("Page.getLayoutMetrics");
          const width = Math.ceil(metrics.contentSize.width);
          const height = Math.ceil(metrics.contentSize.height);
          clip = { x: 0, y: 0, width, height, scale: 1 };
          if (!captureBeyondViewport) {
            const { isMobile = false, deviceScaleFactor = 1, isLandscape = false } = this._viewport || {};
            const screenOrientation = isLandscape ? { angle: 90, type: "landscapePrimary" } : { angle: 0, type: "portraitPrimary" };
            await this._client.send("Emulation.setDeviceMetricsOverride", {
              mobile: isMobile,
              width,
              height,
              deviceScaleFactor,
              screenOrientation
            });
          }
        }
        const shouldSetDefaultBackground = options.omitBackground && format14 === "png";
        if (shouldSetDefaultBackground) {
          await this._setTransparentBackgroundColor();
        }
        const result2 = await this._client.send("Page.captureScreenshot", {
          format: format14,
          quality: options.quality,
          clip,
          captureBeyondViewport
        });
        if (shouldSetDefaultBackground) {
          await this._resetDefaultBackgroundColor();
        }
        if (options.fullPage && this._viewport) {
          await this.setViewport(this._viewport);
        }
        const data3 = options.encoding === "base64" ? result2.data : decode2(result2.data);
        if (options.path) {
          await Deno.writeFile(options.path, decode2(result2.data));
        }
        return data3;
        function processClip(clip2) {
          const x3 = Math.round(clip2.x);
          const y4 = Math.round(clip2.y);
          const width = Math.round(clip2.width + clip2.x - x3);
          const height = Math.round(clip2.height + clip2.y - y4);
          return { x: x3, y: y4, width, height, scale: 1 };
        }
      }
      /**
         * Generatees a PDF of the page with the `print` CSS media type.
         * @remarks
         *
         * IMPORTANT: PDF generation is only supported in Chrome headless mode.
         *
         * To generate a PDF with the `screen` media type, call
         * {@link Page.emulateMediaType | `page.emulateMediaType('screen')`} before
         * calling `page.pdf()`.
         *
         * By default, `page.pdf()` generates a pdf with modified colors for printing.
         * Use the
         * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/-webkit-print-color-adjust | `-webkit-print-color-adjust`}
         * property to force rendering of exact colors.
         *
         *
         * @param options - options for generating the PDF.
         */
      async pdf(options = {}) {
        const {
          scale = 1,
          displayHeaderFooter = false,
          headerTemplate = "",
          footerTemplate = "",
          printBackground = false,
          landscape = false,
          pageRanges = "",
          preferCSSPageSize = false,
          margin = {},
          path: path3 = null,
          omitBackground = false
        } = options;
        let paperWidth = 8.5;
        let paperHeight = 11;
        if (options.format) {
          const format14 = paperFormats[options.format.toLowerCase()];
          assert3(format14, "Unknown paper format: " + options.format);
          paperWidth = format14.width;
          paperHeight = format14.height;
        } else {
          paperWidth = convertPrintParameterToInches(options.width) || paperWidth;
          paperHeight = convertPrintParameterToInches(options.height) || paperHeight;
        }
        const marginTop = convertPrintParameterToInches(margin.top) || 0;
        const marginLeft = convertPrintParameterToInches(margin.left) || 0;
        const marginBottom = convertPrintParameterToInches(margin.bottom) || 0;
        const marginRight = convertPrintParameterToInches(margin.right) || 0;
        if (omitBackground) {
          await this._setTransparentBackgroundColor();
        }
        const result2 = await this._client.send("Page.printToPDF", {
          transferMode: "ReturnAsStream",
          landscape,
          displayHeaderFooter,
          headerTemplate,
          footerTemplate,
          printBackground,
          scale,
          paperWidth,
          paperHeight,
          marginTop,
          marginBottom,
          marginLeft,
          marginRight,
          pageRanges,
          preferCSSPageSize
        });
        if (omitBackground) {
          await this._resetDefaultBackgroundColor();
        }
        return await helper.readProtocolStream(this._client, result2.stream, path3);
      }
      async title() {
        return this.mainFrame().title();
      }
      async close(options = { runBeforeUnload: void 0 }) {
        assert3(
          !!this._client._connection,
          "Protocol error: Connection closed. Most likely the page has been closed."
        );
        const runBeforeUnload = !!options.runBeforeUnload;
        if (runBeforeUnload) {
          await this._client.send("Page.close");
        } else {
          await this._client._connection.send("Target.closeTarget", {
            targetId: this._target._targetId
          });
          await this._target._isClosedPromise;
        }
      }
      isClosed() {
        return this._closed;
      }
      get mouse() {
        return this._mouse;
      }
      click(selector, options = {}) {
        return this.mainFrame().click(selector, options);
      }
      focus(selector) {
        return this.mainFrame().focus(selector);
      }
      hover(selector) {
        return this.mainFrame().hover(selector);
      }
      select(selector, ...values) {
        return this.mainFrame().select(selector, ...values);
      }
      tap(selector) {
        return this.mainFrame().tap(selector);
      }
      type(selector, text, options) {
        return this.mainFrame().type(selector, text, options);
      }
      /**
         * @remarks
         *
         * This method behaves differently depending on the first parameter. If it's a
         * `string`, it will be treated as a `selector` or `xpath` (if the string
         * starts with `//`). This method then is a shortcut for
         * {@link Page.waitForSelector} or {@link Page.waitForXPath}.
         *
         * If the first argument is a function this method is a shortcut for
         * {@link Page.waitForFunction}.
         *
         * If the first argument is a `number`, it's treated as a timeout in
         * milliseconds and the method returns a promise which resolves after the
         * timeout.
         *
         * @param selectorOrFunctionOrTimeout - a selector, predicate or timeout to
         * wait for.
         * @param options - optional waiting parameters.
         * @param args - arguments to pass to `pageFunction`.
         *
         * @deprecated Don't use this method directly. Instead use the more explicit
         * methods available: {@link Page.waitForSelector},
         * {@link Page.waitForXPath}, {@link Page.waitForFunction} or
         * {@link Page.waitForTimeout}.
         */
      waitFor(selectorOrFunctionOrTimeout, options = {}, ...args) {
        return this.mainFrame().waitFor(
          selectorOrFunctionOrTimeout,
          options,
          ...args
        );
      }
      /**
         * Causes your script to wait for the given number of milliseconds.
         *
         * @remarks
         *
         * It's generally recommended to not wait for a number of seconds, but instead
         * use {@link Page.waitForSelector}, {@link Page.waitForXPath} or
         * {@link Page.waitForFunction} to wait for exactly the conditions you want.
         *
         * @example
         *
         * Wait for 1 second:
         *
         * ```
         * await page.waitForTimeout(1000);
         * ```
         *
         * @param milliseconds - the number of milliseconds to wait.
         */
      waitForTimeout(milliseconds) {
        return this.mainFrame().waitForTimeout(milliseconds);
      }
      waitForSelector(selector, options = {}) {
        return this.mainFrame().waitForSelector(selector, options);
      }
      waitForXPath(xpath, options = {}) {
        return this.mainFrame().waitForXPath(xpath, options);
      }
      waitForFunction(pageFunction, options = {}, ...args) {
        return this.mainFrame().waitForFunction(pageFunction, options, ...args);
      }
    };
    supportedMetrics = /* @__PURE__ */ new Set([
      "Timestamp",
      "Documents",
      "Frames",
      "JSEventListeners",
      "Nodes",
      "LayoutCount",
      "RecalcStyleCount",
      "LayoutDuration",
      "RecalcStyleDuration",
      "ScriptDuration",
      "TaskDuration",
      "JSHeapUsedSize",
      "JSHeapTotalSize"
    ]);
    unitToPixels = {
      px: 1,
      in: 96,
      cm: 37.8,
      mm: 3.78
    };
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/Target.js
var Target;
var init_Target = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/Target.js"() {
    init_Page();
    init_WebWorker();
    Target = class {
      /**
         * @internal
         */
      constructor(targetInfo, browserContext, sessionFactory, ignoreHTTPSErrors, defaultViewport) {
        this._targetInfo = targetInfo;
        this._browserContext = browserContext;
        this._targetId = targetInfo.targetId;
        this._sessionFactory = sessionFactory;
        this._ignoreHTTPSErrors = ignoreHTTPSErrors;
        this._defaultViewport = defaultViewport;
        this._pagePromise = null;
        this._workerPromise = null;
        this._initializedPromise = new Promise((fulfill) => this._initializedCallback = fulfill).then(async (success) => {
          if (!success) {
            return false;
          }
          const opener = this.opener();
          if (!opener || !opener._pagePromise || this.type() !== "page") {
            return true;
          }
          const openerPage = await opener._pagePromise;
          if (!openerPage.listenerCount(
            "popup"
            /* Popup */
          )) {
            return true;
          }
          const popupPage = await this.page();
          openerPage.emit(
            "popup",
            /* Popup */
            popupPage
          );
          return true;
        });
        this._isClosedPromise = new Promise((fulfill) => this._closedCallback = fulfill);
        this._isInitialized = this._targetInfo.type !== "page" || this._targetInfo.url !== "";
        if (this._isInitialized) {
          this._initializedCallback(true);
        }
      }
      /**
         * Creates a Chrome Devtools Protocol session attached to the target.
         */
      createCDPSession() {
        return this._sessionFactory();
      }
      /**
         * If the target is not of type `"page"` or `"background_page"`, returns `null`.
         */
      async page() {
        if ((this._targetInfo.type === "page" || this._targetInfo.type === "background_page" || this._targetInfo.type === "webview") && !this._pagePromise) {
          this._pagePromise = this._sessionFactory().then(
            (client) => Page.create(
              client,
              this,
              this._ignoreHTTPSErrors,
              this._defaultViewport
            )
          );
        }
        return this._pagePromise;
      }
      /**
         * If the target is not of type `"service_worker"` or `"shared_worker"`, returns `null`.
         */
      async worker() {
        if (this._targetInfo.type !== "service_worker" && this._targetInfo.type !== "shared_worker") {
          return null;
        }
        if (!this._workerPromise) {
          this._workerPromise = this._sessionFactory().then(
            (client) => new WebWorker(
              client,
              this._targetInfo.url,
              () => {
              },
              /* consoleAPICalled */
              () => {
              }
              /* exceptionThrown */
            )
          );
        }
        return this._workerPromise;
      }
      url() {
        return this._targetInfo.url;
      }
      /**
         * Identifies what kind of target this is.
         *
         * @remarks
         *
         * See {@link https://developer.chrome.com/extensions/background_pages | docs} for more info about background pages.
         */
      type() {
        const type4 = this._targetInfo.type;
        if (type4 === "page" || type4 === "background_page" || type4 === "service_worker" || type4 === "shared_worker" || type4 === "browser" || type4 === "webview") {
          return type4;
        }
        return "other";
      }
      /**
         * Get the browser the target belongs to.
         */
      browser() {
        return this._browserContext.browser();
      }
      browserContext() {
        return this._browserContext;
      }
      /**
         * Get the target that opened this target. Top-level targets return `null`.
         */
      opener() {
        const { openerId } = this._targetInfo;
        if (!openerId) {
          return null;
        }
        return this.browser()._targets.get(openerId);
      }
      /**
         * @internal
         */
      _targetInfoChanged(targetInfo) {
        this._targetInfo = targetInfo;
        if (!this._isInitialized && (this._targetInfo.type !== "page" || this._targetInfo.url !== "")) {
          this._isInitialized = true;
          this._initializedCallback(true);
          return;
        }
      }
    };
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/Browser.js
var WEB_PERMISSION_TO_PROTOCOL_PERMISSION, Browser, BrowserContext;
var init_Browser = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/Browser.js"() {
    init_assert2();
    init_helper();
    init_Target();
    init_EventEmitter();
    init_Connection();
    WEB_PERMISSION_TO_PROTOCOL_PERMISSION = /* @__PURE__ */ new Map([
      ["geolocation", "geolocation"],
      ["midi", "midi"],
      ["notifications", "notifications"],
      // TODO: push isn't a valid type?
      // ['push', 'push'],
      ["camera", "videoCapture"],
      ["microphone", "audioCapture"],
      ["background-sync", "backgroundSync"],
      ["ambient-light-sensor", "sensors"],
      ["accelerometer", "sensors"],
      ["gyroscope", "sensors"],
      ["magnetometer", "sensors"],
      ["accessibility-events", "accessibilityEvents"],
      ["clipboard-read", "clipboardReadWrite"],
      ["clipboard-write", "clipboardReadWrite"],
      ["payment-handler", "paymentHandler"],
      ["idle-detection", "idleDetection"],
      // chrome-specific permissions we have.
      ["midi-sysex", "midiSysex"]
    ]);
    Browser = class _Browser extends EventEmitter2 {
      /**
         * @internal
         */
      constructor(connection, contextIds, ignoreHTTPSErrors, defaultViewport, process4, closeCallback) {
        super();
        this._ignoreHTTPSErrors = ignoreHTTPSErrors;
        this._defaultViewport = defaultViewport;
        this._process = process4;
        this._connection = connection;
        this._closeCallback = closeCallback || function() {
        };
        this._defaultContext = new BrowserContext(this._connection, this, null);
        this._contexts = /* @__PURE__ */ new Map();
        for (const contextId of contextIds) {
          this._contexts.set(
            contextId,
            new BrowserContext(this._connection, this, contextId)
          );
        }
        this._targets = /* @__PURE__ */ new Map();
        this._connection.on(
          ConnectionEmittedEvents.Disconnected,
          () => this.emit(
            "disconnected"
            /* Disconnected */
          )
        );
        this._connection.on("Target.targetCreated", this._targetCreated.bind(this));
        this._connection.on(
          "Target.targetDestroyed",
          this._targetDestroyed.bind(this)
        );
        this._connection.on(
          "Target.targetInfoChanged",
          this._targetInfoChanged.bind(this)
        );
      }
      /**
         * @internal
         */
      static async create(connection, contextIds, ignoreHTTPSErrors, defaultViewport, process4, closeCallback) {
        const browser2 = new _Browser(
          connection,
          contextIds,
          ignoreHTTPSErrors,
          defaultViewport,
          process4,
          closeCallback
        );
        await connection.send("Target.setDiscoverTargets", { discover: true });
        return browser2;
      }
      /**
         * The spawned browser process. Returns `null` if the browser instance was created with
         * {@link Puppeteer.connect}.
         */
      process() {
        return this._process;
      }
      /**
         * Creates a new incognito browser context. This won't share cookies/cache with other
         * browser contexts.
         *
         * @example
         * ```js
         * (async () => {
         *  const browser = await puppeteer.launch();
         *   // Create a new incognito browser context.
         *   const context = await browser.createIncognitoBrowserContext();
         *   // Create a new page in a pristine context.
         *   const page = await context.newPage();
         *   // Do stuff
         *   await page.goto('https://example.com');
         * })();
         * ```
         */
      async createIncognitoBrowserContext() {
        const { browserContextId } = await this._connection.send(
          "Target.createBrowserContext"
        );
        const context = new BrowserContext(
          this._connection,
          this,
          browserContextId
        );
        this._contexts.set(browserContextId, context);
        return context;
      }
      /**
         * Returns an array of all open browser contexts. In a newly created browser, this will
         * return a single instance of {@link BrowserContext}.
         */
      browserContexts() {
        return [this._defaultContext, ...Array.from(this._contexts.values())];
      }
      /**
         * Returns the default browser context. The default browser context cannot be closed.
         */
      defaultBrowserContext() {
        return this._defaultContext;
      }
      /**
         * @internal
         * Used by BrowserContext directly so cannot be marked private.
         */
      async _disposeContext(contextId) {
        await this._connection.send("Target.disposeBrowserContext", {
          browserContextId: contextId || void 0
        });
        this._contexts.delete(contextId);
      }
      async _targetCreated(event) {
        const targetInfo = event.targetInfo;
        const { browserContextId } = targetInfo;
        const context = browserContextId && this._contexts.has(browserContextId) ? this._contexts.get(browserContextId) : this._defaultContext;
        const target = new Target(
          targetInfo,
          context,
          () => this._connection.createSession(targetInfo),
          this._ignoreHTTPSErrors,
          this._defaultViewport
        );
        assert3(
          !this._targets.has(event.targetInfo.targetId),
          "Target should not exist before targetCreated"
        );
        this._targets.set(event.targetInfo.targetId, target);
        if (await target._initializedPromise) {
          this.emit(
            "targetcreated",
            /* TargetCreated */
            target
          );
          context.emit(
            "targetcreated",
            /* TargetCreated */
            target
          );
        }
      }
      async _targetDestroyed(event) {
        const target = this._targets.get(event.targetId);
        target._initializedCallback(false);
        this._targets.delete(event.targetId);
        target._closedCallback();
        if (await target._initializedPromise) {
          this.emit(
            "targetdestroyed",
            /* TargetDestroyed */
            target
          );
          target.browserContext().emit(
            "targetdestroyed",
            /* TargetDestroyed */
            target
          );
        }
      }
      _targetInfoChanged(event) {
        const target = this._targets.get(event.targetInfo.targetId);
        assert3(target, "target should exist before targetInfoChanged");
        const previousURL = target.url();
        const wasInitialized = target._isInitialized;
        target._targetInfoChanged(event.targetInfo);
        if (wasInitialized && previousURL !== target.url()) {
          this.emit(
            "targetchanged",
            /* TargetChanged */
            target
          );
          target.browserContext().emit(
            "targetchanged",
            /* TargetChanged */
            target
          );
        }
      }
      /**
         * The browser websocket endpoint which can be used as an argument to
         * {@link Puppeteer.connect}.
         *
         * @returns The Browser websocket url.
         *
         * @remarks
         *
         * The format is `ws://${host}:${port}/devtools/browser/<id>`.
         *
         * You can find the `webSocketDebuggerUrl` from `http://${host}:${port}/json/version`.
         * Learn more about the
         * {@link https://chromedevtools.github.io/devtools-protocol | devtools protocol} and
         * the {@link
         * https://chromedevtools.github.io/devtools-protocol/#how-do-i-access-the-browser-target
         * | browser endpoint}.
         */
      wsEndpoint() {
        return this._connection.url();
      }
      /**
         * Creates a {@link Page} in the default browser context.
         */
      async newPage() {
        return this._defaultContext.newPage();
      }
      /**
         * @internal
         * Used by BrowserContext directly so cannot be marked private.
         */
      async _createPageInContext(contextId) {
        const { targetId } = await this._connection.send("Target.createTarget", {
          url: "about:blank",
          browserContextId: contextId || void 0
        });
        const target = await this._targets.get(targetId);
        assert3(
          await target._initializedPromise,
          "Failed to create target for page"
        );
        const page = await target.page();
        return page;
      }
      /**
         * All active targets inside the Browser. In case of multiple browser contexts, returns
         * an array with all the targets in all browser contexts.
         */
      targets() {
        return Array.from(this._targets.values()).filter(
          (target) => target._isInitialized
        );
      }
      /**
         * The target associated with the browser.
         */
      target() {
        return this.targets().find((target) => target.type() === "browser");
      }
      /**
         * Searches for a target in all browser contexts.
         *
         * @param predicate - A function to be run for every target.
         * @returns The first target found that matches the `predicate` function.
         *
         * @example
         *
         * An example of finding a target for a page opened via `window.open`:
         * ```js
         * await page.evaluate(() => window.open('https://www.example.com/'));
         * const newWindowTarget = await browser.waitForTarget(target => target.url() === 'https://www.example.com/');
         * ```
         */
      async waitForTarget(predicate, options = {}) {
        const { timeout = 3e4 } = options;
        const existingTarget = this.targets().find(predicate);
        if (existingTarget) {
          return existingTarget;
        }
        let resolve16;
        const targetPromise = new Promise((x3) => resolve16 = x3);
        this.on(
          "targetcreated",
          /* TargetCreated */
          check2
        );
        this.on(
          "targetchanged",
          /* TargetChanged */
          check2
        );
        try {
          if (!timeout) {
            return await targetPromise;
          }
          return await helper.waitWithTimeout(targetPromise, "target", timeout);
        } finally {
          this.removeListener(
            "targetcreated",
            /* TargetCreated */
            check2
          );
          this.removeListener(
            "targetchanged",
            /* TargetChanged */
            check2
          );
        }
        function check2(target) {
          if (predicate(target)) {
            resolve16(target);
          }
        }
      }
      /**
         * An array of all open pages inside the Browser.
         *
         * @remarks
         *
         * In case of multiple browser contexts, returns an array with all the pages in all
         * browser contexts. Non-visible pages, such as `"background_page"`, will not be listed
         * here. You can find them using {@link Target.page}.
         */
      async pages() {
        const contextPages = await Promise.all(
          this.browserContexts().map((context) => context.pages())
        );
        return contextPages.reduce((acc, x3) => acc.concat(x3), []);
      }
      /**
         * A string representing the browser name and version.
         *
         * @remarks
         *
         * For headless Chromium, this is similar to `HeadlessChrome/61.0.3153.0`. For
         * non-headless, this is similar to `Chrome/61.0.3153.0`.
         *
         * The format of browser.version() might change with future releases of Chromium.
         */
      async version() {
        const version4 = await this._getVersion();
        return version4.product;
      }
      /**
         * The browser's original user agent. Pages can override the browser user agent with
         * {@link Page.setUserAgent}.
         */
      async userAgent() {
        const version4 = await this._getVersion();
        return version4.userAgent;
      }
      /**
         * Closes Chromium and all of its pages (if any were opened). The {@link Browser} object
         * itself is considered to be disposed and cannot be used anymore.
         */
      async close() {
        await this._closeCallback.call(null);
        await this.disconnect();
      }
      /**
         * Disconnects Puppeteer from the browser, but leaves the Chromium process running.
         * After calling `disconnect`, the {@link Browser} object is considered disposed and
         * cannot be used anymore.
         */
      async disconnect() {
        await this._connection.dispose();
      }
      /**
         * Indicates that the browser is connected.
         */
      isConnected() {
        return !this._connection._closed;
      }
      _getVersion() {
        return this._connection.send("Browser.getVersion");
      }
    };
    BrowserContext = class extends EventEmitter2 {
      /**
         * @internal
         */
      constructor(connection, browser2, contextId) {
        super();
        this._connection = connection;
        this._browser = browser2;
        this._id = contextId;
      }
      /**
         * An array of all active targets inside the browser context.
         */
      targets() {
        return this._browser.targets().filter((target) => target.browserContext() === this);
      }
      /**
         * This searches for a target in this specific browser context.
         *
         * @example
         * An example of finding a target for a page opened via `window.open`:
         * ```js
         * await page.evaluate(() => window.open('https://www.example.com/'));
         * const newWindowTarget = await browserContext.waitForTarget(target => target.url() === 'https://www.example.com/');
         * ```
         *
         * @param predicate - A function to be run for every target
         * @param options - An object of options. Accepts a timout,
         * which is the maximum wait time in milliseconds.
         * Pass `0` to disable the timeout. Defaults to 30 seconds.
         * @returns Promise which resolves to the first target found
         * that matches the `predicate` function.
         */
      waitForTarget(predicate, options = {}) {
        return this._browser.waitForTarget(
          (target) => target.browserContext() === this && predicate(target),
          options
        );
      }
      /**
         * An array of all pages inside the browser context.
         *
         * @returns Promise which resolves to an array of all open pages.
         * Non visible pages, such as `"background_page"`, will not be listed here.
         * You can find them using {@link Target.page | the target page}.
         */
      async pages() {
        const pages2 = await Promise.all(
          this.targets().filter((target) => target.type() === "page").map((target) => target.page())
        );
        return pages2.filter((page) => !!page);
      }
      /**
         * Returns whether BrowserContext is incognito.
         * The default browser context is the only non-incognito browser context.
         *
         * @remarks
         * The default browser context cannot be closed.
         */
      isIncognito() {
        return !!this._id;
      }
      /**
         * @example
         * ```js
         * const context = browser.defaultBrowserContext();
         * await context.overridePermissions('https://html5demos.com', ['geolocation']);
         * ```
         *
         * @param origin - The origin to grant permissions to, e.g. "https://example.com".
         * @param permissions - An array of permissions to grant.
         * All permissions that are not listed here will be automatically denied.
         */
      async overridePermissions(origin, permissions) {
        const protocolPermissions = permissions.map((permission) => {
          const protocolPermission = WEB_PERMISSION_TO_PROTOCOL_PERMISSION.get(
            permission
          );
          if (!protocolPermission) {
            throw new Error("Unknown permission: " + permission);
          }
          return protocolPermission;
        });
        await this._connection.send("Browser.grantPermissions", {
          origin,
          browserContextId: this._id || void 0,
          permissions: protocolPermissions
        });
      }
      /**
         * Clears all permission overrides for the browser context.
         *
         * @example
         * ```js
         * const context = browser.defaultBrowserContext();
         * context.overridePermissions('https://example.com', ['clipboard-read']);
         * // do stuff ..
         * context.clearPermissionOverrides();
         * ```
         */
      async clearPermissionOverrides() {
        await this._connection.send("Browser.resetPermissions", {
          browserContextId: this._id || void 0
        });
      }
      /**
         * Creates a new page in the browser context.
         */
      newPage() {
        return this._browser._createPageInContext(this._id);
      }
      /**
         * The browser this browser context belongs to.
         */
      browser() {
        return this._browser;
      }
      /**
         * Closes the browser context. All the targets that belong to the browser context
         * will be closed.
         *
         * @remarks
         * Only incognito browser contexts can be closed.
         */
      async close() {
        assert3(this._id, "Non-incognito profiles cannot be closed!");
        await this._browser._disposeContext(this._id);
      }
    };
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/fetch.js
var getFetch;
var init_fetch = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/fetch.js"() {
    getFetch = async () => {
      return globalThis.fetch;
    };
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/BrowserWebSocketTransport.js
var BrowserWebSocketTransport;
var init_BrowserWebSocketTransport = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/BrowserWebSocketTransport.js"() {
    BrowserWebSocketTransport = class _BrowserWebSocketTransport {
      constructor(ws) {
        this._ws = ws;
        this._ws.addEventListener("message", (event) => {
          if (this.onmessage) {
            this.onmessage.call(null, event.data);
          }
        });
        this._ws.addEventListener("close", () => {
          this._closed = true;
          if (this.onclose) {
            this.onclose.call(null);
          }
        });
        this._ws.addEventListener("error", () => {
        });
        this._closed = false;
        this.onmessage = null;
        this.onclose = null;
      }
      static create(url) {
        return new Promise((resolve16, reject2) => {
          const ws = new WebSocket(url);
          ws.addEventListener(
            "open",
            () => resolve16(new _BrowserWebSocketTransport(ws))
          );
          ws.addEventListener("error", reject2);
        });
      }
      send(message) {
        this._ws.send(message);
      }
      close() {
        return new Promise((resolve16, reject2) => {
          this._ws.addEventListener("close", () => resolve16());
          this._ws.addEventListener("error", (err2) => reject2(err2));
          this._ws.close();
          if (this._closed) resolve16();
        });
      }
    };
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/BrowserConnector.js
async function getWSEndpoint(browserURL) {
  const endpointURL = new URL("/json/version", browserURL);
  const fetch3 = await getFetch();
  try {
    const result2 = await fetch3(endpointURL.toString(), {
      method: "GET"
    });
    if (!result2.ok) {
      throw new Error(`HTTP ${result2.statusText}`);
    }
    const data3 = await result2.json();
    return data3.webSocketDebuggerUrl;
  } catch (error2) {
    error2.message = `Failed to fetch browser webSocket URL from ${endpointURL}: ` + error2.message;
    throw error2;
  }
}
var getWebSocketTransportClass, connectToBrowser;
var init_BrowserConnector = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/BrowserConnector.js"() {
    init_Browser();
    init_assert2();
    init_helper();
    init_Connection();
    init_fetch();
    init_BrowserWebSocketTransport();
    getWebSocketTransportClass = () => {
      return Promise.resolve(BrowserWebSocketTransport);
    };
    connectToBrowser = async (options) => {
      const {
        browserWSEndpoint,
        browserURL,
        ignoreHTTPSErrors = false,
        defaultViewport = { width: 800, height: 600 },
        transport,
        slowMo = 0
      } = options;
      assert3(
        Number(!!browserWSEndpoint) + Number(!!browserURL) + Number(!!transport) === 1,
        "Exactly one of browserWSEndpoint, browserURL or transport must be passed to puppeteer.connect"
      );
      let connection = null;
      if (transport) {
        connection = new Connection("", transport, slowMo);
      } else if (browserWSEndpoint) {
        const WebSocketClass = await getWebSocketTransportClass();
        const connectionTransport = await WebSocketClass.create(browserWSEndpoint);
        connection = new Connection(browserWSEndpoint, connectionTransport, slowMo);
      } else if (browserURL) {
        const connectionURL = await getWSEndpoint(browserURL);
        const WebSocketClass = await getWebSocketTransportClass();
        const connectionTransport = await WebSocketClass.create(connectionURL);
        connection = new Connection(connectionURL, connectionTransport, slowMo);
      }
      const { browserContextIds } = await connection.send(
        "Target.getBrowserContexts"
      );
      return Browser.create(
        connection,
        browserContextIds,
        ignoreHTTPSErrors,
        defaultViewport,
        null,
        () => connection.send("Browser.close").catch(debugError)
      );
    };
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/NetworkConditions.js
var networkConditions;
var init_NetworkConditions = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/NetworkConditions.js"() {
    networkConditions = {
      "Slow 3G": {
        download: 500 * 1e3 / 8 * 0.8,
        upload: 500 * 1e3 / 8 * 0.8,
        latency: 400 * 5
      },
      "Fast 3G": {
        download: 1.6 * 1e3 * 1e3 / 8 * 0.9,
        upload: 750 * 1e3 / 8 * 0.9,
        latency: 150 * 3.75
      }
    };
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/Puppeteer.js
var Puppeteer;
var init_Puppeteer = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/Puppeteer.js"() {
    init_Errors();
    init_DeviceDescriptors();
    init_QueryHandler();
    init_BrowserConnector();
    init_NetworkConditions();
    Puppeteer = class {
      /**
         * @internal
         */
      constructor() {
        this._changedProduct = false;
      }
      /**
         * This method attaches Puppeteer to an existing browser instance.
         *
         * @remarks
         *
         * @param options - Set of configurable options to set on the browser.
         * @returns Promise which resolves to browser instance.
         */
      connect(options) {
        return connectToBrowser(options);
      }
      /**
         * @remarks
         * A list of devices to be used with `page.emulate(options)`. Actual list of devices can be found in {@link https://github.com/puppeteer/puppeteer/blob/main/src/common/DeviceDescriptors.ts | src/common/DeviceDescriptors.ts}.
         *
         * @example
         *
         * ```js
         * const puppeteer = require('puppeteer');
         * const iPhone = puppeteer.devices['iPhone 6'];
         *
         * (async () => {
         *   const browser = await puppeteer.launch();
         *   const page = await browser.newPage();
         *   await page.emulate(iPhone);
         *   await page.goto('https://www.google.com');
         *   // other actions...
         *   await browser.close();
         * })();
         * ```
         *
         */
      get devices() {
        return devicesMap;
      }
      /**
         * @remarks
         *
         * Puppeteer methods might throw errors if they are unable to fulfill a request.
         * For example, `page.waitForSelector(selector[, options])` might fail if
         * the selector doesn't match any nodes during the given timeframe.
         *
         * For certain types of errors Puppeteer uses specific error classes.
         * These classes are available via `puppeteer.errors`.
         *
         * @example
         * An example of handling a timeout error:
         * ```js
         * try {
         *   await page.waitForSelector('.foo');
         * } catch (e) {
         *   if (e instanceof puppeteer.errors.TimeoutError) {
         *     // Do something if this is a timeout.
         *   }
         * }
         * ```
         */
      get errors() {
        return puppeteerErrors;
      }
      /**
         * @remarks
         * Returns a list of network conditions to be used with `page.emulateNetworkConditions(networkConditions)`. Actual list of predefined conditions can be found in {@link https://github.com/puppeteer/puppeteer/blob/main/src/common/NetworkConditions.ts | src/common/NetworkConditions.ts}.
         *
         * @example
         *
         * ```js
         * const puppeteer = require('puppeteer');
         * const slow3G = puppeteer.networkConditions['Slow 3G'];
         *
         * (async () => {
         *   const browser = await puppeteer.launch();
         *   const page = await browser.newPage();
         *   await page.emulateNetworkConditions(slow3G);
         *   await page.goto('https://www.google.com');
         *   // other actions...
         *   await browser.close();
         * })();
         * ```
         *
         */
      get networkConditions() {
        return networkConditions;
      }
      /**
         * Registers a {@link CustomQueryHandler | custom query handler}. After
         * registration, the handler can be used everywhere where a selector is
         * expected by prepending the selection string with `<name>/`. The name is
         * only allowed to consist of lower- and upper case latin letters.
         * @example
         * ```
         * puppeteer.registerCustomQueryHandler('text', { … });
         * const aHandle = await page.$('text/…');
         * ```
         * @param name - The name that the custom query handler will be registered under.
         * @param queryHandler - The {@link CustomQueryHandler | custom query handler} to
         * register.
         */
      registerCustomQueryHandler(name2, queryHandler) {
        registerCustomQueryHandler(name2, queryHandler);
      }
      /**
         * @param name - The name of the query handler to unregistered.
         */
      unregisterCustomQueryHandler(name2) {
        unregisterCustomQueryHandler(name2);
      }
      /**
         * @returns a list with the names of all registered custom query handlers.
         */
      customQueryHandlerNames() {
        return customQueryHandlerNames();
      }
      /**
         * Clears all registered handlers.
         */
      clearCustomQueryHandlers() {
        clearCustomQueryHandlers();
      }
    };
  }
});

// https://dev.jspm.io/npm:@jspm/core@2.0.1/_/8ddf35de.js
function o() {
  o.init.call(this);
}
function u(e5) {
  if ("function" != typeof e5) throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof e5);
}
function f(e5) {
  return void 0 === e5._maxListeners ? o.defaultMaxListeners : e5._maxListeners;
}
function v(e5, t5, n5, r5) {
  var i6, o5, s5, v4;
  if (u(n5), void 0 === (o5 = e5._events) ? (o5 = e5._events = /* @__PURE__ */ Object.create(null), e5._eventsCount = 0) : (void 0 !== o5.newListener && (e5.emit("newListener", t5, n5.listener ? n5.listener : n5), o5 = e5._events), s5 = o5[t5]), void 0 === s5) s5 = o5[t5] = n5, ++e5._eventsCount;
  else if ("function" == typeof s5 ? s5 = o5[t5] = r5 ? [n5, s5] : [s5, n5] : r5 ? s5.unshift(n5) : s5.push(n5), (i6 = f(e5)) > 0 && s5.length > i6 && !s5.warned) {
    s5.warned = true;
    var a5 = new Error("Possible EventEmitter memory leak detected. " + s5.length + " " + String(t5) + " listeners added. Use emitter.setMaxListeners() to increase limit");
    a5.name = "MaxListenersExceededWarning", a5.emitter = e5, a5.type = t5, a5.count = s5.length, v4 = a5, console && console.warn && console.warn(v4);
  }
  return e5;
}
function a() {
  if (!this.fired) return this.target.removeListener(this.type, this.wrapFn), this.fired = true, 0 === arguments.length ? this.listener.call(this.target) : this.listener.apply(this.target, arguments);
}
function l2(e5, t5, n5) {
  var r5 = { fired: false, wrapFn: void 0, target: e5, type: t5, listener: n5 }, i6 = a.bind(r5);
  return i6.listener = n5, r5.wrapFn = i6, i6;
}
function h(e5, t5, n5) {
  var r5 = e5._events;
  if (void 0 === r5) return [];
  var i6 = r5[t5];
  return void 0 === i6 ? [] : "function" == typeof i6 ? n5 ? [i6.listener || i6] : [i6] : n5 ? (function(e6) {
    for (var t6 = new Array(e6.length), n6 = 0; n6 < t6.length; ++n6) t6[n6] = e6[n6].listener || e6[n6];
    return t6;
  })(i6) : c(i6, i6.length);
}
function p(e5) {
  var t5 = this._events;
  if (void 0 !== t5) {
    var n5 = t5[e5];
    if ("function" == typeof n5) return 1;
    if (void 0 !== n5) return n5.length;
  }
  return 0;
}
function c(e5, t5) {
  for (var n5 = new Array(t5), r5 = 0; r5 < t5; ++r5) n5[r5] = e5[r5];
  return n5;
}
var e, t, n, r, i2, s, y;
var init_ddf35de = __esm({
  "https://dev.jspm.io/npm:@jspm/core@2.0.1/_/8ddf35de.js"() {
    n = "object" == typeof Reflect ? Reflect : null;
    r = n && "function" == typeof n.apply ? n.apply : function(e5, t5, n5) {
      return Function.prototype.apply.call(e5, t5, n5);
    };
    t = n && "function" == typeof n.ownKeys ? n.ownKeys : Object.getOwnPropertySymbols ? function(e5) {
      return Object.getOwnPropertyNames(e5).concat(Object.getOwnPropertySymbols(e5));
    } : function(e5) {
      return Object.getOwnPropertyNames(e5);
    };
    i2 = Number.isNaN || function(e5) {
      return e5 != e5;
    };
    e = o, o.EventEmitter = o, o.prototype._events = void 0, o.prototype._eventsCount = 0, o.prototype._maxListeners = void 0;
    s = 10;
    Object.defineProperty(o, "defaultMaxListeners", { enumerable: true, get: function() {
      return s;
    }, set: function(e5) {
      if ("number" != typeof e5 || e5 < 0 || i2(e5)) throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + e5 + ".");
      s = e5;
    } }), o.init = function() {
      void 0 !== this._events && this._events !== Object.getPrototypeOf(this)._events || (this._events = /* @__PURE__ */ Object.create(null), this._eventsCount = 0), this._maxListeners = this._maxListeners || void 0;
    }, o.prototype.setMaxListeners = function(e5) {
      if ("number" != typeof e5 || e5 < 0 || i2(e5)) throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + e5 + ".");
      return this._maxListeners = e5, this;
    }, o.prototype.getMaxListeners = function() {
      return f(this);
    }, o.prototype.emit = function(e5) {
      for (var t5 = [], n5 = 1; n5 < arguments.length; n5++) t5.push(arguments[n5]);
      var i6 = "error" === e5, o5 = this._events;
      if (void 0 !== o5) i6 = i6 && void 0 === o5.error;
      else if (!i6) return false;
      if (i6) {
        var s5;
        if (t5.length > 0 && (s5 = t5[0]), s5 instanceof Error) throw s5;
        var u5 = new Error("Unhandled error." + (s5 ? " (" + s5.message + ")" : ""));
        throw u5.context = s5, u5;
      }
      var f5 = o5[e5];
      if (void 0 === f5) return false;
      if ("function" == typeof f5) r(f5, this, t5);
      else {
        var v4 = f5.length, a5 = c(f5, v4);
        for (n5 = 0; n5 < v4; ++n5) r(a5[n5], this, t5);
      }
      return true;
    }, o.prototype.addListener = function(e5, t5) {
      return v(this, e5, t5, false);
    }, o.prototype.on = o.prototype.addListener, o.prototype.prependListener = function(e5, t5) {
      return v(this, e5, t5, true);
    }, o.prototype.once = function(e5, t5) {
      return u(t5), this.on(e5, l2(this, e5, t5)), this;
    }, o.prototype.prependOnceListener = function(e5, t5) {
      return u(t5), this.prependListener(e5, l2(this, e5, t5)), this;
    }, o.prototype.removeListener = function(e5, t5) {
      var n5, r5, i6, o5, s5;
      if (u(t5), void 0 === (r5 = this._events)) return this;
      if (void 0 === (n5 = r5[e5])) return this;
      if (n5 === t5 || n5.listener === t5) 0 == --this._eventsCount ? this._events = /* @__PURE__ */ Object.create(null) : (delete r5[e5], r5.removeListener && this.emit("removeListener", e5, n5.listener || t5));
      else if ("function" != typeof n5) {
        for (i6 = -1, o5 = n5.length - 1; o5 >= 0; o5--) if (n5[o5] === t5 || n5[o5].listener === t5) {
          s5 = n5[o5].listener, i6 = o5;
          break;
        }
        if (i6 < 0) return this;
        0 === i6 ? n5.shift() : !(function(e6, t6) {
          for (; t6 + 1 < e6.length; t6++) e6[t6] = e6[t6 + 1];
          e6.pop();
        })(n5, i6), 1 === n5.length && (r5[e5] = n5[0]), void 0 !== r5.removeListener && this.emit("removeListener", e5, s5 || t5);
      }
      return this;
    }, o.prototype.off = o.prototype.removeListener, o.prototype.removeAllListeners = function(e5) {
      var t5, n5, r5;
      if (void 0 === (n5 = this._events)) return this;
      if (void 0 === n5.removeListener) return 0 === arguments.length ? (this._events = /* @__PURE__ */ Object.create(null), this._eventsCount = 0) : void 0 !== n5[e5] && (0 == --this._eventsCount ? this._events = /* @__PURE__ */ Object.create(null) : delete n5[e5]), this;
      if (0 === arguments.length) {
        var i6, o5 = Object.keys(n5);
        for (r5 = 0; r5 < o5.length; ++r5) "removeListener" !== (i6 = o5[r5]) && this.removeAllListeners(i6);
        return this.removeAllListeners("removeListener"), this._events = /* @__PURE__ */ Object.create(null), this._eventsCount = 0, this;
      }
      if ("function" == typeof (t5 = n5[e5])) this.removeListener(e5, t5);
      else if (void 0 !== t5) for (r5 = t5.length - 1; r5 >= 0; r5--) this.removeListener(e5, t5[r5]);
      return this;
    }, o.prototype.listeners = function(e5) {
      return h(this, e5, true);
    }, o.prototype.rawListeners = function(e5) {
      return h(this, e5, false);
    }, o.listenerCount = function(e5, t5) {
      return "function" == typeof e5.listenerCount ? e5.listenerCount(t5) : p.call(e5, t5);
    }, o.prototype.listenerCount = p, o.prototype.eventNames = function() {
      return this._eventsCount > 0 ? t(this._events) : [];
    };
    y = e;
    y.EventEmitter;
    y.defaultMaxListeners;
    y.init;
    y.listenerCount;
    y.EventEmitter;
    y.defaultMaxListeners;
    y.init;
    y.listenerCount;
  }
});

// https://dev.jspm.io/npm:@jspm/core@2.0.1/nodelibs/events
var EventEmitter3, defaultMaxListeners, init2, listenerCount, on, once;
var init_events = __esm({
  "https://dev.jspm.io/npm:@jspm/core@2.0.1/nodelibs/events"() {
    init_ddf35de();
    init_ddf35de();
    y.once = function(emitter, event) {
      return new Promise((resolve16, reject2) => {
        function eventListener(...args) {
          if (errorListener !== void 0) {
            emitter.removeListener("error", errorListener);
          }
          resolve16(args);
        }
        let errorListener;
        if (event !== "error") {
          errorListener = (err2) => {
            emitter.removeListener(name, eventListener);
            reject2(err2);
          };
          emitter.once("error", errorListener);
        }
        emitter.once(event, eventListener);
      });
    };
    y.on = function(emitter, event) {
      const unconsumedEventValues = [];
      const unconsumedPromises = [];
      let error2 = null;
      let finished2 = false;
      const iterator = {
        async next() {
          const value = unconsumedEventValues.shift();
          if (value) {
            return createIterResult(value, false);
          }
          if (error2) {
            const p5 = Promise.reject(error2);
            error2 = null;
            return p5;
          }
          if (finished2) {
            return createIterResult(void 0, true);
          }
          return new Promise((resolve16, reject2) => unconsumedPromises.push({ resolve: resolve16, reject: reject2 }));
        },
        async return() {
          emitter.removeListener(event, eventHandler);
          emitter.removeListener("error", errorHandler);
          finished2 = true;
          for (const promise of unconsumedPromises) {
            promise.resolve(createIterResult(void 0, true));
          }
          return createIterResult(void 0, true);
        },
        throw(err2) {
          error2 = err2;
          emitter.removeListener(event, eventHandler);
          emitter.removeListener("error", errorHandler);
        },
        [Symbol.asyncIterator]() {
          return this;
        }
      };
      emitter.on(event, eventHandler);
      emitter.on("error", errorHandler);
      return iterator;
      function eventHandler(...args) {
        const promise = unconsumedPromises.shift();
        if (promise) {
          promise.resolve(createIterResult(args, false));
        } else {
          unconsumedEventValues.push(args);
        }
      }
      function errorHandler(err2) {
        finished2 = true;
        const toError = unconsumedPromises.shift();
        if (toError) {
          toError.reject(err2);
        } else {
          error2 = err2;
        }
        iterator.return();
      }
    };
    ({
      EventEmitter: EventEmitter3,
      defaultMaxListeners,
      init: init2,
      listenerCount,
      on,
      once
    } = y);
  }
});

// https://dev.jspm.io/npm:@jspm/core@2.0.1/_/633ae550.js
function i3() {
  throw new Error("setTimeout has not been defined");
}
function u2() {
  throw new Error("clearTimeout has not been defined");
}
function c2(e5) {
  if (t2 === setTimeout) return setTimeout(e5, 0);
  if ((t2 === i3 || !t2) && setTimeout) return t2 = setTimeout, setTimeout(e5, 0);
  try {
    return t2(e5, 0);
  } catch (n5) {
    try {
      return t2.call(null, e5, 0);
    } catch (n6) {
      return t2.call(this || r2, e5, 0);
    }
  }
}
function h2() {
  f2 && l3 && (f2 = false, l3.length ? s2 = l3.concat(s2) : a2 = -1, s2.length && d());
}
function d() {
  if (!f2) {
    var e5 = c2(h2);
    f2 = true;
    for (var t5 = s2.length; t5; ) {
      for (l3 = s2, s2 = []; ++a2 < t5; ) l3 && l3[a2].run();
      a2 = -1, t5 = s2.length;
    }
    l3 = null, f2 = false, (function(e6) {
      if (n2 === clearTimeout) return clearTimeout(e6);
      if ((n2 === u2 || !n2) && clearTimeout) return n2 = clearTimeout, clearTimeout(e6);
      try {
        n2(e6);
      } catch (t6) {
        try {
          return n2.call(null, e6);
        } catch (t7) {
          return n2.call(this || r2, e6);
        }
      }
    })(e5);
  }
}
function m(e5, t5) {
  (this || r2).fun = e5, (this || r2).array = t5;
}
function p2() {
}
var e2, t2, n2, r2, o2, l3, s2, f2, a2, T;
var init_ae550 = __esm({
  "https://dev.jspm.io/npm:@jspm/core@2.0.1/_/633ae550.js"() {
    r2 = "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : global;
    o2 = e2 = {};
    !(function() {
      try {
        t2 = "function" == typeof setTimeout ? setTimeout : i3;
      } catch (e5) {
        t2 = i3;
      }
      try {
        n2 = "function" == typeof clearTimeout ? clearTimeout : u2;
      } catch (e5) {
        n2 = u2;
      }
    })();
    s2 = [];
    f2 = false;
    a2 = -1;
    o2.nextTick = function(e5) {
      var t5 = new Array(arguments.length - 1);
      if (arguments.length > 1) for (var n5 = 1; n5 < arguments.length; n5++) t5[n5 - 1] = arguments[n5];
      s2.push(new m(e5, t5)), 1 !== s2.length || f2 || c2(d);
    }, m.prototype.run = function() {
      (this || r2).fun.apply(null, (this || r2).array);
    }, o2.title = "browser", o2.browser = true, o2.env = {}, o2.argv = [], o2.version = "", o2.versions = {}, o2.on = p2, o2.addListener = p2, o2.once = p2, o2.off = p2, o2.removeListener = p2, o2.removeAllListeners = p2, o2.emit = p2, o2.prependListener = p2, o2.prependOnceListener = p2, o2.listeners = function(e5) {
      return [];
    }, o2.binding = function(e5) {
      throw new Error("process.binding is not supported");
    }, o2.cwd = function() {
      return "/";
    }, o2.chdir = function(e5) {
      throw new Error("process.chdir is not supported");
    }, o2.umask = function() {
      return 0;
    };
    T = e2;
    T.addListener;
    T.argv;
    T.binding;
    T.browser;
    T.chdir;
    T.cwd;
    T.emit;
    T.env;
    T.listeners;
    T.nextTick;
    T.off;
    T.on;
    T.once;
    T.prependListener;
    T.prependOnceListener;
    T.removeAllListeners;
    T.removeListener;
    T.title;
    T.umask;
    T.version;
    T.versions;
  }
});

// https://dev.jspm.io/npm:@jspm/core@2.0.1/_/57403c48.js
function c$1(e5) {
  return e5.call.bind(e5);
}
function O(e5, t5) {
  if ("object" != typeof e5) return false;
  try {
    return t5(e5), true;
  } catch (e6) {
    return false;
  }
}
function S(e5) {
  return l$1 && y2 ? void 0 !== b(e5) : B(e5) || k(e5) || E(e5) || D(e5) || U(e5) || P(e5) || x(e5) || I(e5) || M(e5) || z(e5) || F2(e5);
}
function B(e5) {
  return l$1 && y2 ? "Uint8Array" === b(e5) : "[object Uint8Array]" === m2(e5) || u$1(e5) && void 0 !== e5.buffer;
}
function k(e5) {
  return l$1 && y2 ? "Uint8ClampedArray" === b(e5) : "[object Uint8ClampedArray]" === m2(e5);
}
function E(e5) {
  return l$1 && y2 ? "Uint16Array" === b(e5) : "[object Uint16Array]" === m2(e5);
}
function D(e5) {
  return l$1 && y2 ? "Uint32Array" === b(e5) : "[object Uint32Array]" === m2(e5);
}
function U(e5) {
  return l$1 && y2 ? "Int8Array" === b(e5) : "[object Int8Array]" === m2(e5);
}
function P(e5) {
  return l$1 && y2 ? "Int16Array" === b(e5) : "[object Int16Array]" === m2(e5);
}
function x(e5) {
  return l$1 && y2 ? "Int32Array" === b(e5) : "[object Int32Array]" === m2(e5);
}
function I(e5) {
  return l$1 && y2 ? "Float32Array" === b(e5) : "[object Float32Array]" === m2(e5);
}
function M(e5) {
  return l$1 && y2 ? "Float64Array" === b(e5) : "[object Float64Array]" === m2(e5);
}
function z(e5) {
  return l$1 && y2 ? "BigInt64Array" === b(e5) : "[object BigInt64Array]" === m2(e5);
}
function F2(e5) {
  return l$1 && y2 ? "BigUint64Array" === b(e5) : "[object BigUint64Array]" === m2(e5);
}
function T2(e5) {
  return "[object Map]" === m2(e5);
}
function N(e5) {
  return "[object Set]" === m2(e5);
}
function W(e5) {
  return "[object WeakMap]" === m2(e5);
}
function $(e5) {
  return "[object WeakSet]" === m2(e5);
}
function C(e5) {
  return "[object ArrayBuffer]" === m2(e5);
}
function V(e5) {
  return "undefined" != typeof ArrayBuffer && (C.working ? C(e5) : e5 instanceof ArrayBuffer);
}
function G(e5) {
  return "[object DataView]" === m2(e5);
}
function R2(e5) {
  return "undefined" != typeof DataView && (G.working ? G(e5) : e5 instanceof DataView);
}
function J(e5) {
  return "[object SharedArrayBuffer]" === m2(e5);
}
function _(e5) {
  return "undefined" != typeof SharedArrayBuffer && (J.working ? J(e5) : e5 instanceof SharedArrayBuffer);
}
function H(e5) {
  return O(e5, h3);
}
function Z(e5) {
  return O(e5, j);
}
function q(e5) {
  return O(e5, A);
}
function K(e5) {
  return s3 && O(e5, w);
}
function L(e5) {
  return p3 && O(e5, v2);
}
function oe(e5, t5) {
  var r5 = { seen: [], stylize: fe };
  return arguments.length >= 3 && (r5.depth = arguments[2]), arguments.length >= 4 && (r5.colors = arguments[3]), ye(t5) ? r5.showHidden = t5 : t5 && X._extend(r5, t5), be(r5.showHidden) && (r5.showHidden = false), be(r5.depth) && (r5.depth = 2), be(r5.colors) && (r5.colors = false), be(r5.customInspect) && (r5.customInspect = true), r5.colors && (r5.stylize = ue), ae(r5, e5, r5.depth);
}
function ue(e5, t5) {
  var r5 = oe.styles[t5];
  return r5 ? "\x1B[" + oe.colors[r5][0] + "m" + e5 + "\x1B[" + oe.colors[r5][1] + "m" : e5;
}
function fe(e5, t5) {
  return e5;
}
function ae(e5, t5, r5) {
  if (e5.customInspect && t5 && we(t5.inspect) && t5.inspect !== X.inspect && (!t5.constructor || t5.constructor.prototype !== t5)) {
    var n5 = t5.inspect(r5, e5);
    return ge(n5) || (n5 = ae(e5, n5, r5)), n5;
  }
  var i6 = (function(e6, t6) {
    if (be(t6)) return e6.stylize("undefined", "undefined");
    if (ge(t6)) {
      var r6 = "'" + JSON.stringify(t6).replace(/^"|"$/g, "").replace(/'/g, "\\'").replace(/\\"/g, '"') + "'";
      return e6.stylize(r6, "string");
    }
    if (de(t6)) return e6.stylize("" + t6, "number");
    if (ye(t6)) return e6.stylize("" + t6, "boolean");
    if (le(t6)) return e6.stylize("null", "null");
  })(e5, t5);
  if (i6) return i6;
  var o5 = Object.keys(t5), u5 = (function(e6) {
    var t6 = {};
    return e6.forEach((function(e7, r6) {
      t6[e7] = true;
    })), t6;
  })(o5);
  if (e5.showHidden && (o5 = Object.getOwnPropertyNames(t5)), Ae(t5) && (o5.indexOf("message") >= 0 || o5.indexOf("description") >= 0)) return ce(t5);
  if (0 === o5.length) {
    if (we(t5)) {
      var f5 = t5.name ? ": " + t5.name : "";
      return e5.stylize("[Function" + f5 + "]", "special");
    }
    if (me(t5)) return e5.stylize(RegExp.prototype.toString.call(t5), "regexp");
    if (je(t5)) return e5.stylize(Date.prototype.toString.call(t5), "date");
    if (Ae(t5)) return ce(t5);
  }
  var a5, c6 = "", s5 = false, p5 = ["{", "}"];
  (pe(t5) && (s5 = true, p5 = ["[", "]"]), we(t5)) && (c6 = " [Function" + (t5.name ? ": " + t5.name : "") + "]");
  return me(t5) && (c6 = " " + RegExp.prototype.toString.call(t5)), je(t5) && (c6 = " " + Date.prototype.toUTCString.call(t5)), Ae(t5) && (c6 = " " + ce(t5)), 0 !== o5.length || s5 && 0 != t5.length ? r5 < 0 ? me(t5) ? e5.stylize(RegExp.prototype.toString.call(t5), "regexp") : e5.stylize("[Object]", "special") : (e5.seen.push(t5), a5 = s5 ? (function(e6, t6, r6, n6, i7) {
    for (var o6 = [], u6 = 0, f6 = t6.length; u6 < f6; ++u6) ke(t6, String(u6)) ? o6.push(se(e6, t6, r6, n6, String(u6), true)) : o6.push("");
    return i7.forEach((function(i8) {
      i8.match(/^\d+$/) || o6.push(se(e6, t6, r6, n6, i8, true));
    })), o6;
  })(e5, t5, r5, u5, o5) : o5.map((function(n6) {
    return se(e5, t5, r5, u5, n6, s5);
  })), e5.seen.pop(), (function(e6, t6, r6) {
    var n6 = 0;
    if (e6.reduce((function(e7, t7) {
      return n6++, t7.indexOf("\n") >= 0 && n6++, e7 + t7.replace(/\u001b\[\d\d?m/g, "").length + 1;
    }), 0) > 60) return r6[0] + ("" === t6 ? "" : t6 + "\n ") + " " + e6.join(",\n  ") + " " + r6[1];
    return r6[0] + t6 + " " + e6.join(", ") + " " + r6[1];
  })(a5, c6, p5)) : p5[0] + c6 + p5[1];
}
function ce(e5) {
  return "[" + Error.prototype.toString.call(e5) + "]";
}
function se(e5, t5, r5, n5, i6, o5) {
  var u5, f5, a5;
  if ((a5 = Object.getOwnPropertyDescriptor(t5, i6) || { value: t5[i6] }).get ? f5 = a5.set ? e5.stylize("[Getter/Setter]", "special") : e5.stylize("[Getter]", "special") : a5.set && (f5 = e5.stylize("[Setter]", "special")), ke(n5, i6) || (u5 = "[" + i6 + "]"), f5 || (e5.seen.indexOf(a5.value) < 0 ? (f5 = le(r5) ? ae(e5, a5.value, null) : ae(e5, a5.value, r5 - 1)).indexOf("\n") > -1 && (f5 = o5 ? f5.split("\n").map((function(e6) {
    return "  " + e6;
  })).join("\n").substr(2) : "\n" + f5.split("\n").map((function(e6) {
    return "   " + e6;
  })).join("\n")) : f5 = e5.stylize("[Circular]", "special")), be(u5)) {
    if (o5 && i6.match(/^\d+$/)) return f5;
    (u5 = JSON.stringify("" + i6)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/) ? (u5 = u5.substr(1, u5.length - 2), u5 = e5.stylize(u5, "name")) : (u5 = u5.replace(/'/g, "\\'").replace(/\\"/g, '"').replace(/(^"|"$)/g, "'"), u5 = e5.stylize(u5, "string"));
  }
  return u5 + ": " + f5;
}
function pe(e5) {
  return Array.isArray(e5);
}
function ye(e5) {
  return "boolean" == typeof e5;
}
function le(e5) {
  return null === e5;
}
function de(e5) {
  return "number" == typeof e5;
}
function ge(e5) {
  return "string" == typeof e5;
}
function be(e5) {
  return void 0 === e5;
}
function me(e5) {
  return he(e5) && "[object RegExp]" === ve(e5);
}
function he(e5) {
  return "object" == typeof e5 && null !== e5;
}
function je(e5) {
  return he(e5) && "[object Date]" === ve(e5);
}
function Ae(e5) {
  return he(e5) && ("[object Error]" === ve(e5) || e5 instanceof Error);
}
function we(e5) {
  return "function" == typeof e5;
}
function ve(e5) {
  return Object.prototype.toString.call(e5);
}
function Oe(e5) {
  return e5 < 10 ? "0" + e5.toString(10) : e5.toString(10);
}
function Be() {
  var e5 = /* @__PURE__ */ new Date(), t5 = [Oe(e5.getHours()), Oe(e5.getMinutes()), Oe(e5.getSeconds())].join(":");
  return [e5.getDate(), Se[e5.getMonth()], t5].join(" ");
}
function ke(e5, t5) {
  return Object.prototype.hasOwnProperty.call(e5, t5);
}
function De(e5, t5) {
  if (!e5) {
    var r5 = new Error("Promise was rejected with a falsy value");
    r5.reason = e5, e5 = r5;
  }
  return t5(e5);
}
var t3, e3, o3, n3, r3, l4, t$1, o$1, n$1, e$1, r$1, c3, u3, i4, t$2, i$1, o$2, u$1, f3, a3, s3, p3, y2, l$1, d2, g, b, m2, h3, j, A, w, v2, Q, X, Y, ee, te, re2, ne, ie, Se, Ee;
var init_c48 = __esm({
  "https://dev.jspm.io/npm:@jspm/core@2.0.1/_/57403c48.js"() {
    init_ae550();
    t3 = "function" == typeof Symbol && "symbol" == typeof Symbol.toStringTag;
    e3 = Object.prototype.toString;
    o3 = function(o5) {
      return !(t3 && o5 && "object" == typeof o5 && Symbol.toStringTag in o5) && "[object Arguments]" === e3.call(o5);
    };
    n3 = function(t5) {
      return !!o3(t5) || null !== t5 && "object" == typeof t5 && "number" == typeof t5.length && t5.length >= 0 && "[object Array]" !== e3.call(t5) && "[object Function]" === e3.call(t5.callee);
    };
    r3 = (function() {
      return o3(arguments);
    })();
    o3.isLegacyArguments = n3;
    l4 = r3 ? o3 : n3;
    t$1 = Object.prototype.toString;
    o$1 = Function.prototype.toString;
    n$1 = /^\s*(?:function)?\*/;
    e$1 = "function" == typeof Symbol && "symbol" == typeof Symbol.toStringTag;
    r$1 = Object.getPrototypeOf;
    c3 = (function() {
      if (!e$1) return false;
      try {
        return Function("return function*() {}")();
      } catch (t5) {
      }
    })();
    u3 = c3 ? r$1(c3) : {};
    i4 = function(c6) {
      return "function" == typeof c6 && (!!n$1.test(o$1.call(c6)) || (e$1 ? r$1(c6) === u3 : "[object GeneratorFunction]" === t$1.call(c6)));
    };
    t$2 = "function" == typeof Object.create ? function(t5, e5) {
      e5 && (t5.super_ = e5, t5.prototype = Object.create(e5.prototype, { constructor: { value: t5, enumerable: false, writable: true, configurable: true } }));
    } : function(t5, e5) {
      if (e5) {
        t5.super_ = e5;
        var o5 = function() {
        };
        o5.prototype = e5.prototype, t5.prototype = new o5(), t5.prototype.constructor = t5;
      }
    };
    i$1 = function(e5) {
      return e5 && "object" == typeof e5 && "function" == typeof e5.copy && "function" == typeof e5.fill && "function" == typeof e5.readUInt8;
    };
    o$2 = {};
    u$1 = i$1;
    f3 = l4;
    a3 = i4;
    s3 = "undefined" != typeof BigInt;
    p3 = "undefined" != typeof Symbol;
    y2 = p3 && void 0 !== Symbol.toStringTag;
    l$1 = "undefined" != typeof Uint8Array;
    d2 = "undefined" != typeof ArrayBuffer;
    if (l$1 && y2) g = Object.getPrototypeOf(Uint8Array.prototype), b = c$1(Object.getOwnPropertyDescriptor(g, Symbol.toStringTag).get);
    m2 = c$1(Object.prototype.toString);
    h3 = c$1(Number.prototype.valueOf);
    j = c$1(String.prototype.valueOf);
    A = c$1(Boolean.prototype.valueOf);
    if (s3) w = c$1(BigInt.prototype.valueOf);
    if (p3) v2 = c$1(Symbol.prototype.valueOf);
    o$2.isArgumentsObject = f3, o$2.isGeneratorFunction = a3, o$2.isPromise = function(e5) {
      return "undefined" != typeof Promise && e5 instanceof Promise || null !== e5 && "object" == typeof e5 && "function" == typeof e5.then && "function" == typeof e5.catch;
    }, o$2.isArrayBufferView = function(e5) {
      return d2 && ArrayBuffer.isView ? ArrayBuffer.isView(e5) : S(e5) || R2(e5);
    }, o$2.isTypedArray = S, o$2.isUint8Array = B, o$2.isUint8ClampedArray = k, o$2.isUint16Array = E, o$2.isUint32Array = D, o$2.isInt8Array = U, o$2.isInt16Array = P, o$2.isInt32Array = x, o$2.isFloat32Array = I, o$2.isFloat64Array = M, o$2.isBigInt64Array = z, o$2.isBigUint64Array = F2, T2.working = "undefined" != typeof Map && T2(/* @__PURE__ */ new Map()), o$2.isMap = function(e5) {
      return "undefined" != typeof Map && (T2.working ? T2(e5) : e5 instanceof Map);
    }, N.working = "undefined" != typeof Set && N(/* @__PURE__ */ new Set()), o$2.isSet = function(e5) {
      return "undefined" != typeof Set && (N.working ? N(e5) : e5 instanceof Set);
    }, W.working = "undefined" != typeof WeakMap && W(/* @__PURE__ */ new WeakMap()), o$2.isWeakMap = function(e5) {
      return "undefined" != typeof WeakMap && (W.working ? W(e5) : e5 instanceof WeakMap);
    }, $.working = "undefined" != typeof WeakSet && $(/* @__PURE__ */ new WeakSet()), o$2.isWeakSet = function(e5) {
      return $(e5);
    }, C.working = "undefined" != typeof ArrayBuffer && C(new ArrayBuffer()), o$2.isArrayBuffer = V, G.working = "undefined" != typeof ArrayBuffer && "undefined" != typeof DataView && G(new DataView(new ArrayBuffer(1), 0, 1)), o$2.isDataView = R2, J.working = "undefined" != typeof SharedArrayBuffer && J(new SharedArrayBuffer()), o$2.isSharedArrayBuffer = _, o$2.isAsyncFunction = function(e5) {
      return "[object AsyncFunction]" === m2(e5);
    }, o$2.isMapIterator = function(e5) {
      return "[object Map Iterator]" === m2(e5);
    }, o$2.isSetIterator = function(e5) {
      return "[object Set Iterator]" === m2(e5);
    }, o$2.isGeneratorObject = function(e5) {
      return "[object Generator]" === m2(e5);
    }, o$2.isWebAssemblyCompiledModule = function(e5) {
      return "[object WebAssembly.Module]" === m2(e5);
    }, o$2.isNumberObject = H, o$2.isStringObject = Z, o$2.isBooleanObject = q, o$2.isBigIntObject = K, o$2.isSymbolObject = L, o$2.isBoxedPrimitive = function(e5) {
      return H(e5) || Z(e5) || q(e5) || K(e5) || L(e5);
    }, o$2.isAnyArrayBuffer = function(e5) {
      return l$1 && (V(e5) || _(e5));
    }, ["isProxy", "isExternal", "isModuleNamespaceObject"].forEach((function(e5) {
      Object.defineProperty(o$2, e5, { enumerable: false, value: function() {
        throw new Error(e5 + " is not supported in userland");
      } });
    }));
    Q = "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : global;
    X = {};
    Y = T;
    ee = Object.getOwnPropertyDescriptors || function(e5) {
      for (var t5 = Object.keys(e5), r5 = {}, n5 = 0; n5 < t5.length; n5++) r5[t5[n5]] = Object.getOwnPropertyDescriptor(e5, t5[n5]);
      return r5;
    };
    te = /%[sdj%]/g;
    X.format = function(e5) {
      if (!ge(e5)) {
        for (var t5 = [], r5 = 0; r5 < arguments.length; r5++) t5.push(oe(arguments[r5]));
        return t5.join(" ");
      }
      r5 = 1;
      for (var n5 = arguments, i6 = n5.length, o5 = String(e5).replace(te, (function(e6) {
        if ("%%" === e6) return "%";
        if (r5 >= i6) return e6;
        switch (e6) {
          case "%s":
            return String(n5[r5++]);
          case "%d":
            return Number(n5[r5++]);
          case "%j":
            try {
              return JSON.stringify(n5[r5++]);
            } catch (e7) {
              return "[Circular]";
            }
          default:
            return e6;
        }
      })), u5 = n5[r5]; r5 < i6; u5 = n5[++r5]) le(u5) || !he(u5) ? o5 += " " + u5 : o5 += " " + oe(u5);
      return o5;
    }, X.deprecate = function(e5, t5) {
      if (void 0 !== Y && true === Y.noDeprecation) return e5;
      if (void 0 === Y) return function() {
        return X.deprecate(e5, t5).apply(this || Q, arguments);
      };
      var r5 = false;
      return function() {
        if (!r5) {
          if (Y.throwDeprecation) throw new Error(t5);
          Y.traceDeprecation ? console.trace(t5) : console.error(t5), r5 = true;
        }
        return e5.apply(this || Q, arguments);
      };
    };
    re2 = {};
    ne = /^$/;
    if (Y.env.NODE_DEBUG) {
      ie = Y.env.NODE_DEBUG;
      ie = ie.replace(/[|\\{}()[\]^$+?.]/g, "\\$&").replace(/\*/g, ".*").replace(/,/g, "$|^").toUpperCase(), ne = new RegExp("^" + ie + "$", "i");
    }
    X.debuglog = function(e5) {
      if (e5 = e5.toUpperCase(), !re2[e5]) if (ne.test(e5)) {
        var t5 = Y.pid;
        re2[e5] = function() {
          var r5 = X.format.apply(X, arguments);
          console.error("%s %d: %s", e5, t5, r5);
        };
      } else re2[e5] = function() {
      };
      return re2[e5];
    }, X.inspect = oe, oe.colors = { bold: [1, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], white: [37, 39], grey: [90, 39], black: [30, 39], blue: [34, 39], cyan: [36, 39], green: [32, 39], magenta: [35, 39], red: [31, 39], yellow: [33, 39] }, oe.styles = { special: "cyan", number: "yellow", boolean: "yellow", undefined: "grey", null: "bold", string: "green", date: "magenta", regexp: "red" }, X.types = o$2, X.isArray = pe, X.isBoolean = ye, X.isNull = le, X.isNullOrUndefined = function(e5) {
      return null == e5;
    }, X.isNumber = de, X.isString = ge, X.isSymbol = function(e5) {
      return "symbol" == typeof e5;
    }, X.isUndefined = be, X.isRegExp = me, X.types.isRegExp = me, X.isObject = he, X.isDate = je, X.types.isDate = je, X.isError = Ae, X.types.isNativeError = Ae, X.isFunction = we, X.isPrimitive = function(e5) {
      return null === e5 || "boolean" == typeof e5 || "number" == typeof e5 || "string" == typeof e5 || "symbol" == typeof e5 || void 0 === e5;
    }, X.isBuffer = i$1;
    Se = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    X.log = function() {
      console.log("%s - %s", Be(), X.format.apply(X, arguments));
    }, X.inherits = t$2, X._extend = function(e5, t5) {
      if (!t5 || !he(t5)) return e5;
      for (var r5 = Object.keys(t5), n5 = r5.length; n5--; ) e5[r5[n5]] = t5[r5[n5]];
      return e5;
    };
    Ee = "undefined" != typeof Symbol ? /* @__PURE__ */ Symbol("util.promisify.custom") : void 0;
    X.promisify = function(e5) {
      if ("function" != typeof e5) throw new TypeError('The "original" argument must be of type Function');
      if (Ee && e5[Ee]) {
        var t5;
        if ("function" != typeof (t5 = e5[Ee])) throw new TypeError('The "util.promisify.custom" argument must be of type Function');
        return Object.defineProperty(t5, Ee, { value: t5, enumerable: false, writable: false, configurable: true }), t5;
      }
      function t5() {
        for (var t6, r5, n5 = new Promise((function(e6, n6) {
          t6 = e6, r5 = n6;
        })), i6 = [], o5 = 0; o5 < arguments.length; o5++) i6.push(arguments[o5]);
        i6.push((function(e6, n6) {
          e6 ? r5(e6) : t6(n6);
        }));
        try {
          e5.apply(this || Q, i6);
        } catch (e6) {
          r5(e6);
        }
        return n5;
      }
      return Object.setPrototypeOf(t5, Object.getPrototypeOf(e5)), Ee && Object.defineProperty(t5, Ee, { value: t5, enumerable: false, writable: false, configurable: true }), Object.defineProperties(t5, ee(e5));
    }, X.promisify.custom = Ee, X.callbackify = function(e5) {
      if ("function" != typeof e5) throw new TypeError('The "original" argument must be of type Function');
      function t5() {
        for (var t6 = [], r5 = 0; r5 < arguments.length; r5++) t6.push(arguments[r5]);
        var n5 = t6.pop();
        if ("function" != typeof n5) throw new TypeError("The last argument must be of type Function");
        var i6 = this || Q, o5 = function() {
          return n5.apply(i6, arguments);
        };
        e5.apply(this || Q, t6).then((function(e6) {
          Y.nextTick(o5.bind(null, null, e6));
        }), (function(e6) {
          Y.nextTick(De.bind(null, e6, o5));
        }));
      }
      return Object.setPrototypeOf(t5, Object.getPrototypeOf(e5)), Object.defineProperties(t5, ee(e5)), t5;
    };
  }
});

// https://dev.jspm.io/npm:@jspm/core@2.0.1/_/a421dfba.js
var _extend, callbackify, debuglog, deprecate, format6, inherits, inspect2, isArray2, isBoolean3, isBuffer, isDate, isError, isFunction, isNull3, isNullOrUndefined, isNumber2, isObject5, isPrimitive, isRegExp, isString2, isSymbol, isUndefined, log, promisify, types2, TextEncoder2, TextDecoder2;
var init_a421dfba = __esm({
  "https://dev.jspm.io/npm:@jspm/core@2.0.1/_/a421dfba.js"() {
    init_c48();
    init_ae550();
    X._extend;
    X.callbackify;
    X.debuglog;
    X.deprecate;
    X.format;
    X.inherits;
    X.inspect;
    X.isArray;
    X.isBoolean;
    X.isBuffer;
    X.isDate;
    X.isError;
    X.isFunction;
    X.isNull;
    X.isNullOrUndefined;
    X.isNumber;
    X.isObject;
    X.isPrimitive;
    X.isRegExp;
    X.isString;
    X.isSymbol;
    X.isUndefined;
    X.log;
    X.promisify;
    _extend = X._extend;
    callbackify = X.callbackify;
    debuglog = X.debuglog;
    deprecate = X.deprecate;
    format6 = X.format;
    inherits = X.inherits;
    inspect2 = X.inspect;
    isArray2 = X.isArray;
    isBoolean3 = X.isBoolean;
    isBuffer = X.isBuffer;
    isDate = X.isDate;
    isError = X.isError;
    isFunction = X.isFunction;
    isNull3 = X.isNull;
    isNullOrUndefined = X.isNullOrUndefined;
    isNumber2 = X.isNumber;
    isObject5 = X.isObject;
    isPrimitive = X.isPrimitive;
    isRegExp = X.isRegExp;
    isString2 = X.isString;
    isSymbol = X.isSymbol;
    isUndefined = X.isUndefined;
    log = X.log;
    promisify = X.promisify;
    types2 = X.types;
    TextEncoder2 = self.TextEncoder;
    TextDecoder2 = self.TextDecoder;
  }
});

// https://dev.jspm.io/npm:@jspm/core@2.0.1/_/e0803811.js
function dew() {
  if (_dewExec) return exports;
  _dewExec = true;
  var process4 = exports = {};
  var cachedSetTimeout;
  var cachedClearTimeout;
  function defaultSetTimout() {
    throw new Error("setTimeout has not been defined");
  }
  function defaultClearTimeout() {
    throw new Error("clearTimeout has not been defined");
  }
  (function() {
    try {
      if (typeof setTimeout === "function") {
        cachedSetTimeout = setTimeout;
      } else {
        cachedSetTimeout = defaultSetTimout;
      }
    } catch (e5) {
      cachedSetTimeout = defaultSetTimout;
    }
    try {
      if (typeof clearTimeout === "function") {
        cachedClearTimeout = clearTimeout;
      } else {
        cachedClearTimeout = defaultClearTimeout;
      }
    } catch (e5) {
      cachedClearTimeout = defaultClearTimeout;
    }
  })();
  function runTimeout(fun) {
    if (cachedSetTimeout === setTimeout) {
      return setTimeout(fun, 0);
    }
    if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
      cachedSetTimeout = setTimeout;
      return setTimeout(fun, 0);
    }
    try {
      return cachedSetTimeout(fun, 0);
    } catch (e5) {
      try {
        return cachedSetTimeout.call(null, fun, 0);
      } catch (e6) {
        return cachedSetTimeout.call(this || _global, fun, 0);
      }
    }
  }
  function runClearTimeout(marker) {
    if (cachedClearTimeout === clearTimeout) {
      return clearTimeout(marker);
    }
    if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
      cachedClearTimeout = clearTimeout;
      return clearTimeout(marker);
    }
    try {
      return cachedClearTimeout(marker);
    } catch (e5) {
      try {
        return cachedClearTimeout.call(null, marker);
      } catch (e6) {
        return cachedClearTimeout.call(this || _global, marker);
      }
    }
  }
  var queue3 = [];
  var draining3 = false;
  var currentQueue2;
  var queueIndex2 = -1;
  function cleanUpNextTick2() {
    if (!draining3 || !currentQueue2) {
      return;
    }
    draining3 = false;
    if (currentQueue2.length) {
      queue3 = currentQueue2.concat(queue3);
    } else {
      queueIndex2 = -1;
    }
    if (queue3.length) {
      drainQueue2();
    }
  }
  function drainQueue2() {
    if (draining3) {
      return;
    }
    var timeout = runTimeout(cleanUpNextTick2);
    draining3 = true;
    var len = queue3.length;
    while (len) {
      currentQueue2 = queue3;
      queue3 = [];
      while (++queueIndex2 < len) {
        if (currentQueue2) {
          currentQueue2[queueIndex2].run();
        }
      }
      queueIndex2 = -1;
      len = queue3.length;
    }
    currentQueue2 = null;
    draining3 = false;
    runClearTimeout(timeout);
  }
  process4.nextTick = function(fun) {
    var args = new Array(arguments.length - 1);
    if (arguments.length > 1) {
      for (var i6 = 1; i6 < arguments.length; i6++) {
        args[i6 - 1] = arguments[i6];
      }
    }
    queue3.push(new Item2(fun, args));
    if (queue3.length === 1 && !draining3) {
      runTimeout(drainQueue2);
    }
  };
  function Item2(fun, array) {
    (this || _global).fun = fun;
    (this || _global).array = array;
  }
  Item2.prototype.run = function() {
    (this || _global).fun.apply(null, (this || _global).array);
  };
  process4.title = "browser";
  process4.browser = true;
  process4.env = {};
  process4.argv = [];
  process4.version = "";
  process4.versions = {};
  function noop2() {
  }
  process4.on = noop2;
  process4.addListener = noop2;
  process4.once = noop2;
  process4.off = noop2;
  process4.removeListener = noop2;
  process4.removeAllListeners = noop2;
  process4.emit = noop2;
  process4.prependListener = noop2;
  process4.prependOnceListener = noop2;
  process4.listeners = function(name2) {
    return [];
  };
  process4.binding = function(name2) {
    throw new Error("process.binding is not supported");
  };
  process4.cwd = function() {
    return "/";
  };
  process4.chdir = function(dir) {
    throw new Error("process.chdir is not supported");
  };
  process4.umask = function() {
    return 0;
  };
  return exports;
}
var exports, _dewExec, _global, process;
var init_e0803811 = __esm({
  "https://dev.jspm.io/npm:@jspm/core@2.0.1/_/e0803811.js"() {
    exports = {};
    _dewExec = false;
    _global = typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : global;
    process = dew();
    process.platform = "browser";
    process.addListener;
    process.argv;
    process.binding;
    process.browser;
    process.chdir;
    process.cwd;
    process.emit;
    process.env;
    process.listeners;
    process.nextTick;
    process.off;
    process.on;
    process.once;
    process.prependListener;
    process.prependOnceListener;
    process.removeAllListeners;
    process.removeListener;
    process.title;
    process.umask;
    process.version;
    process.versions;
  }
});

// https://dev.jspm.io/npm:@jspm/core@2.0.1/_/cb95b980.js
function u$2(r5) {
  var t5 = r5.length;
  if (t5 % 4 > 0) throw new Error("Invalid string. Length must be a multiple of 4");
  var e5 = r5.indexOf("=");
  return -1 === e5 && (e5 = t5), [e5, e5 === t5 ? 0 : 4 - e5 % 4];
}
function c$12(r5, e5, n5) {
  for (var o5, a5, h5 = [], u5 = e5; u5 < n5; u5 += 3) o5 = (r5[u5] << 16 & 16711680) + (r5[u5 + 1] << 8 & 65280) + (255 & r5[u5 + 2]), h5.push(t$12[(a5 = o5) >> 18 & 63] + t$12[a5 >> 12 & 63] + t$12[a5 >> 6 & 63] + t$12[63 & a5]);
  return h5.join("");
}
function f$2(t5) {
  if (t5 > 2147483647) throw new RangeError('The value "' + t5 + '" is invalid for option "size"');
  var r5 = new Uint8Array(t5);
  return Object.setPrototypeOf(r5, u$1$1.prototype), r5;
}
function u$1$1(t5, r5, e5) {
  if ("number" == typeof t5) {
    if ("string" == typeof r5) throw new TypeError('The "string" argument must be of type string. Received type number');
    return a$2(t5);
  }
  return s$1(t5, r5, e5);
}
function s$1(t5, r5, e5) {
  if ("string" == typeof t5) return (function(t6, r6) {
    "string" == typeof r6 && "" !== r6 || (r6 = "utf8");
    if (!u$1$1.isEncoding(r6)) throw new TypeError("Unknown encoding: " + r6);
    var e6 = 0 | y3(t6, r6), n6 = f$2(e6), i7 = n6.write(t6, r6);
    i7 !== e6 && (n6 = n6.slice(0, i7));
    return n6;
  })(t5, r5);
  if (ArrayBuffer.isView(t5)) return p4(t5);
  if (null == t5) throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof t5);
  if (F3(t5, ArrayBuffer) || t5 && F3(t5.buffer, ArrayBuffer)) return c$1$1(t5, r5, e5);
  if ("undefined" != typeof SharedArrayBuffer && (F3(t5, SharedArrayBuffer) || t5 && F3(t5.buffer, SharedArrayBuffer))) return c$1$1(t5, r5, e5);
  if ("number" == typeof t5) throw new TypeError('The "value" argument must not be of type number. Received type number');
  var n5 = t5.valueOf && t5.valueOf();
  if (null != n5 && n5 !== t5) return u$1$1.from(n5, r5, e5);
  var i6 = (function(t6) {
    if (u$1$1.isBuffer(t6)) {
      var r6 = 0 | l$12(t6.length), e6 = f$2(r6);
      return 0 === e6.length || t6.copy(e6, 0, 0, r6), e6;
    }
    if (void 0 !== t6.length) return "number" != typeof t6.length || N2(t6.length) ? f$2(0) : p4(t6);
    if ("Buffer" === t6.type && Array.isArray(t6.data)) return p4(t6.data);
  })(t5);
  if (i6) return i6;
  if ("undefined" != typeof Symbol && null != Symbol.toPrimitive && "function" == typeof t5[Symbol.toPrimitive]) return u$1$1.from(t5[Symbol.toPrimitive]("string"), r5, e5);
  throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof t5);
}
function h$1$1(t5) {
  if ("number" != typeof t5) throw new TypeError('"size" argument must be of type number');
  if (t5 < 0) throw new RangeError('The value "' + t5 + '" is invalid for option "size"');
}
function a$2(t5) {
  return h$1$1(t5), f$2(t5 < 0 ? 0 : 0 | l$12(t5));
}
function p4(t5) {
  for (var r5 = t5.length < 0 ? 0 : 0 | l$12(t5.length), e5 = f$2(r5), n5 = 0; n5 < r5; n5 += 1) e5[n5] = 255 & t5[n5];
  return e5;
}
function c$1$1(t5, r5, e5) {
  if (r5 < 0 || t5.byteLength < r5) throw new RangeError('"offset" is outside of buffer bounds');
  if (t5.byteLength < r5 + (e5 || 0)) throw new RangeError('"length" is outside of buffer bounds');
  var n5;
  return n5 = void 0 === r5 && void 0 === e5 ? new Uint8Array(t5) : void 0 === e5 ? new Uint8Array(t5, r5) : new Uint8Array(t5, r5, e5), Object.setPrototypeOf(n5, u$1$1.prototype), n5;
}
function l$12(t5) {
  if (t5 >= 2147483647) throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + 2147483647 .toString(16) + " bytes");
  return 0 | t5;
}
function y3(t5, r5) {
  if (u$1$1.isBuffer(t5)) return t5.length;
  if (ArrayBuffer.isView(t5) || F3(t5, ArrayBuffer)) return t5.byteLength;
  if ("string" != typeof t5) throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof t5);
  var e5 = t5.length, n5 = arguments.length > 2 && true === arguments[2];
  if (!n5 && 0 === e5) return 0;
  for (var i6 = false; ; ) switch (r5) {
    case "ascii":
    case "latin1":
    case "binary":
      return e5;
    case "utf8":
    case "utf-8":
      return _2(t5).length;
    case "ucs2":
    case "ucs-2":
    case "utf16le":
    case "utf-16le":
      return 2 * e5;
    case "hex":
      return e5 >>> 1;
    case "base64":
      return z2(t5).length;
    default:
      if (i6) return n5 ? -1 : _2(t5).length;
      r5 = ("" + r5).toLowerCase(), i6 = true;
  }
}
function g2(t5, r5, e5) {
  var n5 = false;
  if ((void 0 === r5 || r5 < 0) && (r5 = 0), r5 > this.length) return "";
  if ((void 0 === e5 || e5 > this.length) && (e5 = this.length), e5 <= 0) return "";
  if ((e5 >>>= 0) <= (r5 >>>= 0)) return "";
  for (t5 || (t5 = "utf8"); ; ) switch (t5) {
    case "hex":
      return O2(this, r5, e5);
    case "utf8":
    case "utf-8":
      return I2(this, r5, e5);
    case "ascii":
      return S2(this, r5, e5);
    case "latin1":
    case "binary":
      return R3(this, r5, e5);
    case "base64":
      return T3(this, r5, e5);
    case "ucs2":
    case "ucs-2":
    case "utf16le":
    case "utf-16le":
      return L2(this, r5, e5);
    default:
      if (n5) throw new TypeError("Unknown encoding: " + t5);
      t5 = (t5 + "").toLowerCase(), n5 = true;
  }
}
function w2(t5, r5, e5) {
  var n5 = t5[r5];
  t5[r5] = t5[e5], t5[e5] = n5;
}
function d3(t5, r5, e5, n5, i6) {
  if (0 === t5.length) return -1;
  if ("string" == typeof e5 ? (n5 = e5, e5 = 0) : e5 > 2147483647 ? e5 = 2147483647 : e5 < -2147483648 && (e5 = -2147483648), N2(e5 = +e5) && (e5 = i6 ? 0 : t5.length - 1), e5 < 0 && (e5 = t5.length + e5), e5 >= t5.length) {
    if (i6) return -1;
    e5 = t5.length - 1;
  } else if (e5 < 0) {
    if (!i6) return -1;
    e5 = 0;
  }
  if ("string" == typeof r5 && (r5 = u$1$1.from(r5, n5)), u$1$1.isBuffer(r5)) return 0 === r5.length ? -1 : v3(t5, r5, e5, n5, i6);
  if ("number" == typeof r5) return r5 &= 255, "function" == typeof Uint8Array.prototype.indexOf ? i6 ? Uint8Array.prototype.indexOf.call(t5, r5, e5) : Uint8Array.prototype.lastIndexOf.call(t5, r5, e5) : v3(t5, [r5], e5, n5, i6);
  throw new TypeError("val must be string, number or Buffer");
}
function v3(t5, r5, e5, n5, i6) {
  var o5, f5 = 1, u5 = t5.length, s5 = r5.length;
  if (void 0 !== n5 && ("ucs2" === (n5 = String(n5).toLowerCase()) || "ucs-2" === n5 || "utf16le" === n5 || "utf-16le" === n5)) {
    if (t5.length < 2 || r5.length < 2) return -1;
    f5 = 2, u5 /= 2, s5 /= 2, e5 /= 2;
  }
  function h5(t6, r6) {
    return 1 === f5 ? t6[r6] : t6.readUInt16BE(r6 * f5);
  }
  if (i6) {
    var a5 = -1;
    for (o5 = e5; o5 < u5; o5++) if (h5(t5, o5) === h5(r5, -1 === a5 ? 0 : o5 - a5)) {
      if (-1 === a5 && (a5 = o5), o5 - a5 + 1 === s5) return a5 * f5;
    } else -1 !== a5 && (o5 -= o5 - a5), a5 = -1;
  } else for (e5 + s5 > u5 && (e5 = u5 - s5), o5 = e5; o5 >= 0; o5--) {
    for (var p5 = true, c6 = 0; c6 < s5; c6++) if (h5(t5, o5 + c6) !== h5(r5, c6)) {
      p5 = false;
      break;
    }
    if (p5) return o5;
  }
  return -1;
}
function b2(t5, r5, e5, n5) {
  e5 = Number(e5) || 0;
  var i6 = t5.length - e5;
  n5 ? (n5 = Number(n5)) > i6 && (n5 = i6) : n5 = i6;
  var o5 = r5.length;
  n5 > o5 / 2 && (n5 = o5 / 2);
  for (var f5 = 0; f5 < n5; ++f5) {
    var u5 = parseInt(r5.substr(2 * f5, 2), 16);
    if (N2(u5)) return f5;
    t5[e5 + f5] = u5;
  }
  return f5;
}
function m3(t5, r5, e5, n5) {
  return D2(_2(r5, t5.length - e5), t5, e5, n5);
}
function E2(t5, r5, e5, n5) {
  return D2((function(t6) {
    for (var r6 = [], e6 = 0; e6 < t6.length; ++e6) r6.push(255 & t6.charCodeAt(e6));
    return r6;
  })(r5), t5, e5, n5);
}
function B2(t5, r5, e5, n5) {
  return E2(t5, r5, e5, n5);
}
function A2(t5, r5, e5, n5) {
  return D2(z2(r5), t5, e5, n5);
}
function U2(t5, r5, e5, n5) {
  return D2((function(t6, r6) {
    for (var e6, n6, i6, o5 = [], f5 = 0; f5 < t6.length && !((r6 -= 2) < 0); ++f5) e6 = t6.charCodeAt(f5), n6 = e6 >> 8, i6 = e6 % 256, o5.push(i6), o5.push(n6);
    return o5;
  })(r5, t5.length - e5), t5, e5, n5);
}
function T3(t5, r5, e5) {
  return 0 === r5 && e5 === t5.length ? n$1$1.fromByteArray(t5) : n$1$1.fromByteArray(t5.slice(r5, e5));
}
function I2(t5, r5, e5) {
  e5 = Math.min(t5.length, e5);
  for (var n5 = [], i6 = r5; i6 < e5; ) {
    var o5, f5, u5, s5, h5 = t5[i6], a5 = null, p5 = h5 > 239 ? 4 : h5 > 223 ? 3 : h5 > 191 ? 2 : 1;
    if (i6 + p5 <= e5) switch (p5) {
      case 1:
        h5 < 128 && (a5 = h5);
        break;
      case 2:
        128 == (192 & (o5 = t5[i6 + 1])) && (s5 = (31 & h5) << 6 | 63 & o5) > 127 && (a5 = s5);
        break;
      case 3:
        o5 = t5[i6 + 1], f5 = t5[i6 + 2], 128 == (192 & o5) && 128 == (192 & f5) && (s5 = (15 & h5) << 12 | (63 & o5) << 6 | 63 & f5) > 2047 && (s5 < 55296 || s5 > 57343) && (a5 = s5);
        break;
      case 4:
        o5 = t5[i6 + 1], f5 = t5[i6 + 2], u5 = t5[i6 + 3], 128 == (192 & o5) && 128 == (192 & f5) && 128 == (192 & u5) && (s5 = (15 & h5) << 18 | (63 & o5) << 12 | (63 & f5) << 6 | 63 & u5) > 65535 && s5 < 1114112 && (a5 = s5);
    }
    null === a5 ? (a5 = 65533, p5 = 1) : a5 > 65535 && (a5 -= 65536, n5.push(a5 >>> 10 & 1023 | 55296), a5 = 56320 | 1023 & a5), n5.push(a5), i6 += p5;
  }
  return (function(t6) {
    var r6 = t6.length;
    if (r6 <= 4096) return String.fromCharCode.apply(String, t6);
    var e6 = "", n6 = 0;
    for (; n6 < r6; ) e6 += String.fromCharCode.apply(String, t6.slice(n6, n6 += 4096));
    return e6;
  })(n5);
}
function S2(t5, r5, e5) {
  var n5 = "";
  e5 = Math.min(t5.length, e5);
  for (var i6 = r5; i6 < e5; ++i6) n5 += String.fromCharCode(127 & t5[i6]);
  return n5;
}
function R3(t5, r5, e5) {
  var n5 = "";
  e5 = Math.min(t5.length, e5);
  for (var i6 = r5; i6 < e5; ++i6) n5 += String.fromCharCode(t5[i6]);
  return n5;
}
function O2(t5, r5, e5) {
  var n5 = t5.length;
  (!r5 || r5 < 0) && (r5 = 0), (!e5 || e5 < 0 || e5 > n5) && (e5 = n5);
  for (var i6 = "", o5 = r5; o5 < e5; ++o5) i6 += Y2[t5[o5]];
  return i6;
}
function L2(t5, r5, e5) {
  for (var n5 = t5.slice(r5, e5), i6 = "", o5 = 0; o5 < n5.length; o5 += 2) i6 += String.fromCharCode(n5[o5] + 256 * n5[o5 + 1]);
  return i6;
}
function x2(t5, r5, e5) {
  if (t5 % 1 != 0 || t5 < 0) throw new RangeError("offset is not uint");
  if (t5 + r5 > e5) throw new RangeError("Trying to access beyond buffer length");
}
function C2(t5, r5, e5, n5, i6, o5) {
  if (!u$1$1.isBuffer(t5)) throw new TypeError('"buffer" argument must be a Buffer instance');
  if (r5 > i6 || r5 < o5) throw new RangeError('"value" argument is out of bounds');
  if (e5 + n5 > t5.length) throw new RangeError("Index out of range");
}
function P2(t5, r5, e5, n5, i6, o5) {
  if (e5 + n5 > t5.length) throw new RangeError("Index out of range");
  if (e5 < 0) throw new RangeError("Index out of range");
}
function k2(t5, r5, e5, n5, o5) {
  return r5 = +r5, e5 >>>= 0, o5 || P2(t5, 0, e5, 4), i$12.write(t5, r5, e5, n5, 23, 4), e5 + 4;
}
function M2(t5, r5, e5, n5, o5) {
  return r5 = +r5, e5 >>>= 0, o5 || P2(t5, 0, e5, 8), i$12.write(t5, r5, e5, n5, 52, 8), e5 + 8;
}
function _2(t5, r5) {
  var e5;
  r5 = r5 || 1 / 0;
  for (var n5 = t5.length, i6 = null, o5 = [], f5 = 0; f5 < n5; ++f5) {
    if ((e5 = t5.charCodeAt(f5)) > 55295 && e5 < 57344) {
      if (!i6) {
        if (e5 > 56319) {
          (r5 -= 3) > -1 && o5.push(239, 191, 189);
          continue;
        }
        if (f5 + 1 === n5) {
          (r5 -= 3) > -1 && o5.push(239, 191, 189);
          continue;
        }
        i6 = e5;
        continue;
      }
      if (e5 < 56320) {
        (r5 -= 3) > -1 && o5.push(239, 191, 189), i6 = e5;
        continue;
      }
      e5 = 65536 + (i6 - 55296 << 10 | e5 - 56320);
    } else i6 && (r5 -= 3) > -1 && o5.push(239, 191, 189);
    if (i6 = null, e5 < 128) {
      if ((r5 -= 1) < 0) break;
      o5.push(e5);
    } else if (e5 < 2048) {
      if ((r5 -= 2) < 0) break;
      o5.push(e5 >> 6 | 192, 63 & e5 | 128);
    } else if (e5 < 65536) {
      if ((r5 -= 3) < 0) break;
      o5.push(e5 >> 12 | 224, e5 >> 6 & 63 | 128, 63 & e5 | 128);
    } else {
      if (!(e5 < 1114112)) throw new Error("Invalid code point");
      if ((r5 -= 4) < 0) break;
      o5.push(e5 >> 18 | 240, e5 >> 12 & 63 | 128, e5 >> 6 & 63 | 128, 63 & e5 | 128);
    }
  }
  return o5;
}
function z2(t5) {
  return n$1$1.toByteArray((function(t6) {
    if ((t6 = (t6 = t6.split("=")[0]).trim().replace(j2, "")).length < 2) return "";
    for (; t6.length % 4 != 0; ) t6 += "=";
    return t6;
  })(t5));
}
function D2(t5, r5, e5, n5) {
  for (var i6 = 0; i6 < n5 && !(i6 + e5 >= r5.length || i6 >= t5.length); ++i6) r5[i6 + e5] = t5[i6];
  return i6;
}
function F3(t5, r5) {
  return t5 instanceof r5 || null != t5 && null != t5.constructor && null != t5.constructor.name && t5.constructor.name === r5.name;
}
function N2(t5) {
  return t5 != t5;
}
function t4(r5, e5) {
  for (var n5 in r5) e5[n5] = r5[n5];
}
function f4(r5, e5, n5) {
  return o4(r5, e5, n5);
}
function a4(t5) {
  var e5;
  switch (this.encoding = (function(t6) {
    var e6 = (function(t7) {
      if (!t7) return "utf8";
      for (var e7; ; ) switch (t7) {
        case "utf8":
        case "utf-8":
          return "utf8";
        case "ucs2":
        case "ucs-2":
        case "utf16le":
        case "utf-16le":
          return "utf16le";
        case "latin1":
        case "binary":
          return "latin1";
        case "base64":
        case "ascii":
        case "hex":
          return t7;
        default:
          if (e7) return;
          t7 = ("" + t7).toLowerCase(), e7 = true;
      }
    })(t6);
    if ("string" != typeof e6 && (s4.isEncoding === i5 || !i5(t6))) throw new Error("Unknown encoding: " + t6);
    return e6 || t6;
  })(t5), this.encoding) {
    case "utf16le":
      this.text = h4, this.end = l5, e5 = 4;
      break;
    case "utf8":
      this.fillLast = n$12, e5 = 4;
      break;
    case "base64":
      this.text = u$12, this.end = o$12, e5 = 3;
      break;
    default:
      return this.write = f$1, this.end = c4, void 0;
  }
  this.lastNeed = 0, this.lastTotal = 0, this.lastChar = s4.allocUnsafe(e5);
}
function r4(t5) {
  return t5 <= 127 ? 0 : t5 >> 5 == 6 ? 2 : t5 >> 4 == 14 ? 3 : t5 >> 3 == 30 ? 4 : t5 >> 6 == 2 ? -1 : -2;
}
function n$12(t5) {
  var e5 = this.lastTotal - this.lastNeed, s5 = (function(t6, e6, s6) {
    if (128 != (192 & e6[0])) return t6.lastNeed = 0, "\uFFFD";
    if (t6.lastNeed > 1 && e6.length > 1) {
      if (128 != (192 & e6[1])) return t6.lastNeed = 1, "\uFFFD";
      if (t6.lastNeed > 2 && e6.length > 2 && 128 != (192 & e6[2])) return t6.lastNeed = 2, "\uFFFD";
    }
  })(this, t5);
  return void 0 !== s5 ? s5 : this.lastNeed <= t5.length ? (t5.copy(this.lastChar, e5, 0, this.lastNeed), this.lastChar.toString(this.encoding, 0, this.lastTotal)) : (t5.copy(this.lastChar, e5, 0, t5.length), this.lastNeed -= t5.length, void 0);
}
function h4(t5, e5) {
  if ((t5.length - e5) % 2 == 0) {
    var s5 = t5.toString("utf16le", e5);
    if (s5) {
      var i6 = s5.charCodeAt(s5.length - 1);
      if (i6 >= 55296 && i6 <= 56319) return this.lastNeed = 2, this.lastTotal = 4, this.lastChar[0] = t5[t5.length - 2], this.lastChar[1] = t5[t5.length - 1], s5.slice(0, -1);
    }
    return s5;
  }
  return this.lastNeed = 1, this.lastTotal = 2, this.lastChar[0] = t5[t5.length - 1], t5.toString("utf16le", e5, t5.length - 1);
}
function l5(t5) {
  var e5 = t5 && t5.length ? this.write(t5) : "";
  if (this.lastNeed) {
    var s5 = this.lastTotal - this.lastNeed;
    return e5 + this.lastChar.toString("utf16le", 0, s5);
  }
  return e5;
}
function u$12(t5, e5) {
  var s5 = (t5.length - e5) % 3;
  return 0 === s5 ? t5.toString("base64", e5) : (this.lastNeed = 3 - s5, this.lastTotal = 3, 1 === s5 ? this.lastChar[0] = t5[t5.length - 1] : (this.lastChar[0] = t5[t5.length - 2], this.lastChar[1] = t5[t5.length - 1]), t5.toString("base64", e5, t5.length - s5));
}
function o$12(t5) {
  var e5 = t5 && t5.length ? this.write(t5) : "";
  return this.lastNeed ? e5 + this.lastChar.toString("base64", 0, 3 - this.lastNeed) : e5;
}
function f$1(t5) {
  return t5.toString(this.encoding);
}
function c4(t5) {
  return t5 && t5.length ? this.write(t5) : "";
}
var r$12, t$12, e$2, n$2, o$22, a$1, h$1, a$1$1, e$1$1, n$1$1, i$12, o$1$1, j2, Y2, e4, n4, o4, u4, e$12, s4, i5;
var init_cb95b980 = __esm({
  "https://dev.jspm.io/npm:@jspm/core@2.0.1/_/cb95b980.js"() {
    for (r$12 = { byteLength: function(r5) {
      var t5 = u$2(r5), e5 = t5[0], n5 = t5[1];
      return 3 * (e5 + n5) / 4 - n5;
    }, toByteArray: function(r5) {
      var t5, o5, a5 = u$2(r5), h5 = a5[0], c6 = a5[1], d4 = new n$2((function(r6, t6, e5) {
        return 3 * (t6 + e5) / 4 - e5;
      })(0, h5, c6)), f5 = 0, A3 = c6 > 0 ? h5 - 4 : h5;
      for (o5 = 0; o5 < A3; o5 += 4) t5 = e$2[r5.charCodeAt(o5)] << 18 | e$2[r5.charCodeAt(o5 + 1)] << 12 | e$2[r5.charCodeAt(o5 + 2)] << 6 | e$2[r5.charCodeAt(o5 + 3)], d4[f5++] = t5 >> 16 & 255, d4[f5++] = t5 >> 8 & 255, d4[f5++] = 255 & t5;
      2 === c6 && (t5 = e$2[r5.charCodeAt(o5)] << 2 | e$2[r5.charCodeAt(o5 + 1)] >> 4, d4[f5++] = 255 & t5);
      1 === c6 && (t5 = e$2[r5.charCodeAt(o5)] << 10 | e$2[r5.charCodeAt(o5 + 1)] << 4 | e$2[r5.charCodeAt(o5 + 2)] >> 2, d4[f5++] = t5 >> 8 & 255, d4[f5++] = 255 & t5);
      return d4;
    }, fromByteArray: function(r5) {
      for (var e5, n5 = r5.length, o5 = n5 % 3, a5 = [], h5 = 0, u5 = n5 - o5; h5 < u5; h5 += 16383) a5.push(c$12(r5, h5, h5 + 16383 > u5 ? u5 : h5 + 16383));
      1 === o5 ? (e5 = r5[n5 - 1], a5.push(t$12[e5 >> 2] + t$12[e5 << 4 & 63] + "==")) : 2 === o5 && (e5 = (r5[n5 - 2] << 8) + r5[n5 - 1], a5.push(t$12[e5 >> 10] + t$12[e5 >> 4 & 63] + t$12[e5 << 2 & 63] + "="));
      return a5.join("");
    } }, t$12 = [], e$2 = [], n$2 = "undefined" != typeof Uint8Array ? Uint8Array : Array, o$22 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", a$1 = 0, h$1 = o$22.length; a$1 < h$1; ++a$1) t$12[a$1] = o$22[a$1], e$2[o$22.charCodeAt(a$1)] = a$1;
    e$2["-".charCodeAt(0)] = 62, e$2["_".charCodeAt(0)] = 63;
    a$1$1 = { read: function(a5, t5, o5, r5, h5) {
      var M3, f5, p5 = 8 * h5 - r5 - 1, w3 = (1 << p5) - 1, e5 = w3 >> 1, i6 = -7, N3 = o5 ? h5 - 1 : 0, n5 = o5 ? -1 : 1, u5 = a5[t5 + N3];
      for (N3 += n5, M3 = u5 & (1 << -i6) - 1, u5 >>= -i6, i6 += p5; i6 > 0; M3 = 256 * M3 + a5[t5 + N3], N3 += n5, i6 -= 8) ;
      for (f5 = M3 & (1 << -i6) - 1, M3 >>= -i6, i6 += r5; i6 > 0; f5 = 256 * f5 + a5[t5 + N3], N3 += n5, i6 -= 8) ;
      if (0 === M3) M3 = 1 - e5;
      else {
        if (M3 === w3) return f5 ? NaN : 1 / 0 * (u5 ? -1 : 1);
        f5 += Math.pow(2, r5), M3 -= e5;
      }
      return (u5 ? -1 : 1) * f5 * Math.pow(2, M3 - r5);
    }, write: function(a5, t5, o5, r5, h5, M3) {
      var f5, p5, w3, e5 = 8 * M3 - h5 - 1, i6 = (1 << e5) - 1, N3 = i6 >> 1, n5 = 23 === h5 ? Math.pow(2, -24) - Math.pow(2, -77) : 0, u5 = r5 ? 0 : M3 - 1, l6 = r5 ? 1 : -1, s5 = t5 < 0 || 0 === t5 && 1 / t5 < 0 ? 1 : 0;
      for (t5 = Math.abs(t5), isNaN(t5) || t5 === 1 / 0 ? (p5 = isNaN(t5) ? 1 : 0, f5 = i6) : (f5 = Math.floor(Math.log(t5) / Math.LN2), t5 * (w3 = Math.pow(2, -f5)) < 1 && (f5--, w3 *= 2), (t5 += f5 + N3 >= 1 ? n5 / w3 : n5 * Math.pow(2, 1 - N3)) * w3 >= 2 && (f5++, w3 /= 2), f5 + N3 >= i6 ? (p5 = 0, f5 = i6) : f5 + N3 >= 1 ? (p5 = (t5 * w3 - 1) * Math.pow(2, h5), f5 += N3) : (p5 = t5 * Math.pow(2, N3 - 1) * Math.pow(2, h5), f5 = 0)); h5 >= 8; a5[o5 + u5] = 255 & p5, u5 += l6, p5 /= 256, h5 -= 8) ;
      for (f5 = f5 << h5 | p5, e5 += h5; e5 > 0; a5[o5 + u5] = 255 & f5, u5 += l6, f5 /= 256, e5 -= 8) ;
      a5[o5 + u5 - l6] |= 128 * s5;
    } };
    e$1$1 = {};
    n$1$1 = r$12;
    i$12 = a$1$1;
    o$1$1 = "function" == typeof Symbol && "function" == typeof Symbol.for ? /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom") : null;
    e$1$1.Buffer = u$1$1, e$1$1.SlowBuffer = function(t5) {
      +t5 != t5 && (t5 = 0);
      return u$1$1.alloc(+t5);
    }, e$1$1.INSPECT_MAX_BYTES = 50;
    e$1$1.kMaxLength = 2147483647, u$1$1.TYPED_ARRAY_SUPPORT = (function() {
      try {
        var t5 = new Uint8Array(1), r5 = { foo: function() {
          return 42;
        } };
        return Object.setPrototypeOf(r5, Uint8Array.prototype), Object.setPrototypeOf(t5, r5), 42 === t5.foo();
      } catch (t6) {
        return false;
      }
    })(), u$1$1.TYPED_ARRAY_SUPPORT || "undefined" == typeof console || "function" != typeof console.error || console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."), Object.defineProperty(u$1$1.prototype, "parent", { enumerable: true, get: function() {
      if (u$1$1.isBuffer(this)) return this.buffer;
    } }), Object.defineProperty(u$1$1.prototype, "offset", { enumerable: true, get: function() {
      if (u$1$1.isBuffer(this)) return this.byteOffset;
    } }), u$1$1.poolSize = 8192, u$1$1.from = function(t5, r5, e5) {
      return s$1(t5, r5, e5);
    }, Object.setPrototypeOf(u$1$1.prototype, Uint8Array.prototype), Object.setPrototypeOf(u$1$1, Uint8Array), u$1$1.alloc = function(t5, r5, e5) {
      return (function(t6, r6, e6) {
        return h$1$1(t6), t6 <= 0 ? f$2(t6) : void 0 !== r6 ? "string" == typeof e6 ? f$2(t6).fill(r6, e6) : f$2(t6).fill(r6) : f$2(t6);
      })(t5, r5, e5);
    }, u$1$1.allocUnsafe = function(t5) {
      return a$2(t5);
    }, u$1$1.allocUnsafeSlow = function(t5) {
      return a$2(t5);
    }, u$1$1.isBuffer = function(t5) {
      return null != t5 && true === t5._isBuffer && t5 !== u$1$1.prototype;
    }, u$1$1.compare = function(t5, r5) {
      if (F3(t5, Uint8Array) && (t5 = u$1$1.from(t5, t5.offset, t5.byteLength)), F3(r5, Uint8Array) && (r5 = u$1$1.from(r5, r5.offset, r5.byteLength)), !u$1$1.isBuffer(t5) || !u$1$1.isBuffer(r5)) throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');
      if (t5 === r5) return 0;
      for (var e5 = t5.length, n5 = r5.length, i6 = 0, o5 = Math.min(e5, n5); i6 < o5; ++i6) if (t5[i6] !== r5[i6]) {
        e5 = t5[i6], n5 = r5[i6];
        break;
      }
      return e5 < n5 ? -1 : n5 < e5 ? 1 : 0;
    }, u$1$1.isEncoding = function(t5) {
      switch (String(t5).toLowerCase()) {
        case "hex":
        case "utf8":
        case "utf-8":
        case "ascii":
        case "latin1":
        case "binary":
        case "base64":
        case "ucs2":
        case "ucs-2":
        case "utf16le":
        case "utf-16le":
          return true;
        default:
          return false;
      }
    }, u$1$1.concat = function(t5, r5) {
      if (!Array.isArray(t5)) throw new TypeError('"list" argument must be an Array of Buffers');
      if (0 === t5.length) return u$1$1.alloc(0);
      var e5;
      if (void 0 === r5) for (r5 = 0, e5 = 0; e5 < t5.length; ++e5) r5 += t5[e5].length;
      var n5 = u$1$1.allocUnsafe(r5), i6 = 0;
      for (e5 = 0; e5 < t5.length; ++e5) {
        var o5 = t5[e5];
        if (F3(o5, Uint8Array) && (o5 = u$1$1.from(o5)), !u$1$1.isBuffer(o5)) throw new TypeError('"list" argument must be an Array of Buffers');
        o5.copy(n5, i6), i6 += o5.length;
      }
      return n5;
    }, u$1$1.byteLength = y3, u$1$1.prototype._isBuffer = true, u$1$1.prototype.swap16 = function() {
      var t5 = this.length;
      if (t5 % 2 != 0) throw new RangeError("Buffer size must be a multiple of 16-bits");
      for (var r5 = 0; r5 < t5; r5 += 2) w2(this, r5, r5 + 1);
      return this;
    }, u$1$1.prototype.swap32 = function() {
      var t5 = this.length;
      if (t5 % 4 != 0) throw new RangeError("Buffer size must be a multiple of 32-bits");
      for (var r5 = 0; r5 < t5; r5 += 4) w2(this, r5, r5 + 3), w2(this, r5 + 1, r5 + 2);
      return this;
    }, u$1$1.prototype.swap64 = function() {
      var t5 = this.length;
      if (t5 % 8 != 0) throw new RangeError("Buffer size must be a multiple of 64-bits");
      for (var r5 = 0; r5 < t5; r5 += 8) w2(this, r5, r5 + 7), w2(this, r5 + 1, r5 + 6), w2(this, r5 + 2, r5 + 5), w2(this, r5 + 3, r5 + 4);
      return this;
    }, u$1$1.prototype.toString = function() {
      var t5 = this.length;
      return 0 === t5 ? "" : 0 === arguments.length ? I2(this, 0, t5) : g2.apply(this, arguments);
    }, u$1$1.prototype.toLocaleString = u$1$1.prototype.toString, u$1$1.prototype.equals = function(t5) {
      if (!u$1$1.isBuffer(t5)) throw new TypeError("Argument must be a Buffer");
      return this === t5 || 0 === u$1$1.compare(this, t5);
    }, u$1$1.prototype.inspect = function() {
      var t5 = "", r5 = e$1$1.INSPECT_MAX_BYTES;
      return t5 = this.toString("hex", 0, r5).replace(/(.{2})/g, "$1 ").trim(), this.length > r5 && (t5 += " ... "), "<Buffer " + t5 + ">";
    }, o$1$1 && (u$1$1.prototype[o$1$1] = u$1$1.prototype.inspect), u$1$1.prototype.compare = function(t5, r5, e5, n5, i6) {
      if (F3(t5, Uint8Array) && (t5 = u$1$1.from(t5, t5.offset, t5.byteLength)), !u$1$1.isBuffer(t5)) throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof t5);
      if (void 0 === r5 && (r5 = 0), void 0 === e5 && (e5 = t5 ? t5.length : 0), void 0 === n5 && (n5 = 0), void 0 === i6 && (i6 = this.length), r5 < 0 || e5 > t5.length || n5 < 0 || i6 > this.length) throw new RangeError("out of range index");
      if (n5 >= i6 && r5 >= e5) return 0;
      if (n5 >= i6) return -1;
      if (r5 >= e5) return 1;
      if (this === t5) return 0;
      for (var o5 = (i6 >>>= 0) - (n5 >>>= 0), f5 = (e5 >>>= 0) - (r5 >>>= 0), s5 = Math.min(o5, f5), h5 = this.slice(n5, i6), a5 = t5.slice(r5, e5), p5 = 0; p5 < s5; ++p5) if (h5[p5] !== a5[p5]) {
        o5 = h5[p5], f5 = a5[p5];
        break;
      }
      return o5 < f5 ? -1 : f5 < o5 ? 1 : 0;
    }, u$1$1.prototype.includes = function(t5, r5, e5) {
      return -1 !== this.indexOf(t5, r5, e5);
    }, u$1$1.prototype.indexOf = function(t5, r5, e5) {
      return d3(this, t5, r5, e5, true);
    }, u$1$1.prototype.lastIndexOf = function(t5, r5, e5) {
      return d3(this, t5, r5, e5, false);
    }, u$1$1.prototype.write = function(t5, r5, e5, n5) {
      if (void 0 === r5) n5 = "utf8", e5 = this.length, r5 = 0;
      else if (void 0 === e5 && "string" == typeof r5) n5 = r5, e5 = this.length, r5 = 0;
      else {
        if (!isFinite(r5)) throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");
        r5 >>>= 0, isFinite(e5) ? (e5 >>>= 0, void 0 === n5 && (n5 = "utf8")) : (n5 = e5, e5 = void 0);
      }
      var i6 = this.length - r5;
      if ((void 0 === e5 || e5 > i6) && (e5 = i6), t5.length > 0 && (e5 < 0 || r5 < 0) || r5 > this.length) throw new RangeError("Attempt to write outside buffer bounds");
      n5 || (n5 = "utf8");
      for (var o5 = false; ; ) switch (n5) {
        case "hex":
          return b2(this, t5, r5, e5);
        case "utf8":
        case "utf-8":
          return m3(this, t5, r5, e5);
        case "ascii":
          return E2(this, t5, r5, e5);
        case "latin1":
        case "binary":
          return B2(this, t5, r5, e5);
        case "base64":
          return A2(this, t5, r5, e5);
        case "ucs2":
        case "ucs-2":
        case "utf16le":
        case "utf-16le":
          return U2(this, t5, r5, e5);
        default:
          if (o5) throw new TypeError("Unknown encoding: " + n5);
          n5 = ("" + n5).toLowerCase(), o5 = true;
      }
    }, u$1$1.prototype.toJSON = function() {
      return { type: "Buffer", data: Array.prototype.slice.call(this._arr || this, 0) };
    };
    u$1$1.prototype.slice = function(t5, r5) {
      var e5 = this.length;
      (t5 = ~~t5) < 0 ? (t5 += e5) < 0 && (t5 = 0) : t5 > e5 && (t5 = e5), (r5 = void 0 === r5 ? e5 : ~~r5) < 0 ? (r5 += e5) < 0 && (r5 = 0) : r5 > e5 && (r5 = e5), r5 < t5 && (r5 = t5);
      var n5 = this.subarray(t5, r5);
      return Object.setPrototypeOf(n5, u$1$1.prototype), n5;
    }, u$1$1.prototype.readUIntLE = function(t5, r5, e5) {
      t5 >>>= 0, r5 >>>= 0, e5 || x2(t5, r5, this.length);
      for (var n5 = this[t5], i6 = 1, o5 = 0; ++o5 < r5 && (i6 *= 256); ) n5 += this[t5 + o5] * i6;
      return n5;
    }, u$1$1.prototype.readUIntBE = function(t5, r5, e5) {
      t5 >>>= 0, r5 >>>= 0, e5 || x2(t5, r5, this.length);
      for (var n5 = this[t5 + --r5], i6 = 1; r5 > 0 && (i6 *= 256); ) n5 += this[t5 + --r5] * i6;
      return n5;
    }, u$1$1.prototype.readUInt8 = function(t5, r5) {
      return t5 >>>= 0, r5 || x2(t5, 1, this.length), this[t5];
    }, u$1$1.prototype.readUInt16LE = function(t5, r5) {
      return t5 >>>= 0, r5 || x2(t5, 2, this.length), this[t5] | this[t5 + 1] << 8;
    }, u$1$1.prototype.readUInt16BE = function(t5, r5) {
      return t5 >>>= 0, r5 || x2(t5, 2, this.length), this[t5] << 8 | this[t5 + 1];
    }, u$1$1.prototype.readUInt32LE = function(t5, r5) {
      return t5 >>>= 0, r5 || x2(t5, 4, this.length), (this[t5] | this[t5 + 1] << 8 | this[t5 + 2] << 16) + 16777216 * this[t5 + 3];
    }, u$1$1.prototype.readUInt32BE = function(t5, r5) {
      return t5 >>>= 0, r5 || x2(t5, 4, this.length), 16777216 * this[t5] + (this[t5 + 1] << 16 | this[t5 + 2] << 8 | this[t5 + 3]);
    }, u$1$1.prototype.readIntLE = function(t5, r5, e5) {
      t5 >>>= 0, r5 >>>= 0, e5 || x2(t5, r5, this.length);
      for (var n5 = this[t5], i6 = 1, o5 = 0; ++o5 < r5 && (i6 *= 256); ) n5 += this[t5 + o5] * i6;
      return n5 >= (i6 *= 128) && (n5 -= Math.pow(2, 8 * r5)), n5;
    }, u$1$1.prototype.readIntBE = function(t5, r5, e5) {
      t5 >>>= 0, r5 >>>= 0, e5 || x2(t5, r5, this.length);
      for (var n5 = r5, i6 = 1, o5 = this[t5 + --n5]; n5 > 0 && (i6 *= 256); ) o5 += this[t5 + --n5] * i6;
      return o5 >= (i6 *= 128) && (o5 -= Math.pow(2, 8 * r5)), o5;
    }, u$1$1.prototype.readInt8 = function(t5, r5) {
      return t5 >>>= 0, r5 || x2(t5, 1, this.length), 128 & this[t5] ? -1 * (255 - this[t5] + 1) : this[t5];
    }, u$1$1.prototype.readInt16LE = function(t5, r5) {
      t5 >>>= 0, r5 || x2(t5, 2, this.length);
      var e5 = this[t5] | this[t5 + 1] << 8;
      return 32768 & e5 ? 4294901760 | e5 : e5;
    }, u$1$1.prototype.readInt16BE = function(t5, r5) {
      t5 >>>= 0, r5 || x2(t5, 2, this.length);
      var e5 = this[t5 + 1] | this[t5] << 8;
      return 32768 & e5 ? 4294901760 | e5 : e5;
    }, u$1$1.prototype.readInt32LE = function(t5, r5) {
      return t5 >>>= 0, r5 || x2(t5, 4, this.length), this[t5] | this[t5 + 1] << 8 | this[t5 + 2] << 16 | this[t5 + 3] << 24;
    }, u$1$1.prototype.readInt32BE = function(t5, r5) {
      return t5 >>>= 0, r5 || x2(t5, 4, this.length), this[t5] << 24 | this[t5 + 1] << 16 | this[t5 + 2] << 8 | this[t5 + 3];
    }, u$1$1.prototype.readFloatLE = function(t5, r5) {
      return t5 >>>= 0, r5 || x2(t5, 4, this.length), i$12.read(this, t5, true, 23, 4);
    }, u$1$1.prototype.readFloatBE = function(t5, r5) {
      return t5 >>>= 0, r5 || x2(t5, 4, this.length), i$12.read(this, t5, false, 23, 4);
    }, u$1$1.prototype.readDoubleLE = function(t5, r5) {
      return t5 >>>= 0, r5 || x2(t5, 8, this.length), i$12.read(this, t5, true, 52, 8);
    }, u$1$1.prototype.readDoubleBE = function(t5, r5) {
      return t5 >>>= 0, r5 || x2(t5, 8, this.length), i$12.read(this, t5, false, 52, 8);
    }, u$1$1.prototype.writeUIntLE = function(t5, r5, e5, n5) {
      (t5 = +t5, r5 >>>= 0, e5 >>>= 0, n5) || C2(this, t5, r5, e5, Math.pow(2, 8 * e5) - 1, 0);
      var i6 = 1, o5 = 0;
      for (this[r5] = 255 & t5; ++o5 < e5 && (i6 *= 256); ) this[r5 + o5] = t5 / i6 & 255;
      return r5 + e5;
    }, u$1$1.prototype.writeUIntBE = function(t5, r5, e5, n5) {
      (t5 = +t5, r5 >>>= 0, e5 >>>= 0, n5) || C2(this, t5, r5, e5, Math.pow(2, 8 * e5) - 1, 0);
      var i6 = e5 - 1, o5 = 1;
      for (this[r5 + i6] = 255 & t5; --i6 >= 0 && (o5 *= 256); ) this[r5 + i6] = t5 / o5 & 255;
      return r5 + e5;
    }, u$1$1.prototype.writeUInt8 = function(t5, r5, e5) {
      return t5 = +t5, r5 >>>= 0, e5 || C2(this, t5, r5, 1, 255, 0), this[r5] = 255 & t5, r5 + 1;
    }, u$1$1.prototype.writeUInt16LE = function(t5, r5, e5) {
      return t5 = +t5, r5 >>>= 0, e5 || C2(this, t5, r5, 2, 65535, 0), this[r5] = 255 & t5, this[r5 + 1] = t5 >>> 8, r5 + 2;
    }, u$1$1.prototype.writeUInt16BE = function(t5, r5, e5) {
      return t5 = +t5, r5 >>>= 0, e5 || C2(this, t5, r5, 2, 65535, 0), this[r5] = t5 >>> 8, this[r5 + 1] = 255 & t5, r5 + 2;
    }, u$1$1.prototype.writeUInt32LE = function(t5, r5, e5) {
      return t5 = +t5, r5 >>>= 0, e5 || C2(this, t5, r5, 4, 4294967295, 0), this[r5 + 3] = t5 >>> 24, this[r5 + 2] = t5 >>> 16, this[r5 + 1] = t5 >>> 8, this[r5] = 255 & t5, r5 + 4;
    }, u$1$1.prototype.writeUInt32BE = function(t5, r5, e5) {
      return t5 = +t5, r5 >>>= 0, e5 || C2(this, t5, r5, 4, 4294967295, 0), this[r5] = t5 >>> 24, this[r5 + 1] = t5 >>> 16, this[r5 + 2] = t5 >>> 8, this[r5 + 3] = 255 & t5, r5 + 4;
    }, u$1$1.prototype.writeIntLE = function(t5, r5, e5, n5) {
      if (t5 = +t5, r5 >>>= 0, !n5) {
        var i6 = Math.pow(2, 8 * e5 - 1);
        C2(this, t5, r5, e5, i6 - 1, -i6);
      }
      var o5 = 0, f5 = 1, u5 = 0;
      for (this[r5] = 255 & t5; ++o5 < e5 && (f5 *= 256); ) t5 < 0 && 0 === u5 && 0 !== this[r5 + o5 - 1] && (u5 = 1), this[r5 + o5] = (t5 / f5 >> 0) - u5 & 255;
      return r5 + e5;
    }, u$1$1.prototype.writeIntBE = function(t5, r5, e5, n5) {
      if (t5 = +t5, r5 >>>= 0, !n5) {
        var i6 = Math.pow(2, 8 * e5 - 1);
        C2(this, t5, r5, e5, i6 - 1, -i6);
      }
      var o5 = e5 - 1, f5 = 1, u5 = 0;
      for (this[r5 + o5] = 255 & t5; --o5 >= 0 && (f5 *= 256); ) t5 < 0 && 0 === u5 && 0 !== this[r5 + o5 + 1] && (u5 = 1), this[r5 + o5] = (t5 / f5 >> 0) - u5 & 255;
      return r5 + e5;
    }, u$1$1.prototype.writeInt8 = function(t5, r5, e5) {
      return t5 = +t5, r5 >>>= 0, e5 || C2(this, t5, r5, 1, 127, -128), t5 < 0 && (t5 = 255 + t5 + 1), this[r5] = 255 & t5, r5 + 1;
    }, u$1$1.prototype.writeInt16LE = function(t5, r5, e5) {
      return t5 = +t5, r5 >>>= 0, e5 || C2(this, t5, r5, 2, 32767, -32768), this[r5] = 255 & t5, this[r5 + 1] = t5 >>> 8, r5 + 2;
    }, u$1$1.prototype.writeInt16BE = function(t5, r5, e5) {
      return t5 = +t5, r5 >>>= 0, e5 || C2(this, t5, r5, 2, 32767, -32768), this[r5] = t5 >>> 8, this[r5 + 1] = 255 & t5, r5 + 2;
    }, u$1$1.prototype.writeInt32LE = function(t5, r5, e5) {
      return t5 = +t5, r5 >>>= 0, e5 || C2(this, t5, r5, 4, 2147483647, -2147483648), this[r5] = 255 & t5, this[r5 + 1] = t5 >>> 8, this[r5 + 2] = t5 >>> 16, this[r5 + 3] = t5 >>> 24, r5 + 4;
    }, u$1$1.prototype.writeInt32BE = function(t5, r5, e5) {
      return t5 = +t5, r5 >>>= 0, e5 || C2(this, t5, r5, 4, 2147483647, -2147483648), t5 < 0 && (t5 = 4294967295 + t5 + 1), this[r5] = t5 >>> 24, this[r5 + 1] = t5 >>> 16, this[r5 + 2] = t5 >>> 8, this[r5 + 3] = 255 & t5, r5 + 4;
    }, u$1$1.prototype.writeFloatLE = function(t5, r5, e5) {
      return k2(this, t5, r5, true, e5);
    }, u$1$1.prototype.writeFloatBE = function(t5, r5, e5) {
      return k2(this, t5, r5, false, e5);
    }, u$1$1.prototype.writeDoubleLE = function(t5, r5, e5) {
      return M2(this, t5, r5, true, e5);
    }, u$1$1.prototype.writeDoubleBE = function(t5, r5, e5) {
      return M2(this, t5, r5, false, e5);
    }, u$1$1.prototype.copy = function(t5, r5, e5, n5) {
      if (!u$1$1.isBuffer(t5)) throw new TypeError("argument should be a Buffer");
      if (e5 || (e5 = 0), n5 || 0 === n5 || (n5 = this.length), r5 >= t5.length && (r5 = t5.length), r5 || (r5 = 0), n5 > 0 && n5 < e5 && (n5 = e5), n5 === e5) return 0;
      if (0 === t5.length || 0 === this.length) return 0;
      if (r5 < 0) throw new RangeError("targetStart out of bounds");
      if (e5 < 0 || e5 >= this.length) throw new RangeError("Index out of range");
      if (n5 < 0) throw new RangeError("sourceEnd out of bounds");
      n5 > this.length && (n5 = this.length), t5.length - r5 < n5 - e5 && (n5 = t5.length - r5 + e5);
      var i6 = n5 - e5;
      if (this === t5 && "function" == typeof Uint8Array.prototype.copyWithin) this.copyWithin(r5, e5, n5);
      else if (this === t5 && e5 < r5 && r5 < n5) for (var o5 = i6 - 1; o5 >= 0; --o5) t5[o5 + r5] = this[o5 + e5];
      else Uint8Array.prototype.set.call(t5, this.subarray(e5, n5), r5);
      return i6;
    }, u$1$1.prototype.fill = function(t5, r5, e5, n5) {
      if ("string" == typeof t5) {
        if ("string" == typeof r5 ? (n5 = r5, r5 = 0, e5 = this.length) : "string" == typeof e5 && (n5 = e5, e5 = this.length), void 0 !== n5 && "string" != typeof n5) throw new TypeError("encoding must be a string");
        if ("string" == typeof n5 && !u$1$1.isEncoding(n5)) throw new TypeError("Unknown encoding: " + n5);
        if (1 === t5.length) {
          var i6 = t5.charCodeAt(0);
          ("utf8" === n5 && i6 < 128 || "latin1" === n5) && (t5 = i6);
        }
      } else "number" == typeof t5 ? t5 &= 255 : "boolean" == typeof t5 && (t5 = Number(t5));
      if (r5 < 0 || this.length < r5 || this.length < e5) throw new RangeError("Out of range index");
      if (e5 <= r5) return this;
      var o5;
      if (r5 >>>= 0, e5 = void 0 === e5 ? this.length : e5 >>> 0, t5 || (t5 = 0), "number" == typeof t5) for (o5 = r5; o5 < e5; ++o5) this[o5] = t5;
      else {
        var f5 = u$1$1.isBuffer(t5) ? t5 : u$1$1.from(t5, n5), s5 = f5.length;
        if (0 === s5) throw new TypeError('The value "' + t5 + '" is invalid for argument "value"');
        for (o5 = 0; o5 < e5 - r5; ++o5) this[o5 + r5] = f5[o5 % s5];
      }
      return this;
    };
    j2 = /[^+/0-9A-Za-z-_]/g;
    Y2 = (function() {
      for (var t5 = new Array(256), r5 = 0; r5 < 16; ++r5) for (var e5 = 16 * r5, n5 = 0; n5 < 16; ++n5) t5[e5 + n5] = "0123456789abcdef"[r5] + "0123456789abcdef"[n5];
      return t5;
    })();
    e$1$1.Buffer;
    e$1$1.INSPECT_MAX_BYTES;
    e$1$1.kMaxLength;
    e4 = {};
    n4 = e$1$1;
    o4 = n4.Buffer;
    o4.from && o4.alloc && o4.allocUnsafe && o4.allocUnsafeSlow ? e4 = n4 : (t4(n4, e4), e4.Buffer = f4), f4.prototype = Object.create(o4.prototype), t4(o4, f4), f4.from = function(r5, e5, n5) {
      if ("number" == typeof r5) throw new TypeError("Argument must not be a number");
      return o4(r5, e5, n5);
    }, f4.alloc = function(r5, e5, n5) {
      if ("number" != typeof r5) throw new TypeError("Argument must be a number");
      var t5 = o4(r5);
      return void 0 !== e5 ? "string" == typeof n5 ? t5.fill(e5, n5) : t5.fill(e5) : t5.fill(0), t5;
    }, f4.allocUnsafe = function(r5) {
      if ("number" != typeof r5) throw new TypeError("Argument must be a number");
      return o4(r5);
    }, f4.allocUnsafeSlow = function(r5) {
      if ("number" != typeof r5) throw new TypeError("Argument must be a number");
      return n4.SlowBuffer(r5);
    };
    u4 = e4;
    e$12 = {};
    s4 = u4.Buffer;
    i5 = s4.isEncoding || function(t5) {
      switch ((t5 = "" + t5) && t5.toLowerCase()) {
        case "hex":
        case "utf8":
        case "utf-8":
        case "ascii":
        case "binary":
        case "base64":
        case "ucs2":
        case "ucs-2":
        case "utf16le":
        case "utf-16le":
        case "raw":
          return true;
        default:
          return false;
      }
    };
    e$12.StringDecoder = a4, a4.prototype.write = function(t5) {
      if (0 === t5.length) return "";
      var e5, s5;
      if (this.lastNeed) {
        if (void 0 === (e5 = this.fillLast(t5))) return "";
        s5 = this.lastNeed, this.lastNeed = 0;
      } else s5 = 0;
      return s5 < t5.length ? e5 ? e5 + this.text(t5, s5) : this.text(t5, s5) : e5 || "";
    }, a4.prototype.end = function(t5) {
      var e5 = t5 && t5.length ? this.write(t5) : "";
      return this.lastNeed ? e5 + "\uFFFD" : e5;
    }, a4.prototype.text = function(t5, e5) {
      var s5 = (function(t6, e6, s6) {
        var i7 = e6.length - 1;
        if (i7 < s6) return 0;
        var a5 = r4(e6[i7]);
        if (a5 >= 0) return a5 > 0 && (t6.lastNeed = a5 - 1), a5;
        if (--i7 < s6 || -2 === a5) return 0;
        if ((a5 = r4(e6[i7])) >= 0) return a5 > 0 && (t6.lastNeed = a5 - 2), a5;
        if (--i7 < s6 || -2 === a5) return 0;
        if ((a5 = r4(e6[i7])) >= 0) return a5 > 0 && (2 === a5 ? a5 = 0 : t6.lastNeed = a5 - 3), a5;
        return 0;
      })(this, t5, e5);
      if (!this.lastNeed) return t5.toString("utf8", e5);
      this.lastTotal = s5;
      var i6 = t5.length - (s5 - this.lastNeed);
      return t5.copy(this.lastChar, 0, i6), t5.toString("utf8", e5, i6);
    }, a4.prototype.fillLast = function(t5) {
      if (this.lastNeed <= t5.length) return t5.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed), this.lastChar.toString(this.encoding, 0, this.lastTotal);
      t5.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, t5.length), this.lastNeed -= t5.length;
    };
    e$12.StringDecoder;
    e$12.StringDecoder;
  }
});

// https://dev.jspm.io/npm:@jspm/core@2.0.1/_/8dc3f476.js
function dew$2$1() {
  if (_dewExec$2$1) return exports$2$1;
  _dewExec$2$1 = true;
  exports$2$1.byteLength = byteLength;
  exports$2$1.toByteArray = toByteArray;
  exports$2$1.fromByteArray = fromByteArray;
  var lookup3 = [];
  var revLookup = [];
  var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array;
  var code5 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  for (var i6 = 0, len = code5.length; i6 < len; ++i6) {
    lookup3[i6] = code5[i6];
    revLookup[code5.charCodeAt(i6)] = i6;
  }
  revLookup["-".charCodeAt(0)] = 62;
  revLookup["_".charCodeAt(0)] = 63;
  function getLens(b64) {
    var len2 = b64.length;
    if (len2 % 4 > 0) {
      throw new Error("Invalid string. Length must be a multiple of 4");
    }
    var validLen = b64.indexOf("=");
    if (validLen === -1) validLen = len2;
    var placeHoldersLen = validLen === len2 ? 0 : 4 - validLen % 4;
    return [validLen, placeHoldersLen];
  }
  function byteLength(b64) {
    var lens = getLens(b64);
    var validLen = lens[0];
    var placeHoldersLen = lens[1];
    return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
  }
  function _byteLength(b64, validLen, placeHoldersLen) {
    return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
  }
  function toByteArray(b64) {
    var tmp;
    var lens = getLens(b64);
    var validLen = lens[0];
    var placeHoldersLen = lens[1];
    var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen));
    var curByte = 0;
    var len2 = placeHoldersLen > 0 ? validLen - 4 : validLen;
    var i7;
    for (i7 = 0; i7 < len2; i7 += 4) {
      tmp = revLookup[b64.charCodeAt(i7)] << 18 | revLookup[b64.charCodeAt(i7 + 1)] << 12 | revLookup[b64.charCodeAt(i7 + 2)] << 6 | revLookup[b64.charCodeAt(i7 + 3)];
      arr[curByte++] = tmp >> 16 & 255;
      arr[curByte++] = tmp >> 8 & 255;
      arr[curByte++] = tmp & 255;
    }
    if (placeHoldersLen === 2) {
      tmp = revLookup[b64.charCodeAt(i7)] << 2 | revLookup[b64.charCodeAt(i7 + 1)] >> 4;
      arr[curByte++] = tmp & 255;
    }
    if (placeHoldersLen === 1) {
      tmp = revLookup[b64.charCodeAt(i7)] << 10 | revLookup[b64.charCodeAt(i7 + 1)] << 4 | revLookup[b64.charCodeAt(i7 + 2)] >> 2;
      arr[curByte++] = tmp >> 8 & 255;
      arr[curByte++] = tmp & 255;
    }
    return arr;
  }
  function tripletToBase64(num) {
    return lookup3[num >> 18 & 63] + lookup3[num >> 12 & 63] + lookup3[num >> 6 & 63] + lookup3[num & 63];
  }
  function encodeChunk(uint8, start, end) {
    var tmp;
    var output = [];
    for (var i7 = start; i7 < end; i7 += 3) {
      tmp = (uint8[i7] << 16 & 16711680) + (uint8[i7 + 1] << 8 & 65280) + (uint8[i7 + 2] & 255);
      output.push(tripletToBase64(tmp));
    }
    return output.join("");
  }
  function fromByteArray(uint8) {
    var tmp;
    var len2 = uint8.length;
    var extraBytes = len2 % 3;
    var parts = [];
    var maxChunkLength = 16383;
    for (var i7 = 0, len22 = len2 - extraBytes; i7 < len22; i7 += maxChunkLength) {
      parts.push(encodeChunk(uint8, i7, i7 + maxChunkLength > len22 ? len22 : i7 + maxChunkLength));
    }
    if (extraBytes === 1) {
      tmp = uint8[len2 - 1];
      parts.push(lookup3[tmp >> 2] + lookup3[tmp << 4 & 63] + "==");
    } else if (extraBytes === 2) {
      tmp = (uint8[len2 - 2] << 8) + uint8[len2 - 1];
      parts.push(lookup3[tmp >> 10] + lookup3[tmp >> 4 & 63] + lookup3[tmp << 2 & 63] + "=");
    }
    return parts.join("");
  }
  return exports$2$1;
}
function dew$1$1() {
  if (_dewExec$1$1) return exports$1$1;
  _dewExec$1$1 = true;
  exports$1$1.read = function(buffer2, offset3, isLE, mLen, nBytes) {
    var e5, m4;
    var eLen = nBytes * 8 - mLen - 1;
    var eMax = (1 << eLen) - 1;
    var eBias = eMax >> 1;
    var nBits = -7;
    var i6 = isLE ? nBytes - 1 : 0;
    var d4 = isLE ? -1 : 1;
    var s5 = buffer2[offset3 + i6];
    i6 += d4;
    e5 = s5 & (1 << -nBits) - 1;
    s5 >>= -nBits;
    nBits += eLen;
    for (; nBits > 0; e5 = e5 * 256 + buffer2[offset3 + i6], i6 += d4, nBits -= 8) {
    }
    m4 = e5 & (1 << -nBits) - 1;
    e5 >>= -nBits;
    nBits += mLen;
    for (; nBits > 0; m4 = m4 * 256 + buffer2[offset3 + i6], i6 += d4, nBits -= 8) {
    }
    if (e5 === 0) {
      e5 = 1 - eBias;
    } else if (e5 === eMax) {
      return m4 ? NaN : (s5 ? -1 : 1) * Infinity;
    } else {
      m4 = m4 + Math.pow(2, mLen);
      e5 = e5 - eBias;
    }
    return (s5 ? -1 : 1) * m4 * Math.pow(2, e5 - mLen);
  };
  exports$1$1.write = function(buffer2, value, offset3, isLE, mLen, nBytes) {
    var e5, m4, c6;
    var eLen = nBytes * 8 - mLen - 1;
    var eMax = (1 << eLen) - 1;
    var eBias = eMax >> 1;
    var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
    var i6 = isLE ? 0 : nBytes - 1;
    var d4 = isLE ? 1 : -1;
    var s5 = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
    value = Math.abs(value);
    if (isNaN(value) || value === Infinity) {
      m4 = isNaN(value) ? 1 : 0;
      e5 = eMax;
    } else {
      e5 = Math.floor(Math.log(value) / Math.LN2);
      if (value * (c6 = Math.pow(2, -e5)) < 1) {
        e5--;
        c6 *= 2;
      }
      if (e5 + eBias >= 1) {
        value += rt / c6;
      } else {
        value += rt * Math.pow(2, 1 - eBias);
      }
      if (value * c6 >= 2) {
        e5++;
        c6 /= 2;
      }
      if (e5 + eBias >= eMax) {
        m4 = 0;
        e5 = eMax;
      } else if (e5 + eBias >= 1) {
        m4 = (value * c6 - 1) * Math.pow(2, mLen);
        e5 = e5 + eBias;
      } else {
        m4 = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
        e5 = 0;
      }
    }
    for (; mLen >= 8; buffer2[offset3 + i6] = m4 & 255, i6 += d4, m4 /= 256, mLen -= 8) {
    }
    e5 = e5 << mLen | m4;
    eLen += mLen;
    for (; eLen > 0; buffer2[offset3 + i6] = e5 & 255, i6 += d4, e5 /= 256, eLen -= 8) {
    }
    buffer2[offset3 + i6 - d4] |= s5 * 128;
  };
  return exports$1$1;
}
function dew$g() {
  if (_dewExec$g) return exports$g;
  _dewExec$g = true;
  const base642 = dew$2$1();
  const ieee754 = dew$1$1();
  const customInspectSymbol = typeof Symbol === "function" && typeof Symbol["for"] === "function" ? Symbol["for"]("nodejs.util.inspect.custom") : null;
  exports$g.Buffer = Buffer4;
  exports$g.SlowBuffer = SlowBuffer;
  exports$g.INSPECT_MAX_BYTES = 50;
  const K_MAX_LENGTH = 2147483647;
  exports$g.kMaxLength = K_MAX_LENGTH;
  Buffer4.TYPED_ARRAY_SUPPORT = typedArraySupport();
  if (!Buffer4.TYPED_ARRAY_SUPPORT && typeof console !== "undefined" && typeof console.error === "function") {
    console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");
  }
  function typedArraySupport() {
    try {
      const arr = new Uint8Array(1);
      const proto2 = {
        foo: function() {
          return 42;
        }
      };
      Object.setPrototypeOf(proto2, Uint8Array.prototype);
      Object.setPrototypeOf(arr, proto2);
      return arr.foo() === 42;
    } catch (e5) {
      return false;
    }
  }
  Object.defineProperty(Buffer4.prototype, "parent", {
    enumerable: true,
    get: function() {
      if (!Buffer4.isBuffer(this)) return void 0;
      return this.buffer;
    }
  });
  Object.defineProperty(Buffer4.prototype, "offset", {
    enumerable: true,
    get: function() {
      if (!Buffer4.isBuffer(this)) return void 0;
      return this.byteOffset;
    }
  });
  function createBuffer(length) {
    if (length > K_MAX_LENGTH) {
      throw new RangeError('The value "' + length + '" is invalid for option "size"');
    }
    const buf = new Uint8Array(length);
    Object.setPrototypeOf(buf, Buffer4.prototype);
    return buf;
  }
  function Buffer4(arg, encodingOrOffset, length) {
    if (typeof arg === "number") {
      if (typeof encodingOrOffset === "string") {
        throw new TypeError('The "string" argument must be of type string. Received type number');
      }
      return allocUnsafe(arg);
    }
    return from(arg, encodingOrOffset, length);
  }
  Buffer4.poolSize = 8192;
  function from(value, encodingOrOffset, length) {
    if (typeof value === "string") {
      return fromString(value, encodingOrOffset);
    }
    if (ArrayBuffer.isView(value)) {
      return fromArrayView(value);
    }
    if (value == null) {
      throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value);
    }
    if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) {
      return fromArrayBuffer(value, encodingOrOffset, length);
    }
    if (typeof SharedArrayBuffer !== "undefined" && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer))) {
      return fromArrayBuffer(value, encodingOrOffset, length);
    }
    if (typeof value === "number") {
      throw new TypeError('The "value" argument must not be of type number. Received type number');
    }
    const valueOf = value.valueOf && value.valueOf();
    if (valueOf != null && valueOf !== value) {
      return Buffer4.from(valueOf, encodingOrOffset, length);
    }
    const b3 = fromObject(value);
    if (b3) return b3;
    if (typeof Symbol !== "undefined" && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === "function") {
      return Buffer4.from(value[Symbol.toPrimitive]("string"), encodingOrOffset, length);
    }
    throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value);
  }
  Buffer4.from = function(value, encodingOrOffset, length) {
    return from(value, encodingOrOffset, length);
  };
  Object.setPrototypeOf(Buffer4.prototype, Uint8Array.prototype);
  Object.setPrototypeOf(Buffer4, Uint8Array);
  function assertSize(size) {
    if (typeof size !== "number") {
      throw new TypeError('"size" argument must be of type number');
    } else if (size < 0) {
      throw new RangeError('The value "' + size + '" is invalid for option "size"');
    }
  }
  function alloc(size, fill, encoding) {
    assertSize(size);
    if (size <= 0) {
      return createBuffer(size);
    }
    if (fill !== void 0) {
      return typeof encoding === "string" ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill);
    }
    return createBuffer(size);
  }
  Buffer4.alloc = function(size, fill, encoding) {
    return alloc(size, fill, encoding);
  };
  function allocUnsafe(size) {
    assertSize(size);
    return createBuffer(size < 0 ? 0 : checked(size) | 0);
  }
  Buffer4.allocUnsafe = function(size) {
    return allocUnsafe(size);
  };
  Buffer4.allocUnsafeSlow = function(size) {
    return allocUnsafe(size);
  };
  function fromString(string2, encoding) {
    if (typeof encoding !== "string" || encoding === "") {
      encoding = "utf8";
    }
    if (!Buffer4.isEncoding(encoding)) {
      throw new TypeError("Unknown encoding: " + encoding);
    }
    const length = byteLength(string2, encoding) | 0;
    let buf = createBuffer(length);
    const actual = buf.write(string2, encoding);
    if (actual !== length) {
      buf = buf.slice(0, actual);
    }
    return buf;
  }
  function fromArrayLike(array) {
    const length = array.length < 0 ? 0 : checked(array.length) | 0;
    const buf = createBuffer(length);
    for (let i6 = 0; i6 < length; i6 += 1) {
      buf[i6] = array[i6] & 255;
    }
    return buf;
  }
  function fromArrayView(arrayView) {
    if (isInstance(arrayView, Uint8Array)) {
      const copy6 = new Uint8Array(arrayView);
      return fromArrayBuffer(copy6.buffer, copy6.byteOffset, copy6.byteLength);
    }
    return fromArrayLike(arrayView);
  }
  function fromArrayBuffer(array, byteOffset, length) {
    if (byteOffset < 0 || array.byteLength < byteOffset) {
      throw new RangeError('"offset" is outside of buffer bounds');
    }
    if (array.byteLength < byteOffset + (length || 0)) {
      throw new RangeError('"length" is outside of buffer bounds');
    }
    let buf;
    if (byteOffset === void 0 && length === void 0) {
      buf = new Uint8Array(array);
    } else if (length === void 0) {
      buf = new Uint8Array(array, byteOffset);
    } else {
      buf = new Uint8Array(array, byteOffset, length);
    }
    Object.setPrototypeOf(buf, Buffer4.prototype);
    return buf;
  }
  function fromObject(obj) {
    if (Buffer4.isBuffer(obj)) {
      const len = checked(obj.length) | 0;
      const buf = createBuffer(len);
      if (buf.length === 0) {
        return buf;
      }
      obj.copy(buf, 0, 0, len);
      return buf;
    }
    if (obj.length !== void 0) {
      if (typeof obj.length !== "number" || numberIsNaN(obj.length)) {
        return createBuffer(0);
      }
      return fromArrayLike(obj);
    }
    if (obj.type === "Buffer" && Array.isArray(obj.data)) {
      return fromArrayLike(obj.data);
    }
  }
  function checked(length) {
    if (length >= K_MAX_LENGTH) {
      throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + K_MAX_LENGTH.toString(16) + " bytes");
    }
    return length | 0;
  }
  function SlowBuffer(length) {
    if (+length != length) {
      length = 0;
    }
    return Buffer4.alloc(+length);
  }
  Buffer4.isBuffer = function isBuffer3(b3) {
    return b3 != null && b3._isBuffer === true && b3 !== Buffer4.prototype;
  };
  Buffer4.compare = function compare2(a5, b3) {
    if (isInstance(a5, Uint8Array)) a5 = Buffer4.from(a5, a5.offset, a5.byteLength);
    if (isInstance(b3, Uint8Array)) b3 = Buffer4.from(b3, b3.offset, b3.byteLength);
    if (!Buffer4.isBuffer(a5) || !Buffer4.isBuffer(b3)) {
      throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');
    }
    if (a5 === b3) return 0;
    let x3 = a5.length;
    let y4 = b3.length;
    for (let i6 = 0, len = Math.min(x3, y4); i6 < len; ++i6) {
      if (a5[i6] !== b3[i6]) {
        x3 = a5[i6];
        y4 = b3[i6];
        break;
      }
    }
    if (x3 < y4) return -1;
    if (y4 < x3) return 1;
    return 0;
  };
  Buffer4.isEncoding = function isEncoding(encoding) {
    switch (String(encoding).toLowerCase()) {
      case "hex":
      case "utf8":
      case "utf-8":
      case "ascii":
      case "latin1":
      case "binary":
      case "base64":
      case "ucs2":
      case "ucs-2":
      case "utf16le":
      case "utf-16le":
        return true;
      default:
        return false;
    }
  };
  Buffer4.concat = function concat3(list, length) {
    if (!Array.isArray(list)) {
      throw new TypeError('"list" argument must be an Array of Buffers');
    }
    if (list.length === 0) {
      return Buffer4.alloc(0);
    }
    let i6;
    if (length === void 0) {
      length = 0;
      for (i6 = 0; i6 < list.length; ++i6) {
        length += list[i6].length;
      }
    }
    const buffer2 = Buffer4.allocUnsafe(length);
    let pos = 0;
    for (i6 = 0; i6 < list.length; ++i6) {
      let buf = list[i6];
      if (isInstance(buf, Uint8Array)) {
        if (pos + buf.length > buffer2.length) {
          if (!Buffer4.isBuffer(buf)) buf = Buffer4.from(buf);
          buf.copy(buffer2, pos);
        } else {
          Uint8Array.prototype.set.call(buffer2, buf, pos);
        }
      } else if (!Buffer4.isBuffer(buf)) {
        throw new TypeError('"list" argument must be an Array of Buffers');
      } else {
        buf.copy(buffer2, pos);
      }
      pos += buf.length;
    }
    return buffer2;
  };
  function byteLength(string2, encoding) {
    if (Buffer4.isBuffer(string2)) {
      return string2.length;
    }
    if (ArrayBuffer.isView(string2) || isInstance(string2, ArrayBuffer)) {
      return string2.byteLength;
    }
    if (typeof string2 !== "string") {
      throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof string2);
    }
    const len = string2.length;
    const mustMatch = arguments.length > 2 && arguments[2] === true;
    if (!mustMatch && len === 0) return 0;
    let loweredCase = false;
    for (; ; ) {
      switch (encoding) {
        case "ascii":
        case "latin1":
        case "binary":
          return len;
        case "utf8":
        case "utf-8":
          return utf8ToBytes(string2).length;
        case "ucs2":
        case "ucs-2":
        case "utf16le":
        case "utf-16le":
          return len * 2;
        case "hex":
          return len >>> 1;
        case "base64":
          return base64ToBytes(string2).length;
        default:
          if (loweredCase) {
            return mustMatch ? -1 : utf8ToBytes(string2).length;
          }
          encoding = ("" + encoding).toLowerCase();
          loweredCase = true;
      }
    }
  }
  Buffer4.byteLength = byteLength;
  function slowToString(encoding, start, end) {
    let loweredCase = false;
    if (start === void 0 || start < 0) {
      start = 0;
    }
    if (start > this.length) {
      return "";
    }
    if (end === void 0 || end > this.length) {
      end = this.length;
    }
    if (end <= 0) {
      return "";
    }
    end >>>= 0;
    start >>>= 0;
    if (end <= start) {
      return "";
    }
    if (!encoding) encoding = "utf8";
    while (true) {
      switch (encoding) {
        case "hex":
          return hexSlice(this, start, end);
        case "utf8":
        case "utf-8":
          return utf8Slice(this, start, end);
        case "ascii":
          return asciiSlice(this, start, end);
        case "latin1":
        case "binary":
          return latin1Slice(this, start, end);
        case "base64":
          return base64Slice(this, start, end);
        case "ucs2":
        case "ucs-2":
        case "utf16le":
        case "utf-16le":
          return utf16leSlice(this, start, end);
        default:
          if (loweredCase) throw new TypeError("Unknown encoding: " + encoding);
          encoding = (encoding + "").toLowerCase();
          loweredCase = true;
      }
    }
  }
  Buffer4.prototype._isBuffer = true;
  function swap(b3, n5, m4) {
    const i6 = b3[n5];
    b3[n5] = b3[m4];
    b3[m4] = i6;
  }
  Buffer4.prototype.swap16 = function swap16() {
    const len = this.length;
    if (len % 2 !== 0) {
      throw new RangeError("Buffer size must be a multiple of 16-bits");
    }
    for (let i6 = 0; i6 < len; i6 += 2) {
      swap(this, i6, i6 + 1);
    }
    return this;
  };
  Buffer4.prototype.swap32 = function swap32() {
    const len = this.length;
    if (len % 4 !== 0) {
      throw new RangeError("Buffer size must be a multiple of 32-bits");
    }
    for (let i6 = 0; i6 < len; i6 += 4) {
      swap(this, i6, i6 + 3);
      swap(this, i6 + 1, i6 + 2);
    }
    return this;
  };
  Buffer4.prototype.swap64 = function swap64() {
    const len = this.length;
    if (len % 8 !== 0) {
      throw new RangeError("Buffer size must be a multiple of 64-bits");
    }
    for (let i6 = 0; i6 < len; i6 += 8) {
      swap(this, i6, i6 + 7);
      swap(this, i6 + 1, i6 + 6);
      swap(this, i6 + 2, i6 + 5);
      swap(this, i6 + 3, i6 + 4);
    }
    return this;
  };
  Buffer4.prototype.toString = function toString8() {
    const length = this.length;
    if (length === 0) return "";
    if (arguments.length === 0) return utf8Slice(this, 0, length);
    return slowToString.apply(this, arguments);
  };
  Buffer4.prototype.toLocaleString = Buffer4.prototype.toString;
  Buffer4.prototype.equals = function equals2(b3) {
    if (!Buffer4.isBuffer(b3)) throw new TypeError("Argument must be a Buffer");
    if (this === b3) return true;
    return Buffer4.compare(this, b3) === 0;
  };
  Buffer4.prototype.inspect = function inspect4() {
    let str3 = "";
    const max = exports$g.INSPECT_MAX_BYTES;
    str3 = this.toString("hex", 0, max).replace(/(.{2})/g, "$1 ").trim();
    if (this.length > max) str3 += " ... ";
    return "<Buffer " + str3 + ">";
  };
  if (customInspectSymbol) {
    Buffer4.prototype[customInspectSymbol] = Buffer4.prototype.inspect;
  }
  Buffer4.prototype.compare = function compare2(target, start, end, thisStart, thisEnd) {
    if (isInstance(target, Uint8Array)) {
      target = Buffer4.from(target, target.offset, target.byteLength);
    }
    if (!Buffer4.isBuffer(target)) {
      throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof target);
    }
    if (start === void 0) {
      start = 0;
    }
    if (end === void 0) {
      end = target ? target.length : 0;
    }
    if (thisStart === void 0) {
      thisStart = 0;
    }
    if (thisEnd === void 0) {
      thisEnd = this.length;
    }
    if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
      throw new RangeError("out of range index");
    }
    if (thisStart >= thisEnd && start >= end) {
      return 0;
    }
    if (thisStart >= thisEnd) {
      return -1;
    }
    if (start >= end) {
      return 1;
    }
    start >>>= 0;
    end >>>= 0;
    thisStart >>>= 0;
    thisEnd >>>= 0;
    if (this === target) return 0;
    let x3 = thisEnd - thisStart;
    let y4 = end - start;
    const len = Math.min(x3, y4);
    const thisCopy = this.slice(thisStart, thisEnd);
    const targetCopy = target.slice(start, end);
    for (let i6 = 0; i6 < len; ++i6) {
      if (thisCopy[i6] !== targetCopy[i6]) {
        x3 = thisCopy[i6];
        y4 = targetCopy[i6];
        break;
      }
    }
    if (x3 < y4) return -1;
    if (y4 < x3) return 1;
    return 0;
  };
  function bidirectionalIndexOf(buffer2, val, byteOffset, encoding, dir) {
    if (buffer2.length === 0) return -1;
    if (typeof byteOffset === "string") {
      encoding = byteOffset;
      byteOffset = 0;
    } else if (byteOffset > 2147483647) {
      byteOffset = 2147483647;
    } else if (byteOffset < -2147483648) {
      byteOffset = -2147483648;
    }
    byteOffset = +byteOffset;
    if (numberIsNaN(byteOffset)) {
      byteOffset = dir ? 0 : buffer2.length - 1;
    }
    if (byteOffset < 0) byteOffset = buffer2.length + byteOffset;
    if (byteOffset >= buffer2.length) {
      if (dir) return -1;
      else byteOffset = buffer2.length - 1;
    } else if (byteOffset < 0) {
      if (dir) byteOffset = 0;
      else return -1;
    }
    if (typeof val === "string") {
      val = Buffer4.from(val, encoding);
    }
    if (Buffer4.isBuffer(val)) {
      if (val.length === 0) {
        return -1;
      }
      return arrayIndexOf(buffer2, val, byteOffset, encoding, dir);
    } else if (typeof val === "number") {
      val = val & 255;
      if (typeof Uint8Array.prototype.indexOf === "function") {
        if (dir) {
          return Uint8Array.prototype.indexOf.call(buffer2, val, byteOffset);
        } else {
          return Uint8Array.prototype.lastIndexOf.call(buffer2, val, byteOffset);
        }
      }
      return arrayIndexOf(buffer2, [val], byteOffset, encoding, dir);
    }
    throw new TypeError("val must be string, number or Buffer");
  }
  function arrayIndexOf(arr, val, byteOffset, encoding, dir) {
    let indexSize = 1;
    let arrLength = arr.length;
    let valLength = val.length;
    if (encoding !== void 0) {
      encoding = String(encoding).toLowerCase();
      if (encoding === "ucs2" || encoding === "ucs-2" || encoding === "utf16le" || encoding === "utf-16le") {
        if (arr.length < 2 || val.length < 2) {
          return -1;
        }
        indexSize = 2;
        arrLength /= 2;
        valLength /= 2;
        byteOffset /= 2;
      }
    }
    function read(buf, i7) {
      if (indexSize === 1) {
        return buf[i7];
      } else {
        return buf.readUInt16BE(i7 * indexSize);
      }
    }
    let i6;
    if (dir) {
      let foundIndex = -1;
      for (i6 = byteOffset; i6 < arrLength; i6++) {
        if (read(arr, i6) === read(val, foundIndex === -1 ? 0 : i6 - foundIndex)) {
          if (foundIndex === -1) foundIndex = i6;
          if (i6 - foundIndex + 1 === valLength) return foundIndex * indexSize;
        } else {
          if (foundIndex !== -1) i6 -= i6 - foundIndex;
          foundIndex = -1;
        }
      }
    } else {
      if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
      for (i6 = byteOffset; i6 >= 0; i6--) {
        let found = true;
        for (let j3 = 0; j3 < valLength; j3++) {
          if (read(arr, i6 + j3) !== read(val, j3)) {
            found = false;
            break;
          }
        }
        if (found) return i6;
      }
    }
    return -1;
  }
  Buffer4.prototype.includes = function includes(val, byteOffset, encoding) {
    return this.indexOf(val, byteOffset, encoding) !== -1;
  };
  Buffer4.prototype.indexOf = function indexOf2(val, byteOffset, encoding) {
    return bidirectionalIndexOf(this, val, byteOffset, encoding, true);
  };
  Buffer4.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) {
    return bidirectionalIndexOf(this, val, byteOffset, encoding, false);
  };
  function hexWrite(buf, string2, offset3, length) {
    offset3 = Number(offset3) || 0;
    const remaining = buf.length - offset3;
    if (!length) {
      length = remaining;
    } else {
      length = Number(length);
      if (length > remaining) {
        length = remaining;
      }
    }
    const strLen = string2.length;
    if (length > strLen / 2) {
      length = strLen / 2;
    }
    let i6;
    for (i6 = 0; i6 < length; ++i6) {
      const parsed = parseInt(string2.substr(i6 * 2, 2), 16);
      if (numberIsNaN(parsed)) return i6;
      buf[offset3 + i6] = parsed;
    }
    return i6;
  }
  function utf8Write(buf, string2, offset3, length) {
    return blitBuffer(utf8ToBytes(string2, buf.length - offset3), buf, offset3, length);
  }
  function asciiWrite(buf, string2, offset3, length) {
    return blitBuffer(asciiToBytes(string2), buf, offset3, length);
  }
  function base64Write(buf, string2, offset3, length) {
    return blitBuffer(base64ToBytes(string2), buf, offset3, length);
  }
  function ucs2Write(buf, string2, offset3, length) {
    return blitBuffer(utf16leToBytes(string2, buf.length - offset3), buf, offset3, length);
  }
  Buffer4.prototype.write = function write(string2, offset3, length, encoding) {
    if (offset3 === void 0) {
      encoding = "utf8";
      length = this.length;
      offset3 = 0;
    } else if (length === void 0 && typeof offset3 === "string") {
      encoding = offset3;
      length = this.length;
      offset3 = 0;
    } else if (isFinite(offset3)) {
      offset3 = offset3 >>> 0;
      if (isFinite(length)) {
        length = length >>> 0;
        if (encoding === void 0) encoding = "utf8";
      } else {
        encoding = length;
        length = void 0;
      }
    } else {
      throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");
    }
    const remaining = this.length - offset3;
    if (length === void 0 || length > remaining) length = remaining;
    if (string2.length > 0 && (length < 0 || offset3 < 0) || offset3 > this.length) {
      throw new RangeError("Attempt to write outside buffer bounds");
    }
    if (!encoding) encoding = "utf8";
    let loweredCase = false;
    for (; ; ) {
      switch (encoding) {
        case "hex":
          return hexWrite(this, string2, offset3, length);
        case "utf8":
        case "utf-8":
          return utf8Write(this, string2, offset3, length);
        case "ascii":
        case "latin1":
        case "binary":
          return asciiWrite(this, string2, offset3, length);
        case "base64":
          return base64Write(this, string2, offset3, length);
        case "ucs2":
        case "ucs-2":
        case "utf16le":
        case "utf-16le":
          return ucs2Write(this, string2, offset3, length);
        default:
          if (loweredCase) throw new TypeError("Unknown encoding: " + encoding);
          encoding = ("" + encoding).toLowerCase();
          loweredCase = true;
      }
    }
  };
  Buffer4.prototype.toJSON = function toJSON() {
    return {
      type: "Buffer",
      data: Array.prototype.slice.call(this._arr || this, 0)
    };
  };
  function base64Slice(buf, start, end) {
    if (start === 0 && end === buf.length) {
      return base642.fromByteArray(buf);
    } else {
      return base642.fromByteArray(buf.slice(start, end));
    }
  }
  function utf8Slice(buf, start, end) {
    end = Math.min(buf.length, end);
    const res = [];
    let i6 = start;
    while (i6 < end) {
      const firstByte = buf[i6];
      let codePoint = null;
      let bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1;
      if (i6 + bytesPerSequence <= end) {
        let secondByte, thirdByte, fourthByte, tempCodePoint;
        switch (bytesPerSequence) {
          case 1:
            if (firstByte < 128) {
              codePoint = firstByte;
            }
            break;
          case 2:
            secondByte = buf[i6 + 1];
            if ((secondByte & 192) === 128) {
              tempCodePoint = (firstByte & 31) << 6 | secondByte & 63;
              if (tempCodePoint > 127) {
                codePoint = tempCodePoint;
              }
            }
            break;
          case 3:
            secondByte = buf[i6 + 1];
            thirdByte = buf[i6 + 2];
            if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) {
              tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63;
              if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) {
                codePoint = tempCodePoint;
              }
            }
            break;
          case 4:
            secondByte = buf[i6 + 1];
            thirdByte = buf[i6 + 2];
            fourthByte = buf[i6 + 3];
            if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) {
              tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63;
              if (tempCodePoint > 65535 && tempCodePoint < 1114112) {
                codePoint = tempCodePoint;
              }
            }
        }
      }
      if (codePoint === null) {
        codePoint = 65533;
        bytesPerSequence = 1;
      } else if (codePoint > 65535) {
        codePoint -= 65536;
        res.push(codePoint >>> 10 & 1023 | 55296);
        codePoint = 56320 | codePoint & 1023;
      }
      res.push(codePoint);
      i6 += bytesPerSequence;
    }
    return decodeCodePointsArray(res);
  }
  const MAX_ARGUMENTS_LENGTH = 4096;
  function decodeCodePointsArray(codePoints) {
    const len = codePoints.length;
    if (len <= MAX_ARGUMENTS_LENGTH) {
      return String.fromCharCode.apply(String, codePoints);
    }
    let res = "";
    let i6 = 0;
    while (i6 < len) {
      res += String.fromCharCode.apply(String, codePoints.slice(i6, i6 += MAX_ARGUMENTS_LENGTH));
    }
    return res;
  }
  function asciiSlice(buf, start, end) {
    let ret = "";
    end = Math.min(buf.length, end);
    for (let i6 = start; i6 < end; ++i6) {
      ret += String.fromCharCode(buf[i6] & 127);
    }
    return ret;
  }
  function latin1Slice(buf, start, end) {
    let ret = "";
    end = Math.min(buf.length, end);
    for (let i6 = start; i6 < end; ++i6) {
      ret += String.fromCharCode(buf[i6]);
    }
    return ret;
  }
  function hexSlice(buf, start, end) {
    const len = buf.length;
    if (!start || start < 0) start = 0;
    if (!end || end < 0 || end > len) end = len;
    let out = "";
    for (let i6 = start; i6 < end; ++i6) {
      out += hexSliceLookupTable[buf[i6]];
    }
    return out;
  }
  function utf16leSlice(buf, start, end) {
    const bytes = buf.slice(start, end);
    let res = "";
    for (let i6 = 0; i6 < bytes.length - 1; i6 += 2) {
      res += String.fromCharCode(bytes[i6] + bytes[i6 + 1] * 256);
    }
    return res;
  }
  Buffer4.prototype.slice = function slice2(start, end) {
    const len = this.length;
    start = ~~start;
    end = end === void 0 ? len : ~~end;
    if (start < 0) {
      start += len;
      if (start < 0) start = 0;
    } else if (start > len) {
      start = len;
    }
    if (end < 0) {
      end += len;
      if (end < 0) end = 0;
    } else if (end > len) {
      end = len;
    }
    if (end < start) end = start;
    const newBuf = this.subarray(start, end);
    Object.setPrototypeOf(newBuf, Buffer4.prototype);
    return newBuf;
  };
  function checkOffset(offset3, ext, length) {
    if (offset3 % 1 !== 0 || offset3 < 0) throw new RangeError("offset is not uint");
    if (offset3 + ext > length) throw new RangeError("Trying to access beyond buffer length");
  }
  Buffer4.prototype.readUintLE = Buffer4.prototype.readUIntLE = function readUIntLE(offset3, byteLength2, noAssert) {
    offset3 = offset3 >>> 0;
    byteLength2 = byteLength2 >>> 0;
    if (!noAssert) checkOffset(offset3, byteLength2, this.length);
    let val = this[offset3];
    let mul = 1;
    let i6 = 0;
    while (++i6 < byteLength2 && (mul *= 256)) {
      val += this[offset3 + i6] * mul;
    }
    return val;
  };
  Buffer4.prototype.readUintBE = Buffer4.prototype.readUIntBE = function readUIntBE(offset3, byteLength2, noAssert) {
    offset3 = offset3 >>> 0;
    byteLength2 = byteLength2 >>> 0;
    if (!noAssert) {
      checkOffset(offset3, byteLength2, this.length);
    }
    let val = this[offset3 + --byteLength2];
    let mul = 1;
    while (byteLength2 > 0 && (mul *= 256)) {
      val += this[offset3 + --byteLength2] * mul;
    }
    return val;
  };
  Buffer4.prototype.readUint8 = Buffer4.prototype.readUInt8 = function readUInt8(offset3, noAssert) {
    offset3 = offset3 >>> 0;
    if (!noAssert) checkOffset(offset3, 1, this.length);
    return this[offset3];
  };
  Buffer4.prototype.readUint16LE = Buffer4.prototype.readUInt16LE = function readUInt16LE(offset3, noAssert) {
    offset3 = offset3 >>> 0;
    if (!noAssert) checkOffset(offset3, 2, this.length);
    return this[offset3] | this[offset3 + 1] << 8;
  };
  Buffer4.prototype.readUint16BE = Buffer4.prototype.readUInt16BE = function readUInt16BE(offset3, noAssert) {
    offset3 = offset3 >>> 0;
    if (!noAssert) checkOffset(offset3, 2, this.length);
    return this[offset3] << 8 | this[offset3 + 1];
  };
  Buffer4.prototype.readUint32LE = Buffer4.prototype.readUInt32LE = function readUInt32LE(offset3, noAssert) {
    offset3 = offset3 >>> 0;
    if (!noAssert) checkOffset(offset3, 4, this.length);
    return (this[offset3] | this[offset3 + 1] << 8 | this[offset3 + 2] << 16) + this[offset3 + 3] * 16777216;
  };
  Buffer4.prototype.readUint32BE = Buffer4.prototype.readUInt32BE = function readUInt32BE(offset3, noAssert) {
    offset3 = offset3 >>> 0;
    if (!noAssert) checkOffset(offset3, 4, this.length);
    return this[offset3] * 16777216 + (this[offset3 + 1] << 16 | this[offset3 + 2] << 8 | this[offset3 + 3]);
  };
  Buffer4.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE(offset3) {
    offset3 = offset3 >>> 0;
    validateNumber2(offset3, "offset");
    const first = this[offset3];
    const last = this[offset3 + 7];
    if (first === void 0 || last === void 0) {
      boundsError(offset3, this.length - 8);
    }
    const lo = first + this[++offset3] * 2 ** 8 + this[++offset3] * 2 ** 16 + this[++offset3] * 2 ** 24;
    const hi = this[++offset3] + this[++offset3] * 2 ** 8 + this[++offset3] * 2 ** 16 + last * 2 ** 24;
    return BigInt(lo) + (BigInt(hi) << BigInt(32));
  });
  Buffer4.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE(offset3) {
    offset3 = offset3 >>> 0;
    validateNumber2(offset3, "offset");
    const first = this[offset3];
    const last = this[offset3 + 7];
    if (first === void 0 || last === void 0) {
      boundsError(offset3, this.length - 8);
    }
    const hi = first * 2 ** 24 + this[++offset3] * 2 ** 16 + this[++offset3] * 2 ** 8 + this[++offset3];
    const lo = this[++offset3] * 2 ** 24 + this[++offset3] * 2 ** 16 + this[++offset3] * 2 ** 8 + last;
    return (BigInt(hi) << BigInt(32)) + BigInt(lo);
  });
  Buffer4.prototype.readIntLE = function readIntLE(offset3, byteLength2, noAssert) {
    offset3 = offset3 >>> 0;
    byteLength2 = byteLength2 >>> 0;
    if (!noAssert) checkOffset(offset3, byteLength2, this.length);
    let val = this[offset3];
    let mul = 1;
    let i6 = 0;
    while (++i6 < byteLength2 && (mul *= 256)) {
      val += this[offset3 + i6] * mul;
    }
    mul *= 128;
    if (val >= mul) val -= Math.pow(2, 8 * byteLength2);
    return val;
  };
  Buffer4.prototype.readIntBE = function readIntBE(offset3, byteLength2, noAssert) {
    offset3 = offset3 >>> 0;
    byteLength2 = byteLength2 >>> 0;
    if (!noAssert) checkOffset(offset3, byteLength2, this.length);
    let i6 = byteLength2;
    let mul = 1;
    let val = this[offset3 + --i6];
    while (i6 > 0 && (mul *= 256)) {
      val += this[offset3 + --i6] * mul;
    }
    mul *= 128;
    if (val >= mul) val -= Math.pow(2, 8 * byteLength2);
    return val;
  };
  Buffer4.prototype.readInt8 = function readInt8(offset3, noAssert) {
    offset3 = offset3 >>> 0;
    if (!noAssert) checkOffset(offset3, 1, this.length);
    if (!(this[offset3] & 128)) return this[offset3];
    return (255 - this[offset3] + 1) * -1;
  };
  Buffer4.prototype.readInt16LE = function readInt16LE(offset3, noAssert) {
    offset3 = offset3 >>> 0;
    if (!noAssert) checkOffset(offset3, 2, this.length);
    const val = this[offset3] | this[offset3 + 1] << 8;
    return val & 32768 ? val | 4294901760 : val;
  };
  Buffer4.prototype.readInt16BE = function readInt16BE(offset3, noAssert) {
    offset3 = offset3 >>> 0;
    if (!noAssert) checkOffset(offset3, 2, this.length);
    const val = this[offset3 + 1] | this[offset3] << 8;
    return val & 32768 ? val | 4294901760 : val;
  };
  Buffer4.prototype.readInt32LE = function readInt32LE(offset3, noAssert) {
    offset3 = offset3 >>> 0;
    if (!noAssert) checkOffset(offset3, 4, this.length);
    return this[offset3] | this[offset3 + 1] << 8 | this[offset3 + 2] << 16 | this[offset3 + 3] << 24;
  };
  Buffer4.prototype.readInt32BE = function readInt32BE(offset3, noAssert) {
    offset3 = offset3 >>> 0;
    if (!noAssert) checkOffset(offset3, 4, this.length);
    return this[offset3] << 24 | this[offset3 + 1] << 16 | this[offset3 + 2] << 8 | this[offset3 + 3];
  };
  Buffer4.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE(offset3) {
    offset3 = offset3 >>> 0;
    validateNumber2(offset3, "offset");
    const first = this[offset3];
    const last = this[offset3 + 7];
    if (first === void 0 || last === void 0) {
      boundsError(offset3, this.length - 8);
    }
    const val = this[offset3 + 4] + this[offset3 + 5] * 2 ** 8 + this[offset3 + 6] * 2 ** 16 + (last << 24);
    return (BigInt(val) << BigInt(32)) + BigInt(first + this[++offset3] * 2 ** 8 + this[++offset3] * 2 ** 16 + this[++offset3] * 2 ** 24);
  });
  Buffer4.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE(offset3) {
    offset3 = offset3 >>> 0;
    validateNumber2(offset3, "offset");
    const first = this[offset3];
    const last = this[offset3 + 7];
    if (first === void 0 || last === void 0) {
      boundsError(offset3, this.length - 8);
    }
    const val = (first << 24) + // Overflow
    this[++offset3] * 2 ** 16 + this[++offset3] * 2 ** 8 + this[++offset3];
    return (BigInt(val) << BigInt(32)) + BigInt(this[++offset3] * 2 ** 24 + this[++offset3] * 2 ** 16 + this[++offset3] * 2 ** 8 + last);
  });
  Buffer4.prototype.readFloatLE = function readFloatLE(offset3, noAssert) {
    offset3 = offset3 >>> 0;
    if (!noAssert) checkOffset(offset3, 4, this.length);
    return ieee754.read(this, offset3, true, 23, 4);
  };
  Buffer4.prototype.readFloatBE = function readFloatBE(offset3, noAssert) {
    offset3 = offset3 >>> 0;
    if (!noAssert) checkOffset(offset3, 4, this.length);
    return ieee754.read(this, offset3, false, 23, 4);
  };
  Buffer4.prototype.readDoubleLE = function readDoubleLE(offset3, noAssert) {
    offset3 = offset3 >>> 0;
    if (!noAssert) checkOffset(offset3, 8, this.length);
    return ieee754.read(this, offset3, true, 52, 8);
  };
  Buffer4.prototype.readDoubleBE = function readDoubleBE(offset3, noAssert) {
    offset3 = offset3 >>> 0;
    if (!noAssert) checkOffset(offset3, 8, this.length);
    return ieee754.read(this, offset3, false, 52, 8);
  };
  function checkInt(buf, value, offset3, ext, max, min2) {
    if (!Buffer4.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance');
    if (value > max || value < min2) throw new RangeError('"value" argument is out of bounds');
    if (offset3 + ext > buf.length) throw new RangeError("Index out of range");
  }
  Buffer4.prototype.writeUintLE = Buffer4.prototype.writeUIntLE = function writeUIntLE(value, offset3, byteLength2, noAssert) {
    value = +value;
    offset3 = offset3 >>> 0;
    byteLength2 = byteLength2 >>> 0;
    if (!noAssert) {
      const maxBytes = Math.pow(2, 8 * byteLength2) - 1;
      checkInt(this, value, offset3, byteLength2, maxBytes, 0);
    }
    let mul = 1;
    let i6 = 0;
    this[offset3] = value & 255;
    while (++i6 < byteLength2 && (mul *= 256)) {
      this[offset3 + i6] = value / mul & 255;
    }
    return offset3 + byteLength2;
  };
  Buffer4.prototype.writeUintBE = Buffer4.prototype.writeUIntBE = function writeUIntBE(value, offset3, byteLength2, noAssert) {
    value = +value;
    offset3 = offset3 >>> 0;
    byteLength2 = byteLength2 >>> 0;
    if (!noAssert) {
      const maxBytes = Math.pow(2, 8 * byteLength2) - 1;
      checkInt(this, value, offset3, byteLength2, maxBytes, 0);
    }
    let i6 = byteLength2 - 1;
    let mul = 1;
    this[offset3 + i6] = value & 255;
    while (--i6 >= 0 && (mul *= 256)) {
      this[offset3 + i6] = value / mul & 255;
    }
    return offset3 + byteLength2;
  };
  Buffer4.prototype.writeUint8 = Buffer4.prototype.writeUInt8 = function writeUInt8(value, offset3, noAssert) {
    value = +value;
    offset3 = offset3 >>> 0;
    if (!noAssert) checkInt(this, value, offset3, 1, 255, 0);
    this[offset3] = value & 255;
    return offset3 + 1;
  };
  Buffer4.prototype.writeUint16LE = Buffer4.prototype.writeUInt16LE = function writeUInt16LE(value, offset3, noAssert) {
    value = +value;
    offset3 = offset3 >>> 0;
    if (!noAssert) checkInt(this, value, offset3, 2, 65535, 0);
    this[offset3] = value & 255;
    this[offset3 + 1] = value >>> 8;
    return offset3 + 2;
  };
  Buffer4.prototype.writeUint16BE = Buffer4.prototype.writeUInt16BE = function writeUInt16BE(value, offset3, noAssert) {
    value = +value;
    offset3 = offset3 >>> 0;
    if (!noAssert) checkInt(this, value, offset3, 2, 65535, 0);
    this[offset3] = value >>> 8;
    this[offset3 + 1] = value & 255;
    return offset3 + 2;
  };
  Buffer4.prototype.writeUint32LE = Buffer4.prototype.writeUInt32LE = function writeUInt32LE(value, offset3, noAssert) {
    value = +value;
    offset3 = offset3 >>> 0;
    if (!noAssert) checkInt(this, value, offset3, 4, 4294967295, 0);
    this[offset3 + 3] = value >>> 24;
    this[offset3 + 2] = value >>> 16;
    this[offset3 + 1] = value >>> 8;
    this[offset3] = value & 255;
    return offset3 + 4;
  };
  Buffer4.prototype.writeUint32BE = Buffer4.prototype.writeUInt32BE = function writeUInt32BE(value, offset3, noAssert) {
    value = +value;
    offset3 = offset3 >>> 0;
    if (!noAssert) checkInt(this, value, offset3, 4, 4294967295, 0);
    this[offset3] = value >>> 24;
    this[offset3 + 1] = value >>> 16;
    this[offset3 + 2] = value >>> 8;
    this[offset3 + 3] = value & 255;
    return offset3 + 4;
  };
  function wrtBigUInt64LE(buf, value, offset3, min2, max) {
    checkIntBI(value, min2, max, buf, offset3, 7);
    let lo = Number(value & BigInt(4294967295));
    buf[offset3++] = lo;
    lo = lo >> 8;
    buf[offset3++] = lo;
    lo = lo >> 8;
    buf[offset3++] = lo;
    lo = lo >> 8;
    buf[offset3++] = lo;
    let hi = Number(value >> BigInt(32) & BigInt(4294967295));
    buf[offset3++] = hi;
    hi = hi >> 8;
    buf[offset3++] = hi;
    hi = hi >> 8;
    buf[offset3++] = hi;
    hi = hi >> 8;
    buf[offset3++] = hi;
    return offset3;
  }
  function wrtBigUInt64BE(buf, value, offset3, min2, max) {
    checkIntBI(value, min2, max, buf, offset3, 7);
    let lo = Number(value & BigInt(4294967295));
    buf[offset3 + 7] = lo;
    lo = lo >> 8;
    buf[offset3 + 6] = lo;
    lo = lo >> 8;
    buf[offset3 + 5] = lo;
    lo = lo >> 8;
    buf[offset3 + 4] = lo;
    let hi = Number(value >> BigInt(32) & BigInt(4294967295));
    buf[offset3 + 3] = hi;
    hi = hi >> 8;
    buf[offset3 + 2] = hi;
    hi = hi >> 8;
    buf[offset3 + 1] = hi;
    hi = hi >> 8;
    buf[offset3] = hi;
    return offset3 + 8;
  }
  Buffer4.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE(value, offset3 = 0) {
    return wrtBigUInt64LE(this, value, offset3, BigInt(0), BigInt("0xffffffffffffffff"));
  });
  Buffer4.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE(value, offset3 = 0) {
    return wrtBigUInt64BE(this, value, offset3, BigInt(0), BigInt("0xffffffffffffffff"));
  });
  Buffer4.prototype.writeIntLE = function writeIntLE(value, offset3, byteLength2, noAssert) {
    value = +value;
    offset3 = offset3 >>> 0;
    if (!noAssert) {
      const limit = Math.pow(2, 8 * byteLength2 - 1);
      checkInt(this, value, offset3, byteLength2, limit - 1, -limit);
    }
    let i6 = 0;
    let mul = 1;
    let sub = 0;
    this[offset3] = value & 255;
    while (++i6 < byteLength2 && (mul *= 256)) {
      if (value < 0 && sub === 0 && this[offset3 + i6 - 1] !== 0) {
        sub = 1;
      }
      this[offset3 + i6] = (value / mul >> 0) - sub & 255;
    }
    return offset3 + byteLength2;
  };
  Buffer4.prototype.writeIntBE = function writeIntBE(value, offset3, byteLength2, noAssert) {
    value = +value;
    offset3 = offset3 >>> 0;
    if (!noAssert) {
      const limit = Math.pow(2, 8 * byteLength2 - 1);
      checkInt(this, value, offset3, byteLength2, limit - 1, -limit);
    }
    let i6 = byteLength2 - 1;
    let mul = 1;
    let sub = 0;
    this[offset3 + i6] = value & 255;
    while (--i6 >= 0 && (mul *= 256)) {
      if (value < 0 && sub === 0 && this[offset3 + i6 + 1] !== 0) {
        sub = 1;
      }
      this[offset3 + i6] = (value / mul >> 0) - sub & 255;
    }
    return offset3 + byteLength2;
  };
  Buffer4.prototype.writeInt8 = function writeInt8(value, offset3, noAssert) {
    value = +value;
    offset3 = offset3 >>> 0;
    if (!noAssert) checkInt(this, value, offset3, 1, 127, -128);
    if (value < 0) value = 255 + value + 1;
    this[offset3] = value & 255;
    return offset3 + 1;
  };
  Buffer4.prototype.writeInt16LE = function writeInt16LE(value, offset3, noAssert) {
    value = +value;
    offset3 = offset3 >>> 0;
    if (!noAssert) checkInt(this, value, offset3, 2, 32767, -32768);
    this[offset3] = value & 255;
    this[offset3 + 1] = value >>> 8;
    return offset3 + 2;
  };
  Buffer4.prototype.writeInt16BE = function writeInt16BE(value, offset3, noAssert) {
    value = +value;
    offset3 = offset3 >>> 0;
    if (!noAssert) checkInt(this, value, offset3, 2, 32767, -32768);
    this[offset3] = value >>> 8;
    this[offset3 + 1] = value & 255;
    return offset3 + 2;
  };
  Buffer4.prototype.writeInt32LE = function writeInt32LE(value, offset3, noAssert) {
    value = +value;
    offset3 = offset3 >>> 0;
    if (!noAssert) checkInt(this, value, offset3, 4, 2147483647, -2147483648);
    this[offset3] = value & 255;
    this[offset3 + 1] = value >>> 8;
    this[offset3 + 2] = value >>> 16;
    this[offset3 + 3] = value >>> 24;
    return offset3 + 4;
  };
  Buffer4.prototype.writeInt32BE = function writeInt32BE(value, offset3, noAssert) {
    value = +value;
    offset3 = offset3 >>> 0;
    if (!noAssert) checkInt(this, value, offset3, 4, 2147483647, -2147483648);
    if (value < 0) value = 4294967295 + value + 1;
    this[offset3] = value >>> 24;
    this[offset3 + 1] = value >>> 16;
    this[offset3 + 2] = value >>> 8;
    this[offset3 + 3] = value & 255;
    return offset3 + 4;
  };
  Buffer4.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE(value, offset3 = 0) {
    return wrtBigUInt64LE(this, value, offset3, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff"));
  });
  Buffer4.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE(value, offset3 = 0) {
    return wrtBigUInt64BE(this, value, offset3, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff"));
  });
  function checkIEEE754(buf, value, offset3, ext, max, min2) {
    if (offset3 + ext > buf.length) throw new RangeError("Index out of range");
    if (offset3 < 0) throw new RangeError("Index out of range");
  }
  function writeFloat(buf, value, offset3, littleEndian, noAssert) {
    value = +value;
    offset3 = offset3 >>> 0;
    if (!noAssert) {
      checkIEEE754(buf, value, offset3, 4);
    }
    ieee754.write(buf, value, offset3, littleEndian, 23, 4);
    return offset3 + 4;
  }
  Buffer4.prototype.writeFloatLE = function writeFloatLE(value, offset3, noAssert) {
    return writeFloat(this, value, offset3, true, noAssert);
  };
  Buffer4.prototype.writeFloatBE = function writeFloatBE(value, offset3, noAssert) {
    return writeFloat(this, value, offset3, false, noAssert);
  };
  function writeDouble(buf, value, offset3, littleEndian, noAssert) {
    value = +value;
    offset3 = offset3 >>> 0;
    if (!noAssert) {
      checkIEEE754(buf, value, offset3, 8);
    }
    ieee754.write(buf, value, offset3, littleEndian, 52, 8);
    return offset3 + 8;
  }
  Buffer4.prototype.writeDoubleLE = function writeDoubleLE(value, offset3, noAssert) {
    return writeDouble(this, value, offset3, true, noAssert);
  };
  Buffer4.prototype.writeDoubleBE = function writeDoubleBE(value, offset3, noAssert) {
    return writeDouble(this, value, offset3, false, noAssert);
  };
  Buffer4.prototype.copy = function copy6(target, targetStart, start, end) {
    if (!Buffer4.isBuffer(target)) throw new TypeError("argument should be a Buffer");
    if (!start) start = 0;
    if (!end && end !== 0) end = this.length;
    if (targetStart >= target.length) targetStart = target.length;
    if (!targetStart) targetStart = 0;
    if (end > 0 && end < start) end = start;
    if (end === start) return 0;
    if (target.length === 0 || this.length === 0) return 0;
    if (targetStart < 0) {
      throw new RangeError("targetStart out of bounds");
    }
    if (start < 0 || start >= this.length) throw new RangeError("Index out of range");
    if (end < 0) throw new RangeError("sourceEnd out of bounds");
    if (end > this.length) end = this.length;
    if (target.length - targetStart < end - start) {
      end = target.length - targetStart + start;
    }
    const len = end - start;
    if (this === target && typeof Uint8Array.prototype.copyWithin === "function") {
      this.copyWithin(targetStart, start, end);
    } else {
      Uint8Array.prototype.set.call(target, this.subarray(start, end), targetStart);
    }
    return len;
  };
  Buffer4.prototype.fill = function fill(val, start, end, encoding) {
    if (typeof val === "string") {
      if (typeof start === "string") {
        encoding = start;
        start = 0;
        end = this.length;
      } else if (typeof end === "string") {
        encoding = end;
        end = this.length;
      }
      if (encoding !== void 0 && typeof encoding !== "string") {
        throw new TypeError("encoding must be a string");
      }
      if (typeof encoding === "string" && !Buffer4.isEncoding(encoding)) {
        throw new TypeError("Unknown encoding: " + encoding);
      }
      if (val.length === 1) {
        const code5 = val.charCodeAt(0);
        if (encoding === "utf8" && code5 < 128 || encoding === "latin1") {
          val = code5;
        }
      }
    } else if (typeof val === "number") {
      val = val & 255;
    } else if (typeof val === "boolean") {
      val = Number(val);
    }
    if (start < 0 || this.length < start || this.length < end) {
      throw new RangeError("Out of range index");
    }
    if (end <= start) {
      return this;
    }
    start = start >>> 0;
    end = end === void 0 ? this.length : end >>> 0;
    if (!val) val = 0;
    let i6;
    if (typeof val === "number") {
      for (i6 = start; i6 < end; ++i6) {
        this[i6] = val;
      }
    } else {
      const bytes = Buffer4.isBuffer(val) ? val : Buffer4.from(val, encoding);
      const len = bytes.length;
      if (len === 0) {
        throw new TypeError('The value "' + val + '" is invalid for argument "value"');
      }
      for (i6 = 0; i6 < end - start; ++i6) {
        this[i6 + start] = bytes[i6 % len];
      }
    }
    return this;
  };
  const errors2 = {};
  function E3(sym, getMessage, Base) {
    errors2[sym] = class NodeError extends Base {
      constructor() {
        super();
        Object.defineProperty(this, "message", {
          value: getMessage.apply(this, arguments),
          writable: true,
          configurable: true
        });
        this.name = `${this.name} [${sym}]`;
        this.stack;
        delete this.name;
      }
      get code() {
        return sym;
      }
      set code(value) {
        Object.defineProperty(this, "code", {
          configurable: true,
          enumerable: true,
          value,
          writable: true
        });
      }
      toString() {
        return `${this.name} [${sym}]: ${this.message}`;
      }
    };
  }
  E3("ERR_BUFFER_OUT_OF_BOUNDS", function(name2) {
    if (name2) {
      return `${name2} is outside of buffer bounds`;
    }
    return "Attempt to access memory outside buffer bounds";
  }, RangeError);
  E3("ERR_INVALID_ARG_TYPE", function(name2, actual) {
    return `The "${name2}" argument must be of type number. Received type ${typeof actual}`;
  }, TypeError);
  E3("ERR_OUT_OF_RANGE", function(str3, range, input) {
    let msg5 = `The value of "${str3}" is out of range.`;
    let received = input;
    if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) {
      received = addNumericalSeparator(String(input));
    } else if (typeof input === "bigint") {
      received = String(input);
      if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) {
        received = addNumericalSeparator(received);
      }
      received += "n";
    }
    msg5 += ` It must be ${range}. Received ${received}`;
    return msg5;
  }, RangeError);
  function addNumericalSeparator(val) {
    let res = "";
    let i6 = val.length;
    const start = val[0] === "-" ? 1 : 0;
    for (; i6 >= start + 4; i6 -= 3) {
      res = `_${val.slice(i6 - 3, i6)}${res}`;
    }
    return `${val.slice(0, i6)}${res}`;
  }
  function checkBounds(buf, offset3, byteLength2) {
    validateNumber2(offset3, "offset");
    if (buf[offset3] === void 0 || buf[offset3 + byteLength2] === void 0) {
      boundsError(offset3, buf.length - (byteLength2 + 1));
    }
  }
  function checkIntBI(value, min2, max, buf, offset3, byteLength2) {
    if (value > max || value < min2) {
      const n5 = typeof min2 === "bigint" ? "n" : "";
      let range;
      if (byteLength2 > 3) {
        if (min2 === 0 || min2 === BigInt(0)) {
          range = `>= 0${n5} and < 2${n5} ** ${(byteLength2 + 1) * 8}${n5}`;
        } else {
          range = `>= -(2${n5} ** ${(byteLength2 + 1) * 8 - 1}${n5}) and < 2 ** ${(byteLength2 + 1) * 8 - 1}${n5}`;
        }
      } else {
        range = `>= ${min2}${n5} and <= ${max}${n5}`;
      }
      throw new errors2.ERR_OUT_OF_RANGE("value", range, value);
    }
    checkBounds(buf, offset3, byteLength2);
  }
  function validateNumber2(value, name2) {
    if (typeof value !== "number") {
      throw new errors2.ERR_INVALID_ARG_TYPE(name2, "number", value);
    }
  }
  function boundsError(value, length, type4) {
    if (Math.floor(value) !== value) {
      validateNumber2(value, type4);
      throw new errors2.ERR_OUT_OF_RANGE(type4 || "offset", "an integer", value);
    }
    if (length < 0) {
      throw new errors2.ERR_BUFFER_OUT_OF_BOUNDS();
    }
    throw new errors2.ERR_OUT_OF_RANGE(type4 || "offset", `>= ${type4 ? 1 : 0} and <= ${length}`, value);
  }
  const INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g;
  function base64clean(str3) {
    str3 = str3.split("=")[0];
    str3 = str3.trim().replace(INVALID_BASE64_RE, "");
    if (str3.length < 2) return "";
    while (str3.length % 4 !== 0) {
      str3 = str3 + "=";
    }
    return str3;
  }
  function utf8ToBytes(string2, units2) {
    units2 = units2 || Infinity;
    let codePoint;
    const length = string2.length;
    let leadSurrogate = null;
    const bytes = [];
    for (let i6 = 0; i6 < length; ++i6) {
      codePoint = string2.charCodeAt(i6);
      if (codePoint > 55295 && codePoint < 57344) {
        if (!leadSurrogate) {
          if (codePoint > 56319) {
            if ((units2 -= 3) > -1) bytes.push(239, 191, 189);
            continue;
          } else if (i6 + 1 === length) {
            if ((units2 -= 3) > -1) bytes.push(239, 191, 189);
            continue;
          }
          leadSurrogate = codePoint;
          continue;
        }
        if (codePoint < 56320) {
          if ((units2 -= 3) > -1) bytes.push(239, 191, 189);
          leadSurrogate = codePoint;
          continue;
        }
        codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536;
      } else if (leadSurrogate) {
        if ((units2 -= 3) > -1) bytes.push(239, 191, 189);
      }
      leadSurrogate = null;
      if (codePoint < 128) {
        if ((units2 -= 1) < 0) break;
        bytes.push(codePoint);
      } else if (codePoint < 2048) {
        if ((units2 -= 2) < 0) break;
        bytes.push(codePoint >> 6 | 192, codePoint & 63 | 128);
      } else if (codePoint < 65536) {
        if ((units2 -= 3) < 0) break;
        bytes.push(codePoint >> 12 | 224, codePoint >> 6 & 63 | 128, codePoint & 63 | 128);
      } else if (codePoint < 1114112) {
        if ((units2 -= 4) < 0) break;
        bytes.push(codePoint >> 18 | 240, codePoint >> 12 & 63 | 128, codePoint >> 6 & 63 | 128, codePoint & 63 | 128);
      } else {
        throw new Error("Invalid code point");
      }
    }
    return bytes;
  }
  function asciiToBytes(str3) {
    const byteArray = [];
    for (let i6 = 0; i6 < str3.length; ++i6) {
      byteArray.push(str3.charCodeAt(i6) & 255);
    }
    return byteArray;
  }
  function utf16leToBytes(str3, units2) {
    let c6, hi, lo;
    const byteArray = [];
    for (let i6 = 0; i6 < str3.length; ++i6) {
      if ((units2 -= 2) < 0) break;
      c6 = str3.charCodeAt(i6);
      hi = c6 >> 8;
      lo = c6 % 256;
      byteArray.push(lo);
      byteArray.push(hi);
    }
    return byteArray;
  }
  function base64ToBytes(str3) {
    return base642.toByteArray(base64clean(str3));
  }
  function blitBuffer(src2, dst, offset3, length) {
    let i6;
    for (i6 = 0; i6 < length; ++i6) {
      if (i6 + offset3 >= dst.length || i6 >= src2.length) break;
      dst[i6 + offset3] = src2[i6];
    }
    return i6;
  }
  function isInstance(obj, type4) {
    return obj instanceof type4 || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type4.name;
  }
  function numberIsNaN(obj) {
    return obj !== obj;
  }
  const hexSliceLookupTable = (function() {
    const alphabet5 = "0123456789abcdef";
    const table = new Array(256);
    for (let i6 = 0; i6 < 16; ++i6) {
      const i16 = i6 * 16;
      for (let j3 = 0; j3 < 16; ++j3) {
        table[i16 + j3] = alphabet5[i6] + alphabet5[j3];
      }
    }
    return table;
  })();
  function defineBigIntMethod(fn) {
    return typeof BigInt === "undefined" ? BufferBigIntNotDefined : fn;
  }
  function BufferBigIntNotDefined() {
    throw new Error("BigInt not supported");
  }
  return exports$g;
}
function dew$f() {
  if (_dewExec$f) return exports$f;
  _dewExec$f = true;
  if (typeof Object.create === "function") {
    exports$f = function inherits3(ctor, superCtor) {
      if (superCtor) {
        ctor.super_ = superCtor;
        ctor.prototype = Object.create(superCtor.prototype, {
          constructor: {
            value: ctor,
            enumerable: false,
            writable: true,
            configurable: true
          }
        });
      }
    };
  } else {
    exports$f = function inherits3(ctor, superCtor) {
      if (superCtor) {
        ctor.super_ = superCtor;
        var TempCtor = function() {
        };
        TempCtor.prototype = superCtor.prototype;
        ctor.prototype = new TempCtor();
        ctor.prototype.constructor = ctor;
      }
    };
  }
  return exports$f;
}
function dew$e() {
  if (_dewExec$e) return exports$e;
  _dewExec$e = true;
  exports$e = y.EventEmitter;
  return exports$e;
}
function dew$d() {
  if (_dewExec$d) return exports$d;
  _dewExec$d = true;
  function ownKeys(object, enumerableOnly) {
    var keys = Object.keys(object);
    if (Object.getOwnPropertySymbols) {
      var symbols = Object.getOwnPropertySymbols(object);
      if (enumerableOnly) symbols = symbols.filter(function(sym) {
        return Object.getOwnPropertyDescriptor(object, sym).enumerable;
      });
      keys.push.apply(keys, symbols);
    }
    return keys;
  }
  function _objectSpread(target) {
    for (var i6 = 1; i6 < arguments.length; i6++) {
      var source2 = arguments[i6] != null ? arguments[i6] : {};
      if (i6 % 2) {
        ownKeys(Object(source2), true).forEach(function(key) {
          _defineProperty(target, key, source2[key]);
        });
      } else if (Object.getOwnPropertyDescriptors) {
        Object.defineProperties(target, Object.getOwnPropertyDescriptors(source2));
      } else {
        ownKeys(Object(source2)).forEach(function(key) {
          Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source2, key));
        });
      }
    }
    return target;
  }
  function _defineProperty(obj, key, value) {
    if (key in obj) {
      Object.defineProperty(obj, key, {
        value,
        enumerable: true,
        configurable: true,
        writable: true
      });
    } else {
      obj[key] = value;
    }
    return obj;
  }
  function _classCallCheck(instance, Constructor) {
    if (!(instance instanceof Constructor)) {
      throw new TypeError("Cannot call a class as a function");
    }
  }
  function _defineProperties(target, props) {
    for (var i6 = 0; i6 < props.length; i6++) {
      var descriptor = props[i6];
      descriptor.enumerable = descriptor.enumerable || false;
      descriptor.configurable = true;
      if ("value" in descriptor) descriptor.writable = true;
      Object.defineProperty(target, descriptor.key, descriptor);
    }
  }
  function _createClass(Constructor, protoProps, staticProps) {
    if (protoProps) _defineProperties(Constructor.prototype, protoProps);
    if (staticProps) _defineProperties(Constructor, staticProps);
    return Constructor;
  }
  var _require = buffer, Buffer4 = _require.Buffer;
  var _require2 = X, inspect4 = _require2.inspect;
  var custom2 = inspect4 && inspect4.custom || "inspect";
  function copyBuffer(src2, target, offset3) {
    Buffer4.prototype.copy.call(src2, target, offset3);
  }
  exports$d = /* @__PURE__ */ (function() {
    function BufferList() {
      _classCallCheck(this, BufferList);
      this.head = null;
      this.tail = null;
      this.length = 0;
    }
    _createClass(BufferList, [{
      key: "push",
      value: function push3(v4) {
        var entry = {
          data: v4,
          next: null
        };
        if (this.length > 0) this.tail.next = entry;
        else this.head = entry;
        this.tail = entry;
        ++this.length;
      }
    }, {
      key: "unshift",
      value: function unshift(v4) {
        var entry = {
          data: v4,
          next: this.head
        };
        if (this.length === 0) this.tail = entry;
        this.head = entry;
        ++this.length;
      }
    }, {
      key: "shift",
      value: function shift() {
        if (this.length === 0) return;
        var ret = this.head.data;
        if (this.length === 1) this.head = this.tail = null;
        else this.head = this.head.next;
        --this.length;
        return ret;
      }
    }, {
      key: "clear",
      value: function clear() {
        this.head = this.tail = null;
        this.length = 0;
      }
    }, {
      key: "join",
      value: function join17(s5) {
        if (this.length === 0) return "";
        var p5 = this.head;
        var ret = "" + p5.data;
        while (p5 = p5.next) {
          ret += s5 + p5.data;
        }
        return ret;
      }
    }, {
      key: "concat",
      value: function concat3(n5) {
        if (this.length === 0) return Buffer4.alloc(0);
        var ret = Buffer4.allocUnsafe(n5 >>> 0);
        var p5 = this.head;
        var i6 = 0;
        while (p5) {
          copyBuffer(p5.data, ret, i6);
          i6 += p5.data.length;
          p5 = p5.next;
        }
        return ret;
      }
      // Consumes a specified amount of bytes or characters from the buffered data.
    }, {
      key: "consume",
      value: function consume(n5, hasStrings) {
        var ret;
        if (n5 < this.head.data.length) {
          ret = this.head.data.slice(0, n5);
          this.head.data = this.head.data.slice(n5);
        } else if (n5 === this.head.data.length) {
          ret = this.shift();
        } else {
          ret = hasStrings ? this._getString(n5) : this._getBuffer(n5);
        }
        return ret;
      }
    }, {
      key: "first",
      value: function first() {
        return this.head.data;
      }
      // Consumes a specified amount of characters from the buffered data.
    }, {
      key: "_getString",
      value: function _getString(n5) {
        var p5 = this.head;
        var c6 = 1;
        var ret = p5.data;
        n5 -= ret.length;
        while (p5 = p5.next) {
          var str3 = p5.data;
          var nb = n5 > str3.length ? str3.length : n5;
          if (nb === str3.length) ret += str3;
          else ret += str3.slice(0, n5);
          n5 -= nb;
          if (n5 === 0) {
            if (nb === str3.length) {
              ++c6;
              if (p5.next) this.head = p5.next;
              else this.head = this.tail = null;
            } else {
              this.head = p5;
              p5.data = str3.slice(nb);
            }
            break;
          }
          ++c6;
        }
        this.length -= c6;
        return ret;
      }
      // Consumes a specified amount of bytes from the buffered data.
    }, {
      key: "_getBuffer",
      value: function _getBuffer(n5) {
        var ret = Buffer4.allocUnsafe(n5);
        var p5 = this.head;
        var c6 = 1;
        p5.data.copy(ret);
        n5 -= p5.data.length;
        while (p5 = p5.next) {
          var buf = p5.data;
          var nb = n5 > buf.length ? buf.length : n5;
          buf.copy(ret, ret.length - n5, 0, nb);
          n5 -= nb;
          if (n5 === 0) {
            if (nb === buf.length) {
              ++c6;
              if (p5.next) this.head = p5.next;
              else this.head = this.tail = null;
            } else {
              this.head = p5;
              p5.data = buf.slice(nb);
            }
            break;
          }
          ++c6;
        }
        this.length -= c6;
        return ret;
      }
      // Make sure the linked list only shows the minimal necessary information.
    }, {
      key: custom2,
      value: function value(_3, options) {
        return inspect4(this, _objectSpread({}, options, {
          // Only inspect one level.
          depth: 0,
          // It should not recurse.
          customInspect: false
        }));
      }
    }]);
    return BufferList;
  })();
  return exports$d;
}
function dew$c() {
  if (_dewExec$c) return exports$c;
  _dewExec$c = true;
  var process$1 = process;
  function destroy(err2, cb) {
    var _this = this;
    var readableDestroyed = this._readableState && this._readableState.destroyed;
    var writableDestroyed = this._writableState && this._writableState.destroyed;
    if (readableDestroyed || writableDestroyed) {
      if (cb) {
        cb(err2);
      } else if (err2) {
        if (!this._writableState) {
          process$1.nextTick(emitErrorNT, this, err2);
        } else if (!this._writableState.errorEmitted) {
          this._writableState.errorEmitted = true;
          process$1.nextTick(emitErrorNT, this, err2);
        }
      }
      return this;
    }
    if (this._readableState) {
      this._readableState.destroyed = true;
    }
    if (this._writableState) {
      this._writableState.destroyed = true;
    }
    this._destroy(err2 || null, function(err3) {
      if (!cb && err3) {
        if (!_this._writableState) {
          process$1.nextTick(emitErrorAndCloseNT, _this, err3);
        } else if (!_this._writableState.errorEmitted) {
          _this._writableState.errorEmitted = true;
          process$1.nextTick(emitErrorAndCloseNT, _this, err3);
        } else {
          process$1.nextTick(emitCloseNT, _this);
        }
      } else if (cb) {
        process$1.nextTick(emitCloseNT, _this);
        cb(err3);
      } else {
        process$1.nextTick(emitCloseNT, _this);
      }
    });
    return this;
  }
  function emitErrorAndCloseNT(self2, err2) {
    emitErrorNT(self2, err2);
    emitCloseNT(self2);
  }
  function emitCloseNT(self2) {
    if (self2._writableState && !self2._writableState.emitClose) return;
    if (self2._readableState && !self2._readableState.emitClose) return;
    self2.emit("close");
  }
  function undestroy() {
    if (this._readableState) {
      this._readableState.destroyed = false;
      this._readableState.reading = false;
      this._readableState.ended = false;
      this._readableState.endEmitted = false;
    }
    if (this._writableState) {
      this._writableState.destroyed = false;
      this._writableState.ended = false;
      this._writableState.ending = false;
      this._writableState.finalCalled = false;
      this._writableState.prefinished = false;
      this._writableState.finished = false;
      this._writableState.errorEmitted = false;
    }
  }
  function emitErrorNT(self2, err2) {
    self2.emit("error", err2);
  }
  function errorOrDestroy(stream, err2) {
    var rState = stream._readableState;
    var wState = stream._writableState;
    if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err2);
    else stream.emit("error", err2);
  }
  exports$c = {
    destroy,
    undestroy,
    errorOrDestroy
  };
  return exports$c;
}
function dew$b() {
  if (_dewExec$b) return exports$b;
  _dewExec$b = true;
  const codes = {};
  function createErrorType(code5, message, Base) {
    if (!Base) {
      Base = Error;
    }
    function getMessage(arg1, arg2, arg3) {
      if (typeof message === "string") {
        return message;
      } else {
        return message(arg1, arg2, arg3);
      }
    }
    class NodeError extends Base {
      constructor(arg1, arg2, arg3) {
        super(getMessage(arg1, arg2, arg3));
      }
    }
    NodeError.prototype.name = Base.name;
    NodeError.prototype.code = code5;
    codes[code5] = NodeError;
  }
  function oneOf(expected, thing) {
    if (Array.isArray(expected)) {
      const len = expected.length;
      expected = expected.map((i6) => String(i6));
      if (len > 2) {
        return `one of ${thing} ${expected.slice(0, len - 1).join(", ")}, or ` + expected[len - 1];
      } else if (len === 2) {
        return `one of ${thing} ${expected[0]} or ${expected[1]}`;
      } else {
        return `of ${thing} ${expected[0]}`;
      }
    } else {
      return `of ${thing} ${String(expected)}`;
    }
  }
  function startsWith(str3, search, pos) {
    return str3.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
  }
  function endsWith(str3, search, this_len) {
    if (this_len === void 0 || this_len > str3.length) {
      this_len = str3.length;
    }
    return str3.substring(this_len - search.length, this_len) === search;
  }
  function includes(str3, search, start) {
    if (typeof start !== "number") {
      start = 0;
    }
    if (start + search.length > str3.length) {
      return false;
    } else {
      return str3.indexOf(search, start) !== -1;
    }
  }
  createErrorType("ERR_INVALID_OPT_VALUE", function(name2, value) {
    return 'The value "' + value + '" is invalid for option "' + name2 + '"';
  }, TypeError);
  createErrorType("ERR_INVALID_ARG_TYPE", function(name2, expected, actual) {
    let determiner;
    if (typeof expected === "string" && startsWith(expected, "not ")) {
      determiner = "must not be";
      expected = expected.replace(/^not /, "");
    } else {
      determiner = "must be";
    }
    let msg5;
    if (endsWith(name2, " argument")) {
      msg5 = `The ${name2} ${determiner} ${oneOf(expected, "type")}`;
    } else {
      const type4 = includes(name2, ".") ? "property" : "argument";
      msg5 = `The "${name2}" ${type4} ${determiner} ${oneOf(expected, "type")}`;
    }
    msg5 += `. Received type ${typeof actual}`;
    return msg5;
  }, TypeError);
  createErrorType("ERR_STREAM_PUSH_AFTER_EOF", "stream.push() after EOF");
  createErrorType("ERR_METHOD_NOT_IMPLEMENTED", function(name2) {
    return "The " + name2 + " method is not implemented";
  });
  createErrorType("ERR_STREAM_PREMATURE_CLOSE", "Premature close");
  createErrorType("ERR_STREAM_DESTROYED", function(name2) {
    return "Cannot call " + name2 + " after a stream was destroyed";
  });
  createErrorType("ERR_MULTIPLE_CALLBACK", "Callback called multiple times");
  createErrorType("ERR_STREAM_CANNOT_PIPE", "Cannot pipe, not readable");
  createErrorType("ERR_STREAM_WRITE_AFTER_END", "write after end");
  createErrorType("ERR_STREAM_NULL_VALUES", "May not write null values to stream", TypeError);
  createErrorType("ERR_UNKNOWN_ENCODING", function(arg) {
    return "Unknown encoding: " + arg;
  }, TypeError);
  createErrorType("ERR_STREAM_UNSHIFT_AFTER_END_EVENT", "stream.unshift() after end event");
  exports$b.codes = codes;
  return exports$b;
}
function dew$a() {
  if (_dewExec$a) return exports$a;
  _dewExec$a = true;
  var ERR_INVALID_OPT_VALUE = dew$b().codes.ERR_INVALID_OPT_VALUE;
  function highWaterMarkFrom(options, isDuplex, duplexKey) {
    return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;
  }
  function getHighWaterMark(state2, options, duplexKey, isDuplex) {
    var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
    if (hwm != null) {
      if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {
        var name2 = isDuplex ? duplexKey : "highWaterMark";
        throw new ERR_INVALID_OPT_VALUE(name2, hwm);
      }
      return Math.floor(hwm);
    }
    return state2.objectMode ? 16 : 16 * 1024;
  }
  exports$a = {
    getHighWaterMark
  };
  return exports$a;
}
function dew$9() {
  if (_dewExec$9) return exports$9;
  _dewExec$9 = true;
  exports$9 = deprecate3;
  function deprecate3(fn, msg5) {
    if (config2("noDeprecation")) {
      return fn;
    }
    var warned = false;
    function deprecated() {
      if (!warned) {
        if (config2("throwDeprecation")) {
          throw new Error(msg5);
        } else if (config2("traceDeprecation")) {
          console.trace(msg5);
        } else {
          console.warn(msg5);
        }
        warned = true;
      }
      return fn.apply(this || _global$2, arguments);
    }
    return deprecated;
  }
  function config2(name2) {
    try {
      if (!_global$2.localStorage) return false;
    } catch (_3) {
      return false;
    }
    var val = _global$2.localStorage[name2];
    if (null == val) return false;
    return String(val).toLowerCase() === "true";
  }
  return exports$9;
}
function dew$8() {
  if (_dewExec$8) return exports$8;
  _dewExec$8 = true;
  var process$1 = process;
  exports$8 = Writable2;
  function CorkedRequest(state2) {
    var _this = this;
    this.next = null;
    this.entry = null;
    this.finish = function() {
      onCorkedFinish(_this, state2);
    };
  }
  var Duplex2;
  Writable2.WritableState = WritableState;
  var internalUtil = {
    deprecate: dew$9()
  };
  var Stream3 = dew$e();
  var Buffer4 = buffer.Buffer;
  var OurUint8Array = _global$1.Uint8Array || function() {
  };
  function _uint8ArrayToBuffer(chunk) {
    return Buffer4.from(chunk);
  }
  function _isUint8Array(obj) {
    return Buffer4.isBuffer(obj) || obj instanceof OurUint8Array;
  }
  var destroyImpl = dew$c();
  var _require = dew$a(), getHighWaterMark = _require.getHighWaterMark;
  var _require$codes = dew$b().codes, ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;
  var errorOrDestroy = destroyImpl.errorOrDestroy;
  dew$f()(Writable2, Stream3);
  function nop() {
  }
  function WritableState(options, stream, isDuplex) {
    Duplex2 = Duplex2 || dew$7();
    options = options || {};
    if (typeof isDuplex !== "boolean") isDuplex = stream instanceof Duplex2;
    this.objectMode = !!options.objectMode;
    if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
    this.highWaterMark = getHighWaterMark(this, options, "writableHighWaterMark", isDuplex);
    this.finalCalled = false;
    this.needDrain = false;
    this.ending = false;
    this.ended = false;
    this.finished = false;
    this.destroyed = false;
    var noDecode = options.decodeStrings === false;
    this.decodeStrings = !noDecode;
    this.defaultEncoding = options.defaultEncoding || "utf8";
    this.length = 0;
    this.writing = false;
    this.corked = 0;
    this.sync = true;
    this.bufferProcessing = false;
    this.onwrite = function(er) {
      onwrite(stream, er);
    };
    this.writecb = null;
    this.writelen = 0;
    this.bufferedRequest = null;
    this.lastBufferedRequest = null;
    this.pendingcb = 0;
    this.prefinished = false;
    this.errorEmitted = false;
    this.emitClose = options.emitClose !== false;
    this.autoDestroy = !!options.autoDestroy;
    this.bufferedRequestCount = 0;
    this.corkedRequestsFree = new CorkedRequest(this);
  }
  WritableState.prototype.getBuffer = function getBuffer() {
    var current3 = this.bufferedRequest;
    var out = [];
    while (current3) {
      out.push(current3);
      current3 = current3.next;
    }
    return out;
  };
  (function() {
    try {
      Object.defineProperty(WritableState.prototype, "buffer", {
        get: internalUtil.deprecate(function writableStateBufferGetter() {
          return this.getBuffer();
        }, "_writableState.buffer is deprecated. Use _writableState.getBuffer instead.", "DEP0003")
      });
    } catch (_3) {
    }
  })();
  var realHasInstance;
  if (typeof Symbol === "function" && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === "function") {
    realHasInstance = Function.prototype[Symbol.hasInstance];
    Object.defineProperty(Writable2, Symbol.hasInstance, {
      value: function value(object) {
        if (realHasInstance.call(this, object)) return true;
        if (this !== Writable2) return false;
        return object && object._writableState instanceof WritableState;
      }
    });
  } else {
    realHasInstance = function realHasInstance2(object) {
      return object instanceof this;
    };
  }
  function Writable2(options) {
    Duplex2 = Duplex2 || dew$7();
    var isDuplex = this instanceof Duplex2;
    if (!isDuplex && !realHasInstance.call(Writable2, this)) return new Writable2(options);
    this._writableState = new WritableState(options, this, isDuplex);
    this.writable = true;
    if (options) {
      if (typeof options.write === "function") this._write = options.write;
      if (typeof options.writev === "function") this._writev = options.writev;
      if (typeof options.destroy === "function") this._destroy = options.destroy;
      if (typeof options.final === "function") this._final = options.final;
    }
    Stream3.call(this);
  }
  Writable2.prototype.pipe = function() {
    errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());
  };
  function writeAfterEnd(stream, cb) {
    var er = new ERR_STREAM_WRITE_AFTER_END();
    errorOrDestroy(stream, er);
    process$1.nextTick(cb, er);
  }
  function validChunk(stream, state2, chunk, cb) {
    var er;
    if (chunk === null) {
      er = new ERR_STREAM_NULL_VALUES();
    } else if (typeof chunk !== "string" && !state2.objectMode) {
      er = new ERR_INVALID_ARG_TYPE("chunk", ["string", "Buffer"], chunk);
    }
    if (er) {
      errorOrDestroy(stream, er);
      process$1.nextTick(cb, er);
      return false;
    }
    return true;
  }
  Writable2.prototype.write = function(chunk, encoding, cb) {
    var state2 = this._writableState;
    var ret = false;
    var isBuf = !state2.objectMode && _isUint8Array(chunk);
    if (isBuf && !Buffer4.isBuffer(chunk)) {
      chunk = _uint8ArrayToBuffer(chunk);
    }
    if (typeof encoding === "function") {
      cb = encoding;
      encoding = null;
    }
    if (isBuf) encoding = "buffer";
    else if (!encoding) encoding = state2.defaultEncoding;
    if (typeof cb !== "function") cb = nop;
    if (state2.ending) writeAfterEnd(this, cb);
    else if (isBuf || validChunk(this, state2, chunk, cb)) {
      state2.pendingcb++;
      ret = writeOrBuffer(this, state2, isBuf, chunk, encoding, cb);
    }
    return ret;
  };
  Writable2.prototype.cork = function() {
    this._writableState.corked++;
  };
  Writable2.prototype.uncork = function() {
    var state2 = this._writableState;
    if (state2.corked) {
      state2.corked--;
      if (!state2.writing && !state2.corked && !state2.bufferProcessing && state2.bufferedRequest) clearBuffer(this, state2);
    }
  };
  Writable2.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
    if (typeof encoding === "string") encoding = encoding.toLowerCase();
    if (!(["hex", "utf8", "utf-8", "ascii", "binary", "base64", "ucs2", "ucs-2", "utf16le", "utf-16le", "raw"].indexOf((encoding + "").toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding);
    this._writableState.defaultEncoding = encoding;
    return this;
  };
  Object.defineProperty(Writable2.prototype, "writableBuffer", {
    // making it explicit this property is not enumerable
    // because otherwise some prototype manipulation in
    // userland will fail
    enumerable: false,
    get: function get2() {
      return this._writableState && this._writableState.getBuffer();
    }
  });
  function decodeChunk(state2, chunk, encoding) {
    if (!state2.objectMode && state2.decodeStrings !== false && typeof chunk === "string") {
      chunk = Buffer4.from(chunk, encoding);
    }
    return chunk;
  }
  Object.defineProperty(Writable2.prototype, "writableHighWaterMark", {
    // making it explicit this property is not enumerable
    // because otherwise some prototype manipulation in
    // userland will fail
    enumerable: false,
    get: function get2() {
      return this._writableState.highWaterMark;
    }
  });
  function writeOrBuffer(stream, state2, isBuf, chunk, encoding, cb) {
    if (!isBuf) {
      var newChunk = decodeChunk(state2, chunk, encoding);
      if (chunk !== newChunk) {
        isBuf = true;
        encoding = "buffer";
        chunk = newChunk;
      }
    }
    var len = state2.objectMode ? 1 : chunk.length;
    state2.length += len;
    var ret = state2.length < state2.highWaterMark;
    if (!ret) state2.needDrain = true;
    if (state2.writing || state2.corked) {
      var last = state2.lastBufferedRequest;
      state2.lastBufferedRequest = {
        chunk,
        encoding,
        isBuf,
        callback: cb,
        next: null
      };
      if (last) {
        last.next = state2.lastBufferedRequest;
      } else {
        state2.bufferedRequest = state2.lastBufferedRequest;
      }
      state2.bufferedRequestCount += 1;
    } else {
      doWrite(stream, state2, false, len, chunk, encoding, cb);
    }
    return ret;
  }
  function doWrite(stream, state2, writev, len, chunk, encoding, cb) {
    state2.writelen = len;
    state2.writecb = cb;
    state2.writing = true;
    state2.sync = true;
    if (state2.destroyed) state2.onwrite(new ERR_STREAM_DESTROYED("write"));
    else if (writev) stream._writev(chunk, state2.onwrite);
    else stream._write(chunk, encoding, state2.onwrite);
    state2.sync = false;
  }
  function onwriteError(stream, state2, sync, er, cb) {
    --state2.pendingcb;
    if (sync) {
      process$1.nextTick(cb, er);
      process$1.nextTick(finishMaybe, stream, state2);
      stream._writableState.errorEmitted = true;
      errorOrDestroy(stream, er);
    } else {
      cb(er);
      stream._writableState.errorEmitted = true;
      errorOrDestroy(stream, er);
      finishMaybe(stream, state2);
    }
  }
  function onwriteStateUpdate(state2) {
    state2.writing = false;
    state2.writecb = null;
    state2.length -= state2.writelen;
    state2.writelen = 0;
  }
  function onwrite(stream, er) {
    var state2 = stream._writableState;
    var sync = state2.sync;
    var cb = state2.writecb;
    if (typeof cb !== "function") throw new ERR_MULTIPLE_CALLBACK();
    onwriteStateUpdate(state2);
    if (er) onwriteError(stream, state2, sync, er, cb);
    else {
      var finished2 = needFinish(state2) || stream.destroyed;
      if (!finished2 && !state2.corked && !state2.bufferProcessing && state2.bufferedRequest) {
        clearBuffer(stream, state2);
      }
      if (sync) {
        process$1.nextTick(afterWrite, stream, state2, finished2, cb);
      } else {
        afterWrite(stream, state2, finished2, cb);
      }
    }
  }
  function afterWrite(stream, state2, finished2, cb) {
    if (!finished2) onwriteDrain(stream, state2);
    state2.pendingcb--;
    cb();
    finishMaybe(stream, state2);
  }
  function onwriteDrain(stream, state2) {
    if (state2.length === 0 && state2.needDrain) {
      state2.needDrain = false;
      stream.emit("drain");
    }
  }
  function clearBuffer(stream, state2) {
    state2.bufferProcessing = true;
    var entry = state2.bufferedRequest;
    if (stream._writev && entry && entry.next) {
      var l6 = state2.bufferedRequestCount;
      var buffer2 = new Array(l6);
      var holder = state2.corkedRequestsFree;
      holder.entry = entry;
      var count = 0;
      var allBuffers = true;
      while (entry) {
        buffer2[count] = entry;
        if (!entry.isBuf) allBuffers = false;
        entry = entry.next;
        count += 1;
      }
      buffer2.allBuffers = allBuffers;
      doWrite(stream, state2, true, state2.length, buffer2, "", holder.finish);
      state2.pendingcb++;
      state2.lastBufferedRequest = null;
      if (holder.next) {
        state2.corkedRequestsFree = holder.next;
        holder.next = null;
      } else {
        state2.corkedRequestsFree = new CorkedRequest(state2);
      }
      state2.bufferedRequestCount = 0;
    } else {
      while (entry) {
        var chunk = entry.chunk;
        var encoding = entry.encoding;
        var cb = entry.callback;
        var len = state2.objectMode ? 1 : chunk.length;
        doWrite(stream, state2, false, len, chunk, encoding, cb);
        entry = entry.next;
        state2.bufferedRequestCount--;
        if (state2.writing) {
          break;
        }
      }
      if (entry === null) state2.lastBufferedRequest = null;
    }
    state2.bufferedRequest = entry;
    state2.bufferProcessing = false;
  }
  Writable2.prototype._write = function(chunk, encoding, cb) {
    cb(new ERR_METHOD_NOT_IMPLEMENTED("_write()"));
  };
  Writable2.prototype._writev = null;
  Writable2.prototype.end = function(chunk, encoding, cb) {
    var state2 = this._writableState;
    if (typeof chunk === "function") {
      cb = chunk;
      chunk = null;
      encoding = null;
    } else if (typeof encoding === "function") {
      cb = encoding;
      encoding = null;
    }
    if (chunk !== null && chunk !== void 0) this.write(chunk, encoding);
    if (state2.corked) {
      state2.corked = 1;
      this.uncork();
    }
    if (!state2.ending) endWritable(this, state2, cb);
    return this;
  };
  Object.defineProperty(Writable2.prototype, "writableLength", {
    // making it explicit this property is not enumerable
    // because otherwise some prototype manipulation in
    // userland will fail
    enumerable: false,
    get: function get2() {
      return this._writableState.length;
    }
  });
  function needFinish(state2) {
    return state2.ending && state2.length === 0 && state2.bufferedRequest === null && !state2.finished && !state2.writing;
  }
  function callFinal(stream, state2) {
    stream._final(function(err2) {
      state2.pendingcb--;
      if (err2) {
        errorOrDestroy(stream, err2);
      }
      state2.prefinished = true;
      stream.emit("prefinish");
      finishMaybe(stream, state2);
    });
  }
  function prefinish(stream, state2) {
    if (!state2.prefinished && !state2.finalCalled) {
      if (typeof stream._final === "function" && !state2.destroyed) {
        state2.pendingcb++;
        state2.finalCalled = true;
        process$1.nextTick(callFinal, stream, state2);
      } else {
        state2.prefinished = true;
        stream.emit("prefinish");
      }
    }
  }
  function finishMaybe(stream, state2) {
    var need = needFinish(state2);
    if (need) {
      prefinish(stream, state2);
      if (state2.pendingcb === 0) {
        state2.finished = true;
        stream.emit("finish");
        if (state2.autoDestroy) {
          var rState = stream._readableState;
          if (!rState || rState.autoDestroy && rState.endEmitted) {
            stream.destroy();
          }
        }
      }
    }
    return need;
  }
  function endWritable(stream, state2, cb) {
    state2.ending = true;
    finishMaybe(stream, state2);
    if (cb) {
      if (state2.finished) process$1.nextTick(cb);
      else stream.once("finish", cb);
    }
    state2.ended = true;
    stream.writable = false;
  }
  function onCorkedFinish(corkReq, state2, err2) {
    var entry = corkReq.entry;
    corkReq.entry = null;
    while (entry) {
      var cb = entry.callback;
      state2.pendingcb--;
      cb(err2);
      entry = entry.next;
    }
    state2.corkedRequestsFree.next = corkReq;
  }
  Object.defineProperty(Writable2.prototype, "destroyed", {
    // making it explicit this property is not enumerable
    // because otherwise some prototype manipulation in
    // userland will fail
    enumerable: false,
    get: function get2() {
      if (this._writableState === void 0) {
        return false;
      }
      return this._writableState.destroyed;
    },
    set: function set3(value) {
      if (!this._writableState) {
        return;
      }
      this._writableState.destroyed = value;
    }
  });
  Writable2.prototype.destroy = destroyImpl.destroy;
  Writable2.prototype._undestroy = destroyImpl.undestroy;
  Writable2.prototype._destroy = function(err2, cb) {
    cb(err2);
  };
  return exports$8;
}
function dew$7() {
  if (_dewExec$7) return exports$7;
  _dewExec$7 = true;
  var process$1 = process;
  var objectKeys = Object.keys || function(obj) {
    var keys2 = [];
    for (var key in obj) {
      keys2.push(key);
    }
    return keys2;
  };
  exports$7 = Duplex2;
  var Readable2 = dew$3();
  var Writable2 = dew$8();
  dew$f()(Duplex2, Readable2);
  {
    var keys = objectKeys(Writable2.prototype);
    for (var v4 = 0; v4 < keys.length; v4++) {
      var method = keys[v4];
      if (!Duplex2.prototype[method]) Duplex2.prototype[method] = Writable2.prototype[method];
    }
  }
  function Duplex2(options) {
    if (!(this instanceof Duplex2)) return new Duplex2(options);
    Readable2.call(this, options);
    Writable2.call(this, options);
    this.allowHalfOpen = true;
    if (options) {
      if (options.readable === false) this.readable = false;
      if (options.writable === false) this.writable = false;
      if (options.allowHalfOpen === false) {
        this.allowHalfOpen = false;
        this.once("end", onend);
      }
    }
  }
  Object.defineProperty(Duplex2.prototype, "writableHighWaterMark", {
    // making it explicit this property is not enumerable
    // because otherwise some prototype manipulation in
    // userland will fail
    enumerable: false,
    get: function get2() {
      return this._writableState.highWaterMark;
    }
  });
  Object.defineProperty(Duplex2.prototype, "writableBuffer", {
    // making it explicit this property is not enumerable
    // because otherwise some prototype manipulation in
    // userland will fail
    enumerable: false,
    get: function get2() {
      return this._writableState && this._writableState.getBuffer();
    }
  });
  Object.defineProperty(Duplex2.prototype, "writableLength", {
    // making it explicit this property is not enumerable
    // because otherwise some prototype manipulation in
    // userland will fail
    enumerable: false,
    get: function get2() {
      return this._writableState.length;
    }
  });
  function onend() {
    if (this._writableState.ended) return;
    process$1.nextTick(onEndNT, this);
  }
  function onEndNT(self2) {
    self2.end();
  }
  Object.defineProperty(Duplex2.prototype, "destroyed", {
    // making it explicit this property is not enumerable
    // because otherwise some prototype manipulation in
    // userland will fail
    enumerable: false,
    get: function get2() {
      if (this._readableState === void 0 || this._writableState === void 0) {
        return false;
      }
      return this._readableState.destroyed && this._writableState.destroyed;
    },
    set: function set3(value) {
      if (this._readableState === void 0 || this._writableState === void 0) {
        return;
      }
      this._readableState.destroyed = value;
      this._writableState.destroyed = value;
    }
  });
  return exports$7;
}
function dew$6() {
  if (_dewExec$6) return exports$6;
  _dewExec$6 = true;
  var ERR_STREAM_PREMATURE_CLOSE = dew$b().codes.ERR_STREAM_PREMATURE_CLOSE;
  function once3(callback) {
    var called = false;
    return function() {
      if (called) return;
      called = true;
      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }
      callback.apply(this, args);
    };
  }
  function noop2() {
  }
  function isRequest(stream) {
    return stream.setHeader && typeof stream.abort === "function";
  }
  function eos(stream, opts, callback) {
    if (typeof opts === "function") return eos(stream, null, opts);
    if (!opts) opts = {};
    callback = once3(callback || noop2);
    var readable = opts.readable || opts.readable !== false && stream.readable;
    var writable = opts.writable || opts.writable !== false && stream.writable;
    var onlegacyfinish = function onlegacyfinish2() {
      if (!stream.writable) onfinish();
    };
    var writableEnded = stream._writableState && stream._writableState.finished;
    var onfinish = function onfinish2() {
      writable = false;
      writableEnded = true;
      if (!readable) callback.call(stream);
    };
    var readableEnded = stream._readableState && stream._readableState.endEmitted;
    var onend = function onend2() {
      readable = false;
      readableEnded = true;
      if (!writable) callback.call(stream);
    };
    var onerror = function onerror2(err2) {
      callback.call(stream, err2);
    };
    var onclose = function onclose2() {
      var err2;
      if (readable && !readableEnded) {
        if (!stream._readableState || !stream._readableState.ended) err2 = new ERR_STREAM_PREMATURE_CLOSE();
        return callback.call(stream, err2);
      }
      if (writable && !writableEnded) {
        if (!stream._writableState || !stream._writableState.ended) err2 = new ERR_STREAM_PREMATURE_CLOSE();
        return callback.call(stream, err2);
      }
    };
    var onrequest = function onrequest2() {
      stream.req.on("finish", onfinish);
    };
    if (isRequest(stream)) {
      stream.on("complete", onfinish);
      stream.on("abort", onclose);
      if (stream.req) onrequest();
      else stream.on("request", onrequest);
    } else if (writable && !stream._writableState) {
      stream.on("end", onlegacyfinish);
      stream.on("close", onlegacyfinish);
    }
    stream.on("end", onend);
    stream.on("finish", onfinish);
    if (opts.error !== false) stream.on("error", onerror);
    stream.on("close", onclose);
    return function() {
      stream.removeListener("complete", onfinish);
      stream.removeListener("abort", onclose);
      stream.removeListener("request", onrequest);
      if (stream.req) stream.req.removeListener("finish", onfinish);
      stream.removeListener("end", onlegacyfinish);
      stream.removeListener("close", onlegacyfinish);
      stream.removeListener("finish", onfinish);
      stream.removeListener("end", onend);
      stream.removeListener("error", onerror);
      stream.removeListener("close", onclose);
    };
  }
  exports$6 = eos;
  return exports$6;
}
function dew$5() {
  if (_dewExec$5) return exports$5;
  _dewExec$5 = true;
  var process$1 = process;
  var _Object$setPrototypeO;
  function _defineProperty(obj, key, value) {
    if (key in obj) {
      Object.defineProperty(obj, key, {
        value,
        enumerable: true,
        configurable: true,
        writable: true
      });
    } else {
      obj[key] = value;
    }
    return obj;
  }
  var finished2 = dew$6();
  var kLastResolve = /* @__PURE__ */ Symbol("lastResolve");
  var kLastReject = /* @__PURE__ */ Symbol("lastReject");
  var kError2 = /* @__PURE__ */ Symbol("error");
  var kEnded = /* @__PURE__ */ Symbol("ended");
  var kLastPromise = /* @__PURE__ */ Symbol("lastPromise");
  var kHandlePromise = /* @__PURE__ */ Symbol("handlePromise");
  var kStream = /* @__PURE__ */ Symbol("stream");
  function createIterResult2(value, done) {
    return {
      value,
      done
    };
  }
  function readAndResolve(iter) {
    var resolve16 = iter[kLastResolve];
    if (resolve16 !== null) {
      var data3 = iter[kStream].read();
      if (data3 !== null) {
        iter[kLastPromise] = null;
        iter[kLastResolve] = null;
        iter[kLastReject] = null;
        resolve16(createIterResult2(data3, false));
      }
    }
  }
  function onReadable(iter) {
    process$1.nextTick(readAndResolve, iter);
  }
  function wrapForNext(lastPromise, iter) {
    return function(resolve16, reject2) {
      lastPromise.then(function() {
        if (iter[kEnded]) {
          resolve16(createIterResult2(void 0, true));
          return;
        }
        iter[kHandlePromise](resolve16, reject2);
      }, reject2);
    };
  }
  var AsyncIteratorPrototype = Object.getPrototypeOf(function() {
  });
  var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {
    get stream() {
      return this[kStream];
    },
    next: function next() {
      var _this = this;
      var error2 = this[kError2];
      if (error2 !== null) {
        return Promise.reject(error2);
      }
      if (this[kEnded]) {
        return Promise.resolve(createIterResult2(void 0, true));
      }
      if (this[kStream].destroyed) {
        return new Promise(function(resolve16, reject2) {
          process$1.nextTick(function() {
            if (_this[kError2]) {
              reject2(_this[kError2]);
            } else {
              resolve16(createIterResult2(void 0, true));
            }
          });
        });
      }
      var lastPromise = this[kLastPromise];
      var promise;
      if (lastPromise) {
        promise = new Promise(wrapForNext(lastPromise, this));
      } else {
        var data3 = this[kStream].read();
        if (data3 !== null) {
          return Promise.resolve(createIterResult2(data3, false));
        }
        promise = new Promise(this[kHandlePromise]);
      }
      this[kLastPromise] = promise;
      return promise;
    }
  }, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function() {
    return this;
  }), _defineProperty(_Object$setPrototypeO, "return", function _return() {
    var _this2 = this;
    return new Promise(function(resolve16, reject2) {
      _this2[kStream].destroy(null, function(err2) {
        if (err2) {
          reject2(err2);
          return;
        }
        resolve16(createIterResult2(void 0, true));
      });
    });
  }), _Object$setPrototypeO), AsyncIteratorPrototype);
  var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator2(stream) {
    var _Object$create;
    var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {
      value: stream,
      writable: true
    }), _defineProperty(_Object$create, kLastResolve, {
      value: null,
      writable: true
    }), _defineProperty(_Object$create, kLastReject, {
      value: null,
      writable: true
    }), _defineProperty(_Object$create, kError2, {
      value: null,
      writable: true
    }), _defineProperty(_Object$create, kEnded, {
      value: stream._readableState.endEmitted,
      writable: true
    }), _defineProperty(_Object$create, kHandlePromise, {
      value: function value(resolve16, reject2) {
        var data3 = iterator[kStream].read();
        if (data3) {
          iterator[kLastPromise] = null;
          iterator[kLastResolve] = null;
          iterator[kLastReject] = null;
          resolve16(createIterResult2(data3, false));
        } else {
          iterator[kLastResolve] = resolve16;
          iterator[kLastReject] = reject2;
        }
      },
      writable: true
    }), _Object$create));
    iterator[kLastPromise] = null;
    finished2(stream, function(err2) {
      if (err2 && err2.code !== "ERR_STREAM_PREMATURE_CLOSE") {
        var reject2 = iterator[kLastReject];
        if (reject2 !== null) {
          iterator[kLastPromise] = null;
          iterator[kLastResolve] = null;
          iterator[kLastReject] = null;
          reject2(err2);
        }
        iterator[kError2] = err2;
        return;
      }
      var resolve16 = iterator[kLastResolve];
      if (resolve16 !== null) {
        iterator[kLastPromise] = null;
        iterator[kLastResolve] = null;
        iterator[kLastReject] = null;
        resolve16(createIterResult2(void 0, true));
      }
      iterator[kEnded] = true;
    });
    stream.on("readable", onReadable.bind(null, iterator));
    return iterator;
  };
  exports$5 = createReadableStreamAsyncIterator;
  return exports$5;
}
function dew$4() {
  if (_dewExec$4) return exports$4;
  _dewExec$4 = true;
  exports$4 = function() {
    throw new Error("Readable.from is not available in the browser");
  };
  return exports$4;
}
function dew$3() {
  if (_dewExec$3) return exports$3;
  _dewExec$3 = true;
  var process$1 = process;
  exports$3 = Readable2;
  var Duplex2;
  Readable2.ReadableState = ReadableState;
  y.EventEmitter;
  var EElistenerCount = function EElistenerCount2(emitter, type4) {
    return emitter.listeners(type4).length;
  };
  var Stream3 = dew$e();
  var Buffer4 = buffer.Buffer;
  var OurUint8Array = _global2.Uint8Array || function() {
  };
  function _uint8ArrayToBuffer(chunk) {
    return Buffer4.from(chunk);
  }
  function _isUint8Array(obj) {
    return Buffer4.isBuffer(obj) || obj instanceof OurUint8Array;
  }
  var debugUtil = X;
  var debug4;
  if (debugUtil && debugUtil.debuglog) {
    debug4 = debugUtil.debuglog("stream");
  } else {
    debug4 = function debug5() {
    };
  }
  var BufferList = dew$d();
  var destroyImpl = dew$c();
  var _require = dew$a(), getHighWaterMark = _require.getHighWaterMark;
  var _require$codes = dew$b().codes, ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;
  var StringDecoder;
  var createReadableStreamAsyncIterator;
  var from;
  dew$f()(Readable2, Stream3);
  var errorOrDestroy = destroyImpl.errorOrDestroy;
  var kProxyEvents = ["error", "close", "destroy", "pause", "resume"];
  function prependListener2(emitter, event, fn) {
    if (typeof emitter.prependListener === "function") return emitter.prependListener(event, fn);
    if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);
    else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);
    else emitter._events[event] = [fn, emitter._events[event]];
  }
  function ReadableState(options, stream, isDuplex) {
    Duplex2 = Duplex2 || dew$7();
    options = options || {};
    if (typeof isDuplex !== "boolean") isDuplex = stream instanceof Duplex2;
    this.objectMode = !!options.objectMode;
    if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
    this.highWaterMark = getHighWaterMark(this, options, "readableHighWaterMark", isDuplex);
    this.buffer = new BufferList();
    this.length = 0;
    this.pipes = null;
    this.pipesCount = 0;
    this.flowing = null;
    this.ended = false;
    this.endEmitted = false;
    this.reading = false;
    this.sync = true;
    this.needReadable = false;
    this.emittedReadable = false;
    this.readableListening = false;
    this.resumeScheduled = false;
    this.paused = true;
    this.emitClose = options.emitClose !== false;
    this.autoDestroy = !!options.autoDestroy;
    this.destroyed = false;
    this.defaultEncoding = options.defaultEncoding || "utf8";
    this.awaitDrain = 0;
    this.readingMore = false;
    this.decoder = null;
    this.encoding = null;
    if (options.encoding) {
      if (!StringDecoder) StringDecoder = e$12.StringDecoder;
      this.decoder = new StringDecoder(options.encoding);
      this.encoding = options.encoding;
    }
  }
  function Readable2(options) {
    Duplex2 = Duplex2 || dew$7();
    if (!(this instanceof Readable2)) return new Readable2(options);
    var isDuplex = this instanceof Duplex2;
    this._readableState = new ReadableState(options, this, isDuplex);
    this.readable = true;
    if (options) {
      if (typeof options.read === "function") this._read = options.read;
      if (typeof options.destroy === "function") this._destroy = options.destroy;
    }
    Stream3.call(this);
  }
  Object.defineProperty(Readable2.prototype, "destroyed", {
    // making it explicit this property is not enumerable
    // because otherwise some prototype manipulation in
    // userland will fail
    enumerable: false,
    get: function get2() {
      if (this._readableState === void 0) {
        return false;
      }
      return this._readableState.destroyed;
    },
    set: function set3(value) {
      if (!this._readableState) {
        return;
      }
      this._readableState.destroyed = value;
    }
  });
  Readable2.prototype.destroy = destroyImpl.destroy;
  Readable2.prototype._undestroy = destroyImpl.undestroy;
  Readable2.prototype._destroy = function(err2, cb) {
    cb(err2);
  };
  Readable2.prototype.push = function(chunk, encoding) {
    var state2 = this._readableState;
    var skipChunkCheck;
    if (!state2.objectMode) {
      if (typeof chunk === "string") {
        encoding = encoding || state2.defaultEncoding;
        if (encoding !== state2.encoding) {
          chunk = Buffer4.from(chunk, encoding);
          encoding = "";
        }
        skipChunkCheck = true;
      }
    } else {
      skipChunkCheck = true;
    }
    return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
  };
  Readable2.prototype.unshift = function(chunk) {
    return readableAddChunk(this, chunk, null, true, false);
  };
  function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
    debug4("readableAddChunk", chunk);
    var state2 = stream._readableState;
    if (chunk === null) {
      state2.reading = false;
      onEofChunk(stream, state2);
    } else {
      var er;
      if (!skipChunkCheck) er = chunkInvalid(state2, chunk);
      if (er) {
        errorOrDestroy(stream, er);
      } else if (state2.objectMode || chunk && chunk.length > 0) {
        if (typeof chunk !== "string" && !state2.objectMode && Object.getPrototypeOf(chunk) !== Buffer4.prototype) {
          chunk = _uint8ArrayToBuffer(chunk);
        }
        if (addToFront) {
          if (state2.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());
          else addChunk(stream, state2, chunk, true);
        } else if (state2.ended) {
          errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());
        } else if (state2.destroyed) {
          return false;
        } else {
          state2.reading = false;
          if (state2.decoder && !encoding) {
            chunk = state2.decoder.write(chunk);
            if (state2.objectMode || chunk.length !== 0) addChunk(stream, state2, chunk, false);
            else maybeReadMore(stream, state2);
          } else {
            addChunk(stream, state2, chunk, false);
          }
        }
      } else if (!addToFront) {
        state2.reading = false;
        maybeReadMore(stream, state2);
      }
    }
    return !state2.ended && (state2.length < state2.highWaterMark || state2.length === 0);
  }
  function addChunk(stream, state2, chunk, addToFront) {
    if (state2.flowing && state2.length === 0 && !state2.sync) {
      state2.awaitDrain = 0;
      stream.emit("data", chunk);
    } else {
      state2.length += state2.objectMode ? 1 : chunk.length;
      if (addToFront) state2.buffer.unshift(chunk);
      else state2.buffer.push(chunk);
      if (state2.needReadable) emitReadable(stream);
    }
    maybeReadMore(stream, state2);
  }
  function chunkInvalid(state2, chunk) {
    var er;
    if (!_isUint8Array(chunk) && typeof chunk !== "string" && chunk !== void 0 && !state2.objectMode) {
      er = new ERR_INVALID_ARG_TYPE("chunk", ["string", "Buffer", "Uint8Array"], chunk);
    }
    return er;
  }
  Readable2.prototype.isPaused = function() {
    return this._readableState.flowing === false;
  };
  Readable2.prototype.setEncoding = function(enc) {
    if (!StringDecoder) StringDecoder = e$12.StringDecoder;
    var decoder3 = new StringDecoder(enc);
    this._readableState.decoder = decoder3;
    this._readableState.encoding = this._readableState.decoder.encoding;
    var p5 = this._readableState.buffer.head;
    var content = "";
    while (p5 !== null) {
      content += decoder3.write(p5.data);
      p5 = p5.next;
    }
    this._readableState.buffer.clear();
    if (content !== "") this._readableState.buffer.push(content);
    this._readableState.length = content.length;
    return this;
  };
  var MAX_HWM = 1073741824;
  function computeNewHighWaterMark(n5) {
    if (n5 >= MAX_HWM) {
      n5 = MAX_HWM;
    } else {
      n5--;
      n5 |= n5 >>> 1;
      n5 |= n5 >>> 2;
      n5 |= n5 >>> 4;
      n5 |= n5 >>> 8;
      n5 |= n5 >>> 16;
      n5++;
    }
    return n5;
  }
  function howMuchToRead(n5, state2) {
    if (n5 <= 0 || state2.length === 0 && state2.ended) return 0;
    if (state2.objectMode) return 1;
    if (n5 !== n5) {
      if (state2.flowing && state2.length) return state2.buffer.head.data.length;
      else return state2.length;
    }
    if (n5 > state2.highWaterMark) state2.highWaterMark = computeNewHighWaterMark(n5);
    if (n5 <= state2.length) return n5;
    if (!state2.ended) {
      state2.needReadable = true;
      return 0;
    }
    return state2.length;
  }
  Readable2.prototype.read = function(n5) {
    debug4("read", n5);
    n5 = parseInt(n5, 10);
    var state2 = this._readableState;
    var nOrig = n5;
    if (n5 !== 0) state2.emittedReadable = false;
    if (n5 === 0 && state2.needReadable && ((state2.highWaterMark !== 0 ? state2.length >= state2.highWaterMark : state2.length > 0) || state2.ended)) {
      debug4("read: emitReadable", state2.length, state2.ended);
      if (state2.length === 0 && state2.ended) endReadable(this);
      else emitReadable(this);
      return null;
    }
    n5 = howMuchToRead(n5, state2);
    if (n5 === 0 && state2.ended) {
      if (state2.length === 0) endReadable(this);
      return null;
    }
    var doRead = state2.needReadable;
    debug4("need readable", doRead);
    if (state2.length === 0 || state2.length - n5 < state2.highWaterMark) {
      doRead = true;
      debug4("length less than watermark", doRead);
    }
    if (state2.ended || state2.reading) {
      doRead = false;
      debug4("reading or ended", doRead);
    } else if (doRead) {
      debug4("do read");
      state2.reading = true;
      state2.sync = true;
      if (state2.length === 0) state2.needReadable = true;
      this._read(state2.highWaterMark);
      state2.sync = false;
      if (!state2.reading) n5 = howMuchToRead(nOrig, state2);
    }
    var ret;
    if (n5 > 0) ret = fromList(n5, state2);
    else ret = null;
    if (ret === null) {
      state2.needReadable = state2.length <= state2.highWaterMark;
      n5 = 0;
    } else {
      state2.length -= n5;
      state2.awaitDrain = 0;
    }
    if (state2.length === 0) {
      if (!state2.ended) state2.needReadable = true;
      if (nOrig !== n5 && state2.ended) endReadable(this);
    }
    if (ret !== null) this.emit("data", ret);
    return ret;
  };
  function onEofChunk(stream, state2) {
    debug4("onEofChunk");
    if (state2.ended) return;
    if (state2.decoder) {
      var chunk = state2.decoder.end();
      if (chunk && chunk.length) {
        state2.buffer.push(chunk);
        state2.length += state2.objectMode ? 1 : chunk.length;
      }
    }
    state2.ended = true;
    if (state2.sync) {
      emitReadable(stream);
    } else {
      state2.needReadable = false;
      if (!state2.emittedReadable) {
        state2.emittedReadable = true;
        emitReadable_(stream);
      }
    }
  }
  function emitReadable(stream) {
    var state2 = stream._readableState;
    debug4("emitReadable", state2.needReadable, state2.emittedReadable);
    state2.needReadable = false;
    if (!state2.emittedReadable) {
      debug4("emitReadable", state2.flowing);
      state2.emittedReadable = true;
      process$1.nextTick(emitReadable_, stream);
    }
  }
  function emitReadable_(stream) {
    var state2 = stream._readableState;
    debug4("emitReadable_", state2.destroyed, state2.length, state2.ended);
    if (!state2.destroyed && (state2.length || state2.ended)) {
      stream.emit("readable");
      state2.emittedReadable = false;
    }
    state2.needReadable = !state2.flowing && !state2.ended && state2.length <= state2.highWaterMark;
    flow(stream);
  }
  function maybeReadMore(stream, state2) {
    if (!state2.readingMore) {
      state2.readingMore = true;
      process$1.nextTick(maybeReadMore_, stream, state2);
    }
  }
  function maybeReadMore_(stream, state2) {
    while (!state2.reading && !state2.ended && (state2.length < state2.highWaterMark || state2.flowing && state2.length === 0)) {
      var len = state2.length;
      debug4("maybeReadMore read 0");
      stream.read(0);
      if (len === state2.length)
        break;
    }
    state2.readingMore = false;
  }
  Readable2.prototype._read = function(n5) {
    errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED("_read()"));
  };
  Readable2.prototype.pipe = function(dest, pipeOpts) {
    var src2 = this;
    var state2 = this._readableState;
    switch (state2.pipesCount) {
      case 0:
        state2.pipes = dest;
        break;
      case 1:
        state2.pipes = [state2.pipes, dest];
        break;
      default:
        state2.pipes.push(dest);
        break;
    }
    state2.pipesCount += 1;
    debug4("pipe count=%d opts=%j", state2.pipesCount, pipeOpts);
    var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process$1.stdout && dest !== process$1.stderr;
    var endFn = doEnd ? onend : unpipe;
    if (state2.endEmitted) process$1.nextTick(endFn);
    else src2.once("end", endFn);
    dest.on("unpipe", onunpipe);
    function onunpipe(readable, unpipeInfo) {
      debug4("onunpipe");
      if (readable === src2) {
        if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
          unpipeInfo.hasUnpiped = true;
          cleanup2();
        }
      }
    }
    function onend() {
      debug4("onend");
      dest.end();
    }
    var ondrain = pipeOnDrain(src2);
    dest.on("drain", ondrain);
    var cleanedUp = false;
    function cleanup2() {
      debug4("cleanup");
      dest.removeListener("close", onclose);
      dest.removeListener("finish", onfinish);
      dest.removeListener("drain", ondrain);
      dest.removeListener("error", onerror);
      dest.removeListener("unpipe", onunpipe);
      src2.removeListener("end", onend);
      src2.removeListener("end", unpipe);
      src2.removeListener("data", ondata);
      cleanedUp = true;
      if (state2.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
    }
    src2.on("data", ondata);
    function ondata(chunk) {
      debug4("ondata");
      var ret = dest.write(chunk);
      debug4("dest.write", ret);
      if (ret === false) {
        if ((state2.pipesCount === 1 && state2.pipes === dest || state2.pipesCount > 1 && indexOf2(state2.pipes, dest) !== -1) && !cleanedUp) {
          debug4("false write response, pause", state2.awaitDrain);
          state2.awaitDrain++;
        }
        src2.pause();
      }
    }
    function onerror(er) {
      debug4("onerror", er);
      unpipe();
      dest.removeListener("error", onerror);
      if (EElistenerCount(dest, "error") === 0) errorOrDestroy(dest, er);
    }
    prependListener2(dest, "error", onerror);
    function onclose() {
      dest.removeListener("finish", onfinish);
      unpipe();
    }
    dest.once("close", onclose);
    function onfinish() {
      debug4("onfinish");
      dest.removeListener("close", onclose);
      unpipe();
    }
    dest.once("finish", onfinish);
    function unpipe() {
      debug4("unpipe");
      src2.unpipe(dest);
    }
    dest.emit("pipe", src2);
    if (!state2.flowing) {
      debug4("pipe resume");
      src2.resume();
    }
    return dest;
  };
  function pipeOnDrain(src2) {
    return function pipeOnDrainFunctionResult() {
      var state2 = src2._readableState;
      debug4("pipeOnDrain", state2.awaitDrain);
      if (state2.awaitDrain) state2.awaitDrain--;
      if (state2.awaitDrain === 0 && EElistenerCount(src2, "data")) {
        state2.flowing = true;
        flow(src2);
      }
    };
  }
  Readable2.prototype.unpipe = function(dest) {
    var state2 = this._readableState;
    var unpipeInfo = {
      hasUnpiped: false
    };
    if (state2.pipesCount === 0) return this;
    if (state2.pipesCount === 1) {
      if (dest && dest !== state2.pipes) return this;
      if (!dest) dest = state2.pipes;
      state2.pipes = null;
      state2.pipesCount = 0;
      state2.flowing = false;
      if (dest) dest.emit("unpipe", this, unpipeInfo);
      return this;
    }
    if (!dest) {
      var dests = state2.pipes;
      var len = state2.pipesCount;
      state2.pipes = null;
      state2.pipesCount = 0;
      state2.flowing = false;
      for (var i6 = 0; i6 < len; i6++) {
        dests[i6].emit("unpipe", this, {
          hasUnpiped: false
        });
      }
      return this;
    }
    var index2 = indexOf2(state2.pipes, dest);
    if (index2 === -1) return this;
    state2.pipes.splice(index2, 1);
    state2.pipesCount -= 1;
    if (state2.pipesCount === 1) state2.pipes = state2.pipes[0];
    dest.emit("unpipe", this, unpipeInfo);
    return this;
  };
  Readable2.prototype.on = function(ev, fn) {
    var res = Stream3.prototype.on.call(this, ev, fn);
    var state2 = this._readableState;
    if (ev === "data") {
      state2.readableListening = this.listenerCount("readable") > 0;
      if (state2.flowing !== false) this.resume();
    } else if (ev === "readable") {
      if (!state2.endEmitted && !state2.readableListening) {
        state2.readableListening = state2.needReadable = true;
        state2.flowing = false;
        state2.emittedReadable = false;
        debug4("on readable", state2.length, state2.reading);
        if (state2.length) {
          emitReadable(this);
        } else if (!state2.reading) {
          process$1.nextTick(nReadingNextTick, this);
        }
      }
    }
    return res;
  };
  Readable2.prototype.addListener = Readable2.prototype.on;
  Readable2.prototype.removeListener = function(ev, fn) {
    var res = Stream3.prototype.removeListener.call(this, ev, fn);
    if (ev === "readable") {
      process$1.nextTick(updateReadableListening, this);
    }
    return res;
  };
  Readable2.prototype.removeAllListeners = function(ev) {
    var res = Stream3.prototype.removeAllListeners.apply(this, arguments);
    if (ev === "readable" || ev === void 0) {
      process$1.nextTick(updateReadableListening, this);
    }
    return res;
  };
  function updateReadableListening(self2) {
    var state2 = self2._readableState;
    state2.readableListening = self2.listenerCount("readable") > 0;
    if (state2.resumeScheduled && !state2.paused) {
      state2.flowing = true;
    } else if (self2.listenerCount("data") > 0) {
      self2.resume();
    }
  }
  function nReadingNextTick(self2) {
    debug4("readable nexttick read 0");
    self2.read(0);
  }
  Readable2.prototype.resume = function() {
    var state2 = this._readableState;
    if (!state2.flowing) {
      debug4("resume");
      state2.flowing = !state2.readableListening;
      resume(this, state2);
    }
    state2.paused = false;
    return this;
  };
  function resume(stream, state2) {
    if (!state2.resumeScheduled) {
      state2.resumeScheduled = true;
      process$1.nextTick(resume_, stream, state2);
    }
  }
  function resume_(stream, state2) {
    debug4("resume", state2.reading);
    if (!state2.reading) {
      stream.read(0);
    }
    state2.resumeScheduled = false;
    stream.emit("resume");
    flow(stream);
    if (state2.flowing && !state2.reading) stream.read(0);
  }
  Readable2.prototype.pause = function() {
    debug4("call pause flowing=%j", this._readableState.flowing);
    if (this._readableState.flowing !== false) {
      debug4("pause");
      this._readableState.flowing = false;
      this.emit("pause");
    }
    this._readableState.paused = true;
    return this;
  };
  function flow(stream) {
    var state2 = stream._readableState;
    debug4("flow", state2.flowing);
    while (state2.flowing && stream.read() !== null) {
    }
  }
  Readable2.prototype.wrap = function(stream) {
    var _this = this;
    var state2 = this._readableState;
    var paused = false;
    stream.on("end", function() {
      debug4("wrapped end");
      if (state2.decoder && !state2.ended) {
        var chunk = state2.decoder.end();
        if (chunk && chunk.length) _this.push(chunk);
      }
      _this.push(null);
    });
    stream.on("data", function(chunk) {
      debug4("wrapped data");
      if (state2.decoder) chunk = state2.decoder.write(chunk);
      if (state2.objectMode && (chunk === null || chunk === void 0)) return;
      else if (!state2.objectMode && (!chunk || !chunk.length)) return;
      var ret = _this.push(chunk);
      if (!ret) {
        paused = true;
        stream.pause();
      }
    });
    for (var i6 in stream) {
      if (this[i6] === void 0 && typeof stream[i6] === "function") {
        this[i6] = /* @__PURE__ */ (function methodWrap(method) {
          return function methodWrapReturnFunction() {
            return stream[method].apply(stream, arguments);
          };
        })(i6);
      }
    }
    for (var n5 = 0; n5 < kProxyEvents.length; n5++) {
      stream.on(kProxyEvents[n5], this.emit.bind(this, kProxyEvents[n5]));
    }
    this._read = function(n6) {
      debug4("wrapped _read", n6);
      if (paused) {
        paused = false;
        stream.resume();
      }
    };
    return this;
  };
  if (typeof Symbol === "function") {
    Readable2.prototype[Symbol.asyncIterator] = function() {
      if (createReadableStreamAsyncIterator === void 0) {
        createReadableStreamAsyncIterator = dew$5();
      }
      return createReadableStreamAsyncIterator(this);
    };
  }
  Object.defineProperty(Readable2.prototype, "readableHighWaterMark", {
    // making it explicit this property is not enumerable
    // because otherwise some prototype manipulation in
    // userland will fail
    enumerable: false,
    get: function get2() {
      return this._readableState.highWaterMark;
    }
  });
  Object.defineProperty(Readable2.prototype, "readableBuffer", {
    // making it explicit this property is not enumerable
    // because otherwise some prototype manipulation in
    // userland will fail
    enumerable: false,
    get: function get2() {
      return this._readableState && this._readableState.buffer;
    }
  });
  Object.defineProperty(Readable2.prototype, "readableFlowing", {
    // making it explicit this property is not enumerable
    // because otherwise some prototype manipulation in
    // userland will fail
    enumerable: false,
    get: function get2() {
      return this._readableState.flowing;
    },
    set: function set3(state2) {
      if (this._readableState) {
        this._readableState.flowing = state2;
      }
    }
  });
  Readable2._fromList = fromList;
  Object.defineProperty(Readable2.prototype, "readableLength", {
    // making it explicit this property is not enumerable
    // because otherwise some prototype manipulation in
    // userland will fail
    enumerable: false,
    get: function get2() {
      return this._readableState.length;
    }
  });
  function fromList(n5, state2) {
    if (state2.length === 0) return null;
    var ret;
    if (state2.objectMode) ret = state2.buffer.shift();
    else if (!n5 || n5 >= state2.length) {
      if (state2.decoder) ret = state2.buffer.join("");
      else if (state2.buffer.length === 1) ret = state2.buffer.first();
      else ret = state2.buffer.concat(state2.length);
      state2.buffer.clear();
    } else {
      ret = state2.buffer.consume(n5, state2.decoder);
    }
    return ret;
  }
  function endReadable(stream) {
    var state2 = stream._readableState;
    debug4("endReadable", state2.endEmitted);
    if (!state2.endEmitted) {
      state2.ended = true;
      process$1.nextTick(endReadableNT, state2, stream);
    }
  }
  function endReadableNT(state2, stream) {
    debug4("endReadableNT", state2.endEmitted, state2.length);
    if (!state2.endEmitted && state2.length === 0) {
      state2.endEmitted = true;
      stream.readable = false;
      stream.emit("end");
      if (state2.autoDestroy) {
        var wState = stream._writableState;
        if (!wState || wState.autoDestroy && wState.finished) {
          stream.destroy();
        }
      }
    }
  }
  if (typeof Symbol === "function") {
    Readable2.from = function(iterable, opts) {
      if (from === void 0) {
        from = dew$4();
      }
      return from(Readable2, iterable, opts);
    };
  }
  function indexOf2(xs, x3) {
    for (var i6 = 0, l6 = xs.length; i6 < l6; i6++) {
      if (xs[i6] === x3) return i6;
    }
    return -1;
  }
  return exports$3;
}
function dew$2() {
  if (_dewExec$2) return exports$2;
  _dewExec$2 = true;
  exports$2 = Transform2;
  var _require$codes = dew$b().codes, ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;
  var Duplex2 = dew$7();
  dew$f()(Transform2, Duplex2);
  function afterTransform(er, data3) {
    var ts = this._transformState;
    ts.transforming = false;
    var cb = ts.writecb;
    if (cb === null) {
      return this.emit("error", new ERR_MULTIPLE_CALLBACK());
    }
    ts.writechunk = null;
    ts.writecb = null;
    if (data3 != null)
      this.push(data3);
    cb(er);
    var rs = this._readableState;
    rs.reading = false;
    if (rs.needReadable || rs.length < rs.highWaterMark) {
      this._read(rs.highWaterMark);
    }
  }
  function Transform2(options) {
    if (!(this instanceof Transform2)) return new Transform2(options);
    Duplex2.call(this, options);
    this._transformState = {
      afterTransform: afterTransform.bind(this),
      needTransform: false,
      transforming: false,
      writecb: null,
      writechunk: null,
      writeencoding: null
    };
    this._readableState.needReadable = true;
    this._readableState.sync = false;
    if (options) {
      if (typeof options.transform === "function") this._transform = options.transform;
      if (typeof options.flush === "function") this._flush = options.flush;
    }
    this.on("prefinish", prefinish);
  }
  function prefinish() {
    var _this = this;
    if (typeof this._flush === "function" && !this._readableState.destroyed) {
      this._flush(function(er, data3) {
        done(_this, er, data3);
      });
    } else {
      done(this, null, null);
    }
  }
  Transform2.prototype.push = function(chunk, encoding) {
    this._transformState.needTransform = false;
    return Duplex2.prototype.push.call(this, chunk, encoding);
  };
  Transform2.prototype._transform = function(chunk, encoding, cb) {
    cb(new ERR_METHOD_NOT_IMPLEMENTED("_transform()"));
  };
  Transform2.prototype._write = function(chunk, encoding, cb) {
    var ts = this._transformState;
    ts.writecb = cb;
    ts.writechunk = chunk;
    ts.writeencoding = encoding;
    if (!ts.transforming) {
      var rs = this._readableState;
      if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
    }
  };
  Transform2.prototype._read = function(n5) {
    var ts = this._transformState;
    if (ts.writechunk !== null && !ts.transforming) {
      ts.transforming = true;
      this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
    } else {
      ts.needTransform = true;
    }
  };
  Transform2.prototype._destroy = function(err2, cb) {
    Duplex2.prototype._destroy.call(this, err2, function(err22) {
      cb(err22);
    });
  };
  function done(stream, er, data3) {
    if (er) return stream.emit("error", er);
    if (data3 != null)
      stream.push(data3);
    if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();
    if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();
    return stream.push(null);
  }
  return exports$2;
}
function dew$1() {
  if (_dewExec$1) return exports$1;
  _dewExec$1 = true;
  exports$1 = PassThrough2;
  var Transform2 = dew$2();
  dew$f()(PassThrough2, Transform2);
  function PassThrough2(options) {
    if (!(this instanceof PassThrough2)) return new PassThrough2(options);
    Transform2.call(this, options);
  }
  PassThrough2.prototype._transform = function(chunk, encoding, cb) {
    cb(null, chunk);
  };
  return exports$1;
}
function dew2() {
  if (_dewExec2) return exports2;
  _dewExec2 = true;
  var eos;
  function once3(callback) {
    var called = false;
    return function() {
      if (called) return;
      called = true;
      callback.apply(void 0, arguments);
    };
  }
  var _require$codes = dew$b().codes, ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;
  function noop2(err2) {
    if (err2) throw err2;
  }
  function isRequest(stream) {
    return stream.setHeader && typeof stream.abort === "function";
  }
  function destroyer(stream, reading, writing, callback) {
    callback = once3(callback);
    var closed = false;
    stream.on("close", function() {
      closed = true;
    });
    if (eos === void 0) eos = dew$6();
    eos(stream, {
      readable: reading,
      writable: writing
    }, function(err2) {
      if (err2) return callback(err2);
      closed = true;
      callback();
    });
    var destroyed = false;
    return function(err2) {
      if (closed) return;
      if (destroyed) return;
      destroyed = true;
      if (isRequest(stream)) return stream.abort();
      if (typeof stream.destroy === "function") return stream.destroy();
      callback(err2 || new ERR_STREAM_DESTROYED("pipe"));
    };
  }
  function call2(fn) {
    fn();
  }
  function pipe(from, to) {
    return from.pipe(to);
  }
  function popCallback(streams) {
    if (!streams.length) return noop2;
    if (typeof streams[streams.length - 1] !== "function") return noop2;
    return streams.pop();
  }
  function pipeline2() {
    for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {
      streams[_key] = arguments[_key];
    }
    var callback = popCallback(streams);
    if (Array.isArray(streams[0])) streams = streams[0];
    if (streams.length < 2) {
      throw new ERR_MISSING_ARGS("streams");
    }
    var error2;
    var destroys = streams.map(function(stream, i6) {
      var reading = i6 < streams.length - 1;
      var writing = i6 > 0;
      return destroyer(stream, reading, writing, function(err2) {
        if (!error2) error2 = err2;
        if (err2) destroys.forEach(call2);
        if (reading) return;
        destroys.forEach(call2);
        callback(error2);
      });
    });
    return streams.reduce(pipe);
  }
  exports2 = pipeline2;
  return exports2;
}
var exports$2$1, _dewExec$2$1, exports$1$1, _dewExec$1$1, exports$g, _dewExec$g, buffer, exports$f, _dewExec$f, exports$e, _dewExec$e, exports$d, _dewExec$d, exports$c, _dewExec$c, exports$b, _dewExec$b, exports$a, _dewExec$a, exports$9, _dewExec$9, _global$2, exports$8, _dewExec$8, _global$1, exports$7, _dewExec$7, exports$6, _dewExec$6, exports$5, _dewExec$5, exports$4, _dewExec$4, exports$3, _dewExec$3, _global2, exports$2, _dewExec$2, exports$1, _dewExec$1, exports2, _dewExec2;
var init_dc3f476 = __esm({
  "https://dev.jspm.io/npm:@jspm/core@2.0.1/_/8dc3f476.js"() {
    init_ddf35de();
    init_a421dfba();
    init_c48();
    init_e0803811();
    init_cb95b980();
    exports$2$1 = {};
    _dewExec$2$1 = false;
    exports$1$1 = {};
    _dewExec$1$1 = false;
    exports$g = {};
    _dewExec$g = false;
    buffer = dew$g();
    buffer.Buffer;
    buffer.INSPECT_MAX_BYTES;
    buffer.kMaxLength;
    exports$f = {};
    _dewExec$f = false;
    exports$e = {};
    _dewExec$e = false;
    exports$d = {};
    _dewExec$d = false;
    exports$c = {};
    _dewExec$c = false;
    exports$b = {};
    _dewExec$b = false;
    exports$a = {};
    _dewExec$a = false;
    exports$9 = {};
    _dewExec$9 = false;
    _global$2 = typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : global;
    exports$8 = {};
    _dewExec$8 = false;
    _global$1 = typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : global;
    exports$7 = {};
    _dewExec$7 = false;
    exports$6 = {};
    _dewExec$6 = false;
    exports$5 = {};
    _dewExec$5 = false;
    exports$4 = {};
    _dewExec$4 = false;
    exports$3 = {};
    _dewExec$3 = false;
    _global2 = typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : global;
    exports$2 = {};
    _dewExec$2 = false;
    exports$1 = {};
    _dewExec$1 = false;
    exports2 = {};
    _dewExec2 = false;
  }
});

// https://dev.jspm.io/npm:@jspm/core@2.0.1/_/a17f45f2.js
function dew3() {
  if (_dewExec3) return exports$12;
  _dewExec3 = true;
  exports$12 = Stream3;
  var EE = y.EventEmitter;
  var inherits3 = dew$f();
  inherits3(Stream3, EE);
  Stream3.Readable = dew$3();
  Stream3.Writable = dew$8();
  Stream3.Duplex = dew$7();
  Stream3.Transform = dew$2();
  Stream3.PassThrough = dew$1();
  Stream3.finished = dew$6();
  Stream3.pipeline = dew2();
  Stream3.Stream = Stream3;
  function Stream3() {
    EE.call(this || _global3);
  }
  Stream3.prototype.pipe = function(dest, options) {
    var source2 = this || _global3;
    function ondata(chunk) {
      if (dest.writable) {
        if (false === dest.write(chunk) && source2.pause) {
          source2.pause();
        }
      }
    }
    source2.on("data", ondata);
    function ondrain() {
      if (source2.readable && source2.resume) {
        source2.resume();
      }
    }
    dest.on("drain", ondrain);
    if (!dest._isStdio && (!options || options.end !== false)) {
      source2.on("end", onend);
      source2.on("close", onclose);
    }
    var didOnEnd = false;
    function onend() {
      if (didOnEnd) return;
      didOnEnd = true;
      dest.end();
    }
    function onclose() {
      if (didOnEnd) return;
      didOnEnd = true;
      if (typeof dest.destroy === "function") dest.destroy();
    }
    function onerror(er) {
      cleanup2();
      if (EE.listenerCount(this || _global3, "error") === 0) {
        throw er;
      }
    }
    source2.on("error", onerror);
    dest.on("error", onerror);
    function cleanup2() {
      source2.removeListener("data", ondata);
      dest.removeListener("drain", ondrain);
      source2.removeListener("end", onend);
      source2.removeListener("close", onclose);
      source2.removeListener("error", onerror);
      dest.removeListener("error", onerror);
      source2.removeListener("end", cleanup2);
      source2.removeListener("close", cleanup2);
      dest.removeListener("close", cleanup2);
    }
    source2.on("end", cleanup2);
    source2.on("close", cleanup2);
    dest.on("close", cleanup2);
    dest.emit("pipe", source2);
    return dest;
  };
  return exports$12;
}
var exports$12, _dewExec3, _global3, exports3;
var init_a17f45f2 = __esm({
  "https://dev.jspm.io/npm:@jspm/core@2.0.1/_/a17f45f2.js"() {
    init_events();
    init_dc3f476();
    init_ddf35de();
    exports$12 = {};
    _dewExec3 = false;
    _global3 = typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : global;
    exports3 = dew3();
  }
});

// https://dev.jspm.io/npm:@jspm/core@2.0.1/nodelibs/util
var _extend2, callbackify2, debuglog2, deprecate2, format7, inherits2, inspect3, isArray3, isBoolean4, isBuffer2, isDate2, isError2, isFunction2, isNull4, isNullOrUndefined2, isNumber3, isObject6, isPrimitive2, isRegExp2, isString3, isSymbol2, isUndefined2, log2, promisify2, types3, TextEncoder3, TextDecoder3;
var init_util8 = __esm({
  "https://dev.jspm.io/npm:@jspm/core@2.0.1/nodelibs/util"() {
    init_a421dfba();
    init_c48();
    init_c48();
    init_ae550();
    _extend2 = X._extend;
    callbackify2 = X.callbackify;
    debuglog2 = X.debuglog;
    deprecate2 = X.deprecate;
    format7 = X.format;
    inherits2 = X.inherits;
    inspect3 = X.inspect;
    isArray3 = X.isArray;
    isBoolean4 = X.isBoolean;
    isBuffer2 = X.isBuffer;
    isDate2 = X.isDate;
    isError2 = X.isError;
    isFunction2 = X.isFunction;
    isNull4 = X.isNull;
    isNullOrUndefined2 = X.isNullOrUndefined;
    isNumber3 = X.isNumber;
    isObject6 = X.isObject;
    isPrimitive2 = X.isPrimitive;
    isRegExp2 = X.isRegExp;
    isString3 = X.isString;
    isSymbol2 = X.isSymbol;
    isUndefined2 = X.isUndefined;
    log2 = X.log;
    promisify2 = X.promisify;
    types3 = X.types;
    TextEncoder3 = X.TextEncoder = globalThis.TextEncoder;
    TextDecoder3 = X.TextDecoder = globalThis.TextDecoder;
  }
});

// https://dev.jspm.io/npm:@jspm/core@2.0.1/nodelibs/stream
var Readable, Writable, Duplex, Transform, PassThrough, finished, pipeline, Stream, promises;
var init_stream = __esm({
  "https://dev.jspm.io/npm:@jspm/core@2.0.1/nodelibs/stream"() {
    init_a17f45f2();
    init_a17f45f2();
    init_util8();
    init_events();
    init_ddf35de();
    init_dc3f476();
    init_a421dfba();
    init_c48();
    init_ae550();
    init_e0803811();
    init_cb95b980();
    Readable = exports3.Readable;
    Readable.wrap = function(src2, options) {
      options = Object.assign({ objectMode: src2.readableObjectMode != null || src2.objectMode != null || true }, options);
      options.destroy = function(err2, callback) {
        src2.destroy(err2);
        callback(err2);
      };
      return new Readable(options).wrap(src2);
    };
    Writable = exports3.Writable;
    Duplex = exports3.Duplex;
    Transform = exports3.Transform;
    PassThrough = exports3.PassThrough;
    finished = exports3.finished;
    pipeline = exports3.pipeline;
    Stream = exports3.Stream;
    promises = {
      finished: promisify2(exports3.finished),
      pipeline: promisify2(exports3.pipeline)
    };
  }
});

// https://dev.jspm.io/npm:@jspm/core@2/nodelibs/stream
var init_stream2 = __esm({
  "https://dev.jspm.io/npm:@jspm/core@2/nodelibs/stream"() {
    init_a17f45f2();
    init_util8();
    init_events();
    init_ddf35de();
    init_dc3f476();
    init_a421dfba();
    init_c48();
    init_ae550();
    init_e0803811();
    init_cb95b980();
    init_stream();
    init_stream();
  }
});

// https://dev.jspm.io/npm:jszip@3.5.0/_/89f50b93.js
function dew4() {
  if (_dewExec4) return exports4;
  _dewExec4 = true;
  exports4 = exports3;
  return exports4;
}
var exports4, _dewExec4;
var init_f50b93 = __esm({
  "https://dev.jspm.io/npm:jszip@3.5.0/_/89f50b93.js"() {
    init_stream2();
    exports4 = {};
    _dewExec4 = false;
  }
});

// https://dev.jspm.io/npm:@jspm/core@2.0.1/nodelibs/buffer
function dew$22() {
  if (_dewExec$22) return exports$32;
  _dewExec$22 = true;
  exports$32.byteLength = byteLength;
  exports$32.toByteArray = toByteArray;
  exports$32.fromByteArray = fromByteArray;
  var lookup3 = [];
  var revLookup = [];
  var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array;
  var code5 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  for (var i6 = 0, len = code5.length; i6 < len; ++i6) {
    lookup3[i6] = code5[i6];
    revLookup[code5.charCodeAt(i6)] = i6;
  }
  revLookup["-".charCodeAt(0)] = 62;
  revLookup["_".charCodeAt(0)] = 63;
  function getLens(b64) {
    var len2 = b64.length;
    if (len2 % 4 > 0) {
      throw new Error("Invalid string. Length must be a multiple of 4");
    }
    var validLen = b64.indexOf("=");
    if (validLen === -1) validLen = len2;
    var placeHoldersLen = validLen === len2 ? 0 : 4 - validLen % 4;
    return [validLen, placeHoldersLen];
  }
  function byteLength(b64) {
    var lens = getLens(b64);
    var validLen = lens[0];
    var placeHoldersLen = lens[1];
    return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
  }
  function _byteLength(b64, validLen, placeHoldersLen) {
    return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
  }
  function toByteArray(b64) {
    var tmp;
    var lens = getLens(b64);
    var validLen = lens[0];
    var placeHoldersLen = lens[1];
    var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen));
    var curByte = 0;
    var len2 = placeHoldersLen > 0 ? validLen - 4 : validLen;
    var i7;
    for (i7 = 0; i7 < len2; i7 += 4) {
      tmp = revLookup[b64.charCodeAt(i7)] << 18 | revLookup[b64.charCodeAt(i7 + 1)] << 12 | revLookup[b64.charCodeAt(i7 + 2)] << 6 | revLookup[b64.charCodeAt(i7 + 3)];
      arr[curByte++] = tmp >> 16 & 255;
      arr[curByte++] = tmp >> 8 & 255;
      arr[curByte++] = tmp & 255;
    }
    if (placeHoldersLen === 2) {
      tmp = revLookup[b64.charCodeAt(i7)] << 2 | revLookup[b64.charCodeAt(i7 + 1)] >> 4;
      arr[curByte++] = tmp & 255;
    }
    if (placeHoldersLen === 1) {
      tmp = revLookup[b64.charCodeAt(i7)] << 10 | revLookup[b64.charCodeAt(i7 + 1)] << 4 | revLookup[b64.charCodeAt(i7 + 2)] >> 2;
      arr[curByte++] = tmp >> 8 & 255;
      arr[curByte++] = tmp & 255;
    }
    return arr;
  }
  function tripletToBase64(num) {
    return lookup3[num >> 18 & 63] + lookup3[num >> 12 & 63] + lookup3[num >> 6 & 63] + lookup3[num & 63];
  }
  function encodeChunk(uint8, start, end) {
    var tmp;
    var output = [];
    for (var i7 = start; i7 < end; i7 += 3) {
      tmp = (uint8[i7] << 16 & 16711680) + (uint8[i7 + 1] << 8 & 65280) + (uint8[i7 + 2] & 255);
      output.push(tripletToBase64(tmp));
    }
    return output.join("");
  }
  function fromByteArray(uint8) {
    var tmp;
    var len2 = uint8.length;
    var extraBytes = len2 % 3;
    var parts = [];
    var maxChunkLength = 16383;
    for (var i7 = 0, len22 = len2 - extraBytes; i7 < len22; i7 += maxChunkLength) {
      parts.push(encodeChunk(uint8, i7, i7 + maxChunkLength > len22 ? len22 : i7 + maxChunkLength));
    }
    if (extraBytes === 1) {
      tmp = uint8[len2 - 1];
      parts.push(lookup3[tmp >> 2] + lookup3[tmp << 4 & 63] + "==");
    } else if (extraBytes === 2) {
      tmp = (uint8[len2 - 2] << 8) + uint8[len2 - 1];
      parts.push(lookup3[tmp >> 10] + lookup3[tmp >> 4 & 63] + lookup3[tmp << 2 & 63] + "=");
    }
    return parts.join("");
  }
  return exports$32;
}
function dew$12() {
  if (_dewExec$12) return exports$22;
  _dewExec$12 = true;
  exports$22.read = function(buffer2, offset3, isLE, mLen, nBytes) {
    var e5, m4;
    var eLen = nBytes * 8 - mLen - 1;
    var eMax = (1 << eLen) - 1;
    var eBias = eMax >> 1;
    var nBits = -7;
    var i6 = isLE ? nBytes - 1 : 0;
    var d4 = isLE ? -1 : 1;
    var s5 = buffer2[offset3 + i6];
    i6 += d4;
    e5 = s5 & (1 << -nBits) - 1;
    s5 >>= -nBits;
    nBits += eLen;
    for (; nBits > 0; e5 = e5 * 256 + buffer2[offset3 + i6], i6 += d4, nBits -= 8) {
    }
    m4 = e5 & (1 << -nBits) - 1;
    e5 >>= -nBits;
    nBits += mLen;
    for (; nBits > 0; m4 = m4 * 256 + buffer2[offset3 + i6], i6 += d4, nBits -= 8) {
    }
    if (e5 === 0) {
      e5 = 1 - eBias;
    } else if (e5 === eMax) {
      return m4 ? NaN : (s5 ? -1 : 1) * Infinity;
    } else {
      m4 = m4 + Math.pow(2, mLen);
      e5 = e5 - eBias;
    }
    return (s5 ? -1 : 1) * m4 * Math.pow(2, e5 - mLen);
  };
  exports$22.write = function(buffer2, value, offset3, isLE, mLen, nBytes) {
    var e5, m4, c6;
    var eLen = nBytes * 8 - mLen - 1;
    var eMax = (1 << eLen) - 1;
    var eBias = eMax >> 1;
    var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
    var i6 = isLE ? 0 : nBytes - 1;
    var d4 = isLE ? 1 : -1;
    var s5 = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
    value = Math.abs(value);
    if (isNaN(value) || value === Infinity) {
      m4 = isNaN(value) ? 1 : 0;
      e5 = eMax;
    } else {
      e5 = Math.floor(Math.log(value) / Math.LN2);
      if (value * (c6 = Math.pow(2, -e5)) < 1) {
        e5--;
        c6 *= 2;
      }
      if (e5 + eBias >= 1) {
        value += rt / c6;
      } else {
        value += rt * Math.pow(2, 1 - eBias);
      }
      if (value * c6 >= 2) {
        e5++;
        c6 /= 2;
      }
      if (e5 + eBias >= eMax) {
        m4 = 0;
        e5 = eMax;
      } else if (e5 + eBias >= 1) {
        m4 = (value * c6 - 1) * Math.pow(2, mLen);
        e5 = e5 + eBias;
      } else {
        m4 = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
        e5 = 0;
      }
    }
    for (; mLen >= 8; buffer2[offset3 + i6] = m4 & 255, i6 += d4, m4 /= 256, mLen -= 8) {
    }
    e5 = e5 << mLen | m4;
    eLen += mLen;
    for (; eLen > 0; buffer2[offset3 + i6] = e5 & 255, i6 += d4, e5 /= 256, eLen -= 8) {
    }
    buffer2[offset3 + i6 - d4] |= s5 * 128;
  };
  return exports$22;
}
function dew5() {
  if (_dewExec5) return exports$13;
  _dewExec5 = true;
  const base642 = dew$22();
  const ieee754 = dew$12();
  const customInspectSymbol = typeof Symbol === "function" && typeof Symbol["for"] === "function" ? Symbol["for"]("nodejs.util.inspect.custom") : null;
  exports$13.Buffer = Buffer4;
  exports$13.SlowBuffer = SlowBuffer;
  exports$13.INSPECT_MAX_BYTES = 50;
  const K_MAX_LENGTH = 2147483647;
  exports$13.kMaxLength = K_MAX_LENGTH;
  Buffer4.TYPED_ARRAY_SUPPORT = typedArraySupport();
  if (!Buffer4.TYPED_ARRAY_SUPPORT && typeof console !== "undefined" && typeof console.error === "function") {
    console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");
  }
  function typedArraySupport() {
    try {
      const arr = new Uint8Array(1);
      const proto2 = {
        foo: function() {
          return 42;
        }
      };
      Object.setPrototypeOf(proto2, Uint8Array.prototype);
      Object.setPrototypeOf(arr, proto2);
      return arr.foo() === 42;
    } catch (e5) {
      return false;
    }
  }
  Object.defineProperty(Buffer4.prototype, "parent", {
    enumerable: true,
    get: function() {
      if (!Buffer4.isBuffer(this)) return void 0;
      return this.buffer;
    }
  });
  Object.defineProperty(Buffer4.prototype, "offset", {
    enumerable: true,
    get: function() {
      if (!Buffer4.isBuffer(this)) return void 0;
      return this.byteOffset;
    }
  });
  function createBuffer(length) {
    if (length > K_MAX_LENGTH) {
      throw new RangeError('The value "' + length + '" is invalid for option "size"');
    }
    const buf = new Uint8Array(length);
    Object.setPrototypeOf(buf, Buffer4.prototype);
    return buf;
  }
  function Buffer4(arg, encodingOrOffset, length) {
    if (typeof arg === "number") {
      if (typeof encodingOrOffset === "string") {
        throw new TypeError('The "string" argument must be of type string. Received type number');
      }
      return allocUnsafe(arg);
    }
    return from(arg, encodingOrOffset, length);
  }
  Buffer4.poolSize = 8192;
  function from(value, encodingOrOffset, length) {
    if (typeof value === "string") {
      return fromString(value, encodingOrOffset);
    }
    if (ArrayBuffer.isView(value)) {
      return fromArrayView(value);
    }
    if (value == null) {
      throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value);
    }
    if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) {
      return fromArrayBuffer(value, encodingOrOffset, length);
    }
    if (typeof SharedArrayBuffer !== "undefined" && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer))) {
      return fromArrayBuffer(value, encodingOrOffset, length);
    }
    if (typeof value === "number") {
      throw new TypeError('The "value" argument must not be of type number. Received type number');
    }
    const valueOf = value.valueOf && value.valueOf();
    if (valueOf != null && valueOf !== value) {
      return Buffer4.from(valueOf, encodingOrOffset, length);
    }
    const b3 = fromObject(value);
    if (b3) return b3;
    if (typeof Symbol !== "undefined" && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === "function") {
      return Buffer4.from(value[Symbol.toPrimitive]("string"), encodingOrOffset, length);
    }
    throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value);
  }
  Buffer4.from = function(value, encodingOrOffset, length) {
    return from(value, encodingOrOffset, length);
  };
  Object.setPrototypeOf(Buffer4.prototype, Uint8Array.prototype);
  Object.setPrototypeOf(Buffer4, Uint8Array);
  function assertSize(size) {
    if (typeof size !== "number") {
      throw new TypeError('"size" argument must be of type number');
    } else if (size < 0) {
      throw new RangeError('The value "' + size + '" is invalid for option "size"');
    }
  }
  function alloc(size, fill, encoding) {
    assertSize(size);
    if (size <= 0) {
      return createBuffer(size);
    }
    if (fill !== void 0) {
      return typeof encoding === "string" ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill);
    }
    return createBuffer(size);
  }
  Buffer4.alloc = function(size, fill, encoding) {
    return alloc(size, fill, encoding);
  };
  function allocUnsafe(size) {
    assertSize(size);
    return createBuffer(size < 0 ? 0 : checked(size) | 0);
  }
  Buffer4.allocUnsafe = function(size) {
    return allocUnsafe(size);
  };
  Buffer4.allocUnsafeSlow = function(size) {
    return allocUnsafe(size);
  };
  function fromString(string2, encoding) {
    if (typeof encoding !== "string" || encoding === "") {
      encoding = "utf8";
    }
    if (!Buffer4.isEncoding(encoding)) {
      throw new TypeError("Unknown encoding: " + encoding);
    }
    const length = byteLength(string2, encoding) | 0;
    let buf = createBuffer(length);
    const actual = buf.write(string2, encoding);
    if (actual !== length) {
      buf = buf.slice(0, actual);
    }
    return buf;
  }
  function fromArrayLike(array) {
    const length = array.length < 0 ? 0 : checked(array.length) | 0;
    const buf = createBuffer(length);
    for (let i6 = 0; i6 < length; i6 += 1) {
      buf[i6] = array[i6] & 255;
    }
    return buf;
  }
  function fromArrayView(arrayView) {
    if (isInstance(arrayView, Uint8Array)) {
      const copy6 = new Uint8Array(arrayView);
      return fromArrayBuffer(copy6.buffer, copy6.byteOffset, copy6.byteLength);
    }
    return fromArrayLike(arrayView);
  }
  function fromArrayBuffer(array, byteOffset, length) {
    if (byteOffset < 0 || array.byteLength < byteOffset) {
      throw new RangeError('"offset" is outside of buffer bounds');
    }
    if (array.byteLength < byteOffset + (length || 0)) {
      throw new RangeError('"length" is outside of buffer bounds');
    }
    let buf;
    if (byteOffset === void 0 && length === void 0) {
      buf = new Uint8Array(array);
    } else if (length === void 0) {
      buf = new Uint8Array(array, byteOffset);
    } else {
      buf = new Uint8Array(array, byteOffset, length);
    }
    Object.setPrototypeOf(buf, Buffer4.prototype);
    return buf;
  }
  function fromObject(obj) {
    if (Buffer4.isBuffer(obj)) {
      const len = checked(obj.length) | 0;
      const buf = createBuffer(len);
      if (buf.length === 0) {
        return buf;
      }
      obj.copy(buf, 0, 0, len);
      return buf;
    }
    if (obj.length !== void 0) {
      if (typeof obj.length !== "number" || numberIsNaN(obj.length)) {
        return createBuffer(0);
      }
      return fromArrayLike(obj);
    }
    if (obj.type === "Buffer" && Array.isArray(obj.data)) {
      return fromArrayLike(obj.data);
    }
  }
  function checked(length) {
    if (length >= K_MAX_LENGTH) {
      throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + K_MAX_LENGTH.toString(16) + " bytes");
    }
    return length | 0;
  }
  function SlowBuffer(length) {
    if (+length != length) {
      length = 0;
    }
    return Buffer4.alloc(+length);
  }
  Buffer4.isBuffer = function isBuffer3(b3) {
    return b3 != null && b3._isBuffer === true && b3 !== Buffer4.prototype;
  };
  Buffer4.compare = function compare2(a5, b3) {
    if (isInstance(a5, Uint8Array)) a5 = Buffer4.from(a5, a5.offset, a5.byteLength);
    if (isInstance(b3, Uint8Array)) b3 = Buffer4.from(b3, b3.offset, b3.byteLength);
    if (!Buffer4.isBuffer(a5) || !Buffer4.isBuffer(b3)) {
      throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');
    }
    if (a5 === b3) return 0;
    let x3 = a5.length;
    let y4 = b3.length;
    for (let i6 = 0, len = Math.min(x3, y4); i6 < len; ++i6) {
      if (a5[i6] !== b3[i6]) {
        x3 = a5[i6];
        y4 = b3[i6];
        break;
      }
    }
    if (x3 < y4) return -1;
    if (y4 < x3) return 1;
    return 0;
  };
  Buffer4.isEncoding = function isEncoding(encoding) {
    switch (String(encoding).toLowerCase()) {
      case "hex":
      case "utf8":
      case "utf-8":
      case "ascii":
      case "latin1":
      case "binary":
      case "base64":
      case "ucs2":
      case "ucs-2":
      case "utf16le":
      case "utf-16le":
        return true;
      default:
        return false;
    }
  };
  Buffer4.concat = function concat3(list, length) {
    if (!Array.isArray(list)) {
      throw new TypeError('"list" argument must be an Array of Buffers');
    }
    if (list.length === 0) {
      return Buffer4.alloc(0);
    }
    let i6;
    if (length === void 0) {
      length = 0;
      for (i6 = 0; i6 < list.length; ++i6) {
        length += list[i6].length;
      }
    }
    const buffer2 = Buffer4.allocUnsafe(length);
    let pos = 0;
    for (i6 = 0; i6 < list.length; ++i6) {
      let buf = list[i6];
      if (isInstance(buf, Uint8Array)) {
        if (pos + buf.length > buffer2.length) {
          if (!Buffer4.isBuffer(buf)) buf = Buffer4.from(buf);
          buf.copy(buffer2, pos);
        } else {
          Uint8Array.prototype.set.call(buffer2, buf, pos);
        }
      } else if (!Buffer4.isBuffer(buf)) {
        throw new TypeError('"list" argument must be an Array of Buffers');
      } else {
        buf.copy(buffer2, pos);
      }
      pos += buf.length;
    }
    return buffer2;
  };
  function byteLength(string2, encoding) {
    if (Buffer4.isBuffer(string2)) {
      return string2.length;
    }
    if (ArrayBuffer.isView(string2) || isInstance(string2, ArrayBuffer)) {
      return string2.byteLength;
    }
    if (typeof string2 !== "string") {
      throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof string2);
    }
    const len = string2.length;
    const mustMatch = arguments.length > 2 && arguments[2] === true;
    if (!mustMatch && len === 0) return 0;
    let loweredCase = false;
    for (; ; ) {
      switch (encoding) {
        case "ascii":
        case "latin1":
        case "binary":
          return len;
        case "utf8":
        case "utf-8":
          return utf8ToBytes(string2).length;
        case "ucs2":
        case "ucs-2":
        case "utf16le":
        case "utf-16le":
          return len * 2;
        case "hex":
          return len >>> 1;
        case "base64":
          return base64ToBytes(string2).length;
        default:
          if (loweredCase) {
            return mustMatch ? -1 : utf8ToBytes(string2).length;
          }
          encoding = ("" + encoding).toLowerCase();
          loweredCase = true;
      }
    }
  }
  Buffer4.byteLength = byteLength;
  function slowToString(encoding, start, end) {
    let loweredCase = false;
    if (start === void 0 || start < 0) {
      start = 0;
    }
    if (start > this.length) {
      return "";
    }
    if (end === void 0 || end > this.length) {
      end = this.length;
    }
    if (end <= 0) {
      return "";
    }
    end >>>= 0;
    start >>>= 0;
    if (end <= start) {
      return "";
    }
    if (!encoding) encoding = "utf8";
    while (true) {
      switch (encoding) {
        case "hex":
          return hexSlice(this, start, end);
        case "utf8":
        case "utf-8":
          return utf8Slice(this, start, end);
        case "ascii":
          return asciiSlice(this, start, end);
        case "latin1":
        case "binary":
          return latin1Slice(this, start, end);
        case "base64":
          return base64Slice(this, start, end);
        case "ucs2":
        case "ucs-2":
        case "utf16le":
        case "utf-16le":
          return utf16leSlice(this, start, end);
        default:
          if (loweredCase) throw new TypeError("Unknown encoding: " + encoding);
          encoding = (encoding + "").toLowerCase();
          loweredCase = true;
      }
    }
  }
  Buffer4.prototype._isBuffer = true;
  function swap(b3, n5, m4) {
    const i6 = b3[n5];
    b3[n5] = b3[m4];
    b3[m4] = i6;
  }
  Buffer4.prototype.swap16 = function swap16() {
    const len = this.length;
    if (len % 2 !== 0) {
      throw new RangeError("Buffer size must be a multiple of 16-bits");
    }
    for (let i6 = 0; i6 < len; i6 += 2) {
      swap(this, i6, i6 + 1);
    }
    return this;
  };
  Buffer4.prototype.swap32 = function swap32() {
    const len = this.length;
    if (len % 4 !== 0) {
      throw new RangeError("Buffer size must be a multiple of 32-bits");
    }
    for (let i6 = 0; i6 < len; i6 += 4) {
      swap(this, i6, i6 + 3);
      swap(this, i6 + 1, i6 + 2);
    }
    return this;
  };
  Buffer4.prototype.swap64 = function swap64() {
    const len = this.length;
    if (len % 8 !== 0) {
      throw new RangeError("Buffer size must be a multiple of 64-bits");
    }
    for (let i6 = 0; i6 < len; i6 += 8) {
      swap(this, i6, i6 + 7);
      swap(this, i6 + 1, i6 + 6);
      swap(this, i6 + 2, i6 + 5);
      swap(this, i6 + 3, i6 + 4);
    }
    return this;
  };
  Buffer4.prototype.toString = function toString8() {
    const length = this.length;
    if (length === 0) return "";
    if (arguments.length === 0) return utf8Slice(this, 0, length);
    return slowToString.apply(this, arguments);
  };
  Buffer4.prototype.toLocaleString = Buffer4.prototype.toString;
  Buffer4.prototype.equals = function equals2(b3) {
    if (!Buffer4.isBuffer(b3)) throw new TypeError("Argument must be a Buffer");
    if (this === b3) return true;
    return Buffer4.compare(this, b3) === 0;
  };
  Buffer4.prototype.inspect = function inspect4() {
    let str3 = "";
    const max = exports$13.INSPECT_MAX_BYTES;
    str3 = this.toString("hex", 0, max).replace(/(.{2})/g, "$1 ").trim();
    if (this.length > max) str3 += " ... ";
    return "<Buffer " + str3 + ">";
  };
  if (customInspectSymbol) {
    Buffer4.prototype[customInspectSymbol] = Buffer4.prototype.inspect;
  }
  Buffer4.prototype.compare = function compare2(target, start, end, thisStart, thisEnd) {
    if (isInstance(target, Uint8Array)) {
      target = Buffer4.from(target, target.offset, target.byteLength);
    }
    if (!Buffer4.isBuffer(target)) {
      throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof target);
    }
    if (start === void 0) {
      start = 0;
    }
    if (end === void 0) {
      end = target ? target.length : 0;
    }
    if (thisStart === void 0) {
      thisStart = 0;
    }
    if (thisEnd === void 0) {
      thisEnd = this.length;
    }
    if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
      throw new RangeError("out of range index");
    }
    if (thisStart >= thisEnd && start >= end) {
      return 0;
    }
    if (thisStart >= thisEnd) {
      return -1;
    }
    if (start >= end) {
      return 1;
    }
    start >>>= 0;
    end >>>= 0;
    thisStart >>>= 0;
    thisEnd >>>= 0;
    if (this === target) return 0;
    let x3 = thisEnd - thisStart;
    let y4 = end - start;
    const len = Math.min(x3, y4);
    const thisCopy = this.slice(thisStart, thisEnd);
    const targetCopy = target.slice(start, end);
    for (let i6 = 0; i6 < len; ++i6) {
      if (thisCopy[i6] !== targetCopy[i6]) {
        x3 = thisCopy[i6];
        y4 = targetCopy[i6];
        break;
      }
    }
    if (x3 < y4) return -1;
    if (y4 < x3) return 1;
    return 0;
  };
  function bidirectionalIndexOf(buffer2, val, byteOffset, encoding, dir) {
    if (buffer2.length === 0) return -1;
    if (typeof byteOffset === "string") {
      encoding = byteOffset;
      byteOffset = 0;
    } else if (byteOffset > 2147483647) {
      byteOffset = 2147483647;
    } else if (byteOffset < -2147483648) {
      byteOffset = -2147483648;
    }
    byteOffset = +byteOffset;
    if (numberIsNaN(byteOffset)) {
      byteOffset = dir ? 0 : buffer2.length - 1;
    }
    if (byteOffset < 0) byteOffset = buffer2.length + byteOffset;
    if (byteOffset >= buffer2.length) {
      if (dir) return -1;
      else byteOffset = buffer2.length - 1;
    } else if (byteOffset < 0) {
      if (dir) byteOffset = 0;
      else return -1;
    }
    if (typeof val === "string") {
      val = Buffer4.from(val, encoding);
    }
    if (Buffer4.isBuffer(val)) {
      if (val.length === 0) {
        return -1;
      }
      return arrayIndexOf(buffer2, val, byteOffset, encoding, dir);
    } else if (typeof val === "number") {
      val = val & 255;
      if (typeof Uint8Array.prototype.indexOf === "function") {
        if (dir) {
          return Uint8Array.prototype.indexOf.call(buffer2, val, byteOffset);
        } else {
          return Uint8Array.prototype.lastIndexOf.call(buffer2, val, byteOffset);
        }
      }
      return arrayIndexOf(buffer2, [val], byteOffset, encoding, dir);
    }
    throw new TypeError("val must be string, number or Buffer");
  }
  function arrayIndexOf(arr, val, byteOffset, encoding, dir) {
    let indexSize = 1;
    let arrLength = arr.length;
    let valLength = val.length;
    if (encoding !== void 0) {
      encoding = String(encoding).toLowerCase();
      if (encoding === "ucs2" || encoding === "ucs-2" || encoding === "utf16le" || encoding === "utf-16le") {
        if (arr.length < 2 || val.length < 2) {
          return -1;
        }
        indexSize = 2;
        arrLength /= 2;
        valLength /= 2;
        byteOffset /= 2;
      }
    }
    function read(buf, i7) {
      if (indexSize === 1) {
        return buf[i7];
      } else {
        return buf.readUInt16BE(i7 * indexSize);
      }
    }
    let i6;
    if (dir) {
      let foundIndex = -1;
      for (i6 = byteOffset; i6 < arrLength; i6++) {
        if (read(arr, i6) === read(val, foundIndex === -1 ? 0 : i6 - foundIndex)) {
          if (foundIndex === -1) foundIndex = i6;
          if (i6 - foundIndex + 1 === valLength) return foundIndex * indexSize;
        } else {
          if (foundIndex !== -1) i6 -= i6 - foundIndex;
          foundIndex = -1;
        }
      }
    } else {
      if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
      for (i6 = byteOffset; i6 >= 0; i6--) {
        let found = true;
        for (let j3 = 0; j3 < valLength; j3++) {
          if (read(arr, i6 + j3) !== read(val, j3)) {
            found = false;
            break;
          }
        }
        if (found) return i6;
      }
    }
    return -1;
  }
  Buffer4.prototype.includes = function includes(val, byteOffset, encoding) {
    return this.indexOf(val, byteOffset, encoding) !== -1;
  };
  Buffer4.prototype.indexOf = function indexOf2(val, byteOffset, encoding) {
    return bidirectionalIndexOf(this, val, byteOffset, encoding, true);
  };
  Buffer4.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) {
    return bidirectionalIndexOf(this, val, byteOffset, encoding, false);
  };
  function hexWrite(buf, string2, offset3, length) {
    offset3 = Number(offset3) || 0;
    const remaining = buf.length - offset3;
    if (!length) {
      length = remaining;
    } else {
      length = Number(length);
      if (length > remaining) {
        length = remaining;
      }
    }
    const strLen = string2.length;
    if (length > strLen / 2) {
      length = strLen / 2;
    }
    let i6;
    for (i6 = 0; i6 < length; ++i6) {
      const parsed = parseInt(string2.substr(i6 * 2, 2), 16);
      if (numberIsNaN(parsed)) return i6;
      buf[offset3 + i6] = parsed;
    }
    return i6;
  }
  function utf8Write(buf, string2, offset3, length) {
    return blitBuffer(utf8ToBytes(string2, buf.length - offset3), buf, offset3, length);
  }
  function asciiWrite(buf, string2, offset3, length) {
    return blitBuffer(asciiToBytes(string2), buf, offset3, length);
  }
  function base64Write(buf, string2, offset3, length) {
    return blitBuffer(base64ToBytes(string2), buf, offset3, length);
  }
  function ucs2Write(buf, string2, offset3, length) {
    return blitBuffer(utf16leToBytes(string2, buf.length - offset3), buf, offset3, length);
  }
  Buffer4.prototype.write = function write(string2, offset3, length, encoding) {
    if (offset3 === void 0) {
      encoding = "utf8";
      length = this.length;
      offset3 = 0;
    } else if (length === void 0 && typeof offset3 === "string") {
      encoding = offset3;
      length = this.length;
      offset3 = 0;
    } else if (isFinite(offset3)) {
      offset3 = offset3 >>> 0;
      if (isFinite(length)) {
        length = length >>> 0;
        if (encoding === void 0) encoding = "utf8";
      } else {
        encoding = length;
        length = void 0;
      }
    } else {
      throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");
    }
    const remaining = this.length - offset3;
    if (length === void 0 || length > remaining) length = remaining;
    if (string2.length > 0 && (length < 0 || offset3 < 0) || offset3 > this.length) {
      throw new RangeError("Attempt to write outside buffer bounds");
    }
    if (!encoding) encoding = "utf8";
    let loweredCase = false;
    for (; ; ) {
      switch (encoding) {
        case "hex":
          return hexWrite(this, string2, offset3, length);
        case "utf8":
        case "utf-8":
          return utf8Write(this, string2, offset3, length);
        case "ascii":
        case "latin1":
        case "binary":
          return asciiWrite(this, string2, offset3, length);
        case "base64":
          return base64Write(this, string2, offset3, length);
        case "ucs2":
        case "ucs-2":
        case "utf16le":
        case "utf-16le":
          return ucs2Write(this, string2, offset3, length);
        default:
          if (loweredCase) throw new TypeError("Unknown encoding: " + encoding);
          encoding = ("" + encoding).toLowerCase();
          loweredCase = true;
      }
    }
  };
  Buffer4.prototype.toJSON = function toJSON() {
    return {
      type: "Buffer",
      data: Array.prototype.slice.call(this._arr || this, 0)
    };
  };
  function base64Slice(buf, start, end) {
    if (start === 0 && end === buf.length) {
      return base642.fromByteArray(buf);
    } else {
      return base642.fromByteArray(buf.slice(start, end));
    }
  }
  function utf8Slice(buf, start, end) {
    end = Math.min(buf.length, end);
    const res = [];
    let i6 = start;
    while (i6 < end) {
      const firstByte = buf[i6];
      let codePoint = null;
      let bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1;
      if (i6 + bytesPerSequence <= end) {
        let secondByte, thirdByte, fourthByte, tempCodePoint;
        switch (bytesPerSequence) {
          case 1:
            if (firstByte < 128) {
              codePoint = firstByte;
            }
            break;
          case 2:
            secondByte = buf[i6 + 1];
            if ((secondByte & 192) === 128) {
              tempCodePoint = (firstByte & 31) << 6 | secondByte & 63;
              if (tempCodePoint > 127) {
                codePoint = tempCodePoint;
              }
            }
            break;
          case 3:
            secondByte = buf[i6 + 1];
            thirdByte = buf[i6 + 2];
            if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) {
              tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63;
              if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) {
                codePoint = tempCodePoint;
              }
            }
            break;
          case 4:
            secondByte = buf[i6 + 1];
            thirdByte = buf[i6 + 2];
            fourthByte = buf[i6 + 3];
            if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) {
              tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63;
              if (tempCodePoint > 65535 && tempCodePoint < 1114112) {
                codePoint = tempCodePoint;
              }
            }
        }
      }
      if (codePoint === null) {
        codePoint = 65533;
        bytesPerSequence = 1;
      } else if (codePoint > 65535) {
        codePoint -= 65536;
        res.push(codePoint >>> 10 & 1023 | 55296);
        codePoint = 56320 | codePoint & 1023;
      }
      res.push(codePoint);
      i6 += bytesPerSequence;
    }
    return decodeCodePointsArray(res);
  }
  const MAX_ARGUMENTS_LENGTH = 4096;
  function decodeCodePointsArray(codePoints) {
    const len = codePoints.length;
    if (len <= MAX_ARGUMENTS_LENGTH) {
      return String.fromCharCode.apply(String, codePoints);
    }
    let res = "";
    let i6 = 0;
    while (i6 < len) {
      res += String.fromCharCode.apply(String, codePoints.slice(i6, i6 += MAX_ARGUMENTS_LENGTH));
    }
    return res;
  }
  function asciiSlice(buf, start, end) {
    let ret = "";
    end = Math.min(buf.length, end);
    for (let i6 = start; i6 < end; ++i6) {
      ret += String.fromCharCode(buf[i6] & 127);
    }
    return ret;
  }
  function latin1Slice(buf, start, end) {
    let ret = "";
    end = Math.min(buf.length, end);
    for (let i6 = start; i6 < end; ++i6) {
      ret += String.fromCharCode(buf[i6]);
    }
    return ret;
  }
  function hexSlice(buf, start, end) {
    const len = buf.length;
    if (!start || start < 0) start = 0;
    if (!end || end < 0 || end > len) end = len;
    let out = "";
    for (let i6 = start; i6 < end; ++i6) {
      out += hexSliceLookupTable[buf[i6]];
    }
    return out;
  }
  function utf16leSlice(buf, start, end) {
    const bytes = buf.slice(start, end);
    let res = "";
    for (let i6 = 0; i6 < bytes.length - 1; i6 += 2) {
      res += String.fromCharCode(bytes[i6] + bytes[i6 + 1] * 256);
    }
    return res;
  }
  Buffer4.prototype.slice = function slice2(start, end) {
    const len = this.length;
    start = ~~start;
    end = end === void 0 ? len : ~~end;
    if (start < 0) {
      start += len;
      if (start < 0) start = 0;
    } else if (start > len) {
      start = len;
    }
    if (end < 0) {
      end += len;
      if (end < 0) end = 0;
    } else if (end > len) {
      end = len;
    }
    if (end < start) end = start;
    const newBuf = this.subarray(start, end);
    Object.setPrototypeOf(newBuf, Buffer4.prototype);
    return newBuf;
  };
  function checkOffset(offset3, ext, length) {
    if (offset3 % 1 !== 0 || offset3 < 0) throw new RangeError("offset is not uint");
    if (offset3 + ext > length) throw new RangeError("Trying to access beyond buffer length");
  }
  Buffer4.prototype.readUintLE = Buffer4.prototype.readUIntLE = function readUIntLE(offset3, byteLength2, noAssert) {
    offset3 = offset3 >>> 0;
    byteLength2 = byteLength2 >>> 0;
    if (!noAssert) checkOffset(offset3, byteLength2, this.length);
    let val = this[offset3];
    let mul = 1;
    let i6 = 0;
    while (++i6 < byteLength2 && (mul *= 256)) {
      val += this[offset3 + i6] * mul;
    }
    return val;
  };
  Buffer4.prototype.readUintBE = Buffer4.prototype.readUIntBE = function readUIntBE(offset3, byteLength2, noAssert) {
    offset3 = offset3 >>> 0;
    byteLength2 = byteLength2 >>> 0;
    if (!noAssert) {
      checkOffset(offset3, byteLength2, this.length);
    }
    let val = this[offset3 + --byteLength2];
    let mul = 1;
    while (byteLength2 > 0 && (mul *= 256)) {
      val += this[offset3 + --byteLength2] * mul;
    }
    return val;
  };
  Buffer4.prototype.readUint8 = Buffer4.prototype.readUInt8 = function readUInt8(offset3, noAssert) {
    offset3 = offset3 >>> 0;
    if (!noAssert) checkOffset(offset3, 1, this.length);
    return this[offset3];
  };
  Buffer4.prototype.readUint16LE = Buffer4.prototype.readUInt16LE = function readUInt16LE(offset3, noAssert) {
    offset3 = offset3 >>> 0;
    if (!noAssert) checkOffset(offset3, 2, this.length);
    return this[offset3] | this[offset3 + 1] << 8;
  };
  Buffer4.prototype.readUint16BE = Buffer4.prototype.readUInt16BE = function readUInt16BE(offset3, noAssert) {
    offset3 = offset3 >>> 0;
    if (!noAssert) checkOffset(offset3, 2, this.length);
    return this[offset3] << 8 | this[offset3 + 1];
  };
  Buffer4.prototype.readUint32LE = Buffer4.prototype.readUInt32LE = function readUInt32LE(offset3, noAssert) {
    offset3 = offset3 >>> 0;
    if (!noAssert) checkOffset(offset3, 4, this.length);
    return (this[offset3] | this[offset3 + 1] << 8 | this[offset3 + 2] << 16) + this[offset3 + 3] * 16777216;
  };
  Buffer4.prototype.readUint32BE = Buffer4.prototype.readUInt32BE = function readUInt32BE(offset3, noAssert) {
    offset3 = offset3 >>> 0;
    if (!noAssert) checkOffset(offset3, 4, this.length);
    return this[offset3] * 16777216 + (this[offset3 + 1] << 16 | this[offset3 + 2] << 8 | this[offset3 + 3]);
  };
  Buffer4.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE(offset3) {
    offset3 = offset3 >>> 0;
    validateNumber2(offset3, "offset");
    const first = this[offset3];
    const last = this[offset3 + 7];
    if (first === void 0 || last === void 0) {
      boundsError(offset3, this.length - 8);
    }
    const lo = first + this[++offset3] * 2 ** 8 + this[++offset3] * 2 ** 16 + this[++offset3] * 2 ** 24;
    const hi = this[++offset3] + this[++offset3] * 2 ** 8 + this[++offset3] * 2 ** 16 + last * 2 ** 24;
    return BigInt(lo) + (BigInt(hi) << BigInt(32));
  });
  Buffer4.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE(offset3) {
    offset3 = offset3 >>> 0;
    validateNumber2(offset3, "offset");
    const first = this[offset3];
    const last = this[offset3 + 7];
    if (first === void 0 || last === void 0) {
      boundsError(offset3, this.length - 8);
    }
    const hi = first * 2 ** 24 + this[++offset3] * 2 ** 16 + this[++offset3] * 2 ** 8 + this[++offset3];
    const lo = this[++offset3] * 2 ** 24 + this[++offset3] * 2 ** 16 + this[++offset3] * 2 ** 8 + last;
    return (BigInt(hi) << BigInt(32)) + BigInt(lo);
  });
  Buffer4.prototype.readIntLE = function readIntLE(offset3, byteLength2, noAssert) {
    offset3 = offset3 >>> 0;
    byteLength2 = byteLength2 >>> 0;
    if (!noAssert) checkOffset(offset3, byteLength2, this.length);
    let val = this[offset3];
    let mul = 1;
    let i6 = 0;
    while (++i6 < byteLength2 && (mul *= 256)) {
      val += this[offset3 + i6] * mul;
    }
    mul *= 128;
    if (val >= mul) val -= Math.pow(2, 8 * byteLength2);
    return val;
  };
  Buffer4.prototype.readIntBE = function readIntBE(offset3, byteLength2, noAssert) {
    offset3 = offset3 >>> 0;
    byteLength2 = byteLength2 >>> 0;
    if (!noAssert) checkOffset(offset3, byteLength2, this.length);
    let i6 = byteLength2;
    let mul = 1;
    let val = this[offset3 + --i6];
    while (i6 > 0 && (mul *= 256)) {
      val += this[offset3 + --i6] * mul;
    }
    mul *= 128;
    if (val >= mul) val -= Math.pow(2, 8 * byteLength2);
    return val;
  };
  Buffer4.prototype.readInt8 = function readInt8(offset3, noAssert) {
    offset3 = offset3 >>> 0;
    if (!noAssert) checkOffset(offset3, 1, this.length);
    if (!(this[offset3] & 128)) return this[offset3];
    return (255 - this[offset3] + 1) * -1;
  };
  Buffer4.prototype.readInt16LE = function readInt16LE(offset3, noAssert) {
    offset3 = offset3 >>> 0;
    if (!noAssert) checkOffset(offset3, 2, this.length);
    const val = this[offset3] | this[offset3 + 1] << 8;
    return val & 32768 ? val | 4294901760 : val;
  };
  Buffer4.prototype.readInt16BE = function readInt16BE(offset3, noAssert) {
    offset3 = offset3 >>> 0;
    if (!noAssert) checkOffset(offset3, 2, this.length);
    const val = this[offset3 + 1] | this[offset3] << 8;
    return val & 32768 ? val | 4294901760 : val;
  };
  Buffer4.prototype.readInt32LE = function readInt32LE(offset3, noAssert) {
    offset3 = offset3 >>> 0;
    if (!noAssert) checkOffset(offset3, 4, this.length);
    return this[offset3] | this[offset3 + 1] << 8 | this[offset3 + 2] << 16 | this[offset3 + 3] << 24;
  };
  Buffer4.prototype.readInt32BE = function readInt32BE(offset3, noAssert) {
    offset3 = offset3 >>> 0;
    if (!noAssert) checkOffset(offset3, 4, this.length);
    return this[offset3] << 24 | this[offset3 + 1] << 16 | this[offset3 + 2] << 8 | this[offset3 + 3];
  };
  Buffer4.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE(offset3) {
    offset3 = offset3 >>> 0;
    validateNumber2(offset3, "offset");
    const first = this[offset3];
    const last = this[offset3 + 7];
    if (first === void 0 || last === void 0) {
      boundsError(offset3, this.length - 8);
    }
    const val = this[offset3 + 4] + this[offset3 + 5] * 2 ** 8 + this[offset3 + 6] * 2 ** 16 + (last << 24);
    return (BigInt(val) << BigInt(32)) + BigInt(first + this[++offset3] * 2 ** 8 + this[++offset3] * 2 ** 16 + this[++offset3] * 2 ** 24);
  });
  Buffer4.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE(offset3) {
    offset3 = offset3 >>> 0;
    validateNumber2(offset3, "offset");
    const first = this[offset3];
    const last = this[offset3 + 7];
    if (first === void 0 || last === void 0) {
      boundsError(offset3, this.length - 8);
    }
    const val = (first << 24) + // Overflow
    this[++offset3] * 2 ** 16 + this[++offset3] * 2 ** 8 + this[++offset3];
    return (BigInt(val) << BigInt(32)) + BigInt(this[++offset3] * 2 ** 24 + this[++offset3] * 2 ** 16 + this[++offset3] * 2 ** 8 + last);
  });
  Buffer4.prototype.readFloatLE = function readFloatLE(offset3, noAssert) {
    offset3 = offset3 >>> 0;
    if (!noAssert) checkOffset(offset3, 4, this.length);
    return ieee754.read(this, offset3, true, 23, 4);
  };
  Buffer4.prototype.readFloatBE = function readFloatBE(offset3, noAssert) {
    offset3 = offset3 >>> 0;
    if (!noAssert) checkOffset(offset3, 4, this.length);
    return ieee754.read(this, offset3, false, 23, 4);
  };
  Buffer4.prototype.readDoubleLE = function readDoubleLE(offset3, noAssert) {
    offset3 = offset3 >>> 0;
    if (!noAssert) checkOffset(offset3, 8, this.length);
    return ieee754.read(this, offset3, true, 52, 8);
  };
  Buffer4.prototype.readDoubleBE = function readDoubleBE(offset3, noAssert) {
    offset3 = offset3 >>> 0;
    if (!noAssert) checkOffset(offset3, 8, this.length);
    return ieee754.read(this, offset3, false, 52, 8);
  };
  function checkInt(buf, value, offset3, ext, max, min2) {
    if (!Buffer4.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance');
    if (value > max || value < min2) throw new RangeError('"value" argument is out of bounds');
    if (offset3 + ext > buf.length) throw new RangeError("Index out of range");
  }
  Buffer4.prototype.writeUintLE = Buffer4.prototype.writeUIntLE = function writeUIntLE(value, offset3, byteLength2, noAssert) {
    value = +value;
    offset3 = offset3 >>> 0;
    byteLength2 = byteLength2 >>> 0;
    if (!noAssert) {
      const maxBytes = Math.pow(2, 8 * byteLength2) - 1;
      checkInt(this, value, offset3, byteLength2, maxBytes, 0);
    }
    let mul = 1;
    let i6 = 0;
    this[offset3] = value & 255;
    while (++i6 < byteLength2 && (mul *= 256)) {
      this[offset3 + i6] = value / mul & 255;
    }
    return offset3 + byteLength2;
  };
  Buffer4.prototype.writeUintBE = Buffer4.prototype.writeUIntBE = function writeUIntBE(value, offset3, byteLength2, noAssert) {
    value = +value;
    offset3 = offset3 >>> 0;
    byteLength2 = byteLength2 >>> 0;
    if (!noAssert) {
      const maxBytes = Math.pow(2, 8 * byteLength2) - 1;
      checkInt(this, value, offset3, byteLength2, maxBytes, 0);
    }
    let i6 = byteLength2 - 1;
    let mul = 1;
    this[offset3 + i6] = value & 255;
    while (--i6 >= 0 && (mul *= 256)) {
      this[offset3 + i6] = value / mul & 255;
    }
    return offset3 + byteLength2;
  };
  Buffer4.prototype.writeUint8 = Buffer4.prototype.writeUInt8 = function writeUInt8(value, offset3, noAssert) {
    value = +value;
    offset3 = offset3 >>> 0;
    if (!noAssert) checkInt(this, value, offset3, 1, 255, 0);
    this[offset3] = value & 255;
    return offset3 + 1;
  };
  Buffer4.prototype.writeUint16LE = Buffer4.prototype.writeUInt16LE = function writeUInt16LE(value, offset3, noAssert) {
    value = +value;
    offset3 = offset3 >>> 0;
    if (!noAssert) checkInt(this, value, offset3, 2, 65535, 0);
    this[offset3] = value & 255;
    this[offset3 + 1] = value >>> 8;
    return offset3 + 2;
  };
  Buffer4.prototype.writeUint16BE = Buffer4.prototype.writeUInt16BE = function writeUInt16BE(value, offset3, noAssert) {
    value = +value;
    offset3 = offset3 >>> 0;
    if (!noAssert) checkInt(this, value, offset3, 2, 65535, 0);
    this[offset3] = value >>> 8;
    this[offset3 + 1] = value & 255;
    return offset3 + 2;
  };
  Buffer4.prototype.writeUint32LE = Buffer4.prototype.writeUInt32LE = function writeUInt32LE(value, offset3, noAssert) {
    value = +value;
    offset3 = offset3 >>> 0;
    if (!noAssert) checkInt(this, value, offset3, 4, 4294967295, 0);
    this[offset3 + 3] = value >>> 24;
    this[offset3 + 2] = value >>> 16;
    this[offset3 + 1] = value >>> 8;
    this[offset3] = value & 255;
    return offset3 + 4;
  };
  Buffer4.prototype.writeUint32BE = Buffer4.prototype.writeUInt32BE = function writeUInt32BE(value, offset3, noAssert) {
    value = +value;
    offset3 = offset3 >>> 0;
    if (!noAssert) checkInt(this, value, offset3, 4, 4294967295, 0);
    this[offset3] = value >>> 24;
    this[offset3 + 1] = value >>> 16;
    this[offset3 + 2] = value >>> 8;
    this[offset3 + 3] = value & 255;
    return offset3 + 4;
  };
  function wrtBigUInt64LE(buf, value, offset3, min2, max) {
    checkIntBI(value, min2, max, buf, offset3, 7);
    let lo = Number(value & BigInt(4294967295));
    buf[offset3++] = lo;
    lo = lo >> 8;
    buf[offset3++] = lo;
    lo = lo >> 8;
    buf[offset3++] = lo;
    lo = lo >> 8;
    buf[offset3++] = lo;
    let hi = Number(value >> BigInt(32) & BigInt(4294967295));
    buf[offset3++] = hi;
    hi = hi >> 8;
    buf[offset3++] = hi;
    hi = hi >> 8;
    buf[offset3++] = hi;
    hi = hi >> 8;
    buf[offset3++] = hi;
    return offset3;
  }
  function wrtBigUInt64BE(buf, value, offset3, min2, max) {
    checkIntBI(value, min2, max, buf, offset3, 7);
    let lo = Number(value & BigInt(4294967295));
    buf[offset3 + 7] = lo;
    lo = lo >> 8;
    buf[offset3 + 6] = lo;
    lo = lo >> 8;
    buf[offset3 + 5] = lo;
    lo = lo >> 8;
    buf[offset3 + 4] = lo;
    let hi = Number(value >> BigInt(32) & BigInt(4294967295));
    buf[offset3 + 3] = hi;
    hi = hi >> 8;
    buf[offset3 + 2] = hi;
    hi = hi >> 8;
    buf[offset3 + 1] = hi;
    hi = hi >> 8;
    buf[offset3] = hi;
    return offset3 + 8;
  }
  Buffer4.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE(value, offset3 = 0) {
    return wrtBigUInt64LE(this, value, offset3, BigInt(0), BigInt("0xffffffffffffffff"));
  });
  Buffer4.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE(value, offset3 = 0) {
    return wrtBigUInt64BE(this, value, offset3, BigInt(0), BigInt("0xffffffffffffffff"));
  });
  Buffer4.prototype.writeIntLE = function writeIntLE(value, offset3, byteLength2, noAssert) {
    value = +value;
    offset3 = offset3 >>> 0;
    if (!noAssert) {
      const limit = Math.pow(2, 8 * byteLength2 - 1);
      checkInt(this, value, offset3, byteLength2, limit - 1, -limit);
    }
    let i6 = 0;
    let mul = 1;
    let sub = 0;
    this[offset3] = value & 255;
    while (++i6 < byteLength2 && (mul *= 256)) {
      if (value < 0 && sub === 0 && this[offset3 + i6 - 1] !== 0) {
        sub = 1;
      }
      this[offset3 + i6] = (value / mul >> 0) - sub & 255;
    }
    return offset3 + byteLength2;
  };
  Buffer4.prototype.writeIntBE = function writeIntBE(value, offset3, byteLength2, noAssert) {
    value = +value;
    offset3 = offset3 >>> 0;
    if (!noAssert) {
      const limit = Math.pow(2, 8 * byteLength2 - 1);
      checkInt(this, value, offset3, byteLength2, limit - 1, -limit);
    }
    let i6 = byteLength2 - 1;
    let mul = 1;
    let sub = 0;
    this[offset3 + i6] = value & 255;
    while (--i6 >= 0 && (mul *= 256)) {
      if (value < 0 && sub === 0 && this[offset3 + i6 + 1] !== 0) {
        sub = 1;
      }
      this[offset3 + i6] = (value / mul >> 0) - sub & 255;
    }
    return offset3 + byteLength2;
  };
  Buffer4.prototype.writeInt8 = function writeInt8(value, offset3, noAssert) {
    value = +value;
    offset3 = offset3 >>> 0;
    if (!noAssert) checkInt(this, value, offset3, 1, 127, -128);
    if (value < 0) value = 255 + value + 1;
    this[offset3] = value & 255;
    return offset3 + 1;
  };
  Buffer4.prototype.writeInt16LE = function writeInt16LE(value, offset3, noAssert) {
    value = +value;
    offset3 = offset3 >>> 0;
    if (!noAssert) checkInt(this, value, offset3, 2, 32767, -32768);
    this[offset3] = value & 255;
    this[offset3 + 1] = value >>> 8;
    return offset3 + 2;
  };
  Buffer4.prototype.writeInt16BE = function writeInt16BE(value, offset3, noAssert) {
    value = +value;
    offset3 = offset3 >>> 0;
    if (!noAssert) checkInt(this, value, offset3, 2, 32767, -32768);
    this[offset3] = value >>> 8;
    this[offset3 + 1] = value & 255;
    return offset3 + 2;
  };
  Buffer4.prototype.writeInt32LE = function writeInt32LE(value, offset3, noAssert) {
    value = +value;
    offset3 = offset3 >>> 0;
    if (!noAssert) checkInt(this, value, offset3, 4, 2147483647, -2147483648);
    this[offset3] = value & 255;
    this[offset3 + 1] = value >>> 8;
    this[offset3 + 2] = value >>> 16;
    this[offset3 + 3] = value >>> 24;
    return offset3 + 4;
  };
  Buffer4.prototype.writeInt32BE = function writeInt32BE(value, offset3, noAssert) {
    value = +value;
    offset3 = offset3 >>> 0;
    if (!noAssert) checkInt(this, value, offset3, 4, 2147483647, -2147483648);
    if (value < 0) value = 4294967295 + value + 1;
    this[offset3] = value >>> 24;
    this[offset3 + 1] = value >>> 16;
    this[offset3 + 2] = value >>> 8;
    this[offset3 + 3] = value & 255;
    return offset3 + 4;
  };
  Buffer4.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE(value, offset3 = 0) {
    return wrtBigUInt64LE(this, value, offset3, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff"));
  });
  Buffer4.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE(value, offset3 = 0) {
    return wrtBigUInt64BE(this, value, offset3, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff"));
  });
  function checkIEEE754(buf, value, offset3, ext, max, min2) {
    if (offset3 + ext > buf.length) throw new RangeError("Index out of range");
    if (offset3 < 0) throw new RangeError("Index out of range");
  }
  function writeFloat(buf, value, offset3, littleEndian, noAssert) {
    value = +value;
    offset3 = offset3 >>> 0;
    if (!noAssert) {
      checkIEEE754(buf, value, offset3, 4);
    }
    ieee754.write(buf, value, offset3, littleEndian, 23, 4);
    return offset3 + 4;
  }
  Buffer4.prototype.writeFloatLE = function writeFloatLE(value, offset3, noAssert) {
    return writeFloat(this, value, offset3, true, noAssert);
  };
  Buffer4.prototype.writeFloatBE = function writeFloatBE(value, offset3, noAssert) {
    return writeFloat(this, value, offset3, false, noAssert);
  };
  function writeDouble(buf, value, offset3, littleEndian, noAssert) {
    value = +value;
    offset3 = offset3 >>> 0;
    if (!noAssert) {
      checkIEEE754(buf, value, offset3, 8);
    }
    ieee754.write(buf, value, offset3, littleEndian, 52, 8);
    return offset3 + 8;
  }
  Buffer4.prototype.writeDoubleLE = function writeDoubleLE(value, offset3, noAssert) {
    return writeDouble(this, value, offset3, true, noAssert);
  };
  Buffer4.prototype.writeDoubleBE = function writeDoubleBE(value, offset3, noAssert) {
    return writeDouble(this, value, offset3, false, noAssert);
  };
  Buffer4.prototype.copy = function copy6(target, targetStart, start, end) {
    if (!Buffer4.isBuffer(target)) throw new TypeError("argument should be a Buffer");
    if (!start) start = 0;
    if (!end && end !== 0) end = this.length;
    if (targetStart >= target.length) targetStart = target.length;
    if (!targetStart) targetStart = 0;
    if (end > 0 && end < start) end = start;
    if (end === start) return 0;
    if (target.length === 0 || this.length === 0) return 0;
    if (targetStart < 0) {
      throw new RangeError("targetStart out of bounds");
    }
    if (start < 0 || start >= this.length) throw new RangeError("Index out of range");
    if (end < 0) throw new RangeError("sourceEnd out of bounds");
    if (end > this.length) end = this.length;
    if (target.length - targetStart < end - start) {
      end = target.length - targetStart + start;
    }
    const len = end - start;
    if (this === target && typeof Uint8Array.prototype.copyWithin === "function") {
      this.copyWithin(targetStart, start, end);
    } else {
      Uint8Array.prototype.set.call(target, this.subarray(start, end), targetStart);
    }
    return len;
  };
  Buffer4.prototype.fill = function fill(val, start, end, encoding) {
    if (typeof val === "string") {
      if (typeof start === "string") {
        encoding = start;
        start = 0;
        end = this.length;
      } else if (typeof end === "string") {
        encoding = end;
        end = this.length;
      }
      if (encoding !== void 0 && typeof encoding !== "string") {
        throw new TypeError("encoding must be a string");
      }
      if (typeof encoding === "string" && !Buffer4.isEncoding(encoding)) {
        throw new TypeError("Unknown encoding: " + encoding);
      }
      if (val.length === 1) {
        const code5 = val.charCodeAt(0);
        if (encoding === "utf8" && code5 < 128 || encoding === "latin1") {
          val = code5;
        }
      }
    } else if (typeof val === "number") {
      val = val & 255;
    } else if (typeof val === "boolean") {
      val = Number(val);
    }
    if (start < 0 || this.length < start || this.length < end) {
      throw new RangeError("Out of range index");
    }
    if (end <= start) {
      return this;
    }
    start = start >>> 0;
    end = end === void 0 ? this.length : end >>> 0;
    if (!val) val = 0;
    let i6;
    if (typeof val === "number") {
      for (i6 = start; i6 < end; ++i6) {
        this[i6] = val;
      }
    } else {
      const bytes = Buffer4.isBuffer(val) ? val : Buffer4.from(val, encoding);
      const len = bytes.length;
      if (len === 0) {
        throw new TypeError('The value "' + val + '" is invalid for argument "value"');
      }
      for (i6 = 0; i6 < end - start; ++i6) {
        this[i6 + start] = bytes[i6 % len];
      }
    }
    return this;
  };
  const errors2 = {};
  function E3(sym, getMessage, Base) {
    errors2[sym] = class NodeError extends Base {
      constructor() {
        super();
        Object.defineProperty(this, "message", {
          value: getMessage.apply(this, arguments),
          writable: true,
          configurable: true
        });
        this.name = `${this.name} [${sym}]`;
        this.stack;
        delete this.name;
      }
      get code() {
        return sym;
      }
      set code(value) {
        Object.defineProperty(this, "code", {
          configurable: true,
          enumerable: true,
          value,
          writable: true
        });
      }
      toString() {
        return `${this.name} [${sym}]: ${this.message}`;
      }
    };
  }
  E3("ERR_BUFFER_OUT_OF_BOUNDS", function(name2) {
    if (name2) {
      return `${name2} is outside of buffer bounds`;
    }
    return "Attempt to access memory outside buffer bounds";
  }, RangeError);
  E3("ERR_INVALID_ARG_TYPE", function(name2, actual) {
    return `The "${name2}" argument must be of type number. Received type ${typeof actual}`;
  }, TypeError);
  E3("ERR_OUT_OF_RANGE", function(str3, range, input) {
    let msg5 = `The value of "${str3}" is out of range.`;
    let received = input;
    if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) {
      received = addNumericalSeparator(String(input));
    } else if (typeof input === "bigint") {
      received = String(input);
      if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) {
        received = addNumericalSeparator(received);
      }
      received += "n";
    }
    msg5 += ` It must be ${range}. Received ${received}`;
    return msg5;
  }, RangeError);
  function addNumericalSeparator(val) {
    let res = "";
    let i6 = val.length;
    const start = val[0] === "-" ? 1 : 0;
    for (; i6 >= start + 4; i6 -= 3) {
      res = `_${val.slice(i6 - 3, i6)}${res}`;
    }
    return `${val.slice(0, i6)}${res}`;
  }
  function checkBounds(buf, offset3, byteLength2) {
    validateNumber2(offset3, "offset");
    if (buf[offset3] === void 0 || buf[offset3 + byteLength2] === void 0) {
      boundsError(offset3, buf.length - (byteLength2 + 1));
    }
  }
  function checkIntBI(value, min2, max, buf, offset3, byteLength2) {
    if (value > max || value < min2) {
      const n5 = typeof min2 === "bigint" ? "n" : "";
      let range;
      if (byteLength2 > 3) {
        if (min2 === 0 || min2 === BigInt(0)) {
          range = `>= 0${n5} and < 2${n5} ** ${(byteLength2 + 1) * 8}${n5}`;
        } else {
          range = `>= -(2${n5} ** ${(byteLength2 + 1) * 8 - 1}${n5}) and < 2 ** ${(byteLength2 + 1) * 8 - 1}${n5}`;
        }
      } else {
        range = `>= ${min2}${n5} and <= ${max}${n5}`;
      }
      throw new errors2.ERR_OUT_OF_RANGE("value", range, value);
    }
    checkBounds(buf, offset3, byteLength2);
  }
  function validateNumber2(value, name2) {
    if (typeof value !== "number") {
      throw new errors2.ERR_INVALID_ARG_TYPE(name2, "number", value);
    }
  }
  function boundsError(value, length, type4) {
    if (Math.floor(value) !== value) {
      validateNumber2(value, type4);
      throw new errors2.ERR_OUT_OF_RANGE(type4 || "offset", "an integer", value);
    }
    if (length < 0) {
      throw new errors2.ERR_BUFFER_OUT_OF_BOUNDS();
    }
    throw new errors2.ERR_OUT_OF_RANGE(type4 || "offset", `>= ${type4 ? 1 : 0} and <= ${length}`, value);
  }
  const INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g;
  function base64clean(str3) {
    str3 = str3.split("=")[0];
    str3 = str3.trim().replace(INVALID_BASE64_RE, "");
    if (str3.length < 2) return "";
    while (str3.length % 4 !== 0) {
      str3 = str3 + "=";
    }
    return str3;
  }
  function utf8ToBytes(string2, units2) {
    units2 = units2 || Infinity;
    let codePoint;
    const length = string2.length;
    let leadSurrogate = null;
    const bytes = [];
    for (let i6 = 0; i6 < length; ++i6) {
      codePoint = string2.charCodeAt(i6);
      if (codePoint > 55295 && codePoint < 57344) {
        if (!leadSurrogate) {
          if (codePoint > 56319) {
            if ((units2 -= 3) > -1) bytes.push(239, 191, 189);
            continue;
          } else if (i6 + 1 === length) {
            if ((units2 -= 3) > -1) bytes.push(239, 191, 189);
            continue;
          }
          leadSurrogate = codePoint;
          continue;
        }
        if (codePoint < 56320) {
          if ((units2 -= 3) > -1) bytes.push(239, 191, 189);
          leadSurrogate = codePoint;
          continue;
        }
        codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536;
      } else if (leadSurrogate) {
        if ((units2 -= 3) > -1) bytes.push(239, 191, 189);
      }
      leadSurrogate = null;
      if (codePoint < 128) {
        if ((units2 -= 1) < 0) break;
        bytes.push(codePoint);
      } else if (codePoint < 2048) {
        if ((units2 -= 2) < 0) break;
        bytes.push(codePoint >> 6 | 192, codePoint & 63 | 128);
      } else if (codePoint < 65536) {
        if ((units2 -= 3) < 0) break;
        bytes.push(codePoint >> 12 | 224, codePoint >> 6 & 63 | 128, codePoint & 63 | 128);
      } else if (codePoint < 1114112) {
        if ((units2 -= 4) < 0) break;
        bytes.push(codePoint >> 18 | 240, codePoint >> 12 & 63 | 128, codePoint >> 6 & 63 | 128, codePoint & 63 | 128);
      } else {
        throw new Error("Invalid code point");
      }
    }
    return bytes;
  }
  function asciiToBytes(str3) {
    const byteArray = [];
    for (let i6 = 0; i6 < str3.length; ++i6) {
      byteArray.push(str3.charCodeAt(i6) & 255);
    }
    return byteArray;
  }
  function utf16leToBytes(str3, units2) {
    let c6, hi, lo;
    const byteArray = [];
    for (let i6 = 0; i6 < str3.length; ++i6) {
      if ((units2 -= 2) < 0) break;
      c6 = str3.charCodeAt(i6);
      hi = c6 >> 8;
      lo = c6 % 256;
      byteArray.push(lo);
      byteArray.push(hi);
    }
    return byteArray;
  }
  function base64ToBytes(str3) {
    return base642.toByteArray(base64clean(str3));
  }
  function blitBuffer(src2, dst, offset3, length) {
    let i6;
    for (i6 = 0; i6 < length; ++i6) {
      if (i6 + offset3 >= dst.length || i6 >= src2.length) break;
      dst[i6 + offset3] = src2[i6];
    }
    return i6;
  }
  function isInstance(obj, type4) {
    return obj instanceof type4 || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type4.name;
  }
  function numberIsNaN(obj) {
    return obj !== obj;
  }
  const hexSliceLookupTable = (function() {
    const alphabet5 = "0123456789abcdef";
    const table = new Array(256);
    for (let i6 = 0; i6 < 16; ++i6) {
      const i16 = i6 * 16;
      for (let j3 = 0; j3 < 16; ++j3) {
        table[i16 + j3] = alphabet5[i6] + alphabet5[j3];
      }
    }
    return table;
  })();
  function defineBigIntMethod(fn) {
    return typeof BigInt === "undefined" ? BufferBigIntNotDefined : fn;
  }
  function BufferBigIntNotDefined() {
    throw new Error("BigInt not supported");
  }
  return exports$13;
}
var exports$32, _dewExec$22, exports$22, _dewExec$12, exports$13, _dewExec5, exports5, Buffer3, INSPECT_MAX_BYTES, kMaxLength;
var init_buffer2 = __esm({
  "https://dev.jspm.io/npm:@jspm/core@2.0.1/nodelibs/buffer"() {
    exports$32 = {};
    _dewExec$22 = false;
    exports$22 = {};
    _dewExec$12 = false;
    exports$13 = {};
    _dewExec5 = false;
    exports5 = dew5();
    exports5["Buffer"];
    exports5["SlowBuffer"];
    exports5["INSPECT_MAX_BYTES"];
    exports5["kMaxLength"];
    Buffer3 = exports5.Buffer;
    INSPECT_MAX_BYTES = exports5.INSPECT_MAX_BYTES;
    kMaxLength = exports5.kMaxLength;
  }
});

// https://dev.jspm.io/npm:@jspm/core@2/nodelibs/buffer
var init_buffer3 = __esm({
  "https://dev.jspm.io/npm:@jspm/core@2/nodelibs/buffer"() {
    init_buffer2();
    init_buffer2();
  }
});

// https://dev.jspm.io/npm:@jspm/core@2.0.1/nodelibs/process
function unimplemented(name2) {
  throw new Error("Node.js process " + name2 + " is not supported by JSPM core outside of Node.js");
}
function cleanUpNextTick() {
  if (!draining || !currentQueue)
    return;
  draining = false;
  if (currentQueue.length) {
    queue = currentQueue.concat(queue);
  } else {
    queueIndex = -1;
  }
  if (queue.length)
    drainQueue();
}
function drainQueue() {
  if (draining)
    return;
  var timeout = setTimeout(cleanUpNextTick, 0);
  draining = true;
  var len = queue.length;
  while (len) {
    currentQueue = queue;
    queue = [];
    while (++queueIndex < len) {
      if (currentQueue)
        currentQueue[queueIndex].run();
    }
    queueIndex = -1;
    len = queue.length;
  }
  currentQueue = null;
  draining = false;
  clearTimeout(timeout);
}
function nextTick2(fun) {
  var args = new Array(arguments.length - 1);
  if (arguments.length > 1) {
    for (var i6 = 1; i6 < arguments.length; i6++)
      args[i6 - 1] = arguments[i6];
  }
  queue.push(new Item(fun, args));
  if (queue.length === 1 && !draining)
    setTimeout(drainQueue, 0);
}
function Item(fun, array) {
  this.fun = fun;
  this.array = array;
}
function noop() {
}
function _linkedBinding(name2) {
  unimplemented("_linkedBinding");
}
function dlopen(name2) {
  unimplemented("dlopen");
}
function _getActiveRequests() {
  return [];
}
function _getActiveHandles() {
  return [];
}
function assert6(condition, message) {
  if (!condition) throw new Error(message || "assertion error");
}
function hasUncaughtExceptionCaptureCallback() {
  return false;
}
function uptime() {
  return _performance.now() / 1e3;
}
function hrtime(previousTimestamp) {
  var baseNow = Math.floor((Date.now() - _performance.now()) * 1e-3);
  var clocktime = _performance.now() * 1e-3;
  var seconds = Math.floor(clocktime) + baseNow;
  var nanoseconds = Math.floor(clocktime % 1 * 1e9);
  if (previousTimestamp) {
    seconds = seconds - previousTimestamp[0];
    nanoseconds = nanoseconds - previousTimestamp[1];
    if (nanoseconds < 0) {
      seconds--;
      nanoseconds += nanoPerSec;
    }
  }
  return [seconds, nanoseconds];
}
function on2() {
  return process2;
}
function listeners3(name2) {
  return [];
}
var queue, draining, currentQueue, queueIndex, title, arch2, platform, env, argv, execArgv, version, versions, emitWarning, binding, umask, cwd, chdir, release, _rawDebug, moduleLoadList, domain, _exiting, config, reallyExit, _kill, cpuUsage, resourceUsage, memoryUsage, kill, exit, openStdin, allowedNodeEnvironmentFlags, features, _fatalExceptions, setUncaughtExceptionCaptureCallback, _tickCallback, _debugProcess, _debugEnd, _startProfilerIdleNotifier, _stopProfilerIdleNotifier, stdout, stderr, stdin, abort, pid, ppid, execPath, debugPort, argv0, _preload_modules, setSourceMapsEnabled, _performance, nowOffset, nanoPerSec, _maxListeners, _events, _eventsCount, addListener, once2, off, removeListener, removeAllListeners, emit, prependListener, prependOnceListener, process2;
var init_process2 = __esm({
  "https://dev.jspm.io/npm:@jspm/core@2.0.1/nodelibs/process"() {
    queue = [];
    draining = false;
    queueIndex = -1;
    Item.prototype.run = function() {
      this.fun.apply(null, this.array);
    };
    title = "browser";
    arch2 = "x64";
    platform = "browser";
    env = {
      PATH: "/usr/bin",
      LANG: navigator.language + ".UTF-8",
      PWD: "/",
      HOME: "/home",
      TMP: "/tmp"
    };
    argv = ["/usr/bin/node"];
    execArgv = [];
    version = "v16.8.0";
    versions = {};
    emitWarning = function(message, type4) {
      console.warn((type4 ? type4 + ": " : "") + message);
    };
    binding = function(name2) {
      unimplemented("binding");
    };
    umask = function(mask) {
      return 0;
    };
    cwd = function() {
      return "/";
    };
    chdir = function(dir) {
    };
    release = {
      name: "node",
      sourceUrl: "",
      headersUrl: "",
      libUrl: ""
    };
    _rawDebug = noop;
    moduleLoadList = [];
    domain = {};
    _exiting = false;
    config = {};
    reallyExit = noop;
    _kill = noop;
    cpuUsage = function() {
      return {};
    };
    resourceUsage = cpuUsage;
    memoryUsage = cpuUsage;
    kill = noop;
    exit = noop;
    openStdin = noop;
    allowedNodeEnvironmentFlags = {};
    features = {
      inspector: false,
      debug: false,
      uv: false,
      ipv6: false,
      tls_alpn: false,
      tls_sni: false,
      tls_ocsp: false,
      tls: false,
      cached_builtins: true
    };
    _fatalExceptions = noop;
    setUncaughtExceptionCaptureCallback = noop;
    _tickCallback = noop;
    _debugProcess = noop;
    _debugEnd = noop;
    _startProfilerIdleNotifier = noop;
    _stopProfilerIdleNotifier = noop;
    stdout = void 0;
    stderr = void 0;
    stdin = void 0;
    abort = noop;
    pid = 2;
    ppid = 1;
    execPath = "/bin/usr/node";
    debugPort = 9229;
    argv0 = "node";
    _preload_modules = [];
    setSourceMapsEnabled = noop;
    _performance = {
      now: typeof performance !== "undefined" ? performance.now.bind(performance) : void 0,
      timing: typeof performance !== "undefined" ? performance.timing : void 0
    };
    if (_performance.now === void 0) {
      nowOffset = Date.now();
      if (_performance.timing && _performance.timing.navigationStart) {
        nowOffset = _performance.timing.navigationStart;
      }
      _performance.now = () => Date.now() - nowOffset;
    }
    nanoPerSec = 1e9;
    hrtime.bigint = function(time) {
      var diff3 = hrtime(time);
      if (typeof BigInt === "undefined") {
        return diff3[0] * nanoPerSec + diff3[1];
      }
      return BigInt(diff3[0] * nanoPerSec) + BigInt(diff3[1]);
    };
    _maxListeners = 10;
    _events = {};
    _eventsCount = 0;
    addListener = on2;
    once2 = on2;
    off = on2;
    removeListener = on2;
    removeAllListeners = on2;
    emit = noop;
    prependListener = on2;
    prependOnceListener = on2;
    process2 = {
      version,
      versions,
      arch: arch2,
      platform,
      release,
      _rawDebug,
      moduleLoadList,
      binding,
      _linkedBinding,
      _events,
      _eventsCount,
      _maxListeners,
      on: on2,
      addListener,
      once: once2,
      off,
      removeListener,
      removeAllListeners,
      emit,
      prependListener,
      prependOnceListener,
      listeners: listeners3,
      domain,
      _exiting,
      config,
      dlopen,
      uptime,
      _getActiveRequests,
      _getActiveHandles,
      reallyExit,
      _kill,
      cpuUsage,
      resourceUsage,
      memoryUsage,
      kill,
      exit,
      openStdin,
      allowedNodeEnvironmentFlags,
      assert: assert6,
      features,
      _fatalExceptions,
      setUncaughtExceptionCaptureCallback,
      hasUncaughtExceptionCaptureCallback,
      emitWarning,
      nextTick: nextTick2,
      _tickCallback,
      _debugProcess,
      _debugEnd,
      _startProfilerIdleNotifier,
      _stopProfilerIdleNotifier,
      stdout,
      stdin,
      stderr,
      abort,
      umask,
      chdir,
      cwd,
      env,
      title,
      argv,
      execArgv,
      pid,
      ppid,
      execPath,
      debugPort,
      hrtime,
      argv0,
      _preload_modules,
      setSourceMapsEnabled
    };
  }
});

// https://dev.jspm.io/npm:@jspm/core@2/nodelibs/process
var init_process3 = __esm({
  "https://dev.jspm.io/npm:@jspm/core@2/nodelibs/process"() {
    init_process2();
    init_process2();
  }
});

// https://dev.jspm.io/npm:set-immediate-shim@1.0.1!cjs
var exports6, process3, exports$14, npm_set_immediate_shim_1_0_default;
var init_npm_set_immediate_shim_1_0 = __esm({
  "https://dev.jspm.io/npm:set-immediate-shim@1.0.1!cjs"() {
    init_process3();
    exports6 = {};
    process3 = process2;
    exports6 = typeof process3.nextTick === "function" ? process3.nextTick : function setImmediate() {
      var args = [].slice.apply(arguments);
      args.splice(1, 0, 0);
      setTimeout.apply(null, args);
    };
    exports$14 = exports6;
    npm_set_immediate_shim_1_0_default = exports$14;
  }
});

// https://dev.jspm.io/npm:set-immediate-shim@1.0!cjs
var init_npm_set_immediate_shim_1 = __esm({
  "https://dev.jspm.io/npm:set-immediate-shim@1.0!cjs"() {
    init_process3();
    init_npm_set_immediate_shim_1_0();
  }
});

// https://dev.jspm.io/npm:immediate@3.0.6!cjs
function nextTick3() {
  draining2 = true;
  var i6, oldQueue;
  var len = queue2.length;
  while (len) {
    oldQueue = queue2;
    queue2 = [];
    i6 = -1;
    while (++i6 < len) {
      oldQueue[i6]();
    }
    len = queue2.length;
  }
  draining2 = false;
}
function immediate(task) {
  if (queue2.push(task) === 1 && !draining2) {
    scheduleDrain();
  }
}
var _global4, exports7, Mutation, scheduleDrain, called, observer, element, channel, draining2, queue2, exports$15, npm_immediate_3_0_default;
var init_npm_immediate_3_0 = __esm({
  "https://dev.jspm.io/npm:immediate@3.0.6!cjs"() {
    _global4 = typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : global;
    exports7 = {};
    Mutation = _global4.MutationObserver || _global4.WebKitMutationObserver;
    {
      if (Mutation) {
        called = 0;
        observer = new Mutation(nextTick3);
        element = _global4.document.createTextNode("");
        observer.observe(element, {
          characterData: true
        });
        scheduleDrain = function() {
          element.data = called = ++called % 2;
        };
      } else if (!_global4.setImmediate && typeof _global4.MessageChannel !== "undefined") {
        channel = new _global4.MessageChannel();
        channel.port1.onmessage = nextTick3;
        scheduleDrain = function() {
          channel.port2.postMessage(0);
        };
      } else if ("document" in _global4 && "onreadystatechange" in _global4.document.createElement("script")) {
        scheduleDrain = function() {
          var scriptEl = _global4.document.createElement("script");
          scriptEl.onreadystatechange = function() {
            nextTick3();
            scriptEl.onreadystatechange = null;
            scriptEl.parentNode.removeChild(scriptEl);
            scriptEl = null;
          };
          _global4.document.documentElement.appendChild(scriptEl);
        };
      } else {
        scheduleDrain = function() {
          setTimeout(nextTick3, 0);
        };
      }
    }
    queue2 = [];
    exports7 = immediate;
    exports$15 = exports7;
    npm_immediate_3_0_default = exports$15;
  }
});

// https://dev.jspm.io/npm:immediate@3.0!cjs
var init_npm_immediate_3 = __esm({
  "https://dev.jspm.io/npm:immediate@3.0!cjs"() {
    init_npm_immediate_3_0();
  }
});

// https://dev.jspm.io/npm:lie@3.3.0!cjs
function INTERNAL() {
}
function Promise2(resolver) {
  if (typeof resolver !== "function") {
    throw new TypeError("resolver must be a function");
  }
  this.state = PENDING;
  this.queue = [];
  this.outcome = void 0;
  if (resolver !== INTERNAL) {
    safelyResolveThenable(this, resolver);
  }
}
function QueueItem(promise, onFulfilled, onRejected) {
  this.promise = promise;
  if (typeof onFulfilled === "function") {
    this.onFulfilled = onFulfilled;
    this.callFulfilled = this.otherCallFulfilled;
  }
  if (typeof onRejected === "function") {
    this.onRejected = onRejected;
    this.callRejected = this.otherCallRejected;
  }
}
function unwrap(promise, func, value) {
  immediate2(function() {
    var returnValue;
    try {
      returnValue = func(value);
    } catch (e5) {
      return handlers.reject(promise, e5);
    }
    if (returnValue === promise) {
      handlers.reject(promise, new TypeError("Cannot resolve promise with itself"));
    } else {
      handlers.resolve(promise, returnValue);
    }
  });
}
function getThen(obj) {
  var then = obj && obj.then;
  if (obj && (typeof obj === "object" || typeof obj === "function") && typeof then === "function") {
    return function appyThen() {
      then.apply(obj, arguments);
    };
  }
}
function safelyResolveThenable(self2, thenable) {
  var called = false;
  function onError(value) {
    if (called) {
      return;
    }
    called = true;
    handlers.reject(self2, value);
  }
  function onSuccess(value) {
    if (called) {
      return;
    }
    called = true;
    handlers.resolve(self2, value);
  }
  function tryToUnwrap() {
    thenable(onSuccess, onError);
  }
  var result2 = tryCatch(tryToUnwrap);
  if (result2.status === "error") {
    onError(result2.value);
  }
}
function tryCatch(func, value) {
  var out = {};
  try {
    out.value = func(value);
    out.status = "success";
  } catch (e5) {
    out.status = "error";
    out.value = e5;
  }
  return out;
}
function resolve11(value) {
  if (value instanceof this) {
    return value;
  }
  return handlers.resolve(new this(INTERNAL), value);
}
function reject(reason) {
  var promise = new this(INTERNAL);
  return handlers.reject(promise, reason);
}
function all(iterable) {
  var self2 = this;
  if (Object.prototype.toString.call(iterable) !== "[object Array]") {
    return this.reject(new TypeError("must be an array"));
  }
  var len = iterable.length;
  var called = false;
  if (!len) {
    return this.resolve([]);
  }
  var values = new Array(len);
  var resolved = 0;
  var i6 = -1;
  var promise = new this(INTERNAL);
  while (++i6 < len) {
    allResolver(iterable[i6], i6);
  }
  return promise;
  function allResolver(value, i7) {
    self2.resolve(value).then(resolveFromAll, function(error2) {
      if (!called) {
        called = true;
        handlers.reject(promise, error2);
      }
    });
    function resolveFromAll(outValue) {
      values[i7] = outValue;
      if (++resolved === len && !called) {
        called = true;
        handlers.resolve(promise, values);
      }
    }
  }
}
function race(iterable) {
  var self2 = this;
  if (Object.prototype.toString.call(iterable) !== "[object Array]") {
    return this.reject(new TypeError("must be an array"));
  }
  var len = iterable.length;
  var called = false;
  if (!len) {
    return this.resolve([]);
  }
  var i6 = -1;
  var promise = new this(INTERNAL);
  while (++i6 < len) {
    resolver(iterable[i6]);
  }
  return promise;
  function resolver(value) {
    self2.resolve(value).then(function(response) {
      if (!called) {
        called = true;
        handlers.resolve(promise, response);
      }
    }, function(error2) {
      if (!called) {
        called = true;
        handlers.reject(promise, error2);
      }
    });
  }
}
var exports8, immediate2, handlers, REJECTED, FULFILLED, PENDING, _lib, npm_lie_3_3_default;
var init_npm_lie_3_3 = __esm({
  "https://dev.jspm.io/npm:lie@3.3.0!cjs"() {
    init_npm_immediate_3();
    exports8 = {};
    immediate2 = npm_immediate_3_0_default;
    handlers = {};
    REJECTED = ["REJECTED"];
    FULFILLED = ["FULFILLED"];
    PENDING = ["PENDING"];
    exports8 = Promise2;
    Promise2.prototype["finally"] = function(callback) {
      if (typeof callback !== "function") {
        return this;
      }
      var p5 = this.constructor;
      return this.then(resolve16, reject2);
      function resolve16(value) {
        function yes() {
          return value;
        }
        return p5.resolve(callback()).then(yes);
      }
      function reject2(reason) {
        function no() {
          throw reason;
        }
        return p5.resolve(callback()).then(no);
      }
    };
    Promise2.prototype["catch"] = function(onRejected) {
      return this.then(null, onRejected);
    };
    Promise2.prototype.then = function(onFulfilled, onRejected) {
      if (typeof onFulfilled !== "function" && this.state === FULFILLED || typeof onRejected !== "function" && this.state === REJECTED) {
        return this;
      }
      var promise = new this.constructor(INTERNAL);
      if (this.state !== PENDING) {
        var resolver = this.state === FULFILLED ? onFulfilled : onRejected;
        unwrap(promise, resolver, this.outcome);
      } else {
        this.queue.push(new QueueItem(promise, onFulfilled, onRejected));
      }
      return promise;
    };
    QueueItem.prototype.callFulfilled = function(value) {
      handlers.resolve(this.promise, value);
    };
    QueueItem.prototype.otherCallFulfilled = function(value) {
      unwrap(this.promise, this.onFulfilled, value);
    };
    QueueItem.prototype.callRejected = function(value) {
      handlers.reject(this.promise, value);
    };
    QueueItem.prototype.otherCallRejected = function(value) {
      unwrap(this.promise, this.onRejected, value);
    };
    handlers.resolve = function(self2, value) {
      var result2 = tryCatch(getThen, value);
      if (result2.status === "error") {
        return handlers.reject(self2, result2.value);
      }
      var thenable = result2.value;
      if (thenable) {
        safelyResolveThenable(self2, thenable);
      } else {
        self2.state = FULFILLED;
        self2.outcome = value;
        var i6 = -1;
        var len = self2.queue.length;
        while (++i6 < len) {
          self2.queue[i6].callFulfilled(value);
        }
      }
      return self2;
    };
    handlers.reject = function(self2, error2) {
      self2.state = REJECTED;
      self2.outcome = error2;
      var i6 = -1;
      var len = self2.queue.length;
      while (++i6 < len) {
        self2.queue[i6].callRejected(error2);
      }
      return self2;
    };
    Promise2.resolve = resolve11;
    Promise2.reject = reject;
    Promise2.all = all;
    Promise2.race = race;
    _lib = exports8;
    npm_lie_3_3_default = _lib;
  }
});

// https://dev.jspm.io/npm:lie@3.3!cjs
var init_npm_lie_3 = __esm({
  "https://dev.jspm.io/npm:lie@3.3!cjs"() {
    init_npm_immediate_3();
    init_npm_lie_3_3();
  }
});

// https://dev.jspm.io/npm:pako@1.0.11/lib/utils/common!cjs
function _has(obj, key) {
  return Object.prototype.hasOwnProperty.call(obj, key);
}
var exports9, TYPED_OK, fnTyped, fnUntyped, assign, shrinkBuf, setTyped, Buf8, Buf16, Buf32, common_cjs_default;
var init_common_cjs = __esm({
  "https://dev.jspm.io/npm:pako@1.0.11/lib/utils/common!cjs"() {
    exports9 = {};
    TYPED_OK = typeof Uint8Array !== "undefined" && typeof Uint16Array !== "undefined" && typeof Int32Array !== "undefined";
    exports9.assign = function(obj) {
      var sources = Array.prototype.slice.call(arguments, 1);
      while (sources.length) {
        var source2 = sources.shift();
        if (!source2) {
          continue;
        }
        if (typeof source2 !== "object") {
          throw new TypeError(source2 + "must be non-object");
        }
        for (var p5 in source2) {
          if (_has(source2, p5)) {
            obj[p5] = source2[p5];
          }
        }
      }
      return obj;
    };
    exports9.shrinkBuf = function(buf, size) {
      if (buf.length === size) {
        return buf;
      }
      if (buf.subarray) {
        return buf.subarray(0, size);
      }
      buf.length = size;
      return buf;
    };
    fnTyped = {
      arraySet: function(dest, src2, src_offs, len, dest_offs) {
        if (src2.subarray && dest.subarray) {
          dest.set(src2.subarray(src_offs, src_offs + len), dest_offs);
          return;
        }
        for (var i6 = 0; i6 < len; i6++) {
          dest[dest_offs + i6] = src2[src_offs + i6];
        }
      },
      // Join array of chunks to single array.
      flattenChunks: function(chunks) {
        var i6, l6, len, pos, chunk, result2;
        len = 0;
        for (i6 = 0, l6 = chunks.length; i6 < l6; i6++) {
          len += chunks[i6].length;
        }
        result2 = new Uint8Array(len);
        pos = 0;
        for (i6 = 0, l6 = chunks.length; i6 < l6; i6++) {
          chunk = chunks[i6];
          result2.set(chunk, pos);
          pos += chunk.length;
        }
        return result2;
      }
    };
    fnUntyped = {
      arraySet: function(dest, src2, src_offs, len, dest_offs) {
        for (var i6 = 0; i6 < len; i6++) {
          dest[dest_offs + i6] = src2[src_offs + i6];
        }
      },
      // Join array of chunks to single array.
      flattenChunks: function(chunks) {
        return [].concat.apply([], chunks);
      }
    };
    exports9.setTyped = function(on3) {
      if (on3) {
        exports9.Buf8 = Uint8Array;
        exports9.Buf16 = Uint16Array;
        exports9.Buf32 = Int32Array;
        exports9.assign(exports9, fnTyped);
      } else {
        exports9.Buf8 = Array;
        exports9.Buf16 = Array;
        exports9.Buf32 = Array;
        exports9.assign(exports9, fnUntyped);
      }
    };
    exports9.setTyped(TYPED_OK);
    assign = exports9.assign;
    shrinkBuf = exports9.shrinkBuf;
    setTyped = exports9.setTyped;
    Buf8 = exports9.Buf8;
    Buf16 = exports9.Buf16;
    Buf32 = exports9.Buf32;
    common_cjs_default = exports9;
  }
});

// https://dev.jspm.io/npm:pako@1.0.11/lib/zlib/adler32!cjs
function adler32(adler, buf, len, pos) {
  var s1 = adler & 65535 | 0, s22 = adler >>> 16 & 65535 | 0, n5 = 0;
  while (len !== 0) {
    n5 = len > 2e3 ? 2e3 : len;
    len -= n5;
    do {
      s1 = s1 + buf[pos++] | 0;
      s22 = s22 + s1 | 0;
    } while (--n5);
    s1 %= 65521;
    s22 %= 65521;
  }
  return s1 | s22 << 16 | 0;
}
var exports10, _adler, adler32_cjs_default;
var init_adler32_cjs = __esm({
  "https://dev.jspm.io/npm:pako@1.0.11/lib/zlib/adler32!cjs"() {
    exports10 = {};
    exports10 = adler32;
    _adler = exports10;
    adler32_cjs_default = _adler;
  }
});

// https://dev.jspm.io/npm:pako@1.0.11/lib/zlib/crc32!cjs
function makeTable() {
  var c6, table = [];
  for (var n5 = 0; n5 < 256; n5++) {
    c6 = n5;
    for (var k3 = 0; k3 < 8; k3++) {
      c6 = c6 & 1 ? 3988292384 ^ c6 >>> 1 : c6 >>> 1;
    }
    table[n5] = c6;
  }
  return table;
}
function crc32(crc, buf, len, pos) {
  var t5 = crcTable, end = pos + len;
  crc ^= -1;
  for (var i6 = pos; i6 < end; i6++) {
    crc = crc >>> 8 ^ t5[(crc ^ buf[i6]) & 255];
  }
  return crc ^ -1;
}
var exports11, crcTable, _crc, crc32_cjs_default;
var init_crc32_cjs = __esm({
  "https://dev.jspm.io/npm:pako@1.0.11/lib/zlib/crc32!cjs"() {
    exports11 = {};
    crcTable = makeTable();
    exports11 = crc32;
    _crc = exports11;
    crc32_cjs_default = _crc;
  }
});

// https://dev.jspm.io/npm:pako@1.0.11/lib/zlib/messages!cjs
var exports12, _messages, messages_cjs_default;
var init_messages_cjs = __esm({
  "https://dev.jspm.io/npm:pako@1.0.11/lib/zlib/messages!cjs"() {
    exports12 = {};
    exports12 = {
      2: "need dictionary",
      /* Z_NEED_DICT       2  */
      1: "stream end",
      /* Z_STREAM_END      1  */
      0: "",
      /* Z_OK              0  */
      "-1": "file error",
      /* Z_ERRNO         (-1) */
      "-2": "stream error",
      /* Z_STREAM_ERROR  (-2) */
      "-3": "data error",
      /* Z_DATA_ERROR    (-3) */
      "-4": "insufficient memory",
      /* Z_MEM_ERROR     (-4) */
      "-5": "buffer error",
      /* Z_BUF_ERROR     (-5) */
      "-6": "incompatible version"
      /* Z_VERSION_ERROR (-6) */
    };
    _messages = exports12;
    messages_cjs_default = _messages;
  }
});

// https://dev.jspm.io/npm:pako@1.0.11/lib/zlib/deflate.js!cjs
function zero(buf) {
  var len = buf.length;
  while (--len >= 0) {
    buf[len] = 0;
  }
}
function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
  this.static_tree = static_tree;
  this.extra_bits = extra_bits;
  this.extra_base = extra_base;
  this.elems = elems;
  this.max_length = max_length;
  this.has_stree = static_tree && static_tree.length;
}
function TreeDesc(dyn_tree, stat_desc) {
  this.dyn_tree = dyn_tree;
  this.max_code = 0;
  this.stat_desc = stat_desc;
}
function d_code(dist) {
  return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
}
function put_short(s5, w3) {
  s5.pending_buf[s5.pending++] = w3 & 255;
  s5.pending_buf[s5.pending++] = w3 >>> 8 & 255;
}
function send_bits(s5, value, length) {
  if (s5.bi_valid > Buf_size - length) {
    s5.bi_buf |= value << s5.bi_valid & 65535;
    put_short(s5, s5.bi_buf);
    s5.bi_buf = value >> Buf_size - s5.bi_valid;
    s5.bi_valid += length - Buf_size;
  } else {
    s5.bi_buf |= value << s5.bi_valid & 65535;
    s5.bi_valid += length;
  }
}
function send_code(s5, c6, tree) {
  send_bits(
    s5,
    tree[c6 * 2],
    tree[c6 * 2 + 1]
    /*.Len*/
  );
}
function bi_reverse(code5, len) {
  var res = 0;
  do {
    res |= code5 & 1;
    code5 >>>= 1;
    res <<= 1;
  } while (--len > 0);
  return res >>> 1;
}
function bi_flush(s5) {
  if (s5.bi_valid === 16) {
    put_short(s5, s5.bi_buf);
    s5.bi_buf = 0;
    s5.bi_valid = 0;
  } else if (s5.bi_valid >= 8) {
    s5.pending_buf[s5.pending++] = s5.bi_buf & 255;
    s5.bi_buf >>= 8;
    s5.bi_valid -= 8;
  }
}
function gen_bitlen(s5, desc) {
  var tree = desc.dyn_tree;
  var max_code = desc.max_code;
  var stree = desc.stat_desc.static_tree;
  var has_stree = desc.stat_desc.has_stree;
  var extra = desc.stat_desc.extra_bits;
  var base3 = desc.stat_desc.extra_base;
  var max_length = desc.stat_desc.max_length;
  var h5;
  var n5, m4;
  var bits;
  var xbits;
  var f5;
  var overflow = 0;
  for (bits = 0; bits <= MAX_BITS; bits++) {
    s5.bl_count[bits] = 0;
  }
  tree[s5.heap[s5.heap_max] * 2 + 1] = 0;
  for (h5 = s5.heap_max + 1; h5 < HEAP_SIZE; h5++) {
    n5 = s5.heap[h5];
    bits = tree[tree[n5 * 2 + 1] * 2 + 1] + 1;
    if (bits > max_length) {
      bits = max_length;
      overflow++;
    }
    tree[n5 * 2 + 1] = bits;
    if (n5 > max_code) {
      continue;
    }
    s5.bl_count[bits]++;
    xbits = 0;
    if (n5 >= base3) {
      xbits = extra[n5 - base3];
    }
    f5 = tree[n5 * 2];
    s5.opt_len += f5 * (bits + xbits);
    if (has_stree) {
      s5.static_len += f5 * (stree[n5 * 2 + 1] + xbits);
    }
  }
  if (overflow === 0) {
    return;
  }
  do {
    bits = max_length - 1;
    while (s5.bl_count[bits] === 0) {
      bits--;
    }
    s5.bl_count[bits]--;
    s5.bl_count[bits + 1] += 2;
    s5.bl_count[max_length]--;
    overflow -= 2;
  } while (overflow > 0);
  for (bits = max_length; bits !== 0; bits--) {
    n5 = s5.bl_count[bits];
    while (n5 !== 0) {
      m4 = s5.heap[--h5];
      if (m4 > max_code) {
        continue;
      }
      if (tree[m4 * 2 + 1] !== bits) {
        s5.opt_len += (bits - tree[m4 * 2 + 1]) * tree[m4 * 2];
        tree[m4 * 2 + 1] = bits;
      }
      n5--;
    }
  }
}
function gen_codes(tree, max_code, bl_count) {
  var next_code = new Array(MAX_BITS + 1);
  var code5 = 0;
  var bits;
  var n5;
  for (bits = 1; bits <= MAX_BITS; bits++) {
    next_code[bits] = code5 = code5 + bl_count[bits - 1] << 1;
  }
  for (n5 = 0; n5 <= max_code; n5++) {
    var len = tree[n5 * 2 + 1];
    if (len === 0) {
      continue;
    }
    tree[n5 * 2] = bi_reverse(next_code[len]++, len);
  }
}
function tr_static_init() {
  var n5;
  var bits;
  var length;
  var code5;
  var dist;
  var bl_count = new Array(MAX_BITS + 1);
  length = 0;
  for (code5 = 0; code5 < LENGTH_CODES - 1; code5++) {
    base_length[code5] = length;
    for (n5 = 0; n5 < 1 << extra_lbits[code5]; n5++) {
      _length_code[length++] = code5;
    }
  }
  _length_code[length - 1] = code5;
  dist = 0;
  for (code5 = 0; code5 < 16; code5++) {
    base_dist[code5] = dist;
    for (n5 = 0; n5 < 1 << extra_dbits[code5]; n5++) {
      _dist_code[dist++] = code5;
    }
  }
  dist >>= 7;
  for (; code5 < D_CODES; code5++) {
    base_dist[code5] = dist << 7;
    for (n5 = 0; n5 < 1 << extra_dbits[code5] - 7; n5++) {
      _dist_code[256 + dist++] = code5;
    }
  }
  for (bits = 0; bits <= MAX_BITS; bits++) {
    bl_count[bits] = 0;
  }
  n5 = 0;
  while (n5 <= 143) {
    static_ltree[n5 * 2 + 1] = 8;
    n5++;
    bl_count[8]++;
  }
  while (n5 <= 255) {
    static_ltree[n5 * 2 + 1] = 9;
    n5++;
    bl_count[9]++;
  }
  while (n5 <= 279) {
    static_ltree[n5 * 2 + 1] = 7;
    n5++;
    bl_count[7]++;
  }
  while (n5 <= 287) {
    static_ltree[n5 * 2 + 1] = 8;
    n5++;
    bl_count[8]++;
  }
  gen_codes(static_ltree, L_CODES + 1, bl_count);
  for (n5 = 0; n5 < D_CODES; n5++) {
    static_dtree[n5 * 2 + 1] = 5;
    static_dtree[n5 * 2] = bi_reverse(n5, 5);
  }
  static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
  static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
}
function init_block(s5) {
  var n5;
  for (n5 = 0; n5 < L_CODES; n5++) {
    s5.dyn_ltree[n5 * 2] = 0;
  }
  for (n5 = 0; n5 < D_CODES; n5++) {
    s5.dyn_dtree[n5 * 2] = 0;
  }
  for (n5 = 0; n5 < BL_CODES; n5++) {
    s5.bl_tree[n5 * 2] = 0;
  }
  s5.dyn_ltree[END_BLOCK * 2] = 1;
  s5.opt_len = s5.static_len = 0;
  s5.last_lit = s5.matches = 0;
}
function bi_windup(s5) {
  if (s5.bi_valid > 8) {
    put_short(s5, s5.bi_buf);
  } else if (s5.bi_valid > 0) {
    s5.pending_buf[s5.pending++] = s5.bi_buf;
  }
  s5.bi_buf = 0;
  s5.bi_valid = 0;
}
function copy_block(s5, buf, len, header) {
  bi_windup(s5);
  if (header) {
    put_short(s5, len);
    put_short(s5, ~len);
  }
  utils.arraySet(s5.pending_buf, s5.window, buf, len, s5.pending);
  s5.pending += len;
}
function smaller(tree, n5, m4, depth) {
  var _n2 = n5 * 2;
  var _m2 = m4 * 2;
  return tree[_n2] < tree[_m2] || tree[_n2] === tree[_m2] && depth[n5] <= depth[m4];
}
function pqdownheap(s5, tree, k3) {
  var v4 = s5.heap[k3];
  var j3 = k3 << 1;
  while (j3 <= s5.heap_len) {
    if (j3 < s5.heap_len && smaller(tree, s5.heap[j3 + 1], s5.heap[j3], s5.depth)) {
      j3++;
    }
    if (smaller(tree, v4, s5.heap[j3], s5.depth)) {
      break;
    }
    s5.heap[k3] = s5.heap[j3];
    k3 = j3;
    j3 <<= 1;
  }
  s5.heap[k3] = v4;
}
function compress_block(s5, ltree, dtree) {
  var dist;
  var lc;
  var lx = 0;
  var code5;
  var extra;
  if (s5.last_lit !== 0) {
    do {
      dist = s5.pending_buf[s5.d_buf + lx * 2] << 8 | s5.pending_buf[s5.d_buf + lx * 2 + 1];
      lc = s5.pending_buf[s5.l_buf + lx];
      lx++;
      if (dist === 0) {
        send_code(s5, lc, ltree);
      } else {
        code5 = _length_code[lc];
        send_code(s5, code5 + LITERALS + 1, ltree);
        extra = extra_lbits[code5];
        if (extra !== 0) {
          lc -= base_length[code5];
          send_bits(s5, lc, extra);
        }
        dist--;
        code5 = d_code(dist);
        send_code(s5, code5, dtree);
        extra = extra_dbits[code5];
        if (extra !== 0) {
          dist -= base_dist[code5];
          send_bits(s5, dist, extra);
        }
      }
    } while (lx < s5.last_lit);
  }
  send_code(s5, END_BLOCK, ltree);
}
function build_tree(s5, desc) {
  var tree = desc.dyn_tree;
  var stree = desc.stat_desc.static_tree;
  var has_stree = desc.stat_desc.has_stree;
  var elems = desc.stat_desc.elems;
  var n5, m4;
  var max_code = -1;
  var node;
  s5.heap_len = 0;
  s5.heap_max = HEAP_SIZE;
  for (n5 = 0; n5 < elems; n5++) {
    if (tree[n5 * 2] !== 0) {
      s5.heap[++s5.heap_len] = max_code = n5;
      s5.depth[n5] = 0;
    } else {
      tree[n5 * 2 + 1] = 0;
    }
  }
  while (s5.heap_len < 2) {
    node = s5.heap[++s5.heap_len] = max_code < 2 ? ++max_code : 0;
    tree[node * 2] = 1;
    s5.depth[node] = 0;
    s5.opt_len--;
    if (has_stree) {
      s5.static_len -= stree[node * 2 + 1];
    }
  }
  desc.max_code = max_code;
  for (n5 = s5.heap_len >> 1; n5 >= 1; n5--) {
    pqdownheap(s5, tree, n5);
  }
  node = elems;
  do {
    n5 = s5.heap[
      1
      /*SMALLEST*/
    ];
    s5.heap[
      1
      /*SMALLEST*/
    ] = s5.heap[s5.heap_len--];
    pqdownheap(
      s5,
      tree,
      1
      /*SMALLEST*/
    );
    m4 = s5.heap[
      1
      /*SMALLEST*/
    ];
    s5.heap[--s5.heap_max] = n5;
    s5.heap[--s5.heap_max] = m4;
    tree[node * 2] = tree[n5 * 2] + tree[m4 * 2];
    s5.depth[node] = (s5.depth[n5] >= s5.depth[m4] ? s5.depth[n5] : s5.depth[m4]) + 1;
    tree[n5 * 2 + 1] = tree[m4 * 2 + 1] = node;
    s5.heap[
      1
      /*SMALLEST*/
    ] = node++;
    pqdownheap(
      s5,
      tree,
      1
      /*SMALLEST*/
    );
  } while (s5.heap_len >= 2);
  s5.heap[--s5.heap_max] = s5.heap[
    1
    /*SMALLEST*/
  ];
  gen_bitlen(s5, desc);
  gen_codes(tree, max_code, s5.bl_count);
}
function scan_tree(s5, tree, max_code) {
  var n5;
  var prevlen = -1;
  var curlen;
  var nextlen = tree[0 * 2 + 1];
  var count = 0;
  var max_count = 7;
  var min_count = 4;
  if (nextlen === 0) {
    max_count = 138;
    min_count = 3;
  }
  tree[(max_code + 1) * 2 + 1] = 65535;
  for (n5 = 0; n5 <= max_code; n5++) {
    curlen = nextlen;
    nextlen = tree[(n5 + 1) * 2 + 1];
    if (++count < max_count && curlen === nextlen) {
      continue;
    } else if (count < min_count) {
      s5.bl_tree[curlen * 2] += count;
    } else if (curlen !== 0) {
      if (curlen !== prevlen) {
        s5.bl_tree[curlen * 2]++;
      }
      s5.bl_tree[REP_3_6 * 2]++;
    } else if (count <= 10) {
      s5.bl_tree[REPZ_3_10 * 2]++;
    } else {
      s5.bl_tree[REPZ_11_138 * 2]++;
    }
    count = 0;
    prevlen = curlen;
    if (nextlen === 0) {
      max_count = 138;
      min_count = 3;
    } else if (curlen === nextlen) {
      max_count = 6;
      min_count = 3;
    } else {
      max_count = 7;
      min_count = 4;
    }
  }
}
function send_tree(s5, tree, max_code) {
  var n5;
  var prevlen = -1;
  var curlen;
  var nextlen = tree[0 * 2 + 1];
  var count = 0;
  var max_count = 7;
  var min_count = 4;
  if (nextlen === 0) {
    max_count = 138;
    min_count = 3;
  }
  for (n5 = 0; n5 <= max_code; n5++) {
    curlen = nextlen;
    nextlen = tree[(n5 + 1) * 2 + 1];
    if (++count < max_count && curlen === nextlen) {
      continue;
    } else if (count < min_count) {
      do {
        send_code(s5, curlen, s5.bl_tree);
      } while (--count !== 0);
    } else if (curlen !== 0) {
      if (curlen !== prevlen) {
        send_code(s5, curlen, s5.bl_tree);
        count--;
      }
      send_code(s5, REP_3_6, s5.bl_tree);
      send_bits(s5, count - 3, 2);
    } else if (count <= 10) {
      send_code(s5, REPZ_3_10, s5.bl_tree);
      send_bits(s5, count - 3, 3);
    } else {
      send_code(s5, REPZ_11_138, s5.bl_tree);
      send_bits(s5, count - 11, 7);
    }
    count = 0;
    prevlen = curlen;
    if (nextlen === 0) {
      max_count = 138;
      min_count = 3;
    } else if (curlen === nextlen) {
      max_count = 6;
      min_count = 3;
    } else {
      max_count = 7;
      min_count = 4;
    }
  }
}
function build_bl_tree(s5) {
  var max_blindex;
  scan_tree(s5, s5.dyn_ltree, s5.l_desc.max_code);
  scan_tree(s5, s5.dyn_dtree, s5.d_desc.max_code);
  build_tree(s5, s5.bl_desc);
  for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
    if (s5.bl_tree[bl_order[max_blindex] * 2 + 1] !== 0) {
      break;
    }
  }
  s5.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
  return max_blindex;
}
function send_all_trees(s5, lcodes, dcodes, blcodes) {
  var rank2;
  send_bits(s5, lcodes - 257, 5);
  send_bits(s5, dcodes - 1, 5);
  send_bits(s5, blcodes - 4, 4);
  for (rank2 = 0; rank2 < blcodes; rank2++) {
    send_bits(
      s5,
      s5.bl_tree[bl_order[rank2] * 2 + 1],
      3
    );
  }
  send_tree(s5, s5.dyn_ltree, lcodes - 1);
  send_tree(s5, s5.dyn_dtree, dcodes - 1);
}
function detect_data_type(s5) {
  var black_mask = 4093624447;
  var n5;
  for (n5 = 0; n5 <= 31; n5++, black_mask >>>= 1) {
    if (black_mask & 1 && s5.dyn_ltree[n5 * 2] !== 0) {
      return Z_BINARY;
    }
  }
  if (s5.dyn_ltree[9 * 2] !== 0 || s5.dyn_ltree[10 * 2] !== 0 || s5.dyn_ltree[13 * 2] !== 0) {
    return Z_TEXT;
  }
  for (n5 = 32; n5 < LITERALS; n5++) {
    if (s5.dyn_ltree[n5 * 2] !== 0) {
      return Z_TEXT;
    }
  }
  return Z_BINARY;
}
function _tr_init(s5) {
  if (!static_init_done) {
    tr_static_init();
    static_init_done = true;
  }
  s5.l_desc = new TreeDesc(s5.dyn_ltree, static_l_desc);
  s5.d_desc = new TreeDesc(s5.dyn_dtree, static_d_desc);
  s5.bl_desc = new TreeDesc(s5.bl_tree, static_bl_desc);
  s5.bi_buf = 0;
  s5.bi_valid = 0;
  init_block(s5);
}
function _tr_stored_block(s5, buf, stored_len, last) {
  send_bits(s5, (STORED_BLOCK << 1) + (last ? 1 : 0), 3);
  copy_block(s5, buf, stored_len, true);
}
function _tr_align(s5) {
  send_bits(s5, STATIC_TREES << 1, 3);
  send_code(s5, END_BLOCK, static_ltree);
  bi_flush(s5);
}
function _tr_flush_block(s5, buf, stored_len, last) {
  var opt_lenb, static_lenb;
  var max_blindex = 0;
  if (s5.level > 0) {
    if (s5.strm.data_type === Z_UNKNOWN) {
      s5.strm.data_type = detect_data_type(s5);
    }
    build_tree(s5, s5.l_desc);
    build_tree(s5, s5.d_desc);
    max_blindex = build_bl_tree(s5);
    opt_lenb = s5.opt_len + 3 + 7 >>> 3;
    static_lenb = s5.static_len + 3 + 7 >>> 3;
    if (static_lenb <= opt_lenb) {
      opt_lenb = static_lenb;
    }
  } else {
    opt_lenb = static_lenb = stored_len + 5;
  }
  if (stored_len + 4 <= opt_lenb && buf !== -1) {
    _tr_stored_block(s5, buf, stored_len, last);
  } else if (s5.strategy === Z_FIXED || static_lenb === opt_lenb) {
    send_bits(s5, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
    compress_block(s5, static_ltree, static_dtree);
  } else {
    send_bits(s5, (DYN_TREES << 1) + (last ? 1 : 0), 3);
    send_all_trees(s5, s5.l_desc.max_code + 1, s5.d_desc.max_code + 1, max_blindex + 1);
    compress_block(s5, s5.dyn_ltree, s5.dyn_dtree);
  }
  init_block(s5);
  if (last) {
    bi_windup(s5);
  }
}
function _tr_tally(s5, dist, lc) {
  s5.pending_buf[s5.d_buf + s5.last_lit * 2] = dist >>> 8 & 255;
  s5.pending_buf[s5.d_buf + s5.last_lit * 2 + 1] = dist & 255;
  s5.pending_buf[s5.l_buf + s5.last_lit] = lc & 255;
  s5.last_lit++;
  if (dist === 0) {
    s5.dyn_ltree[lc * 2]++;
  } else {
    s5.matches++;
    dist--;
    s5.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]++;
    s5.dyn_dtree[d_code(dist) * 2]++;
  }
  return s5.last_lit === s5.lit_bufsize - 1;
}
function err(strm, errorCode) {
  strm.msg = msg[errorCode];
  return errorCode;
}
function rank(f5) {
  return (f5 << 1) - (f5 > 4 ? 9 : 0);
}
function zero$1(buf) {
  var len = buf.length;
  while (--len >= 0) {
    buf[len] = 0;
  }
}
function flush_pending(strm) {
  var s5 = strm.state;
  var len = s5.pending;
  if (len > strm.avail_out) {
    len = strm.avail_out;
  }
  if (len === 0) {
    return;
  }
  utils$1.arraySet(strm.output, s5.pending_buf, s5.pending_out, len, strm.next_out);
  strm.next_out += len;
  s5.pending_out += len;
  strm.total_out += len;
  strm.avail_out -= len;
  s5.pending -= len;
  if (s5.pending === 0) {
    s5.pending_out = 0;
  }
}
function flush_block_only(s5, last) {
  trees._tr_flush_block(s5, s5.block_start >= 0 ? s5.block_start : -1, s5.strstart - s5.block_start, last);
  s5.block_start = s5.strstart;
  flush_pending(s5.strm);
}
function put_byte(s5, b3) {
  s5.pending_buf[s5.pending++] = b3;
}
function putShortMSB(s5, b3) {
  s5.pending_buf[s5.pending++] = b3 >>> 8 & 255;
  s5.pending_buf[s5.pending++] = b3 & 255;
}
function read_buf(strm, buf, start, size) {
  var len = strm.avail_in;
  if (len > size) {
    len = size;
  }
  if (len === 0) {
    return 0;
  }
  strm.avail_in -= len;
  utils$1.arraySet(buf, strm.input, strm.next_in, len, start);
  if (strm.state.wrap === 1) {
    strm.adler = adler322(strm.adler, buf, len, start);
  } else if (strm.state.wrap === 2) {
    strm.adler = crc322(strm.adler, buf, len, start);
  }
  strm.next_in += len;
  strm.total_in += len;
  return len;
}
function longest_match(s5, cur_match) {
  var chain_length = s5.max_chain_length;
  var scan = s5.strstart;
  var match;
  var len;
  var best_len = s5.prev_length;
  var nice_match = s5.nice_match;
  var limit = s5.strstart > s5.w_size - MIN_LOOKAHEAD ? s5.strstart - (s5.w_size - MIN_LOOKAHEAD) : 0;
  var _win = s5.window;
  var wmask = s5.w_mask;
  var prev = s5.prev;
  var strend = s5.strstart + MAX_MATCH$1;
  var scan_end1 = _win[scan + best_len - 1];
  var scan_end = _win[scan + best_len];
  if (s5.prev_length >= s5.good_match) {
    chain_length >>= 2;
  }
  if (nice_match > s5.lookahead) {
    nice_match = s5.lookahead;
  }
  do {
    match = cur_match;
    if (_win[match + best_len] !== scan_end || _win[match + best_len - 1] !== scan_end1 || _win[match] !== _win[scan] || _win[++match] !== _win[scan + 1]) {
      continue;
    }
    scan += 2;
    match++;
    do {
    } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && scan < strend);
    len = MAX_MATCH$1 - (strend - scan);
    scan = strend - MAX_MATCH$1;
    if (len > best_len) {
      s5.match_start = cur_match;
      best_len = len;
      if (len >= nice_match) {
        break;
      }
      scan_end1 = _win[scan + best_len - 1];
      scan_end = _win[scan + best_len];
    }
  } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  if (best_len <= s5.lookahead) {
    return best_len;
  }
  return s5.lookahead;
}
function fill_window(s5) {
  var _w_size = s5.w_size;
  var p5, n5, m4, more, str3;
  do {
    more = s5.window_size - s5.lookahead - s5.strstart;
    if (s5.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
      utils$1.arraySet(s5.window, s5.window, _w_size, _w_size, 0);
      s5.match_start -= _w_size;
      s5.strstart -= _w_size;
      s5.block_start -= _w_size;
      n5 = s5.hash_size;
      p5 = n5;
      do {
        m4 = s5.head[--p5];
        s5.head[p5] = m4 >= _w_size ? m4 - _w_size : 0;
      } while (--n5);
      n5 = _w_size;
      p5 = n5;
      do {
        m4 = s5.prev[--p5];
        s5.prev[p5] = m4 >= _w_size ? m4 - _w_size : 0;
      } while (--n5);
      more += _w_size;
    }
    if (s5.strm.avail_in === 0) {
      break;
    }
    n5 = read_buf(s5.strm, s5.window, s5.strstart + s5.lookahead, more);
    s5.lookahead += n5;
    if (s5.lookahead + s5.insert >= MIN_MATCH$1) {
      str3 = s5.strstart - s5.insert;
      s5.ins_h = s5.window[str3];
      s5.ins_h = (s5.ins_h << s5.hash_shift ^ s5.window[str3 + 1]) & s5.hash_mask;
      while (s5.insert) {
        s5.ins_h = (s5.ins_h << s5.hash_shift ^ s5.window[str3 + MIN_MATCH$1 - 1]) & s5.hash_mask;
        s5.prev[str3 & s5.w_mask] = s5.head[s5.ins_h];
        s5.head[s5.ins_h] = str3;
        str3++;
        s5.insert--;
        if (s5.lookahead + s5.insert < MIN_MATCH$1) {
          break;
        }
      }
    }
  } while (s5.lookahead < MIN_LOOKAHEAD && s5.strm.avail_in !== 0);
}
function deflate_stored(s5, flush) {
  var max_block_size = 65535;
  if (max_block_size > s5.pending_buf_size - 5) {
    max_block_size = s5.pending_buf_size - 5;
  }
  for (; ; ) {
    if (s5.lookahead <= 1) {
      fill_window(s5);
      if (s5.lookahead === 0 && flush === Z_NO_FLUSH) {
        return BS_NEED_MORE;
      }
      if (s5.lookahead === 0) {
        break;
      }
    }
    s5.strstart += s5.lookahead;
    s5.lookahead = 0;
    var max_start = s5.block_start + max_block_size;
    if (s5.strstart === 0 || s5.strstart >= max_start) {
      s5.lookahead = s5.strstart - max_start;
      s5.strstart = max_start;
      flush_block_only(s5, false);
      if (s5.strm.avail_out === 0) {
        return BS_NEED_MORE;
      }
    }
    if (s5.strstart - s5.block_start >= s5.w_size - MIN_LOOKAHEAD) {
      flush_block_only(s5, false);
      if (s5.strm.avail_out === 0) {
        return BS_NEED_MORE;
      }
    }
  }
  s5.insert = 0;
  if (flush === Z_FINISH) {
    flush_block_only(s5, true);
    if (s5.strm.avail_out === 0) {
      return BS_FINISH_STARTED;
    }
    return BS_FINISH_DONE;
  }
  if (s5.strstart > s5.block_start) {
    flush_block_only(s5, false);
    if (s5.strm.avail_out === 0) {
      return BS_NEED_MORE;
    }
  }
  return BS_NEED_MORE;
}
function deflate_fast(s5, flush) {
  var hash_head;
  var bflush;
  for (; ; ) {
    if (s5.lookahead < MIN_LOOKAHEAD) {
      fill_window(s5);
      if (s5.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
        return BS_NEED_MORE;
      }
      if (s5.lookahead === 0) {
        break;
      }
    }
    hash_head = 0;
    if (s5.lookahead >= MIN_MATCH$1) {
      s5.ins_h = (s5.ins_h << s5.hash_shift ^ s5.window[s5.strstart + MIN_MATCH$1 - 1]) & s5.hash_mask;
      hash_head = s5.prev[s5.strstart & s5.w_mask] = s5.head[s5.ins_h];
      s5.head[s5.ins_h] = s5.strstart;
    }
    if (hash_head !== 0 && s5.strstart - hash_head <= s5.w_size - MIN_LOOKAHEAD) {
      s5.match_length = longest_match(s5, hash_head);
    }
    if (s5.match_length >= MIN_MATCH$1) {
      bflush = trees._tr_tally(s5, s5.strstart - s5.match_start, s5.match_length - MIN_MATCH$1);
      s5.lookahead -= s5.match_length;
      if (s5.match_length <= s5.max_lazy_match && s5.lookahead >= MIN_MATCH$1) {
        s5.match_length--;
        do {
          s5.strstart++;
          s5.ins_h = (s5.ins_h << s5.hash_shift ^ s5.window[s5.strstart + MIN_MATCH$1 - 1]) & s5.hash_mask;
          hash_head = s5.prev[s5.strstart & s5.w_mask] = s5.head[s5.ins_h];
          s5.head[s5.ins_h] = s5.strstart;
        } while (--s5.match_length !== 0);
        s5.strstart++;
      } else {
        s5.strstart += s5.match_length;
        s5.match_length = 0;
        s5.ins_h = s5.window[s5.strstart];
        s5.ins_h = (s5.ins_h << s5.hash_shift ^ s5.window[s5.strstart + 1]) & s5.hash_mask;
      }
    } else {
      bflush = trees._tr_tally(s5, 0, s5.window[s5.strstart]);
      s5.lookahead--;
      s5.strstart++;
    }
    if (bflush) {
      flush_block_only(s5, false);
      if (s5.strm.avail_out === 0) {
        return BS_NEED_MORE;
      }
    }
  }
  s5.insert = s5.strstart < MIN_MATCH$1 - 1 ? s5.strstart : MIN_MATCH$1 - 1;
  if (flush === Z_FINISH) {
    flush_block_only(s5, true);
    if (s5.strm.avail_out === 0) {
      return BS_FINISH_STARTED;
    }
    return BS_FINISH_DONE;
  }
  if (s5.last_lit) {
    flush_block_only(s5, false);
    if (s5.strm.avail_out === 0) {
      return BS_NEED_MORE;
    }
  }
  return BS_BLOCK_DONE;
}
function deflate_slow(s5, flush) {
  var hash_head;
  var bflush;
  var max_insert;
  for (; ; ) {
    if (s5.lookahead < MIN_LOOKAHEAD) {
      fill_window(s5);
      if (s5.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
        return BS_NEED_MORE;
      }
      if (s5.lookahead === 0) {
        break;
      }
    }
    hash_head = 0;
    if (s5.lookahead >= MIN_MATCH$1) {
      s5.ins_h = (s5.ins_h << s5.hash_shift ^ s5.window[s5.strstart + MIN_MATCH$1 - 1]) & s5.hash_mask;
      hash_head = s5.prev[s5.strstart & s5.w_mask] = s5.head[s5.ins_h];
      s5.head[s5.ins_h] = s5.strstart;
    }
    s5.prev_length = s5.match_length;
    s5.prev_match = s5.match_start;
    s5.match_length = MIN_MATCH$1 - 1;
    if (hash_head !== 0 && s5.prev_length < s5.max_lazy_match && s5.strstart - hash_head <= s5.w_size - MIN_LOOKAHEAD) {
      s5.match_length = longest_match(s5, hash_head);
      if (s5.match_length <= 5 && (s5.strategy === Z_FILTERED || s5.match_length === MIN_MATCH$1 && s5.strstart - s5.match_start > 4096)) {
        s5.match_length = MIN_MATCH$1 - 1;
      }
    }
    if (s5.prev_length >= MIN_MATCH$1 && s5.match_length <= s5.prev_length) {
      max_insert = s5.strstart + s5.lookahead - MIN_MATCH$1;
      bflush = trees._tr_tally(s5, s5.strstart - 1 - s5.prev_match, s5.prev_length - MIN_MATCH$1);
      s5.lookahead -= s5.prev_length - 1;
      s5.prev_length -= 2;
      do {
        if (++s5.strstart <= max_insert) {
          s5.ins_h = (s5.ins_h << s5.hash_shift ^ s5.window[s5.strstart + MIN_MATCH$1 - 1]) & s5.hash_mask;
          hash_head = s5.prev[s5.strstart & s5.w_mask] = s5.head[s5.ins_h];
          s5.head[s5.ins_h] = s5.strstart;
        }
      } while (--s5.prev_length !== 0);
      s5.match_available = 0;
      s5.match_length = MIN_MATCH$1 - 1;
      s5.strstart++;
      if (bflush) {
        flush_block_only(s5, false);
        if (s5.strm.avail_out === 0) {
          return BS_NEED_MORE;
        }
      }
    } else if (s5.match_available) {
      bflush = trees._tr_tally(s5, 0, s5.window[s5.strstart - 1]);
      if (bflush) {
        flush_block_only(s5, false);
      }
      s5.strstart++;
      s5.lookahead--;
      if (s5.strm.avail_out === 0) {
        return BS_NEED_MORE;
      }
    } else {
      s5.match_available = 1;
      s5.strstart++;
      s5.lookahead--;
    }
  }
  if (s5.match_available) {
    bflush = trees._tr_tally(s5, 0, s5.window[s5.strstart - 1]);
    s5.match_available = 0;
  }
  s5.insert = s5.strstart < MIN_MATCH$1 - 1 ? s5.strstart : MIN_MATCH$1 - 1;
  if (flush === Z_FINISH) {
    flush_block_only(s5, true);
    if (s5.strm.avail_out === 0) {
      return BS_FINISH_STARTED;
    }
    return BS_FINISH_DONE;
  }
  if (s5.last_lit) {
    flush_block_only(s5, false);
    if (s5.strm.avail_out === 0) {
      return BS_NEED_MORE;
    }
  }
  return BS_BLOCK_DONE;
}
function deflate_rle(s5, flush) {
  var bflush;
  var prev;
  var scan, strend;
  var _win = s5.window;
  for (; ; ) {
    if (s5.lookahead <= MAX_MATCH$1) {
      fill_window(s5);
      if (s5.lookahead <= MAX_MATCH$1 && flush === Z_NO_FLUSH) {
        return BS_NEED_MORE;
      }
      if (s5.lookahead === 0) {
        break;
      }
    }
    s5.match_length = 0;
    if (s5.lookahead >= MIN_MATCH$1 && s5.strstart > 0) {
      scan = s5.strstart - 1;
      prev = _win[scan];
      if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
        strend = s5.strstart + MAX_MATCH$1;
        do {
        } while (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && scan < strend);
        s5.match_length = MAX_MATCH$1 - (strend - scan);
        if (s5.match_length > s5.lookahead) {
          s5.match_length = s5.lookahead;
        }
      }
    }
    if (s5.match_length >= MIN_MATCH$1) {
      bflush = trees._tr_tally(s5, 1, s5.match_length - MIN_MATCH$1);
      s5.lookahead -= s5.match_length;
      s5.strstart += s5.match_length;
      s5.match_length = 0;
    } else {
      bflush = trees._tr_tally(s5, 0, s5.window[s5.strstart]);
      s5.lookahead--;
      s5.strstart++;
    }
    if (bflush) {
      flush_block_only(s5, false);
      if (s5.strm.avail_out === 0) {
        return BS_NEED_MORE;
      }
    }
  }
  s5.insert = 0;
  if (flush === Z_FINISH) {
    flush_block_only(s5, true);
    if (s5.strm.avail_out === 0) {
      return BS_FINISH_STARTED;
    }
    return BS_FINISH_DONE;
  }
  if (s5.last_lit) {
    flush_block_only(s5, false);
    if (s5.strm.avail_out === 0) {
      return BS_NEED_MORE;
    }
  }
  return BS_BLOCK_DONE;
}
function deflate_huff(s5, flush) {
  var bflush;
  for (; ; ) {
    if (s5.lookahead === 0) {
      fill_window(s5);
      if (s5.lookahead === 0) {
        if (flush === Z_NO_FLUSH) {
          return BS_NEED_MORE;
        }
        break;
      }
    }
    s5.match_length = 0;
    bflush = trees._tr_tally(s5, 0, s5.window[s5.strstart]);
    s5.lookahead--;
    s5.strstart++;
    if (bflush) {
      flush_block_only(s5, false);
      if (s5.strm.avail_out === 0) {
        return BS_NEED_MORE;
      }
    }
  }
  s5.insert = 0;
  if (flush === Z_FINISH) {
    flush_block_only(s5, true);
    if (s5.strm.avail_out === 0) {
      return BS_FINISH_STARTED;
    }
    return BS_FINISH_DONE;
  }
  if (s5.last_lit) {
    flush_block_only(s5, false);
    if (s5.strm.avail_out === 0) {
      return BS_NEED_MORE;
    }
  }
  return BS_BLOCK_DONE;
}
function Config(good_length, max_lazy, nice_length, max_chain, func) {
  this.good_length = good_length;
  this.max_lazy = max_lazy;
  this.nice_length = nice_length;
  this.max_chain = max_chain;
  this.func = func;
}
function lm_init(s5) {
  s5.window_size = 2 * s5.w_size;
  zero$1(s5.head);
  s5.max_lazy_match = configuration_table[s5.level].max_lazy;
  s5.good_match = configuration_table[s5.level].good_length;
  s5.nice_match = configuration_table[s5.level].nice_length;
  s5.max_chain_length = configuration_table[s5.level].max_chain;
  s5.strstart = 0;
  s5.block_start = 0;
  s5.lookahead = 0;
  s5.insert = 0;
  s5.match_length = s5.prev_length = MIN_MATCH$1 - 1;
  s5.match_available = 0;
  s5.ins_h = 0;
}
function DeflateState() {
  this.strm = null;
  this.status = 0;
  this.pending_buf = null;
  this.pending_buf_size = 0;
  this.pending_out = 0;
  this.pending = 0;
  this.wrap = 0;
  this.gzhead = null;
  this.gzindex = 0;
  this.method = Z_DEFLATED;
  this.last_flush = -1;
  this.w_size = 0;
  this.w_bits = 0;
  this.w_mask = 0;
  this.window = null;
  this.window_size = 0;
  this.prev = null;
  this.head = null;
  this.ins_h = 0;
  this.hash_size = 0;
  this.hash_bits = 0;
  this.hash_mask = 0;
  this.hash_shift = 0;
  this.block_start = 0;
  this.match_length = 0;
  this.prev_match = 0;
  this.match_available = 0;
  this.strstart = 0;
  this.match_start = 0;
  this.lookahead = 0;
  this.prev_length = 0;
  this.max_chain_length = 0;
  this.max_lazy_match = 0;
  this.level = 0;
  this.strategy = 0;
  this.good_match = 0;
  this.nice_match = 0;
  this.dyn_ltree = new utils$1.Buf16(HEAP_SIZE$1 * 2);
  this.dyn_dtree = new utils$1.Buf16((2 * D_CODES$1 + 1) * 2);
  this.bl_tree = new utils$1.Buf16((2 * BL_CODES$1 + 1) * 2);
  zero$1(this.dyn_ltree);
  zero$1(this.dyn_dtree);
  zero$1(this.bl_tree);
  this.l_desc = null;
  this.d_desc = null;
  this.bl_desc = null;
  this.bl_count = new utils$1.Buf16(MAX_BITS$1 + 1);
  this.heap = new utils$1.Buf16(2 * L_CODES$1 + 1);
  zero$1(this.heap);
  this.heap_len = 0;
  this.heap_max = 0;
  this.depth = new utils$1.Buf16(2 * L_CODES$1 + 1);
  zero$1(this.depth);
  this.l_buf = 0;
  this.lit_bufsize = 0;
  this.last_lit = 0;
  this.d_buf = 0;
  this.opt_len = 0;
  this.static_len = 0;
  this.matches = 0;
  this.insert = 0;
  this.bi_buf = 0;
  this.bi_valid = 0;
}
function deflateResetKeep(strm) {
  var s5;
  if (!strm || !strm.state) {
    return err(strm, Z_STREAM_ERROR);
  }
  strm.total_in = strm.total_out = 0;
  strm.data_type = Z_UNKNOWN$1;
  s5 = strm.state;
  s5.pending = 0;
  s5.pending_out = 0;
  if (s5.wrap < 0) {
    s5.wrap = -s5.wrap;
  }
  s5.status = s5.wrap ? INIT_STATE : BUSY_STATE;
  strm.adler = s5.wrap === 2 ? 0 : 1;
  s5.last_flush = Z_NO_FLUSH;
  trees._tr_init(s5);
  return Z_OK;
}
function deflateReset(strm) {
  var ret = deflateResetKeep(strm);
  if (ret === Z_OK) {
    lm_init(strm.state);
  }
  return ret;
}
function deflateSetHeader(strm, head) {
  if (!strm || !strm.state) {
    return Z_STREAM_ERROR;
  }
  if (strm.state.wrap !== 2) {
    return Z_STREAM_ERROR;
  }
  strm.state.gzhead = head;
  return Z_OK;
}
function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  if (!strm) {
    return Z_STREAM_ERROR;
  }
  var wrap = 1;
  if (level === Z_DEFAULT_COMPRESSION) {
    level = 6;
  }
  if (windowBits < 0) {
    wrap = 0;
    windowBits = -windowBits;
  } else if (windowBits > 15) {
    wrap = 2;
    windowBits -= 16;
  }
  if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED$1) {
    return err(strm, Z_STREAM_ERROR);
  }
  if (windowBits === 8) {
    windowBits = 9;
  }
  var s5 = new DeflateState();
  strm.state = s5;
  s5.strm = strm;
  s5.wrap = wrap;
  s5.gzhead = null;
  s5.w_bits = windowBits;
  s5.w_size = 1 << s5.w_bits;
  s5.w_mask = s5.w_size - 1;
  s5.hash_bits = memLevel + 7;
  s5.hash_size = 1 << s5.hash_bits;
  s5.hash_mask = s5.hash_size - 1;
  s5.hash_shift = ~~((s5.hash_bits + MIN_MATCH$1 - 1) / MIN_MATCH$1);
  s5.window = new utils$1.Buf8(s5.w_size * 2);
  s5.head = new utils$1.Buf16(s5.hash_size);
  s5.prev = new utils$1.Buf16(s5.w_size);
  s5.lit_bufsize = 1 << memLevel + 6;
  s5.pending_buf_size = s5.lit_bufsize * 4;
  s5.pending_buf = new utils$1.Buf8(s5.pending_buf_size);
  s5.d_buf = 1 * s5.lit_bufsize;
  s5.l_buf = (1 + 2) * s5.lit_bufsize;
  s5.level = level;
  s5.strategy = strategy;
  s5.method = method;
  return deflateReset(strm);
}
function deflateInit(strm, level) {
  return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
}
function deflate(strm, flush) {
  var old_flush, s5;
  var beg, val;
  if (!strm || !strm.state || flush > Z_BLOCK || flush < 0) {
    return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  }
  s5 = strm.state;
  if (!strm.output || !strm.input && strm.avail_in !== 0 || s5.status === FINISH_STATE && flush !== Z_FINISH) {
    return err(strm, strm.avail_out === 0 ? Z_BUF_ERROR : Z_STREAM_ERROR);
  }
  s5.strm = strm;
  old_flush = s5.last_flush;
  s5.last_flush = flush;
  if (s5.status === INIT_STATE) {
    if (s5.wrap === 2) {
      strm.adler = 0;
      put_byte(s5, 31);
      put_byte(s5, 139);
      put_byte(s5, 8);
      if (!s5.gzhead) {
        put_byte(s5, 0);
        put_byte(s5, 0);
        put_byte(s5, 0);
        put_byte(s5, 0);
        put_byte(s5, 0);
        put_byte(s5, s5.level === 9 ? 2 : s5.strategy >= Z_HUFFMAN_ONLY || s5.level < 2 ? 4 : 0);
        put_byte(s5, OS_CODE);
        s5.status = BUSY_STATE;
      } else {
        put_byte(s5, (s5.gzhead.text ? 1 : 0) + (s5.gzhead.hcrc ? 2 : 0) + (!s5.gzhead.extra ? 0 : 4) + (!s5.gzhead.name ? 0 : 8) + (!s5.gzhead.comment ? 0 : 16));
        put_byte(s5, s5.gzhead.time & 255);
        put_byte(s5, s5.gzhead.time >> 8 & 255);
        put_byte(s5, s5.gzhead.time >> 16 & 255);
        put_byte(s5, s5.gzhead.time >> 24 & 255);
        put_byte(s5, s5.level === 9 ? 2 : s5.strategy >= Z_HUFFMAN_ONLY || s5.level < 2 ? 4 : 0);
        put_byte(s5, s5.gzhead.os & 255);
        if (s5.gzhead.extra && s5.gzhead.extra.length) {
          put_byte(s5, s5.gzhead.extra.length & 255);
          put_byte(s5, s5.gzhead.extra.length >> 8 & 255);
        }
        if (s5.gzhead.hcrc) {
          strm.adler = crc322(strm.adler, s5.pending_buf, s5.pending, 0);
        }
        s5.gzindex = 0;
        s5.status = EXTRA_STATE;
      }
    } else {
      var header = Z_DEFLATED + (s5.w_bits - 8 << 4) << 8;
      var level_flags = -1;
      if (s5.strategy >= Z_HUFFMAN_ONLY || s5.level < 2) {
        level_flags = 0;
      } else if (s5.level < 6) {
        level_flags = 1;
      } else if (s5.level === 6) {
        level_flags = 2;
      } else {
        level_flags = 3;
      }
      header |= level_flags << 6;
      if (s5.strstart !== 0) {
        header |= PRESET_DICT;
      }
      header += 31 - header % 31;
      s5.status = BUSY_STATE;
      putShortMSB(s5, header);
      if (s5.strstart !== 0) {
        putShortMSB(s5, strm.adler >>> 16);
        putShortMSB(s5, strm.adler & 65535);
      }
      strm.adler = 1;
    }
  }
  if (s5.status === EXTRA_STATE) {
    if (s5.gzhead.extra) {
      beg = s5.pending;
      while (s5.gzindex < (s5.gzhead.extra.length & 65535)) {
        if (s5.pending === s5.pending_buf_size) {
          if (s5.gzhead.hcrc && s5.pending > beg) {
            strm.adler = crc322(strm.adler, s5.pending_buf, s5.pending - beg, beg);
          }
          flush_pending(strm);
          beg = s5.pending;
          if (s5.pending === s5.pending_buf_size) {
            break;
          }
        }
        put_byte(s5, s5.gzhead.extra[s5.gzindex] & 255);
        s5.gzindex++;
      }
      if (s5.gzhead.hcrc && s5.pending > beg) {
        strm.adler = crc322(strm.adler, s5.pending_buf, s5.pending - beg, beg);
      }
      if (s5.gzindex === s5.gzhead.extra.length) {
        s5.gzindex = 0;
        s5.status = NAME_STATE;
      }
    } else {
      s5.status = NAME_STATE;
    }
  }
  if (s5.status === NAME_STATE) {
    if (s5.gzhead.name) {
      beg = s5.pending;
      do {
        if (s5.pending === s5.pending_buf_size) {
          if (s5.gzhead.hcrc && s5.pending > beg) {
            strm.adler = crc322(strm.adler, s5.pending_buf, s5.pending - beg, beg);
          }
          flush_pending(strm);
          beg = s5.pending;
          if (s5.pending === s5.pending_buf_size) {
            val = 1;
            break;
          }
        }
        if (s5.gzindex < s5.gzhead.name.length) {
          val = s5.gzhead.name.charCodeAt(s5.gzindex++) & 255;
        } else {
          val = 0;
        }
        put_byte(s5, val);
      } while (val !== 0);
      if (s5.gzhead.hcrc && s5.pending > beg) {
        strm.adler = crc322(strm.adler, s5.pending_buf, s5.pending - beg, beg);
      }
      if (val === 0) {
        s5.gzindex = 0;
        s5.status = COMMENT_STATE;
      }
    } else {
      s5.status = COMMENT_STATE;
    }
  }
  if (s5.status === COMMENT_STATE) {
    if (s5.gzhead.comment) {
      beg = s5.pending;
      do {
        if (s5.pending === s5.pending_buf_size) {
          if (s5.gzhead.hcrc && s5.pending > beg) {
            strm.adler = crc322(strm.adler, s5.pending_buf, s5.pending - beg, beg);
          }
          flush_pending(strm);
          beg = s5.pending;
          if (s5.pending === s5.pending_buf_size) {
            val = 1;
            break;
          }
        }
        if (s5.gzindex < s5.gzhead.comment.length) {
          val = s5.gzhead.comment.charCodeAt(s5.gzindex++) & 255;
        } else {
          val = 0;
        }
        put_byte(s5, val);
      } while (val !== 0);
      if (s5.gzhead.hcrc && s5.pending > beg) {
        strm.adler = crc322(strm.adler, s5.pending_buf, s5.pending - beg, beg);
      }
      if (val === 0) {
        s5.status = HCRC_STATE;
      }
    } else {
      s5.status = HCRC_STATE;
    }
  }
  if (s5.status === HCRC_STATE) {
    if (s5.gzhead.hcrc) {
      if (s5.pending + 2 > s5.pending_buf_size) {
        flush_pending(strm);
      }
      if (s5.pending + 2 <= s5.pending_buf_size) {
        put_byte(s5, strm.adler & 255);
        put_byte(s5, strm.adler >> 8 & 255);
        strm.adler = 0;
        s5.status = BUSY_STATE;
      }
    } else {
      s5.status = BUSY_STATE;
    }
  }
  if (s5.pending !== 0) {
    flush_pending(strm);
    if (strm.avail_out === 0) {
      s5.last_flush = -1;
      return Z_OK;
    }
  } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && flush !== Z_FINISH) {
    return err(strm, Z_BUF_ERROR);
  }
  if (s5.status === FINISH_STATE && strm.avail_in !== 0) {
    return err(strm, Z_BUF_ERROR);
  }
  if (strm.avail_in !== 0 || s5.lookahead !== 0 || flush !== Z_NO_FLUSH && s5.status !== FINISH_STATE) {
    var bstate = s5.strategy === Z_HUFFMAN_ONLY ? deflate_huff(s5, flush) : s5.strategy === Z_RLE ? deflate_rle(s5, flush) : configuration_table[s5.level].func(s5, flush);
    if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
      s5.status = FINISH_STATE;
    }
    if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
      if (strm.avail_out === 0) {
        s5.last_flush = -1;
      }
      return Z_OK;
    }
    if (bstate === BS_BLOCK_DONE) {
      if (flush === Z_PARTIAL_FLUSH) {
        trees._tr_align(s5);
      } else if (flush !== Z_BLOCK) {
        trees._tr_stored_block(s5, 0, 0, false);
        if (flush === Z_FULL_FLUSH) {
          zero$1(s5.head);
          if (s5.lookahead === 0) {
            s5.strstart = 0;
            s5.block_start = 0;
            s5.insert = 0;
          }
        }
      }
      flush_pending(strm);
      if (strm.avail_out === 0) {
        s5.last_flush = -1;
        return Z_OK;
      }
    }
  }
  if (flush !== Z_FINISH) {
    return Z_OK;
  }
  if (s5.wrap <= 0) {
    return Z_STREAM_END;
  }
  if (s5.wrap === 2) {
    put_byte(s5, strm.adler & 255);
    put_byte(s5, strm.adler >> 8 & 255);
    put_byte(s5, strm.adler >> 16 & 255);
    put_byte(s5, strm.adler >> 24 & 255);
    put_byte(s5, strm.total_in & 255);
    put_byte(s5, strm.total_in >> 8 & 255);
    put_byte(s5, strm.total_in >> 16 & 255);
    put_byte(s5, strm.total_in >> 24 & 255);
  } else {
    putShortMSB(s5, strm.adler >>> 16);
    putShortMSB(s5, strm.adler & 65535);
  }
  flush_pending(strm);
  if (s5.wrap > 0) {
    s5.wrap = -s5.wrap;
  }
  return s5.pending !== 0 ? Z_OK : Z_STREAM_END;
}
function deflateEnd(strm) {
  var status;
  if (!strm || !strm.state) {
    return Z_STREAM_ERROR;
  }
  status = strm.state.status;
  if (status !== INIT_STATE && status !== EXTRA_STATE && status !== NAME_STATE && status !== COMMENT_STATE && status !== HCRC_STATE && status !== BUSY_STATE && status !== FINISH_STATE) {
    return err(strm, Z_STREAM_ERROR);
  }
  strm.state = null;
  return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
}
function deflateSetDictionary(strm, dictionary) {
  var dictLength = dictionary.length;
  var s5;
  var str3, n5;
  var wrap;
  var avail;
  var next;
  var input;
  var tmpDict;
  if (!strm || !strm.state) {
    return Z_STREAM_ERROR;
  }
  s5 = strm.state;
  wrap = s5.wrap;
  if (wrap === 2 || wrap === 1 && s5.status !== INIT_STATE || s5.lookahead) {
    return Z_STREAM_ERROR;
  }
  if (wrap === 1) {
    strm.adler = adler322(strm.adler, dictionary, dictLength, 0);
  }
  s5.wrap = 0;
  if (dictLength >= s5.w_size) {
    if (wrap === 0) {
      zero$1(s5.head);
      s5.strstart = 0;
      s5.block_start = 0;
      s5.insert = 0;
    }
    tmpDict = new utils$1.Buf8(s5.w_size);
    utils$1.arraySet(tmpDict, dictionary, dictLength - s5.w_size, s5.w_size, 0);
    dictionary = tmpDict;
    dictLength = s5.w_size;
  }
  avail = strm.avail_in;
  next = strm.next_in;
  input = strm.input;
  strm.avail_in = dictLength;
  strm.next_in = 0;
  strm.input = dictionary;
  fill_window(s5);
  while (s5.lookahead >= MIN_MATCH$1) {
    str3 = s5.strstart;
    n5 = s5.lookahead - (MIN_MATCH$1 - 1);
    do {
      s5.ins_h = (s5.ins_h << s5.hash_shift ^ s5.window[str3 + MIN_MATCH$1 - 1]) & s5.hash_mask;
      s5.prev[str3 & s5.w_mask] = s5.head[s5.ins_h];
      s5.head[s5.ins_h] = str3;
      str3++;
    } while (--n5);
    s5.strstart = str3;
    s5.lookahead = MIN_MATCH$1 - 1;
    fill_window(s5);
  }
  s5.strstart += s5.lookahead;
  s5.block_start = s5.strstart;
  s5.insert = s5.lookahead;
  s5.lookahead = 0;
  s5.match_length = s5.prev_length = MIN_MATCH$1 - 1;
  s5.match_available = 0;
  strm.next_in = next;
  strm.input = input;
  strm.avail_in = avail;
  s5.wrap = wrap;
  return Z_OK;
}
var exports13, utils, Z_FIXED, Z_BINARY, Z_TEXT, Z_UNKNOWN, STORED_BLOCK, STATIC_TREES, DYN_TREES, MIN_MATCH, MAX_MATCH, LENGTH_CODES, LITERALS, L_CODES, D_CODES, BL_CODES, HEAP_SIZE, MAX_BITS, Buf_size, MAX_BL_BITS, END_BLOCK, REP_3_6, REPZ_3_10, REPZ_11_138, extra_lbits, extra_dbits, extra_blbits, bl_order, DIST_CODE_LEN, static_ltree, static_dtree, _dist_code, _length_code, base_length, base_dist, static_l_desc, static_d_desc, static_bl_desc, static_init_done, exports$16, utils$1, trees, adler322, crc322, msg, Z_NO_FLUSH, Z_PARTIAL_FLUSH, Z_FULL_FLUSH, Z_FINISH, Z_BLOCK, Z_OK, Z_STREAM_END, Z_STREAM_ERROR, Z_DATA_ERROR, Z_BUF_ERROR, Z_DEFAULT_COMPRESSION, Z_FILTERED, Z_HUFFMAN_ONLY, Z_RLE, Z_FIXED$1, Z_DEFAULT_STRATEGY, Z_UNKNOWN$1, Z_DEFLATED, MAX_MEM_LEVEL, MAX_WBITS, DEF_MEM_LEVEL, LENGTH_CODES$1, LITERALS$1, L_CODES$1, D_CODES$1, BL_CODES$1, HEAP_SIZE$1, MAX_BITS$1, MIN_MATCH$1, MAX_MATCH$1, MIN_LOOKAHEAD, PRESET_DICT, INIT_STATE, EXTRA_STATE, NAME_STATE, COMMENT_STATE, HCRC_STATE, BUSY_STATE, FINISH_STATE, BS_NEED_MORE, BS_BLOCK_DONE, BS_FINISH_STARTED, BS_FINISH_DONE, OS_CODE, configuration_table, deflateInfo, _deflateInit, _deflateInit2, _deflateReset, _deflateResetKeep, _deflateSetHeader, _deflate, _deflateEnd, _deflateSetDictionary, deflate_default;
var init_deflate = __esm({
  "https://dev.jspm.io/npm:pako@1.0.11/lib/zlib/deflate.js!cjs"() {
    init_common_cjs();
    init_adler32_cjs();
    init_crc32_cjs();
    init_messages_cjs();
    exports13 = {};
    utils = common_cjs_default;
    Z_FIXED = 4;
    Z_BINARY = 0;
    Z_TEXT = 1;
    Z_UNKNOWN = 2;
    STORED_BLOCK = 0;
    STATIC_TREES = 1;
    DYN_TREES = 2;
    MIN_MATCH = 3;
    MAX_MATCH = 258;
    LENGTH_CODES = 29;
    LITERALS = 256;
    L_CODES = LITERALS + 1 + LENGTH_CODES;
    D_CODES = 30;
    BL_CODES = 19;
    HEAP_SIZE = 2 * L_CODES + 1;
    MAX_BITS = 15;
    Buf_size = 16;
    MAX_BL_BITS = 7;
    END_BLOCK = 256;
    REP_3_6 = 16;
    REPZ_3_10 = 17;
    REPZ_11_138 = 18;
    extra_lbits = /* extra bits for each length code */
    [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0];
    extra_dbits = /* extra bits for each distance code */
    [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13];
    extra_blbits = /* extra bits for each bit length code */
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7];
    bl_order = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
    DIST_CODE_LEN = 512;
    static_ltree = new Array((L_CODES + 2) * 2);
    zero(static_ltree);
    static_dtree = new Array(D_CODES * 2);
    zero(static_dtree);
    _dist_code = new Array(DIST_CODE_LEN);
    zero(_dist_code);
    _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);
    zero(_length_code);
    base_length = new Array(LENGTH_CODES);
    zero(base_length);
    base_dist = new Array(D_CODES);
    zero(base_dist);
    static_init_done = false;
    exports13._tr_init = _tr_init;
    exports13._tr_stored_block = _tr_stored_block;
    exports13._tr_flush_block = _tr_flush_block;
    exports13._tr_tally = _tr_tally;
    exports13._tr_align = _tr_align;
    exports$16 = {};
    utils$1 = common_cjs_default;
    trees = exports13;
    adler322 = adler32_cjs_default;
    crc322 = crc32_cjs_default;
    msg = messages_cjs_default;
    Z_NO_FLUSH = 0;
    Z_PARTIAL_FLUSH = 1;
    Z_FULL_FLUSH = 3;
    Z_FINISH = 4;
    Z_BLOCK = 5;
    Z_OK = 0;
    Z_STREAM_END = 1;
    Z_STREAM_ERROR = -2;
    Z_DATA_ERROR = -3;
    Z_BUF_ERROR = -5;
    Z_DEFAULT_COMPRESSION = -1;
    Z_FILTERED = 1;
    Z_HUFFMAN_ONLY = 2;
    Z_RLE = 3;
    Z_FIXED$1 = 4;
    Z_DEFAULT_STRATEGY = 0;
    Z_UNKNOWN$1 = 2;
    Z_DEFLATED = 8;
    MAX_MEM_LEVEL = 9;
    MAX_WBITS = 15;
    DEF_MEM_LEVEL = 8;
    LENGTH_CODES$1 = 29;
    LITERALS$1 = 256;
    L_CODES$1 = LITERALS$1 + 1 + LENGTH_CODES$1;
    D_CODES$1 = 30;
    BL_CODES$1 = 19;
    HEAP_SIZE$1 = 2 * L_CODES$1 + 1;
    MAX_BITS$1 = 15;
    MIN_MATCH$1 = 3;
    MAX_MATCH$1 = 258;
    MIN_LOOKAHEAD = MAX_MATCH$1 + MIN_MATCH$1 + 1;
    PRESET_DICT = 32;
    INIT_STATE = 42;
    EXTRA_STATE = 69;
    NAME_STATE = 73;
    COMMENT_STATE = 91;
    HCRC_STATE = 103;
    BUSY_STATE = 113;
    FINISH_STATE = 666;
    BS_NEED_MORE = 1;
    BS_BLOCK_DONE = 2;
    BS_FINISH_STARTED = 3;
    BS_FINISH_DONE = 4;
    OS_CODE = 3;
    configuration_table = [
      /*      good lazy nice chain */
      new Config(0, 0, 0, 0, deflate_stored),
      /* 0 store only */
      new Config(4, 4, 8, 4, deflate_fast),
      /* 1 max speed, no lazy matches */
      new Config(4, 5, 16, 8, deflate_fast),
      /* 2 */
      new Config(4, 6, 32, 32, deflate_fast),
      /* 3 */
      new Config(4, 4, 16, 16, deflate_slow),
      /* 4 lazy matches */
      new Config(8, 16, 32, 32, deflate_slow),
      /* 5 */
      new Config(8, 16, 128, 128, deflate_slow),
      /* 6 */
      new Config(8, 32, 128, 256, deflate_slow),
      /* 7 */
      new Config(32, 128, 258, 1024, deflate_slow),
      /* 8 */
      new Config(32, 258, 258, 4096, deflate_slow)
      /* 9 max compression */
    ];
    exports$16.deflateInit = deflateInit;
    exports$16.deflateInit2 = deflateInit2;
    exports$16.deflateReset = deflateReset;
    exports$16.deflateResetKeep = deflateResetKeep;
    exports$16.deflateSetHeader = deflateSetHeader;
    exports$16.deflate = deflate;
    exports$16.deflateEnd = deflateEnd;
    exports$16.deflateSetDictionary = deflateSetDictionary;
    exports$16.deflateInfo = "pako deflate (from Nodeca project)";
    deflateInfo = exports$16.deflateInfo;
    _deflateInit = exports$16.deflateInit;
    _deflateInit2 = exports$16.deflateInit2;
    _deflateReset = exports$16.deflateReset;
    _deflateResetKeep = exports$16.deflateResetKeep;
    _deflateSetHeader = exports$16.deflateSetHeader;
    _deflate = exports$16.deflate;
    _deflateEnd = exports$16.deflateEnd;
    _deflateSetDictionary = exports$16.deflateSetDictionary;
    deflate_default = exports$16;
  }
});

// https://dev.jspm.io/npm:pako@1.0.11/lib/utils/strings!cjs
function buf2binstring(buf, len) {
  if (len < 65534) {
    if (buf.subarray && STR_APPLY_UIA_OK || !buf.subarray && STR_APPLY_OK) {
      return String.fromCharCode.apply(null, utils2.shrinkBuf(buf, len));
    }
  }
  var result2 = "";
  for (var i6 = 0; i6 < len; i6++) {
    result2 += String.fromCharCode(buf[i6]);
  }
  return result2;
}
var exports14, utils2, STR_APPLY_OK, STR_APPLY_UIA_OK, _utf8len, q2, string2buf, binstring2buf, buf2string, utf8border, _buf2binstring, strings_cjs_default;
var init_strings_cjs = __esm({
  "https://dev.jspm.io/npm:pako@1.0.11/lib/utils/strings!cjs"() {
    init_common_cjs();
    exports14 = {};
    utils2 = common_cjs_default;
    STR_APPLY_OK = true;
    STR_APPLY_UIA_OK = true;
    try {
      String.fromCharCode.apply(null, [0]);
    } catch (__) {
      STR_APPLY_OK = false;
    }
    try {
      String.fromCharCode.apply(null, new Uint8Array(1));
    } catch (__) {
      STR_APPLY_UIA_OK = false;
    }
    _utf8len = new utils2.Buf8(256);
    for (q2 = 0; q2 < 256; q2++) {
      _utf8len[q2] = q2 >= 252 ? 6 : q2 >= 248 ? 5 : q2 >= 240 ? 4 : q2 >= 224 ? 3 : q2 >= 192 ? 2 : 1;
    }
    _utf8len[254] = _utf8len[254] = 1;
    exports14.string2buf = function(str3) {
      var buf, c6, c22, m_pos, i6, str_len = str3.length, buf_len = 0;
      for (m_pos = 0; m_pos < str_len; m_pos++) {
        c6 = str3.charCodeAt(m_pos);
        if ((c6 & 64512) === 55296 && m_pos + 1 < str_len) {
          c22 = str3.charCodeAt(m_pos + 1);
          if ((c22 & 64512) === 56320) {
            c6 = 65536 + (c6 - 55296 << 10) + (c22 - 56320);
            m_pos++;
          }
        }
        buf_len += c6 < 128 ? 1 : c6 < 2048 ? 2 : c6 < 65536 ? 3 : 4;
      }
      buf = new utils2.Buf8(buf_len);
      for (i6 = 0, m_pos = 0; i6 < buf_len; m_pos++) {
        c6 = str3.charCodeAt(m_pos);
        if ((c6 & 64512) === 55296 && m_pos + 1 < str_len) {
          c22 = str3.charCodeAt(m_pos + 1);
          if ((c22 & 64512) === 56320) {
            c6 = 65536 + (c6 - 55296 << 10) + (c22 - 56320);
            m_pos++;
          }
        }
        if (c6 < 128) {
          buf[i6++] = c6;
        } else if (c6 < 2048) {
          buf[i6++] = 192 | c6 >>> 6;
          buf[i6++] = 128 | c6 & 63;
        } else if (c6 < 65536) {
          buf[i6++] = 224 | c6 >>> 12;
          buf[i6++] = 128 | c6 >>> 6 & 63;
          buf[i6++] = 128 | c6 & 63;
        } else {
          buf[i6++] = 240 | c6 >>> 18;
          buf[i6++] = 128 | c6 >>> 12 & 63;
          buf[i6++] = 128 | c6 >>> 6 & 63;
          buf[i6++] = 128 | c6 & 63;
        }
      }
      return buf;
    };
    exports14.buf2binstring = function(buf) {
      return buf2binstring(buf, buf.length);
    };
    exports14.binstring2buf = function(str3) {
      var buf = new utils2.Buf8(str3.length);
      for (var i6 = 0, len = buf.length; i6 < len; i6++) {
        buf[i6] = str3.charCodeAt(i6);
      }
      return buf;
    };
    exports14.buf2string = function(buf, max) {
      var i6, out, c6, c_len;
      var len = max || buf.length;
      var utf16buf = new Array(len * 2);
      for (out = 0, i6 = 0; i6 < len; ) {
        c6 = buf[i6++];
        if (c6 < 128) {
          utf16buf[out++] = c6;
          continue;
        }
        c_len = _utf8len[c6];
        if (c_len > 4) {
          utf16buf[out++] = 65533;
          i6 += c_len - 1;
          continue;
        }
        c6 &= c_len === 2 ? 31 : c_len === 3 ? 15 : 7;
        while (c_len > 1 && i6 < len) {
          c6 = c6 << 6 | buf[i6++] & 63;
          c_len--;
        }
        if (c_len > 1) {
          utf16buf[out++] = 65533;
          continue;
        }
        if (c6 < 65536) {
          utf16buf[out++] = c6;
        } else {
          c6 -= 65536;
          utf16buf[out++] = 55296 | c6 >> 10 & 1023;
          utf16buf[out++] = 56320 | c6 & 1023;
        }
      }
      return buf2binstring(utf16buf, out);
    };
    exports14.utf8border = function(buf, max) {
      var pos;
      max = max || buf.length;
      if (max > buf.length) {
        max = buf.length;
      }
      pos = max - 1;
      while (pos >= 0 && (buf[pos] & 192) === 128) {
        pos--;
      }
      if (pos < 0) {
        return max;
      }
      if (pos === 0) {
        return max;
      }
      return pos + _utf8len[buf[pos]] > max ? pos : max;
    };
    string2buf = exports14.string2buf;
    binstring2buf = exports14.binstring2buf;
    buf2string = exports14.buf2string;
    utf8border = exports14.utf8border;
    _buf2binstring = exports14.buf2binstring;
    strings_cjs_default = exports14;
  }
});

// https://dev.jspm.io/npm:pako@1.0.11/lib/zlib/zstream!cjs
function ZStream() {
  this.input = null;
  this.next_in = 0;
  this.avail_in = 0;
  this.total_in = 0;
  this.output = null;
  this.next_out = 0;
  this.avail_out = 0;
  this.total_out = 0;
  this.msg = "";
  this.state = null;
  this.data_type = 2;
  this.adler = 0;
}
var exports15, _zstream, zstream_cjs_default;
var init_zstream_cjs = __esm({
  "https://dev.jspm.io/npm:pako@1.0.11/lib/zlib/zstream!cjs"() {
    exports15 = {};
    exports15 = ZStream;
    _zstream = exports15;
    zstream_cjs_default = _zstream;
  }
});

// https://dev.jspm.io/npm:pako@1.0.11/lib/deflate!cjs
function Deflate(options) {
  if (!(this instanceof Deflate)) return new Deflate(options);
  this.options = utils3.assign({
    level: Z_DEFAULT_COMPRESSION2,
    method: Z_DEFLATED2,
    chunkSize: 16384,
    windowBits: 15,
    memLevel: 8,
    strategy: Z_DEFAULT_STRATEGY2,
    to: ""
  }, options || {});
  var opt = this.options;
  if (opt.raw && opt.windowBits > 0) {
    opt.windowBits = -opt.windowBits;
  } else if (opt.gzip && opt.windowBits > 0 && opt.windowBits < 16) {
    opt.windowBits += 16;
  }
  this.err = 0;
  this.msg = "";
  this.ended = false;
  this.chunks = [];
  this.strm = new ZStream2();
  this.strm.avail_out = 0;
  var status = zlib_deflate.deflateInit2(this.strm, opt.level, opt.method, opt.windowBits, opt.memLevel, opt.strategy);
  if (status !== Z_OK2) {
    throw new Error(msg2[status]);
  }
  if (opt.header) {
    zlib_deflate.deflateSetHeader(this.strm, opt.header);
  }
  if (opt.dictionary) {
    var dict;
    if (typeof opt.dictionary === "string") {
      dict = strings.string2buf(opt.dictionary);
    } else if (toString4.call(opt.dictionary) === "[object ArrayBuffer]") {
      dict = new Uint8Array(opt.dictionary);
    } else {
      dict = opt.dictionary;
    }
    status = zlib_deflate.deflateSetDictionary(this.strm, dict);
    if (status !== Z_OK2) {
      throw new Error(msg2[status]);
    }
    this._dict_set = true;
  }
}
function deflate2(input, options) {
  var deflator = new Deflate(options);
  deflator.push(input, true);
  if (deflator.err) {
    throw deflator.msg || msg2[deflator.err];
  }
  return deflator.result;
}
function deflateRaw(input, options) {
  options = options || {};
  options.raw = true;
  return deflate2(input, options);
}
function gzip(input, options) {
  options = options || {};
  options.gzip = true;
  return deflate2(input, options);
}
var exports16, zlib_deflate, utils3, strings, msg2, ZStream2, toString4, Z_NO_FLUSH2, Z_FINISH2, Z_OK2, Z_STREAM_END2, Z_SYNC_FLUSH, Z_DEFAULT_COMPRESSION2, Z_DEFAULT_STRATEGY2, Z_DEFLATED2, _Deflate, _deflate2, _deflateRaw, _gzip, deflate_cjs_default;
var init_deflate_cjs = __esm({
  "https://dev.jspm.io/npm:pako@1.0.11/lib/deflate!cjs"() {
    init_common_cjs();
    init_deflate();
    init_adler32_cjs();
    init_crc32_cjs();
    init_messages_cjs();
    init_strings_cjs();
    init_zstream_cjs();
    exports16 = {};
    zlib_deflate = deflate_default;
    utils3 = common_cjs_default;
    strings = strings_cjs_default;
    msg2 = messages_cjs_default;
    ZStream2 = zstream_cjs_default;
    toString4 = Object.prototype.toString;
    Z_NO_FLUSH2 = 0;
    Z_FINISH2 = 4;
    Z_OK2 = 0;
    Z_STREAM_END2 = 1;
    Z_SYNC_FLUSH = 2;
    Z_DEFAULT_COMPRESSION2 = -1;
    Z_DEFAULT_STRATEGY2 = 0;
    Z_DEFLATED2 = 8;
    Deflate.prototype.push = function(data3, mode) {
      var strm = this.strm;
      var chunkSize = this.options.chunkSize;
      var status, _mode;
      if (this.ended) {
        return false;
      }
      _mode = mode === ~~mode ? mode : mode === true ? Z_FINISH2 : Z_NO_FLUSH2;
      if (typeof data3 === "string") {
        strm.input = strings.string2buf(data3);
      } else if (toString4.call(data3) === "[object ArrayBuffer]") {
        strm.input = new Uint8Array(data3);
      } else {
        strm.input = data3;
      }
      strm.next_in = 0;
      strm.avail_in = strm.input.length;
      do {
        if (strm.avail_out === 0) {
          strm.output = new utils3.Buf8(chunkSize);
          strm.next_out = 0;
          strm.avail_out = chunkSize;
        }
        status = zlib_deflate.deflate(strm, _mode);
        if (status !== Z_STREAM_END2 && status !== Z_OK2) {
          this.onEnd(status);
          this.ended = true;
          return false;
        }
        if (strm.avail_out === 0 || strm.avail_in === 0 && (_mode === Z_FINISH2 || _mode === Z_SYNC_FLUSH)) {
          if (this.options.to === "string") {
            this.onData(strings.buf2binstring(utils3.shrinkBuf(strm.output, strm.next_out)));
          } else {
            this.onData(utils3.shrinkBuf(strm.output, strm.next_out));
          }
        }
      } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END2);
      if (_mode === Z_FINISH2) {
        status = zlib_deflate.deflateEnd(this.strm);
        this.onEnd(status);
        this.ended = true;
        return status === Z_OK2;
      }
      if (_mode === Z_SYNC_FLUSH) {
        this.onEnd(Z_OK2);
        strm.avail_out = 0;
        return true;
      }
      return true;
    };
    Deflate.prototype.onData = function(chunk) {
      this.chunks.push(chunk);
    };
    Deflate.prototype.onEnd = function(status) {
      if (status === Z_OK2) {
        if (this.options.to === "string") {
          this.result = this.chunks.join("");
        } else {
          this.result = utils3.flattenChunks(this.chunks);
        }
      }
      this.chunks = [];
      this.err = status;
      this.msg = this.strm.msg;
    };
    exports16.Deflate = Deflate;
    exports16.deflate = deflate2;
    exports16.deflateRaw = deflateRaw;
    exports16.gzip = gzip;
    _Deflate = exports16.Deflate;
    _deflate2 = exports16.deflate;
    _deflateRaw = exports16.deflateRaw;
    _gzip = exports16.gzip;
    deflate_cjs_default = exports16;
  }
});

// https://dev.jspm.io/npm:pako@1.0.11/lib/zlib/inflate.js!cjs
function zswap32(q2) {
  return (q2 >>> 24 & 255) + (q2 >>> 8 & 65280) + ((q2 & 65280) << 8) + ((q2 & 255) << 24);
}
function InflateState() {
  this.mode = 0;
  this.last = false;
  this.wrap = 0;
  this.havedict = false;
  this.flags = 0;
  this.dmax = 0;
  this.check = 0;
  this.total = 0;
  this.head = null;
  this.wbits = 0;
  this.wsize = 0;
  this.whave = 0;
  this.wnext = 0;
  this.window = null;
  this.hold = 0;
  this.bits = 0;
  this.length = 0;
  this.offset = 0;
  this.extra = 0;
  this.lencode = null;
  this.distcode = null;
  this.lenbits = 0;
  this.distbits = 0;
  this.ncode = 0;
  this.nlen = 0;
  this.ndist = 0;
  this.have = 0;
  this.next = null;
  this.lens = new utils$12.Buf16(320);
  this.work = new utils$12.Buf16(288);
  this.lendyn = null;
  this.distdyn = null;
  this.sane = 0;
  this.back = 0;
  this.was = 0;
}
function inflateResetKeep(strm) {
  var state2;
  if (!strm || !strm.state) {
    return Z_STREAM_ERROR2;
  }
  state2 = strm.state;
  strm.total_in = strm.total_out = state2.total = 0;
  strm.msg = "";
  if (state2.wrap) {
    strm.adler = state2.wrap & 1;
  }
  state2.mode = HEAD;
  state2.last = 0;
  state2.havedict = 0;
  state2.dmax = 32768;
  state2.head = null;
  state2.hold = 0;
  state2.bits = 0;
  state2.lencode = state2.lendyn = new utils$12.Buf32(ENOUGH_LENS$1);
  state2.distcode = state2.distdyn = new utils$12.Buf32(ENOUGH_DISTS$1);
  state2.sane = 1;
  state2.back = -1;
  return Z_OK3;
}
function inflateReset(strm) {
  var state2;
  if (!strm || !strm.state) {
    return Z_STREAM_ERROR2;
  }
  state2 = strm.state;
  state2.wsize = 0;
  state2.whave = 0;
  state2.wnext = 0;
  return inflateResetKeep(strm);
}
function inflateReset2(strm, windowBits) {
  var wrap;
  var state2;
  if (!strm || !strm.state) {
    return Z_STREAM_ERROR2;
  }
  state2 = strm.state;
  if (windowBits < 0) {
    wrap = 0;
    windowBits = -windowBits;
  } else {
    wrap = (windowBits >> 4) + 1;
    if (windowBits < 48) {
      windowBits &= 15;
    }
  }
  if (windowBits && (windowBits < 8 || windowBits > 15)) {
    return Z_STREAM_ERROR2;
  }
  if (state2.window !== null && state2.wbits !== windowBits) {
    state2.window = null;
  }
  state2.wrap = wrap;
  state2.wbits = windowBits;
  return inflateReset(strm);
}
function inflateInit2(strm, windowBits) {
  var ret;
  var state2;
  if (!strm) {
    return Z_STREAM_ERROR2;
  }
  state2 = new InflateState();
  strm.state = state2;
  state2.window = null;
  ret = inflateReset2(strm, windowBits);
  if (ret !== Z_OK3) {
    strm.state = null;
  }
  return ret;
}
function inflateInit(strm) {
  return inflateInit2(strm, DEF_WBITS);
}
function fixedtables(state2) {
  if (virgin) {
    var sym;
    lenfix = new utils$12.Buf32(512);
    distfix = new utils$12.Buf32(32);
    sym = 0;
    while (sym < 144) {
      state2.lens[sym++] = 8;
    }
    while (sym < 256) {
      state2.lens[sym++] = 9;
    }
    while (sym < 280) {
      state2.lens[sym++] = 7;
    }
    while (sym < 288) {
      state2.lens[sym++] = 8;
    }
    inflate_table2(LENS$1, state2.lens, 0, 288, lenfix, 0, state2.work, {
      bits: 9
    });
    sym = 0;
    while (sym < 32) {
      state2.lens[sym++] = 5;
    }
    inflate_table2(DISTS$1, state2.lens, 0, 32, distfix, 0, state2.work, {
      bits: 5
    });
    virgin = false;
  }
  state2.lencode = lenfix;
  state2.lenbits = 9;
  state2.distcode = distfix;
  state2.distbits = 5;
}
function updatewindow(strm, src2, end, copy6) {
  var dist;
  var state2 = strm.state;
  if (state2.window === null) {
    state2.wsize = 1 << state2.wbits;
    state2.wnext = 0;
    state2.whave = 0;
    state2.window = new utils$12.Buf8(state2.wsize);
  }
  if (copy6 >= state2.wsize) {
    utils$12.arraySet(state2.window, src2, end - state2.wsize, state2.wsize, 0);
    state2.wnext = 0;
    state2.whave = state2.wsize;
  } else {
    dist = state2.wsize - state2.wnext;
    if (dist > copy6) {
      dist = copy6;
    }
    utils$12.arraySet(state2.window, src2, end - copy6, dist, state2.wnext);
    copy6 -= dist;
    if (copy6) {
      utils$12.arraySet(state2.window, src2, end - copy6, copy6, 0);
      state2.wnext = copy6;
      state2.whave = state2.wsize;
    } else {
      state2.wnext += dist;
      if (state2.wnext === state2.wsize) {
        state2.wnext = 0;
      }
      if (state2.whave < state2.wsize) {
        state2.whave += dist;
      }
    }
  }
  return 0;
}
function inflate(strm, flush) {
  var state2;
  var input, output;
  var next;
  var put;
  var have, left;
  var hold;
  var bits;
  var _in, _out;
  var copy6;
  var from;
  var from_source;
  var here = 0;
  var here_bits, here_op, here_val;
  var last_bits, last_op, last_val;
  var len;
  var ret;
  var hbuf = new utils$12.Buf8(4);
  var opts;
  var n5;
  var order = (
    /* permutation of code lengths */
    [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]
  );
  if (!strm || !strm.state || !strm.output || !strm.input && strm.avail_in !== 0) {
    return Z_STREAM_ERROR2;
  }
  state2 = strm.state;
  if (state2.mode === TYPE$1) {
    state2.mode = TYPEDO;
  }
  put = strm.next_out;
  output = strm.output;
  left = strm.avail_out;
  next = strm.next_in;
  input = strm.input;
  have = strm.avail_in;
  hold = state2.hold;
  bits = state2.bits;
  _in = have;
  _out = left;
  ret = Z_OK3;
  inf_leave:
    for (; ; ) {
      switch (state2.mode) {
        case HEAD:
          if (state2.wrap === 0) {
            state2.mode = TYPEDO;
            break;
          }
          while (bits < 16) {
            if (have === 0) {
              break inf_leave;
            }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          if (state2.wrap & 2 && hold === 35615) {
            state2.check = 0;
            hbuf[0] = hold & 255;
            hbuf[1] = hold >>> 8 & 255;
            state2.check = crc323(state2.check, hbuf, 2, 0);
            hold = 0;
            bits = 0;
            state2.mode = FLAGS;
            break;
          }
          state2.flags = 0;
          if (state2.head) {
            state2.head.done = false;
          }
          if (!(state2.wrap & 1) || /* check if zlib header allowed */
          (((hold & 255) << /*BITS(8)*/
          8) + (hold >> 8)) % 31) {
            strm.msg = "incorrect header check";
            state2.mode = BAD$1;
            break;
          }
          if ((hold & 15) !== /*BITS(4)*/
          Z_DEFLATED3) {
            strm.msg = "unknown compression method";
            state2.mode = BAD$1;
            break;
          }
          hold >>>= 4;
          bits -= 4;
          len = (hold & 15) + /*BITS(4)*/
          8;
          if (state2.wbits === 0) {
            state2.wbits = len;
          } else if (len > state2.wbits) {
            strm.msg = "invalid window size";
            state2.mode = BAD$1;
            break;
          }
          state2.dmax = 1 << len;
          strm.adler = state2.check = 1;
          state2.mode = hold & 512 ? DICTID : TYPE$1;
          hold = 0;
          bits = 0;
          break;
        case FLAGS:
          while (bits < 16) {
            if (have === 0) {
              break inf_leave;
            }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          state2.flags = hold;
          if ((state2.flags & 255) !== Z_DEFLATED3) {
            strm.msg = "unknown compression method";
            state2.mode = BAD$1;
            break;
          }
          if (state2.flags & 57344) {
            strm.msg = "unknown header flags set";
            state2.mode = BAD$1;
            break;
          }
          if (state2.head) {
            state2.head.text = hold >> 8 & 1;
          }
          if (state2.flags & 512) {
            hbuf[0] = hold & 255;
            hbuf[1] = hold >>> 8 & 255;
            state2.check = crc323(state2.check, hbuf, 2, 0);
          }
          hold = 0;
          bits = 0;
          state2.mode = TIME;
        /* falls through */
        case TIME:
          while (bits < 32) {
            if (have === 0) {
              break inf_leave;
            }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          if (state2.head) {
            state2.head.time = hold;
          }
          if (state2.flags & 512) {
            hbuf[0] = hold & 255;
            hbuf[1] = hold >>> 8 & 255;
            hbuf[2] = hold >>> 16 & 255;
            hbuf[3] = hold >>> 24 & 255;
            state2.check = crc323(state2.check, hbuf, 4, 0);
          }
          hold = 0;
          bits = 0;
          state2.mode = OS;
        /* falls through */
        case OS:
          while (bits < 16) {
            if (have === 0) {
              break inf_leave;
            }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          if (state2.head) {
            state2.head.xflags = hold & 255;
            state2.head.os = hold >> 8;
          }
          if (state2.flags & 512) {
            hbuf[0] = hold & 255;
            hbuf[1] = hold >>> 8 & 255;
            state2.check = crc323(state2.check, hbuf, 2, 0);
          }
          hold = 0;
          bits = 0;
          state2.mode = EXLEN;
        /* falls through */
        case EXLEN:
          if (state2.flags & 1024) {
            while (bits < 16) {
              if (have === 0) {
                break inf_leave;
              }
              have--;
              hold += input[next++] << bits;
              bits += 8;
            }
            state2.length = hold;
            if (state2.head) {
              state2.head.extra_len = hold;
            }
            if (state2.flags & 512) {
              hbuf[0] = hold & 255;
              hbuf[1] = hold >>> 8 & 255;
              state2.check = crc323(state2.check, hbuf, 2, 0);
            }
            hold = 0;
            bits = 0;
          } else if (state2.head) {
            state2.head.extra = null;
          }
          state2.mode = EXTRA;
        /* falls through */
        case EXTRA:
          if (state2.flags & 1024) {
            copy6 = state2.length;
            if (copy6 > have) {
              copy6 = have;
            }
            if (copy6) {
              if (state2.head) {
                len = state2.head.extra_len - state2.length;
                if (!state2.head.extra) {
                  state2.head.extra = new Array(state2.head.extra_len);
                }
                utils$12.arraySet(
                  state2.head.extra,
                  input,
                  next,
                  // extra field is limited to 65536 bytes
                  // - no need for additional size check
                  copy6,
                  /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
                  len
                );
              }
              if (state2.flags & 512) {
                state2.check = crc323(state2.check, input, copy6, next);
              }
              have -= copy6;
              next += copy6;
              state2.length -= copy6;
            }
            if (state2.length) {
              break inf_leave;
            }
          }
          state2.length = 0;
          state2.mode = NAME;
        /* falls through */
        case NAME:
          if (state2.flags & 2048) {
            if (have === 0) {
              break inf_leave;
            }
            copy6 = 0;
            do {
              len = input[next + copy6++];
              if (state2.head && len && state2.length < 65536) {
                state2.head.name += String.fromCharCode(len);
              }
            } while (len && copy6 < have);
            if (state2.flags & 512) {
              state2.check = crc323(state2.check, input, copy6, next);
            }
            have -= copy6;
            next += copy6;
            if (len) {
              break inf_leave;
            }
          } else if (state2.head) {
            state2.head.name = null;
          }
          state2.length = 0;
          state2.mode = COMMENT;
        /* falls through */
        case COMMENT:
          if (state2.flags & 4096) {
            if (have === 0) {
              break inf_leave;
            }
            copy6 = 0;
            do {
              len = input[next + copy6++];
              if (state2.head && len && state2.length < 65536) {
                state2.head.comment += String.fromCharCode(len);
              }
            } while (len && copy6 < have);
            if (state2.flags & 512) {
              state2.check = crc323(state2.check, input, copy6, next);
            }
            have -= copy6;
            next += copy6;
            if (len) {
              break inf_leave;
            }
          } else if (state2.head) {
            state2.head.comment = null;
          }
          state2.mode = HCRC;
        /* falls through */
        case HCRC:
          if (state2.flags & 512) {
            while (bits < 16) {
              if (have === 0) {
                break inf_leave;
              }
              have--;
              hold += input[next++] << bits;
              bits += 8;
            }
            if (hold !== (state2.check & 65535)) {
              strm.msg = "header crc mismatch";
              state2.mode = BAD$1;
              break;
            }
            hold = 0;
            bits = 0;
          }
          if (state2.head) {
            state2.head.hcrc = state2.flags >> 9 & 1;
            state2.head.done = true;
          }
          strm.adler = state2.check = 0;
          state2.mode = TYPE$1;
          break;
        case DICTID:
          while (bits < 32) {
            if (have === 0) {
              break inf_leave;
            }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          strm.adler = state2.check = zswap32(hold);
          hold = 0;
          bits = 0;
          state2.mode = DICT;
        /* falls through */
        case DICT:
          if (state2.havedict === 0) {
            strm.next_out = put;
            strm.avail_out = left;
            strm.next_in = next;
            strm.avail_in = have;
            state2.hold = hold;
            state2.bits = bits;
            return Z_NEED_DICT;
          }
          strm.adler = state2.check = 1;
          state2.mode = TYPE$1;
        /* falls through */
        case TYPE$1:
          if (flush === Z_BLOCK2 || flush === Z_TREES) {
            break inf_leave;
          }
        /* falls through */
        case TYPEDO:
          if (state2.last) {
            hold >>>= bits & 7;
            bits -= bits & 7;
            state2.mode = CHECK;
            break;
          }
          while (bits < 3) {
            if (have === 0) {
              break inf_leave;
            }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          state2.last = hold & 1;
          hold >>>= 1;
          bits -= 1;
          switch (hold & 3) {
            /*BITS(2)*/
            case 0:
              state2.mode = STORED;
              break;
            case 1:
              fixedtables(state2);
              state2.mode = LEN_;
              if (flush === Z_TREES) {
                hold >>>= 2;
                bits -= 2;
                break inf_leave;
              }
              break;
            case 2:
              state2.mode = TABLE;
              break;
            case 3:
              strm.msg = "invalid block type";
              state2.mode = BAD$1;
          }
          hold >>>= 2;
          bits -= 2;
          break;
        case STORED:
          hold >>>= bits & 7;
          bits -= bits & 7;
          while (bits < 32) {
            if (have === 0) {
              break inf_leave;
            }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          if ((hold & 65535) !== (hold >>> 16 ^ 65535)) {
            strm.msg = "invalid stored block lengths";
            state2.mode = BAD$1;
            break;
          }
          state2.length = hold & 65535;
          hold = 0;
          bits = 0;
          state2.mode = COPY_;
          if (flush === Z_TREES) {
            break inf_leave;
          }
        /* falls through */
        case COPY_:
          state2.mode = COPY;
        /* falls through */
        case COPY:
          copy6 = state2.length;
          if (copy6) {
            if (copy6 > have) {
              copy6 = have;
            }
            if (copy6 > left) {
              copy6 = left;
            }
            if (copy6 === 0) {
              break inf_leave;
            }
            utils$12.arraySet(output, input, next, copy6, put);
            have -= copy6;
            next += copy6;
            left -= copy6;
            put += copy6;
            state2.length -= copy6;
            break;
          }
          state2.mode = TYPE$1;
          break;
        case TABLE:
          while (bits < 14) {
            if (have === 0) {
              break inf_leave;
            }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          state2.nlen = (hold & 31) + /*BITS(5)*/
          257;
          hold >>>= 5;
          bits -= 5;
          state2.ndist = (hold & 31) + /*BITS(5)*/
          1;
          hold >>>= 5;
          bits -= 5;
          state2.ncode = (hold & 15) + /*BITS(4)*/
          4;
          hold >>>= 4;
          bits -= 4;
          if (state2.nlen > 286 || state2.ndist > 30) {
            strm.msg = "too many length or distance symbols";
            state2.mode = BAD$1;
            break;
          }
          state2.have = 0;
          state2.mode = LENLENS;
        /* falls through */
        case LENLENS:
          while (state2.have < state2.ncode) {
            while (bits < 3) {
              if (have === 0) {
                break inf_leave;
              }
              have--;
              hold += input[next++] << bits;
              bits += 8;
            }
            state2.lens[order[state2.have++]] = hold & 7;
            hold >>>= 3;
            bits -= 3;
          }
          while (state2.have < 19) {
            state2.lens[order[state2.have++]] = 0;
          }
          state2.lencode = state2.lendyn;
          state2.lenbits = 7;
          opts = {
            bits: state2.lenbits
          };
          ret = inflate_table2(CODES$1, state2.lens, 0, 19, state2.lencode, 0, state2.work, opts);
          state2.lenbits = opts.bits;
          if (ret) {
            strm.msg = "invalid code lengths set";
            state2.mode = BAD$1;
            break;
          }
          state2.have = 0;
          state2.mode = CODELENS;
        /* falls through */
        case CODELENS:
          while (state2.have < state2.nlen + state2.ndist) {
            for (; ; ) {
              here = state2.lencode[hold & (1 << state2.lenbits) - 1];
              here_bits = here >>> 24;
              here_op = here >>> 16 & 255;
              here_val = here & 65535;
              if (here_bits <= bits) {
                break;
              }
              if (have === 0) {
                break inf_leave;
              }
              have--;
              hold += input[next++] << bits;
              bits += 8;
            }
            if (here_val < 16) {
              hold >>>= here_bits;
              bits -= here_bits;
              state2.lens[state2.have++] = here_val;
            } else {
              if (here_val === 16) {
                n5 = here_bits + 2;
                while (bits < n5) {
                  if (have === 0) {
                    break inf_leave;
                  }
                  have--;
                  hold += input[next++] << bits;
                  bits += 8;
                }
                hold >>>= here_bits;
                bits -= here_bits;
                if (state2.have === 0) {
                  strm.msg = "invalid bit length repeat";
                  state2.mode = BAD$1;
                  break;
                }
                len = state2.lens[state2.have - 1];
                copy6 = 3 + (hold & 3);
                hold >>>= 2;
                bits -= 2;
              } else if (here_val === 17) {
                n5 = here_bits + 3;
                while (bits < n5) {
                  if (have === 0) {
                    break inf_leave;
                  }
                  have--;
                  hold += input[next++] << bits;
                  bits += 8;
                }
                hold >>>= here_bits;
                bits -= here_bits;
                len = 0;
                copy6 = 3 + (hold & 7);
                hold >>>= 3;
                bits -= 3;
              } else {
                n5 = here_bits + 7;
                while (bits < n5) {
                  if (have === 0) {
                    break inf_leave;
                  }
                  have--;
                  hold += input[next++] << bits;
                  bits += 8;
                }
                hold >>>= here_bits;
                bits -= here_bits;
                len = 0;
                copy6 = 11 + (hold & 127);
                hold >>>= 7;
                bits -= 7;
              }
              if (state2.have + copy6 > state2.nlen + state2.ndist) {
                strm.msg = "invalid bit length repeat";
                state2.mode = BAD$1;
                break;
              }
              while (copy6--) {
                state2.lens[state2.have++] = len;
              }
            }
          }
          if (state2.mode === BAD$1) {
            break;
          }
          if (state2.lens[256] === 0) {
            strm.msg = "invalid code -- missing end-of-block";
            state2.mode = BAD$1;
            break;
          }
          state2.lenbits = 9;
          opts = {
            bits: state2.lenbits
          };
          ret = inflate_table2(LENS$1, state2.lens, 0, state2.nlen, state2.lencode, 0, state2.work, opts);
          state2.lenbits = opts.bits;
          if (ret) {
            strm.msg = "invalid literal/lengths set";
            state2.mode = BAD$1;
            break;
          }
          state2.distbits = 6;
          state2.distcode = state2.distdyn;
          opts = {
            bits: state2.distbits
          };
          ret = inflate_table2(DISTS$1, state2.lens, state2.nlen, state2.ndist, state2.distcode, 0, state2.work, opts);
          state2.distbits = opts.bits;
          if (ret) {
            strm.msg = "invalid distances set";
            state2.mode = BAD$1;
            break;
          }
          state2.mode = LEN_;
          if (flush === Z_TREES) {
            break inf_leave;
          }
        /* falls through */
        case LEN_:
          state2.mode = LEN;
        /* falls through */
        case LEN:
          if (have >= 6 && left >= 258) {
            strm.next_out = put;
            strm.avail_out = left;
            strm.next_in = next;
            strm.avail_in = have;
            state2.hold = hold;
            state2.bits = bits;
            inflate_fast2(strm, _out);
            put = strm.next_out;
            output = strm.output;
            left = strm.avail_out;
            next = strm.next_in;
            input = strm.input;
            have = strm.avail_in;
            hold = state2.hold;
            bits = state2.bits;
            if (state2.mode === TYPE$1) {
              state2.back = -1;
            }
            break;
          }
          state2.back = 0;
          for (; ; ) {
            here = state2.lencode[hold & (1 << state2.lenbits) - 1];
            here_bits = here >>> 24;
            here_op = here >>> 16 & 255;
            here_val = here & 65535;
            if (here_bits <= bits) {
              break;
            }
            if (have === 0) {
              break inf_leave;
            }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          if (here_op && (here_op & 240) === 0) {
            last_bits = here_bits;
            last_op = here_op;
            last_val = here_val;
            for (; ; ) {
              here = state2.lencode[last_val + ((hold & (1 << last_bits + last_op) - 1) >> /*BITS(last.bits + last.op)*/
              last_bits)];
              here_bits = here >>> 24;
              here_op = here >>> 16 & 255;
              here_val = here & 65535;
              if (last_bits + here_bits <= bits) {
                break;
              }
              if (have === 0) {
                break inf_leave;
              }
              have--;
              hold += input[next++] << bits;
              bits += 8;
            }
            hold >>>= last_bits;
            bits -= last_bits;
            state2.back += last_bits;
          }
          hold >>>= here_bits;
          bits -= here_bits;
          state2.back += here_bits;
          state2.length = here_val;
          if (here_op === 0) {
            state2.mode = LIT;
            break;
          }
          if (here_op & 32) {
            state2.back = -1;
            state2.mode = TYPE$1;
            break;
          }
          if (here_op & 64) {
            strm.msg = "invalid literal/length code";
            state2.mode = BAD$1;
            break;
          }
          state2.extra = here_op & 15;
          state2.mode = LENEXT;
        /* falls through */
        case LENEXT:
          if (state2.extra) {
            n5 = state2.extra;
            while (bits < n5) {
              if (have === 0) {
                break inf_leave;
              }
              have--;
              hold += input[next++] << bits;
              bits += 8;
            }
            state2.length += hold & (1 << state2.extra) - 1;
            hold >>>= state2.extra;
            bits -= state2.extra;
            state2.back += state2.extra;
          }
          state2.was = state2.length;
          state2.mode = DIST;
        /* falls through */
        case DIST:
          for (; ; ) {
            here = state2.distcode[hold & (1 << state2.distbits) - 1];
            here_bits = here >>> 24;
            here_op = here >>> 16 & 255;
            here_val = here & 65535;
            if (here_bits <= bits) {
              break;
            }
            if (have === 0) {
              break inf_leave;
            }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          if ((here_op & 240) === 0) {
            last_bits = here_bits;
            last_op = here_op;
            last_val = here_val;
            for (; ; ) {
              here = state2.distcode[last_val + ((hold & (1 << last_bits + last_op) - 1) >> /*BITS(last.bits + last.op)*/
              last_bits)];
              here_bits = here >>> 24;
              here_op = here >>> 16 & 255;
              here_val = here & 65535;
              if (last_bits + here_bits <= bits) {
                break;
              }
              if (have === 0) {
                break inf_leave;
              }
              have--;
              hold += input[next++] << bits;
              bits += 8;
            }
            hold >>>= last_bits;
            bits -= last_bits;
            state2.back += last_bits;
          }
          hold >>>= here_bits;
          bits -= here_bits;
          state2.back += here_bits;
          if (here_op & 64) {
            strm.msg = "invalid distance code";
            state2.mode = BAD$1;
            break;
          }
          state2.offset = here_val;
          state2.extra = here_op & 15;
          state2.mode = DISTEXT;
        /* falls through */
        case DISTEXT:
          if (state2.extra) {
            n5 = state2.extra;
            while (bits < n5) {
              if (have === 0) {
                break inf_leave;
              }
              have--;
              hold += input[next++] << bits;
              bits += 8;
            }
            state2.offset += hold & (1 << state2.extra) - 1;
            hold >>>= state2.extra;
            bits -= state2.extra;
            state2.back += state2.extra;
          }
          if (state2.offset > state2.dmax) {
            strm.msg = "invalid distance too far back";
            state2.mode = BAD$1;
            break;
          }
          state2.mode = MATCH;
        /* falls through */
        case MATCH:
          if (left === 0) {
            break inf_leave;
          }
          copy6 = _out - left;
          if (state2.offset > copy6) {
            copy6 = state2.offset - copy6;
            if (copy6 > state2.whave) {
              if (state2.sane) {
                strm.msg = "invalid distance too far back";
                state2.mode = BAD$1;
                break;
              }
            }
            if (copy6 > state2.wnext) {
              copy6 -= state2.wnext;
              from = state2.wsize - copy6;
            } else {
              from = state2.wnext - copy6;
            }
            if (copy6 > state2.length) {
              copy6 = state2.length;
            }
            from_source = state2.window;
          } else {
            from_source = output;
            from = put - state2.offset;
            copy6 = state2.length;
          }
          if (copy6 > left) {
            copy6 = left;
          }
          left -= copy6;
          state2.length -= copy6;
          do {
            output[put++] = from_source[from++];
          } while (--copy6);
          if (state2.length === 0) {
            state2.mode = LEN;
          }
          break;
        case LIT:
          if (left === 0) {
            break inf_leave;
          }
          output[put++] = state2.length;
          left--;
          state2.mode = LEN;
          break;
        case CHECK:
          if (state2.wrap) {
            while (bits < 32) {
              if (have === 0) {
                break inf_leave;
              }
              have--;
              hold |= input[next++] << bits;
              bits += 8;
            }
            _out -= left;
            strm.total_out += _out;
            state2.total += _out;
            if (_out) {
              strm.adler = state2.check = /*UPDATE(state.check, put - _out, _out);*/
              state2.flags ? crc323(state2.check, output, _out, put - _out) : adler323(state2.check, output, _out, put - _out);
            }
            _out = left;
            if ((state2.flags ? hold : zswap32(hold)) !== state2.check) {
              strm.msg = "incorrect data check";
              state2.mode = BAD$1;
              break;
            }
            hold = 0;
            bits = 0;
          }
          state2.mode = LENGTH;
        /* falls through */
        case LENGTH:
          if (state2.wrap && state2.flags) {
            while (bits < 32) {
              if (have === 0) {
                break inf_leave;
              }
              have--;
              hold += input[next++] << bits;
              bits += 8;
            }
            if (hold !== (state2.total & 4294967295)) {
              strm.msg = "incorrect length check";
              state2.mode = BAD$1;
              break;
            }
            hold = 0;
            bits = 0;
          }
          state2.mode = DONE;
        /* falls through */
        case DONE:
          ret = Z_STREAM_END3;
          break inf_leave;
        case BAD$1:
          ret = Z_DATA_ERROR2;
          break inf_leave;
        case MEM:
          return Z_MEM_ERROR;
        case SYNC:
        /* falls through */
        default:
          return Z_STREAM_ERROR2;
      }
    }
  strm.next_out = put;
  strm.avail_out = left;
  strm.next_in = next;
  strm.avail_in = have;
  state2.hold = hold;
  state2.bits = bits;
  if (state2.wsize || _out !== strm.avail_out && state2.mode < BAD$1 && (state2.mode < CHECK || flush !== Z_FINISH3)) {
    if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
      state2.mode = MEM;
      return Z_MEM_ERROR;
    }
  }
  _in -= strm.avail_in;
  _out -= strm.avail_out;
  strm.total_in += _in;
  strm.total_out += _out;
  state2.total += _out;
  if (state2.wrap && _out) {
    strm.adler = state2.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
    state2.flags ? crc323(state2.check, output, _out, strm.next_out - _out) : adler323(state2.check, output, _out, strm.next_out - _out);
  }
  strm.data_type = state2.bits + (state2.last ? 64 : 0) + (state2.mode === TYPE$1 ? 128 : 0) + (state2.mode === LEN_ || state2.mode === COPY_ ? 256 : 0);
  if ((_in === 0 && _out === 0 || flush === Z_FINISH3) && ret === Z_OK3) {
    ret = Z_BUF_ERROR2;
  }
  return ret;
}
function inflateEnd(strm) {
  if (!strm || !strm.state) {
    return Z_STREAM_ERROR2;
  }
  var state2 = strm.state;
  if (state2.window) {
    state2.window = null;
  }
  strm.state = null;
  return Z_OK3;
}
function inflateGetHeader(strm, head) {
  var state2;
  if (!strm || !strm.state) {
    return Z_STREAM_ERROR2;
  }
  state2 = strm.state;
  if ((state2.wrap & 2) === 0) {
    return Z_STREAM_ERROR2;
  }
  state2.head = head;
  head.done = false;
  return Z_OK3;
}
function inflateSetDictionary(strm, dictionary) {
  var dictLength = dictionary.length;
  var state2;
  var dictid;
  var ret;
  if (!strm || !strm.state) {
    return Z_STREAM_ERROR2;
  }
  state2 = strm.state;
  if (state2.wrap !== 0 && state2.mode !== DICT) {
    return Z_STREAM_ERROR2;
  }
  if (state2.mode === DICT) {
    dictid = 1;
    dictid = adler323(dictid, dictionary, dictLength, 0);
    if (dictid !== state2.check) {
      return Z_DATA_ERROR2;
    }
  }
  ret = updatewindow(strm, dictionary, dictLength, dictLength);
  if (ret) {
    state2.mode = MEM;
    return Z_MEM_ERROR;
  }
  state2.havedict = 1;
  return Z_OK3;
}
var exports17, BAD, TYPE, _inffast, exports$17, utils4, MAXBITS, ENOUGH_LENS, ENOUGH_DISTS, CODES, LENS, DISTS, lbase, lext, dbase, dext, _inftrees, exports$23, utils$12, adler323, crc323, inflate_fast2, inflate_table2, CODES$1, LENS$1, DISTS$1, Z_FINISH3, Z_BLOCK2, Z_TREES, Z_OK3, Z_STREAM_END3, Z_NEED_DICT, Z_STREAM_ERROR2, Z_DATA_ERROR2, Z_MEM_ERROR, Z_BUF_ERROR2, Z_DEFLATED3, HEAD, FLAGS, TIME, OS, EXLEN, EXTRA, NAME, COMMENT, HCRC, DICTID, DICT, TYPE$1, TYPEDO, STORED, COPY_, COPY, TABLE, LENLENS, CODELENS, LEN_, LEN, LENEXT, DIST, DISTEXT, MATCH, LIT, CHECK, LENGTH, DONE, BAD$1, MEM, SYNC, ENOUGH_LENS$1, ENOUGH_DISTS$1, MAX_WBITS2, DEF_WBITS, virgin, lenfix, distfix, inflateInfo, _inflateReset, _inflateReset2, _inflateResetKeep, _inflateInit, _inflateInit2, _inflate, _inflateEnd, _inflateGetHeader, _inflateSetDictionary, inflate_default;
var init_inflate = __esm({
  "https://dev.jspm.io/npm:pako@1.0.11/lib/zlib/inflate.js!cjs"() {
    init_common_cjs();
    init_adler32_cjs();
    init_crc32_cjs();
    exports17 = {};
    BAD = 30;
    TYPE = 12;
    exports17 = function inflate_fast(strm, start) {
      var state2;
      var _in;
      var last;
      var _out;
      var beg;
      var end;
      var dmax;
      var wsize;
      var whave;
      var wnext;
      var s_window;
      var hold;
      var bits;
      var lcode;
      var dcode;
      var lmask;
      var dmask;
      var here;
      var op;
      var len;
      var dist;
      var from;
      var from_source;
      var input, output;
      state2 = strm.state;
      _in = strm.next_in;
      input = strm.input;
      last = _in + (strm.avail_in - 5);
      _out = strm.next_out;
      output = strm.output;
      beg = _out - (start - strm.avail_out);
      end = _out + (strm.avail_out - 257);
      dmax = state2.dmax;
      wsize = state2.wsize;
      whave = state2.whave;
      wnext = state2.wnext;
      s_window = state2.window;
      hold = state2.hold;
      bits = state2.bits;
      lcode = state2.lencode;
      dcode = state2.distcode;
      lmask = (1 << state2.lenbits) - 1;
      dmask = (1 << state2.distbits) - 1;
      top: do {
        if (bits < 15) {
          hold += input[_in++] << bits;
          bits += 8;
          hold += input[_in++] << bits;
          bits += 8;
        }
        here = lcode[hold & lmask];
        dolen: for (; ; ) {
          op = here >>> 24;
          hold >>>= op;
          bits -= op;
          op = here >>> 16 & 255;
          if (op === 0) {
            output[_out++] = here & 65535;
          } else if (op & 16) {
            len = here & 65535;
            op &= 15;
            if (op) {
              if (bits < op) {
                hold += input[_in++] << bits;
                bits += 8;
              }
              len += hold & (1 << op) - 1;
              hold >>>= op;
              bits -= op;
            }
            if (bits < 15) {
              hold += input[_in++] << bits;
              bits += 8;
              hold += input[_in++] << bits;
              bits += 8;
            }
            here = dcode[hold & dmask];
            dodist: for (; ; ) {
              op = here >>> 24;
              hold >>>= op;
              bits -= op;
              op = here >>> 16 & 255;
              if (op & 16) {
                dist = here & 65535;
                op &= 15;
                if (bits < op) {
                  hold += input[_in++] << bits;
                  bits += 8;
                  if (bits < op) {
                    hold += input[_in++] << bits;
                    bits += 8;
                  }
                }
                dist += hold & (1 << op) - 1;
                if (dist > dmax) {
                  strm.msg = "invalid distance too far back";
                  state2.mode = BAD;
                  break top;
                }
                hold >>>= op;
                bits -= op;
                op = _out - beg;
                if (dist > op) {
                  op = dist - op;
                  if (op > whave) {
                    if (state2.sane) {
                      strm.msg = "invalid distance too far back";
                      state2.mode = BAD;
                      break top;
                    }
                  }
                  from = 0;
                  from_source = s_window;
                  if (wnext === 0) {
                    from += wsize - op;
                    if (op < len) {
                      len -= op;
                      do {
                        output[_out++] = s_window[from++];
                      } while (--op);
                      from = _out - dist;
                      from_source = output;
                    }
                  } else if (wnext < op) {
                    from += wsize + wnext - op;
                    op -= wnext;
                    if (op < len) {
                      len -= op;
                      do {
                        output[_out++] = s_window[from++];
                      } while (--op);
                      from = 0;
                      if (wnext < len) {
                        op = wnext;
                        len -= op;
                        do {
                          output[_out++] = s_window[from++];
                        } while (--op);
                        from = _out - dist;
                        from_source = output;
                      }
                    }
                  } else {
                    from += wnext - op;
                    if (op < len) {
                      len -= op;
                      do {
                        output[_out++] = s_window[from++];
                      } while (--op);
                      from = _out - dist;
                      from_source = output;
                    }
                  }
                  while (len > 2) {
                    output[_out++] = from_source[from++];
                    output[_out++] = from_source[from++];
                    output[_out++] = from_source[from++];
                    len -= 3;
                  }
                  if (len) {
                    output[_out++] = from_source[from++];
                    if (len > 1) {
                      output[_out++] = from_source[from++];
                    }
                  }
                } else {
                  from = _out - dist;
                  do {
                    output[_out++] = output[from++];
                    output[_out++] = output[from++];
                    output[_out++] = output[from++];
                    len -= 3;
                  } while (len > 2);
                  if (len) {
                    output[_out++] = output[from++];
                    if (len > 1) {
                      output[_out++] = output[from++];
                    }
                  }
                }
              } else if ((op & 64) === 0) {
                here = dcode[(here & 65535) + /*here.val*/
                (hold & (1 << op) - 1)];
                continue dodist;
              } else {
                strm.msg = "invalid distance code";
                state2.mode = BAD;
                break top;
              }
              break;
            }
          } else if ((op & 64) === 0) {
            here = lcode[(here & 65535) + /*here.val*/
            (hold & (1 << op) - 1)];
            continue dolen;
          } else if (op & 32) {
            state2.mode = TYPE;
            break top;
          } else {
            strm.msg = "invalid literal/length code";
            state2.mode = BAD;
            break top;
          }
          break;
        }
      } while (_in < last && _out < end);
      len = bits >> 3;
      _in -= len;
      bits -= len << 3;
      hold &= (1 << bits) - 1;
      strm.next_in = _in;
      strm.next_out = _out;
      strm.avail_in = _in < last ? 5 + (last - _in) : 5 - (_in - last);
      strm.avail_out = _out < end ? 257 + (end - _out) : 257 - (_out - end);
      state2.hold = hold;
      state2.bits = bits;
      return;
    };
    _inffast = exports17;
    exports$17 = {};
    utils4 = common_cjs_default;
    MAXBITS = 15;
    ENOUGH_LENS = 852;
    ENOUGH_DISTS = 592;
    CODES = 0;
    LENS = 1;
    DISTS = 2;
    lbase = [
      /* Length codes 257..285 base */
      3,
      4,
      5,
      6,
      7,
      8,
      9,
      10,
      11,
      13,
      15,
      17,
      19,
      23,
      27,
      31,
      35,
      43,
      51,
      59,
      67,
      83,
      99,
      115,
      131,
      163,
      195,
      227,
      258,
      0,
      0
    ];
    lext = [
      /* Length codes 257..285 extra */
      16,
      16,
      16,
      16,
      16,
      16,
      16,
      16,
      17,
      17,
      17,
      17,
      18,
      18,
      18,
      18,
      19,
      19,
      19,
      19,
      20,
      20,
      20,
      20,
      21,
      21,
      21,
      21,
      16,
      72,
      78
    ];
    dbase = [
      /* Distance codes 0..29 base */
      1,
      2,
      3,
      4,
      5,
      7,
      9,
      13,
      17,
      25,
      33,
      49,
      65,
      97,
      129,
      193,
      257,
      385,
      513,
      769,
      1025,
      1537,
      2049,
      3073,
      4097,
      6145,
      8193,
      12289,
      16385,
      24577,
      0,
      0
    ];
    dext = [
      /* Distance codes 0..29 extra */
      16,
      16,
      16,
      16,
      17,
      17,
      18,
      18,
      19,
      19,
      20,
      20,
      21,
      21,
      22,
      22,
      23,
      23,
      24,
      24,
      25,
      25,
      26,
      26,
      27,
      27,
      28,
      28,
      29,
      29,
      64,
      64
    ];
    exports$17 = function inflate_table(type4, lens, lens_index, codes, table, table_index, work, opts) {
      var bits = opts.bits;
      var len = 0;
      var sym = 0;
      var min2 = 0, max = 0;
      var root = 0;
      var curr = 0;
      var drop = 0;
      var left = 0;
      var used = 0;
      var huff = 0;
      var incr;
      var fill;
      var low;
      var mask;
      var next;
      var base3 = null;
      var base_index = 0;
      var end;
      var count = new utils4.Buf16(MAXBITS + 1);
      var offs = new utils4.Buf16(MAXBITS + 1);
      var extra = null;
      var extra_index = 0;
      var here_bits, here_op, here_val;
      for (len = 0; len <= MAXBITS; len++) {
        count[len] = 0;
      }
      for (sym = 0; sym < codes; sym++) {
        count[lens[lens_index + sym]]++;
      }
      root = bits;
      for (max = MAXBITS; max >= 1; max--) {
        if (count[max] !== 0) {
          break;
        }
      }
      if (root > max) {
        root = max;
      }
      if (max === 0) {
        table[table_index++] = 1 << 24 | 64 << 16 | 0;
        table[table_index++] = 1 << 24 | 64 << 16 | 0;
        opts.bits = 1;
        return 0;
      }
      for (min2 = 1; min2 < max; min2++) {
        if (count[min2] !== 0) {
          break;
        }
      }
      if (root < min2) {
        root = min2;
      }
      left = 1;
      for (len = 1; len <= MAXBITS; len++) {
        left <<= 1;
        left -= count[len];
        if (left < 0) {
          return -1;
        }
      }
      if (left > 0 && (type4 === CODES || max !== 1)) {
        return -1;
      }
      offs[1] = 0;
      for (len = 1; len < MAXBITS; len++) {
        offs[len + 1] = offs[len] + count[len];
      }
      for (sym = 0; sym < codes; sym++) {
        if (lens[lens_index + sym] !== 0) {
          work[offs[lens[lens_index + sym]]++] = sym;
        }
      }
      if (type4 === CODES) {
        base3 = extra = work;
        end = 19;
      } else if (type4 === LENS) {
        base3 = lbase;
        base_index -= 257;
        extra = lext;
        extra_index -= 257;
        end = 256;
      } else {
        base3 = dbase;
        extra = dext;
        end = -1;
      }
      huff = 0;
      sym = 0;
      len = min2;
      next = table_index;
      curr = root;
      drop = 0;
      low = -1;
      used = 1 << root;
      mask = used - 1;
      if (type4 === LENS && used > ENOUGH_LENS || type4 === DISTS && used > ENOUGH_DISTS) {
        return 1;
      }
      for (; ; ) {
        here_bits = len - drop;
        if (work[sym] < end) {
          here_op = 0;
          here_val = work[sym];
        } else if (work[sym] > end) {
          here_op = extra[extra_index + work[sym]];
          here_val = base3[base_index + work[sym]];
        } else {
          here_op = 32 + 64;
          here_val = 0;
        }
        incr = 1 << len - drop;
        fill = 1 << curr;
        min2 = fill;
        do {
          fill -= incr;
          table[next + (huff >> drop) + fill] = here_bits << 24 | here_op << 16 | here_val | 0;
        } while (fill !== 0);
        incr = 1 << len - 1;
        while (huff & incr) {
          incr >>= 1;
        }
        if (incr !== 0) {
          huff &= incr - 1;
          huff += incr;
        } else {
          huff = 0;
        }
        sym++;
        if (--count[len] === 0) {
          if (len === max) {
            break;
          }
          len = lens[lens_index + work[sym]];
        }
        if (len > root && (huff & mask) !== low) {
          if (drop === 0) {
            drop = root;
          }
          next += min2;
          curr = len - drop;
          left = 1 << curr;
          while (curr + drop < max) {
            left -= count[curr + drop];
            if (left <= 0) {
              break;
            }
            curr++;
            left <<= 1;
          }
          used += 1 << curr;
          if (type4 === LENS && used > ENOUGH_LENS || type4 === DISTS && used > ENOUGH_DISTS) {
            return 1;
          }
          low = huff & mask;
          table[low] = root << 24 | curr << 16 | next - table_index | 0;
        }
      }
      if (huff !== 0) {
        table[next + huff] = len - drop << 24 | 64 << 16 | 0;
      }
      opts.bits = root;
      return 0;
    };
    _inftrees = exports$17;
    exports$23 = {};
    utils$12 = common_cjs_default;
    adler323 = adler32_cjs_default;
    crc323 = crc32_cjs_default;
    inflate_fast2 = _inffast;
    inflate_table2 = _inftrees;
    CODES$1 = 0;
    LENS$1 = 1;
    DISTS$1 = 2;
    Z_FINISH3 = 4;
    Z_BLOCK2 = 5;
    Z_TREES = 6;
    Z_OK3 = 0;
    Z_STREAM_END3 = 1;
    Z_NEED_DICT = 2;
    Z_STREAM_ERROR2 = -2;
    Z_DATA_ERROR2 = -3;
    Z_MEM_ERROR = -4;
    Z_BUF_ERROR2 = -5;
    Z_DEFLATED3 = 8;
    HEAD = 1;
    FLAGS = 2;
    TIME = 3;
    OS = 4;
    EXLEN = 5;
    EXTRA = 6;
    NAME = 7;
    COMMENT = 8;
    HCRC = 9;
    DICTID = 10;
    DICT = 11;
    TYPE$1 = 12;
    TYPEDO = 13;
    STORED = 14;
    COPY_ = 15;
    COPY = 16;
    TABLE = 17;
    LENLENS = 18;
    CODELENS = 19;
    LEN_ = 20;
    LEN = 21;
    LENEXT = 22;
    DIST = 23;
    DISTEXT = 24;
    MATCH = 25;
    LIT = 26;
    CHECK = 27;
    LENGTH = 28;
    DONE = 29;
    BAD$1 = 30;
    MEM = 31;
    SYNC = 32;
    ENOUGH_LENS$1 = 852;
    ENOUGH_DISTS$1 = 592;
    MAX_WBITS2 = 15;
    DEF_WBITS = MAX_WBITS2;
    virgin = true;
    exports$23.inflateReset = inflateReset;
    exports$23.inflateReset2 = inflateReset2;
    exports$23.inflateResetKeep = inflateResetKeep;
    exports$23.inflateInit = inflateInit;
    exports$23.inflateInit2 = inflateInit2;
    exports$23.inflate = inflate;
    exports$23.inflateEnd = inflateEnd;
    exports$23.inflateGetHeader = inflateGetHeader;
    exports$23.inflateSetDictionary = inflateSetDictionary;
    exports$23.inflateInfo = "pako inflate (from Nodeca project)";
    inflateInfo = exports$23.inflateInfo;
    _inflateReset = exports$23.inflateReset;
    _inflateReset2 = exports$23.inflateReset2;
    _inflateResetKeep = exports$23.inflateResetKeep;
    _inflateInit = exports$23.inflateInit;
    _inflateInit2 = exports$23.inflateInit2;
    _inflate = exports$23.inflate;
    _inflateEnd = exports$23.inflateEnd;
    _inflateGetHeader = exports$23.inflateGetHeader;
    _inflateSetDictionary = exports$23.inflateSetDictionary;
    inflate_default = exports$23;
  }
});

// https://dev.jspm.io/npm:pako@1.0.11/lib/zlib/constants!cjs
var exports18, _constants, constants_cjs_default;
var init_constants_cjs = __esm({
  "https://dev.jspm.io/npm:pako@1.0.11/lib/zlib/constants!cjs"() {
    exports18 = {};
    exports18 = {
      /* Allowed flush values; see deflate() and inflate() below for details */
      Z_NO_FLUSH: 0,
      Z_PARTIAL_FLUSH: 1,
      Z_SYNC_FLUSH: 2,
      Z_FULL_FLUSH: 3,
      Z_FINISH: 4,
      Z_BLOCK: 5,
      Z_TREES: 6,
      /* Return codes for the compression/decompression functions. Negative values
      * are errors, positive values are used for special but normal events.
      */
      Z_OK: 0,
      Z_STREAM_END: 1,
      Z_NEED_DICT: 2,
      Z_ERRNO: -1,
      Z_STREAM_ERROR: -2,
      Z_DATA_ERROR: -3,
      //Z_MEM_ERROR:     -4,
      Z_BUF_ERROR: -5,
      //Z_VERSION_ERROR: -6,
      /* compression levels */
      Z_NO_COMPRESSION: 0,
      Z_BEST_SPEED: 1,
      Z_BEST_COMPRESSION: 9,
      Z_DEFAULT_COMPRESSION: -1,
      Z_FILTERED: 1,
      Z_HUFFMAN_ONLY: 2,
      Z_RLE: 3,
      Z_FIXED: 4,
      Z_DEFAULT_STRATEGY: 0,
      /* Possible values of the data_type field (though see inflate()) */
      Z_BINARY: 0,
      Z_TEXT: 1,
      //Z_ASCII:                1, // = Z_TEXT (deprecated)
      Z_UNKNOWN: 2,
      /* The deflate compression method */
      Z_DEFLATED: 8
      //Z_NULL:                 null // Use -1 or null inline, depending on var type
    };
    _constants = exports18;
    constants_cjs_default = _constants;
  }
});

// https://dev.jspm.io/npm:pako@1.0.11/lib/zlib/gzheader!cjs
function GZheader() {
  this.text = 0;
  this.time = 0;
  this.xflags = 0;
  this.os = 0;
  this.extra = null;
  this.extra_len = 0;
  this.name = "";
  this.comment = "";
  this.hcrc = 0;
  this.done = false;
}
var exports19, _gzheader, gzheader_cjs_default;
var init_gzheader_cjs = __esm({
  "https://dev.jspm.io/npm:pako@1.0.11/lib/zlib/gzheader!cjs"() {
    exports19 = {};
    exports19 = GZheader;
    _gzheader = exports19;
    gzheader_cjs_default = _gzheader;
  }
});

// https://dev.jspm.io/npm:pako@1.0.11/lib/inflate!cjs
function Inflate(options) {
  if (!(this instanceof Inflate)) return new Inflate(options);
  this.options = utils5.assign({
    chunkSize: 16384,
    windowBits: 0,
    to: ""
  }, options || {});
  var opt = this.options;
  if (opt.raw && opt.windowBits >= 0 && opt.windowBits < 16) {
    opt.windowBits = -opt.windowBits;
    if (opt.windowBits === 0) {
      opt.windowBits = -15;
    }
  }
  if (opt.windowBits >= 0 && opt.windowBits < 16 && !(options && options.windowBits)) {
    opt.windowBits += 32;
  }
  if (opt.windowBits > 15 && opt.windowBits < 48) {
    if ((opt.windowBits & 15) === 0) {
      opt.windowBits |= 15;
    }
  }
  this.err = 0;
  this.msg = "";
  this.ended = false;
  this.chunks = [];
  this.strm = new ZStream3();
  this.strm.avail_out = 0;
  var status = zlib_inflate.inflateInit2(this.strm, opt.windowBits);
  if (status !== c5.Z_OK) {
    throw new Error(msg3[status]);
  }
  this.header = new GZheader2();
  zlib_inflate.inflateGetHeader(this.strm, this.header);
  if (opt.dictionary) {
    if (typeof opt.dictionary === "string") {
      opt.dictionary = strings2.string2buf(opt.dictionary);
    } else if (toString5.call(opt.dictionary) === "[object ArrayBuffer]") {
      opt.dictionary = new Uint8Array(opt.dictionary);
    }
    if (opt.raw) {
      status = zlib_inflate.inflateSetDictionary(this.strm, opt.dictionary);
      if (status !== c5.Z_OK) {
        throw new Error(msg3[status]);
      }
    }
  }
}
function inflate2(input, options) {
  var inflator = new Inflate(options);
  inflator.push(input, true);
  if (inflator.err) {
    throw inflator.msg || msg3[inflator.err];
  }
  return inflator.result;
}
function inflateRaw(input, options) {
  options = options || {};
  options.raw = true;
  return inflate2(input, options);
}
var exports20, zlib_inflate, utils5, strings2, c5, msg3, ZStream3, GZheader2, toString5, ungzip, _Inflate, _inflate2, _inflateRaw, inflate_cjs_default;
var init_inflate_cjs = __esm({
  "https://dev.jspm.io/npm:pako@1.0.11/lib/inflate!cjs"() {
    init_common_cjs();
    init_adler32_cjs();
    init_crc32_cjs();
    init_messages_cjs();
    init_strings_cjs();
    init_zstream_cjs();
    init_inflate();
    init_constants_cjs();
    init_gzheader_cjs();
    exports20 = {};
    zlib_inflate = inflate_default;
    utils5 = common_cjs_default;
    strings2 = strings_cjs_default;
    c5 = constants_cjs_default;
    msg3 = messages_cjs_default;
    ZStream3 = zstream_cjs_default;
    GZheader2 = gzheader_cjs_default;
    toString5 = Object.prototype.toString;
    Inflate.prototype.push = function(data3, mode) {
      var strm = this.strm;
      var chunkSize = this.options.chunkSize;
      var dictionary = this.options.dictionary;
      var status, _mode;
      var next_out_utf8, tail, utf8str;
      var allowBufError = false;
      if (this.ended) {
        return false;
      }
      _mode = mode === ~~mode ? mode : mode === true ? c5.Z_FINISH : c5.Z_NO_FLUSH;
      if (typeof data3 === "string") {
        strm.input = strings2.binstring2buf(data3);
      } else if (toString5.call(data3) === "[object ArrayBuffer]") {
        strm.input = new Uint8Array(data3);
      } else {
        strm.input = data3;
      }
      strm.next_in = 0;
      strm.avail_in = strm.input.length;
      do {
        if (strm.avail_out === 0) {
          strm.output = new utils5.Buf8(chunkSize);
          strm.next_out = 0;
          strm.avail_out = chunkSize;
        }
        status = zlib_inflate.inflate(strm, c5.Z_NO_FLUSH);
        if (status === c5.Z_NEED_DICT && dictionary) {
          status = zlib_inflate.inflateSetDictionary(this.strm, dictionary);
        }
        if (status === c5.Z_BUF_ERROR && allowBufError === true) {
          status = c5.Z_OK;
          allowBufError = false;
        }
        if (status !== c5.Z_STREAM_END && status !== c5.Z_OK) {
          this.onEnd(status);
          this.ended = true;
          return false;
        }
        if (strm.next_out) {
          if (strm.avail_out === 0 || status === c5.Z_STREAM_END || strm.avail_in === 0 && (_mode === c5.Z_FINISH || _mode === c5.Z_SYNC_FLUSH)) {
            if (this.options.to === "string") {
              next_out_utf8 = strings2.utf8border(strm.output, strm.next_out);
              tail = strm.next_out - next_out_utf8;
              utf8str = strings2.buf2string(strm.output, next_out_utf8);
              strm.next_out = tail;
              strm.avail_out = chunkSize - tail;
              if (tail) {
                utils5.arraySet(strm.output, strm.output, next_out_utf8, tail, 0);
              }
              this.onData(utf8str);
            } else {
              this.onData(utils5.shrinkBuf(strm.output, strm.next_out));
            }
          }
        }
        if (strm.avail_in === 0 && strm.avail_out === 0) {
          allowBufError = true;
        }
      } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c5.Z_STREAM_END);
      if (status === c5.Z_STREAM_END) {
        _mode = c5.Z_FINISH;
      }
      if (_mode === c5.Z_FINISH) {
        status = zlib_inflate.inflateEnd(this.strm);
        this.onEnd(status);
        this.ended = true;
        return status === c5.Z_OK;
      }
      if (_mode === c5.Z_SYNC_FLUSH) {
        this.onEnd(c5.Z_OK);
        strm.avail_out = 0;
        return true;
      }
      return true;
    };
    Inflate.prototype.onData = function(chunk) {
      this.chunks.push(chunk);
    };
    Inflate.prototype.onEnd = function(status) {
      if (status === c5.Z_OK) {
        if (this.options.to === "string") {
          this.result = this.chunks.join("");
        } else {
          this.result = utils5.flattenChunks(this.chunks);
        }
      }
      this.chunks = [];
      this.err = status;
      this.msg = this.strm.msg;
    };
    exports20.Inflate = Inflate;
    exports20.inflate = inflate2;
    exports20.inflateRaw = inflateRaw;
    exports20.ungzip = inflate2;
    ungzip = exports20.ungzip;
    _Inflate = exports20.Inflate;
    _inflate2 = exports20.inflate;
    _inflateRaw = exports20.inflateRaw;
    inflate_cjs_default = exports20;
  }
});

// https://dev.jspm.io/npm:pako@1.0.11!cjs
var exports21, assign2, deflate3, inflate3, constants3, pako, exports$18, npm_pako_1_0_default;
var init_npm_pako_1_0 = __esm({
  "https://dev.jspm.io/npm:pako@1.0.11!cjs"() {
    init_common_cjs();
    init_deflate();
    init_adler32_cjs();
    init_crc32_cjs();
    init_messages_cjs();
    init_strings_cjs();
    init_zstream_cjs();
    init_deflate_cjs();
    init_inflate();
    init_constants_cjs();
    init_gzheader_cjs();
    init_inflate_cjs();
    exports21 = {};
    assign2 = common_cjs_default.assign;
    deflate3 = deflate_cjs_default;
    inflate3 = inflate_cjs_default;
    constants3 = constants_cjs_default;
    pako = {};
    assign2(pako, deflate3, inflate3, constants3);
    exports21 = pako;
    exports$18 = exports21;
    npm_pako_1_0_default = exports$18;
  }
});

// https://dev.jspm.io/npm:pako@1.0!cjs
var init_npm_pako_1 = __esm({
  "https://dev.jspm.io/npm:pako@1.0!cjs"() {
    init_common_cjs();
    init_deflate();
    init_adler32_cjs();
    init_crc32_cjs();
    init_messages_cjs();
    init_strings_cjs();
    init_zstream_cjs();
    init_deflate_cjs();
    init_inflate();
    init_constants_cjs();
    init_gzheader_cjs();
    init_inflate_cjs();
    init_npm_pako_1_0();
  }
});

// https://dev.jspm.io/npm:jszip@3.5.0!cjs
function dew6() {
  if (_dewExec6) return exports22;
  _dewExec6 = true;
  var Buffer4 = exports5.Buffer;
  exports22.base64 = true;
  exports22.array = true;
  exports22.string = true;
  exports22.arraybuffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined";
  exports22.nodebuffer = typeof Buffer4 !== "undefined";
  exports22.uint8array = typeof Uint8Array !== "undefined";
  if (typeof ArrayBuffer === "undefined") {
    exports22.blob = false;
  } else {
    var buffer2 = new ArrayBuffer(0);
    try {
      exports22.blob = new Blob([buffer2], {
        type: "application/zip"
      }).size === 0;
    } catch (e5) {
      try {
        var Builder = self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder;
        var builder = new Builder();
        builder.append(buffer2);
        exports22.blob = builder.getBlob("application/zip").size === 0;
      } catch (e6) {
        exports22.blob = false;
      }
    }
  }
  try {
    exports22.nodestream = !!dew4().Readable;
  } catch (e5) {
    exports22.nodestream = false;
  }
  return exports22;
}
function dew$13() {
  if (_dewExec$13) return exports$19;
  _dewExec$13 = true;
  var utils6 = dew$42();
  var support = dew6();
  var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  exports$19.encode = function(input) {
    var output = [];
    var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
    var i6 = 0, len = input.length, remainingBytes = len;
    var isArray6 = utils6.getTypeOf(input) !== "string";
    while (i6 < input.length) {
      remainingBytes = len - i6;
      if (!isArray6) {
        chr1 = input.charCodeAt(i6++);
        chr2 = i6 < len ? input.charCodeAt(i6++) : 0;
        chr3 = i6 < len ? input.charCodeAt(i6++) : 0;
      } else {
        chr1 = input[i6++];
        chr2 = i6 < len ? input[i6++] : 0;
        chr3 = i6 < len ? input[i6++] : 0;
      }
      enc1 = chr1 >> 2;
      enc2 = (chr1 & 3) << 4 | chr2 >> 4;
      enc3 = remainingBytes > 1 ? (chr2 & 15) << 2 | chr3 >> 6 : 64;
      enc4 = remainingBytes > 2 ? chr3 & 63 : 64;
      output.push(_keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4));
    }
    return output.join("");
  };
  exports$19.decode = function(input) {
    var chr1, chr2, chr3;
    var enc1, enc2, enc3, enc4;
    var i6 = 0, resultIndex = 0;
    var dataUrlPrefix = "data:";
    if (input.substr(0, dataUrlPrefix.length) === dataUrlPrefix) {
      throw new Error("Invalid base64 input, it looks like a data url.");
    }
    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
    var totalLength = input.length * 3 / 4;
    if (input.charAt(input.length - 1) === _keyStr.charAt(64)) {
      totalLength--;
    }
    if (input.charAt(input.length - 2) === _keyStr.charAt(64)) {
      totalLength--;
    }
    if (totalLength % 1 !== 0) {
      throw new Error("Invalid base64 input, bad content length.");
    }
    var output;
    if (support.uint8array) {
      output = new Uint8Array(totalLength | 0);
    } else {
      output = new Array(totalLength | 0);
    }
    while (i6 < input.length) {
      enc1 = _keyStr.indexOf(input.charAt(i6++));
      enc2 = _keyStr.indexOf(input.charAt(i6++));
      enc3 = _keyStr.indexOf(input.charAt(i6++));
      enc4 = _keyStr.indexOf(input.charAt(i6++));
      chr1 = enc1 << 2 | enc2 >> 4;
      chr2 = (enc2 & 15) << 4 | enc3 >> 2;
      chr3 = (enc3 & 3) << 6 | enc4;
      output[resultIndex++] = chr1;
      if (enc3 !== 64) {
        output[resultIndex++] = chr2;
      }
      if (enc4 !== 64) {
        output[resultIndex++] = chr3;
      }
    }
    return output;
  };
  return exports$19;
}
function dew$23() {
  if (_dewExec$23) return exports$24;
  _dewExec$23 = true;
  var Buffer4 = exports5.Buffer;
  exports$24 = {
    /**
     * True if this is running in Nodejs, will be undefined in a browser.
     * In a browser, browserify won't include this file and the whole module
     * will be resolved an empty object.
     */
    isNode: typeof Buffer4 !== "undefined",
    /**
     * Create a new nodejs Buffer from an existing content.
     * @param {Object} data the data to pass to the constructor.
     * @param {String} encoding the encoding to use.
     * @return {Buffer} a new Buffer.
     */
    newBufferFrom: function(data3, encoding) {
      if (Buffer4.from && Buffer4.from !== Uint8Array.from) {
        return Buffer4.from(data3, encoding);
      } else {
        if (typeof data3 === "number") {
          throw new Error('The "data" argument must not be a number');
        }
        return new Buffer4(data3, encoding);
      }
    },
    /**
     * Create a new nodejs Buffer with the specified size.
     * @param {Integer} size the size of the buffer.
     * @return {Buffer} a new Buffer.
     */
    allocBuffer: function(size) {
      if (Buffer4.alloc) {
        return Buffer4.alloc(size);
      } else {
        var buf = new Buffer4(size);
        buf.fill(0);
        return buf;
      }
    },
    /**
     * Find out if an object is a Buffer.
     * @param {Object} b the object to test.
     * @return {Boolean} true if the object is a Buffer, false otherwise.
     */
    isBuffer: function(b3) {
      return Buffer4.isBuffer(b3);
    },
    isStream: function(obj) {
      return obj && typeof obj.on === "function" && typeof obj.pause === "function" && typeof obj.resume === "function";
    }
  };
  return exports$24;
}
function dew$32() {
  if (_dewExec$32) return exports$33;
  _dewExec$32 = true;
  var ES6Promise = null;
  if (typeof Promise !== "undefined") {
    ES6Promise = Promise;
  } else {
    ES6Promise = npm_lie_3_3_default;
  }
  exports$33 = {
    Promise: ES6Promise
  };
  return exports$33;
}
function dew$42() {
  if (_dewExec$42) return exports$42;
  _dewExec$42 = true;
  var support = dew6();
  var base642 = dew$13();
  var nodejsUtils = dew$23();
  var setImmediate2 = npm_set_immediate_shim_1_0_default;
  var external = dew$32();
  function string2binary(str3) {
    var result2 = null;
    if (support.uint8array) {
      result2 = new Uint8Array(str3.length);
    } else {
      result2 = new Array(str3.length);
    }
    return stringToArrayLike(str3, result2);
  }
  exports$42.newBlob = function(part, type4) {
    exports$42.checkSupport("blob");
    try {
      return new Blob([part], {
        type: type4
      });
    } catch (e5) {
      try {
        var Builder = self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder;
        var builder = new Builder();
        builder.append(part);
        return builder.getBlob(type4);
      } catch (e6) {
        throw new Error("Bug : can't construct the Blob.");
      }
    }
  };
  function identity(input) {
    return input;
  }
  function stringToArrayLike(str3, array) {
    for (var i6 = 0; i6 < str3.length; ++i6) {
      array[i6] = str3.charCodeAt(i6) & 255;
    }
    return array;
  }
  var arrayToStringHelper = {
    /**
     * Transform an array of int into a string, chunk by chunk.
     * See the performances notes on arrayLikeToString.
     * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
     * @param {String} type the type of the array.
     * @param {Integer} chunk the chunk size.
     * @return {String} the resulting string.
     * @throws Error if the chunk is too big for the stack.
     */
    stringifyByChunk: function(array, type4, chunk) {
      var result2 = [], k3 = 0, len = array.length;
      if (len <= chunk) {
        return String.fromCharCode.apply(null, array);
      }
      while (k3 < len) {
        if (type4 === "array" || type4 === "nodebuffer") {
          result2.push(String.fromCharCode.apply(null, array.slice(k3, Math.min(k3 + chunk, len))));
        } else {
          result2.push(String.fromCharCode.apply(null, array.subarray(k3, Math.min(k3 + chunk, len))));
        }
        k3 += chunk;
      }
      return result2.join("");
    },
    /**
     * Call String.fromCharCode on every item in the array.
     * This is the naive implementation, which generate A LOT of intermediate string.
     * This should be used when everything else fail.
     * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
     * @return {String} the result.
     */
    stringifyByChar: function(array) {
      var resultStr = "";
      for (var i6 = 0; i6 < array.length; i6++) {
        resultStr += String.fromCharCode(array[i6]);
      }
      return resultStr;
    },
    applyCanBeUsed: {
      /**
       * true if the browser accepts to use String.fromCharCode on Uint8Array
       */
      uint8array: (function() {
        try {
          return support.uint8array && String.fromCharCode.apply(null, new Uint8Array(1)).length === 1;
        } catch (e5) {
          return false;
        }
      })(),
      /**
       * true if the browser accepts to use String.fromCharCode on nodejs Buffer.
       */
      nodebuffer: (function() {
        try {
          return support.nodebuffer && String.fromCharCode.apply(null, nodejsUtils.allocBuffer(1)).length === 1;
        } catch (e5) {
          return false;
        }
      })()
    }
  };
  function arrayLikeToString(array) {
    var chunk = 65536, type4 = exports$42.getTypeOf(array), canUseApply = true;
    if (type4 === "uint8array") {
      canUseApply = arrayToStringHelper.applyCanBeUsed.uint8array;
    } else if (type4 === "nodebuffer") {
      canUseApply = arrayToStringHelper.applyCanBeUsed.nodebuffer;
    }
    if (canUseApply) {
      while (chunk > 1) {
        try {
          return arrayToStringHelper.stringifyByChunk(array, type4, chunk);
        } catch (e5) {
          chunk = Math.floor(chunk / 2);
        }
      }
    }
    return arrayToStringHelper.stringifyByChar(array);
  }
  exports$42.applyFromCharCode = arrayLikeToString;
  function arrayLikeToArrayLike(arrayFrom, arrayTo) {
    for (var i6 = 0; i6 < arrayFrom.length; i6++) {
      arrayTo[i6] = arrayFrom[i6];
    }
    return arrayTo;
  }
  var transform = {};
  transform["string"] = {
    "string": identity,
    "array": function(input) {
      return stringToArrayLike(input, new Array(input.length));
    },
    "arraybuffer": function(input) {
      return transform["string"]["uint8array"](input).buffer;
    },
    "uint8array": function(input) {
      return stringToArrayLike(input, new Uint8Array(input.length));
    },
    "nodebuffer": function(input) {
      return stringToArrayLike(input, nodejsUtils.allocBuffer(input.length));
    }
  };
  transform["array"] = {
    "string": arrayLikeToString,
    "array": identity,
    "arraybuffer": function(input) {
      return new Uint8Array(input).buffer;
    },
    "uint8array": function(input) {
      return new Uint8Array(input);
    },
    "nodebuffer": function(input) {
      return nodejsUtils.newBufferFrom(input);
    }
  };
  transform["arraybuffer"] = {
    "string": function(input) {
      return arrayLikeToString(new Uint8Array(input));
    },
    "array": function(input) {
      return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength));
    },
    "arraybuffer": identity,
    "uint8array": function(input) {
      return new Uint8Array(input);
    },
    "nodebuffer": function(input) {
      return nodejsUtils.newBufferFrom(new Uint8Array(input));
    }
  };
  transform["uint8array"] = {
    "string": arrayLikeToString,
    "array": function(input) {
      return arrayLikeToArrayLike(input, new Array(input.length));
    },
    "arraybuffer": function(input) {
      return input.buffer;
    },
    "uint8array": identity,
    "nodebuffer": function(input) {
      return nodejsUtils.newBufferFrom(input);
    }
  };
  transform["nodebuffer"] = {
    "string": arrayLikeToString,
    "array": function(input) {
      return arrayLikeToArrayLike(input, new Array(input.length));
    },
    "arraybuffer": function(input) {
      return transform["nodebuffer"]["uint8array"](input).buffer;
    },
    "uint8array": function(input) {
      return arrayLikeToArrayLike(input, new Uint8Array(input.length));
    },
    "nodebuffer": identity
  };
  exports$42.transformTo = function(outputType, input) {
    if (!input) {
      input = "";
    }
    if (!outputType) {
      return input;
    }
    exports$42.checkSupport(outputType);
    var inputType = exports$42.getTypeOf(input);
    var result2 = transform[inputType][outputType](input);
    return result2;
  };
  exports$42.getTypeOf = function(input) {
    if (typeof input === "string") {
      return "string";
    }
    if (Object.prototype.toString.call(input) === "[object Array]") {
      return "array";
    }
    if (support.nodebuffer && nodejsUtils.isBuffer(input)) {
      return "nodebuffer";
    }
    if (support.uint8array && input instanceof Uint8Array) {
      return "uint8array";
    }
    if (support.arraybuffer && input instanceof ArrayBuffer) {
      return "arraybuffer";
    }
  };
  exports$42.checkSupport = function(type4) {
    var supported = support[type4.toLowerCase()];
    if (!supported) {
      throw new Error(type4 + " is not supported by this platform");
    }
  };
  exports$42.MAX_VALUE_16BITS = 65535;
  exports$42.MAX_VALUE_32BITS = -1;
  exports$42.pretty = function(str3) {
    var res = "", code5, i6;
    for (i6 = 0; i6 < (str3 || "").length; i6++) {
      code5 = str3.charCodeAt(i6);
      res += "\\x" + (code5 < 16 ? "0" : "") + code5.toString(16).toUpperCase();
    }
    return res;
  };
  exports$42.delay = function(callback, args, self2) {
    setImmediate2(function() {
      callback.apply(self2 || null, args || []);
    });
  };
  exports$42.inherits = function(ctor, superCtor) {
    var Obj = function() {
    };
    Obj.prototype = superCtor.prototype;
    ctor.prototype = new Obj();
  };
  exports$42.extend = function() {
    var result2 = {}, i6, attr;
    for (i6 = 0; i6 < arguments.length; i6++) {
      for (attr in arguments[i6]) {
        if (arguments[i6].hasOwnProperty(attr) && typeof result2[attr] === "undefined") {
          result2[attr] = arguments[i6][attr];
        }
      }
    }
    return result2;
  };
  exports$42.prepareContent = function(name2, inputData, isBinary3, isOptimizedBinaryString, isBase64) {
    var promise = external.Promise.resolve(inputData).then(function(data3) {
      var isBlob2 = support.blob && (data3 instanceof Blob || ["[object File]", "[object Blob]"].indexOf(Object.prototype.toString.call(data3)) !== -1);
      if (isBlob2 && typeof FileReader !== "undefined") {
        return new external.Promise(function(resolve16, reject2) {
          var reader = new FileReader();
          reader.onload = function(e5) {
            resolve16(e5.target.result);
          };
          reader.onerror = function(e5) {
            reject2(e5.target.error);
          };
          reader.readAsArrayBuffer(data3);
        });
      } else {
        return data3;
      }
    });
    return promise.then(function(data3) {
      var dataType = exports$42.getTypeOf(data3);
      if (!dataType) {
        return external.Promise.reject(new Error("Can't read the data of '" + name2 + "'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?"));
      }
      if (dataType === "arraybuffer") {
        data3 = exports$42.transformTo("uint8array", data3);
      } else if (dataType === "string") {
        if (isBase64) {
          data3 = base642.decode(data3);
        } else if (isBinary3) {
          if (isOptimizedBinaryString !== true) {
            data3 = string2binary(data3);
          }
        }
      }
      return data3;
    });
  };
  return exports$42;
}
function dew$52() {
  if (_dewExec$52) return exports$52;
  _dewExec$52 = true;
  function GenericWorker(name2) {
    this.name = name2 || "default";
    this.streamInfo = {};
    this.generatedError = null;
    this.extraStreamInfo = {};
    this.isPaused = true;
    this.isFinished = false;
    this.isLocked = false;
    this._listeners = {
      "data": [],
      "end": [],
      "error": []
    };
    this.previous = null;
  }
  GenericWorker.prototype = {
    /**
     * Push a chunk to the next workers.
     * @param {Object} chunk the chunk to push
     */
    push: function(chunk) {
      this.emit("data", chunk);
    },
    /**
     * End the stream.
     * @return {Boolean} true if this call ended the worker, false otherwise.
     */
    end: function() {
      if (this.isFinished) {
        return false;
      }
      this.flush();
      try {
        this.emit("end");
        this.cleanUp();
        this.isFinished = true;
      } catch (e5) {
        this.emit("error", e5);
      }
      return true;
    },
    /**
     * End the stream with an error.
     * @param {Error} e the error which caused the premature end.
     * @return {Boolean} true if this call ended the worker with an error, false otherwise.
     */
    error: function(e5) {
      if (this.isFinished) {
        return false;
      }
      if (this.isPaused) {
        this.generatedError = e5;
      } else {
        this.isFinished = true;
        this.emit("error", e5);
        if (this.previous) {
          this.previous.error(e5);
        }
        this.cleanUp();
      }
      return true;
    },
    /**
     * Add a callback on an event.
     * @param {String} name the name of the event (data, end, error)
     * @param {Function} listener the function to call when the event is triggered
     * @return {GenericWorker} the current object for chainability
     */
    on: function(name2, listener) {
      this._listeners[name2].push(listener);
      return this;
    },
    /**
     * Clean any references when a worker is ending.
     */
    cleanUp: function() {
      this.streamInfo = this.generatedError = this.extraStreamInfo = null;
      this._listeners = [];
    },
    /**
     * Trigger an event. This will call registered callback with the provided arg.
     * @param {String} name the name of the event (data, end, error)
     * @param {Object} arg the argument to call the callback with.
     */
    emit: function(name2, arg) {
      if (this._listeners[name2]) {
        for (var i6 = 0; i6 < this._listeners[name2].length; i6++) {
          this._listeners[name2][i6].call(this, arg);
        }
      }
    },
    /**
     * Chain a worker with an other.
     * @param {Worker} next the worker receiving events from the current one.
     * @return {worker} the next worker for chainability
     */
    pipe: function(next) {
      return next.registerPrevious(this);
    },
    /**
     * Same as `pipe` in the other direction.
     * Using an API with `pipe(next)` is very easy.
     * Implementing the API with the point of view of the next one registering
     * a source is easier, see the ZipFileWorker.
     * @param {Worker} previous the previous worker, sending events to this one
     * @return {Worker} the current worker for chainability
     */
    registerPrevious: function(previous) {
      if (this.isLocked) {
        throw new Error("The stream '" + this + "' has already been used.");
      }
      this.streamInfo = previous.streamInfo;
      this.mergeStreamInfo();
      this.previous = previous;
      var self2 = this;
      previous.on("data", function(chunk) {
        self2.processChunk(chunk);
      });
      previous.on("end", function() {
        self2.end();
      });
      previous.on("error", function(e5) {
        self2.error(e5);
      });
      return this;
    },
    /**
     * Pause the stream so it doesn't send events anymore.
     * @return {Boolean} true if this call paused the worker, false otherwise.
     */
    pause: function() {
      if (this.isPaused || this.isFinished) {
        return false;
      }
      this.isPaused = true;
      if (this.previous) {
        this.previous.pause();
      }
      return true;
    },
    /**
     * Resume a paused stream.
     * @return {Boolean} true if this call resumed the worker, false otherwise.
     */
    resume: function() {
      if (!this.isPaused || this.isFinished) {
        return false;
      }
      this.isPaused = false;
      var withError = false;
      if (this.generatedError) {
        this.error(this.generatedError);
        withError = true;
      }
      if (this.previous) {
        this.previous.resume();
      }
      return !withError;
    },
    /**
     * Flush any remaining bytes as the stream is ending.
     */
    flush: function() {
    },
    /**
     * Process a chunk. This is usually the method overridden.
     * @param {Object} chunk the chunk to process.
     */
    processChunk: function(chunk) {
      this.push(chunk);
    },
    /**
     * Add a key/value to be added in the workers chain streamInfo once activated.
     * @param {String} key the key to use
     * @param {Object} value the associated value
     * @return {Worker} the current worker for chainability
     */
    withStreamInfo: function(key, value) {
      this.extraStreamInfo[key] = value;
      this.mergeStreamInfo();
      return this;
    },
    /**
     * Merge this worker's streamInfo into the chain's streamInfo.
     */
    mergeStreamInfo: function() {
      for (var key in this.extraStreamInfo) {
        if (!this.extraStreamInfo.hasOwnProperty(key)) {
          continue;
        }
        this.streamInfo[key] = this.extraStreamInfo[key];
      }
    },
    /**
     * Lock the stream to prevent further updates on the workers chain.
     * After calling this method, all calls to pipe will fail.
     */
    lock: function() {
      if (this.isLocked) {
        throw new Error("The stream '" + this + "' has already been used.");
      }
      this.isLocked = true;
      if (this.previous) {
        this.previous.lock();
      }
    },
    /**
     *
     * Pretty print the workers chain.
     */
    toString: function() {
      var me2 = "Worker " + this.name;
      if (this.previous) {
        return this.previous + " -> " + me2;
      } else {
        return me2;
      }
    }
  };
  exports$52 = GenericWorker;
  return exports$52;
}
function dew$62() {
  if (_dewExec$62) return exports$62;
  _dewExec$62 = true;
  var utils6 = dew$42();
  var support = dew6();
  var nodejsUtils = dew$23();
  var GenericWorker = dew$52();
  var _utf8len2 = new Array(256);
  for (var i6 = 0; i6 < 256; i6++) {
    _utf8len2[i6] = i6 >= 252 ? 6 : i6 >= 248 ? 5 : i6 >= 240 ? 4 : i6 >= 224 ? 3 : i6 >= 192 ? 2 : 1;
  }
  _utf8len2[254] = _utf8len2[254] = 1;
  var string2buf2 = function(str3) {
    var buf, c6, c22, m_pos, i7, str_len = str3.length, buf_len = 0;
    for (m_pos = 0; m_pos < str_len; m_pos++) {
      c6 = str3.charCodeAt(m_pos);
      if ((c6 & 64512) === 55296 && m_pos + 1 < str_len) {
        c22 = str3.charCodeAt(m_pos + 1);
        if ((c22 & 64512) === 56320) {
          c6 = 65536 + (c6 - 55296 << 10) + (c22 - 56320);
          m_pos++;
        }
      }
      buf_len += c6 < 128 ? 1 : c6 < 2048 ? 2 : c6 < 65536 ? 3 : 4;
    }
    if (support.uint8array) {
      buf = new Uint8Array(buf_len);
    } else {
      buf = new Array(buf_len);
    }
    for (i7 = 0, m_pos = 0; i7 < buf_len; m_pos++) {
      c6 = str3.charCodeAt(m_pos);
      if ((c6 & 64512) === 55296 && m_pos + 1 < str_len) {
        c22 = str3.charCodeAt(m_pos + 1);
        if ((c22 & 64512) === 56320) {
          c6 = 65536 + (c6 - 55296 << 10) + (c22 - 56320);
          m_pos++;
        }
      }
      if (c6 < 128) {
        buf[i7++] = c6;
      } else if (c6 < 2048) {
        buf[i7++] = 192 | c6 >>> 6;
        buf[i7++] = 128 | c6 & 63;
      } else if (c6 < 65536) {
        buf[i7++] = 224 | c6 >>> 12;
        buf[i7++] = 128 | c6 >>> 6 & 63;
        buf[i7++] = 128 | c6 & 63;
      } else {
        buf[i7++] = 240 | c6 >>> 18;
        buf[i7++] = 128 | c6 >>> 12 & 63;
        buf[i7++] = 128 | c6 >>> 6 & 63;
        buf[i7++] = 128 | c6 & 63;
      }
    }
    return buf;
  };
  var utf8border2 = function(buf, max) {
    var pos;
    max = max || buf.length;
    if (max > buf.length) {
      max = buf.length;
    }
    pos = max - 1;
    while (pos >= 0 && (buf[pos] & 192) === 128) {
      pos--;
    }
    if (pos < 0) {
      return max;
    }
    if (pos === 0) {
      return max;
    }
    return pos + _utf8len2[buf[pos]] > max ? pos : max;
  };
  var buf2string2 = function(buf) {
    var str3, i7, out, c6, c_len;
    var len = buf.length;
    var utf16buf = new Array(len * 2);
    for (out = 0, i7 = 0; i7 < len; ) {
      c6 = buf[i7++];
      if (c6 < 128) {
        utf16buf[out++] = c6;
        continue;
      }
      c_len = _utf8len2[c6];
      if (c_len > 4) {
        utf16buf[out++] = 65533;
        i7 += c_len - 1;
        continue;
      }
      c6 &= c_len === 2 ? 31 : c_len === 3 ? 15 : 7;
      while (c_len > 1 && i7 < len) {
        c6 = c6 << 6 | buf[i7++] & 63;
        c_len--;
      }
      if (c_len > 1) {
        utf16buf[out++] = 65533;
        continue;
      }
      if (c6 < 65536) {
        utf16buf[out++] = c6;
      } else {
        c6 -= 65536;
        utf16buf[out++] = 55296 | c6 >> 10 & 1023;
        utf16buf[out++] = 56320 | c6 & 1023;
      }
    }
    if (utf16buf.length !== out) {
      if (utf16buf.subarray) {
        utf16buf = utf16buf.subarray(0, out);
      } else {
        utf16buf.length = out;
      }
    }
    return utils6.applyFromCharCode(utf16buf);
  };
  exports$62.utf8encode = function utf8encode(str3) {
    if (support.nodebuffer) {
      return nodejsUtils.newBufferFrom(str3, "utf-8");
    }
    return string2buf2(str3);
  };
  exports$62.utf8decode = function utf8decode(buf) {
    if (support.nodebuffer) {
      return utils6.transformTo("nodebuffer", buf).toString("utf-8");
    }
    buf = utils6.transformTo(support.uint8array ? "uint8array" : "array", buf);
    return buf2string2(buf);
  };
  function Utf8DecodeWorker() {
    GenericWorker.call(this, "utf-8 decode");
    this.leftOver = null;
  }
  utils6.inherits(Utf8DecodeWorker, GenericWorker);
  Utf8DecodeWorker.prototype.processChunk = function(chunk) {
    var data3 = utils6.transformTo(support.uint8array ? "uint8array" : "array", chunk.data);
    if (this.leftOver && this.leftOver.length) {
      if (support.uint8array) {
        var previousData = data3;
        data3 = new Uint8Array(previousData.length + this.leftOver.length);
        data3.set(this.leftOver, 0);
        data3.set(previousData, this.leftOver.length);
      } else {
        data3 = this.leftOver.concat(data3);
      }
      this.leftOver = null;
    }
    var nextBoundary = utf8border2(data3);
    var usableData = data3;
    if (nextBoundary !== data3.length) {
      if (support.uint8array) {
        usableData = data3.subarray(0, nextBoundary);
        this.leftOver = data3.subarray(nextBoundary, data3.length);
      } else {
        usableData = data3.slice(0, nextBoundary);
        this.leftOver = data3.slice(nextBoundary, data3.length);
      }
    }
    this.push({
      data: exports$62.utf8decode(usableData),
      meta: chunk.meta
    });
  };
  Utf8DecodeWorker.prototype.flush = function() {
    if (this.leftOver && this.leftOver.length) {
      this.push({
        data: exports$62.utf8decode(this.leftOver),
        meta: {}
      });
      this.leftOver = null;
    }
  };
  exports$62.Utf8DecodeWorker = Utf8DecodeWorker;
  function Utf8EncodeWorker() {
    GenericWorker.call(this, "utf-8 encode");
  }
  utils6.inherits(Utf8EncodeWorker, GenericWorker);
  Utf8EncodeWorker.prototype.processChunk = function(chunk) {
    this.push({
      data: exports$62.utf8encode(chunk.data),
      meta: chunk.meta
    });
  };
  exports$62.Utf8EncodeWorker = Utf8EncodeWorker;
  return exports$62;
}
function dew$72() {
  if (_dewExec$72) return exports$72;
  _dewExec$72 = true;
  var GenericWorker = dew$52();
  var utils6 = dew$42();
  function ConvertWorker(destType) {
    GenericWorker.call(this, "ConvertWorker to " + destType);
    this.destType = destType;
  }
  utils6.inherits(ConvertWorker, GenericWorker);
  ConvertWorker.prototype.processChunk = function(chunk) {
    this.push({
      data: utils6.transformTo(this.destType, chunk.data),
      meta: chunk.meta
    });
  };
  exports$72 = ConvertWorker;
  return exports$72;
}
function dew$82() {
  if (_dewExec$82) return exports$82;
  _dewExec$82 = true;
  var Readable2 = dew4().Readable;
  var utils6 = dew$42();
  utils6.inherits(NodejsStreamOutputAdapter, Readable2);
  function NodejsStreamOutputAdapter(helper2, options, updateCb) {
    Readable2.call(this, options);
    this._helper = helper2;
    var self2 = this;
    helper2.on("data", function(data3, meta) {
      if (!self2.push(data3)) {
        self2._helper.pause();
      }
      if (updateCb) {
        updateCb(meta);
      }
    }).on("error", function(e5) {
      self2.emit("error", e5);
    }).on("end", function() {
      self2.push(null);
    });
  }
  NodejsStreamOutputAdapter.prototype._read = function() {
    this._helper.resume();
  };
  exports$82 = NodejsStreamOutputAdapter;
  return exports$82;
}
function dew$92() {
  if (_dewExec$92) return exports$92;
  _dewExec$92 = true;
  var Buffer4 = exports5.Buffer;
  var utils6 = dew$42();
  var ConvertWorker = dew$72();
  var GenericWorker = dew$52();
  var base642 = dew$13();
  var support = dew6();
  var external = dew$32();
  var NodejsStreamOutputAdapter = null;
  if (support.nodestream) {
    try {
      NodejsStreamOutputAdapter = dew$82();
    } catch (e5) {
    }
  }
  function transformZipOutput(type4, content, mimeType) {
    switch (type4) {
      case "blob":
        return utils6.newBlob(utils6.transformTo("arraybuffer", content), mimeType);
      case "base64":
        return base642.encode(content);
      default:
        return utils6.transformTo(type4, content);
    }
  }
  function concat3(type4, dataArray) {
    var i6, index2 = 0, res = null, totalLength = 0;
    for (i6 = 0; i6 < dataArray.length; i6++) {
      totalLength += dataArray[i6].length;
    }
    switch (type4) {
      case "string":
        return dataArray.join("");
      case "array":
        return Array.prototype.concat.apply([], dataArray);
      case "uint8array":
        res = new Uint8Array(totalLength);
        for (i6 = 0; i6 < dataArray.length; i6++) {
          res.set(dataArray[i6], index2);
          index2 += dataArray[i6].length;
        }
        return res;
      case "nodebuffer":
        return Buffer4.concat(dataArray);
      default:
        throw new Error("concat : unsupported type '" + type4 + "'");
    }
  }
  function accumulate(helper2, updateCallback) {
    return new external.Promise(function(resolve16, reject2) {
      var dataArray = [];
      var chunkType = helper2._internalType, resultType = helper2._outputType, mimeType = helper2._mimeType;
      helper2.on("data", function(data3, meta) {
        dataArray.push(data3);
        if (updateCallback) {
          updateCallback(meta);
        }
      }).on("error", function(err2) {
        dataArray = [];
        reject2(err2);
      }).on("end", function() {
        try {
          var result2 = transformZipOutput(resultType, concat3(chunkType, dataArray), mimeType);
          resolve16(result2);
        } catch (e5) {
          reject2(e5);
        }
        dataArray = [];
      }).resume();
    });
  }
  function StreamHelper(worker, outputType, mimeType) {
    var internalType = outputType;
    switch (outputType) {
      case "blob":
      case "arraybuffer":
        internalType = "uint8array";
        break;
      case "base64":
        internalType = "string";
        break;
    }
    try {
      this._internalType = internalType;
      this._outputType = outputType;
      this._mimeType = mimeType;
      utils6.checkSupport(internalType);
      this._worker = worker.pipe(new ConvertWorker(internalType));
      worker.lock();
    } catch (e5) {
      this._worker = new GenericWorker("error");
      this._worker.error(e5);
    }
  }
  StreamHelper.prototype = {
    /**
     * Listen a StreamHelper, accumulate its content and concatenate it into a
     * complete block.
     * @param {Function} updateCb the update callback.
     * @return Promise the promise for the accumulation.
     */
    accumulate: function(updateCb) {
      return accumulate(this, updateCb);
    },
    /**
     * Add a listener on an event triggered on a stream.
     * @param {String} evt the name of the event
     * @param {Function} fn the listener
     * @return {StreamHelper} the current helper.
     */
    on: function(evt, fn) {
      var self2 = this;
      if (evt === "data") {
        this._worker.on(evt, function(chunk) {
          fn.call(self2, chunk.data, chunk.meta);
        });
      } else {
        this._worker.on(evt, function() {
          utils6.delay(fn, arguments, self2);
        });
      }
      return this;
    },
    /**
     * Resume the flow of chunks.
     * @return {StreamHelper} the current helper.
     */
    resume: function() {
      utils6.delay(this._worker.resume, [], this._worker);
      return this;
    },
    /**
     * Pause the flow of chunks.
     * @return {StreamHelper} the current helper.
     */
    pause: function() {
      this._worker.pause();
      return this;
    },
    /**
     * Return a nodejs stream for this helper.
     * @param {Function} updateCb the update callback.
     * @return {NodejsStreamOutputAdapter} the nodejs stream.
     */
    toNodejsStream: function(updateCb) {
      utils6.checkSupport("nodestream");
      if (this._outputType !== "nodebuffer") {
        throw new Error(this._outputType + " is not supported by this method");
      }
      return new NodejsStreamOutputAdapter(this, {
        objectMode: this._outputType !== "nodebuffer"
      }, updateCb);
    }
  };
  exports$92 = StreamHelper;
  return exports$92;
}
function dew$a2() {
  if (_dewExec$a2) return exports$a2;
  _dewExec$a2 = true;
  exports$a2.base64 = false;
  exports$a2.binary = false;
  exports$a2.dir = false;
  exports$a2.createFolders = true;
  exports$a2.date = null;
  exports$a2.compression = null;
  exports$a2.compressionOptions = null;
  exports$a2.comment = null;
  exports$a2.unixPermissions = null;
  exports$a2.dosPermissions = null;
  return exports$a2;
}
function dew$b2() {
  if (_dewExec$b2) return exports$b2;
  _dewExec$b2 = true;
  var utils6 = dew$42();
  var GenericWorker = dew$52();
  var DEFAULT_BLOCK_SIZE = 16 * 1024;
  function DataWorker(dataP) {
    GenericWorker.call(this, "DataWorker");
    var self2 = this;
    this.dataIsReady = false;
    this.index = 0;
    this.max = 0;
    this.data = null;
    this.type = "";
    this._tickScheduled = false;
    dataP.then(function(data3) {
      self2.dataIsReady = true;
      self2.data = data3;
      self2.max = data3 && data3.length || 0;
      self2.type = utils6.getTypeOf(data3);
      if (!self2.isPaused) {
        self2._tickAndRepeat();
      }
    }, function(e5) {
      self2.error(e5);
    });
  }
  utils6.inherits(DataWorker, GenericWorker);
  DataWorker.prototype.cleanUp = function() {
    GenericWorker.prototype.cleanUp.call(this);
    this.data = null;
  };
  DataWorker.prototype.resume = function() {
    if (!GenericWorker.prototype.resume.call(this)) {
      return false;
    }
    if (!this._tickScheduled && this.dataIsReady) {
      this._tickScheduled = true;
      utils6.delay(this._tickAndRepeat, [], this);
    }
    return true;
  };
  DataWorker.prototype._tickAndRepeat = function() {
    this._tickScheduled = false;
    if (this.isPaused || this.isFinished) {
      return;
    }
    this._tick();
    if (!this.isFinished) {
      utils6.delay(this._tickAndRepeat, [], this);
      this._tickScheduled = true;
    }
  };
  DataWorker.prototype._tick = function() {
    if (this.isPaused || this.isFinished) {
      return false;
    }
    var size = DEFAULT_BLOCK_SIZE;
    var data3 = null, nextIndex3 = Math.min(this.max, this.index + size);
    if (this.index >= this.max) {
      return this.end();
    } else {
      switch (this.type) {
        case "string":
          data3 = this.data.substring(this.index, nextIndex3);
          break;
        case "uint8array":
          data3 = this.data.subarray(this.index, nextIndex3);
          break;
        case "array":
        case "nodebuffer":
          data3 = this.data.slice(this.index, nextIndex3);
          break;
      }
      this.index = nextIndex3;
      return this.push({
        data: data3,
        meta: {
          percent: this.max ? this.index / this.max * 100 : 0
        }
      });
    }
  };
  exports$b2 = DataWorker;
  return exports$b2;
}
function dew$c2() {
  if (_dewExec$c2) return exports$c2;
  _dewExec$c2 = true;
  var utils6 = dew$42();
  var GenericWorker = dew$52();
  function DataLengthProbe(propName) {
    GenericWorker.call(this, "DataLengthProbe for " + propName);
    this.propName = propName;
    this.withStreamInfo(propName, 0);
  }
  utils6.inherits(DataLengthProbe, GenericWorker);
  DataLengthProbe.prototype.processChunk = function(chunk) {
    if (chunk) {
      var length = this.streamInfo[this.propName] || 0;
      this.streamInfo[this.propName] = length + chunk.data.length;
    }
    GenericWorker.prototype.processChunk.call(this, chunk);
  };
  exports$c2 = DataLengthProbe;
  return exports$c2;
}
function dew$d2() {
  if (_dewExec$d2) return exports$d2;
  _dewExec$d2 = true;
  var utils6 = dew$42();
  function makeTable2() {
    var c6, table = [];
    for (var n5 = 0; n5 < 256; n5++) {
      c6 = n5;
      for (var k3 = 0; k3 < 8; k3++) {
        c6 = c6 & 1 ? 3988292384 ^ c6 >>> 1 : c6 >>> 1;
      }
      table[n5] = c6;
    }
    return table;
  }
  var crcTable2 = makeTable2();
  function crc324(crc, buf, len, pos) {
    var t5 = crcTable2, end = pos + len;
    crc = crc ^ -1;
    for (var i6 = pos; i6 < end; i6++) {
      crc = crc >>> 8 ^ t5[(crc ^ buf[i6]) & 255];
    }
    return crc ^ -1;
  }
  function crc32str(crc, str3, len, pos) {
    var t5 = crcTable2, end = pos + len;
    crc = crc ^ -1;
    for (var i6 = pos; i6 < end; i6++) {
      crc = crc >>> 8 ^ t5[(crc ^ str3.charCodeAt(i6)) & 255];
    }
    return crc ^ -1;
  }
  exports$d2 = function crc32wrapper(input, crc) {
    if (typeof input === "undefined" || !input.length) {
      return 0;
    }
    var isArray6 = utils6.getTypeOf(input) !== "string";
    if (isArray6) {
      return crc324(crc | 0, input, input.length, 0);
    } else {
      return crc32str(crc | 0, input, input.length, 0);
    }
  };
  return exports$d2;
}
function dew$e2() {
  if (_dewExec$e2) return exports$e2;
  _dewExec$e2 = true;
  var GenericWorker = dew$52();
  var crc324 = dew$d2();
  var utils6 = dew$42();
  function Crc32Probe() {
    GenericWorker.call(this, "Crc32Probe");
    this.withStreamInfo("crc32", 0);
  }
  utils6.inherits(Crc32Probe, GenericWorker);
  Crc32Probe.prototype.processChunk = function(chunk) {
    this.streamInfo.crc32 = crc324(chunk.data, this.streamInfo.crc32 || 0);
    this.push(chunk);
  };
  exports$e2 = Crc32Probe;
  return exports$e2;
}
function dew$f2() {
  if (_dewExec$f2) return exports$f2;
  _dewExec$f2 = true;
  var external = dew$32();
  var DataWorker = dew$b2();
  var DataLengthProbe = dew$c2();
  var Crc32Probe = dew$e2();
  var DataLengthProbe = dew$c2();
  function CompressedObject(compressedSize, uncompressedSize, crc324, compression, data3) {
    this.compressedSize = compressedSize;
    this.uncompressedSize = uncompressedSize;
    this.crc32 = crc324;
    this.compression = compression;
    this.compressedContent = data3;
  }
  CompressedObject.prototype = {
    /**
     * Create a worker to get the uncompressed content.
     * @return {GenericWorker} the worker.
     */
    getContentWorker: function() {
      var worker = new DataWorker(external.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new DataLengthProbe("data_length"));
      var that = this;
      worker.on("end", function() {
        if (this.streamInfo["data_length"] !== that.uncompressedSize) {
          throw new Error("Bug : uncompressed data size mismatch");
        }
      });
      return worker;
    },
    /**
     * Create a worker to get the compressed content.
     * @return {GenericWorker} the worker.
     */
    getCompressedWorker: function() {
      return new DataWorker(external.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize", this.compressedSize).withStreamInfo("uncompressedSize", this.uncompressedSize).withStreamInfo("crc32", this.crc32).withStreamInfo("compression", this.compression);
    }
  };
  CompressedObject.createWorkerFrom = function(uncompressedWorker, compression, compressionOptions) {
    return uncompressedWorker.pipe(new Crc32Probe()).pipe(new DataLengthProbe("uncompressedSize")).pipe(compression.compressWorker(compressionOptions)).pipe(new DataLengthProbe("compressedSize")).withStreamInfo("compression", compression);
  };
  exports$f2 = CompressedObject;
  return exports$f2;
}
function dew$g2() {
  if (_dewExec$g2) return exports$g2;
  _dewExec$g2 = true;
  var StreamHelper = dew$92();
  var DataWorker = dew$b2();
  var utf8 = dew$62();
  var CompressedObject = dew$f2();
  var GenericWorker = dew$52();
  var ZipObject = function(name2, data3, options) {
    this.name = name2;
    this.dir = options.dir;
    this.date = options.date;
    this.comment = options.comment;
    this.unixPermissions = options.unixPermissions;
    this.dosPermissions = options.dosPermissions;
    this._data = data3;
    this._dataBinary = options.binary;
    this.options = {
      compression: options.compression,
      compressionOptions: options.compressionOptions
    };
  };
  ZipObject.prototype = {
    /**
     * Create an internal stream for the content of this object.
     * @param {String} type the type of each chunk.
     * @return StreamHelper the stream.
     */
    internalStream: function(type4) {
      var result2 = null, outputType = "string";
      try {
        if (!type4) {
          throw new Error("No output type specified.");
        }
        outputType = type4.toLowerCase();
        var askUnicodeString = outputType === "string" || outputType === "text";
        if (outputType === "binarystring" || outputType === "text") {
          outputType = "string";
        }
        result2 = this._decompressWorker();
        var isUnicodeString = !this._dataBinary;
        if (isUnicodeString && !askUnicodeString) {
          result2 = result2.pipe(new utf8.Utf8EncodeWorker());
        }
        if (!isUnicodeString && askUnicodeString) {
          result2 = result2.pipe(new utf8.Utf8DecodeWorker());
        }
      } catch (e5) {
        result2 = new GenericWorker("error");
        result2.error(e5);
      }
      return new StreamHelper(result2, outputType, "");
    },
    /**
     * Prepare the content in the asked type.
     * @param {String} type the type of the result.
     * @param {Function} onUpdate a function to call on each internal update.
     * @return Promise the promise of the result.
     */
    async: function(type4, onUpdate) {
      return this.internalStream(type4).accumulate(onUpdate);
    },
    /**
     * Prepare the content as a nodejs stream.
     * @param {String} type the type of each chunk.
     * @param {Function} onUpdate a function to call on each internal update.
     * @return Stream the stream.
     */
    nodeStream: function(type4, onUpdate) {
      return this.internalStream(type4 || "nodebuffer").toNodejsStream(onUpdate);
    },
    /**
     * Return a worker for the compressed content.
     * @private
     * @param {Object} compression the compression object to use.
     * @param {Object} compressionOptions the options to use when compressing.
     * @return Worker the worker.
     */
    _compressWorker: function(compression, compressionOptions) {
      if (this._data instanceof CompressedObject && this._data.compression.magic === compression.magic) {
        return this._data.getCompressedWorker();
      } else {
        var result2 = this._decompressWorker();
        if (!this._dataBinary) {
          result2 = result2.pipe(new utf8.Utf8EncodeWorker());
        }
        return CompressedObject.createWorkerFrom(result2, compression, compressionOptions);
      }
    },
    /**
     * Return a worker for the decompressed content.
     * @private
     * @return Worker the worker.
     */
    _decompressWorker: function() {
      if (this._data instanceof CompressedObject) {
        return this._data.getContentWorker();
      } else if (this._data instanceof GenericWorker) {
        return this._data;
      } else {
        return new DataWorker(this._data);
      }
    }
  };
  var removedMethods = ["asText", "asBinary", "asNodeBuffer", "asUint8Array", "asArrayBuffer"];
  var removedFn = function() {
    throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
  };
  for (var i6 = 0; i6 < removedMethods.length; i6++) {
    ZipObject.prototype[removedMethods[i6]] = removedFn;
  }
  exports$g2 = ZipObject;
  return exports$g2;
}
function dew$h() {
  if (_dewExec$h) return exports$h;
  _dewExec$h = true;
  var USE_TYPEDARRAY = typeof Uint8Array !== "undefined" && typeof Uint16Array !== "undefined" && typeof Uint32Array !== "undefined";
  var pako2 = npm_pako_1_0_default;
  var utils6 = dew$42();
  var GenericWorker = dew$52();
  var ARRAY_TYPE = USE_TYPEDARRAY ? "uint8array" : "array";
  exports$h.magic = "\b\0";
  function FlateWorker(action, options) {
    GenericWorker.call(this, "FlateWorker/" + action);
    this._pako = null;
    this._pakoAction = action;
    this._pakoOptions = options;
    this.meta = {};
  }
  utils6.inherits(FlateWorker, GenericWorker);
  FlateWorker.prototype.processChunk = function(chunk) {
    this.meta = chunk.meta;
    if (this._pako === null) {
      this._createPako();
    }
    this._pako.push(utils6.transformTo(ARRAY_TYPE, chunk.data), false);
  };
  FlateWorker.prototype.flush = function() {
    GenericWorker.prototype.flush.call(this);
    if (this._pako === null) {
      this._createPako();
    }
    this._pako.push([], true);
  };
  FlateWorker.prototype.cleanUp = function() {
    GenericWorker.prototype.cleanUp.call(this);
    this._pako = null;
  };
  FlateWorker.prototype._createPako = function() {
    this._pako = new pako2[this._pakoAction]({
      raw: true,
      level: this._pakoOptions.level || -1
      // default compression
    });
    var self2 = this;
    this._pako.onData = function(data3) {
      self2.push({
        data: data3,
        meta: self2.meta
      });
    };
  };
  exports$h.compressWorker = function(compressionOptions) {
    return new FlateWorker("Deflate", compressionOptions);
  };
  exports$h.uncompressWorker = function() {
    return new FlateWorker("Inflate", {});
  };
  return exports$h;
}
function dew$i() {
  if (_dewExec$i) return exports$i;
  _dewExec$i = true;
  var GenericWorker = dew$52();
  exports$i.STORE = {
    magic: "\0\0",
    compressWorker: function(compressionOptions) {
      return new GenericWorker("STORE compression");
    },
    uncompressWorker: function() {
      return new GenericWorker("STORE decompression");
    }
  };
  exports$i.DEFLATE = dew$h();
  return exports$i;
}
function dew$j() {
  if (_dewExec$j) return exports$j;
  _dewExec$j = true;
  exports$j.LOCAL_FILE_HEADER = "PK";
  exports$j.CENTRAL_FILE_HEADER = "PK";
  exports$j.CENTRAL_DIRECTORY_END = "PK";
  exports$j.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x07";
  exports$j.ZIP64_CENTRAL_DIRECTORY_END = "PK";
  exports$j.DATA_DESCRIPTOR = "PK\x07\b";
  return exports$j;
}
function dew$k() {
  if (_dewExec$k) return exports$k;
  _dewExec$k = true;
  var utils6 = dew$42();
  var GenericWorker = dew$52();
  var utf8 = dew$62();
  var crc324 = dew$d2();
  var signature = dew$j();
  var decToHex = function(dec, bytes) {
    var hex = "", i6;
    for (i6 = 0; i6 < bytes; i6++) {
      hex += String.fromCharCode(dec & 255);
      dec = dec >>> 8;
    }
    return hex;
  };
  var generateUnixExternalFileAttr = function(unixPermissions, isDir) {
    var result2 = unixPermissions;
    if (!unixPermissions) {
      result2 = isDir ? 16893 : 33204;
    }
    return (result2 & 65535) << 16;
  };
  var generateDosExternalFileAttr = function(dosPermissions, isDir) {
    return (dosPermissions || 0) & 63;
  };
  var generateZipParts = function(streamInfo, streamedContent, streamingEnded, offset3, platform2, encodeFileName) {
    var file = streamInfo["file"], compression = streamInfo["compression"], useCustomEncoding = encodeFileName !== utf8.utf8encode, encodedFileName = utils6.transformTo("string", encodeFileName(file.name)), utfEncodedFileName = utils6.transformTo("string", utf8.utf8encode(file.name)), comment = file.comment, encodedComment = utils6.transformTo("string", encodeFileName(comment)), utfEncodedComment = utils6.transformTo("string", utf8.utf8encode(comment)), useUTF8ForFileName = utfEncodedFileName.length !== file.name.length, useUTF8ForComment = utfEncodedComment.length !== comment.length, dosTime, dosDate, extraFields = "", unicodePathExtraField = "", unicodeCommentExtraField = "", dir = file.dir, date = file.date;
    var dataInfo = {
      crc32: 0,
      compressedSize: 0,
      uncompressedSize: 0
    };
    if (!streamedContent || streamingEnded) {
      dataInfo.crc32 = streamInfo["crc32"];
      dataInfo.compressedSize = streamInfo["compressedSize"];
      dataInfo.uncompressedSize = streamInfo["uncompressedSize"];
    }
    var bitflag = 0;
    if (streamedContent) {
      bitflag |= 8;
    }
    if (!useCustomEncoding && (useUTF8ForFileName || useUTF8ForComment)) {
      bitflag |= 2048;
    }
    var extFileAttr = 0;
    var versionMadeBy = 0;
    if (dir) {
      extFileAttr |= 16;
    }
    if (platform2 === "UNIX") {
      versionMadeBy = 798;
      extFileAttr |= generateUnixExternalFileAttr(file.unixPermissions, dir);
    } else {
      versionMadeBy = 20;
      extFileAttr |= generateDosExternalFileAttr(file.dosPermissions, dir);
    }
    dosTime = date.getUTCHours();
    dosTime = dosTime << 6;
    dosTime = dosTime | date.getUTCMinutes();
    dosTime = dosTime << 5;
    dosTime = dosTime | date.getUTCSeconds() / 2;
    dosDate = date.getUTCFullYear() - 1980;
    dosDate = dosDate << 4;
    dosDate = dosDate | date.getUTCMonth() + 1;
    dosDate = dosDate << 5;
    dosDate = dosDate | date.getUTCDate();
    if (useUTF8ForFileName) {
      unicodePathExtraField = // Version
      decToHex(1, 1) + // NameCRC32
      decToHex(crc324(encodedFileName), 4) + // UnicodeName
      utfEncodedFileName;
      extraFields += // Info-ZIP Unicode Path Extra Field
      "up" + // size
      decToHex(unicodePathExtraField.length, 2) + // content
      unicodePathExtraField;
    }
    if (useUTF8ForComment) {
      unicodeCommentExtraField = // Version
      decToHex(1, 1) + // CommentCRC32
      decToHex(crc324(encodedComment), 4) + // UnicodeName
      utfEncodedComment;
      extraFields += // Info-ZIP Unicode Path Extra Field
      "uc" + // size
      decToHex(unicodeCommentExtraField.length, 2) + // content
      unicodeCommentExtraField;
    }
    var header = "";
    header += "\n\0";
    header += decToHex(bitflag, 2);
    header += compression.magic;
    header += decToHex(dosTime, 2);
    header += decToHex(dosDate, 2);
    header += decToHex(dataInfo.crc32, 4);
    header += decToHex(dataInfo.compressedSize, 4);
    header += decToHex(dataInfo.uncompressedSize, 4);
    header += decToHex(encodedFileName.length, 2);
    header += decToHex(extraFields.length, 2);
    var fileRecord = signature.LOCAL_FILE_HEADER + header + encodedFileName + extraFields;
    var dirRecord = signature.CENTRAL_FILE_HEADER + // version made by (00: DOS)
    decToHex(versionMadeBy, 2) + // file header (common to file and central directory)
    header + // file comment length
    decToHex(encodedComment.length, 2) + // disk number start
    "\0\0\0\0" + // external file attributes
    decToHex(extFileAttr, 4) + // relative offset of local header
    decToHex(offset3, 4) + // file name
    encodedFileName + // extra field
    extraFields + // file comment
    encodedComment;
    return {
      fileRecord,
      dirRecord
    };
  };
  var generateCentralDirectoryEnd = function(entriesCount, centralDirLength, localDirLength, comment, encodeFileName) {
    var dirEnd = "";
    var encodedComment = utils6.transformTo("string", encodeFileName(comment));
    dirEnd = signature.CENTRAL_DIRECTORY_END + // number of this disk
    "\0\0\0\0" + // total number of entries in the central directory on this disk
    decToHex(entriesCount, 2) + // total number of entries in the central directory
    decToHex(entriesCount, 2) + // size of the central directory   4 bytes
    decToHex(centralDirLength, 4) + // offset of start of central directory with respect to the starting disk number
    decToHex(localDirLength, 4) + // .ZIP file comment length
    decToHex(encodedComment.length, 2) + // .ZIP file comment
    encodedComment;
    return dirEnd;
  };
  var generateDataDescriptors = function(streamInfo) {
    var descriptor = "";
    descriptor = signature.DATA_DESCRIPTOR + // crc-32                          4 bytes
    decToHex(streamInfo["crc32"], 4) + // compressed size                 4 bytes
    decToHex(streamInfo["compressedSize"], 4) + // uncompressed size               4 bytes
    decToHex(streamInfo["uncompressedSize"], 4);
    return descriptor;
  };
  function ZipFileWorker(streamFiles, comment, platform2, encodeFileName) {
    GenericWorker.call(this, "ZipFileWorker");
    this.bytesWritten = 0;
    this.zipComment = comment;
    this.zipPlatform = platform2;
    this.encodeFileName = encodeFileName;
    this.streamFiles = streamFiles;
    this.accumulate = false;
    this.contentBuffer = [];
    this.dirRecords = [];
    this.currentSourceOffset = 0;
    this.entriesCount = 0;
    this.currentFile = null;
    this._sources = [];
  }
  utils6.inherits(ZipFileWorker, GenericWorker);
  ZipFileWorker.prototype.push = function(chunk) {
    var currentFilePercent = chunk.meta.percent || 0;
    var entriesCount = this.entriesCount;
    var remainingFiles = this._sources.length;
    if (this.accumulate) {
      this.contentBuffer.push(chunk);
    } else {
      this.bytesWritten += chunk.data.length;
      GenericWorker.prototype.push.call(this, {
        data: chunk.data,
        meta: {
          currentFile: this.currentFile,
          percent: entriesCount ? (currentFilePercent + 100 * (entriesCount - remainingFiles - 1)) / entriesCount : 100
        }
      });
    }
  };
  ZipFileWorker.prototype.openedSource = function(streamInfo) {
    this.currentSourceOffset = this.bytesWritten;
    this.currentFile = streamInfo["file"].name;
    var streamedContent = this.streamFiles && !streamInfo["file"].dir;
    if (streamedContent) {
      var record = generateZipParts(streamInfo, streamedContent, false, this.currentSourceOffset, this.zipPlatform, this.encodeFileName);
      this.push({
        data: record.fileRecord,
        meta: {
          percent: 0
        }
      });
    } else {
      this.accumulate = true;
    }
  };
  ZipFileWorker.prototype.closedSource = function(streamInfo) {
    this.accumulate = false;
    var streamedContent = this.streamFiles && !streamInfo["file"].dir;
    var record = generateZipParts(streamInfo, streamedContent, true, this.currentSourceOffset, this.zipPlatform, this.encodeFileName);
    this.dirRecords.push(record.dirRecord);
    if (streamedContent) {
      this.push({
        data: generateDataDescriptors(streamInfo),
        meta: {
          percent: 100
        }
      });
    } else {
      this.push({
        data: record.fileRecord,
        meta: {
          percent: 0
        }
      });
      while (this.contentBuffer.length) {
        this.push(this.contentBuffer.shift());
      }
    }
    this.currentFile = null;
  };
  ZipFileWorker.prototype.flush = function() {
    var localDirLength = this.bytesWritten;
    for (var i6 = 0; i6 < this.dirRecords.length; i6++) {
      this.push({
        data: this.dirRecords[i6],
        meta: {
          percent: 100
        }
      });
    }
    var centralDirLength = this.bytesWritten - localDirLength;
    var dirEnd = generateCentralDirectoryEnd(this.dirRecords.length, centralDirLength, localDirLength, this.zipComment, this.encodeFileName);
    this.push({
      data: dirEnd,
      meta: {
        percent: 100
      }
    });
  };
  ZipFileWorker.prototype.prepareNextSource = function() {
    this.previous = this._sources.shift();
    this.openedSource(this.previous.streamInfo);
    if (this.isPaused) {
      this.previous.pause();
    } else {
      this.previous.resume();
    }
  };
  ZipFileWorker.prototype.registerPrevious = function(previous) {
    this._sources.push(previous);
    var self2 = this;
    previous.on("data", function(chunk) {
      self2.processChunk(chunk);
    });
    previous.on("end", function() {
      self2.closedSource(self2.previous.streamInfo);
      if (self2._sources.length) {
        self2.prepareNextSource();
      } else {
        self2.end();
      }
    });
    previous.on("error", function(e5) {
      self2.error(e5);
    });
    return this;
  };
  ZipFileWorker.prototype.resume = function() {
    if (!GenericWorker.prototype.resume.call(this)) {
      return false;
    }
    if (!this.previous && this._sources.length) {
      this.prepareNextSource();
      return true;
    }
    if (!this.previous && !this._sources.length && !this.generatedError) {
      this.end();
      return true;
    }
  };
  ZipFileWorker.prototype.error = function(e5) {
    var sources = this._sources;
    if (!GenericWorker.prototype.error.call(this, e5)) {
      return false;
    }
    for (var i6 = 0; i6 < sources.length; i6++) {
      try {
        sources[i6].error(e5);
      } catch (e6) {
      }
    }
    return true;
  };
  ZipFileWorker.prototype.lock = function() {
    GenericWorker.prototype.lock.call(this);
    var sources = this._sources;
    for (var i6 = 0; i6 < sources.length; i6++) {
      sources[i6].lock();
    }
  };
  exports$k = ZipFileWorker;
  return exports$k;
}
function dew$l() {
  if (_dewExec$l) return exports$l;
  _dewExec$l = true;
  var compressions = dew$i();
  var ZipFileWorker = dew$k();
  var getCompression = function(fileCompression, zipCompression) {
    var compressionName = fileCompression || zipCompression;
    var compression = compressions[compressionName];
    if (!compression) {
      throw new Error(compressionName + " is not a valid compression method !");
    }
    return compression;
  };
  exports$l.generateWorker = function(zip2, options, comment) {
    var zipFileWorker = new ZipFileWorker(options.streamFiles, comment, options.platform, options.encodeFileName);
    var entriesCount = 0;
    try {
      zip2.forEach(function(relativePath, file) {
        entriesCount++;
        var compression = getCompression(file.options.compression, options.compression);
        var compressionOptions = file.options.compressionOptions || options.compressionOptions || {};
        var dir = file.dir, date = file.date;
        file._compressWorker(compression, compressionOptions).withStreamInfo("file", {
          name: relativePath,
          dir,
          date,
          comment: file.comment || "",
          unixPermissions: file.unixPermissions,
          dosPermissions: file.dosPermissions
        }).pipe(zipFileWorker);
      });
      zipFileWorker.entriesCount = entriesCount;
    } catch (e5) {
      zipFileWorker.error(e5);
    }
    return zipFileWorker;
  };
  return exports$l;
}
function dew$m() {
  if (_dewExec$m) return exports$m;
  _dewExec$m = true;
  var utils6 = dew$42();
  var GenericWorker = dew$52();
  function NodejsStreamInputAdapter(filename, stream) {
    GenericWorker.call(this, "Nodejs stream input adapter for " + filename);
    this._upstreamEnded = false;
    this._bindStream(stream);
  }
  utils6.inherits(NodejsStreamInputAdapter, GenericWorker);
  NodejsStreamInputAdapter.prototype._bindStream = function(stream) {
    var self2 = this;
    this._stream = stream;
    stream.pause();
    stream.on("data", function(chunk) {
      self2.push({
        data: chunk,
        meta: {
          percent: 0
        }
      });
    }).on("error", function(e5) {
      if (self2.isPaused) {
        this.generatedError = e5;
      } else {
        self2.error(e5);
      }
    }).on("end", function() {
      if (self2.isPaused) {
        self2._upstreamEnded = true;
      } else {
        self2.end();
      }
    });
  };
  NodejsStreamInputAdapter.prototype.pause = function() {
    if (!GenericWorker.prototype.pause.call(this)) {
      return false;
    }
    this._stream.pause();
    return true;
  };
  NodejsStreamInputAdapter.prototype.resume = function() {
    if (!GenericWorker.prototype.resume.call(this)) {
      return false;
    }
    if (this._upstreamEnded) {
      this.end();
    } else {
      this._stream.resume();
    }
    return true;
  };
  exports$m = NodejsStreamInputAdapter;
  return exports$m;
}
function dew$n() {
  if (_dewExec$n) return exports$n;
  _dewExec$n = true;
  var utf8 = dew$62();
  var utils6 = dew$42();
  var GenericWorker = dew$52();
  var StreamHelper = dew$92();
  var defaults = dew$a2();
  var CompressedObject = dew$f2();
  var ZipObject = dew$g2();
  var generate = dew$l();
  var nodejsUtils = dew$23();
  var NodejsStreamInputAdapter = dew$m();
  var fileAdd = function(name2, data3, originalOptions) {
    var dataType = utils6.getTypeOf(data3), parent;
    var o5 = utils6.extend(originalOptions || {}, defaults);
    o5.date = o5.date || /* @__PURE__ */ new Date();
    if (o5.compression !== null) {
      o5.compression = o5.compression.toUpperCase();
    }
    if (typeof o5.unixPermissions === "string") {
      o5.unixPermissions = parseInt(o5.unixPermissions, 8);
    }
    if (o5.unixPermissions && o5.unixPermissions & 16384) {
      o5.dir = true;
    }
    if (o5.dosPermissions && o5.dosPermissions & 16) {
      o5.dir = true;
    }
    if (o5.dir) {
      name2 = forceTrailingSlash(name2);
    }
    if (o5.createFolders && (parent = parentFolder(name2))) {
      folderAdd.call(this, parent, true);
    }
    var isUnicodeString = dataType === "string" && o5.binary === false && o5.base64 === false;
    if (!originalOptions || typeof originalOptions.binary === "undefined") {
      o5.binary = !isUnicodeString;
    }
    var isCompressedEmpty = data3 instanceof CompressedObject && data3.uncompressedSize === 0;
    if (isCompressedEmpty || o5.dir || !data3 || data3.length === 0) {
      o5.base64 = false;
      o5.binary = true;
      data3 = "";
      o5.compression = "STORE";
      dataType = "string";
    }
    var zipObjectContent = null;
    if (data3 instanceof CompressedObject || data3 instanceof GenericWorker) {
      zipObjectContent = data3;
    } else if (nodejsUtils.isNode && nodejsUtils.isStream(data3)) {
      zipObjectContent = new NodejsStreamInputAdapter(name2, data3);
    } else {
      zipObjectContent = utils6.prepareContent(name2, data3, o5.binary, o5.optimizedBinaryString, o5.base64);
    }
    var object = new ZipObject(name2, zipObjectContent, o5);
    this.files[name2] = object;
  };
  var parentFolder = function(path3) {
    if (path3.slice(-1) === "/") {
      path3 = path3.substring(0, path3.length - 1);
    }
    var lastSlash = path3.lastIndexOf("/");
    return lastSlash > 0 ? path3.substring(0, lastSlash) : "";
  };
  var forceTrailingSlash = function(path3) {
    if (path3.slice(-1) !== "/") {
      path3 += "/";
    }
    return path3;
  };
  var folderAdd = function(name2, createFolders) {
    createFolders = typeof createFolders !== "undefined" ? createFolders : defaults.createFolders;
    name2 = forceTrailingSlash(name2);
    if (!this.files[name2]) {
      fileAdd.call(this, name2, null, {
        dir: true,
        createFolders
      });
    }
    return this.files[name2];
  };
  function isRegExp3(object) {
    return Object.prototype.toString.call(object) === "[object RegExp]";
  }
  var out = {
    /**
     * @see loadAsync
     */
    load: function() {
      throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
    },
    /**
     * Call a callback function for each entry at this folder level.
     * @param {Function} cb the callback function:
     * function (relativePath, file) {...}
     * It takes 2 arguments : the relative path and the file.
     */
    forEach: function(cb) {
      var filename, relativePath, file;
      for (filename in this.files) {
        if (!this.files.hasOwnProperty(filename)) {
          continue;
        }
        file = this.files[filename];
        relativePath = filename.slice(this.root.length, filename.length);
        if (relativePath && filename.slice(0, this.root.length) === this.root) {
          cb(relativePath, file);
        }
      }
    },
    /**
     * Filter nested files/folders with the specified function.
     * @param {Function} search the predicate to use :
     * function (relativePath, file) {...}
     * It takes 2 arguments : the relative path and the file.
     * @return {Array} An array of matching elements.
     */
    filter: function(search) {
      var result2 = [];
      this.forEach(function(relativePath, entry) {
        if (search(relativePath, entry)) {
          result2.push(entry);
        }
      });
      return result2;
    },
    /**
     * Add a file to the zip file, or search a file.
     * @param   {string|RegExp} name The name of the file to add (if data is defined),
     * the name of the file to find (if no data) or a regex to match files.
     * @param   {String|ArrayBuffer|Uint8Array|Buffer} data  The file data, either raw or base64 encoded
     * @param   {Object} o     File options
     * @return  {JSZip|Object|Array} this JSZip object (when adding a file),
     * a file (when searching by string) or an array of files (when searching by regex).
     */
    file: function(name2, data3, o5) {
      if (arguments.length === 1) {
        if (isRegExp3(name2)) {
          var regexp = name2;
          return this.filter(function(relativePath, file) {
            return !file.dir && regexp.test(relativePath);
          });
        } else {
          var obj = this.files[this.root + name2];
          if (obj && !obj.dir) {
            return obj;
          } else {
            return null;
          }
        }
      } else {
        name2 = this.root + name2;
        fileAdd.call(this, name2, data3, o5);
      }
      return this;
    },
    /**
     * Add a directory to the zip file, or search.
     * @param   {String|RegExp} arg The name of the directory to add, or a regex to search folders.
     * @return  {JSZip} an object with the new directory as the root, or an array containing matching folders.
     */
    folder: function(arg) {
      if (!arg) {
        return this;
      }
      if (isRegExp3(arg)) {
        return this.filter(function(relativePath, file) {
          return file.dir && arg.test(relativePath);
        });
      }
      var name2 = this.root + arg;
      var newFolder = folderAdd.call(this, name2);
      var ret = this.clone();
      ret.root = newFolder.name;
      return ret;
    },
    /**
     * Delete a file, or a directory and all sub-files, from the zip
     * @param {string} name the name of the file to delete
     * @return {JSZip} this JSZip object
     */
    remove: function(name2) {
      name2 = this.root + name2;
      var file = this.files[name2];
      if (!file) {
        if (name2.slice(-1) !== "/") {
          name2 += "/";
        }
        file = this.files[name2];
      }
      if (file && !file.dir) {
        delete this.files[name2];
      } else {
        var kids = this.filter(function(relativePath, file2) {
          return file2.name.slice(0, name2.length) === name2;
        });
        for (var i6 = 0; i6 < kids.length; i6++) {
          delete this.files[kids[i6].name];
        }
      }
      return this;
    },
    /**
     * Generate the complete zip file
     * @param {Object} options the options to generate the zip file :
     * - compression, "STORE" by default.
     * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob.
     * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the zip file
     */
    generate: function(options) {
      throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
    },
    /**
     * Generate the complete zip file as an internal stream.
     * @param {Object} options the options to generate the zip file :
     * - compression, "STORE" by default.
     * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob.
     * @return {StreamHelper} the streamed zip file.
     */
    generateInternalStream: function(options) {
      var worker, opts = {};
      try {
        opts = utils6.extend(options || {}, {
          streamFiles: false,
          compression: "STORE",
          compressionOptions: null,
          type: "",
          platform: "DOS",
          comment: null,
          mimeType: "application/zip",
          encodeFileName: utf8.utf8encode
        });
        opts.type = opts.type.toLowerCase();
        opts.compression = opts.compression.toUpperCase();
        if (opts.type === "binarystring") {
          opts.type = "string";
        }
        if (!opts.type) {
          throw new Error("No output type specified.");
        }
        utils6.checkSupport(opts.type);
        if (opts.platform === "darwin" || opts.platform === "freebsd" || opts.platform === "linux" || opts.platform === "sunos") {
          opts.platform = "UNIX";
        }
        if (opts.platform === "win32") {
          opts.platform = "DOS";
        }
        var comment = opts.comment || this.comment || "";
        worker = generate.generateWorker(this, opts, comment);
      } catch (e5) {
        worker = new GenericWorker("error");
        worker.error(e5);
      }
      return new StreamHelper(worker, opts.type || "string", opts.mimeType);
    },
    /**
     * Generate the complete zip file asynchronously.
     * @see generateInternalStream
     */
    generateAsync: function(options, onUpdate) {
      return this.generateInternalStream(options).accumulate(onUpdate);
    },
    /**
     * Generate the complete zip file asynchronously.
     * @see generateInternalStream
     */
    generateNodeStream: function(options, onUpdate) {
      options = options || {};
      if (!options.type) {
        options.type = "nodebuffer";
      }
      return this.generateInternalStream(options).toNodejsStream(onUpdate);
    }
  };
  exports$n = out;
  return exports$n;
}
function dew$o() {
  if (_dewExec$o) return exports$o;
  _dewExec$o = true;
  var utils6 = dew$42();
  function DataReader(data3) {
    this.data = data3;
    this.length = data3.length;
    this.index = 0;
    this.zero = 0;
  }
  DataReader.prototype = {
    /**
     * Check that the offset will not go too far.
     * @param {string} offset the additional offset to check.
     * @throws {Error} an Error if the offset is out of bounds.
     */
    checkOffset: function(offset3) {
      this.checkIndex(this.index + offset3);
    },
    /**
     * Check that the specified index will not be too far.
     * @param {string} newIndex the index to check.
     * @throws {Error} an Error if the index is out of bounds.
     */
    checkIndex: function(newIndex) {
      if (this.length < this.zero + newIndex || newIndex < 0) {
        throw new Error("End of data reached (data length = " + this.length + ", asked index = " + newIndex + "). Corrupted zip ?");
      }
    },
    /**
     * Change the index.
     * @param {number} newIndex The new index.
     * @throws {Error} if the new index is out of the data.
     */
    setIndex: function(newIndex) {
      this.checkIndex(newIndex);
      this.index = newIndex;
    },
    /**
     * Skip the next n bytes.
     * @param {number} n the number of bytes to skip.
     * @throws {Error} if the new index is out of the data.
     */
    skip: function(n5) {
      this.setIndex(this.index + n5);
    },
    /**
     * Get the byte at the specified index.
     * @param {number} i the index to use.
     * @return {number} a byte.
     */
    byteAt: function(i6) {
    },
    /**
     * Get the next number with a given byte size.
     * @param {number} size the number of bytes to read.
     * @return {number} the corresponding number.
     */
    readInt: function(size) {
      var result2 = 0, i6;
      this.checkOffset(size);
      for (i6 = this.index + size - 1; i6 >= this.index; i6--) {
        result2 = (result2 << 8) + this.byteAt(i6);
      }
      this.index += size;
      return result2;
    },
    /**
     * Get the next string with a given byte size.
     * @param {number} size the number of bytes to read.
     * @return {string} the corresponding string.
     */
    readString: function(size) {
      return utils6.transformTo("string", this.readData(size));
    },
    /**
     * Get raw data without conversion, <size> bytes.
     * @param {number} size the number of bytes to read.
     * @return {Object} the raw data, implementation specific.
     */
    readData: function(size) {
    },
    /**
     * Find the last occurrence of a zip signature (4 bytes).
     * @param {string} sig the signature to find.
     * @return {number} the index of the last occurrence, -1 if not found.
     */
    lastIndexOfSignature: function(sig) {
    },
    /**
     * Read the signature (4 bytes) at the current position and compare it with sig.
     * @param {string} sig the expected signature
     * @return {boolean} true if the signature matches, false otherwise.
     */
    readAndCheckSignature: function(sig) {
    },
    /**
     * Get the next date.
     * @return {Date} the date.
     */
    readDate: function() {
      var dostime = this.readInt(4);
      return new Date(Date.UTC(
        (dostime >> 25 & 127) + 1980,
        // year
        (dostime >> 21 & 15) - 1,
        // month
        dostime >> 16 & 31,
        // day
        dostime >> 11 & 31,
        // hour
        dostime >> 5 & 63,
        // minute
        (dostime & 31) << 1
      ));
    }
  };
  exports$o = DataReader;
  return exports$o;
}
function dew$p() {
  if (_dewExec$p) return exports$p;
  _dewExec$p = true;
  var DataReader = dew$o();
  var utils6 = dew$42();
  function ArrayReader(data3) {
    DataReader.call(this, data3);
    for (var i6 = 0; i6 < this.data.length; i6++) {
      data3[i6] = data3[i6] & 255;
    }
  }
  utils6.inherits(ArrayReader, DataReader);
  ArrayReader.prototype.byteAt = function(i6) {
    return this.data[this.zero + i6];
  };
  ArrayReader.prototype.lastIndexOfSignature = function(sig) {
    var sig0 = sig.charCodeAt(0), sig1 = sig.charCodeAt(1), sig2 = sig.charCodeAt(2), sig3 = sig.charCodeAt(3);
    for (var i6 = this.length - 4; i6 >= 0; --i6) {
      if (this.data[i6] === sig0 && this.data[i6 + 1] === sig1 && this.data[i6 + 2] === sig2 && this.data[i6 + 3] === sig3) {
        return i6 - this.zero;
      }
    }
    return -1;
  };
  ArrayReader.prototype.readAndCheckSignature = function(sig) {
    var sig0 = sig.charCodeAt(0), sig1 = sig.charCodeAt(1), sig2 = sig.charCodeAt(2), sig3 = sig.charCodeAt(3), data3 = this.readData(4);
    return sig0 === data3[0] && sig1 === data3[1] && sig2 === data3[2] && sig3 === data3[3];
  };
  ArrayReader.prototype.readData = function(size) {
    this.checkOffset(size);
    if (size === 0) {
      return [];
    }
    var result2 = this.data.slice(this.zero + this.index, this.zero + this.index + size);
    this.index += size;
    return result2;
  };
  exports$p = ArrayReader;
  return exports$p;
}
function dew$q() {
  if (_dewExec$q) return exports$q;
  _dewExec$q = true;
  var DataReader = dew$o();
  var utils6 = dew$42();
  function StringReader(data3) {
    DataReader.call(this, data3);
  }
  utils6.inherits(StringReader, DataReader);
  StringReader.prototype.byteAt = function(i6) {
    return this.data.charCodeAt(this.zero + i6);
  };
  StringReader.prototype.lastIndexOfSignature = function(sig) {
    return this.data.lastIndexOf(sig) - this.zero;
  };
  StringReader.prototype.readAndCheckSignature = function(sig) {
    var data3 = this.readData(4);
    return sig === data3;
  };
  StringReader.prototype.readData = function(size) {
    this.checkOffset(size);
    var result2 = this.data.slice(this.zero + this.index, this.zero + this.index + size);
    this.index += size;
    return result2;
  };
  exports$q = StringReader;
  return exports$q;
}
function dew$r() {
  if (_dewExec$r) return exports$r;
  _dewExec$r = true;
  var ArrayReader = dew$p();
  var utils6 = dew$42();
  function Uint8ArrayReader(data3) {
    ArrayReader.call(this, data3);
  }
  utils6.inherits(Uint8ArrayReader, ArrayReader);
  Uint8ArrayReader.prototype.readData = function(size) {
    this.checkOffset(size);
    if (size === 0) {
      return new Uint8Array(0);
    }
    var result2 = this.data.subarray(this.zero + this.index, this.zero + this.index + size);
    this.index += size;
    return result2;
  };
  exports$r = Uint8ArrayReader;
  return exports$r;
}
function dew$s() {
  if (_dewExec$s) return exports$s;
  _dewExec$s = true;
  var Uint8ArrayReader = dew$r();
  var utils6 = dew$42();
  function NodeBufferReader(data3) {
    Uint8ArrayReader.call(this, data3);
  }
  utils6.inherits(NodeBufferReader, Uint8ArrayReader);
  NodeBufferReader.prototype.readData = function(size) {
    this.checkOffset(size);
    var result2 = this.data.slice(this.zero + this.index, this.zero + this.index + size);
    this.index += size;
    return result2;
  };
  exports$s = NodeBufferReader;
  return exports$s;
}
function dew$t() {
  if (_dewExec$t) return exports$t;
  _dewExec$t = true;
  var utils6 = dew$42();
  var support = dew6();
  var ArrayReader = dew$p();
  var StringReader = dew$q();
  var NodeBufferReader = dew$s();
  var Uint8ArrayReader = dew$r();
  exports$t = function(data3) {
    var type4 = utils6.getTypeOf(data3);
    utils6.checkSupport(type4);
    if (type4 === "string" && !support.uint8array) {
      return new StringReader(data3);
    }
    if (type4 === "nodebuffer") {
      return new NodeBufferReader(data3);
    }
    if (support.uint8array) {
      return new Uint8ArrayReader(utils6.transformTo("uint8array", data3));
    }
    return new ArrayReader(utils6.transformTo("array", data3));
  };
  return exports$t;
}
function dew$u() {
  if (_dewExec$u) return exports$u;
  _dewExec$u = true;
  var readerFor = dew$t();
  var utils6 = dew$42();
  var CompressedObject = dew$f2();
  var crc32fn = dew$d2();
  var utf8 = dew$62();
  var compressions = dew$i();
  var support = dew6();
  var MADE_BY_DOS = 0;
  var MADE_BY_UNIX = 3;
  var findCompression = function(compressionMethod) {
    for (var method in compressions) {
      if (!compressions.hasOwnProperty(method)) {
        continue;
      }
      if (compressions[method].magic === compressionMethod) {
        return compressions[method];
      }
    }
    return null;
  };
  function ZipEntry(options, loadOptions) {
    this.options = options;
    this.loadOptions = loadOptions;
  }
  ZipEntry.prototype = {
    /**
     * say if the file is encrypted.
     * @return {boolean} true if the file is encrypted, false otherwise.
     */
    isEncrypted: function() {
      return (this.bitFlag & 1) === 1;
    },
    /**
     * say if the file has utf-8 filename/comment.
     * @return {boolean} true if the filename/comment is in utf-8, false otherwise.
     */
    useUTF8: function() {
      return (this.bitFlag & 2048) === 2048;
    },
    /**
     * Read the local part of a zip file and add the info in this object.
     * @param {DataReader} reader the reader to use.
     */
    readLocalPart: function(reader) {
      var compression, localExtraFieldsLength;
      reader.skip(22);
      this.fileNameLength = reader.readInt(2);
      localExtraFieldsLength = reader.readInt(2);
      this.fileName = reader.readData(this.fileNameLength);
      reader.skip(localExtraFieldsLength);
      if (this.compressedSize === -1 || this.uncompressedSize === -1) {
        throw new Error("Bug or corrupted zip : didn't get enough information from the central directory (compressedSize === -1 || uncompressedSize === -1)");
      }
      compression = findCompression(this.compressionMethod);
      if (compression === null) {
        throw new Error("Corrupted zip : compression " + utils6.pretty(this.compressionMethod) + " unknown (inner file : " + utils6.transformTo("string", this.fileName) + ")");
      }
      this.decompressed = new CompressedObject(this.compressedSize, this.uncompressedSize, this.crc32, compression, reader.readData(this.compressedSize));
    },
    /**
     * Read the central part of a zip file and add the info in this object.
     * @param {DataReader} reader the reader to use.
     */
    readCentralPart: function(reader) {
      this.versionMadeBy = reader.readInt(2);
      reader.skip(2);
      this.bitFlag = reader.readInt(2);
      this.compressionMethod = reader.readString(2);
      this.date = reader.readDate();
      this.crc32 = reader.readInt(4);
      this.compressedSize = reader.readInt(4);
      this.uncompressedSize = reader.readInt(4);
      var fileNameLength = reader.readInt(2);
      this.extraFieldsLength = reader.readInt(2);
      this.fileCommentLength = reader.readInt(2);
      this.diskNumberStart = reader.readInt(2);
      this.internalFileAttributes = reader.readInt(2);
      this.externalFileAttributes = reader.readInt(4);
      this.localHeaderOffset = reader.readInt(4);
      if (this.isEncrypted()) {
        throw new Error("Encrypted zip are not supported");
      }
      reader.skip(fileNameLength);
      this.readExtraFields(reader);
      this.parseZIP64ExtraField(reader);
      this.fileComment = reader.readData(this.fileCommentLength);
    },
    /**
     * Parse the external file attributes and get the unix/dos permissions.
     */
    processAttributes: function() {
      this.unixPermissions = null;
      this.dosPermissions = null;
      var madeBy = this.versionMadeBy >> 8;
      this.dir = this.externalFileAttributes & 16 ? true : false;
      if (madeBy === MADE_BY_DOS) {
        this.dosPermissions = this.externalFileAttributes & 63;
      }
      if (madeBy === MADE_BY_UNIX) {
        this.unixPermissions = this.externalFileAttributes >> 16 & 65535;
      }
      if (!this.dir && this.fileNameStr.slice(-1) === "/") {
        this.dir = true;
      }
    },
    /**
     * Parse the ZIP64 extra field and merge the info in the current ZipEntry.
     * @param {DataReader} reader the reader to use.
     */
    parseZIP64ExtraField: function(reader) {
      if (!this.extraFields[1]) {
        return;
      }
      var extraReader = readerFor(this.extraFields[1].value);
      if (this.uncompressedSize === utils6.MAX_VALUE_32BITS) {
        this.uncompressedSize = extraReader.readInt(8);
      }
      if (this.compressedSize === utils6.MAX_VALUE_32BITS) {
        this.compressedSize = extraReader.readInt(8);
      }
      if (this.localHeaderOffset === utils6.MAX_VALUE_32BITS) {
        this.localHeaderOffset = extraReader.readInt(8);
      }
      if (this.diskNumberStart === utils6.MAX_VALUE_32BITS) {
        this.diskNumberStart = extraReader.readInt(4);
      }
    },
    /**
     * Read the central part of a zip file and add the info in this object.
     * @param {DataReader} reader the reader to use.
     */
    readExtraFields: function(reader) {
      var end = reader.index + this.extraFieldsLength, extraFieldId, extraFieldLength, extraFieldValue;
      if (!this.extraFields) {
        this.extraFields = {};
      }
      while (reader.index + 4 < end) {
        extraFieldId = reader.readInt(2);
        extraFieldLength = reader.readInt(2);
        extraFieldValue = reader.readData(extraFieldLength);
        this.extraFields[extraFieldId] = {
          id: extraFieldId,
          length: extraFieldLength,
          value: extraFieldValue
        };
      }
      reader.setIndex(end);
    },
    /**
     * Apply an UTF8 transformation if needed.
     */
    handleUTF8: function() {
      var decodeParamType = support.uint8array ? "uint8array" : "array";
      if (this.useUTF8()) {
        this.fileNameStr = utf8.utf8decode(this.fileName);
        this.fileCommentStr = utf8.utf8decode(this.fileComment);
      } else {
        var upath = this.findExtraFieldUnicodePath();
        if (upath !== null) {
          this.fileNameStr = upath;
        } else {
          var fileNameByteArray = utils6.transformTo(decodeParamType, this.fileName);
          this.fileNameStr = this.loadOptions.decodeFileName(fileNameByteArray);
        }
        var ucomment = this.findExtraFieldUnicodeComment();
        if (ucomment !== null) {
          this.fileCommentStr = ucomment;
        } else {
          var commentByteArray = utils6.transformTo(decodeParamType, this.fileComment);
          this.fileCommentStr = this.loadOptions.decodeFileName(commentByteArray);
        }
      }
    },
    /**
     * Find the unicode path declared in the extra field, if any.
     * @return {String} the unicode path, null otherwise.
     */
    findExtraFieldUnicodePath: function() {
      var upathField = this.extraFields[28789];
      if (upathField) {
        var extraReader = readerFor(upathField.value);
        if (extraReader.readInt(1) !== 1) {
          return null;
        }
        if (crc32fn(this.fileName) !== extraReader.readInt(4)) {
          return null;
        }
        return utf8.utf8decode(extraReader.readData(upathField.length - 5));
      }
      return null;
    },
    /**
     * Find the unicode comment declared in the extra field, if any.
     * @return {String} the unicode comment, null otherwise.
     */
    findExtraFieldUnicodeComment: function() {
      var ucommentField = this.extraFields[25461];
      if (ucommentField) {
        var extraReader = readerFor(ucommentField.value);
        if (extraReader.readInt(1) !== 1) {
          return null;
        }
        if (crc32fn(this.fileComment) !== extraReader.readInt(4)) {
          return null;
        }
        return utf8.utf8decode(extraReader.readData(ucommentField.length - 5));
      }
      return null;
    }
  };
  exports$u = ZipEntry;
  return exports$u;
}
function dew$v() {
  if (_dewExec$v) return exports$v;
  _dewExec$v = true;
  var readerFor = dew$t();
  var utils6 = dew$42();
  var sig = dew$j();
  var ZipEntry = dew$u();
  var utf8 = dew$62();
  var support = dew6();
  function ZipEntries(loadOptions) {
    this.files = [];
    this.loadOptions = loadOptions;
  }
  ZipEntries.prototype = {
    /**
     * Check that the reader is on the specified signature.
     * @param {string} expectedSignature the expected signature.
     * @throws {Error} if it is an other signature.
     */
    checkSignature: function(expectedSignature) {
      if (!this.reader.readAndCheckSignature(expectedSignature)) {
        this.reader.index -= 4;
        var signature = this.reader.readString(4);
        throw new Error("Corrupted zip or bug: unexpected signature (" + utils6.pretty(signature) + ", expected " + utils6.pretty(expectedSignature) + ")");
      }
    },
    /**
     * Check if the given signature is at the given index.
     * @param {number} askedIndex the index to check.
     * @param {string} expectedSignature the signature to expect.
     * @return {boolean} true if the signature is here, false otherwise.
     */
    isSignature: function(askedIndex, expectedSignature) {
      var currentIndex = this.reader.index;
      this.reader.setIndex(askedIndex);
      var signature = this.reader.readString(4);
      var result2 = signature === expectedSignature;
      this.reader.setIndex(currentIndex);
      return result2;
    },
    /**
     * Read the end of the central directory.
     */
    readBlockEndOfCentral: function() {
      this.diskNumber = this.reader.readInt(2);
      this.diskWithCentralDirStart = this.reader.readInt(2);
      this.centralDirRecordsOnThisDisk = this.reader.readInt(2);
      this.centralDirRecords = this.reader.readInt(2);
      this.centralDirSize = this.reader.readInt(4);
      this.centralDirOffset = this.reader.readInt(4);
      this.zipCommentLength = this.reader.readInt(2);
      var zipComment = this.reader.readData(this.zipCommentLength);
      var decodeParamType = support.uint8array ? "uint8array" : "array";
      var decodeContent = utils6.transformTo(decodeParamType, zipComment);
      this.zipComment = this.loadOptions.decodeFileName(decodeContent);
    },
    /**
     * Read the end of the Zip 64 central directory.
     * Not merged with the method readEndOfCentral :
     * The end of central can coexist with its Zip64 brother,
     * I don't want to read the wrong number of bytes !
     */
    readBlockZip64EndOfCentral: function() {
      this.zip64EndOfCentralSize = this.reader.readInt(8);
      this.reader.skip(4);
      this.diskNumber = this.reader.readInt(4);
      this.diskWithCentralDirStart = this.reader.readInt(4);
      this.centralDirRecordsOnThisDisk = this.reader.readInt(8);
      this.centralDirRecords = this.reader.readInt(8);
      this.centralDirSize = this.reader.readInt(8);
      this.centralDirOffset = this.reader.readInt(8);
      this.zip64ExtensibleData = {};
      var extraDataSize = this.zip64EndOfCentralSize - 44, index2 = 0, extraFieldId, extraFieldLength, extraFieldValue;
      while (index2 < extraDataSize) {
        extraFieldId = this.reader.readInt(2);
        extraFieldLength = this.reader.readInt(4);
        extraFieldValue = this.reader.readData(extraFieldLength);
        this.zip64ExtensibleData[extraFieldId] = {
          id: extraFieldId,
          length: extraFieldLength,
          value: extraFieldValue
        };
      }
    },
    /**
     * Read the end of the Zip 64 central directory locator.
     */
    readBlockZip64EndOfCentralLocator: function() {
      this.diskWithZip64CentralDirStart = this.reader.readInt(4);
      this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8);
      this.disksCount = this.reader.readInt(4);
      if (this.disksCount > 1) {
        throw new Error("Multi-volumes zip are not supported");
      }
    },
    /**
     * Read the local files, based on the offset read in the central part.
     */
    readLocalFiles: function() {
      var i6, file;
      for (i6 = 0; i6 < this.files.length; i6++) {
        file = this.files[i6];
        this.reader.setIndex(file.localHeaderOffset);
        this.checkSignature(sig.LOCAL_FILE_HEADER);
        file.readLocalPart(this.reader);
        file.handleUTF8();
        file.processAttributes();
      }
    },
    /**
     * Read the central directory.
     */
    readCentralDir: function() {
      var file;
      this.reader.setIndex(this.centralDirOffset);
      while (this.reader.readAndCheckSignature(sig.CENTRAL_FILE_HEADER)) {
        file = new ZipEntry({
          zip64: this.zip64
        }, this.loadOptions);
        file.readCentralPart(this.reader);
        this.files.push(file);
      }
      if (this.centralDirRecords !== this.files.length) {
        if (this.centralDirRecords !== 0 && this.files.length === 0) {
          throw new Error("Corrupted zip or bug: expected " + this.centralDirRecords + " records in central dir, got " + this.files.length);
        } else {
        }
      }
    },
    /**
     * Read the end of central directory.
     */
    readEndOfCentral: function() {
      var offset3 = this.reader.lastIndexOfSignature(sig.CENTRAL_DIRECTORY_END);
      if (offset3 < 0) {
        var isGarbage = !this.isSignature(0, sig.LOCAL_FILE_HEADER);
        if (isGarbage) {
          throw new Error("Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html");
        } else {
          throw new Error("Corrupted zip: can't find end of central directory");
        }
      }
      this.reader.setIndex(offset3);
      var endOfCentralDirOffset = offset3;
      this.checkSignature(sig.CENTRAL_DIRECTORY_END);
      this.readBlockEndOfCentral();
      if (this.diskNumber === utils6.MAX_VALUE_16BITS || this.diskWithCentralDirStart === utils6.MAX_VALUE_16BITS || this.centralDirRecordsOnThisDisk === utils6.MAX_VALUE_16BITS || this.centralDirRecords === utils6.MAX_VALUE_16BITS || this.centralDirSize === utils6.MAX_VALUE_32BITS || this.centralDirOffset === utils6.MAX_VALUE_32BITS) {
        this.zip64 = true;
        offset3 = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
        if (offset3 < 0) {
          throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");
        }
        this.reader.setIndex(offset3);
        this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
        this.readBlockZip64EndOfCentralLocator();
        if (!this.isSignature(this.relativeOffsetEndOfZip64CentralDir, sig.ZIP64_CENTRAL_DIRECTORY_END)) {
          this.relativeOffsetEndOfZip64CentralDir = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);
          if (this.relativeOffsetEndOfZip64CentralDir < 0) {
            throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");
          }
        }
        this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir);
        this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);
        this.readBlockZip64EndOfCentral();
      }
      var expectedEndOfCentralDirOffset = this.centralDirOffset + this.centralDirSize;
      if (this.zip64) {
        expectedEndOfCentralDirOffset += 20;
        expectedEndOfCentralDirOffset += 12 + this.zip64EndOfCentralSize;
      }
      var extraBytes = endOfCentralDirOffset - expectedEndOfCentralDirOffset;
      if (extraBytes > 0) {
        if (this.isSignature(endOfCentralDirOffset, sig.CENTRAL_FILE_HEADER)) {
        } else {
          this.reader.zero = extraBytes;
        }
      } else if (extraBytes < 0) {
        throw new Error("Corrupted zip: missing " + Math.abs(extraBytes) + " bytes.");
      }
    },
    prepareReader: function(data3) {
      this.reader = readerFor(data3);
    },
    /**
     * Read a zip file and create ZipEntries.
     * @param {String|ArrayBuffer|Uint8Array|Buffer} data the binary string representing a zip file.
     */
    load: function(data3) {
      this.prepareReader(data3);
      this.readEndOfCentral();
      this.readCentralDir();
      this.readLocalFiles();
    }
  };
  exports$v = ZipEntries;
  return exports$v;
}
function dew$w() {
  if (_dewExec$w) return exports$w;
  _dewExec$w = true;
  var utils6 = dew$42();
  var external = dew$32();
  var utf8 = dew$62();
  var utils6 = dew$42();
  var ZipEntries = dew$v();
  var Crc32Probe = dew$e2();
  var nodejsUtils = dew$23();
  function checkEntryCRC32(zipEntry) {
    return new external.Promise(function(resolve16, reject2) {
      var worker = zipEntry.decompressed.getContentWorker().pipe(new Crc32Probe());
      worker.on("error", function(e5) {
        reject2(e5);
      }).on("end", function() {
        if (worker.streamInfo.crc32 !== zipEntry.decompressed.crc32) {
          reject2(new Error("Corrupted zip : CRC32 mismatch"));
        } else {
          resolve16();
        }
      }).resume();
    });
  }
  exports$w = function(data3, options) {
    var zip2 = this;
    options = utils6.extend(options || {}, {
      base64: false,
      checkCRC32: false,
      optimizedBinaryString: false,
      createFolders: false,
      decodeFileName: utf8.utf8decode
    });
    if (nodejsUtils.isNode && nodejsUtils.isStream(data3)) {
      return external.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file."));
    }
    return utils6.prepareContent("the loaded zip file", data3, true, options.optimizedBinaryString, options.base64).then(function(data4) {
      var zipEntries = new ZipEntries(options);
      zipEntries.load(data4);
      return zipEntries;
    }).then(function checkCRC32(zipEntries) {
      var promises2 = [external.Promise.resolve(zipEntries)];
      var files = zipEntries.files;
      if (options.checkCRC32) {
        for (var i6 = 0; i6 < files.length; i6++) {
          promises2.push(checkEntryCRC32(files[i6]));
        }
      }
      return external.Promise.all(promises2);
    }).then(function addFiles(results) {
      var zipEntries = results.shift();
      var files = zipEntries.files;
      for (var i6 = 0; i6 < files.length; i6++) {
        var input = files[i6];
        zip2.file(input.fileNameStr, input.decompressed, {
          binary: true,
          optimizedBinaryString: true,
          date: input.date,
          dir: input.dir,
          comment: input.fileCommentStr.length ? input.fileCommentStr : null,
          unixPermissions: input.unixPermissions,
          dosPermissions: input.dosPermissions,
          createFolders: options.createFolders
        });
      }
      if (zipEntries.zipComment.length) {
        zip2.comment = zipEntries.zipComment;
      }
      return zip2;
    });
  };
  return exports$w;
}
function dew$x() {
  if (_dewExec$x) return exports$x;
  _dewExec$x = true;
  function JSZip2() {
    if (!(this instanceof JSZip2)) {
      return new JSZip2();
    }
    if (arguments.length) {
      throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");
    }
    this.files = {};
    this.comment = null;
    this.root = "";
    this.clone = function() {
      var newObj = new JSZip2();
      for (var i6 in this) {
        if (typeof this[i6] !== "function") {
          newObj[i6] = this[i6];
        }
      }
      return newObj;
    };
  }
  JSZip2.prototype = dew$n();
  JSZip2.prototype.loadAsync = dew$w();
  JSZip2.support = dew6();
  JSZip2.defaults = dew$a2();
  JSZip2.version = "3.5.0";
  JSZip2.loadAsync = function(content, options) {
    return new JSZip2().loadAsync(content, options);
  };
  JSZip2.external = dew$32();
  exports$x = JSZip2;
  return exports$x;
}
var exports22, _dewExec6, exports$19, _dewExec$13, exports$24, _dewExec$23, exports$33, _dewExec$32, exports$42, _dewExec$42, exports$52, _dewExec$52, exports$62, _dewExec$62, exports$72, _dewExec$72, exports$82, _dewExec$82, exports$92, _dewExec$92, exports$a2, _dewExec$a2, exports$b2, _dewExec$b2, exports$c2, _dewExec$c2, exports$d2, _dewExec$d2, exports$e2, _dewExec$e2, exports$f2, _dewExec$f2, exports$g2, _dewExec$g2, exports$h, _dewExec$h, exports$i, _dewExec$i, exports$j, _dewExec$j, exports$k, _dewExec$k, exports$l, _dewExec$l, exports$m, _dewExec$m, exports$n, _dewExec$n, exports$o, _dewExec$o, exports$p, _dewExec$p, exports$q, _dewExec$q, exports$r, _dewExec$r, exports$s, _dewExec$s, exports$t, _dewExec$t, exports$u, _dewExec$u, exports$v, _dewExec$v, exports$w, _dewExec$w, exports$x, _dewExec$x, index, npm_jszip_3_5_default;
var init_npm_jszip_3_5 = __esm({
  "https://dev.jspm.io/npm:jszip@3.5.0!cjs"() {
    init_stream2();
    init_f50b93();
    init_buffer3();
    init_npm_set_immediate_shim_1();
    init_npm_lie_3();
    init_npm_pako_1();
    exports22 = {};
    _dewExec6 = false;
    exports$19 = {};
    _dewExec$13 = false;
    exports$24 = {};
    _dewExec$23 = false;
    exports$33 = {};
    _dewExec$32 = false;
    exports$42 = {};
    _dewExec$42 = false;
    exports$52 = {};
    _dewExec$52 = false;
    exports$62 = {};
    _dewExec$62 = false;
    exports$72 = {};
    _dewExec$72 = false;
    exports$82 = {};
    _dewExec$82 = false;
    exports$92 = {};
    _dewExec$92 = false;
    exports$a2 = {};
    _dewExec$a2 = false;
    exports$b2 = {};
    _dewExec$b2 = false;
    exports$c2 = {};
    _dewExec$c2 = false;
    exports$d2 = {};
    _dewExec$d2 = false;
    exports$e2 = {};
    _dewExec$e2 = false;
    exports$f2 = {};
    _dewExec$f2 = false;
    exports$g2 = {};
    _dewExec$g2 = false;
    exports$h = {};
    _dewExec$h = false;
    exports$i = {};
    _dewExec$i = false;
    exports$j = {};
    _dewExec$j = false;
    exports$k = {};
    _dewExec$k = false;
    exports$l = {};
    _dewExec$l = false;
    exports$m = {};
    _dewExec$m = false;
    exports$n = {};
    _dewExec$n = false;
    exports$o = {};
    _dewExec$o = false;
    exports$p = {};
    _dewExec$p = false;
    exports$q = {};
    _dewExec$q = false;
    exports$r = {};
    _dewExec$r = false;
    exports$s = {};
    _dewExec$s = false;
    exports$t = {};
    _dewExec$t = false;
    exports$u = {};
    _dewExec$u = false;
    exports$v = {};
    _dewExec$v = false;
    exports$w = {};
    _dewExec$w = false;
    exports$x = {};
    _dewExec$x = false;
    index = dew$x();
    npm_jszip_3_5_default = index;
  }
});

// https://dev.jspm.io/jszip@3.5.0
var init_jszip_3_5 = __esm({
  "https://dev.jspm.io/jszip@3.5.0"() {
    init_stream2();
    init_f50b93();
    init_buffer3();
    init_npm_set_immediate_shim_1();
    init_npm_lie_3();
    init_npm_pako_1();
    init_npm_jszip_3_5();
    init_npm_jszip_3_5();
  }
});

// https://deno.land/std@0.217.0/path/normalize.ts
var init_normalize12 = __esm({
  "https://deno.land/std@0.217.0/path/normalize.ts"() {
    init_os3();
    init_normalize10();
    init_normalize11();
  }
});

// https://deno.land/std@0.217.0/fs/_create_walk_entry.ts
var init_create_walk_entry2 = __esm({
  "https://deno.land/std@0.217.0/fs/_create_walk_entry.ts"() {
    init_basename12();
    init_normalize12();
    init_to_path_string2();
  }
});

// https://deno.land/std@0.217.0/fs/walk.ts
var init_walk2 = __esm({
  "https://deno.land/std@0.217.0/fs/walk.ts"() {
    init_join9();
    init_normalize12();
    init_to_path_string2();
    init_create_walk_entry2();
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/vendor/zip/mod.ts
async function readZip(path3) {
  const z4 = new JSZip();
  const content = await Deno.readFile(path3);
  await z4.loadAsync(content);
  return z4;
}
var JSZip;
var init_mod13 = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/vendor/zip/mod.ts"() {
    init_jszip_3_5();
    init_ensure_dir2();
    init_walk2();
    init_mod11();
    JSZip = class _JSZip {
      _z;
      // we should assert the type (we want it to be a _JSZip) ?
      constructor(z4) {
        if (z4 === void 0) {
          this._z = new npm_jszip_3_5_default();
        } else {
          this._z = z4;
        }
      }
      /**
       * Returns an new JSZip instance with the given folder as root
       *
       * @param name Name of the folder
       * @return New JSZip object with the given folder as root or null
       */
      folder(name2) {
        const f5 = this._z.folder(name2);
        return new _JSZip(f5);
      }
      /**
       * Get a file from the archive
       *
       * @param Path relative path to file
       * @return File matching path, null if no file found
       */
      file(path3) {
        const f5 = this._z.file(path3);
        return f5;
      }
      /**
       * Add a file to the archive
       *
       * @param path Relative path to file
       * @param data Content of the file
       * @param options Optional information about the file
       * @return JSZip object
       */
      addFile(path3, content, options) {
        const f5 = this._z.file(path3, content, options);
        return f5;
      }
      files() {
        const fs = this._z.files;
        return fs;
      }
      /**
       * Generates a new archive asynchronously
       *
       * @param options Optional options for the generator
       * @param onUpdate The optional function called on each internal update with the metadata.
       * @return The serialized archive
       */
      async generateAsync(options) {
        return await this._z.generateAsync(options);
      }
      /**
       * Get all files which match the given filter function
       *
       * @param predicate Filter function
       * @return Array of matched elements
       */
      filter(predicate) {
        return this._z.filter(predicate);
      }
      /**
       * Removes the file or folder from the archive
       *
       * @param path Relative path of file or folder
       * @return Returns the JSZip instance
       */
      remove(path3) {
        return this._z.remove(path3);
      }
      /**
       * Deserialize zip file asynchronously
       *
       * @param data Serialized zip file
       * @param options Options for deserializing
       * @return Returns promise
       */
      async loadAsync(data3, options) {
        return this._z.loadAsync(data3, options);
      }
      /**
       * Write zip file asynchronously to a file
       *
       * @param path of zip file
       * @return Returns promise
       */
      async writeZip(path3) {
        const b3 = await this.generateAsync({ type: "uint8array" });
        return await Deno.writeFile(path3, b3);
      }
      /**
       * Unzip a JSZip asynchronously to a directory
       *
       * @param dir to unzip into
       * @return Returns promise
       */
      async unzip(dir = ".") {
        for (const f5 of this) {
          const ff = join9(dir, f5.name);
          if (f5.dir) {
            await Deno.mkdir(ff, { recursive: true });
            continue;
          }
          const content = await f5.async("uint8array");
          await ensureDir2(dirname7(ff));
          await Deno.writeFile(ff, content);
        }
      }
      *[Symbol.iterator]() {
        yield* Object.values(this.files());
      }
    };
  }
});

// https://deno.land/std@0.91.0/encoding/base64.ts
function decode3(b64) {
  const binString = atob(b64);
  const size = binString.length;
  const bytes = new Uint8Array(size);
  for (let i6 = 0; i6 < size; i6++) {
    bytes[i6] = binString.charCodeAt(i6);
  }
  return bytes;
}
var init_base643 = __esm({
  "https://deno.land/std@0.91.0/encoding/base64.ts"() {
  }
});

// https://deno.land/std@0.91.0/hash/_wasm/wasm.js
function getUint8Memory02() {
  if (cachegetUint8Memory02 === null || cachegetUint8Memory02.buffer !== wasm2.memory.buffer) {
    cachegetUint8Memory02 = new Uint8Array(wasm2.memory.buffer);
  }
  return cachegetUint8Memory02;
}
function getStringFromWasm02(ptr, len) {
  return cachedTextDecoder2.decode(getUint8Memory02().subarray(ptr, ptr + len));
}
function addHeapObject(obj) {
  if (heap_next === heap.length) heap.push(heap.length + 1);
  const idx = heap_next;
  heap_next = heap[idx];
  heap[idx] = obj;
  return idx;
}
function getObject(idx) {
  return heap[idx];
}
function dropObject(idx) {
  if (idx < 36) return;
  heap[idx] = heap_next;
  heap_next = idx;
}
function takeObject(idx) {
  const ret = getObject(idx);
  dropObject(idx);
  return ret;
}
async function load5(module2, imports2) {
  if (typeof Response === "function" && module2 instanceof Response) {
    if (typeof WebAssembly.instantiateStreaming === "function") {
      try {
        return await WebAssembly.instantiateStreaming(module2, imports2);
      } catch (e5) {
        if (module2.headers.get("Content-Type") != "application/wasm") {
          console.warn(
            "`WebAssembly.instantiateStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",
            e5
          );
        } else {
          throw e5;
        }
      }
    }
    const bytes = await module2.arrayBuffer();
    return await WebAssembly.instantiate(bytes, imports2);
  } else {
    const instance = await WebAssembly.instantiate(module2, imports2);
    if (instance instanceof WebAssembly.Instance) {
      return { instance, module: module2 };
    } else {
      return instance;
    }
  }
}
async function init3(input) {
  if (typeof input === "undefined") {
    input = import.meta.url.replace(/\.js$/, "_bg.wasm");
  }
  const imports2 = {};
  imports2.wbg = {};
  imports2.wbg.__wbindgen_string_new = function(arg0, arg1) {
    var ret = getStringFromWasm02(arg0, arg1);
    return addHeapObject(ret);
  };
  imports2.wbg.__wbindgen_throw = function(arg0, arg1) {
    throw new Error(getStringFromWasm02(arg0, arg1));
  };
  imports2.wbg.__wbindgen_rethrow = function(arg0) {
    throw takeObject(arg0);
  };
  if (typeof input === "string" || typeof Request === "function" && input instanceof Request || typeof URL === "function" && input instanceof URL) {
    input = fetch(input);
  }
  const { instance, module: module2 } = await load5(await input, imports2);
  wasm2 = instance.exports;
  init3.__wbindgen_wasm_module = module2;
  return wasm2;
}
var source, wasm2, cachedTextDecoder2, cachegetUint8Memory02, heap, heap_next, cachedTextEncoder2, encodeString2, wasm_default;
var init_wasm = __esm({
  "https://deno.land/std@0.91.0/hash/_wasm/wasm.js"() {
    init_base643();
    source = decode3(
      " "
    );
    cachedTextDecoder2 = new TextDecoder("utf-8", {
      ignoreBOM: true,
      fatal: true
    });
    cachedTextDecoder2.decode();
    cachegetUint8Memory02 = null;
    heap = new Array(32).fill(void 0);
    heap.push(void 0, null, true, false);
    heap_next = heap.length;
    cachedTextEncoder2 = new TextEncoder("utf-8");
    encodeString2 = typeof cachedTextEncoder2.encodeInto === "function" ? function(arg, view) {
      return cachedTextEncoder2.encodeInto(arg, view);
    } : function(arg, view) {
      const buf = cachedTextEncoder2.encode(arg);
      view.set(buf);
      return {
        read: arg.length,
        written: buf.length
      };
    };
    wasm_default = init3;
  }
});

// https://deno.land/std@0.91.0/encoding/hex.ts
var hexTable;
var init_hex = __esm({
  "https://deno.land/std@0.91.0/encoding/hex.ts"() {
    hexTable = new TextEncoder().encode("0123456789abcdef");
  }
});

// https://deno.land/std@0.91.0/hash/_wasm/hash.ts
var init_hash = __esm({
  async "https://deno.land/std@0.91.0/hash/_wasm/hash.ts"() {
    init_wasm();
    init_hex();
    init_base643();
    await wasm_default(source);
  }
});

// https://deno.land/std@0.91.0/hash/mod.ts
var init_mod14 = __esm({
  async "https://deno.land/std@0.91.0/hash/mod.ts"() {
    await init_hash();
  }
});

// https://deno.land/x/cache@0.2.12/deps.ts
var init_deps = __esm({
  async "https://deno.land/x/cache@0.2.12/deps.ts"() {
    init_mod2();
    init_ensure_dir2();
    init_exists3();
    await init_mod14();
  }
});

// https://deno.land/x/cache@0.2.12/directories.ts
function cachedir() {
  const env2 = Deno.env.get;
  const os2 = Deno.build.os;
  const deno = env2("DENO_DIR");
  if (deno) return resolve3(deno);
  let home;
  let path3;
  switch (os2) {
    case "linux": {
      const xdg = env2("XDG_CACHE_HOME");
      home = xdg ?? env2(POSIX_HOME);
      path3 = xdg ? "deno" : join3(".cache", "deno");
      break;
    }
    case "darwin":
      home = env2(POSIX_HOME);
      path3 = join3("Library", "Caches", "deno");
      break;
    case "windows":
      home = env2("LOCALAPPDATA");
      home = home ?? env2("USERPROFILE");
      path3 = "deno";
      break;
  }
  path3 = home ? path3 : ".deno";
  if (!home) return path3;
  return resolve3(join3(home, path3));
}
var POSIX_HOME;
var init_directories = __esm({
  async "https://deno.land/x/cache@0.2.12/directories.ts"() {
    await init_deps();
    POSIX_HOME = "HOME";
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/vendor/cache.ts
var init_cache = __esm({
  async "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/vendor/cache.ts"() {
    await init_directories();
  }
});

// https://deno.land/x/puppeteer@9.0.2/src/deno/BrowserFetcher.ts
function archiveName(product, platform2, revision) {
  if (product === "chrome") {
    if (platform2 === "linux") return "chrome-linux";
    if (platform2 === "mac") return "chrome-mac";
    if (platform2 === "win32" || platform2 === "win64") {
      return parseInt(revision, 10) > 591479 ? "chrome-win" : "chrome-win32";
    }
  } else if (product === "firefox") {
    return platform2;
  }
  throw new Error(`Unknown product: ${product}`);
}
function downloadURL(product, platform2, host, revision) {
  const url = sprintf2(
    downloadURLs[product][platform2],
    host,
    revision,
    archiveName(product, platform2, revision)
  );
  return url;
}
function parseName(product, name2) {
  const splits = name2.split("-");
  if (splits.length !== 2) return null;
  const [platform2, revision] = splits;
  if (!downloadURLs[product]?.[platform2]) return null;
  return { product, platform: platform2, revision };
}
async function downloadFile(url, destinationPath, progressCallback) {
  debugFetcher(`Downloading binary from ${url}`);
  const response = await fetch(url, { method: "GET" });
  if (response.status !== 200) {
    const error2 = new Error(
      `Download failed: server returned code ${response.status}. URL: ${url}`
    );
    await response.arrayBuffer();
    throw error2;
  }
  const totalBytes = parseInt(response.headers.get("content-length") ?? "", 10);
  let downloadedBytes = 0;
  const file = await Deno.create(destinationPath);
  for await (const chunk of response.body) {
    downloadedBytes += chunk.length;
    progressCallback?.(downloadedBytes, totalBytes);
    await Deno.writeAll(file, chunk);
  }
}
function install(archivePath, folderPath) {
  debugFetcher(`Installing ${archivePath} to ${folderPath}`);
  if (archivePath.endsWith(".zip")) return extractZip(archivePath, folderPath);
  else if (archivePath.endsWith(".tar.bz2")) {
    return extractTar(archivePath, folderPath);
  } else if (archivePath.endsWith(".dmg")) {
    return Deno.mkdir(folderPath, { recursive: true }).then(
      () => installDMG(archivePath, folderPath)
    );
  } else throw new Error(`Unsupported archive format: ${archivePath}`);
}
async function extractZip(zipPath, folderPath) {
  const z4 = await readZip(zipPath);
  await z4.unzip(folderPath);
}
async function extractTar(tarPath, folderPath) {
  console.log(folderPath);
  await Deno.mkdir(folderPath, { recursive: true });
  const bzcat = Deno.run({
    cmd: ["bzcat", tarPath],
    stdout: "piped"
  });
  const tmp = await Deno.makeTempFile();
  const file = await Deno.create(tmp);
  await Deno.copy(bzcat.stdout, file);
  assert3((await bzcat.status()).success, "failed bzcat");
  bzcat.close();
  const untar = Deno.run({
    cmd: ["tar", "-C", folderPath, "-xvf", tmp]
  });
  assert3((await untar.status()).success, "failed untar");
  untar.close();
}
async function installDMG(dmgPath, folderPath) {
  let mountPath;
  try {
    const proc = Deno.run({
      cmd: ["hdiutil", "attach", "-nobrowse", "-noautoopen", dmgPath]
    });
    const stdout2 = new TextDecoder().decode(await proc.output());
    proc.close();
    const volumes = stdout2.match(/\/Volumes\/(.*)/m);
    if (!volumes) throw new Error(`Could not find volume path in ${stdout2}`);
    mountPath = volumes[0];
    let appName = void 0;
    for await (const file of Deno.readDir(mountPath)) {
      if (file.name.endsWith(".app")) {
        appName = file.name;
        break;
      }
    }
    if (!appName) throw new Error(`Cannot find app in ${mountPath}`);
    copy4(join9(mountPath, appName), folderPath);
  } finally {
    if (mountPath) {
      const proc = Deno.run({
        cmd: ["hdiutil", "detach", mountPath, "-quiet"]
      });
      debugFetcher(`Unmounting ${mountPath}`);
      const status = await proc.status();
      proc.close();
      assert3(status.success, "unmounting failed");
    }
  }
}
async function macOSMakeChromiumHelpersExecutable(executablePath) {
  const helperApps = [
    "Chromium Helper",
    "Chromium Helper (GPU)",
    "Chromium Helper (Plugin)",
    "Chromium Helper (Renderer)"
  ];
  const frameworkPath = resolve7(
    executablePath,
    join9("..", "..", "Frameworks", "Chromium Framework.framework", "Versions")
  );
  const versionPath = join9(frameworkPath, "Current");
  try {
    const version4 = await Deno.readTextFile(versionPath);
    for (const helperApp of helperApps) {
      const helperAppPath = join9(
        frameworkPath,
        version4,
        "Helpers",
        helperApp + ".app",
        "Contents",
        "MacOS",
        helperApp
      );
      await Deno.chmod(helperAppPath, 493);
    }
  } catch (err2) {
    console.error("Failed to make Chromium Helpers executable", String(err2));
  }
}
var debugFetcher, downloadURLs, browserConfig, BrowserFetcher;
var init_BrowserFetcher = __esm({
  async "https://deno.land/x/puppeteer@9.0.2/src/deno/BrowserFetcher.ts"() {
    init_Debug();
    init_assert2();
    init_std();
    init_mod13();
    await init_cache();
    debugFetcher = debug2(`puppeteer:fetcher`);
    downloadURLs = {
      chrome: {
        linux: "%s/chromium-browser-snapshots/Linux_x64/%d/%s.zip",
        mac: "%s/chromium-browser-snapshots/Mac/%d/%s.zip",
        win32: "%s/chromium-browser-snapshots/Win/%d/%s.zip",
        win64: "%s/chromium-browser-snapshots/Win_x64/%d/%s.zip"
      },
      firefox: {
        linux: "%s/firefox-%s.en-US.%s-x86_64.tar.bz2",
        mac: "%s/firefox-%s.en-US.%s.dmg",
        win32: "%s/firefox-%s.en-US.%s.zip",
        win64: "%s/firefox-%s.en-US.%s.zip"
      }
    };
    browserConfig = {
      chrome: {
        host: "https://storage.googleapis.com",
        destination: "chromium"
      },
      firefox: {
        host: "https://archive.mozilla.org/pub/firefox/nightly/latest-mozilla-central",
        destination: "firefox"
      }
    };
    BrowserFetcher = class {
      _product;
      _downloadsFolder;
      _downloadHost;
      _platform;
      /**
       * @internal
       */
      constructor(options = {}) {
        this._product = (options.product || "chrome").toLowerCase();
        assert3(
          this._product === "chrome" || this._product === "firefox",
          `Unknown product: "${options.product}"`
        );
        this._downloadsFolder = options.path || join9(
          cachedir(),
          "deno_puppeteer",
          browserConfig[this._product].destination
        );
        this._downloadHost = options.host || browserConfig[this._product].host;
        this.setPlatform(options.platform);
        assert3(
          downloadURLs[this._product][this._platform],
          "Unsupported platform: " + this._platform
        );
      }
      setPlatform(platformFromOptions) {
        if (platformFromOptions) {
          this._platform = platformFromOptions;
          return;
        }
        const platform2 = Deno.build.os;
        if (platform2 === "darwin") this._platform = "mac";
        else if (platform2 === "linux") this._platform = "linux";
        else if (platform2 === "windows") {
          this._platform = Deno.build.arch === "x86_64" ? "win64" : "win32";
        } else assert3(this._platform, "Unsupported platform: " + Deno.build.os);
      }
      /**
       * @returns Returns the current `Platform`.
       */
      platform() {
        return this._platform;
      }
      /**
       * @returns Returns the current `Product`.
       */
      product() {
        return this._product;
      }
      /**
       * @returns The download host being used.
       */
      host() {
        return this._downloadHost;
      }
      /**
       * Initiates a HEAD request to check if the revision is available.
       * @remarks
       * This method is affected by the current `product`.
       * @param revision - The revision to check availability for.
       * @returns A promise that resolves to `true` if the revision could be downloaded
       * from the host.
       */
      async canDownload(revision) {
        const url = downloadURL(
          this._product,
          this._platform,
          this._downloadHost,
          revision
        );
        const req = await fetch(url, { method: "head" });
        return req.status == 200;
      }
      /**
       * Initiates a GET request to download the revision from the host.
       * @remarks
       * This method is affected by the current `product`.
       * @param revision - The revision to download.
       * @param progressCallback - A function that will be called with two arguments:
       * How many bytes have been downloaded and the total number of bytes of the download.
       * @returns A promise with revision information when the revision is downloaded
       * and extracted.
       */
      async download(revision, progressCallback = () => {
      }) {
        const url = downloadURL(
          this._product,
          this._platform,
          this._downloadHost,
          revision
        );
        const fileName = url.split("/").pop();
        const archivePath = join9(this._downloadsFolder, fileName);
        const outputPath = this._getFolderPath(revision);
        if (await exists(outputPath)) return this.revisionInfo(revision);
        if (!await exists(this._downloadsFolder)) {
          await Deno.mkdir(this._downloadsFolder, { recursive: true });
        }
        if (Deno.build.arch === "arm64") {
          console.error("arm64 downloads not supported.");
          console.error(
            "Use PUPPETEER_EXECUTABLE_PATH to specify an executable path."
          );
          throw new Error();
        }
        try {
          await downloadFile(url, archivePath, progressCallback);
          await install(archivePath, outputPath);
        } finally {
          if (await exists(archivePath)) {
            await Deno.remove(archivePath, { recursive: true });
          }
        }
        const revisionInfo = this.revisionInfo(revision);
        if (revisionInfo && Deno.build.os !== "windows") {
          await Deno.chmod(revisionInfo.executablePath, 493);
          if (Deno.build.os === "darwin" && this._product === "chrome") {
            await macOSMakeChromiumHelpersExecutable(revisionInfo.executablePath);
          }
        }
        return revisionInfo;
      }
      /**
       * @remarks
       * This method is affected by the current `product`.
       * @returns A promise with a list of all revision strings (for the current `product`)
       * available locally on disk.
       */
      async localRevisions() {
        if (!await exists(this._downloadsFolder)) return [];
        const fileNames = [];
        for await (const file of Deno.readDir(this._downloadsFolder)) {
          fileNames.push(file.name);
        }
        return fileNames.map((fileName) => parseName(this._product, fileName)).filter((entry) => entry && entry.platform === this._platform).map((entry) => entry.revision);
      }
      /**
       * @remarks
       * This method is affected by the current `product`.
       * @param revision - A revision to remove for the current `product`.
       * @returns A promise that resolves when the revision has been removes or
       * throws if the revision has not been downloaded.
       */
      async remove(revision) {
        const folderPath = this._getFolderPath(revision);
        assert3(
          await exists(folderPath),
          `Failed to remove: revision ${revision} is not downloaded`
        );
        await Deno.remove(folderPath, { recursive: true });
      }
      /**
       * @param revision - The revision to get info for.
       * @returns The revision info for the given revision.
       */
      revisionInfo(revision) {
        const folderPath = this._getFolderPath(revision);
        let executablePath = "";
        if (this._product === "chrome") {
          if (this._platform === "mac") {
            executablePath = join9(
              folderPath,
              archiveName(this._product, this._platform, revision),
              "Chromium.app",
              "Contents",
              "MacOS",
              "Chromium"
            );
          } else if (this._platform === "linux") {
            executablePath = join9(
              folderPath,
              archiveName(this._product, this._platform, revision),
              "chrome"
            );
          } else if (this._platform === "win32" || this._platform === "win64") {
            executablePath = join9(
              folderPath,
              archiveName(this._product, this._platform, revision),
              "chrome.exe"
            );
          } else throw new Error("Unsupported platform: " + this._platform);
        } else if (this._product === "firefox") {
          if (this._platform === "mac") {
            executablePath = join9(
              folderPath,
              "Firefox Nightly.app",
              "Contents",
              "MacOS",
              "firefox"
            );
          } else if (this._platform === "linux") {
            executablePath = join9(folderPath, "firefox", "firefox");
          } else if (this._platform === "win32" || this._platform === "win64") {
            executablePath = join9(folderPath, "firefox", "firefox.exe");
          } else throw new Error("Unsupported platform: " + this._platform);
        } else {
          throw new Error("Unsupported product: " + this._product);
        }
        const url = downloadURL(
          this._product,
          this._platform,
          this._downloadHost,
          revision
        );
        const local = existsSync3(folderPath);
        debugFetcher({
          revision,
          executablePath,
          folderPath,
          local,
          url,
          product: this._product
        });
        return {
          revision,
          executablePath,
          folderPath,
          local,
          url,
          product: this._product
        };
      }
      /**
       * @internal
       */
      _getFolderPath(revision) {
        return join9(this._downloadsFolder, this._platform + "-" + revision);
      }
    };
  }
});

// https://deno.land/x/puppeteer@9.0.2/src/deno/BrowserRunner.ts
async function waitForWSEndpoint(browserProcess, timeout, preferredRevision) {
  const timeId = setTimeout(() => {
    throw new TimeoutError(
      `Timed out after ${timeout} ms while trying to connect to the browser! Only Chrome at revision r${preferredRevision} is guaranteed to work.`
    );
  }, timeout);
  for await (const line of readLines(browserProcess.stderr)) {
    const match = line.match(/^DevTools listening on (ws:\/\/.*)$/);
    if (match) {
      clearTimeout(timeId);
      return match[1];
    }
  }
  clearTimeout(timeId);
  throw new Error(
    [
      "Failed to launch the browser process!",
      "TROUBLESHOOTING: https://github.com/puppeteer/puppeteer/blob/main/docs/troubleshooting.md",
      ""
    ].join("\n")
  );
}
var debugLauncher, PROCESS_ERROR_EXPLANATION, BrowserRunner;
var init_BrowserRunner = __esm({
  "https://deno.land/x/puppeteer@9.0.2/src/deno/BrowserRunner.ts"() {
    init_Debug();
    init_assert2();
    init_helper();
    init_Connection();
    init_BrowserWebSocketTransport();
    init_Errors();
    init_std();
    debugLauncher = debug2("puppeteer:launcher");
    PROCESS_ERROR_EXPLANATION = `Puppeteer was unable to kill the process which ran the browser binary.
This means that, on future Puppeteer launches, Puppeteer might not be able to launch the browser.
Please check your open processes and ensure that the browser processes that Puppeteer launched have been killed.
If you think this is a bug, please report it on the Puppeteer issue tracker.`;
    BrowserRunner = class {
      _executablePath;
      _processArguments;
      _tempDirectory;
      proc = void 0;
      connection = void 0;
      _closed = true;
      _listeners = [];
      _processClosing;
      constructor(executablePath, processArguments, tempDirectory) {
        this._executablePath = executablePath;
        this._processArguments = processArguments;
        this._tempDirectory = tempDirectory;
      }
      start(options) {
        const { env: env2, dumpio } = options;
        assert3(!this.proc, "This process has previously been started.");
        debugLauncher(
          `Calling ${this._executablePath} ${this._processArguments.join(" ")}`
        );
        this.proc = Deno.run({
          cmd: [this._executablePath, ...this._processArguments],
          env: env2,
          stdin: "piped",
          stdout: "piped",
          stderr: "piped"
        });
        this._closed = false;
        this._processClosing = this.proc.status().then(async (status) => {
          this._closed = true;
          try {
            if (this.proc) {
              if (!status.success && dumpio) {
                await Deno.copy(this.proc.stdout, Deno.stdout);
                await Deno.copy(this.proc.stderr, Deno.stderr);
              }
              this.proc.stdin.close();
              this.proc.stdout.close();
              this.proc.stderr.close();
              this.proc.close();
            }
          } catch (err2) {
            if (!(err2 instanceof Deno.errors.BadResource)) {
              throw err2;
            }
          }
          if (this._tempDirectory) {
            await Deno.remove(this._tempDirectory, {
              recursive: true
            }).catch((error2) => {
            });
          }
        });
      }
      close() {
        if (this._closed) return Promise.resolve();
        if (this._tempDirectory) {
          this.kill();
        } else if (this.connection) {
          this.connection.send("Browser.close").catch((error2) => {
            debugError(error2);
            this.kill();
          });
        }
        helper.removeEventListeners(this._listeners);
        return this._processClosing;
      }
      kill() {
        try {
          if (this._tempDirectory) {
            Deno.removeSync(this._tempDirectory, { recursive: true });
          }
        } catch (error2) {
        }
        if (this.proc && this.proc.pid && !this._closed) {
          try {
            this.proc.kill("SIGKILL");
          } catch (error2) {
            throw new Error(
              `${PROCESS_ERROR_EXPLANATION}
Error cause: ${error2.stack}`
            );
          }
        }
        helper.removeEventListeners(this._listeners);
      }
      async setupConnection(options) {
        const { timeout, slowMo, preferredRevision } = options;
        const browserWSEndpoint = await waitForWSEndpoint(
          this.proc,
          timeout,
          preferredRevision
        );
        const transport = await BrowserWebSocketTransport.create(browserWSEndpoint);
        this.connection = new Connection(browserWSEndpoint, transport, slowMo);
        return this.connection;
      }
    };
  }
});

// https://deno.land/x/puppeteer@9.0.2/src/deno/Launcher.ts
function resolveExecutablePath(launcher) {
  const executablePath = Deno.env.get("PUPPETEER_EXECUTABLE_PATH");
  if (executablePath) {
    const missingText2 = !existsSync3(executablePath) ? "Tried to use PUPPETEER_EXECUTABLE_PATH env variable to launch browser but did not find any executable at: " + executablePath : void 0;
    return { executablePath, missingText: missingText2 };
  }
  const downloadPath = Deno.env.get("PUPPETEER_DOWNLOAD_PATH");
  const browserFetcher = new BrowserFetcher({
    product: launcher.product,
    path: downloadPath
  });
  if (launcher.product === "chrome") {
    const revision = Deno.env.get("PUPPETEER_CHROMIUM_REVISION");
    if (revision) {
      const revisionInfo2 = browserFetcher.revisionInfo(revision);
      const missingText2 = !revisionInfo2.local ? "Tried to use PUPPETEER_CHROMIUM_REVISION env variable to launch browser but did not find executable at: " + revisionInfo2.executablePath : void 0;
      return { executablePath: revisionInfo2.executablePath, missingText: missingText2 };
    }
  }
  const revisionInfo = browserFetcher.revisionInfo(launcher._preferredRevision);
  const missingText = !revisionInfo.local ? `Could not find browser revision ${launcher._preferredRevision}. Run "PUPPETEER_PRODUCT=${launcher.product} deno run -A --unstable ${new URL(
    "../../vendor/puppeteer-core/puppeteer/../../../install.ts",
    import.meta.url
  )}" to download a supported browser binary.` : void 0;
  return { executablePath: revisionInfo.executablePath, missingText };
}
function Launcher(preferredRevision, product) {
  if (!product) product = Deno.env.get("PUPPETEER_PRODUCT");
  switch (product) {
    case "firefox":
      return new FirefoxLauncher(preferredRevision);
    case "chrome":
    default:
      if (typeof product !== "undefined" && product !== "chrome") {
        console.warn(
          `Warning: unknown product name ${product}. Falling back to chrome.`
        );
      }
      return new ChromeLauncher(preferredRevision);
  }
}
var ChromeLauncher, FirefoxLauncher;
var init_Launcher = __esm({
  async "https://deno.land/x/puppeteer@9.0.2/src/deno/Launcher.ts"() {
    init_Browser();
    init_BrowserRunner();
    init_std();
    await init_BrowserFetcher();
    ChromeLauncher = class {
      _preferredRevision;
      constructor(preferredRevision) {
        this._preferredRevision = preferredRevision;
      }
      async launch(options = {}) {
        const {
          ignoreDefaultArgs = false,
          args = [],
          executablePath = null,
          env: env2 = Deno.env.toObject(),
          ignoreHTTPSErrors = false,
          defaultViewport = { width: 800, height: 600 },
          slowMo = 0,
          timeout = 3e4,
          dumpio = false
        } = options;
        const profilePath = join9(
          await Deno.makeTempDir(),
          "puppeteer_dev_chrome_profile-"
        );
        await Deno.mkdir(profilePath, { recursive: true });
        const chromeArguments = [];
        if (!ignoreDefaultArgs) chromeArguments.push(...this.defaultArgs(options));
        else if (Array.isArray(ignoreDefaultArgs)) {
          chromeArguments.push(
            ...this.defaultArgs(options).filter(
              (arg) => !ignoreDefaultArgs.includes(arg)
            )
          );
        } else chromeArguments.push(...args);
        let temporaryUserDataDir = void 0;
        if (!chromeArguments.some(
          (argument) => argument.startsWith("--remote-debugging-")
        )) {
          chromeArguments.push("--remote-debugging-port=0");
        }
        if (!chromeArguments.some((arg) => arg.startsWith("--user-data-dir"))) {
          temporaryUserDataDir = await Deno.makeTempDir({ dir: profilePath });
          chromeArguments.push(`--user-data-dir=${temporaryUserDataDir}`);
        }
        let chromeExecutable = executablePath;
        if (Deno.build.arch === "arm64") {
          chromeExecutable = "/usr/bin/chromium-browser";
        } else if (!executablePath) {
          const { missingText, executablePath: executablePath2 } = await resolveExecutablePath(this);
          if (missingText) throw new Error(missingText);
          chromeExecutable = executablePath2;
        }
        const runner = new BrowserRunner(
          chromeExecutable,
          chromeArguments,
          temporaryUserDataDir
        );
        runner.start({
          env: env2,
          dumpio
        });
        try {
          const connection = await runner.setupConnection({
            timeout,
            slowMo,
            preferredRevision: this._preferredRevision
          });
          const browser2 = await Browser.create(
            connection,
            [],
            ignoreHTTPSErrors,
            defaultViewport,
            runner.proc,
            runner.close.bind(runner)
          );
          await browser2.waitForTarget((t5) => t5.type() === "page");
          return browser2;
        } catch (error2) {
          runner.kill();
          throw error2;
        }
      }
      /**
       * @param {!Launcher.ChromeArgOptions=} options
       * @returns {!Array<string>}
       */
      defaultArgs(options = {}) {
        const chromeArguments = [
          "--disable-background-networking",
          "--enable-features=NetworkService,NetworkServiceInProcess",
          "--disable-background-timer-throttling",
          "--disable-backgrounding-occluded-windows",
          "--disable-breakpad",
          "--disable-client-side-phishing-detection",
          "--disable-component-extensions-with-background-pages",
          "--disable-default-apps",
          "--disable-dev-shm-usage",
          "--disable-extensions",
          "--disable-features=Translate",
          "--disable-hang-monitor",
          "--disable-ipc-flooding-protection",
          "--disable-popup-blocking",
          "--disable-prompt-on-repost",
          "--disable-renderer-backgrounding",
          "--disable-sync",
          "--force-color-profile=srgb",
          "--metrics-recording-only",
          "--no-first-run",
          "--enable-automation",
          "--password-store=basic",
          "--use-mock-keychain",
          // TODO(sadym): remove '--enable-blink-features=IdleDetection'
          // once IdleDetection is turned on by default.
          "--enable-blink-features=IdleDetection"
        ];
        const {
          devtools = false,
          headless = !devtools,
          args = [],
          userDataDir: userDataDir2 = null
        } = options;
        if (userDataDir2) {
          chromeArguments.push(`--user-data-dir=${resolve7(userDataDir2)}`);
        }
        if (devtools) chromeArguments.push("--auto-open-devtools-for-tabs");
        if (headless) {
          chromeArguments.push("--headless", "--hide-scrollbars", "--mute-audio");
        }
        if (args.every((arg) => arg.startsWith("-"))) {
          chromeArguments.push("about:blank");
        }
        chromeArguments.push(...args);
        return chromeArguments;
      }
      executablePath() {
        return resolveExecutablePath(this).executablePath;
      }
      get product() {
        return "chrome";
      }
    };
    FirefoxLauncher = class {
      _preferredRevision;
      constructor(preferredRevision) {
        this._preferredRevision = preferredRevision;
      }
      async launch(options = {}) {
        const {
          ignoreDefaultArgs = false,
          args = [],
          executablePath = null,
          env: env2 = Deno.env.toObject(),
          ignoreHTTPSErrors = false,
          defaultViewport = { width: 800, height: 600 },
          slowMo = 0,
          timeout = 3e4,
          extraPrefsFirefox = {}
        } = options;
        const firefoxArguments = [];
        if (!ignoreDefaultArgs) firefoxArguments.push(...this.defaultArgs(options));
        else if (Array.isArray(ignoreDefaultArgs)) {
          firefoxArguments.push(
            ...this.defaultArgs(options).filter(
              (arg) => !ignoreDefaultArgs.includes(arg)
            )
          );
        } else firefoxArguments.push(...args);
        if (!firefoxArguments.some(
          (argument) => argument.startsWith("--remote-debugging-")
        )) {
          firefoxArguments.push("--remote-debugging-port=0");
        }
        let temporaryUserDataDir = void 0;
        if (!firefoxArguments.includes("-profile") && !firefoxArguments.includes("--profile")) {
          temporaryUserDataDir = await this._createProfile(extraPrefsFirefox);
          firefoxArguments.push("--profile");
          firefoxArguments.push(temporaryUserDataDir);
        }
        await this._updateRevision();
        let firefoxExecutable = executablePath;
        if (!executablePath) {
          const { missingText, executablePath: executablePath2 } = resolveExecutablePath(this);
          if (missingText) throw new Error(missingText);
          firefoxExecutable = executablePath2;
        }
        const runner = new BrowserRunner(
          firefoxExecutable,
          firefoxArguments,
          temporaryUserDataDir
        );
        runner.start({
          env: env2
        });
        try {
          const connection = await runner.setupConnection({
            timeout,
            slowMo,
            preferredRevision: this._preferredRevision
          });
          const browser2 = await Browser.create(
            connection,
            [],
            ignoreHTTPSErrors,
            defaultViewport,
            runner.proc,
            runner.close.bind(runner)
          );
          await browser2.waitForTarget((t5) => t5.type() === "page");
          return browser2;
        } catch (error2) {
          runner.kill();
          throw error2;
        }
      }
      executablePath() {
        return resolveExecutablePath(this).executablePath;
      }
      async _updateRevision() {
        if (this._preferredRevision === "latest") {
          const browserFetcher = new BrowserFetcher({
            product: this.product
          });
          const localRevisions = await browserFetcher.localRevisions();
          if (localRevisions[0]) this._preferredRevision = localRevisions[0];
        }
      }
      get product() {
        return "firefox";
      }
      defaultArgs(options = {}) {
        const firefoxArguments = ["--no-remote", "--foreground"];
        if (Deno.build.os == "windows") {
          firefoxArguments.push("--wait-for-browser");
        }
        const {
          devtools = false,
          headless = !devtools,
          args = [],
          userDataDir: userDataDir2 = null
        } = options;
        if (userDataDir2) {
          firefoxArguments.push("--profile");
          firefoxArguments.push(userDataDir2);
        }
        if (headless) firefoxArguments.push("--headless");
        if (devtools) firefoxArguments.push("--devtools");
        if (args.every((arg) => arg.startsWith("-"))) {
          firefoxArguments.push("about:blank");
        }
        firefoxArguments.push(...args);
        return firefoxArguments;
      }
      async _createProfile(extraPrefs) {
        const profilePath = join9(
          await Deno.makeTempDir(),
          "puppeteer_dev_firefox_profile-"
        );
        await Deno.mkdir(profilePath, { recursive: true });
        const prefsJS = [];
        const userJS = [];
        const server = "dummy.test";
        const defaultPreferences = {
          // Make sure Shield doesn't hit the network.
          "app.normandy.api_url": "",
          // Disable Firefox old build background check
          "app.update.checkInstallTime": false,
          // Disable automatically upgrading Firefox
          "app.update.disabledForTesting": true,
          // Increase the APZ content response timeout to 1 minute
          "apz.content_response_timeout": 6e4,
          // Prevent various error message on the console
          // jest-puppeteer asserts that no error message is emitted by the console
          "browser.contentblocking.features.standard": "-tp,tpPrivate,cookieBehavior0,-cm,-fp",
          // Enable the dump function: which sends messages to the system
          // console
          // https://bugzilla.mozilla.org/show_bug.cgi?id=1543115
          "browser.dom.window.dump.enabled": true,
          // Disable topstories
          "browser.newtabpage.activity-stream.feeds.system.topstories": false,
          // Always display a blank page
          "browser.newtabpage.enabled": false,
          // Background thumbnails in particular cause grief: and disabling
          // thumbnails in general cannot hurt
          "browser.pagethumbnails.capturing_disabled": true,
          // Disable safebrowsing components.
          "browser.safebrowsing.blockedURIs.enabled": false,
          "browser.safebrowsing.downloads.enabled": false,
          "browser.safebrowsing.malware.enabled": false,
          "browser.safebrowsing.passwords.enabled": false,
          "browser.safebrowsing.phishing.enabled": false,
          // Disable updates to search engines.
          "browser.search.update": false,
          // Do not restore the last open set of tabs if the browser has crashed
          "browser.sessionstore.resume_from_crash": false,
          // Skip check for default browser on startup
          "browser.shell.checkDefaultBrowser": false,
          // Disable newtabpage
          "browser.startup.homepage": "about:blank",
          // Do not redirect user when a milstone upgrade of Firefox is detected
          "browser.startup.homepage_override.mstone": "ignore",
          // Start with a blank page about:blank
          "browser.startup.page": 0,
          // Do not allow background tabs to be zombified on Android: otherwise for
          // tests that open additional tabs: the test harness tab itself might get
          // unloaded
          "browser.tabs.disableBackgroundZombification": false,
          // Do not warn when closing all other open tabs
          "browser.tabs.warnOnCloseOtherTabs": false,
          // Do not warn when multiple tabs will be opened
          "browser.tabs.warnOnOpen": false,
          // Disable the UI tour.
          "browser.uitour.enabled": false,
          // Turn off search suggestions in the location bar so as not to trigger
          // network connections.
          "browser.urlbar.suggest.searches": false,
          // Disable first run splash page on Windows 10
          "browser.usedOnWindows10.introURL": "",
          // Do not warn on quitting Firefox
          "browser.warnOnQuit": false,
          // Defensively disable data reporting systems
          "datareporting.healthreport.documentServerURI": `http://${server}/dummy/healthreport/`,
          "datareporting.healthreport.logging.consoleEnabled": false,
          "datareporting.healthreport.service.enabled": false,
          "datareporting.healthreport.service.firstRun": false,
          "datareporting.healthreport.uploadEnabled": false,
          // Do not show datareporting policy notifications which can interfere with tests
          "datareporting.policy.dataSubmissionEnabled": false,
          "datareporting.policy.dataSubmissionPolicyBypassNotification": true,
          // DevTools JSONViewer sometimes fails to load dependencies with its require.js.
          // This doesn't affect Puppeteer but spams console (Bug 1424372)
          "devtools.jsonview.enabled": false,
          // Disable popup-blocker
          "dom.disable_open_during_load": false,
          // Enable the support for File object creation in the content process
          // Required for |Page.setFileInputFiles| protocol method.
          "dom.file.createInChild": true,
          // Disable the ProcessHangMonitor
          "dom.ipc.reportProcessHangs": false,
          // Disable slow script dialogues
          "dom.max_chrome_script_run_time": 0,
          "dom.max_script_run_time": 0,
          // Only load extensions from the application and user profile
          // AddonManager.SCOPE_PROFILE + AddonManager.SCOPE_APPLICATION
          "extensions.autoDisableScopes": 0,
          "extensions.enabledScopes": 5,
          // Disable metadata caching for installed add-ons by default
          "extensions.getAddons.cache.enabled": false,
          // Disable installing any distribution extensions or add-ons.
          "extensions.installDistroAddons": false,
          // Disabled screenshots extension
          "extensions.screenshots.disabled": true,
          // Turn off extension updates so they do not bother tests
          "extensions.update.enabled": false,
          // Turn off extension updates so they do not bother tests
          "extensions.update.notifyUser": false,
          // Make sure opening about:addons will not hit the network
          "extensions.webservice.discoverURL": `http://${server}/dummy/discoveryURL`,
          // Force disable Fission until the Remote Agent is compatible
          "fission.autostart": false,
          // Allow the application to have focus even it runs in the background
          "focusmanager.testmode": true,
          // Disable useragent updates
          "general.useragent.updates.enabled": false,
          // Always use network provider for geolocation tests so we bypass the
          // macOS dialog raised by the corelocation provider
          "geo.provider.testing": true,
          // Do not scan Wifi
          "geo.wifi.scan": false,
          // No hang monitor
          "hangmonitor.timeout": 0,
          // Show chrome errors and warnings in the error console
          "javascript.options.showInConsole": true,
          // Disable download and usage of OpenH264: and Widevine plugins
          "media.gmp-manager.updateEnabled": false,
          // Prevent various error message on the console
          // jest-puppeteer asserts that no error message is emitted by the console
          "network.cookie.cookieBehavior": 0,
          // Do not prompt for temporary redirects
          "network.http.prompt-temp-redirect": false,
          // Disable speculative connections so they are not reported as leaking
          // when they are hanging around
          "network.http.speculative-parallel-limit": 0,
          // Do not automatically switch between offline and online
          "network.manage-offline-status": false,
          // Make sure SNTP requests do not hit the network
          "network.sntp.pools": server,
          // Disable Flash.
          "plugin.state.flash": 0,
          "privacy.trackingprotection.enabled": false,
          // Enable Remote Agent
          // https://bugzilla.mozilla.org/show_bug.cgi?id=1544393
          "remote.enabled": true,
          // Don't do network connections for mitm priming
          "security.certerrors.mitm.priming.enabled": false,
          // Local documents have access to all other local documents,
          // including directory listings
          "security.fileuri.strict_origin_policy": false,
          // Do not wait for the notification button security delay
          "security.notification_enable_delay": 0,
          // Ensure blocklist updates do not hit the network
          "services.settings.server": `http://${server}/dummy/blocklist/`,
          // Do not automatically fill sign-in forms with known usernames and
          // passwords
          "signon.autofillForms": false,
          // Disable password capture, so that tests that include forms are not
          // influenced by the presence of the persistent doorhanger notification
          "signon.rememberSignons": false,
          // Disable first-run welcome page
          "startup.homepage_welcome_url": "about:blank",
          // Disable first-run welcome page
          "startup.homepage_welcome_url.additional": "",
          // Disable browser animations (tabs, fullscreen, sliding alerts)
          "toolkit.cosmeticAnimations.enabled": false,
          // Prevent starting into safe mode after application crashes
          "toolkit.startup.max_resumed_crashes": -1
        };
        Object.assign(defaultPreferences, extraPrefs);
        for (const [key, value] of Object.entries(defaultPreferences)) {
          userJS.push(
            `user_pref(${JSON.stringify(key)}, ${JSON.stringify(value)});`
          );
        }
        await Deno.writeTextFile(
          join9(profilePath, "user.js"),
          userJS.join("\n")
        );
        await Deno.writeTextFile(
          join9(profilePath, "prefs.js"),
          prefsJS.join("\n")
        );
        return profilePath;
      }
    };
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/revisions.js
var PUPPETEER_REVISIONS;
var init_revisions = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/revisions.js"() {
    PUPPETEER_REVISIONS = {
      chromium: "869685",
      firefox: "latest"
    };
  }
});

// https://deno.land/x/puppeteer@9.0.2/src/deno/Puppeteer.ts
var PuppeteerDeno;
var init_Puppeteer2 = __esm({
  async "https://deno.land/x/puppeteer@9.0.2/src/deno/Puppeteer.ts"() {
    init_Puppeteer();
    await init_BrowserFetcher();
    await init_Launcher();
    init_revisions();
    PuppeteerDeno = class extends Puppeteer {
      _lazyLauncher;
      __productName;
      /**
       * @internal
       */
      _preferredRevision;
      /**
       * @internal
       */
      constructor(settings) {
        const { preferredRevision, productName } = settings;
        super();
        this.__productName = productName;
        this._preferredRevision = preferredRevision;
      }
      /**
       * This method attaches Puppeteer to an existing browser instance.
       *
       * @remarks
       *
       * @param options - Set of configurable options to set on the browser.
       * @returns Promise which resolves to browser instance.
       */
      connect(options) {
        if (options.product) this._productName = options.product;
        return super.connect(options);
      }
      /**
       * @internal
       */
      get _productName() {
        return this.__productName;
      }
      // don't need any TSDoc here - because the getter is internal the setter is too.
      set _productName(name2) {
        if (this.__productName !== name2) this._changedProduct = true;
        this.__productName = name2;
      }
      /**
       * Launches puppeteer and launches a browser instance with given arguments
       * and options when specified.
       *
       * @remarks
       *
       * @example
       * You can use `ignoreDefaultArgs` to filter out `--mute-audio` from default arguments:
       * ```js
       * const browser = await puppeteer.launch({
       *   ignoreDefaultArgs: ['--mute-audio']
       * });
       * ```
       *
       * **NOTE** Puppeteer can also be used to control the Chrome browser,
       * but it works best with the version of Chromium it is bundled with.
       * There is no guarantee it will work with any other version.
       * Use `executablePath` option with extreme caution.
       * If Google Chrome (rather than Chromium) is preferred, a {@link https://www.google.com/chrome/browser/canary.html | Chrome Canary} or {@link https://www.chromium.org/getting-involved/dev-channel | Dev Channel} build is suggested.
       * In `puppeteer.launch([options])`, any mention of Chromium also applies to Chrome.
       * See {@link https://www.howtogeek.com/202825/what%E2%80%99s-the-difference-between-chromium-and-chrome/ | this article} for a description of the differences between Chromium and Chrome. {@link https://chromium.googlesource.com/chromium/src/+/lkgr/docs/chromium_browser_vs_google_chrome.md | This article} describes some differences for Linux users.
       *
       * @param options - Set of configurable options to set on the browser.
       * @returns Promise which resolves to browser instance.
       */
      launch(options = {}) {
        if (options.product) this._productName = options.product;
        return this._launcher.launch(options);
      }
      /**
       * @remarks
       *
       * **NOTE** `puppeteer.executablePath()` is affected by the `PUPPETEER_EXECUTABLE_PATH`
       * and `PUPPETEER_CHROMIUM_REVISION` environment variables.
       *
       * @returns A path where Puppeteer expects to find the bundled browser.
       * The browser binary might not be there if the download was skipped with
       * the `PUPPETEER_SKIP_DOWNLOAD` environment variable.
       */
      executablePath() {
        return this._launcher.executablePath();
      }
      /**
       * @internal
       */
      get _launcher() {
        if (!this._lazyLauncher || this._lazyLauncher.product !== this._productName || this._changedProduct) {
          switch (this._productName) {
            case "firefox":
              this._preferredRevision = PUPPETEER_REVISIONS.firefox;
              break;
            case "chrome":
            default:
              this._preferredRevision = PUPPETEER_REVISIONS.chromium;
          }
          this._changedProduct = false;
          this._lazyLauncher = Launcher(this._preferredRevision, this._productName);
        }
        return this._lazyLauncher;
      }
      /**
       * The name of the browser that is under automation (`"chrome"` or `"firefox"`)
       *
       * @remarks
       * The product is set by the `PUPPETEER_PRODUCT` environment variable or the `product`
       * option in `puppeteer.launch([options])` and defaults to `chrome`.
       * Firefox support is experimental.
       */
      get product() {
        return this._launcher.product;
      }
      /**
       *
       * @param options - Set of configurable options to set on the browser.
       * @returns The default flags that Chromium will be launched with.
       */
      defaultArgs(options = {}) {
        return this._launcher.defaultArgs(options);
      }
      /**
       * @param options - Set of configurable options to specify the settings
       * of the BrowserFetcher.
       * @returns A new BrowserFetcher instance.
       */
      createBrowserFetcher(options) {
        return new BrowserFetcher(options);
      }
    };
  }
});

// https://deno.land/x/puppeteer@9.0.2/src/initialize-deno.ts
var initializePuppeteerDeno;
var init_initialize_deno = __esm({
  async "https://deno.land/x/puppeteer@9.0.2/src/initialize-deno.ts"() {
    await init_Puppeteer2();
    init_revisions();
    initializePuppeteerDeno = () => {
      const productName = Deno.env.get("PUPPETEER_PRODUCT");
      let preferredRevision = PUPPETEER_REVISIONS.chromium;
      if (productName == "firefox") preferredRevision = PUPPETEER_REVISIONS.firefox;
      return new PuppeteerDeno({
        preferredRevision,
        productName
      });
    };
  }
});

// https://deno.land/x/puppeteer@9.0.2/src/mod.ts
var mod_default3;
var init_mod15 = __esm({
  async "https://deno.land/x/puppeteer@9.0.2/src/mod.ts"() {
    await init_initialize_deno();
    mod_default3 = initializePuppeteerDeno();
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/PuppeteerViewport.js
var init_PuppeteerViewport = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/PuppeteerViewport.js"() {
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/Product.js
var init_Product = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/Product.js"() {
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/EvalTypes.js
var init_EvalTypes = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/common/EvalTypes.js"() {
  }
});

// https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/api-docs-entry.js
var init_api_docs_entry = __esm({
  "https://deno.land/x/puppeteer@9.0.2/vendor/puppeteer-core/puppeteer/api-docs-entry.js"() {
    init_Accessibility();
    init_Browser();
    init_Coverage();
    init_Connection();
    init_ConsoleMessage();
    init_Coverage();
    init_DeviceDescriptors();
    init_Dialog();
    init_DOMWorld();
    init_JSHandle();
    init_ExecutionContext();
    init_EventEmitter();
    init_FileChooser();
    init_FrameManager();
    init_PuppeteerViewport();
    init_Input();
    init_Page();
    init_Product();
    init_Puppeteer();
    init_BrowserConnector();
    init_HTTPRequest();
    init_HTTPResponse();
    init_SecurityDetails();
    init_Target();
    init_Errors();
    init_Tracing();
    init_NetworkManager();
    init_WebWorker();
    init_USKeyboardLayout();
    init_EvalTypes();
    init_PDFOptions();
    init_TimeoutSettings();
    init_LifecycleWatcher();
    init_QueryHandler();
    init_NetworkConditions();
  }
});

// https://deno.land/x/puppeteer@9.0.2/mod.ts
var mod_default4;
var init_mod16 = __esm({
  async "https://deno.land/x/puppeteer@9.0.2/mod.ts"() {
    await init_mod15();
    init_api_docs_entry();
    mod_default4 = mod_default3;
  }
});

// core/zip.ts
function unzip(file, dir) {
  if (!dir) dir = dirname4(file);
  if (isWindows4 && file.endsWith(".exe")) {
    return safeWindowsExec(
      file,
      ["-y"],
      (cmd) => {
        return execProcess({
          cmd: cmd[0],
          args: cmd.slice(1),
          cwd: dir,
          stdout: "piped"
        });
      }
    );
  } else if (file.endsWith("zip")) {
    if (isWindows4) {
      const args = [
        "-Command",
        `"& { Add-Type -A 'System.IO.Compression.FileSystem'; [IO.Compression.ZipFile]::ExtractToDirectory('${file}', '${dir}'); }"`
      ];
      return safeWindowsExec(
        "powershell",
        args,
        (cmd) => {
          return execProcess(
            {
              cmd: cmd[0],
              args: cmd.slice(1),
              stdout: "piped"
            }
          );
        }
      );
    } else {
      return execProcess(
        { cmd: "unzip", args: ["-o", file], cwd: dir, stdout: "piped" }
      );
    }
  } else {
    let tarCmd = "tar";
    if (isWindows4) {
      const systemRoot = Deno.env.get("SystemRoot") || "C:\\Windows";
      const system32Tar = `${systemRoot}\\System32\\tar.exe`;
      if (existsSync2(system32Tar)) {
        tarCmd = system32Tar;
      }
    }
    return execProcess(
      { cmd: tarCmd, args: ["xf", file], cwd: dir, stdout: "piped" }
    );
  }
}
function zip(files, archive, options) {
  if (options?.overwrite === false && existsSync2(archive)) {
    throw new Error(`An archive already exits at ${archive}`);
  }
  const filesArr = Array.isArray(files) ? files : [files];
  const zipCmd = () => {
    if (isWindows4) {
      return [
        "PowerShell",
        "Compress-Archive",
        "-Path",
        filesArr.map((x3) => `"${x3}"`).join(", "),
        "-DestinationPath",
        archive,
        "-Force"
      ];
    } else {
      return [
        "zip",
        "-r",
        archive,
        ...filesArr
      ];
    }
  };
  const cmd = zipCmd();
  return execProcess({
    cmd: cmd[0],
    args: cmd.slice(1),
    cwd: options?.cwd,
    stdout: "piped",
    stderr: "piped"
  });
}
var init_zip = __esm({
  "core/zip.ts"() {
    init_path();
    init_fs();
    init_platform();
    init_process();
    init_windows();
  }
});

// tools/impl/chrome-for-testing.ts
function detectChromePlatform() {
  const platformMap = {
    "linux-x86_64": "linux64",
    "linux-aarch64": "linux-arm64",
    "darwin-aarch64": "mac-arm64",
    "darwin-x86_64": "mac-x64",
    "windows-x86_64": "win64",
    "windows-x86": "win32"
  };
  const key = `${os}-${arch}`;
  const platform2 = platformMap[key];
  if (!platform2) {
    throw new Error(
      `Unsupported platform for chrome-headless-shell: ${os} ${arch}`
    );
  }
  return { platform: platform2, os, arch };
}
function isPlaywrightCdnPlatform(info2) {
  const p5 = info2 ?? detectChromePlatform();
  return p5.platform === "linux-arm64";
}
async function fetchLatestCftRelease() {
  let response;
  try {
    response = await fetch(kCftVersionsUrl);
  } catch (e5) {
    throw new Error(
      `Failed to fetch Chrome for Testing API: ${e5 instanceof Error ? e5.message : String(e5)}`
    );
  }
  if (!response.ok) {
    throw new Error(
      `Chrome for Testing API returned ${response.status}: ${response.statusText}`
    );
  }
  let data3;
  try {
    data3 = await response.json();
  } catch {
    throw new Error("Chrome for Testing API returned invalid JSON");
  }
  const stable = data3?.channels?.Stable;
  if (!stable || !stable.version || !stable.downloads) {
    throw new Error(
      "Chrome for Testing API response missing expected 'channels.Stable' structure"
    );
  }
  return {
    version: stable.version,
    downloads: stable.downloads
  };
}
async function fetchPlaywrightBrowsersJson() {
  let response;
  const fallbackHint = "\nIf this persists, install a system Chrome/Chromium instead (Quarto will detect it automatically).";
  try {
    response = await fetch(kPlaywrightBrowsersJsonUrl);
  } catch (e5) {
    throw new Error(
      `Failed to fetch Playwright browsers.json: ${e5 instanceof Error ? e5.message : String(e5)}${fallbackHint}`
    );
  }
  if (!response.ok) {
    throw new Error(
      `Playwright browsers.json returned ${response.status}: ${response.statusText}${fallbackHint}`
    );
  }
  let data3;
  try {
    data3 = await response.json();
  } catch {
    throw new Error("Playwright browsers.json returned invalid JSON");
  }
  const browsers = data3?.browsers;
  if (!Array.isArray(browsers)) {
    throw new Error("Playwright browsers.json missing 'browsers' array");
  }
  const entry = browsers.find((b3) => b3.name === "chromium-headless-shell");
  if (!entry || !entry.revision || !entry.browserVersion) {
    throw new Error(
      "Playwright browsers.json has no 'chromium-headless-shell' entry with revision and browserVersion"
    );
  }
  return {
    revision: entry.revision,
    browserVersion: entry.browserVersion
  };
}
function playwrightCdnDownloadUrl(revision) {
  return `https://cdn.playwright.dev/builds/chromium/${revision}/chromium-headless-shell-linux-arm64.zip`;
}
function findChromeExecutable(extractedDir, binaryName) {
  const target = isWindows4 ? `${binaryName}.exe` : binaryName;
  try {
    const { platform: platform2 } = detectChromePlatform();
    const knownPath = join4(extractedDir, `${binaryName}-${platform2}`, target);
    if (existsSync2(knownPath)) {
      return knownPath;
    }
  } catch (e5) {
    debug(`findChromeExecutable: platform detection failed, falling back to walk: ${e5}`);
  }
  for (const entry of walkSync(extractedDir, { includeDirs: false, maxDepth: 3 })) {
    if (basename4(entry.path) === target) {
      return entry.path;
    }
  }
  return void 0;
}
async function downloadAndExtractChrome(label, url, targetDir, context, binaryName) {
  const tempZipPath = Deno.makeTempFileSync({ suffix: ".zip" });
  try {
    await context.download(label, url, tempZipPath);
    await unzip(tempZipPath, targetDir);
  } finally {
    safeRemoveSync(tempZipPath);
  }
  if (binaryName) {
    const executable = findChromeExecutable(targetDir, binaryName);
    if (executable) {
      safeChmodSync(executable, 493);
    } else {
      debug(`downloadAndExtractChrome: expected binary '${binaryName}' not found in ${targetDir}`);
    }
  }
  return targetDir;
}
var kCftVersionsUrl, kPlaywrightBrowsersJsonUrl;
var init_chrome_for_testing = __esm({
  "tools/impl/chrome-for-testing.ts"() {
    init_path();
    init_fs();
    init_log();
    init_platform();
    init_zip();
    kCftVersionsUrl = "https://googlechromelabs.github.io/chrome-for-testing/last-known-good-versions-with-downloads.json";
    kPlaywrightBrowsersJsonUrl = "https://raw.githubusercontent.com/microsoft/playwright/main/packages/playwright-core/browsers.json";
  }
});

// tools/impl/chrome-headless-shell-paths.ts
function chromeHeadlessShellInstallDir() {
  return quartoDataDir("chrome-headless-shell");
}
function chromeHeadlessShellBinaryName() {
  try {
    return isPlaywrightCdnPlatform() ? "headless_shell" : "chrome-headless-shell";
  } catch {
    return "chrome-headless-shell";
  }
}
function chromeHeadlessShellExecutablePath() {
  const dir = chromeHeadlessShellInstallDir();
  if (!existsSync2(dir)) {
    return void 0;
  }
  return findChromeExecutable(dir, chromeHeadlessShellBinaryName());
}
function noteInstalledVersion(dir, version4) {
  Deno.writeTextFileSync(join4(dir, kVersionFileName), version4);
}
function readInstalledVersion(dir) {
  const path3 = join4(dir, kVersionFileName);
  if (!existsSync2(path3)) {
    return void 0;
  }
  const text = Deno.readTextFileSync(path3).trim();
  return text || void 0;
}
function isInstalled(dir) {
  return existsSync2(join4(dir, kVersionFileName)) && findChromeExecutable(dir, chromeHeadlessShellBinaryName()) !== void 0;
}
var kVersionFileName;
var init_chrome_headless_shell_paths = __esm({
  "tools/impl/chrome-headless-shell-paths.ts"() {
    init_path();
    init_fs();
    init_appdirs();
    init_chrome_for_testing();
    kVersionFileName = "version";
  }
});

// core/puppeteer.ts
async function getPuppeteer() {
  return mod_default4;
}
async function findChrome() {
  let path3;
  let source2;
  if (isMac) {
    const programs = [
      "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
      "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"
    ];
    path3 = programs.find(safeExistsSync);
    source2 = "MacOS known location";
  } else if (isWindows4) {
    const programs = ["chrome.exe", "msedge.exe"];
    for (let i6 = 0; i6 < programs.length; i6++) {
      path3 = await readRegistryKey(
        "HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\" + programs[i6],
        "(Default)"
      );
      if (path3 && safeExistsSync(path3)) {
        source2 = "Windows Registry";
        break;
      }
    }
    if (!path3) {
      const regKeys = ["ChromeHTML", "MSEdgeHTM"];
      for (let i6 = 0; i6 < regKeys.length; i6++) {
        path3 = await readRegistryKey(
          `HKCR\\${regKeys[i6]}\\shell\\open\\command`,
          "(Default)"
        );
        path3 = path3?.match(/"(.*)"/);
        path3 = path3 ? path3[1] : void 0;
        if (path3 && existsSync2(path3)) {
          source2 = "Windows Registry";
          break;
        }
      }
    }
  } else {
    path3 = await which("google-chrome");
    if (!path3) {
      path3 = await which("chromium-browser");
    }
    if (path3 && existsSync2(path3)) {
      source2 = "PATH";
    }
  }
  if (path3) {
    debug("[CHROMIUM] Found Chromium on OS known location");
    debug(`[CHROMIUM] Path: ${path3}`);
  } else {
    debug("[CHROMIUM] Chromium not found on OS known location");
  }
  return { path: path3, source: source2 };
}
async function detectBrowser() {
  const result2 = {};
  const envPath = Deno.env.get("QUARTO_CHROMIUM");
  if (envPath) {
    if (safeExistsSync(envPath)) {
      result2.detected = {
        path: envPath,
        source: "QUARTO_CHROMIUM",
        label: "Chrome from QUARTO_CHROMIUM"
      };
      return result2;
    }
    result2.warning = `QUARTO_CHROMIUM is set to ${envPath} but the path does not exist.`;
  }
  const chromeHsPath = chromeHeadlessShellExecutablePath();
  if (chromeHsPath !== void 0) {
    const version4 = readInstalledVersion(chromeHeadlessShellInstallDir());
    result2.detected = {
      path: chromeHsPath,
      source: "quarto-chrome-headless-shell",
      label: "Chrome Headless Shell installed by Quarto",
      version: version4
    };
    return result2;
  }
  const chromeInfo = await findChrome();
  if (chromeInfo.path) {
    result2.detected = {
      path: chromeInfo.path,
      source: chromeInfo.source ?? "system",
      label: "Chrome found on system",
      displaySource: chromeInfo.source
    };
    return result2;
  }
  return result2;
}
async function getBrowserExecutablePath() {
  const detection = await detectBrowser();
  if (detection.detected) {
    debug(`[CHROMIUM] Using ${detection.detected.label}: ${detection.detected.path}`);
    return detection.detected.path;
  }
  if (detection.warning) {
    debug(`[CHROMIUM] ${detection.warning} Searching for another browser.`);
  }
  const browserFetcher = await fetcher();
  const availableRevisions = await browserFetcher.localRevisions();
  if (availableRevisions.length > 0) {
    availableRevisions.sort((a5, b3) => Number(b3) - Number(a5));
    const revision = availableRevisions[0];
    const revisionInfo = browserFetcher.revisionInfo(revision);
    return revisionInfo.executablePath;
  }
  error("Chrome not found");
  info(
    "\nNo Chrome or Chromium installation was detected.\n\nPlease run 'quarto install chrome-headless-shell' to install a headless browser.\n"
  );
  throw new Error();
}
async function fetcher() {
  const options = {
    path: chromiumInstallDir()
  };
  const fetcher2 = (await getPuppeteer()).createBrowserFetcher(options);
  return fetcher2;
}
function chromiumInstallDir() {
  return quartoDataDir("chromium");
}
var init_puppeteer = __esm({
  async "core/puppeteer.ts"() {
    init_windows();
    init_path2();
    init_log();
    init_fs();
    init_error2();
    init_appdirs();
    init_platform();
    await init_mod16();
    init_chrome_headless_shell_paths();
  }
});

// core/lib/semaphore.ts
var Semaphore;
var init_semaphore = __esm({
  "core/lib/semaphore.ts"() {
    Semaphore = class {
      value;
      // deno-lint-ignore no-explicit-any
      tasks;
      constructor(value) {
        this.value = value;
        this.tasks = [];
      }
      release() {
        this.value += 1;
        if (this.tasks.length) {
          const { resolve: resolve16 } = this.tasks.pop();
          resolve16();
        }
      }
      async acquire() {
        if (this.value > 0) {
          this.value -= 1;
          return;
        }
        const result2 = new Promise((resolve16, reject2) => {
          this.tasks.push({ resolve: resolve16, reject: reject2 });
        });
        await result2;
        await this.acquire();
      }
      async runExclusive(fun) {
        await this.acquire();
        try {
          const result2 = await fun();
          this.release();
          return result2;
        } catch (e5) {
          this.release();
          throw e5;
        }
      }
    };
  }
});

// core/random.ts
function randomInt(min2, max) {
  min2 = Math.ceil(min2);
  max = Math.floor(max);
  return Math.floor(cryptoRandom() * (max - min2) + min2);
}
function randomHex(length) {
  const result2 = [];
  const hexRef = [
    "0",
    "1",
    "2",
    "3",
    "4",
    "5",
    "6",
    "7",
    "8",
    "9",
    "a",
    "b",
    "c",
    "d",
    "e",
    "f"
  ];
  for (let n5 = 0; n5 < length; n5++) {
    result2.push(hexRef[Math.floor(cryptoRandom() * 16)]);
  }
  return result2.join("");
}
function cryptoRandom() {
  const arr = new Uint32Array(2);
  crypto.getRandomValues(arr);
  const mantissa = arr[0] * Math.pow(2, 20) + (arr[1] >>> 12);
  const result2 = mantissa * Math.pow(2, -52);
  return result2;
}
var init_random = __esm({
  "core/random.ts"() {
  }
});

// core/wait.ts
function sleep2(ms) {
  return new Promise((resolve16) => setTimeout(resolve16, ms));
}
var init_wait = __esm({
  "core/wait.ts"() {
  }
});

// core/port-consts.ts
var kLocalhost;
var init_port_consts = __esm({
  "core/port-consts.ts"() {
    kLocalhost = "127.0.0.1";
  }
});

// core/port.ts
function isPortSafe(port) {
  return ![
    3659,
    // apple-sasl / PasswordServer
    4045,
    // lockd
    4160,
    // sieve
    5060,
    // sip
    5061,
    // sips
    6e3,
    // X11
    6566,
    // sane-port
    6665,
    // Alternate IRC [Apple addition]
    6666,
    // Alternate IRC [Apple addition]
    6667,
    // Standard IRC [Apple addition]
    6668,
    // Alternate IRC [Apple addition]
    6669,
    // Alternate IRC [Apple addition]
    6679,
    // osaut
    6697,
    // IRC + TLS
    7e3
    // As of 2024-10-21, Chrome doesn't appear to like this port anymore
  ].includes(port);
}
function randomSafePort() {
  let result2;
  do {
    result2 = randomInt(kMinPort, kMaxPort);
  } while (!isPortSafe(result2));
  return result2;
}
function findOpenPort(defaultPort) {
  defaultPort = defaultPort || randomSafePort();
  if (isPortAvailableSync({ port: defaultPort, hostname: kLocalhost })) {
    return defaultPort;
  } else {
    let ports = [];
    for (let i6 = kMinPort; i6 < kMaxPort; ++i6) {
      if (isPortSafe(i6)) {
        ports.push(i6);
      }
    }
    while (true) {
      ports = shuffle(ports);
      const port = getAvailablePortSync({
        port: ports,
        hostname: kLocalhost
      });
      if (port === void 0) {
        throw new Error("Unable to find open port");
      }
      if (isPortSafe(port)) {
        return port;
      }
    }
  }
}
async function waitForPort(options, timeout = 5e3) {
  const kWaitInterval = 200;
  let waited = 0;
  while (waited <= timeout) {
    if (isPortAvailableSync(options)) {
      return true;
    }
    await sleep2(kWaitInterval);
    waited += kWaitInterval;
  }
  return false;
}
function isPortAvailableSync(options) {
  try {
    const listener = Deno.listen({
      port: options.port,
      ...options.hostname ? { hostname: options.hostname } : {},
      ...options.transport ? { transport: options.transport } : {}
    });
    listener.close();
    return true;
  } catch (error2) {
    if (error2 instanceof Deno.errors.AddrInUse) {
      return false;
    }
    throw error2;
  }
}
function getAvailablePortSync(options = { transport: "tcp" }) {
  if (options.port === void 0) {
    return getRandomPortSync(options);
  } else if (Array.isArray(options.port)) {
    const portList = options.port;
    for (let i6 = 0; i6 < portList.length; i6++) {
      if (withinRange(portList[i6])) {
        const portAvailable = isPortAvailableSync({
          port: portList[i6],
          ...options.hostname ? { hostname: options.hostname } : {},
          ...options.transport ? { transport: options.transport } : {}
        });
        if (portAvailable) {
          return portList[i6];
        } else {
          continue;
        }
      } else {
        continue;
      }
    }
  } else if (options.port.start !== void 0 && options.port.end !== void 0) {
    const start = options.port.start;
    const end = options.port.end;
    if (start >= 0 && end <= 65535 && start <= end) {
      for (let p5 = start; p5 <= end; p5++) {
        const portAvailable = isPortAvailableSync({
          port: p5,
          ...options.hostname ? { hostname: options.hostname } : {},
          ...options.transport ? { transport: options.transport } : {}
        });
        if (portAvailable) {
          return p5;
        } else {
          continue;
        }
      }
    } else {
      throw new Error(
        "Range should be between 0 - 65535 and start should be less than end"
      );
    }
  }
}
function getRandomPortSync(options) {
  const randomPort = random(0, 65535);
  const restrictedPorts = [
    // from https://chromium.googlesource.com/chromium/src.git/+/refs/heads/master/net/base/port_util.cc
    // as of 2023-02-23.
    1719,
    // h323gatestat
    1720,
    // h323hostcall
    1723,
    // pptp
    2049,
    // nfs
    3659,
    // apple-sasl / PasswordServer
    4045,
    // lockd
    5060,
    // sip
    5061,
    // sips
    6e3,
    // X11
    6566,
    // sane-port
    6665,
    // Alternate IRC [Apple addition]
    6666,
    // Alternate IRC [Apple addition]
    6667,
    // Standard IRC [Apple addition]
    6668,
    // Alternate IRC [Apple addition]
    6669,
    // Alternate IRC [Apple addition]
    6697,
    // IRC + TLS
    10080
    // Amanda
  ];
  if (isPortAvailableSync({
    port: randomPort,
    ...options.hostname ? { hostname: options.hostname } : {},
    ...options.transport ? { transport: options.transport } : {}
  }) && !restrictedPorts.includes(randomPort)) {
    return randomPort;
  } else {
    return getRandomPortSync(options);
  }
}
function random(min2, max) {
  return Math.round(Math.random() * (max - min2)) + min2;
}
function withinRange(port) {
  return port >= 0 && port <= 65535;
}
var kMinPort, kMaxPort;
var init_port = __esm({
  "core/port.ts"() {
    init_lodash();
    init_random();
    init_wait();
    init_port_consts();
    kMinPort = 3e3;
    kMaxPort = 8e3;
  }
});

// core/lifetimes.ts
function waitUntilNamedLifetime(name2) {
  const lt2 = getNamedLifetime(name2);
  if (lt2 === void 0) {
    return Promise.resolve(createNamedLifetime(name2));
  }
  const promise = new Promise((resolve16) => {
    if (_globalAwaitQueues[name2] === void 0) {
      _globalAwaitQueues[name2] = [];
    }
    _globalAwaitQueues[name2].push(resolve16);
  });
  return promise;
}
function createNamedLifetime(name2) {
  if (_globalLifetimes[name2] !== void 0) {
    throw new InternalError(`Lifetime ${name2} already exists.`);
  }
  const lifetime = new Lifetime();
  lifetime.attach({
    cleanup: () => {
      delete _globalLifetimes[name2];
      if (_globalAwaitQueues[name2] && _globalAwaitQueues[name2].length) {
        const resolver = _globalAwaitQueues[name2].shift();
        const newLifetime = createNamedLifetime(name2);
        resolver(newLifetime);
      }
    }
  });
  _globalLifetimes[name2] = lifetime;
  return lifetime;
}
function getNamedLifetime(name2, createIfMissing = false) {
  if (_globalLifetimes[name2] !== void 0) {
    return _globalLifetimes[name2];
  }
  if (createIfMissing) {
    return createNamedLifetime(name2);
  }
}
var _globalLifetimes, _globalAwaitQueues, Lifetime;
var init_lifetimes = __esm({
  "core/lifetimes.ts"() {
    init_error2();
    _globalLifetimes = {};
    _globalAwaitQueues = {};
    Lifetime = class {
      _namedObjs;
      _unnamedObjs;
      constructor() {
        this._namedObjs = {};
        this._unnamedObjs = [];
      }
      attach(obj, key) {
        if (key === void 0) {
          this._unnamedObjs.push(obj);
        } else {
          this._namedObjs[key] = obj;
        }
      }
      get(key) {
        return this._namedObjs[key];
      }
      async cleanup() {
        await Promise.all(this._unnamedObjs.map((x3) => x3.cleanup()));
        await Promise.all(Object.values(this._namedObjs).map((x3) => x3.cleanup()));
        this._namedObjs = {};
        this._unnamedObjs = [];
      }
    };
  }
});

// https://jsr.io/@std/assert/0.224.0/assert_almost_equals.ts
var init_assert_almost_equals = __esm({
  "https://jsr.io/@std/assert/0.224.0/assert_almost_equals.ts"() {
    init_assertion_error();
  }
});

// https://jsr.io/@std/assert/0.224.0/equal.ts
var init_equal = __esm({
  "https://jsr.io/@std/assert/0.224.0/equal.ts"() {
  }
});

// https://jsr.io/@std/internal/0.224.0/format.ts
var init_format10 = __esm({
  "https://jsr.io/@std/internal/0.224.0/format.ts"() {
  }
});

// https://jsr.io/@std/assert/0.224.0/assert_array_includes.ts
var init_assert_array_includes = __esm({
  "https://jsr.io/@std/assert/0.224.0/assert_array_includes.ts"() {
    init_equal();
    init_format10();
    init_assertion_error();
  }
});

// https://jsr.io/@std/internal/0.224.0/diff.ts
var init_diff2 = __esm({
  "https://jsr.io/@std/internal/0.224.0/diff.ts"() {
    init_colors();
  }
});

// https://jsr.io/@std/internal/0.224.0/mod.ts
var init_mod17 = __esm({
  "https://jsr.io/@std/internal/0.224.0/mod.ts"() {
    init_format10();
    init_diff2();
  }
});

// https://jsr.io/@std/assert/0.224.0/_constants.ts
var init_constants11 = __esm({
  "https://jsr.io/@std/assert/0.224.0/_constants.ts"() {
  }
});

// https://jsr.io/@std/assert/0.224.0/assert_equals.ts
var init_assert_equals = __esm({
  "https://jsr.io/@std/assert/0.224.0/assert_equals.ts"() {
    init_equal();
    init_mod17();
    init_assertion_error();
    init_colors();
    init_constants11();
  }
});

// https://jsr.io/@std/assert/0.224.0/assert_exists.ts
function assertExists(actual, msg5) {
  if (actual === void 0 || actual === null) {
    const msgSuffix = msg5 ? `: ${msg5}` : ".";
    msg5 = `Expected actual: "${actual}" to not be null or undefined${msgSuffix}`;
    throw new AssertionError(msg5);
  }
}
var init_assert_exists = __esm({
  "https://jsr.io/@std/assert/0.224.0/assert_exists.ts"() {
    init_assertion_error();
  }
});

// https://jsr.io/@std/assert/0.224.0/assert_false.ts
var init_assert_false = __esm({
  "https://jsr.io/@std/assert/0.224.0/assert_false.ts"() {
    init_assertion_error();
  }
});

// https://jsr.io/@std/assert/0.224.0/assert_greater_or_equal.ts
var init_assert_greater_or_equal = __esm({
  "https://jsr.io/@std/assert/0.224.0/assert_greater_or_equal.ts"() {
    init_format10();
    init_assertion_error();
  }
});

// https://jsr.io/@std/assert/0.224.0/assert_greater.ts
var init_assert_greater = __esm({
  "https://jsr.io/@std/assert/0.224.0/assert_greater.ts"() {
    init_format10();
    init_assertion_error();
  }
});

// https://jsr.io/@std/assert/0.224.0/assert_instance_of.ts
var init_assert_instance_of = __esm({
  "https://jsr.io/@std/assert/0.224.0/assert_instance_of.ts"() {
    init_assertion_error();
  }
});

// https://jsr.io/@std/assert/0.224.0/assert_is_error.ts
var init_assert_is_error = __esm({
  "https://jsr.io/@std/assert/0.224.0/assert_is_error.ts"() {
    init_assertion_error();
    init_colors();
  }
});

// https://jsr.io/@std/assert/0.224.0/assert_less_or_equal.ts
var init_assert_less_or_equal = __esm({
  "https://jsr.io/@std/assert/0.224.0/assert_less_or_equal.ts"() {
    init_format10();
    init_assertion_error();
  }
});

// https://jsr.io/@std/assert/0.224.0/assert_less.ts
var init_assert_less = __esm({
  "https://jsr.io/@std/assert/0.224.0/assert_less.ts"() {
    init_format10();
    init_assertion_error();
  }
});

// https://jsr.io/@std/assert/0.224.0/assert_match.ts
var init_assert_match = __esm({
  "https://jsr.io/@std/assert/0.224.0/assert_match.ts"() {
    init_assertion_error();
  }
});

// https://jsr.io/@std/assert/0.224.0/assert_not_equals.ts
var init_assert_not_equals = __esm({
  "https://jsr.io/@std/assert/0.224.0/assert_not_equals.ts"() {
    init_constants11();
    init_equal();
    init_assertion_error();
  }
});

// https://jsr.io/@std/assert/0.224.0/assert_not_instance_of.ts
var init_assert_not_instance_of = __esm({
  "https://jsr.io/@std/assert/0.224.0/assert_not_instance_of.ts"() {
    init_assert_false();
  }
});

// https://jsr.io/@std/assert/0.224.0/assert_not_match.ts
var init_assert_not_match = __esm({
  "https://jsr.io/@std/assert/0.224.0/assert_not_match.ts"() {
    init_assertion_error();
  }
});

// https://jsr.io/@std/assert/0.224.0/assert_not_strict_equals.ts
var init_assert_not_strict_equals = __esm({
  "https://jsr.io/@std/assert/0.224.0/assert_not_strict_equals.ts"() {
    init_assertion_error();
    init_format10();
  }
});

// https://jsr.io/@std/assert/0.224.0/assert_object_match.ts
var init_assert_object_match = __esm({
  "https://jsr.io/@std/assert/0.224.0/assert_object_match.ts"() {
    init_assert_equals();
  }
});

// https://jsr.io/@std/assert/0.224.0/assert_rejects.ts
var init_assert_rejects = __esm({
  "https://jsr.io/@std/assert/0.224.0/assert_rejects.ts"() {
    init_assertion_error();
    init_assert_is_error();
  }
});

// https://jsr.io/@std/assert/0.224.0/assert_strict_equals.ts
var init_assert_strict_equals = __esm({
  "https://jsr.io/@std/assert/0.224.0/assert_strict_equals.ts"() {
    init_mod17();
    init_assertion_error();
    init_constants11();
    init_colors();
  }
});

// https://jsr.io/@std/assert/0.224.0/assert_string_includes.ts
var init_assert_string_includes = __esm({
  "https://jsr.io/@std/assert/0.224.0/assert_string_includes.ts"() {
    init_assertion_error();
  }
});

// https://jsr.io/@std/assert/0.224.0/assert_throws.ts
var init_assert_throws = __esm({
  "https://jsr.io/@std/assert/0.224.0/assert_throws.ts"() {
    init_assert_is_error();
    init_assertion_error();
  }
});

// https://jsr.io/@std/assert/0.224.0/fail.ts
var init_fail = __esm({
  "https://jsr.io/@std/assert/0.224.0/fail.ts"() {
    init_assert();
  }
});

// https://jsr.io/@std/assert/0.224.0/unimplemented.ts
var init_unimplemented = __esm({
  "https://jsr.io/@std/assert/0.224.0/unimplemented.ts"() {
    init_assertion_error();
  }
});

// https://jsr.io/@std/assert/0.224.0/unreachable.ts
var init_unreachable = __esm({
  "https://jsr.io/@std/assert/0.224.0/unreachable.ts"() {
    init_assertion_error();
  }
});

// https://jsr.io/@std/assert/0.224.0/mod.ts
var init_mod18 = __esm({
  "https://jsr.io/@std/assert/0.224.0/mod.ts"() {
    init_assert_almost_equals();
    init_assert_array_includes();
    init_assert_equals();
    init_assert_exists();
    init_assert_false();
    init_assert_greater_or_equal();
    init_assert_greater();
    init_assert_instance_of();
    init_assert_is_error();
    init_assert_less_or_equal();
    init_assert_less();
    init_assert_match();
    init_assert_not_equals();
    init_assert_not_instance_of();
    init_assert_not_match();
    init_assert_not_strict_equals();
    init_assert_object_match();
    init_assert_rejects();
    init_assert_strict_equals();
    init_assert_string_includes();
    init_assert_throws();
    init_assert();
    init_assertion_error();
    init_equal();
    init_fail();
    init_unimplemented();
    init_unreachable();
  }
});

// https://jsr.io/@std/testing/0.224.0/asserts.ts
function assert7(expr, msg5 = "") {
  assert(expr, msg5);
}
var init_asserts = __esm({
  "https://jsr.io/@std/testing/0.224.0/asserts.ts"() {
    init_mod18();
  }
});

// core/cri/cri.ts
async function waitForServer(port, timeout = 3e3) {
  const interval = 50;
  let soFar = 0;
  do {
    try {
      const response = await fetch(`http://localhost:${port}/json/list`);
      if (response.status !== 200) {
        throw new Error("");
      }
      return true;
    } catch (_e) {
      soFar += interval;
      await new Promise((resolve16) => setTimeout(resolve16, interval));
    }
  } while (soFar < timeout);
  return false;
}
function withCriClient(fn, appPath, port) {
  if (port === void 0) {
    port = findOpenPort(9222);
  }
  return criSemaphore.runExclusive(async () => {
    const lifetime = getNamedLifetime(kRenderFileLifetime);
    if (lifetime === void 0) {
      throw new InternalError("named lifetime render-file not found");
    }
    let client;
    if (lifetime.get("cri-client") === void 0) {
      client = await criClient(appPath, port);
      lifetime.attach({
        client,
        async cleanup() {
          await client.close();
        }
      }, "cri-client");
    } else {
      client = lifetime.get("cri-client").client;
    }
    return await fn(client);
  });
}
async function criClient(appPath, port) {
  if (port === void 0) {
    port = findOpenPort(9222);
  }
  const app = appPath || await getBrowserExecutablePath();
  const headlessMode = getenv("QUARTO_CHROMIUM_HEADLESS_MODE", "none");
  const args = [
    // TODO: Chrome v128 changed the default from --headless=old to --headless=new
    // in 2024-08. Old headless mode was effectively a separate browser render,
    // and while more performant did not share the same browser implementation as
    // headful Chrome. New headless mode will likely be useful to some, but in Quarto use cases
    // like printing to PDF or screenshoting, we need more work to
    // move to the new mode. We'll use `--headless=old` as the default for now
    // until the new mode is more stable, or until we really pin a version as default to be used.
    // This is also impacting in chromote and pagedown R packages and we could keep syncing with them.
    // EDIT: 17/01/2025 - old mode is gone in Chrome 132. Let's default to new mode to unbreak things.
    // Best course of action is to pin a version of Chrome and use the chrome-headless-shell more adapted to our need.
    // ref: https://developer.chrome.com/blog/chrome-headless-shell
    `--headless${headlessMode == "none" ? "" : "=" + headlessMode}`,
    "--no-sandbox",
    "--disable-gpu",
    "--renderer-process-limit=1",
    `--remote-debugging-port=${port}`
  ];
  const browser2 = new Deno.Command(app, {
    args,
    stdout: "piped",
    stderr: "piped"
  });
  const cmd = browser2.spawn();
  const thisProcessId = registerForExitCleanup(cmd);
  if (!await waitForServer(port)) {
    let msg5 = "Couldn't find open server.";
    if (!(await cmd.status).success) {
      debug(`[CHROMIUM path]   : ${app}`);
      debug(`[CHROMIUM cmd]   : ${cmd}`);
      const rawError = await cmd.stderr;
      const reader = rawError.getReader();
      const readerResult = await reader.read();
      assert7(readerResult.done);
      const errorString = new TextDecoder().decode(readerResult.value);
      msg5 = msg5 + `
Chrome process error: ${errorString}`;
    }
    throw new Error(msg5);
  }
  let client;
  const result2 = {
    close: async () => {
      await client.close();
      cmd.kill();
      unregisterForExitCleanup(thisProcessId);
    },
    rawClient: () => client,
    open: async (url) => {
      const maxTries = 5;
      for (let i6 = 0; i6 < maxTries; ++i6) {
        try {
          client = await deno_cri_default({ port });
          break;
        } catch (e5) {
          if (i6 === maxTries - 1) {
            throw e5;
          }
          await sleep(100);
        }
      }
      const { Network, Page: Page2 } = client;
      await Network.enable();
      await Page2.enable();
      await Page2.navigate({ url });
      return new Promise((fulfill, _reject) => {
        Page2.loadEventFired(() => {
          fulfill(null);
        });
      });
    },
    docQuerySelectorAll: async (cssSelector) => {
      await client.DOM.enable();
      const doc = await client.DOM.getDocument();
      const nodeIds = await client.DOM.querySelectorAll({
        nodeId: doc.root.nodeId,
        selector: cssSelector
      });
      return nodeIds.nodeIds;
    },
    contents: async (cssSelector) => {
      const nodeIds = await result2.docQuerySelectorAll(cssSelector);
      return Promise.all(
        // deno-lint-ignore no-explicit-any
        nodeIds.map(async (nodeId) => {
          return (await client.DOM.getOuterHTML({ nodeId })).outerHTML;
        })
      );
    },
    // defaults to screenshotting at 4x scale = 392dpi.
    screenshots: async (cssSelector, scale = 4) => {
      const nodeIds = await result2.docQuerySelectorAll(cssSelector);
      const lst = [];
      for (const nodeId of nodeIds) {
        let quad;
        try {
          quad = (await client.DOM.getContentQuads({ nodeId })).quads[0];
        } catch (_e) {
          continue;
        }
        const minX = Math.min(quad[0], quad[2], quad[4], quad[6]);
        const maxX = Math.max(quad[0], quad[2], quad[4], quad[6]);
        const minY = Math.min(quad[1], quad[3], quad[5], quad[7]);
        const maxY = Math.max(quad[1], quad[3], quad[5], quad[7]);
        try {
          const screenshot = await client.Page.captureScreenshot({
            clip: {
              x: minX,
              y: minY,
              width: maxX - minX,
              height: maxY - minY,
              scale
            },
            fromSurface: true,
            captureBeyondViewport: true
          });
          const buf = decodeBase64(screenshot.data);
          lst.push({ nodeId, data: buf });
        } catch (_e) {
          continue;
        }
      }
      return lst;
    }
  };
  return result2;
}
var criSemaphore;
var init_cri = __esm({
  async "core/cri/cri.ts"() {
    init_base64();
    init_deno_cri();
    await init_puppeteer();
    init_semaphore();
    init_port();
    init_lifetimes();
    init_async();
    init_error2();
    init_env();
    init_constants6();
    init_log();
    init_process();
    init_asserts();
    criSemaphore = new Semaphore(1);
  }
});

// core/handlers/include-standalone.ts
var standaloneInclude;
var init_include_standalone = __esm({
  "core/handlers/include-standalone.ts"() {
    init_mapped_text();
    init_ranged_text();
    init_parse_shortcode();
    standaloneInclude = async (handlerContext, filename) => {
      const source2 = handlerContext.options.context.target.source;
      const retrievedFiles = [source2];
      const textFragments = [];
      if (!handlerContext.options.state) {
        handlerContext.options.state = {};
      }
      if (!handlerContext.options.state.include) {
        handlerContext.options.state.include = {
          includes: []
        };
      }
      const includeState = handlerContext.options.state.include;
      const retrieveInclude = async (filename2) => {
        const path3 = handlerContext.resolvePath(filename2);
        if (retrievedFiles.indexOf(path3) !== -1) {
          throw new Error(
            `Include directive found circular include of file ${filename2}.`
          );
        }
        let includeSrc;
        try {
          includeSrc = asMappedString(
            Deno.readTextFileSync(path3),
            path3
          );
        } catch (_e) {
          const errMsg = [`Include directive failed.`];
          errMsg.push(...retrievedFiles.map((s5) => `  in file ${s5}, `));
          errMsg.push(
            `  could not find file ${path3}.`
          );
          throw new Error(errMsg.join("\n"));
        }
        retrievedFiles.push(filename2);
        let rangeStart = 0;
        for (const { substring, range } of rangedLines(includeSrc.value)) {
          const m4 = isBlockShortcode(substring);
          if (m4 && m4.name.toLocaleLowerCase() === "include") {
            textFragments.push(
              mappedString(includeSrc, [{
                start: rangeStart,
                end: range.start
              }])
            );
            rangeStart = range.end;
            const params = m4.params;
            if (params.length === 0) {
              throw new Error("Include directive needs file parameter");
            }
            includeState.includes.push({ source: filename2, target: params[0] });
            await retrieveInclude(params[0]);
          }
        }
        if (rangeStart !== includeSrc.value.length) {
          textFragments.push(
            mappedString(includeSrc, [{
              start: rangeStart,
              end: includeSrc.value.length
            }])
          );
        }
        textFragments.push(includeSrc.value.endsWith("\n") ? "\n" : "\n\n");
        retrievedFiles.pop();
      };
      await retrieveInclude(filename);
      return Promise.resolve(mappedConcat(textFragments));
    };
  }
});

// core/lib/located-error.ts
var LocalizedError3;
var init_located_error = __esm({
  "core/lib/located-error.ts"() {
    init_mapped_text();
    LocalizedError3 = class extends Error {
      constructor(name2, message, source2, position = 0, printName = true, printStack = true) {
        const fileName = source2.map(position)?.originalString?.fileName;
        if (fileName) {
          const { line, column } = mappedIndexToLineCol(source2)(position);
          message = `In file ${fileName} (${line + 1}:${column + 1}):
${message}`;
        }
        super(message);
        this.name = name2;
        this.printName = printName;
        this.printStack = printStack;
      }
      printName;
      printStack;
    };
  }
});

// core/handlers/base.ts
function resetFigureCounter() {
  globalFigureCounter = {};
}
function makeHandlerContext(options) {
  if (options.state === void 0) {
    options.state = {};
  }
  const results = {
    resourceFiles: [],
    includes: {},
    extras: {},
    supporting: []
  };
  const tempContext2 = options.temp;
  const context = {
    options,
    getState() {
      if (options.state[options.name] === void 0) {
        options.state[options.name] = {};
      }
      return options.state[options.name];
    },
    async extractHtml(opts) {
      const {
        html: content,
        selector
      } = opts;
      const nonEmptyHtmlResources = opts.resources || [];
      const dirName = context.options.temp.createDir();
      for (const [name2, content2] of nonEmptyHtmlResources) {
        Deno.writeTextFileSync(join4(dirName, name2), content2);
      }
      const fileName = join4(dirName, "index.html");
      Deno.writeTextFileSync(fileName, content);
      const url = `file://${fileName}`;
      return await withCriClient(async (client) => {
        await client.open(url);
        return await client.contents(selector);
      });
    },
    async createPngsFromHtml(opts) {
      const {
        prefix,
        html: content,
        deviceScaleFactor,
        selector
      } = opts;
      const nonEmptyHtmlResources = opts.resources || [];
      const dirName = context.options.temp.createDir();
      for (const [name2, content2] of nonEmptyHtmlResources) {
        Deno.writeTextFileSync(join4(dirName, name2), content2);
      }
      const fileName = join4(dirName, "index.html");
      Deno.writeTextFileSync(fileName, content);
      const url = `file://${fileName}`;
      const { elements, images } = await withCriClient(async (client) => {
        await client.open(url);
        const elements2 = await client.contents(selector);
        const screenshots = await client.screenshots(
          selector,
          deviceScaleFactor
        );
        return {
          elements: elements2,
          images: screenshots.map((x3) => x3.data)
        };
      });
      const sourceNames = [];
      for (let i6 = 0; i6 < images.length; ++i6) {
        const { sourceName, fullName } = context.uniqueFigureName(prefix, ".png");
        sourceNames.push(sourceName);
        Deno.writeFileSync(fullName, images[i6]);
      }
      return {
        filenames: sourceNames,
        elements
      };
    },
    cellContent(cell) {
      if (typeof cell?.options?.file === "string") {
        try {
          return mappedStringFromFile(
            context.resolvePath(cell?.options?.file)
          );
        } catch (e5) {
          error(`Couldn't open file ${cell?.options?.file}`);
          throw e5;
        }
      } else {
        return cell.source;
      }
    },
    resolvePath(path3) {
      const sourceDir = dirname4(options.context.target.source);
      const rootDir = options.context.project.isSingleFile ? sourceDir : options.context.project.dir;
      if (path3.startsWith("/")) {
        return resolve4(rootDir, `.${path3}`);
      } else {
        return resolve4(sourceDir, path3);
      }
    },
    uniqueFigureName(prefix, extension) {
      prefix = prefix ?? "figure-";
      extension = extension ?? ".png";
      if (!globalFigureCounter[prefix]) {
        globalFigureCounter[prefix] = 1;
      } else {
        globalFigureCounter[prefix]++;
      }
      const pngName = `${prefix}${globalFigureCounter[prefix]}${extension}`;
      const tempName = join4(context.figuresDir(), pngName);
      const baseDir = dirname4(options.context.target.source);
      const mdName = relative4(baseDir, tempName);
      this.addSupporting(relative4(baseDir, context.figuresDir()));
      return {
        baseName: basename4(mdName),
        sourceName: mdName,
        fullName: tempName
      };
    },
    figuresDir() {
      const file = normalizePath(options.context.target.source);
      const filesDir = join4(dirname4(file), inputFilesDir(file));
      const result2 = join4(
        filesDir,
        figuresDir(context.options.format.pandoc.to)
      );
      ensureDirSync(result2);
      return result2;
    },
    addHtmlDependency(dep) {
      if (results.extras.html === void 0) {
        results.extras.html = { [kDependencies]: [dep] };
      } else {
        results.extras.html[kDependencies].push(dep);
      }
    },
    addSupporting(dir) {
      if (results.supporting.indexOf(dir) === -1) {
        results.supporting.push(dir);
      }
    },
    addResource(fileName) {
      results.resourceFiles.push(fileName);
    },
    addInclude(content, where) {
      const fileName = tempContext2.createFile();
      Deno.writeTextFileSync(fileName, content);
      if (results.includes[where] === void 0) {
        results.includes[where] = [fileName];
      } else {
        results.includes[where].push(fileName);
      }
    }
  };
  return { context, results };
}
function languages() {
  const cellLanguage = [];
  for (const [k3, v4] of Object.entries(handlers2)) {
    if (v4.type === "cell") {
      cellLanguage.push(k3);
    }
  }
  return cellLanguage;
}
async function languageSchema(language) {
  if (handlers2[language] === void 0) {
    return void 0;
  }
  const call2 = handlers2[language].schema;
  if (call2 === void 0) {
    return void 0;
  } else {
    return await call2();
  }
}
function install2(handler) {
  const language = handler.languageName;
  handlers2[language] = handler;
  if (handler.comment !== void 0) {
    addLanguageComment(language, handler.comment);
  }
}
async function expandIncludes(markdown, options, filename) {
  const mdCells = (await breakQuartoMd(markdown, false)).cells;
  if (mdCells.length === 0) {
    return markdown;
  }
  const newCells = [];
  for (let i6 = 0; i6 < mdCells.length; ++i6) {
    const cell = mdCells[i6];
    newCells.push(cell.sourceVerbatim);
  }
  await processMarkdownIncludes(newCells, options, filename);
  return join5(newCells, "");
}
async function handleLanguageCells(options) {
  const mdCells = (await breakQuartoMd(options.markdown, false)).cells;
  if (mdCells.length === 0) {
    return {
      markdown: options.markdown
    };
  }
  const newCells = [];
  const languageCellsPerLanguage = {};
  for (let i6 = 0; i6 < mdCells.length; ++i6) {
    const cell = mdCells[i6];
    newCells.push(cell.sourceVerbatim);
    if (cell.cell_type === "raw" || cell.cell_type === "markdown") {
      continue;
    }
    const language = cell.cell_type.language;
    if (language !== "_directive" && handlers2[language] === void 0) {
      continue;
    }
    if (handlers2[language]?.stage && handlers2[language].stage !== "any" && options.stage !== handlers2[language].stage) {
      continue;
    }
    if (languageCellsPerLanguage[language] === void 0) {
      languageCellsPerLanguage[language] = [];
    }
    languageCellsPerLanguage[language].push({
      index: i6,
      source: cell
    });
  }
  let results = void 0;
  for (const [language, cells] of Object.entries(languageCellsPerLanguage)) {
    if (language === "_directive") {
      for (const cell of cells) {
        const directiveCellType = cell.source.cell_type;
        const innerLanguage = directiveCellType.name;
        const innerLanguageHandler = handlers2[innerLanguage];
        if (innerLanguageHandler && (innerLanguageHandler.stage !== "any" && innerLanguageHandler.stage !== options.stage)) {
          continue;
        }
        if (innerLanguageHandler === void 0 || innerLanguageHandler.type === "cell") {
          continue;
        }
        if (innerLanguageHandler.directive === void 0) {
          throw new Error(
            "Bad language handler: directive callback is undefined"
          );
        }
        const innerHandler = makeHandlerContext({
          ...options,
          name: innerLanguage
        });
        newCells[cell.index] = asMappedString(
          await innerLanguageHandler.directive(
            innerHandler.context,
            directiveCellType
          )
        );
        results = mergeConfigs(results, innerHandler.results);
      }
    } else {
      const handler = makeHandlerContext({
        ...options,
        name: language
      });
      const languageHandler = handlers2[language];
      if (languageHandler !== void 0 && languageHandler.type !== "directive") {
        const transformedCells = await languageHandler.document(
          handler.context,
          cells.map((x3) => x3.source)
        );
        for (let i6 = 0; i6 < transformedCells.length; ++i6) {
          newCells[cells[i6].index] = transformedCells[i6];
        }
        if (results === void 0) {
          results = handler.results;
        } else {
          results = mergeConfigs(results, handler.results);
        }
      }
    }
  }
  await processMarkdownIncludes(newCells, options);
  return {
    markdown: join5(newCells, ""),
    results
  };
}
function getDivAttributes(options, forceSkip) {
  const attrs = [];
  if (forceSkip) {
    options = { ...options };
    for (const skip of forceSkip) {
      delete options[skip];
    }
  }
  const keysToNotSerialize = /* @__PURE__ */ new Set([
    kEcho,
    kCellLabel,
    kCellFigCap,
    kCellFigSubCap,
    kCellFigScap,
    kCapLoc,
    kFigCapLoc,
    kTblCapLoc,
    kCellFigColumn,
    kCellTblColumn,
    kCellFigLink,
    kCellFigAlign,
    kCellFigEnv,
    kCellFigPos,
    kCellFigAlt,
    // FIXME see if it's possible to do this right wrt accessibility
    kOutput,
    kCellLstCap,
    kCellLstLabel,
    kCodeFold,
    kCodeLineNumbers,
    kCodeSummary,
    kCodeOverflow,
    kCellClasses,
    kCellPanel,
    kCellColumn,
    "include.hidden",
    "source.hidden",
    "plot.hidden",
    "output.hidden",
    "echo.hidden"
  ]);
  for (const [key, value] of Object.entries(options || {})) {
    if (!keysToNotSerialize.has(key)) {
      const t5 = typeof value;
      if (t5 === "undefined") {
        continue;
      }
      if (t5 === "object") {
        attrs.push(`${key}="${JSON.stringify(value)}"`);
      } else if (t5 === "string") {
        attrs.push(`${key}=${JSON.stringify(value)}`);
      } else if (t5 === "number") {
        attrs.push(`${key}="${value}"`);
      } else if (t5 === "boolean") {
        attrs.push(`${key}=${value}`);
      } else {
        throw new Error(
          `Can't serialize yaml metadata value of type ${t5}, key ${key}`
        );
      }
    }
  }
  if (options?.[kCellLstCap]) {
    attrs.push(`lst-cap="${options?.[kCellLstCap]}"`);
  }
  const classStr = options?.classes || "";
  const classes = classStr === "" ? [] : classStr.trim().split(" ");
  if (typeof options?.[kFigAlign] === "string") {
    attrs.push(`layout-align="${options?.[kFigAlign]}"`);
  }
  if (typeof options?.panel === "string") {
    classes.push(`panel-${options?.panel}`);
  }
  if (typeof options?.column === "string") {
    classes.push(`column-${options?.column}`);
  }
  if (typeof options?.[kCapLoc] === "string") {
    classes.push(`caption-${options?.[kCapLoc]}`);
  }
  if (typeof options?.[kFigCapLoc] === "string") {
    classes.push(`fig-cap-location-${options?.[kFigCapLoc]}`);
  }
  if (typeof options?.[kTblCapLoc] === "string") {
    classes.push(`tbl-cap-location-${options?.[kTblCapLoc]}`);
  }
  if (typeof options?.[kCellFigColumn] === "string") {
    classes.push(`fig-column-${options?.[kCellFigColumn]}`);
  }
  if (typeof options?.[kCellTblColumn] === "string") {
    classes.push(`tbl-column-${options?.[kCellTblColumn]}`);
  }
  return { attrs, classes };
}
var handlers2, globalFigureCounter, processMarkdownIncludes, baseHandler;
var init_base = __esm({
  async "core/handlers/base.ts"() {
    init_break_quarto_md();
    init_config2();
    init_types5();
    init_mapped_text();
    init_partition_cell_options();
    init_codegen();
    init_constants6();
    init_path();
    init_render();
    init_fs();
    init_mapped_text2();
    init_log();
    await init_cri();
    init_path2();
    init_parse_shortcode();
    init_include_standalone();
    init_located_error();
    handlers2 = {};
    globalFigureCounter = {};
    processMarkdownIncludes = async (newCells, options, filename) => {
      const includeHandler2 = makeHandlerContext(options);
      if (!includeHandler2.context.options.state) {
        includeHandler2.context.options.state = {};
      }
      if (!includeHandler2.context.options.state.include) {
        includeHandler2.context.options.state.include = {
          includes: []
        };
      }
      const includeState = includeHandler2.context.options.state.include;
      for (let i6 = 0; i6 < newCells.length; ++i6) {
        if (newCells[i6].value.search(/\s*```\s*{\s*shortcodes\s*=\s*false\s*}/) !== -1) {
          continue;
        }
        const lines2 = mappedLines(newCells[i6], true);
        let foundShortcodes = false;
        for (let j3 = 0; j3 < lines2.length; ++j3) {
          try {
            const shortcode = isBlockShortcode(lines2[j3].value);
            if (shortcode && shortcode.name === "include") {
              foundShortcodes = true;
              const param = shortcode.params[0];
              if (!param) {
                throw new Error("Include directive needs filename as a parameter");
              }
              if (filename) {
                includeState.includes.push({ source: filename, target: param });
              }
              lines2[j3] = await standaloneInclude(includeHandler2.context, param);
            }
          } catch (e5) {
            if (e5 instanceof InvalidShortcodeError) {
              const mapResult = newCells[i6].map(newCells[i6].value.indexOf("{"));
              throw new LocalizedError3(
                "Invalid Shortcode",
                e5.message,
                mapResult.originalString,
                mapResult.index
              );
            } else {
              throw e5;
            }
          }
        }
        if (foundShortcodes) {
          newCells[i6] = mappedConcat(lines2);
        }
      }
    };
    baseHandler = {
      type: "any",
      stage: "any",
      languageName: "<<<< baseHandler: languageName should have been overridden >>>>",
      defaultOptions: {
        echo: true
      },
      async document(handlerContext, cells) {
        this.documentStart(handlerContext);
        const mermaidExecute = handlerContext.options.format.mergeAdditionalFormats(
          {
            execute: this.defaultOptions
          }
        ).execute;
        const result2 = await Promise.all(cells.map((cell) => {
          return this.cell(
            handlerContext,
            cell,
            mergeConfigs(
              mermaidExecute,
              cell.options ?? {}
            )
          );
        }));
        this.documentEnd(handlerContext);
        return result2;
      },
      // called once per document at the start of processing
      documentStart(_handlerContext) {
      },
      // called once per document at the end of processing
      documentEnd(_handlerContext) {
      },
      cell(_handlerContext, cell, _options) {
        return Promise.resolve(cell.sourceVerbatim);
      },
      // FIXME attributes we're not handling yet:
      // - code-summary
      // - code-overflow
      // - code-line-numbers
      //
      // FIXME how do we set up support for:
      // - things that include subfigures, like tables?
      //
      // FIXME how should we interpret the difference between output and eval
      // here?
      build(handlerContext, cell, content, options, extraCellOptions, skipOptions) {
        const contentLines = mappedLines(cell.sourceWithYaml, true);
        const frontMatterLines = [];
        const commentPattern = optionCommentPatternFromLanguage(this.languageName);
        let inputIndex = 0;
        for (const contentLine of contentLines) {
          const commentMatch = contentLine.value.match(commentPattern);
          if (commentMatch) {
            if (contentLine.value.indexOf("echo: fenced") === -1) {
              frontMatterLines.push(contentLine);
            }
            ++inputIndex;
          } else {
            break;
          }
        }
        const inputLines = contentLines.slice(inputIndex);
        const { classes, attrs } = getDivAttributes({
          ...{
            [kFigAlign]: handlerContext.options.format.render[kFigAlign]
          },
          ...extraCellOptions || {},
          ...cell.options
        }, skipOptions);
        const hasAttribute = (attrKey) => attrs.some((attr) => attr === attrKey || attr.startsWith(`${attrKey}=`));
        const hasLayoutAttributes = hasAttribute(kLayoutNrow) || hasAttribute(kLayoutNcol) || hasAttribute(kLayout);
        const isPowerpointOutput = handlerContext.options.format.pandoc.to?.startsWith("pptx");
        const unrolledOutput = isPowerpointOutput && !hasLayoutAttributes;
        const cellBlock = unrolledOutput ? pandocList({ skipFirstLineBreak: true }) : pandocDiv({
          classes: ["cell", ...classes],
          attrs
        });
        const languageClass = this.languageClass === void 0 ? this.languageName : typeof this.languageClass === "string" ? this.languageClass : this.languageClass(handlerContext.options);
        const cellInputClasses = [
          languageClass,
          "cell-code",
          ...options["class-source"] ?? []
        ];
        const cellInputAttrs = [
          ...options["attr-source"] ?? []
        ];
        const cellOutputClasses = [
          "cell-output-display",
          ...options["class-output"] ?? []
        ];
        const cellOutputAttrs = [
          ...options["attr-output"] ?? []
        ];
        if (options[kCodeFold] !== void 0) {
          cellInputAttrs.push(`code-fold="${options[kCodeFold]}"`);
        }
        switch (options.echo) {
          case true: {
            const cellInput = pandocCode({
              classes: cellInputClasses,
              attrs: cellInputAttrs
            });
            cellInput.push(pandocRawStr(mappedTrim(mappedConcat(inputLines))));
            cellBlock.push(cellInput);
            break;
          }
          case "fenced": {
            const cellInput = pandocCode({
              classes: ["markdown", ...cellInputClasses.slice(1)],
              // replace the language class with markdown
              attrs: cellInputAttrs
            });
            const cellFence = pandocCode({
              language: this.languageName,
              skipFirstLineBreak: true
            });
            const fencedInput = mappedConcat([
              ...frontMatterLines,
              ...inputLines
            ]);
            cellFence.push(pandocRawStr(mappedTrim(fencedInput)));
            cellInput.push(cellFence);
            cellBlock.push(cellInput);
            break;
          }
        }
        const divBlock = pandocDiv;
        const cellOutputDiv = unrolledOutput ? cellBlock : divBlock({
          // id: cell.options?.label as (string | undefined),
          attrs: cellOutputAttrs,
          classes: cellOutputClasses
        });
        cellBlock.push(cellOutputDiv);
        const figureLikeOptions = {};
        if (typeof cell.options?.label === "string") {
          figureLikeOptions.id = cell.options?.label;
        }
        const figureLike = unrolledOutput ? cellBlock : divBlock(figureLikeOptions);
        const cellOutput = unrolledOutput ? cellBlock : divBlock();
        figureLike.push(cellOutput);
        cellOutputDiv.push(figureLike);
        if (options.eval === true) {
          cellOutput.push(pandocRawStr(content));
        }
        if (cell.options?.[kCellFigCap]) {
          let capOpen = "", capClose = "";
          if (cell.options?.label === void 0) {
            capOpen = "`<figcaption>`{=html} ";
            capClose = "`</figcaption>`{=html} ";
          }
          figureLike.push(
            pandocRawStr(
              `

${capOpen}${cell.options[kCellFigCap]}${capClose}`
            )
          );
        }
        if (cell.options?.label === void 0) {
          figureLike.unshift(pandocRawStr("`<figure class=''>`{=html}\n"));
          figureLike.push(pandocRawStr("`</figure>`{=html}\n"));
        }
        return cellBlock.mappedString();
      }
    };
  }
});

// core/pandoc/format-extension.ts
var kPandocExtensions;
var init_format_extension = __esm({
  "core/pandoc/format-extension.ts"() {
    kPandocExtensions = [
      "+abbreviations",
      "-abbreviations",
      "+alerts",
      "-alerts",
      "+all_symbols_escapable",
      "-all_symbols_escapable",
      "+amuse",
      "-amuse",
      "+angle_brackets_escapable",
      "-angle_brackets_escapable",
      "+ascii_identifiers",
      "-ascii_identifiers",
      "+attributes",
      "-attributes",
      "+auto_identifiers",
      "-auto_identifiers",
      "+autolink_bare_uris",
      "-autolink_bare_uris",
      "+backtick_code_blocks",
      "-backtick_code_blocks",
      "+blank_before_blockquote",
      "-blank_before_blockquote",
      "+blank_before_header",
      "-blank_before_header",
      "+bracketed_spans",
      "-bracketed_spans",
      "+citations",
      "-citations",
      "+definition_lists",
      "-definition_lists",
      "+east_asian_line_breaks",
      "-east_asian_line_breaks",
      "+element_citations",
      "-element_citations",
      "+emoji",
      "-emoji",
      "+empty_paragraphs",
      "-empty_paragraphs",
      "+epub_html_exts",
      "-epub_html_exts",
      "+escaped_line_breaks",
      "-escaped_line_breaks",
      "+example_lists",
      "-example_lists",
      "+fancy_lists",
      "-fancy_lists",
      "+fenced_code_attributes",
      "-fenced_code_attributes",
      "+fenced_code_blocks",
      "-fenced_code_blocks",
      "+fenced_divs",
      "-fenced_divs",
      "+footnotes",
      "-footnotes",
      "+four_space_rule",
      "-four_space_rule",
      "+gfm_auto_identifiers",
      "-gfm_auto_identifiers",
      "+grid_tables",
      "-grid_tables",
      "+gutenberg",
      "-gutenberg",
      "+hard_line_breaks",
      "-hard_line_breaks",
      "+header_attributes",
      "-header_attributes",
      "+ignore_line_breaks",
      "-ignore_line_breaks",
      "+implicit_figures",
      "-implicit_figures",
      "+implicit_header_references",
      "-implicit_header_references",
      "+inline_code_attributes",
      "-inline_code_attributes",
      "+inline_notes",
      "-inline_notes",
      "+intraword_underscores",
      "-intraword_underscores",
      "+latex_macros",
      "-latex_macros",
      "+line_blocks",
      "-line_blocks",
      "+link_attributes",
      "-link_attributes",
      "+lists_without_preceding_blankline",
      "-lists_without_preceding_blankline",
      "+literate_haskell",
      "-literate_haskell",
      "+mark",
      "-mark",
      "+markdown_attribute",
      "-markdown_attribute",
      "+markdown_in_html_blocks",
      "-markdown_in_html_blocks",
      "+mmd_header_identifiers",
      "-mmd_header_identifiers",
      "+mmd_link_attributes",
      "-mmd_link_attributes",
      "+mmd_title_block",
      "-mmd_title_block",
      "+multiline_tables",
      "-multiline_tables",
      "+native_divs",
      "-native_divs",
      "+native_numbering",
      "-native_numbering",
      "+native_spans",
      "-native_spans",
      "+ntb",
      "-ntb",
      "+old_dashes",
      "-old_dashes",
      "+pandoc_title_block",
      "-pandoc_title_block",
      "+pipe_tables",
      "-pipe_tables",
      "+raw_attribute",
      "-raw_attribute",
      "+raw_html",
      "-raw_html",
      "+raw_markdown",
      "-raw_markdown",
      "+raw_tex",
      "-raw_tex",
      "+rebase_relative_paths",
      "-rebase_relative_paths",
      "+short_subsuperscripts",
      "-short_subsuperscripts",
      "+shortcut_reference_links",
      "-shortcut_reference_links",
      "+simple_tables",
      "-simple_tables",
      "+smart",
      "-smart",
      "+smart_quotes",
      "-smart_quotes",
      "+sourcepos",
      "-sourcepos",
      "+space_in_atx_header",
      "-space_in_atx_header",
      "+spaced_reference_links",
      "-spaced_reference_links",
      "+special_strings",
      "-special_strings",
      "+startnum",
      "-startnum",
      "+strikeout",
      "-strikeout",
      "+styles",
      "-styles",
      "+subscript",
      "-subscript",
      "+superscript",
      "-superscript",
      "+table_attributes",
      "-table_attributes",
      "+table_captions",
      "-table_captions",
      "+tagging",
      "-tagging",
      "+task_lists",
      "-task_lists",
      "+tex_math_dollars",
      "-tex_math_dollars",
      "+tex_math_double_backslash",
      "-tex_math_double_backslash",
      "+tex_math_gfm",
      "-tex_math_gfm",
      "+tex_math_single_backslash",
      "-tex_math_single_backslash",
      "+wikilinks_title_after_pipe",
      "-wikilinks_title_after_pipe",
      "+wikilinks_title_before_pipe",
      "-wikilinks_title_before_pipe",
      "+xrefs_name",
      "-xrefs_name",
      "+xrefs_number",
      "-xrefs_number",
      "+yaml_metadata_block",
      "-yaml_metadata_block"
    ];
  }
});

// core/pandoc/pandoc-formats.ts
async function pandocListFormats() {
  const result2 = await execProcess({
    cmd: pandocBinaryPath(),
    args: ["--list-output-formats"],
    stdout: "piped"
  });
  if (result2.success) {
    return lines(result2.stdout).filter((line) => line.length > 0);
  } else {
    return Promise.reject();
  }
}
function pandocFormat(format14, extensions2, disabled) {
  let newFormat = pandocFormatWith(
    format14,
    "",
    extensions2.map((ext) => `+${ext}`).join("") + disabled.map((ext) => `-${ext}`).join("")
  );
  extensions2.forEach((ext) => {
    newFormat = newFormat.replace("-" + ext, "");
  });
  return newFormat;
}
function pandocFormatWith(format14, prepend, append) {
  const split2 = splitPandocFormatString(format14);
  return `${split2.format}${prepend}${split2.options}${append}`;
}
function splitPandocFormatString(format14) {
  let optionsPos = format14.indexOf("-");
  if (optionsPos === -1) {
    optionsPos = format14.indexOf("+");
  }
  const base3 = optionsPos === -1 ? format14 : format14.substr(0, optionsPos);
  const options = optionsPos === -1 ? "" : format14.substr(optionsPos);
  return {
    format: base3,
    options
  };
}
function ensureFormats() {
  if (!FormatAliases.pandoc) {
    const formatAliases2 = readYaml(
      resourcePath("schema/format-aliases.yml")
    );
    const pandocFormats = formatAliases2["aliases"]["pandoc-all"];
    FormatAliases.pandoc = pandocFormats;
  }
  if (!FormatAliases.custom) {
    FormatAliases.custom = ["dashboard", "email"];
  }
}
function pandocBuiltInFormats() {
  ensureFormats();
  return FormatAliases.pandoc;
}
function isBuiltInFormat(format14) {
  ensureFormats();
  return FormatAliases.pandoc.includes(format14) || FormatAliases.custom.includes(format14) || extname4(format14) === ".lua";
}
function breakFormatString(formatStr, strict = true) {
  const firstEl = formatStr.split(/[+-]/)[0];
  if (isBuiltInFormat(firstEl)) {
    const variantMatches = formatStr.matchAll(/[\+\-]\S*?(?=\-|\+|$)/g);
    const variantCommands = [];
    for (const match of variantMatches) {
      variantCommands.push(match[0]);
    }
    const variants = [];
    const modifiers = [];
    variantCommands.forEach((cmd) => {
      if (kPandocExtensions.includes(cmd)) {
        variants.push(cmd);
      } else {
        modifiers.push(cmd);
      }
    });
    return {
      baseFormat: firstEl,
      variants,
      modifiers,
      formatWithVariants: `${firstEl}${variants.join("")}`
    };
  } else {
    if (strict) {
      return void 0;
    } else {
      return {
        baseFormat: formatStr,
        variants: [],
        modifiers: [],
        formatWithVariants: formatStr
      };
    }
  }
}
var kYamlMetadataBlock, isValidFormat, parseFormatString, FormatAliases;
var init_pandoc_formats = __esm({
  "core/pandoc/pandoc-formats.ts"() {
    init_path();
    init_process();
    init_resources2();
    init_text2();
    init_yaml();
    init_format_extension();
    kYamlMetadataBlock = "yaml_metadata_block";
    isValidFormat = (formatDesc, pandoc2) => {
      if (isBuiltInFormat(formatDesc.baseFormat)) {
        return true;
      } else if (pandoc2.writer) {
        return true;
      } else {
        return false;
      }
    };
    parseFormatString = (formatStr) => {
      const formatDesc = breakFormatString(formatStr);
      if (formatDesc) {
        return formatDesc;
      } else {
        if (formatStr === "hugo") {
          formatStr = "hugo-md";
        }
        const splitFormat = formatStr.split(/-/);
        const lastEl = splitFormat.pop();
        if (lastEl) {
          const lastElFormatDesc = breakFormatString(lastEl, false);
          if (lastElFormatDesc) {
            lastElFormatDesc.extension = splitFormat.join("-");
            return lastElFormatDesc;
          } else {
            throw new Error("Invalid format string");
          }
        } else {
          throw new Error("Invalid format string");
        }
      }
    };
    FormatAliases = class {
      static pandoc;
      static custom;
    };
  }
});

// project/project-scratch.ts
function projectScratchPath(dir, path3 = "") {
  const scratchDir = join4(dir, kQuartoScratch);
  ensureDirSync(scratchDir);
  if (path3) {
    path3 = join4(scratchDir, path3);
    ensureDirSync(dirname4(path3));
    return path3;
  } else {
    return normalizePath(scratchDir);
  }
}
function migrateProjectScratchPath(dir, oldSubpath, newSubpath) {
  const scratchDir = join4(dir, kQuartoScratch);
  const oldPath = join4(scratchDir, oldSubpath);
  const newPath = join4(scratchDir, newSubpath);
  if (existsSync2(oldPath) && !existsSync2(newPath)) {
    ensureDirSync(dirname4(newPath));
    try {
      Deno.renameSync(oldPath, newPath);
    } catch (e5) {
      warn(`Failed to migrate ${oldSubpath} to ${newSubpath}: ${e5}`);
    }
  }
  return projectScratchPath(dir, newSubpath);
}
var kQuartoScratch;
var init_project_scratch = __esm({
  "project/project-scratch.ts"() {
    init_path();
    init_fs();
    init_path2();
    init_log();
    kQuartoScratch = ".quarto";
  }
});

// project/project-gitignore.ts
async function ensureGitignore(dir, forceEnv = false) {
  const gitignorePath = join4(dir, ".gitignore");
  if (existsSync2(gitignorePath)) {
    const gitignore = lines(Deno.readTextFileSync(gitignorePath)).map((line) => line.trim());
    const requiredEntries = [];
    for (const requiredEntry of gitignoreEntries(dir, forceEnv)) {
      if (!gitignore.includes(requiredEntry)) {
        requiredEntries.push(requiredEntry);
      }
    }
    const kLocalEntry = `/_*.local`;
    if (!gitignore.includes(kLocalEntry)) {
      for (const walk5 of walkSync(dir, { maxDepth: 1 })) {
        if (walk5.name.match(/^_.*?\.local$/)) {
          requiredEntries.push(kLocalEntry);
          break;
        }
      }
    }
    if (requiredEntries.length > 0) {
      writeGitignore(dir, gitignore.concat(requiredEntries));
      return true;
    } else {
      return false;
    }
  } else if (forceEnv) {
    await createGitignore(dir, forceEnv);
    return true;
  } else if (await which("git")) {
    const result2 = await execProcess({
      cmd: "git",
      args: ["rev-parse"],
      cwd: dir,
      stdout: "piped",
      stderr: "piped"
    });
    if (result2.success) {
      await createGitignore(dir, forceEnv);
      return true;
    } else {
      return false;
    }
  } else {
    return false;
  }
}
function createGitignore(dir, forceEnv = false) {
  writeGitignore(dir, gitignoreEntries(dir, forceEnv));
}
function gitignoreEntries(dir, forceEnv = false) {
  const kEnv = "env/";
  if (forceEnv || isEnvDir(join4(dir, kEnv))) {
    return ["/" + kEnv].concat(kQuartoIgnore);
  } else {
    return kQuartoIgnore;
  }
}
function writeGitignore(dir, lines2) {
  const lineEnding = isWindows4 ? "\r\n" : "\n";
  Deno.writeTextFileSync(
    join4(dir, ".gitignore"),
    lines2.join(lineEnding) + lineEnding
  );
}
var kQuartoIgnore;
var init_project_gitignore = __esm({
  "project/project-gitignore.ts"() {
    init_path();
    init_fs();
    init_path2();
    init_process();
    init_project_scratch();
    init_text2();
    init_capabilities();
    init_platform();
    kQuartoIgnore = [`/${kQuartoScratch}/`, `**/*.quarto_ipynb`];
  }
});

// project/types/project-types.ts
function registerProjectType(projectType2) {
  _types.push(projectType2);
}
function kTypes() {
  return _types.slice();
}
function parseProjectType(projType) {
  if (projType) {
    const parts = projType.split(":");
    return {
      type: parts[0],
      template: parts.length > 1 ? parts[1] : void 0
    };
  } else {
    return {
      type: "default"
    };
  }
}
function projectTypes() {
  return kTypes().map((type4) => type4.type);
}
function projectTypeAliases() {
  return kTypes().flatMap((type4) => type4.typeAliases || []);
}
function projectType(type4 = "default") {
  const projectType2 = kTypes().find((pt) => pt.type === type4);
  if (projectType2) {
    return projectType2;
  } else {
    throw new Error(`Unsupported project type ${type4}`);
  }
}
var _types;
var init_project_types = __esm({
  "project/types/project-types.ts"() {
    _types = [];
  }
});

// project/types/website/website-constants.ts
var kWebsite, kSiteUrl, kSitePath, kSiteTitle, kSiteFavicon, kSiteRepoUrl, kSiteRepoSubdir, kSiteRepoBranch, kSiteRepoLinkTarget, kSiteRepoLinkRel, kSiteIssueUrl, kSiteRepoActions, kSiteReaderMode, kLlmsTxt, kSiteNavbar, kSiteSidebar, kSiteSidebarStyle, kSiteSidebarHeader, kSiteSidebarFooter, kSitePageNavigation, kPageFooter, kBackToTopNavigation, kBreadCrumbNavigation, kMarginHeader, kMarginFooter, kBodyHeader, kBodyFooter, kDrafts, kDraftMode, kDraftModeVisible, kDraftModeGone, kAnnouncement, kContents, kTwitterCard, kOpenGraph, kCardStyle, kImage, kImageWidth, kImageHeight, kImageAlt, kCreator, kTwitterSite, kLocale, kSiteName;
var init_website_constants = __esm({
  "project/types/website/website-constants.ts"() {
    kWebsite = "website";
    kSiteUrl = "site-url";
    kSitePath = "site-path";
    kSiteTitle = "title";
    kSiteFavicon = "favicon";
    kSiteRepoUrl = "repo-url";
    kSiteRepoSubdir = "repo-subdir";
    kSiteRepoBranch = "repo-branch";
    kSiteRepoLinkTarget = "repo-link-target";
    kSiteRepoLinkRel = "repo-link-rel";
    kSiteIssueUrl = "issue-url";
    kSiteRepoActions = "repo-actions";
    kSiteReaderMode = "reader-mode";
    kLlmsTxt = "llms-txt";
    kSiteNavbar = "navbar";
    kSiteSidebar = "sidebar";
    kSiteSidebarStyle = "style";
    kSiteSidebarHeader = "header";
    kSiteSidebarFooter = "footer";
    kSitePageNavigation = "page-navigation";
    kPageFooter = "page-footer";
    kBackToTopNavigation = "back-to-top-navigation";
    kBreadCrumbNavigation = "bread-crumbs";
    kMarginHeader = "margin-header";
    kMarginFooter = "margin-footer";
    kBodyHeader = "body-header";
    kBodyFooter = "body-footer";
    kDrafts = "drafts";
    kDraftMode = "draft-mode";
    kDraftModeVisible = "visible";
    kDraftModeGone = "gone";
    kAnnouncement = "announcement";
    kContents = "contents";
    kTwitterCard = "twitter-card";
    kOpenGraph = "open-graph";
    kCardStyle = "card-style";
    kImage = "image";
    kImageWidth = "image-width";
    kImageHeight = "image-height";
    kImageAlt = "image-alt";
    kCreator = "creator";
    kTwitterSite = "site";
    kLocale = "locale";
    kSiteName = "site-name";
  }
});

// https://jsr.io/@std/streams/1.0.9/text_line_stream.ts
var TextLineStream;
var init_text_line_stream = __esm({
  "https://jsr.io/@std/streams/1.0.9/text_line_stream.ts"() {
    TextLineStream = class extends TransformStream {
      #currentLine = "";
      /**
       * Constructs a new instance.
       *
       * @param options Options for the stream.
       */
      constructor(options = { allowCR: false }) {
        super({
          transform: (chars, controller) => {
            chars = this.#currentLine + chars;
            while (true) {
              const lfIndex = chars.indexOf("\n");
              const crIndex = options.allowCR ? chars.indexOf("\r") : -1;
              if (crIndex !== -1 && crIndex !== chars.length - 1 && (lfIndex === -1 || lfIndex - 1 > crIndex)) {
                controller.enqueue(chars.slice(0, crIndex));
                chars = chars.slice(crIndex + 1);
                continue;
              }
              if (lfIndex === -1) break;
              const endIndex = chars[lfIndex - 1] === "\r" ? lfIndex - 1 : lfIndex;
              controller.enqueue(chars.slice(0, endIndex));
              chars = chars.slice(lfIndex + 1);
            }
            this.#currentLine = chars;
          },
          flush: (controller) => {
            if (this.#currentLine === "") return;
            const currentLine = options.allowCR && this.#currentLine.endsWith("\r") ? this.#currentLine.slice(0, -1) : this.#currentLine;
            controller.enqueue(currentLine);
          }
        });
      }
    };
  }
});

// core/file.ts
function existsSync1(s5) {
  return existsSync2(s5);
}
async function appendTextFile(path3, text) {
  const file = await Deno.open(path3, { append: true });
  try {
    const encoder4 = new TextEncoder();
    file.writeSync(encoder4.encode(text));
  } finally {
    file.close();
  }
}
async function touch(path3) {
  if (isWindows4) {
    const contents = await Deno.readFileSync(path3);
    await Deno.writeFileSync(path3, contents);
  } else {
    await execProcess({
      cmd: "touch",
      args: [path3]
    });
  }
}
var init_file = __esm({
  "core/file.ts"() {
    init_fs();
    init_platform();
    init_process();
    init_text_line_stream();
  }
});

// project/types/manuscript/manuscript-types.ts
var kManuscriptType, kManuscriptUrl, kMecaBundle, kEnvironmentFiles;
var init_manuscript_types = __esm({
  "project/types/manuscript/manuscript-types.ts"() {
    kManuscriptType = "manuscript";
    kManuscriptUrl = "manuscript-url";
    kMecaBundle = "meca-bundle";
    kEnvironmentFiles = "environment";
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/zod@3.24.4/node_modules/zod/lib/index.mjs
function setErrorMap(map3) {
  overrideErrorMap = map3;
}
function getErrorMap() {
  return overrideErrorMap;
}
function addIssueToContext(ctx, issueData) {
  const overrideMap = getErrorMap();
  const issue = makeIssue({
    issueData,
    data: ctx.data,
    path: ctx.path,
    errorMaps: [
      ctx.common.contextualErrorMap,
      // contextual error map is first priority
      ctx.schemaErrorMap,
      // then schema-bound map if available
      overrideMap,
      // then global override map
      overrideMap === errorMap ? void 0 : errorMap
      // then global default map
    ].filter((x3) => !!x3)
  });
  ctx.common.issues.push(issue);
}
function __classPrivateFieldGet(receiver, state2, kind, f5) {
  if (kind === "a" && !f5) throw new TypeError("Private accessor was defined without a getter");
  if (typeof state2 === "function" ? receiver !== state2 || !f5 : !state2.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind === "m" ? f5 : kind === "a" ? f5.call(receiver) : f5 ? f5.value : state2.get(receiver);
}
function __classPrivateFieldSet(receiver, state2, value, kind, f5) {
  if (kind === "m") throw new TypeError("Private method is not writable");
  if (kind === "a" && !f5) throw new TypeError("Private accessor was defined without a setter");
  if (typeof state2 === "function" ? receiver !== state2 || !f5 : !state2.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return kind === "a" ? f5.call(receiver, value) : f5 ? f5.value = value : state2.set(receiver, value), value;
}
function processCreateParams(params) {
  if (!params)
    return {};
  const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
  if (errorMap2 && (invalid_type_error || required_error)) {
    throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
  }
  if (errorMap2)
    return { errorMap: errorMap2, description };
  const customMap = (iss, ctx) => {
    var _a, _b;
    const { message } = params;
    if (iss.code === "invalid_enum_value") {
      return { message: message !== null && message !== void 0 ? message : ctx.defaultError };
    }
    if (typeof ctx.data === "undefined") {
      return { message: (_a = message !== null && message !== void 0 ? message : required_error) !== null && _a !== void 0 ? _a : ctx.defaultError };
    }
    if (iss.code !== "invalid_type")
      return { message: ctx.defaultError };
    return { message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError };
  };
  return { errorMap: customMap, description };
}
function timeRegexSource(args) {
  let secondsRegexSource = `[0-5]\\d`;
  if (args.precision) {
    secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
  } else if (args.precision == null) {
    secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
  }
  const secondsQuantifier = args.precision ? "+" : "?";
  return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
}
function timeRegex(args) {
  return new RegExp(`^${timeRegexSource(args)}$`);
}
function datetimeRegex(args) {
  let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
  const opts = [];
  opts.push(args.local ? `Z?` : `Z`);
  if (args.offset)
    opts.push(`([+-]\\d{2}:?\\d{2})`);
  regex = `${regex}(${opts.join("|")})`;
  return new RegExp(`^${regex}$`);
}
function isValidIP(ip, version4) {
  if ((version4 === "v4" || !version4) && ipv4Regex.test(ip)) {
    return true;
  }
  if ((version4 === "v6" || !version4) && ipv6Regex.test(ip)) {
    return true;
  }
  return false;
}
function isValidJWT(jwt, alg) {
  if (!jwtRegex.test(jwt))
    return false;
  try {
    const [header] = jwt.split(".");
    const base642 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
    const decoded = JSON.parse(atob(base642));
    if (typeof decoded !== "object" || decoded === null)
      return false;
    if (!decoded.typ || !decoded.alg)
      return false;
    if (alg && decoded.alg !== alg)
      return false;
    return true;
  } catch (_a) {
    return false;
  }
}
function isValidCidr(ip, version4) {
  if ((version4 === "v4" || !version4) && ipv4CidrRegex.test(ip)) {
    return true;
  }
  if ((version4 === "v6" || !version4) && ipv6CidrRegex.test(ip)) {
    return true;
  }
  return false;
}
function floatSafeRemainder(val, step) {
  const valDecCount = (val.toString().split(".")[1] || "").length;
  const stepDecCount = (step.toString().split(".")[1] || "").length;
  const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
  const valInt = parseInt(val.toFixed(decCount).replace(".", ""));
  const stepInt = parseInt(step.toFixed(decCount).replace(".", ""));
  return valInt % stepInt / Math.pow(10, decCount);
}
function deepPartialify(schema4) {
  if (schema4 instanceof ZodObject) {
    const newShape = {};
    for (const key in schema4.shape) {
      const fieldSchema = schema4.shape[key];
      newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
    }
    return new ZodObject({
      ...schema4._def,
      shape: () => newShape
    });
  } else if (schema4 instanceof ZodArray) {
    return new ZodArray({
      ...schema4._def,
      type: deepPartialify(schema4.element)
    });
  } else if (schema4 instanceof ZodOptional) {
    return ZodOptional.create(deepPartialify(schema4.unwrap()));
  } else if (schema4 instanceof ZodNullable) {
    return ZodNullable.create(deepPartialify(schema4.unwrap()));
  } else if (schema4 instanceof ZodTuple) {
    return ZodTuple.create(schema4.items.map((item) => deepPartialify(item)));
  } else {
    return schema4;
  }
}
function mergeValues(a5, b3) {
  const aType = getParsedType(a5);
  const bType = getParsedType(b3);
  if (a5 === b3) {
    return { valid: true, data: a5 };
  } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
    const bKeys = util.objectKeys(b3);
    const sharedKeys = util.objectKeys(a5).filter((key) => bKeys.indexOf(key) !== -1);
    const newObj = { ...a5, ...b3 };
    for (const key of sharedKeys) {
      const sharedValue = mergeValues(a5[key], b3[key]);
      if (!sharedValue.valid) {
        return { valid: false };
      }
      newObj[key] = sharedValue.data;
    }
    return { valid: true, data: newObj };
  } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
    if (a5.length !== b3.length) {
      return { valid: false };
    }
    const newArray = [];
    for (let index2 = 0; index2 < a5.length; index2++) {
      const itemA = a5[index2];
      const itemB = b3[index2];
      const sharedValue = mergeValues(itemA, itemB);
      if (!sharedValue.valid) {
        return { valid: false };
      }
      newArray.push(sharedValue.data);
    }
    return { valid: true, data: newArray };
  } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a5 === +b3) {
    return { valid: true, data: a5 };
  } else {
    return { valid: false };
  }
}
function createZodEnum(values, params) {
  return new ZodEnum({
    values,
    typeName: ZodFirstPartyTypeKind.ZodEnum,
    ...processCreateParams(params)
  });
}
function cleanParams(params, data3) {
  const p5 = typeof params === "function" ? params(data3) : typeof params === "string" ? { message: params } : params;
  const p22 = typeof p5 === "string" ? { message: p5 } : p5;
  return p22;
}
function custom(check2, _params = {}, fatal) {
  if (check2)
    return ZodAny.create().superRefine((data3, ctx) => {
      var _a, _b;
      const r5 = check2(data3);
      if (r5 instanceof Promise) {
        return r5.then((r6) => {
          var _a2, _b2;
          if (!r6) {
            const params = cleanParams(_params, data3);
            const _fatal = (_b2 = (_a2 = params.fatal) !== null && _a2 !== void 0 ? _a2 : fatal) !== null && _b2 !== void 0 ? _b2 : true;
            ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
          }
        });
      }
      if (!r5) {
        const params = cleanParams(_params, data3);
        const _fatal = (_b = (_a = params.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true;
        ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
      }
      return;
    });
  return ZodAny.create();
}
var util, objectUtil, ZodParsedType, getParsedType, ZodIssueCode, quotelessJson, ZodError, errorMap, overrideErrorMap, makeIssue, EMPTY_PATH, ParseStatus, INVALID, DIRTY, OK, isAborted, isDirty, isValid, isAsync, errorUtil, _ZodEnum_cache, _ZodNativeEnum_cache, ParseInputLazyPath, handleResult, ZodType, cuidRegex, cuid2Regex, ulidRegex, uuidRegex, nanoidRegex, jwtRegex, durationRegex, emailRegex, _emojiRegex, emojiRegex, ipv4Regex, ipv4CidrRegex, ipv6Regex, ipv6CidrRegex, base64Regex, base64urlRegex, dateRegexSource, dateRegex, ZodString, ZodNumber, ZodBigInt, ZodBoolean, ZodDate, ZodSymbol, ZodUndefined, ZodNull, ZodAny, ZodUnknown, ZodNever, ZodVoid, ZodArray, ZodObject, ZodUnion, getDiscriminator, ZodDiscriminatedUnion, ZodIntersection, ZodTuple, ZodRecord, ZodMap, ZodSet, ZodFunction, ZodLazy, ZodLiteral, ZodEnum, ZodNativeEnum, ZodPromise, ZodEffects, ZodOptional, ZodNullable, ZodDefault, ZodCatch, ZodNaN, BRAND, ZodBranded, ZodPipeline, ZodReadonly, late, ZodFirstPartyTypeKind, instanceOfType, stringType, numberType, nanType, bigIntType, booleanType, dateType, symbolType, undefinedType, nullType, anyType, unknownType, neverType, voidType, arrayType, objectType, strictObjectType, unionType, discriminatedUnionType, intersectionType, tupleType, recordType, mapType, setType, functionType, lazyType, literalType, enumType, nativeEnumType, promiseType, effectsType, optionalType, nullableType, preprocessType, pipelineType, ostring, onumber, oboolean, coerce2, NEVER, z3;
var init_lib = __esm({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/zod@3.24.4/node_modules/zod/lib/index.mjs"() {
    (function(util2) {
      util2.assertEqual = (val) => val;
      function assertIs(_arg) {
      }
      util2.assertIs = assertIs;
      function assertNever(_x) {
        throw new Error();
      }
      util2.assertNever = assertNever;
      util2.arrayToEnum = (items) => {
        const obj = {};
        for (const item of items) {
          obj[item] = item;
        }
        return obj;
      };
      util2.getValidEnumValues = (obj) => {
        const validKeys = util2.objectKeys(obj).filter((k3) => typeof obj[obj[k3]] !== "number");
        const filtered = {};
        for (const k3 of validKeys) {
          filtered[k3] = obj[k3];
        }
        return util2.objectValues(filtered);
      };
      util2.objectValues = (obj) => {
        return util2.objectKeys(obj).map(function(e5) {
          return obj[e5];
        });
      };
      util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
        const keys = [];
        for (const key in object) {
          if (Object.prototype.hasOwnProperty.call(object, key)) {
            keys.push(key);
          }
        }
        return keys;
      };
      util2.find = (arr, checker) => {
        for (const item of arr) {
          if (checker(item))
            return item;
        }
        return void 0;
      };
      util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val;
      function joinValues(array, separator = " | ") {
        return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
      }
      util2.joinValues = joinValues;
      util2.jsonStringifyReplacer = (_3, value) => {
        if (typeof value === "bigint") {
          return value.toString();
        }
        return value;
      };
    })(util || (util = {}));
    (function(objectUtil2) {
      objectUtil2.mergeShapes = (first, second) => {
        return {
          ...first,
          ...second
          // second overwrites first
        };
      };
    })(objectUtil || (objectUtil = {}));
    ZodParsedType = util.arrayToEnum([
      "string",
      "nan",
      "number",
      "integer",
      "float",
      "boolean",
      "date",
      "bigint",
      "symbol",
      "function",
      "undefined",
      "null",
      "array",
      "object",
      "unknown",
      "promise",
      "void",
      "never",
      "map",
      "set"
    ]);
    getParsedType = (data3) => {
      const t5 = typeof data3;
      switch (t5) {
        case "undefined":
          return ZodParsedType.undefined;
        case "string":
          return ZodParsedType.string;
        case "number":
          return isNaN(data3) ? ZodParsedType.nan : ZodParsedType.number;
        case "boolean":
          return ZodParsedType.boolean;
        case "function":
          return ZodParsedType.function;
        case "bigint":
          return ZodParsedType.bigint;
        case "symbol":
          return ZodParsedType.symbol;
        case "object":
          if (Array.isArray(data3)) {
            return ZodParsedType.array;
          }
          if (data3 === null) {
            return ZodParsedType.null;
          }
          if (data3.then && typeof data3.then === "function" && data3.catch && typeof data3.catch === "function") {
            return ZodParsedType.promise;
          }
          if (typeof Map !== "undefined" && data3 instanceof Map) {
            return ZodParsedType.map;
          }
          if (typeof Set !== "undefined" && data3 instanceof Set) {
            return ZodParsedType.set;
          }
          if (typeof Date !== "undefined" && data3 instanceof Date) {
            return ZodParsedType.date;
          }
          return ZodParsedType.object;
        default:
          return ZodParsedType.unknown;
      }
    };
    ZodIssueCode = util.arrayToEnum([
      "invalid_type",
      "invalid_literal",
      "custom",
      "invalid_union",
      "invalid_union_discriminator",
      "invalid_enum_value",
      "unrecognized_keys",
      "invalid_arguments",
      "invalid_return_type",
      "invalid_date",
      "invalid_string",
      "too_small",
      "too_big",
      "invalid_intersection_types",
      "not_multiple_of",
      "not_finite"
    ]);
    quotelessJson = (obj) => {
      const json3 = JSON.stringify(obj, null, 2);
      return json3.replace(/"([^"]+)":/g, "$1:");
    };
    ZodError = class _ZodError extends Error {
      get errors() {
        return this.issues;
      }
      constructor(issues) {
        super();
        this.issues = [];
        this.addIssue = (sub) => {
          this.issues = [...this.issues, sub];
        };
        this.addIssues = (subs = []) => {
          this.issues = [...this.issues, ...subs];
        };
        const actualProto = new.target.prototype;
        if (Object.setPrototypeOf) {
          Object.setPrototypeOf(this, actualProto);
        } else {
          this.__proto__ = actualProto;
        }
        this.name = "ZodError";
        this.issues = issues;
      }
      format(_mapper) {
        const mapper = _mapper || function(issue) {
          return issue.message;
        };
        const fieldErrors = { _errors: [] };
        const processError = (error2) => {
          for (const issue of error2.issues) {
            if (issue.code === "invalid_union") {
              issue.unionErrors.map(processError);
            } else if (issue.code === "invalid_return_type") {
              processError(issue.returnTypeError);
            } else if (issue.code === "invalid_arguments") {
              processError(issue.argumentsError);
            } else if (issue.path.length === 0) {
              fieldErrors._errors.push(mapper(issue));
            } else {
              let curr = fieldErrors;
              let i6 = 0;
              while (i6 < issue.path.length) {
                const el = issue.path[i6];
                const terminal = i6 === issue.path.length - 1;
                if (!terminal) {
                  curr[el] = curr[el] || { _errors: [] };
                } else {
                  curr[el] = curr[el] || { _errors: [] };
                  curr[el]._errors.push(mapper(issue));
                }
                curr = curr[el];
                i6++;
              }
            }
          }
        };
        processError(this);
        return fieldErrors;
      }
      static assert(value) {
        if (!(value instanceof _ZodError)) {
          throw new Error(`Not a ZodError: ${value}`);
        }
      }
      toString() {
        return this.message;
      }
      get message() {
        return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
      }
      get isEmpty() {
        return this.issues.length === 0;
      }
      flatten(mapper = (issue) => issue.message) {
        const fieldErrors = {};
        const formErrors = [];
        for (const sub of this.issues) {
          if (sub.path.length > 0) {
            fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
            fieldErrors[sub.path[0]].push(mapper(sub));
          } else {
            formErrors.push(mapper(sub));
          }
        }
        return { formErrors, fieldErrors };
      }
      get formErrors() {
        return this.flatten();
      }
    };
    ZodError.create = (issues) => {
      const error2 = new ZodError(issues);
      return error2;
    };
    errorMap = (issue, _ctx) => {
      let message;
      switch (issue.code) {
        case ZodIssueCode.invalid_type:
          if (issue.received === ZodParsedType.undefined) {
            message = "Required";
          } else {
            message = `Expected ${issue.expected}, received ${issue.received}`;
          }
          break;
        case ZodIssueCode.invalid_literal:
          message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
          break;
        case ZodIssueCode.unrecognized_keys:
          message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
          break;
        case ZodIssueCode.invalid_union:
          message = `Invalid input`;
          break;
        case ZodIssueCode.invalid_union_discriminator:
          message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
          break;
        case ZodIssueCode.invalid_enum_value:
          message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
          break;
        case ZodIssueCode.invalid_arguments:
          message = `Invalid function arguments`;
          break;
        case ZodIssueCode.invalid_return_type:
          message = `Invalid function return type`;
          break;
        case ZodIssueCode.invalid_date:
          message = `Invalid date`;
          break;
        case ZodIssueCode.invalid_string:
          if (typeof issue.validation === "object") {
            if ("includes" in issue.validation) {
              message = `Invalid input: must include "${issue.validation.includes}"`;
              if (typeof issue.validation.position === "number") {
                message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
              }
            } else if ("startsWith" in issue.validation) {
              message = `Invalid input: must start with "${issue.validation.startsWith}"`;
            } else if ("endsWith" in issue.validation) {
              message = `Invalid input: must end with "${issue.validation.endsWith}"`;
            } else {
              util.assertNever(issue.validation);
            }
          } else if (issue.validation !== "regex") {
            message = `Invalid ${issue.validation}`;
          } else {
            message = "Invalid";
          }
          break;
        case ZodIssueCode.too_small:
          if (issue.type === "array")
            message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
          else if (issue.type === "string")
            message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
          else if (issue.type === "number")
            message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
          else if (issue.type === "date")
            message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
          else
            message = "Invalid input";
          break;
        case ZodIssueCode.too_big:
          if (issue.type === "array")
            message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
          else if (issue.type === "string")
            message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
          else if (issue.type === "number")
            message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
          else if (issue.type === "bigint")
            message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
          else if (issue.type === "date")
            message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
          else
            message = "Invalid input";
          break;
        case ZodIssueCode.custom:
          message = `Invalid input`;
          break;
        case ZodIssueCode.invalid_intersection_types:
          message = `Intersection results could not be merged`;
          break;
        case ZodIssueCode.not_multiple_of:
          message = `Number must be a multiple of ${issue.multipleOf}`;
          break;
        case ZodIssueCode.not_finite:
          message = "Number must be finite";
          break;
        default:
          message = _ctx.defaultError;
          util.assertNever(issue);
      }
      return { message };
    };
    overrideErrorMap = errorMap;
    makeIssue = (params) => {
      const { data: data3, path: path3, errorMaps, issueData } = params;
      const fullPath = [...path3, ...issueData.path || []];
      const fullIssue = {
        ...issueData,
        path: fullPath
      };
      if (issueData.message !== void 0) {
        return {
          ...issueData,
          path: fullPath,
          message: issueData.message
        };
      }
      let errorMessage = "";
      const maps = errorMaps.filter((m4) => !!m4).slice().reverse();
      for (const map3 of maps) {
        errorMessage = map3(fullIssue, { data: data3, defaultError: errorMessage }).message;
      }
      return {
        ...issueData,
        path: fullPath,
        message: errorMessage
      };
    };
    EMPTY_PATH = [];
    ParseStatus = class _ParseStatus {
      constructor() {
        this.value = "valid";
      }
      dirty() {
        if (this.value === "valid")
          this.value = "dirty";
      }
      abort() {
        if (this.value !== "aborted")
          this.value = "aborted";
      }
      static mergeArray(status, results) {
        const arrayValue = [];
        for (const s5 of results) {
          if (s5.status === "aborted")
            return INVALID;
          if (s5.status === "dirty")
            status.dirty();
          arrayValue.push(s5.value);
        }
        return { status: status.value, value: arrayValue };
      }
      static async mergeObjectAsync(status, pairs3) {
        const syncPairs = [];
        for (const pair of pairs3) {
          const key = await pair.key;
          const value = await pair.value;
          syncPairs.push({
            key,
            value
          });
        }
        return _ParseStatus.mergeObjectSync(status, syncPairs);
      }
      static mergeObjectSync(status, pairs3) {
        const finalObject = {};
        for (const pair of pairs3) {
          const { key, value } = pair;
          if (key.status === "aborted")
            return INVALID;
          if (value.status === "aborted")
            return INVALID;
          if (key.status === "dirty")
            status.dirty();
          if (value.status === "dirty")
            status.dirty();
          if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
            finalObject[key.value] = value.value;
          }
        }
        return { status: status.value, value: finalObject };
      }
    };
    INVALID = Object.freeze({
      status: "aborted"
    });
    DIRTY = (value) => ({ status: "dirty", value });
    OK = (value) => ({ status: "valid", value });
    isAborted = (x3) => x3.status === "aborted";
    isDirty = (x3) => x3.status === "dirty";
    isValid = (x3) => x3.status === "valid";
    isAsync = (x3) => typeof Promise !== "undefined" && x3 instanceof Promise;
    (function(errorUtil2) {
      errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
      errorUtil2.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message;
    })(errorUtil || (errorUtil = {}));
    ParseInputLazyPath = class {
      constructor(parent, value, path3, key) {
        this._cachedPath = [];
        this.parent = parent;
        this.data = value;
        this._path = path3;
        this._key = key;
      }
      get path() {
        if (!this._cachedPath.length) {
          if (this._key instanceof Array) {
            this._cachedPath.push(...this._path, ...this._key);
          } else {
            this._cachedPath.push(...this._path, this._key);
          }
        }
        return this._cachedPath;
      }
    };
    handleResult = (ctx, result2) => {
      if (isValid(result2)) {
        return { success: true, data: result2.value };
      } else {
        if (!ctx.common.issues.length) {
          throw new Error("Validation failed but no issues detected.");
        }
        return {
          success: false,
          get error() {
            if (this._error)
              return this._error;
            const error2 = new ZodError(ctx.common.issues);
            this._error = error2;
            return this._error;
          }
        };
      }
    };
    ZodType = class {
      get description() {
        return this._def.description;
      }
      _getType(input) {
        return getParsedType(input.data);
      }
      _getOrReturnCtx(input, ctx) {
        return ctx || {
          common: input.parent.common,
          data: input.data,
          parsedType: getParsedType(input.data),
          schemaErrorMap: this._def.errorMap,
          path: input.path,
          parent: input.parent
        };
      }
      _processInputParams(input) {
        return {
          status: new ParseStatus(),
          ctx: {
            common: input.parent.common,
            data: input.data,
            parsedType: getParsedType(input.data),
            schemaErrorMap: this._def.errorMap,
            path: input.path,
            parent: input.parent
          }
        };
      }
      _parseSync(input) {
        const result2 = this._parse(input);
        if (isAsync(result2)) {
          throw new Error("Synchronous parse encountered promise.");
        }
        return result2;
      }
      _parseAsync(input) {
        const result2 = this._parse(input);
        return Promise.resolve(result2);
      }
      parse(data3, params) {
        const result2 = this.safeParse(data3, params);
        if (result2.success)
          return result2.data;
        throw result2.error;
      }
      safeParse(data3, params) {
        var _a;
        const ctx = {
          common: {
            issues: [],
            async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false,
            contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap
          },
          path: (params === null || params === void 0 ? void 0 : params.path) || [],
          schemaErrorMap: this._def.errorMap,
          parent: null,
          data: data3,
          parsedType: getParsedType(data3)
        };
        const result2 = this._parseSync({ data: data3, path: ctx.path, parent: ctx });
        return handleResult(ctx, result2);
      }
      "~validate"(data3) {
        var _a, _b;
        const ctx = {
          common: {
            issues: [],
            async: !!this["~standard"].async
          },
          path: [],
          schemaErrorMap: this._def.errorMap,
          parent: null,
          data: data3,
          parsedType: getParsedType(data3)
        };
        if (!this["~standard"].async) {
          try {
            const result2 = this._parseSync({ data: data3, path: [], parent: ctx });
            return isValid(result2) ? {
              value: result2.value
            } : {
              issues: ctx.common.issues
            };
          } catch (err2) {
            if ((_b = (_a = err2 === null || err2 === void 0 ? void 0 : err2.message) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === null || _b === void 0 ? void 0 : _b.includes("encountered")) {
              this["~standard"].async = true;
            }
            ctx.common = {
              issues: [],
              async: true
            };
          }
        }
        return this._parseAsync({ data: data3, path: [], parent: ctx }).then((result2) => isValid(result2) ? {
          value: result2.value
        } : {
          issues: ctx.common.issues
        });
      }
      async parseAsync(data3, params) {
        const result2 = await this.safeParseAsync(data3, params);
        if (result2.success)
          return result2.data;
        throw result2.error;
      }
      async safeParseAsync(data3, params) {
        const ctx = {
          common: {
            issues: [],
            contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,
            async: true
          },
          path: (params === null || params === void 0 ? void 0 : params.path) || [],
          schemaErrorMap: this._def.errorMap,
          parent: null,
          data: data3,
          parsedType: getParsedType(data3)
        };
        const maybeAsyncResult = this._parse({ data: data3, path: ctx.path, parent: ctx });
        const result2 = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
        return handleResult(ctx, result2);
      }
      refine(check2, message) {
        const getIssueProperties = (val) => {
          if (typeof message === "string" || typeof message === "undefined") {
            return { message };
          } else if (typeof message === "function") {
            return message(val);
          } else {
            return message;
          }
        };
        return this._refinement((val, ctx) => {
          const result2 = check2(val);
          const setError = () => ctx.addIssue({
            code: ZodIssueCode.custom,
            ...getIssueProperties(val)
          });
          if (typeof Promise !== "undefined" && result2 instanceof Promise) {
            return result2.then((data3) => {
              if (!data3) {
                setError();
                return false;
              } else {
                return true;
              }
            });
          }
          if (!result2) {
            setError();
            return false;
          } else {
            return true;
          }
        });
      }
      refinement(check2, refinementData) {
        return this._refinement((val, ctx) => {
          if (!check2(val)) {
            ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
            return false;
          } else {
            return true;
          }
        });
      }
      _refinement(refinement) {
        return new ZodEffects({
          schema: this,
          typeName: ZodFirstPartyTypeKind.ZodEffects,
          effect: { type: "refinement", refinement }
        });
      }
      superRefine(refinement) {
        return this._refinement(refinement);
      }
      constructor(def) {
        this.spa = this.safeParseAsync;
        this._def = def;
        this.parse = this.parse.bind(this);
        this.safeParse = this.safeParse.bind(this);
        this.parseAsync = this.parseAsync.bind(this);
        this.safeParseAsync = this.safeParseAsync.bind(this);
        this.spa = this.spa.bind(this);
        this.refine = this.refine.bind(this);
        this.refinement = this.refinement.bind(this);
        this.superRefine = this.superRefine.bind(this);
        this.optional = this.optional.bind(this);
        this.nullable = this.nullable.bind(this);
        this.nullish = this.nullish.bind(this);
        this.array = this.array.bind(this);
        this.promise = this.promise.bind(this);
        this.or = this.or.bind(this);
        this.and = this.and.bind(this);
        this.transform = this.transform.bind(this);
        this.brand = this.brand.bind(this);
        this.default = this.default.bind(this);
        this.catch = this.catch.bind(this);
        this.describe = this.describe.bind(this);
        this.pipe = this.pipe.bind(this);
        this.readonly = this.readonly.bind(this);
        this.isNullable = this.isNullable.bind(this);
        this.isOptional = this.isOptional.bind(this);
        this["~standard"] = {
          version: 1,
          vendor: "zod",
          validate: (data3) => this["~validate"](data3)
        };
      }
      optional() {
        return ZodOptional.create(this, this._def);
      }
      nullable() {
        return ZodNullable.create(this, this._def);
      }
      nullish() {
        return this.nullable().optional();
      }
      array() {
        return ZodArray.create(this);
      }
      promise() {
        return ZodPromise.create(this, this._def);
      }
      or(option) {
        return ZodUnion.create([this, option], this._def);
      }
      and(incoming) {
        return ZodIntersection.create(this, incoming, this._def);
      }
      transform(transform) {
        return new ZodEffects({
          ...processCreateParams(this._def),
          schema: this,
          typeName: ZodFirstPartyTypeKind.ZodEffects,
          effect: { type: "transform", transform }
        });
      }
      default(def) {
        const defaultValueFunc = typeof def === "function" ? def : () => def;
        return new ZodDefault({
          ...processCreateParams(this._def),
          innerType: this,
          defaultValue: defaultValueFunc,
          typeName: ZodFirstPartyTypeKind.ZodDefault
        });
      }
      brand() {
        return new ZodBranded({
          typeName: ZodFirstPartyTypeKind.ZodBranded,
          type: this,
          ...processCreateParams(this._def)
        });
      }
      catch(def) {
        const catchValueFunc = typeof def === "function" ? def : () => def;
        return new ZodCatch({
          ...processCreateParams(this._def),
          innerType: this,
          catchValue: catchValueFunc,
          typeName: ZodFirstPartyTypeKind.ZodCatch
        });
      }
      describe(description) {
        const This = this.constructor;
        return new This({
          ...this._def,
          description
        });
      }
      pipe(target) {
        return ZodPipeline.create(this, target);
      }
      readonly() {
        return ZodReadonly.create(this);
      }
      isOptional() {
        return this.safeParse(void 0).success;
      }
      isNullable() {
        return this.safeParse(null).success;
      }
    };
    cuidRegex = /^c[^\s-]{8,}$/i;
    cuid2Regex = /^[0-9a-z]+$/;
    ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
    uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
    nanoidRegex = /^[a-z0-9_-]{21}$/i;
    jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
    durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
    emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
    _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
    ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
    ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
    ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
    ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
    base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
    base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
    dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
    dateRegex = new RegExp(`^${dateRegexSource}$`);
    ZodString = class _ZodString extends ZodType {
      _parse(input) {
        if (this._def.coerce) {
          input.data = String(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.string) {
          const ctx2 = this._getOrReturnCtx(input);
          addIssueToContext(ctx2, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.string,
            received: ctx2.parsedType
          });
          return INVALID;
        }
        const status = new ParseStatus();
        let ctx = void 0;
        for (const check2 of this._def.checks) {
          if (check2.kind === "min") {
            if (input.data.length < check2.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                minimum: check2.value,
                type: "string",
                inclusive: true,
                exact: false,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "max") {
            if (input.data.length > check2.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                maximum: check2.value,
                type: "string",
                inclusive: true,
                exact: false,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "length") {
            const tooBig = input.data.length > check2.value;
            const tooSmall = input.data.length < check2.value;
            if (tooBig || tooSmall) {
              ctx = this._getOrReturnCtx(input, ctx);
              if (tooBig) {
                addIssueToContext(ctx, {
                  code: ZodIssueCode.too_big,
                  maximum: check2.value,
                  type: "string",
                  inclusive: true,
                  exact: true,
                  message: check2.message
                });
              } else if (tooSmall) {
                addIssueToContext(ctx, {
                  code: ZodIssueCode.too_small,
                  minimum: check2.value,
                  type: "string",
                  inclusive: true,
                  exact: true,
                  message: check2.message
                });
              }
              status.dirty();
            }
          } else if (check2.kind === "email") {
            if (!emailRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "email",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "emoji") {
            if (!emojiRegex) {
              emojiRegex = new RegExp(_emojiRegex, "u");
            }
            if (!emojiRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "emoji",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "uuid") {
            if (!uuidRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "uuid",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "nanoid") {
            if (!nanoidRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "nanoid",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "cuid") {
            if (!cuidRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "cuid",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "cuid2") {
            if (!cuid2Regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "cuid2",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "ulid") {
            if (!ulidRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "ulid",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "url") {
            try {
              new URL(input.data);
            } catch (_a) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "url",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "regex") {
            check2.regex.lastIndex = 0;
            const testResult = check2.regex.test(input.data);
            if (!testResult) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "regex",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "trim") {
            input.data = input.data.trim();
          } else if (check2.kind === "includes") {
            if (!input.data.includes(check2.value, check2.position)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: { includes: check2.value, position: check2.position },
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "toLowerCase") {
            input.data = input.data.toLowerCase();
          } else if (check2.kind === "toUpperCase") {
            input.data = input.data.toUpperCase();
          } else if (check2.kind === "startsWith") {
            if (!input.data.startsWith(check2.value)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: { startsWith: check2.value },
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "endsWith") {
            if (!input.data.endsWith(check2.value)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: { endsWith: check2.value },
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "datetime") {
            const regex = datetimeRegex(check2);
            if (!regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: "datetime",
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "date") {
            const regex = dateRegex;
            if (!regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: "date",
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "time") {
            const regex = timeRegex(check2);
            if (!regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: "time",
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "duration") {
            if (!durationRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "duration",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "ip") {
            if (!isValidIP(input.data, check2.version)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "ip",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "jwt") {
            if (!isValidJWT(input.data, check2.alg)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "jwt",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "cidr") {
            if (!isValidCidr(input.data, check2.version)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "cidr",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "base64") {
            if (!base64Regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "base64",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "base64url") {
            if (!base64urlRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "base64url",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else {
            util.assertNever(check2);
          }
        }
        return { status: status.value, value: input.data };
      }
      _regex(regex, validation, message) {
        return this.refinement((data3) => regex.test(data3), {
          validation,
          code: ZodIssueCode.invalid_string,
          ...errorUtil.errToObj(message)
        });
      }
      _addCheck(check2) {
        return new _ZodString({
          ...this._def,
          checks: [...this._def.checks, check2]
        });
      }
      email(message) {
        return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
      }
      url(message) {
        return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
      }
      emoji(message) {
        return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
      }
      uuid(message) {
        return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
      }
      nanoid(message) {
        return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
      }
      cuid(message) {
        return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
      }
      cuid2(message) {
        return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
      }
      ulid(message) {
        return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
      }
      base64(message) {
        return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
      }
      base64url(message) {
        return this._addCheck({
          kind: "base64url",
          ...errorUtil.errToObj(message)
        });
      }
      jwt(options) {
        return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
      }
      ip(options) {
        return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
      }
      cidr(options) {
        return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
      }
      datetime(options) {
        var _a, _b;
        if (typeof options === "string") {
          return this._addCheck({
            kind: "datetime",
            precision: null,
            offset: false,
            local: false,
            message: options
          });
        }
        return this._addCheck({
          kind: "datetime",
          precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
          offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false,
          local: (_b = options === null || options === void 0 ? void 0 : options.local) !== null && _b !== void 0 ? _b : false,
          ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message)
        });
      }
      date(message) {
        return this._addCheck({ kind: "date", message });
      }
      time(options) {
        if (typeof options === "string") {
          return this._addCheck({
            kind: "time",
            precision: null,
            message: options
          });
        }
        return this._addCheck({
          kind: "time",
          precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
          ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message)
        });
      }
      duration(message) {
        return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
      }
      regex(regex, message) {
        return this._addCheck({
          kind: "regex",
          regex,
          ...errorUtil.errToObj(message)
        });
      }
      includes(value, options) {
        return this._addCheck({
          kind: "includes",
          value,
          position: options === null || options === void 0 ? void 0 : options.position,
          ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message)
        });
      }
      startsWith(value, message) {
        return this._addCheck({
          kind: "startsWith",
          value,
          ...errorUtil.errToObj(message)
        });
      }
      endsWith(value, message) {
        return this._addCheck({
          kind: "endsWith",
          value,
          ...errorUtil.errToObj(message)
        });
      }
      min(minLength, message) {
        return this._addCheck({
          kind: "min",
          value: minLength,
          ...errorUtil.errToObj(message)
        });
      }
      max(maxLength, message) {
        return this._addCheck({
          kind: "max",
          value: maxLength,
          ...errorUtil.errToObj(message)
        });
      }
      length(len, message) {
        return this._addCheck({
          kind: "length",
          value: len,
          ...errorUtil.errToObj(message)
        });
      }
      /**
       * Equivalent to `.min(1)`
       */
      nonempty(message) {
        return this.min(1, errorUtil.errToObj(message));
      }
      trim() {
        return new _ZodString({
          ...this._def,
          checks: [...this._def.checks, { kind: "trim" }]
        });
      }
      toLowerCase() {
        return new _ZodString({
          ...this._def,
          checks: [...this._def.checks, { kind: "toLowerCase" }]
        });
      }
      toUpperCase() {
        return new _ZodString({
          ...this._def,
          checks: [...this._def.checks, { kind: "toUpperCase" }]
        });
      }
      get isDatetime() {
        return !!this._def.checks.find((ch) => ch.kind === "datetime");
      }
      get isDate() {
        return !!this._def.checks.find((ch) => ch.kind === "date");
      }
      get isTime() {
        return !!this._def.checks.find((ch) => ch.kind === "time");
      }
      get isDuration() {
        return !!this._def.checks.find((ch) => ch.kind === "duration");
      }
      get isEmail() {
        return !!this._def.checks.find((ch) => ch.kind === "email");
      }
      get isURL() {
        return !!this._def.checks.find((ch) => ch.kind === "url");
      }
      get isEmoji() {
        return !!this._def.checks.find((ch) => ch.kind === "emoji");
      }
      get isUUID() {
        return !!this._def.checks.find((ch) => ch.kind === "uuid");
      }
      get isNANOID() {
        return !!this._def.checks.find((ch) => ch.kind === "nanoid");
      }
      get isCUID() {
        return !!this._def.checks.find((ch) => ch.kind === "cuid");
      }
      get isCUID2() {
        return !!this._def.checks.find((ch) => ch.kind === "cuid2");
      }
      get isULID() {
        return !!this._def.checks.find((ch) => ch.kind === "ulid");
      }
      get isIP() {
        return !!this._def.checks.find((ch) => ch.kind === "ip");
      }
      get isCIDR() {
        return !!this._def.checks.find((ch) => ch.kind === "cidr");
      }
      get isBase64() {
        return !!this._def.checks.find((ch) => ch.kind === "base64");
      }
      get isBase64url() {
        return !!this._def.checks.find((ch) => ch.kind === "base64url");
      }
      get minLength() {
        let min2 = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "min") {
            if (min2 === null || ch.value > min2)
              min2 = ch.value;
          }
        }
        return min2;
      }
      get maxLength() {
        let max = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "max") {
            if (max === null || ch.value < max)
              max = ch.value;
          }
        }
        return max;
      }
    };
    ZodString.create = (params) => {
      var _a;
      return new ZodString({
        checks: [],
        typeName: ZodFirstPartyTypeKind.ZodString,
        coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,
        ...processCreateParams(params)
      });
    };
    ZodNumber = class _ZodNumber extends ZodType {
      constructor() {
        super(...arguments);
        this.min = this.gte;
        this.max = this.lte;
        this.step = this.multipleOf;
      }
      _parse(input) {
        if (this._def.coerce) {
          input.data = Number(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.number) {
          const ctx2 = this._getOrReturnCtx(input);
          addIssueToContext(ctx2, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.number,
            received: ctx2.parsedType
          });
          return INVALID;
        }
        let ctx = void 0;
        const status = new ParseStatus();
        for (const check2 of this._def.checks) {
          if (check2.kind === "int") {
            if (!util.isInteger(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: "integer",
                received: "float",
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "min") {
            const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value;
            if (tooSmall) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                minimum: check2.value,
                type: "number",
                inclusive: check2.inclusive,
                exact: false,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "max") {
            const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value;
            if (tooBig) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                maximum: check2.value,
                type: "number",
                inclusive: check2.inclusive,
                exact: false,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "multipleOf") {
            if (floatSafeRemainder(input.data, check2.value) !== 0) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.not_multiple_of,
                multipleOf: check2.value,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "finite") {
            if (!Number.isFinite(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.not_finite,
                message: check2.message
              });
              status.dirty();
            }
          } else {
            util.assertNever(check2);
          }
        }
        return { status: status.value, value: input.data };
      }
      gte(value, message) {
        return this.setLimit("min", value, true, errorUtil.toString(message));
      }
      gt(value, message) {
        return this.setLimit("min", value, false, errorUtil.toString(message));
      }
      lte(value, message) {
        return this.setLimit("max", value, true, errorUtil.toString(message));
      }
      lt(value, message) {
        return this.setLimit("max", value, false, errorUtil.toString(message));
      }
      setLimit(kind, value, inclusive, message) {
        return new _ZodNumber({
          ...this._def,
          checks: [
            ...this._def.checks,
            {
              kind,
              value,
              inclusive,
              message: errorUtil.toString(message)
            }
          ]
        });
      }
      _addCheck(check2) {
        return new _ZodNumber({
          ...this._def,
          checks: [...this._def.checks, check2]
        });
      }
      int(message) {
        return this._addCheck({
          kind: "int",
          message: errorUtil.toString(message)
        });
      }
      positive(message) {
        return this._addCheck({
          kind: "min",
          value: 0,
          inclusive: false,
          message: errorUtil.toString(message)
        });
      }
      negative(message) {
        return this._addCheck({
          kind: "max",
          value: 0,
          inclusive: false,
          message: errorUtil.toString(message)
        });
      }
      nonpositive(message) {
        return this._addCheck({
          kind: "max",
          value: 0,
          inclusive: true,
          message: errorUtil.toString(message)
        });
      }
      nonnegative(message) {
        return this._addCheck({
          kind: "min",
          value: 0,
          inclusive: true,
          message: errorUtil.toString(message)
        });
      }
      multipleOf(value, message) {
        return this._addCheck({
          kind: "multipleOf",
          value,
          message: errorUtil.toString(message)
        });
      }
      finite(message) {
        return this._addCheck({
          kind: "finite",
          message: errorUtil.toString(message)
        });
      }
      safe(message) {
        return this._addCheck({
          kind: "min",
          inclusive: true,
          value: Number.MIN_SAFE_INTEGER,
          message: errorUtil.toString(message)
        })._addCheck({
          kind: "max",
          inclusive: true,
          value: Number.MAX_SAFE_INTEGER,
          message: errorUtil.toString(message)
        });
      }
      get minValue() {
        let min2 = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "min") {
            if (min2 === null || ch.value > min2)
              min2 = ch.value;
          }
        }
        return min2;
      }
      get maxValue() {
        let max = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "max") {
            if (max === null || ch.value < max)
              max = ch.value;
          }
        }
        return max;
      }
      get isInt() {
        return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
      }
      get isFinite() {
        let max = null, min2 = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
            return true;
          } else if (ch.kind === "min") {
            if (min2 === null || ch.value > min2)
              min2 = ch.value;
          } else if (ch.kind === "max") {
            if (max === null || ch.value < max)
              max = ch.value;
          }
        }
        return Number.isFinite(min2) && Number.isFinite(max);
      }
    };
    ZodNumber.create = (params) => {
      return new ZodNumber({
        checks: [],
        typeName: ZodFirstPartyTypeKind.ZodNumber,
        coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
        ...processCreateParams(params)
      });
    };
    ZodBigInt = class _ZodBigInt extends ZodType {
      constructor() {
        super(...arguments);
        this.min = this.gte;
        this.max = this.lte;
      }
      _parse(input) {
        if (this._def.coerce) {
          try {
            input.data = BigInt(input.data);
          } catch (_a) {
            return this._getInvalidInput(input);
          }
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.bigint) {
          return this._getInvalidInput(input);
        }
        let ctx = void 0;
        const status = new ParseStatus();
        for (const check2 of this._def.checks) {
          if (check2.kind === "min") {
            const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value;
            if (tooSmall) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                type: "bigint",
                minimum: check2.value,
                inclusive: check2.inclusive,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "max") {
            const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value;
            if (tooBig) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                type: "bigint",
                maximum: check2.value,
                inclusive: check2.inclusive,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "multipleOf") {
            if (input.data % check2.value !== BigInt(0)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.not_multiple_of,
                multipleOf: check2.value,
                message: check2.message
              });
              status.dirty();
            }
          } else {
            util.assertNever(check2);
          }
        }
        return { status: status.value, value: input.data };
      }
      _getInvalidInput(input) {
        const ctx = this._getOrReturnCtx(input);
        addIssueToContext(ctx, {
          code: ZodIssueCode.invalid_type,
          expected: ZodParsedType.bigint,
          received: ctx.parsedType
        });
        return INVALID;
      }
      gte(value, message) {
        return this.setLimit("min", value, true, errorUtil.toString(message));
      }
      gt(value, message) {
        return this.setLimit("min", value, false, errorUtil.toString(message));
      }
      lte(value, message) {
        return this.setLimit("max", value, true, errorUtil.toString(message));
      }
      lt(value, message) {
        return this.setLimit("max", value, false, errorUtil.toString(message));
      }
      setLimit(kind, value, inclusive, message) {
        return new _ZodBigInt({
          ...this._def,
          checks: [
            ...this._def.checks,
            {
              kind,
              value,
              inclusive,
              message: errorUtil.toString(message)
            }
          ]
        });
      }
      _addCheck(check2) {
        return new _ZodBigInt({
          ...this._def,
          checks: [...this._def.checks, check2]
        });
      }
      positive(message) {
        return this._addCheck({
          kind: "min",
          value: BigInt(0),
          inclusive: false,
          message: errorUtil.toString(message)
        });
      }
      negative(message) {
        return this._addCheck({
          kind: "max",
          value: BigInt(0),
          inclusive: false,
          message: errorUtil.toString(message)
        });
      }
      nonpositive(message) {
        return this._addCheck({
          kind: "max",
          value: BigInt(0),
          inclusive: true,
          message: errorUtil.toString(message)
        });
      }
      nonnegative(message) {
        return this._addCheck({
          kind: "min",
          value: BigInt(0),
          inclusive: true,
          message: errorUtil.toString(message)
        });
      }
      multipleOf(value, message) {
        return this._addCheck({
          kind: "multipleOf",
          value,
          message: errorUtil.toString(message)
        });
      }
      get minValue() {
        let min2 = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "min") {
            if (min2 === null || ch.value > min2)
              min2 = ch.value;
          }
        }
        return min2;
      }
      get maxValue() {
        let max = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "max") {
            if (max === null || ch.value < max)
              max = ch.value;
          }
        }
        return max;
      }
    };
    ZodBigInt.create = (params) => {
      var _a;
      return new ZodBigInt({
        checks: [],
        typeName: ZodFirstPartyTypeKind.ZodBigInt,
        coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,
        ...processCreateParams(params)
      });
    };
    ZodBoolean = class extends ZodType {
      _parse(input) {
        if (this._def.coerce) {
          input.data = Boolean(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.boolean) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.boolean,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return OK(input.data);
      }
    };
    ZodBoolean.create = (params) => {
      return new ZodBoolean({
        typeName: ZodFirstPartyTypeKind.ZodBoolean,
        coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
        ...processCreateParams(params)
      });
    };
    ZodDate = class _ZodDate extends ZodType {
      _parse(input) {
        if (this._def.coerce) {
          input.data = new Date(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.date) {
          const ctx2 = this._getOrReturnCtx(input);
          addIssueToContext(ctx2, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.date,
            received: ctx2.parsedType
          });
          return INVALID;
        }
        if (isNaN(input.data.getTime())) {
          const ctx2 = this._getOrReturnCtx(input);
          addIssueToContext(ctx2, {
            code: ZodIssueCode.invalid_date
          });
          return INVALID;
        }
        const status = new ParseStatus();
        let ctx = void 0;
        for (const check2 of this._def.checks) {
          if (check2.kind === "min") {
            if (input.data.getTime() < check2.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                message: check2.message,
                inclusive: true,
                exact: false,
                minimum: check2.value,
                type: "date"
              });
              status.dirty();
            }
          } else if (check2.kind === "max") {
            if (input.data.getTime() > check2.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                message: check2.message,
                inclusive: true,
                exact: false,
                maximum: check2.value,
                type: "date"
              });
              status.dirty();
            }
          } else {
            util.assertNever(check2);
          }
        }
        return {
          status: status.value,
          value: new Date(input.data.getTime())
        };
      }
      _addCheck(check2) {
        return new _ZodDate({
          ...this._def,
          checks: [...this._def.checks, check2]
        });
      }
      min(minDate, message) {
        return this._addCheck({
          kind: "min",
          value: minDate.getTime(),
          message: errorUtil.toString(message)
        });
      }
      max(maxDate, message) {
        return this._addCheck({
          kind: "max",
          value: maxDate.getTime(),
          message: errorUtil.toString(message)
        });
      }
      get minDate() {
        let min2 = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "min") {
            if (min2 === null || ch.value > min2)
              min2 = ch.value;
          }
        }
        return min2 != null ? new Date(min2) : null;
      }
      get maxDate() {
        let max = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "max") {
            if (max === null || ch.value < max)
              max = ch.value;
          }
        }
        return max != null ? new Date(max) : null;
      }
    };
    ZodDate.create = (params) => {
      return new ZodDate({
        checks: [],
        coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
        typeName: ZodFirstPartyTypeKind.ZodDate,
        ...processCreateParams(params)
      });
    };
    ZodSymbol = class extends ZodType {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.symbol) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.symbol,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return OK(input.data);
      }
    };
    ZodSymbol.create = (params) => {
      return new ZodSymbol({
        typeName: ZodFirstPartyTypeKind.ZodSymbol,
        ...processCreateParams(params)
      });
    };
    ZodUndefined = class extends ZodType {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.undefined) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.undefined,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return OK(input.data);
      }
    };
    ZodUndefined.create = (params) => {
      return new ZodUndefined({
        typeName: ZodFirstPartyTypeKind.ZodUndefined,
        ...processCreateParams(params)
      });
    };
    ZodNull = class extends ZodType {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.null) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.null,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return OK(input.data);
      }
    };
    ZodNull.create = (params) => {
      return new ZodNull({
        typeName: ZodFirstPartyTypeKind.ZodNull,
        ...processCreateParams(params)
      });
    };
    ZodAny = class extends ZodType {
      constructor() {
        super(...arguments);
        this._any = true;
      }
      _parse(input) {
        return OK(input.data);
      }
    };
    ZodAny.create = (params) => {
      return new ZodAny({
        typeName: ZodFirstPartyTypeKind.ZodAny,
        ...processCreateParams(params)
      });
    };
    ZodUnknown = class extends ZodType {
      constructor() {
        super(...arguments);
        this._unknown = true;
      }
      _parse(input) {
        return OK(input.data);
      }
    };
    ZodUnknown.create = (params) => {
      return new ZodUnknown({
        typeName: ZodFirstPartyTypeKind.ZodUnknown,
        ...processCreateParams(params)
      });
    };
    ZodNever = class extends ZodType {
      _parse(input) {
        const ctx = this._getOrReturnCtx(input);
        addIssueToContext(ctx, {
          code: ZodIssueCode.invalid_type,
          expected: ZodParsedType.never,
          received: ctx.parsedType
        });
        return INVALID;
      }
    };
    ZodNever.create = (params) => {
      return new ZodNever({
        typeName: ZodFirstPartyTypeKind.ZodNever,
        ...processCreateParams(params)
      });
    };
    ZodVoid = class extends ZodType {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.undefined) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.void,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return OK(input.data);
      }
    };
    ZodVoid.create = (params) => {
      return new ZodVoid({
        typeName: ZodFirstPartyTypeKind.ZodVoid,
        ...processCreateParams(params)
      });
    };
    ZodArray = class _ZodArray extends ZodType {
      _parse(input) {
        const { ctx, status } = this._processInputParams(input);
        const def = this._def;
        if (ctx.parsedType !== ZodParsedType.array) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.array,
            received: ctx.parsedType
          });
          return INVALID;
        }
        if (def.exactLength !== null) {
          const tooBig = ctx.data.length > def.exactLength.value;
          const tooSmall = ctx.data.length < def.exactLength.value;
          if (tooBig || tooSmall) {
            addIssueToContext(ctx, {
              code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
              minimum: tooSmall ? def.exactLength.value : void 0,
              maximum: tooBig ? def.exactLength.value : void 0,
              type: "array",
              inclusive: true,
              exact: true,
              message: def.exactLength.message
            });
            status.dirty();
          }
        }
        if (def.minLength !== null) {
          if (ctx.data.length < def.minLength.value) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_small,
              minimum: def.minLength.value,
              type: "array",
              inclusive: true,
              exact: false,
              message: def.minLength.message
            });
            status.dirty();
          }
        }
        if (def.maxLength !== null) {
          if (ctx.data.length > def.maxLength.value) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_big,
              maximum: def.maxLength.value,
              type: "array",
              inclusive: true,
              exact: false,
              message: def.maxLength.message
            });
            status.dirty();
          }
        }
        if (ctx.common.async) {
          return Promise.all([...ctx.data].map((item, i6) => {
            return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i6));
          })).then((result3) => {
            return ParseStatus.mergeArray(status, result3);
          });
        }
        const result2 = [...ctx.data].map((item, i6) => {
          return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i6));
        });
        return ParseStatus.mergeArray(status, result2);
      }
      get element() {
        return this._def.type;
      }
      min(minLength, message) {
        return new _ZodArray({
          ...this._def,
          minLength: { value: minLength, message: errorUtil.toString(message) }
        });
      }
      max(maxLength, message) {
        return new _ZodArray({
          ...this._def,
          maxLength: { value: maxLength, message: errorUtil.toString(message) }
        });
      }
      length(len, message) {
        return new _ZodArray({
          ...this._def,
          exactLength: { value: len, message: errorUtil.toString(message) }
        });
      }
      nonempty(message) {
        return this.min(1, message);
      }
    };
    ZodArray.create = (schema4, params) => {
      return new ZodArray({
        type: schema4,
        minLength: null,
        maxLength: null,
        exactLength: null,
        typeName: ZodFirstPartyTypeKind.ZodArray,
        ...processCreateParams(params)
      });
    };
    ZodObject = class _ZodObject extends ZodType {
      constructor() {
        super(...arguments);
        this._cached = null;
        this.nonstrict = this.passthrough;
        this.augment = this.extend;
      }
      _getCached() {
        if (this._cached !== null)
          return this._cached;
        const shape = this._def.shape();
        const keys = util.objectKeys(shape);
        return this._cached = { shape, keys };
      }
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.object) {
          const ctx2 = this._getOrReturnCtx(input);
          addIssueToContext(ctx2, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.object,
            received: ctx2.parsedType
          });
          return INVALID;
        }
        const { status, ctx } = this._processInputParams(input);
        const { shape, keys: shapeKeys } = this._getCached();
        const extraKeys = [];
        if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
          for (const key in ctx.data) {
            if (!shapeKeys.includes(key)) {
              extraKeys.push(key);
            }
          }
        }
        const pairs3 = [];
        for (const key of shapeKeys) {
          const keyValidator = shape[key];
          const value = ctx.data[key];
          pairs3.push({
            key: { status: "valid", value: key },
            value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
            alwaysSet: key in ctx.data
          });
        }
        if (this._def.catchall instanceof ZodNever) {
          const unknownKeys = this._def.unknownKeys;
          if (unknownKeys === "passthrough") {
            for (const key of extraKeys) {
              pairs3.push({
                key: { status: "valid", value: key },
                value: { status: "valid", value: ctx.data[key] }
              });
            }
          } else if (unknownKeys === "strict") {
            if (extraKeys.length > 0) {
              addIssueToContext(ctx, {
                code: ZodIssueCode.unrecognized_keys,
                keys: extraKeys
              });
              status.dirty();
            }
          } else if (unknownKeys === "strip") ;
          else {
            throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
          }
        } else {
          const catchall = this._def.catchall;
          for (const key of extraKeys) {
            const value = ctx.data[key];
            pairs3.push({
              key: { status: "valid", value: key },
              value: catchall._parse(
                new ParseInputLazyPath(ctx, value, ctx.path, key)
                //, ctx.child(key), value, getParsedType(value)
              ),
              alwaysSet: key in ctx.data
            });
          }
        }
        if (ctx.common.async) {
          return Promise.resolve().then(async () => {
            const syncPairs = [];
            for (const pair of pairs3) {
              const key = await pair.key;
              const value = await pair.value;
              syncPairs.push({
                key,
                value,
                alwaysSet: pair.alwaysSet
              });
            }
            return syncPairs;
          }).then((syncPairs) => {
            return ParseStatus.mergeObjectSync(status, syncPairs);
          });
        } else {
          return ParseStatus.mergeObjectSync(status, pairs3);
        }
      }
      get shape() {
        return this._def.shape();
      }
      strict(message) {
        errorUtil.errToObj;
        return new _ZodObject({
          ...this._def,
          unknownKeys: "strict",
          ...message !== void 0 ? {
            errorMap: (issue, ctx) => {
              var _a, _b, _c, _d;
              const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError;
              if (issue.code === "unrecognized_keys")
                return {
                  message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError
                };
              return {
                message: defaultError
              };
            }
          } : {}
        });
      }
      strip() {
        return new _ZodObject({
          ...this._def,
          unknownKeys: "strip"
        });
      }
      passthrough() {
        return new _ZodObject({
          ...this._def,
          unknownKeys: "passthrough"
        });
      }
      // const AugmentFactory =
      //   <Def extends ZodObjectDef>(def: Def) =>
      //   <Augmentation extends ZodRawShape>(
      //     augmentation: Augmentation
      //   ): ZodObject<
      //     extendShape<ReturnType<Def["shape"]>, Augmentation>,
      //     Def["unknownKeys"],
      //     Def["catchall"]
      //   > => {
      //     return new ZodObject({
      //       ...def,
      //       shape: () => ({
      //         ...def.shape(),
      //         ...augmentation,
      //       }),
      //     }) as any;
      //   };
      extend(augmentation) {
        return new _ZodObject({
          ...this._def,
          shape: () => ({
            ...this._def.shape(),
            ...augmentation
          })
        });
      }
      /**
       * Prior to zod@1.0.12 there was a bug in the
       * inferred type of merged objects. Please
       * upgrade if you are experiencing issues.
       */
      merge(merging) {
        const merged = new _ZodObject({
          unknownKeys: merging._def.unknownKeys,
          catchall: merging._def.catchall,
          shape: () => ({
            ...this._def.shape(),
            ...merging._def.shape()
          }),
          typeName: ZodFirstPartyTypeKind.ZodObject
        });
        return merged;
      }
      // merge<
      //   Incoming extends AnyZodObject,
      //   Augmentation extends Incoming["shape"],
      //   NewOutput extends {
      //     [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
      //       ? Augmentation[k]["_output"]
      //       : k extends keyof Output
      //       ? Output[k]
      //       : never;
      //   },
      //   NewInput extends {
      //     [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
      //       ? Augmentation[k]["_input"]
      //       : k extends keyof Input
      //       ? Input[k]
      //       : never;
      //   }
      // >(
      //   merging: Incoming
      // ): ZodObject<
      //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
      //   Incoming["_def"]["unknownKeys"],
      //   Incoming["_def"]["catchall"],
      //   NewOutput,
      //   NewInput
      // > {
      //   const merged: any = new ZodObject({
      //     unknownKeys: merging._def.unknownKeys,
      //     catchall: merging._def.catchall,
      //     shape: () =>
      //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
      //     typeName: ZodFirstPartyTypeKind.ZodObject,
      //   }) as any;
      //   return merged;
      // }
      setKey(key, schema4) {
        return this.augment({ [key]: schema4 });
      }
      // merge<Incoming extends AnyZodObject>(
      //   merging: Incoming
      // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
      // ZodObject<
      //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
      //   Incoming["_def"]["unknownKeys"],
      //   Incoming["_def"]["catchall"]
      // > {
      //   // const mergedShape = objectUtil.mergeShapes(
      //   //   this._def.shape(),
      //   //   merging._def.shape()
      //   // );
      //   const merged: any = new ZodObject({
      //     unknownKeys: merging._def.unknownKeys,
      //     catchall: merging._def.catchall,
      //     shape: () =>
      //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
      //     typeName: ZodFirstPartyTypeKind.ZodObject,
      //   }) as any;
      //   return merged;
      // }
      catchall(index2) {
        return new _ZodObject({
          ...this._def,
          catchall: index2
        });
      }
      pick(mask) {
        const shape = {};
        util.objectKeys(mask).forEach((key) => {
          if (mask[key] && this.shape[key]) {
            shape[key] = this.shape[key];
          }
        });
        return new _ZodObject({
          ...this._def,
          shape: () => shape
        });
      }
      omit(mask) {
        const shape = {};
        util.objectKeys(this.shape).forEach((key) => {
          if (!mask[key]) {
            shape[key] = this.shape[key];
          }
        });
        return new _ZodObject({
          ...this._def,
          shape: () => shape
        });
      }
      /**
       * @deprecated
       */
      deepPartial() {
        return deepPartialify(this);
      }
      partial(mask) {
        const newShape = {};
        util.objectKeys(this.shape).forEach((key) => {
          const fieldSchema = this.shape[key];
          if (mask && !mask[key]) {
            newShape[key] = fieldSchema;
          } else {
            newShape[key] = fieldSchema.optional();
          }
        });
        return new _ZodObject({
          ...this._def,
          shape: () => newShape
        });
      }
      required(mask) {
        const newShape = {};
        util.objectKeys(this.shape).forEach((key) => {
          if (mask && !mask[key]) {
            newShape[key] = this.shape[key];
          } else {
            const fieldSchema = this.shape[key];
            let newField = fieldSchema;
            while (newField instanceof ZodOptional) {
              newField = newField._def.innerType;
            }
            newShape[key] = newField;
          }
        });
        return new _ZodObject({
          ...this._def,
          shape: () => newShape
        });
      }
      keyof() {
        return createZodEnum(util.objectKeys(this.shape));
      }
    };
    ZodObject.create = (shape, params) => {
      return new ZodObject({
        shape: () => shape,
        unknownKeys: "strip",
        catchall: ZodNever.create(),
        typeName: ZodFirstPartyTypeKind.ZodObject,
        ...processCreateParams(params)
      });
    };
    ZodObject.strictCreate = (shape, params) => {
      return new ZodObject({
        shape: () => shape,
        unknownKeys: "strict",
        catchall: ZodNever.create(),
        typeName: ZodFirstPartyTypeKind.ZodObject,
        ...processCreateParams(params)
      });
    };
    ZodObject.lazycreate = (shape, params) => {
      return new ZodObject({
        shape,
        unknownKeys: "strip",
        catchall: ZodNever.create(),
        typeName: ZodFirstPartyTypeKind.ZodObject,
        ...processCreateParams(params)
      });
    };
    ZodUnion = class extends ZodType {
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        const options = this._def.options;
        function handleResults(results) {
          for (const result2 of results) {
            if (result2.result.status === "valid") {
              return result2.result;
            }
          }
          for (const result2 of results) {
            if (result2.result.status === "dirty") {
              ctx.common.issues.push(...result2.ctx.common.issues);
              return result2.result;
            }
          }
          const unionErrors = results.map((result2) => new ZodError(result2.ctx.common.issues));
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_union,
            unionErrors
          });
          return INVALID;
        }
        if (ctx.common.async) {
          return Promise.all(options.map(async (option) => {
            const childCtx = {
              ...ctx,
              common: {
                ...ctx.common,
                issues: []
              },
              parent: null
            };
            return {
              result: await option._parseAsync({
                data: ctx.data,
                path: ctx.path,
                parent: childCtx
              }),
              ctx: childCtx
            };
          })).then(handleResults);
        } else {
          let dirty = void 0;
          const issues = [];
          for (const option of options) {
            const childCtx = {
              ...ctx,
              common: {
                ...ctx.common,
                issues: []
              },
              parent: null
            };
            const result2 = option._parseSync({
              data: ctx.data,
              path: ctx.path,
              parent: childCtx
            });
            if (result2.status === "valid") {
              return result2;
            } else if (result2.status === "dirty" && !dirty) {
              dirty = { result: result2, ctx: childCtx };
            }
            if (childCtx.common.issues.length) {
              issues.push(childCtx.common.issues);
            }
          }
          if (dirty) {
            ctx.common.issues.push(...dirty.ctx.common.issues);
            return dirty.result;
          }
          const unionErrors = issues.map((issues2) => new ZodError(issues2));
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_union,
            unionErrors
          });
          return INVALID;
        }
      }
      get options() {
        return this._def.options;
      }
    };
    ZodUnion.create = (types8, params) => {
      return new ZodUnion({
        options: types8,
        typeName: ZodFirstPartyTypeKind.ZodUnion,
        ...processCreateParams(params)
      });
    };
    getDiscriminator = (type4) => {
      if (type4 instanceof ZodLazy) {
        return getDiscriminator(type4.schema);
      } else if (type4 instanceof ZodEffects) {
        return getDiscriminator(type4.innerType());
      } else if (type4 instanceof ZodLiteral) {
        return [type4.value];
      } else if (type4 instanceof ZodEnum) {
        return type4.options;
      } else if (type4 instanceof ZodNativeEnum) {
        return util.objectValues(type4.enum);
      } else if (type4 instanceof ZodDefault) {
        return getDiscriminator(type4._def.innerType);
      } else if (type4 instanceof ZodUndefined) {
        return [void 0];
      } else if (type4 instanceof ZodNull) {
        return [null];
      } else if (type4 instanceof ZodOptional) {
        return [void 0, ...getDiscriminator(type4.unwrap())];
      } else if (type4 instanceof ZodNullable) {
        return [null, ...getDiscriminator(type4.unwrap())];
      } else if (type4 instanceof ZodBranded) {
        return getDiscriminator(type4.unwrap());
      } else if (type4 instanceof ZodReadonly) {
        return getDiscriminator(type4.unwrap());
      } else if (type4 instanceof ZodCatch) {
        return getDiscriminator(type4._def.innerType);
      } else {
        return [];
      }
    };
    ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.object) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.object,
            received: ctx.parsedType
          });
          return INVALID;
        }
        const discriminator = this.discriminator;
        const discriminatorValue = ctx.data[discriminator];
        const option = this.optionsMap.get(discriminatorValue);
        if (!option) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_union_discriminator,
            options: Array.from(this.optionsMap.keys()),
            path: [discriminator]
          });
          return INVALID;
        }
        if (ctx.common.async) {
          return option._parseAsync({
            data: ctx.data,
            path: ctx.path,
            parent: ctx
          });
        } else {
          return option._parseSync({
            data: ctx.data,
            path: ctx.path,
            parent: ctx
          });
        }
      }
      get discriminator() {
        return this._def.discriminator;
      }
      get options() {
        return this._def.options;
      }
      get optionsMap() {
        return this._def.optionsMap;
      }
      /**
       * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
       * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
       * have a different value for each object in the union.
       * @param discriminator the name of the discriminator property
       * @param types an array of object schemas
       * @param params
       */
      static create(discriminator, options, params) {
        const optionsMap = /* @__PURE__ */ new Map();
        for (const type4 of options) {
          const discriminatorValues = getDiscriminator(type4.shape[discriminator]);
          if (!discriminatorValues.length) {
            throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
          }
          for (const value of discriminatorValues) {
            if (optionsMap.has(value)) {
              throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
            }
            optionsMap.set(value, type4);
          }
        }
        return new _ZodDiscriminatedUnion({
          typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
          discriminator,
          options,
          optionsMap,
          ...processCreateParams(params)
        });
      }
    };
    ZodIntersection = class extends ZodType {
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        const handleParsed = (parsedLeft, parsedRight) => {
          if (isAborted(parsedLeft) || isAborted(parsedRight)) {
            return INVALID;
          }
          const merged = mergeValues(parsedLeft.value, parsedRight.value);
          if (!merged.valid) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.invalid_intersection_types
            });
            return INVALID;
          }
          if (isDirty(parsedLeft) || isDirty(parsedRight)) {
            status.dirty();
          }
          return { status: status.value, value: merged.data };
        };
        if (ctx.common.async) {
          return Promise.all([
            this._def.left._parseAsync({
              data: ctx.data,
              path: ctx.path,
              parent: ctx
            }),
            this._def.right._parseAsync({
              data: ctx.data,
              path: ctx.path,
              parent: ctx
            })
          ]).then(([left, right]) => handleParsed(left, right));
        } else {
          return handleParsed(this._def.left._parseSync({
            data: ctx.data,
            path: ctx.path,
            parent: ctx
          }), this._def.right._parseSync({
            data: ctx.data,
            path: ctx.path,
            parent: ctx
          }));
        }
      }
    };
    ZodIntersection.create = (left, right, params) => {
      return new ZodIntersection({
        left,
        right,
        typeName: ZodFirstPartyTypeKind.ZodIntersection,
        ...processCreateParams(params)
      });
    };
    ZodTuple = class _ZodTuple extends ZodType {
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.array) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.array,
            received: ctx.parsedType
          });
          return INVALID;
        }
        if (ctx.data.length < this._def.items.length) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            minimum: this._def.items.length,
            inclusive: true,
            exact: false,
            type: "array"
          });
          return INVALID;
        }
        const rest = this._def.rest;
        if (!rest && ctx.data.length > this._def.items.length) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            maximum: this._def.items.length,
            inclusive: true,
            exact: false,
            type: "array"
          });
          status.dirty();
        }
        const items = [...ctx.data].map((item, itemIndex) => {
          const schema4 = this._def.items[itemIndex] || this._def.rest;
          if (!schema4)
            return null;
          return schema4._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
        }).filter((x3) => !!x3);
        if (ctx.common.async) {
          return Promise.all(items).then((results) => {
            return ParseStatus.mergeArray(status, results);
          });
        } else {
          return ParseStatus.mergeArray(status, items);
        }
      }
      get items() {
        return this._def.items;
      }
      rest(rest) {
        return new _ZodTuple({
          ...this._def,
          rest
        });
      }
    };
    ZodTuple.create = (schemas, params) => {
      if (!Array.isArray(schemas)) {
        throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
      }
      return new ZodTuple({
        items: schemas,
        typeName: ZodFirstPartyTypeKind.ZodTuple,
        rest: null,
        ...processCreateParams(params)
      });
    };
    ZodRecord = class _ZodRecord extends ZodType {
      get keySchema() {
        return this._def.keyType;
      }
      get valueSchema() {
        return this._def.valueType;
      }
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.object) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.object,
            received: ctx.parsedType
          });
          return INVALID;
        }
        const pairs3 = [];
        const keyType = this._def.keyType;
        const valueType = this._def.valueType;
        for (const key in ctx.data) {
          pairs3.push({
            key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
            value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
            alwaysSet: key in ctx.data
          });
        }
        if (ctx.common.async) {
          return ParseStatus.mergeObjectAsync(status, pairs3);
        } else {
          return ParseStatus.mergeObjectSync(status, pairs3);
        }
      }
      get element() {
        return this._def.valueType;
      }
      static create(first, second, third) {
        if (second instanceof ZodType) {
          return new _ZodRecord({
            keyType: first,
            valueType: second,
            typeName: ZodFirstPartyTypeKind.ZodRecord,
            ...processCreateParams(third)
          });
        }
        return new _ZodRecord({
          keyType: ZodString.create(),
          valueType: first,
          typeName: ZodFirstPartyTypeKind.ZodRecord,
          ...processCreateParams(second)
        });
      }
    };
    ZodMap = class extends ZodType {
      get keySchema() {
        return this._def.keyType;
      }
      get valueSchema() {
        return this._def.valueType;
      }
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.map) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.map,
            received: ctx.parsedType
          });
          return INVALID;
        }
        const keyType = this._def.keyType;
        const valueType = this._def.valueType;
        const pairs3 = [...ctx.data.entries()].map(([key, value], index2) => {
          return {
            key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index2, "key"])),
            value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index2, "value"]))
          };
        });
        if (ctx.common.async) {
          const finalMap = /* @__PURE__ */ new Map();
          return Promise.resolve().then(async () => {
            for (const pair of pairs3) {
              const key = await pair.key;
              const value = await pair.value;
              if (key.status === "aborted" || value.status === "aborted") {
                return INVALID;
              }
              if (key.status === "dirty" || value.status === "dirty") {
                status.dirty();
              }
              finalMap.set(key.value, value.value);
            }
            return { status: status.value, value: finalMap };
          });
        } else {
          const finalMap = /* @__PURE__ */ new Map();
          for (const pair of pairs3) {
            const key = pair.key;
            const value = pair.value;
            if (key.status === "aborted" || value.status === "aborted") {
              return INVALID;
            }
            if (key.status === "dirty" || value.status === "dirty") {
              status.dirty();
            }
            finalMap.set(key.value, value.value);
          }
          return { status: status.value, value: finalMap };
        }
      }
    };
    ZodMap.create = (keyType, valueType, params) => {
      return new ZodMap({
        valueType,
        keyType,
        typeName: ZodFirstPartyTypeKind.ZodMap,
        ...processCreateParams(params)
      });
    };
    ZodSet = class _ZodSet extends ZodType {
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.set) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.set,
            received: ctx.parsedType
          });
          return INVALID;
        }
        const def = this._def;
        if (def.minSize !== null) {
          if (ctx.data.size < def.minSize.value) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_small,
              minimum: def.minSize.value,
              type: "set",
              inclusive: true,
              exact: false,
              message: def.minSize.message
            });
            status.dirty();
          }
        }
        if (def.maxSize !== null) {
          if (ctx.data.size > def.maxSize.value) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_big,
              maximum: def.maxSize.value,
              type: "set",
              inclusive: true,
              exact: false,
              message: def.maxSize.message
            });
            status.dirty();
          }
        }
        const valueType = this._def.valueType;
        function finalizeSet(elements2) {
          const parsedSet = /* @__PURE__ */ new Set();
          for (const element of elements2) {
            if (element.status === "aborted")
              return INVALID;
            if (element.status === "dirty")
              status.dirty();
            parsedSet.add(element.value);
          }
          return { status: status.value, value: parsedSet };
        }
        const elements = [...ctx.data.values()].map((item, i6) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i6)));
        if (ctx.common.async) {
          return Promise.all(elements).then((elements2) => finalizeSet(elements2));
        } else {
          return finalizeSet(elements);
        }
      }
      min(minSize, message) {
        return new _ZodSet({
          ...this._def,
          minSize: { value: minSize, message: errorUtil.toString(message) }
        });
      }
      max(maxSize, message) {
        return new _ZodSet({
          ...this._def,
          maxSize: { value: maxSize, message: errorUtil.toString(message) }
        });
      }
      size(size, message) {
        return this.min(size, message).max(size, message);
      }
      nonempty(message) {
        return this.min(1, message);
      }
    };
    ZodSet.create = (valueType, params) => {
      return new ZodSet({
        valueType,
        minSize: null,
        maxSize: null,
        typeName: ZodFirstPartyTypeKind.ZodSet,
        ...processCreateParams(params)
      });
    };
    ZodFunction = class _ZodFunction extends ZodType {
      constructor() {
        super(...arguments);
        this.validate = this.implement;
      }
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.function) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.function,
            received: ctx.parsedType
          });
          return INVALID;
        }
        function makeArgsIssue(args, error2) {
          return makeIssue({
            data: args,
            path: ctx.path,
            errorMaps: [
              ctx.common.contextualErrorMap,
              ctx.schemaErrorMap,
              getErrorMap(),
              errorMap
            ].filter((x3) => !!x3),
            issueData: {
              code: ZodIssueCode.invalid_arguments,
              argumentsError: error2
            }
          });
        }
        function makeReturnsIssue(returns, error2) {
          return makeIssue({
            data: returns,
            path: ctx.path,
            errorMaps: [
              ctx.common.contextualErrorMap,
              ctx.schemaErrorMap,
              getErrorMap(),
              errorMap
            ].filter((x3) => !!x3),
            issueData: {
              code: ZodIssueCode.invalid_return_type,
              returnTypeError: error2
            }
          });
        }
        const params = { errorMap: ctx.common.contextualErrorMap };
        const fn = ctx.data;
        if (this._def.returns instanceof ZodPromise) {
          const me2 = this;
          return OK(async function(...args) {
            const error2 = new ZodError([]);
            const parsedArgs = await me2._def.args.parseAsync(args, params).catch((e5) => {
              error2.addIssue(makeArgsIssue(args, e5));
              throw error2;
            });
            const result2 = await Reflect.apply(fn, this, parsedArgs);
            const parsedReturns = await me2._def.returns._def.type.parseAsync(result2, params).catch((e5) => {
              error2.addIssue(makeReturnsIssue(result2, e5));
              throw error2;
            });
            return parsedReturns;
          });
        } else {
          const me2 = this;
          return OK(function(...args) {
            const parsedArgs = me2._def.args.safeParse(args, params);
            if (!parsedArgs.success) {
              throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
            }
            const result2 = Reflect.apply(fn, this, parsedArgs.data);
            const parsedReturns = me2._def.returns.safeParse(result2, params);
            if (!parsedReturns.success) {
              throw new ZodError([makeReturnsIssue(result2, parsedReturns.error)]);
            }
            return parsedReturns.data;
          });
        }
      }
      parameters() {
        return this._def.args;
      }
      returnType() {
        return this._def.returns;
      }
      args(...items) {
        return new _ZodFunction({
          ...this._def,
          args: ZodTuple.create(items).rest(ZodUnknown.create())
        });
      }
      returns(returnType) {
        return new _ZodFunction({
          ...this._def,
          returns: returnType
        });
      }
      implement(func) {
        const validatedFunc = this.parse(func);
        return validatedFunc;
      }
      strictImplement(func) {
        const validatedFunc = this.parse(func);
        return validatedFunc;
      }
      static create(args, returns, params) {
        return new _ZodFunction({
          args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
          returns: returns || ZodUnknown.create(),
          typeName: ZodFirstPartyTypeKind.ZodFunction,
          ...processCreateParams(params)
        });
      }
    };
    ZodLazy = class extends ZodType {
      get schema() {
        return this._def.getter();
      }
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        const lazySchema = this._def.getter();
        return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
      }
    };
    ZodLazy.create = (getter, params) => {
      return new ZodLazy({
        getter,
        typeName: ZodFirstPartyTypeKind.ZodLazy,
        ...processCreateParams(params)
      });
    };
    ZodLiteral = class extends ZodType {
      _parse(input) {
        if (input.data !== this._def.value) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            received: ctx.data,
            code: ZodIssueCode.invalid_literal,
            expected: this._def.value
          });
          return INVALID;
        }
        return { status: "valid", value: input.data };
      }
      get value() {
        return this._def.value;
      }
    };
    ZodLiteral.create = (value, params) => {
      return new ZodLiteral({
        value,
        typeName: ZodFirstPartyTypeKind.ZodLiteral,
        ...processCreateParams(params)
      });
    };
    ZodEnum = class _ZodEnum extends ZodType {
      constructor() {
        super(...arguments);
        _ZodEnum_cache.set(this, void 0);
      }
      _parse(input) {
        if (typeof input.data !== "string") {
          const ctx = this._getOrReturnCtx(input);
          const expectedValues = this._def.values;
          addIssueToContext(ctx, {
            expected: util.joinValues(expectedValues),
            received: ctx.parsedType,
            code: ZodIssueCode.invalid_type
          });
          return INVALID;
        }
        if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f")) {
          __classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), "f");
        }
        if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f").has(input.data)) {
          const ctx = this._getOrReturnCtx(input);
          const expectedValues = this._def.values;
          addIssueToContext(ctx, {
            received: ctx.data,
            code: ZodIssueCode.invalid_enum_value,
            options: expectedValues
          });
          return INVALID;
        }
        return OK(input.data);
      }
      get options() {
        return this._def.values;
      }
      get enum() {
        const enumValues = {};
        for (const val of this._def.values) {
          enumValues[val] = val;
        }
        return enumValues;
      }
      get Values() {
        const enumValues = {};
        for (const val of this._def.values) {
          enumValues[val] = val;
        }
        return enumValues;
      }
      get Enum() {
        const enumValues = {};
        for (const val of this._def.values) {
          enumValues[val] = val;
        }
        return enumValues;
      }
      extract(values, newDef = this._def) {
        return _ZodEnum.create(values, {
          ...this._def,
          ...newDef
        });
      }
      exclude(values, newDef = this._def) {
        return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
          ...this._def,
          ...newDef
        });
      }
    };
    _ZodEnum_cache = /* @__PURE__ */ new WeakMap();
    ZodEnum.create = createZodEnum;
    ZodNativeEnum = class extends ZodType {
      constructor() {
        super(...arguments);
        _ZodNativeEnum_cache.set(this, void 0);
      }
      _parse(input) {
        const nativeEnumValues = util.getValidEnumValues(this._def.values);
        const ctx = this._getOrReturnCtx(input);
        if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
          const expectedValues = util.objectValues(nativeEnumValues);
          addIssueToContext(ctx, {
            expected: util.joinValues(expectedValues),
            received: ctx.parsedType,
            code: ZodIssueCode.invalid_type
          });
          return INVALID;
        }
        if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f")) {
          __classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util.getValidEnumValues(this._def.values)), "f");
        }
        if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f").has(input.data)) {
          const expectedValues = util.objectValues(nativeEnumValues);
          addIssueToContext(ctx, {
            received: ctx.data,
            code: ZodIssueCode.invalid_enum_value,
            options: expectedValues
          });
          return INVALID;
        }
        return OK(input.data);
      }
      get enum() {
        return this._def.values;
      }
    };
    _ZodNativeEnum_cache = /* @__PURE__ */ new WeakMap();
    ZodNativeEnum.create = (values, params) => {
      return new ZodNativeEnum({
        values,
        typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
        ...processCreateParams(params)
      });
    };
    ZodPromise = class extends ZodType {
      unwrap() {
        return this._def.type;
      }
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.promise,
            received: ctx.parsedType
          });
          return INVALID;
        }
        const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
        return OK(promisified.then((data3) => {
          return this._def.type.parseAsync(data3, {
            path: ctx.path,
            errorMap: ctx.common.contextualErrorMap
          });
        }));
      }
    };
    ZodPromise.create = (schema4, params) => {
      return new ZodPromise({
        type: schema4,
        typeName: ZodFirstPartyTypeKind.ZodPromise,
        ...processCreateParams(params)
      });
    };
    ZodEffects = class extends ZodType {
      innerType() {
        return this._def.schema;
      }
      sourceType() {
        return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
      }
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        const effect = this._def.effect || null;
        const checkCtx = {
          addIssue: (arg) => {
            addIssueToContext(ctx, arg);
            if (arg.fatal) {
              status.abort();
            } else {
              status.dirty();
            }
          },
          get path() {
            return ctx.path;
          }
        };
        checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
        if (effect.type === "preprocess") {
          const processed = effect.transform(ctx.data, checkCtx);
          if (ctx.common.async) {
            return Promise.resolve(processed).then(async (processed2) => {
              if (status.value === "aborted")
                return INVALID;
              const result2 = await this._def.schema._parseAsync({
                data: processed2,
                path: ctx.path,
                parent: ctx
              });
              if (result2.status === "aborted")
                return INVALID;
              if (result2.status === "dirty")
                return DIRTY(result2.value);
              if (status.value === "dirty")
                return DIRTY(result2.value);
              return result2;
            });
          } else {
            if (status.value === "aborted")
              return INVALID;
            const result2 = this._def.schema._parseSync({
              data: processed,
              path: ctx.path,
              parent: ctx
            });
            if (result2.status === "aborted")
              return INVALID;
            if (result2.status === "dirty")
              return DIRTY(result2.value);
            if (status.value === "dirty")
              return DIRTY(result2.value);
            return result2;
          }
        }
        if (effect.type === "refinement") {
          const executeRefinement = (acc) => {
            const result2 = effect.refinement(acc, checkCtx);
            if (ctx.common.async) {
              return Promise.resolve(result2);
            }
            if (result2 instanceof Promise) {
              throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
            }
            return acc;
          };
          if (ctx.common.async === false) {
            const inner = this._def.schema._parseSync({
              data: ctx.data,
              path: ctx.path,
              parent: ctx
            });
            if (inner.status === "aborted")
              return INVALID;
            if (inner.status === "dirty")
              status.dirty();
            executeRefinement(inner.value);
            return { status: status.value, value: inner.value };
          } else {
            return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
              if (inner.status === "aborted")
                return INVALID;
              if (inner.status === "dirty")
                status.dirty();
              return executeRefinement(inner.value).then(() => {
                return { status: status.value, value: inner.value };
              });
            });
          }
        }
        if (effect.type === "transform") {
          if (ctx.common.async === false) {
            const base3 = this._def.schema._parseSync({
              data: ctx.data,
              path: ctx.path,
              parent: ctx
            });
            if (!isValid(base3))
              return base3;
            const result2 = effect.transform(base3.value, checkCtx);
            if (result2 instanceof Promise) {
              throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
            }
            return { status: status.value, value: result2 };
          } else {
            return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base3) => {
              if (!isValid(base3))
                return base3;
              return Promise.resolve(effect.transform(base3.value, checkCtx)).then((result2) => ({ status: status.value, value: result2 }));
            });
          }
        }
        util.assertNever(effect);
      }
    };
    ZodEffects.create = (schema4, effect, params) => {
      return new ZodEffects({
        schema: schema4,
        typeName: ZodFirstPartyTypeKind.ZodEffects,
        effect,
        ...processCreateParams(params)
      });
    };
    ZodEffects.createWithPreprocess = (preprocess, schema4, params) => {
      return new ZodEffects({
        schema: schema4,
        effect: { type: "preprocess", transform: preprocess },
        typeName: ZodFirstPartyTypeKind.ZodEffects,
        ...processCreateParams(params)
      });
    };
    ZodOptional = class extends ZodType {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType === ZodParsedType.undefined) {
          return OK(void 0);
        }
        return this._def.innerType._parse(input);
      }
      unwrap() {
        return this._def.innerType;
      }
    };
    ZodOptional.create = (type4, params) => {
      return new ZodOptional({
        innerType: type4,
        typeName: ZodFirstPartyTypeKind.ZodOptional,
        ...processCreateParams(params)
      });
    };
    ZodNullable = class extends ZodType {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType === ZodParsedType.null) {
          return OK(null);
        }
        return this._def.innerType._parse(input);
      }
      unwrap() {
        return this._def.innerType;
      }
    };
    ZodNullable.create = (type4, params) => {
      return new ZodNullable({
        innerType: type4,
        typeName: ZodFirstPartyTypeKind.ZodNullable,
        ...processCreateParams(params)
      });
    };
    ZodDefault = class extends ZodType {
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        let data3 = ctx.data;
        if (ctx.parsedType === ZodParsedType.undefined) {
          data3 = this._def.defaultValue();
        }
        return this._def.innerType._parse({
          data: data3,
          path: ctx.path,
          parent: ctx
        });
      }
      removeDefault() {
        return this._def.innerType;
      }
    };
    ZodDefault.create = (type4, params) => {
      return new ZodDefault({
        innerType: type4,
        typeName: ZodFirstPartyTypeKind.ZodDefault,
        defaultValue: typeof params.default === "function" ? params.default : () => params.default,
        ...processCreateParams(params)
      });
    };
    ZodCatch = class extends ZodType {
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        const newCtx = {
          ...ctx,
          common: {
            ...ctx.common,
            issues: []
          }
        };
        const result2 = this._def.innerType._parse({
          data: newCtx.data,
          path: newCtx.path,
          parent: {
            ...newCtx
          }
        });
        if (isAsync(result2)) {
          return result2.then((result3) => {
            return {
              status: "valid",
              value: result3.status === "valid" ? result3.value : this._def.catchValue({
                get error() {
                  return new ZodError(newCtx.common.issues);
                },
                input: newCtx.data
              })
            };
          });
        } else {
          return {
            status: "valid",
            value: result2.status === "valid" ? result2.value : this._def.catchValue({
              get error() {
                return new ZodError(newCtx.common.issues);
              },
              input: newCtx.data
            })
          };
        }
      }
      removeCatch() {
        return this._def.innerType;
      }
    };
    ZodCatch.create = (type4, params) => {
      return new ZodCatch({
        innerType: type4,
        typeName: ZodFirstPartyTypeKind.ZodCatch,
        catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
        ...processCreateParams(params)
      });
    };
    ZodNaN = class extends ZodType {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.nan) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.nan,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return { status: "valid", value: input.data };
      }
    };
    ZodNaN.create = (params) => {
      return new ZodNaN({
        typeName: ZodFirstPartyTypeKind.ZodNaN,
        ...processCreateParams(params)
      });
    };
    BRAND = /* @__PURE__ */ Symbol("zod_brand");
    ZodBranded = class extends ZodType {
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        const data3 = ctx.data;
        return this._def.type._parse({
          data: data3,
          path: ctx.path,
          parent: ctx
        });
      }
      unwrap() {
        return this._def.type;
      }
    };
    ZodPipeline = class _ZodPipeline extends ZodType {
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.common.async) {
          const handleAsync = async () => {
            const inResult = await this._def.in._parseAsync({
              data: ctx.data,
              path: ctx.path,
              parent: ctx
            });
            if (inResult.status === "aborted")
              return INVALID;
            if (inResult.status === "dirty") {
              status.dirty();
              return DIRTY(inResult.value);
            } else {
              return this._def.out._parseAsync({
                data: inResult.value,
                path: ctx.path,
                parent: ctx
              });
            }
          };
          return handleAsync();
        } else {
          const inResult = this._def.in._parseSync({
            data: ctx.data,
            path: ctx.path,
            parent: ctx
          });
          if (inResult.status === "aborted")
            return INVALID;
          if (inResult.status === "dirty") {
            status.dirty();
            return {
              status: "dirty",
              value: inResult.value
            };
          } else {
            return this._def.out._parseSync({
              data: inResult.value,
              path: ctx.path,
              parent: ctx
            });
          }
        }
      }
      static create(a5, b3) {
        return new _ZodPipeline({
          in: a5,
          out: b3,
          typeName: ZodFirstPartyTypeKind.ZodPipeline
        });
      }
    };
    ZodReadonly = class extends ZodType {
      _parse(input) {
        const result2 = this._def.innerType._parse(input);
        const freeze = (data3) => {
          if (isValid(data3)) {
            data3.value = Object.freeze(data3.value);
          }
          return data3;
        };
        return isAsync(result2) ? result2.then((data3) => freeze(data3)) : freeze(result2);
      }
      unwrap() {
        return this._def.innerType;
      }
    };
    ZodReadonly.create = (type4, params) => {
      return new ZodReadonly({
        innerType: type4,
        typeName: ZodFirstPartyTypeKind.ZodReadonly,
        ...processCreateParams(params)
      });
    };
    late = {
      object: ZodObject.lazycreate
    };
    (function(ZodFirstPartyTypeKind2) {
      ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
      ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
      ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
      ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
      ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
      ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
      ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
      ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
      ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
      ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
      ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
      ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
      ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
      ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
      ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
      ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
      ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
      ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
      ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
      ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
      ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
      ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
      ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
      ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
      ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
      ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
      ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
      ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
      ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
      ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
      ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
      ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
      ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
      ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
      ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
      ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
    })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
    instanceOfType = (cls, params = {
      message: `Input not instance of ${cls.name}`
    }) => custom((data3) => data3 instanceof cls, params);
    stringType = ZodString.create;
    numberType = ZodNumber.create;
    nanType = ZodNaN.create;
    bigIntType = ZodBigInt.create;
    booleanType = ZodBoolean.create;
    dateType = ZodDate.create;
    symbolType = ZodSymbol.create;
    undefinedType = ZodUndefined.create;
    nullType = ZodNull.create;
    anyType = ZodAny.create;
    unknownType = ZodUnknown.create;
    neverType = ZodNever.create;
    voidType = ZodVoid.create;
    arrayType = ZodArray.create;
    objectType = ZodObject.create;
    strictObjectType = ZodObject.strictCreate;
    unionType = ZodUnion.create;
    discriminatedUnionType = ZodDiscriminatedUnion.create;
    intersectionType = ZodIntersection.create;
    tupleType = ZodTuple.create;
    recordType = ZodRecord.create;
    mapType = ZodMap.create;
    setType = ZodSet.create;
    functionType = ZodFunction.create;
    lazyType = ZodLazy.create;
    literalType = ZodLiteral.create;
    enumType = ZodEnum.create;
    nativeEnumType = ZodNativeEnum.create;
    promiseType = ZodPromise.create;
    effectsType = ZodEffects.create;
    optionalType = ZodOptional.create;
    nullableType = ZodNullable.create;
    preprocessType = ZodEffects.createWithPreprocess;
    pipelineType = ZodPipeline.create;
    ostring = () => stringType().optional();
    onumber = () => numberType().optional();
    oboolean = () => booleanType().optional();
    coerce2 = {
      string: ((arg) => ZodString.create({ ...arg, coerce: true })),
      number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),
      boolean: ((arg) => ZodBoolean.create({
        ...arg,
        coerce: true
      })),
      bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),
      date: ((arg) => ZodDate.create({ ...arg, coerce: true }))
    };
    NEVER = INVALID;
    z3 = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      defaultErrorMap: errorMap,
      setErrorMap,
      getErrorMap,
      makeIssue,
      EMPTY_PATH,
      addIssueToContext,
      ParseStatus,
      INVALID,
      DIRTY,
      OK,
      isAborted,
      isDirty,
      isValid,
      isAsync,
      get util() {
        return util;
      },
      get objectUtil() {
        return objectUtil;
      },
      ZodParsedType,
      getParsedType,
      ZodType,
      datetimeRegex,
      ZodString,
      ZodNumber,
      ZodBigInt,
      ZodBoolean,
      ZodDate,
      ZodSymbol,
      ZodUndefined,
      ZodNull,
      ZodAny,
      ZodUnknown,
      ZodNever,
      ZodVoid,
      ZodArray,
      ZodObject,
      ZodUnion,
      ZodDiscriminatedUnion,
      ZodIntersection,
      ZodTuple,
      ZodRecord,
      ZodMap,
      ZodSet,
      ZodFunction,
      ZodLazy,
      ZodLiteral,
      ZodEnum,
      ZodNativeEnum,
      ZodPromise,
      ZodEffects,
      ZodTransformer: ZodEffects,
      ZodOptional,
      ZodNullable,
      ZodDefault,
      ZodCatch,
      ZodNaN,
      BRAND,
      ZodBranded,
      ZodPipeline,
      ZodReadonly,
      custom,
      Schema: ZodType,
      ZodSchema: ZodType,
      late,
      get ZodFirstPartyTypeKind() {
        return ZodFirstPartyTypeKind;
      },
      coerce: coerce2,
      any: anyType,
      array: arrayType,
      bigint: bigIntType,
      boolean: booleanType,
      date: dateType,
      discriminatedUnion: discriminatedUnionType,
      effect: effectsType,
      "enum": enumType,
      "function": functionType,
      "instanceof": instanceOfType,
      intersection: intersectionType,
      lazy: lazyType,
      literal: literalType,
      map: mapType,
      nan: nanType,
      nativeEnum: nativeEnumType,
      never: neverType,
      "null": nullType,
      nullable: nullableType,
      number: numberType,
      object: objectType,
      oboolean,
      onumber,
      optional: optionalType,
      ostring,
      pipeline: pipelineType,
      preprocess: preprocessType,
      promise: promiseType,
      record: recordType,
      set: setType,
      strictObject: strictObjectType,
      string: stringType,
      symbol: symbolType,
      transformer: effectsType,
      tuple: tupleType,
      "undefined": undefinedType,
      union: unionType,
      unknown: unknownType,
      "void": voidType,
      NEVER,
      ZodIssueCode,
      quotelessJson,
      ZodError
    });
  }
});

// resources/types/zod/handwritten-schema-types.ts
var Base_ZodSidebarContentsObject, ZodSidebarContentsObject, Base_ZodSidebarContents, ZodSidebarContents, Base_ZodNavigationItem, ZodNavigationItem, Base_ZodNavigationItemObject, ZodNavigationItemObject;
var init_handwritten_schema_types = __esm({
  "resources/types/zod/handwritten-schema-types.ts"() {
    init_lib();
    init_schema_types();
    Base_ZodSidebarContentsObject = z3.object({
      section: z3.union([z3.string(), z3.null()])
      /* hide the recursive declaration
      
        contents: z.lazy(() => ZodSidebarContents),
        */
    }).strict().partial();
    ZodSidebarContentsObject = Base_ZodSidebarContentsObject.extend({
      contents: z3.lazy(() => ZodSidebarContents)
    });
    Base_ZodSidebarContents = z3.union([
      z3.string(),
      z3.lazy(() => ZodContentsAuto)
      /* hide the recursive declaration
      
        z.array(z.union([
          z.lazy(() => ZodNavigationItem),
          z.string(),
          z.lazy(() => ZodSidebarContentsObject),
          z.lazy(() => ZodContentsAuto),
        ])),
        */
    ]);
    ZodSidebarContents = z3.union([
      Base_ZodSidebarContents,
      z3.array(z3.union([
        z3.lazy(() => ZodNavigationItem),
        z3.string(),
        z3.lazy(() => ZodSidebarContentsObject),
        z3.lazy(() => ZodContentsAuto)
      ]))
    ]);
    Base_ZodNavigationItem = z3.string();
    ZodNavigationItem = z3.union([
      Base_ZodNavigationItem,
      z3.lazy(() => ZodNavigationItemObject)
    ]);
    Base_ZodNavigationItemObject = z3.object({
      "aria-label": z3.string(),
      file: z3.string(),
      href: z3.string(),
      icon: z3.string(),
      id: z3.string(),
      /* hide the recursive declaration
      
        menu: z.array(z.lazy(() => ZodNavigationItem)),
        */
      text: z3.string(),
      url: z3.string(),
      rel: z3.string(),
      target: z3.string()
    }).strict().partial();
    ZodNavigationItemObject = Base_ZodNavigationItemObject.extend({
      menu: z3.array(z3.lazy(() => ZodNavigationItem))
    }).strict().partial();
  }
});

// resources/types/zod/schema-types.ts
var ZodDate2, ZodDateFormat, ZodMathMethods, ZodPandocFormatRequestHeaders, ZodPandocFormatOutputFile, ZodFilterEntryPoint, ZodPandocFormatFilters, ZodPandocShortcodes, ZodPageColumn, ZodContentsAuto, ZodGiscusThemes, ZodGiscusConfiguration, ZodExternalEngine, ZodDocumentCommentsConfiguration, ZodSocialMetadata, ZodPageFooterRegion, ZodProjectPreview, ZodProjectServe, ZodPublish, ZodPublishRecord, ZodTwitterCardConfig, ZodOpenGraphConfig, ZodPageFooter, ZodBaseWebsite, ZodBookSchema, ZodChapterItem, ZodChapterList, ZodOtherLinks, ZodCrossrefLabelsSchema, ZodEpubContributor, ZodFormatLanguage, ZodWebsiteAbout, ZodWebsiteListing, ZodWebsiteListingContentsObject, ZodCslDate, ZodCslPerson, ZodCslNumber, ZodCslItemShared, ZodCslItem, ZodCitationItem, ZodSmartInclude, ZodSemver, ZodQuartoDate, ZodProjectProfile, ZodBadParseSchema, ZodQuartoDevSchema, ZodNotebookViewSchema, ZodCodeLinksSchema, ZodManuscriptSchema, ZodBrandMeta, ZodBrandStringLightDark, ZodBrandLogoExplicitResource, ZodBrandLogoResource, ZodBrandLogoSingle, ZodBrandLogoUnified, ZodBrandNamedLogo, ZodLogoOptions, ZodLogoSpecifier, ZodLogoOptionsPathOptional, ZodLogoSpecifierPathOptional, ZodLogoLightDarkSpecifier, ZodLogoLightDarkSpecifierPathOptional, ZodNormalizedLogoLightDarkSpecifier, ZodBrandColorValue, ZodBrandColorSingle, ZodBrandColorLightDark, ZodBrandColorUnified, ZodBrandMaybeNamedColor, ZodBrandMaybeNamedColorLightDark, ZodBrandNamedThemeColor, ZodBrandTypographySingle, ZodBrandTypographyUnified, ZodBrandTypographyOptionsBase, ZodBrandTypographyOptionsHeadingsSingle, ZodBrandTypographyOptionsHeadingsUnified, ZodBrandTypographyOptionsMonospaceSingle, ZodBrandTypographyOptionsMonospaceUnified, ZodBrandTypographyOptionsMonospaceInlineSingle, ZodBrandTypographyOptionsMonospaceInlineUnified, ZodLineHeightNumberString, ZodBrandTypographyOptionsMonospaceBlockSingle, ZodBrandTypographyOptionsMonospaceBlockUnified, ZodBrandTypographyOptionsLinkSingle, ZodBrandTypographyOptionsLinkUnified, ZodBrandNamedTypographyElements, ZodBrandFont, ZodBrandFontWeight, ZodBrandFontStyle, ZodBrandFontCommon, ZodBrandFontSystem, ZodBrandFontGoogle, ZodBrandFontBunny, ZodBrandFontFile, ZodBrandFontFamily, ZodBrandSingle, ZodBrandUnified, ZodBrandPathOnlyLightDark, ZodBrandPathBoolLightDark, ZodBrandDefaults, ZodBrandDefaultsBootstrap, ZodMarginaliaSideGeometry, ZodProjectConfig, ZodBookProject, Zod;
var init_schema_types = __esm({
  "resources/types/zod/schema-types.ts"() {
    init_lib();
    init_handwritten_schema_types();
    init_handwritten_schema_types();
    ZodDate2 = z3.union([
      z3.string(),
      z3.object({ value: z3.string(), format: z3.string() }).passthrough().partial().required({ value: true })
    ]);
    ZodDateFormat = z3.string();
    ZodMathMethods = z3.enum(
      ["plain", "webtex", "gladtex", "mathml", "mathjax", "katex"]
    );
    ZodPandocFormatRequestHeaders = z3.array(z3.array(z3.string()));
    ZodPandocFormatOutputFile = z3.union([z3.string(), z3.literal(null)]);
    ZodFilterEntryPoint = z3.enum(
      [
        "pre-ast",
        "post-ast",
        "pre-quarto",
        "post-quarto",
        "pre-render",
        "post-render",
        "pre-finalize",
        "post-finalize"
      ]
    );
    ZodPandocFormatFilters = z3.array(
      z3.union([
        z3.string(),
        z3.object({ type: z3.string(), path: z3.string() }).passthrough().partial().required({ path: true }),
        z3.object({
          type: z3.string(),
          path: z3.string(),
          at: z3.lazy(() => ZodFilterEntryPoint)
        }).passthrough().partial().required({ path: true, at: true }),
        z3.object({ type: z3.enum(["citeproc"]) }).strict()
      ])
    );
    ZodPandocShortcodes = z3.array(z3.string());
    ZodPageColumn = z3.enum(
      [
        "body",
        "body-outset",
        "body-outset-left",
        "body-outset-right",
        "page",
        "page-left",
        "page-right",
        "page-inset",
        "page-inset-left",
        "page-inset-right",
        "screen",
        "screen-left",
        "screen-right",
        "screen-inset",
        "screen-inset-shaded",
        "screen-inset-left",
        "screen-inset-right",
        "margin"
      ]
    );
    ZodContentsAuto = z3.object({
      auto: z3.union([z3.boolean(), z3.union([z3.string(), z3.array(z3.string())])])
    }).passthrough().partial();
    ZodGiscusThemes = z3.enum(
      [
        "light",
        "light_high_contrast",
        "light_protanopia",
        "light_tritanopia",
        "dark",
        "dark_high_contrast",
        "dark_protanopia",
        "dark_tritanopia",
        "dark_dimmed",
        "transparent_dark",
        "cobalt",
        "purple_dark",
        "noborder_light",
        "noborder_dark",
        "noborder_gray",
        "preferred_color_scheme"
      ]
    );
    ZodGiscusConfiguration = z3.object({
      repo: z3.string(),
      "repo-id": z3.string(),
      category: z3.string(),
      "category-id": z3.string(),
      mapping: z3.union([z3.string(), z3.number()]),
      "reactions-enabled": z3.boolean(),
      loading: z3.enum(["lazy"]),
      "input-position": z3.enum(["top", "bottom"]),
      theme: z3.union([
        z3.string(),
        z3.lazy(() => ZodGiscusThemes),
        z3.object({
          light: z3.union([z3.string(), z3.lazy(() => ZodGiscusThemes)]),
          dark: z3.union([z3.string(), z3.lazy(() => ZodGiscusThemes)])
        }).strict().partial()
      ]),
      language: z3.string()
    }).strict().partial().required({ repo: true });
    ZodExternalEngine = z3.object({ path: z3.string() }).strict().partial().required({ path: true });
    ZodDocumentCommentsConfiguration = z3.union([
      z3.literal(false),
      z3.object({
        utterances: z3.object({
          repo: z3.string(),
          label: z3.string(),
          theme: z3.string(),
          "issue-term": z3.string()
        }).strict().partial().required({ repo: true }),
        giscus: z3.lazy(() => ZodGiscusConfiguration),
        hypothesis: z3.union([
          z3.boolean(),
          z3.object({
            "client-url": z3.string(),
            openSidebar: z3.boolean(),
            showHighlights: z3.union([
              z3.boolean(),
              z3.enum(["always", "whenSidebarOpen", "never"])
            ]),
            theme: z3.enum(["classic", "clean"]),
            enableExperimentalNewNoteButton: z3.boolean(),
            usernameUrl: z3.string(),
            services: z3.array(
              z3.object({
                apiUrl: z3.string(),
                authority: z3.string(),
                grantToken: z3.string(),
                allowLeavingGroups: z3.boolean(),
                enableShareLinks: z3.boolean(),
                groups: z3.union([
                  z3.enum(["$rpc:requestGroups"]),
                  z3.array(z3.string())
                ]),
                icon: z3.string()
              }).passthrough().partial().required({
                apiUrl: true,
                authority: true,
                grantToken: true
              })
            ),
            branding: z3.object({
              accentColor: z3.string(),
              appBackgroundColor: z3.string(),
              ctaBackgroundColor: z3.string(),
              selectionFontFamily: z3.string(),
              annotationFontFamily: z3.string()
            }).passthrough().partial(),
            externalContainerSelector: z3.string(),
            focus: z3.object({
              user: z3.object({
                username: z3.string(),
                userid: z3.string(),
                displayName: z3.string()
              }).passthrough().partial()
            }).passthrough().partial().required({ user: true }),
            requestConfigFromFrame: z3.object({
              origin: z3.string(),
              ancestorLevel: z3.number()
            }).passthrough().partial(),
            assetRoot: z3.string(),
            sidebarAppUrl: z3.string()
          }).strict().partial()
        ])
      }).strict().partial()
    ]);
    ZodSocialMetadata = z3.object({
      title: z3.string(),
      description: z3.string(),
      image: z3.string(),
      "image-alt": z3.string(),
      "image-width": z3.number(),
      "image-height": z3.number()
    }).strict().partial();
    ZodPageFooterRegion = z3.union([
      z3.string(),
      z3.array(z3.lazy(() => ZodNavigationItem))
    ]);
    ZodProjectPreview = z3.object({
      port: z3.number(),
      host: z3.string(),
      serve: z3.lazy(() => ZodProjectServe),
      browser: z3.boolean(),
      "watch-inputs": z3.boolean(),
      navigate: z3.boolean(),
      timeout: z3.number()
    }).strict().partial();
    ZodProjectServe = z3.object({
      cmd: z3.string(),
      args: z3.string(),
      env: z3.object({}).passthrough().partial(),
      ready: z3.string()
    }).strict().partial().required({ cmd: true, ready: true });
    ZodPublish = z3.object({
      netlify: z3.array(z3.lazy(() => ZodPublishRecord))
    }).strict().partial();
    ZodPublishRecord = z3.object({ id: z3.string(), url: z3.string() }).strict().partial();
    ZodTwitterCardConfig = z3.object({
      title: z3.string(),
      description: z3.string(),
      image: z3.string(),
      "image-alt": z3.string(),
      "image-width": z3.number(),
      "image-height": z3.number(),
      "card-style": z3.enum(["summary", "summary_large_image"]),
      creator: z3.string(),
      site: z3.string()
    }).strict().partial();
    ZodOpenGraphConfig = z3.object({
      title: z3.string(),
      description: z3.string(),
      image: z3.string(),
      "image-alt": z3.string(),
      "image-width": z3.number(),
      "image-height": z3.number(),
      locale: z3.string(),
      "site-name": z3.string()
    }).strict().partial();
    ZodPageFooter = z3.object({
      left: z3.lazy(() => ZodPageFooterRegion),
      right: z3.lazy(() => ZodPageFooterRegion),
      center: z3.lazy(() => ZodPageFooterRegion),
      border: z3.union([z3.boolean(), z3.string()]),
      background: z3.string(),
      foreground: z3.string()
    }).strict().partial();
    ZodBaseWebsite = z3.object({
      title: z3.string(),
      description: z3.string(),
      favicon: z3.string(),
      "site-url": z3.string(),
      "site-path": z3.string(),
      "repo-url": z3.string(),
      "repo-link-target": z3.string(),
      "repo-link-rel": z3.string(),
      "repo-subdir": z3.string(),
      "repo-branch": z3.string(),
      "issue-url": z3.string(),
      "repo-actions": z3.union([
        z3.enum(["none", "edit", "source", "issue"]),
        z3.array(z3.enum(["none", "edit", "source", "issue"]))
      ]),
      "reader-mode": z3.boolean(),
      "llms-txt": z3.boolean(),
      "google-analytics": z3.union([
        z3.string(),
        z3.object({
          "tracking-id": z3.string(),
          storage: z3.enum(["cookies", "none"]),
          "anonymize-ip": z3.boolean(),
          version: z3.union([z3.literal(3), z3.literal(4)])
        }).passthrough().partial()
      ]),
      "plausible-analytics": z3.union([
        z3.string(),
        z3.object({ path: z3.string() }).strict().partial().required({ path: true })
      ]),
      announcement: z3.union([
        z3.string(),
        z3.object({
          content: z3.string(),
          dismissable: z3.boolean(),
          icon: z3.string(),
          position: z3.enum(["above-navbar", "below-navbar"]),
          type: z3.enum(
            [
              "primary",
              "secondary",
              "success",
              "danger",
              "warning",
              "info",
              "light",
              "dark"
            ]
          )
        }).passthrough().partial()
      ]),
      "cookie-consent": z3.union([
        z3.enum(["express", "implied"]),
        z3.boolean(),
        z3.object({
          type: z3.enum(["express", "implied"]),
          style: z3.enum(
            ["simple", "headline", "interstitial", "standalone"]
          ),
          palette: z3.enum(["light", "dark"]),
          "policy-url": z3.string(),
          language: z3.string(),
          "prefs-text": z3.string()
        }).passthrough().partial()
      ]),
      search: z3.union([
        z3.boolean(),
        z3.object({
          location: z3.enum(["navbar", "sidebar"]),
          type: z3.enum(["overlay", "textbox"]),
          limit: z3.number(),
          "collapse-after": z3.number(),
          "copy-button": z3.boolean(),
          "merge-navbar-crumbs": z3.boolean(),
          "keyboard-shortcut": z3.union([z3.string(), z3.array(z3.string())]),
          "show-item-context": z3.union([
            z3.enum(["tree", "parent", "root"]),
            z3.boolean()
          ]),
          algolia: z3.object({
            "index-name": z3.string(),
            "application-id": z3.string(),
            "search-only-api-key": z3.string(),
            "analytics-events": z3.boolean(),
            "show-logo": z3.boolean(),
            "index-fields": z3.object({
              href: z3.string(),
              title: z3.string(),
              text: z3.string(),
              section: z3.string()
            }).strict().partial(),
            params: z3.object({}).passthrough().partial()
          }).strict().partial()
        }).strict().partial()
      ]),
      navbar: z3.union([
        z3.boolean(),
        z3.object({
          title: z3.union([z3.string(), z3.boolean()]),
          logo: z3.lazy(() => ZodLogoLightDarkSpecifier),
          "logo-alt": z3.string(),
          "logo-href": z3.string(),
          background: z3.string(),
          foreground: z3.string(),
          search: z3.boolean(),
          pinned: z3.boolean(),
          collapse: z3.boolean(),
          "collapse-below": z3.enum(["sm", "md", "lg", "xl", "xxl"]),
          left: z3.array(z3.lazy(() => ZodNavigationItem)),
          right: z3.array(z3.lazy(() => ZodNavigationItem)),
          "toggle-position": z3.enum(["left", "right"]),
          "tools-collapse": z3.boolean()
        }).passthrough().partial()
      ]),
      sidebar: z3.union([
        z3.boolean(),
        z3.union([
          z3.object({
            id: z3.string(),
            title: z3.union([z3.string(), z3.boolean()]),
            logo: z3.lazy(() => ZodLogoLightDarkSpecifier),
            "logo-alt": z3.string(),
            "logo-href": z3.string(),
            search: z3.boolean(),
            tools: z3.array(z3.lazy(() => ZodNavigationItemObject)),
            contents: z3.lazy(() => ZodSidebarContents),
            style: z3.enum(["docked", "floating"]),
            background: z3.string(),
            foreground: z3.string(),
            border: z3.boolean(),
            alignment: z3.enum(["left", "right", "center"]),
            "collapse-level": z3.number(),
            pinned: z3.boolean(),
            header: z3.union([z3.string(), z3.array(z3.string())]),
            footer: z3.union([z3.string(), z3.array(z3.string())])
          }).passthrough().partial(),
          z3.array(
            z3.object({
              id: z3.string(),
              title: z3.union([z3.string(), z3.boolean()]),
              logo: z3.lazy(() => ZodLogoLightDarkSpecifier),
              "logo-alt": z3.string(),
              "logo-href": z3.string(),
              search: z3.boolean(),
              tools: z3.array(z3.lazy(() => ZodNavigationItemObject)),
              contents: z3.lazy(() => ZodSidebarContents),
              style: z3.enum(["docked", "floating"]),
              background: z3.string(),
              foreground: z3.string(),
              border: z3.boolean(),
              alignment: z3.enum(["left", "right", "center"]),
              "collapse-level": z3.number(),
              pinned: z3.boolean(),
              header: z3.union([z3.string(), z3.array(z3.string())]),
              footer: z3.union([z3.string(), z3.array(z3.string())])
            }).passthrough().partial()
          )
        ])
      ]),
      "body-header": z3.string(),
      "body-footer": z3.string(),
      "margin-header": z3.union([z3.string(), z3.array(z3.string())]),
      "margin-footer": z3.union([z3.string(), z3.array(z3.string())]),
      "page-navigation": z3.boolean(),
      "back-to-top-navigation": z3.boolean(),
      "bread-crumbs": z3.boolean(),
      "page-footer": z3.union([z3.string(), z3.lazy(() => ZodPageFooter)]),
      image: z3.string(),
      "image-alt": z3.string(),
      comments: z3.lazy(() => ZodDocumentCommentsConfiguration),
      "open-graph": z3.union([z3.boolean(), z3.lazy(() => ZodOpenGraphConfig)]),
      "twitter-card": z3.union([z3.boolean(), z3.lazy(() => ZodTwitterCardConfig)]),
      "other-links": z3.lazy(() => ZodOtherLinks),
      "code-links": z3.union([z3.boolean(), z3.lazy(() => ZodCodeLinksSchema)]),
      drafts: z3.union([z3.string(), z3.array(z3.string())]),
      "draft-mode": z3.enum(["visible", "unlinked", "gone"])
    }).strict().partial();
    ZodBookSchema = z3.object({
      title: z3.string(),
      description: z3.string(),
      favicon: z3.string(),
      "site-url": z3.string(),
      "site-path": z3.string(),
      "repo-url": z3.string(),
      "repo-link-target": z3.string(),
      "repo-link-rel": z3.string(),
      "repo-subdir": z3.string(),
      "repo-branch": z3.string(),
      "issue-url": z3.string(),
      "repo-actions": z3.union([
        z3.enum(["none", "edit", "source", "issue"]),
        z3.array(z3.enum(["none", "edit", "source", "issue"]))
      ]),
      "reader-mode": z3.boolean(),
      "llms-txt": z3.boolean(),
      "google-analytics": z3.union([
        z3.string(),
        z3.object({
          "tracking-id": z3.string(),
          storage: z3.enum(["cookies", "none"]),
          "anonymize-ip": z3.boolean(),
          version: z3.union([z3.literal(3), z3.literal(4)])
        }).passthrough().partial()
      ]),
      "plausible-analytics": z3.union([
        z3.string(),
        z3.object({ path: z3.string() }).strict().partial().required({ path: true })
      ]),
      announcement: z3.union([
        z3.string(),
        z3.object({
          content: z3.string(),
          dismissable: z3.boolean(),
          icon: z3.string(),
          position: z3.enum(["above-navbar", "below-navbar"]),
          type: z3.enum(
            [
              "primary",
              "secondary",
              "success",
              "danger",
              "warning",
              "info",
              "light",
              "dark"
            ]
          )
        }).passthrough().partial()
      ]),
      "cookie-consent": z3.union([
        z3.enum(["express", "implied"]),
        z3.boolean(),
        z3.object({
          type: z3.enum(["express", "implied"]),
          style: z3.enum(
            ["simple", "headline", "interstitial", "standalone"]
          ),
          palette: z3.enum(["light", "dark"]),
          "policy-url": z3.string(),
          language: z3.string(),
          "prefs-text": z3.string()
        }).passthrough().partial()
      ]),
      search: z3.union([
        z3.boolean(),
        z3.object({
          location: z3.enum(["navbar", "sidebar"]),
          type: z3.enum(["overlay", "textbox"]),
          limit: z3.number(),
          "collapse-after": z3.number(),
          "copy-button": z3.boolean(),
          "merge-navbar-crumbs": z3.boolean(),
          "keyboard-shortcut": z3.union([z3.string(), z3.array(z3.string())]),
          "show-item-context": z3.union([
            z3.enum(["tree", "parent", "root"]),
            z3.boolean()
          ]),
          algolia: z3.object({
            "index-name": z3.string(),
            "application-id": z3.string(),
            "search-only-api-key": z3.string(),
            "analytics-events": z3.boolean(),
            "show-logo": z3.boolean(),
            "index-fields": z3.object({
              href: z3.string(),
              title: z3.string(),
              text: z3.string(),
              section: z3.string()
            }).strict().partial(),
            params: z3.object({}).passthrough().partial()
          }).strict().partial()
        }).strict().partial()
      ]),
      navbar: z3.union([
        z3.boolean(),
        z3.object({
          title: z3.union([z3.string(), z3.boolean()]),
          logo: z3.lazy(() => ZodLogoLightDarkSpecifier),
          "logo-alt": z3.string(),
          "logo-href": z3.string(),
          background: z3.string(),
          foreground: z3.string(),
          search: z3.boolean(),
          pinned: z3.boolean(),
          collapse: z3.boolean(),
          "collapse-below": z3.enum(["sm", "md", "lg", "xl", "xxl"]),
          left: z3.array(z3.lazy(() => ZodNavigationItem)),
          right: z3.array(z3.lazy(() => ZodNavigationItem)),
          "toggle-position": z3.enum(["left", "right"]),
          "tools-collapse": z3.boolean()
        }).passthrough().partial()
      ]),
      sidebar: z3.union([
        z3.boolean(),
        z3.union([
          z3.object({
            id: z3.string(),
            title: z3.union([z3.string(), z3.boolean()]),
            logo: z3.lazy(() => ZodLogoLightDarkSpecifier),
            "logo-alt": z3.string(),
            "logo-href": z3.string(),
            search: z3.boolean(),
            tools: z3.array(z3.lazy(() => ZodNavigationItemObject)),
            contents: z3.lazy(() => ZodSidebarContents),
            style: z3.enum(["docked", "floating"]),
            background: z3.string(),
            foreground: z3.string(),
            border: z3.boolean(),
            alignment: z3.enum(["left", "right", "center"]),
            "collapse-level": z3.number(),
            pinned: z3.boolean(),
            header: z3.union([z3.string(), z3.array(z3.string())]),
            footer: z3.union([z3.string(), z3.array(z3.string())])
          }).passthrough().partial(),
          z3.array(
            z3.object({
              id: z3.string(),
              title: z3.union([z3.string(), z3.boolean()]),
              logo: z3.lazy(() => ZodLogoLightDarkSpecifier),
              "logo-alt": z3.string(),
              "logo-href": z3.string(),
              search: z3.boolean(),
              tools: z3.array(z3.lazy(() => ZodNavigationItemObject)),
              contents: z3.lazy(() => ZodSidebarContents),
              style: z3.enum(["docked", "floating"]),
              background: z3.string(),
              foreground: z3.string(),
              border: z3.boolean(),
              alignment: z3.enum(["left", "right", "center"]),
              "collapse-level": z3.number(),
              pinned: z3.boolean(),
              header: z3.union([z3.string(), z3.array(z3.string())]),
              footer: z3.union([z3.string(), z3.array(z3.string())])
            }).passthrough().partial()
          )
        ])
      ]),
      "body-header": z3.string(),
      "body-footer": z3.string(),
      "margin-header": z3.union([z3.string(), z3.array(z3.string())]),
      "margin-footer": z3.union([z3.string(), z3.array(z3.string())]),
      "page-navigation": z3.boolean(),
      "back-to-top-navigation": z3.boolean(),
      "bread-crumbs": z3.boolean(),
      "page-footer": z3.union([z3.string(), z3.lazy(() => ZodPageFooter)]),
      image: z3.string(),
      "image-alt": z3.string(),
      comments: z3.lazy(() => ZodDocumentCommentsConfiguration),
      "open-graph": z3.union([z3.boolean(), z3.lazy(() => ZodOpenGraphConfig)]),
      "twitter-card": z3.union([z3.boolean(), z3.lazy(() => ZodTwitterCardConfig)]),
      "other-links": z3.lazy(() => ZodOtherLinks),
      "code-links": z3.union([z3.boolean(), z3.lazy(() => ZodCodeLinksSchema)]),
      drafts: z3.union([z3.string(), z3.array(z3.string())]),
      "draft-mode": z3.enum(["visible", "unlinked", "gone"]),
      subtitle: z3.string(),
      author: z3.union([
        z3.union([z3.string(), z3.object({}).passthrough()]),
        z3.array(z3.union([z3.string(), z3.object({}).passthrough()]))
      ]),
      date: z3.string(),
      "date-format": z3.string(),
      abstract: z3.string(),
      chapters: z3.lazy(() => ZodChapterList),
      appendices: z3.lazy(() => ZodChapterList),
      references: z3.string(),
      "output-file": z3.string(),
      "cover-image": z3.string(),
      "cover-image-alt": z3.string(),
      sharing: z3.union([
        z3.enum(["twitter", "facebook", "linkedin"]),
        z3.array(z3.enum(["twitter", "facebook", "linkedin"]))
      ]),
      downloads: z3.union([
        z3.enum(["pdf", "epub", "docx"]),
        z3.array(z3.enum(["pdf", "epub", "docx"]))
      ]),
      tools: z3.array(z3.lazy(() => ZodNavigationItem)),
      doi: z3.string()
    }).strict().partial();
    ZodChapterItem = z3.union([
      z3.lazy(() => ZodNavigationItem),
      z3.object({
        part: z3.string(),
        chapters: z3.array(z3.lazy(() => ZodNavigationItem))
      }).passthrough().partial().required({ part: true })
    ]);
    ZodChapterList = z3.array(z3.lazy(() => ZodChapterItem));
    ZodOtherLinks = z3.array(
      z3.object({
        text: z3.string(),
        href: z3.string(),
        icon: z3.string(),
        rel: z3.string(),
        target: z3.string()
      }).passthrough().partial().required({ text: true, href: true })
    );
    ZodCrossrefLabelsSchema = z3.string();
    ZodEpubContributor = z3.union([
      z3.string(),
      z3.union([
        z3.object({ role: z3.string(), "file-as": z3.string(), text: z3.string() }).strict().partial(),
        z3.array(
          z3.object({ role: z3.string(), "file-as": z3.string(), text: z3.string() }).strict().partial()
        )
      ])
    ]);
    ZodFormatLanguage = z3.object({
      "toc-title-document": z3.string(),
      "toc-title-website": z3.string(),
      "related-formats-title": z3.string(),
      "related-notebooks-title": z3.string(),
      "callout-tip-title": z3.string(),
      "callout-note-title": z3.string(),
      "callout-warning-title": z3.string(),
      "callout-important-title": z3.string(),
      "callout-caution-title": z3.string(),
      "section-title-abstract": z3.string(),
      "section-title-footnotes": z3.string(),
      "section-title-appendices": z3.string(),
      "code-summary": z3.string(),
      "code-tools-menu-caption": z3.string(),
      "code-tools-show-all-code": z3.string(),
      "code-tools-hide-all-code": z3.string(),
      "code-tools-view-source": z3.string(),
      "code-tools-source-code": z3.string(),
      "search-no-results-text": z3.string(),
      "copy-button-tooltip": z3.string(),
      "copy-button-tooltip-success": z3.string(),
      "repo-action-links-edit": z3.string(),
      "repo-action-links-source": z3.string(),
      "repo-action-links-issue": z3.string(),
      "search-matching-documents-text": z3.string(),
      "search-copy-link-title": z3.string(),
      "search-hide-matches-text": z3.string(),
      "search-more-match-text": z3.string(),
      "search-more-matches-text": z3.string(),
      "search-clear-button-title": z3.string(),
      "search-text-placeholder": z3.string(),
      "search-detached-cancel-button-title": z3.string(),
      "search-submit-button-title": z3.string(),
      "crossref-fig-title": z3.string(),
      "crossref-tbl-title": z3.string(),
      "crossref-lst-title": z3.string(),
      "crossref-thm-title": z3.string(),
      "crossref-lem-title": z3.string(),
      "crossref-cor-title": z3.string(),
      "crossref-prp-title": z3.string(),
      "crossref-cnj-title": z3.string(),
      "crossref-def-title": z3.string(),
      "crossref-exm-title": z3.string(),
      "crossref-exr-title": z3.string(),
      "crossref-fig-prefix": z3.string(),
      "crossref-tbl-prefix": z3.string(),
      "crossref-lst-prefix": z3.string(),
      "crossref-ch-prefix": z3.string(),
      "crossref-apx-prefix": z3.string(),
      "crossref-sec-prefix": z3.string(),
      "crossref-eq-prefix": z3.string(),
      "crossref-thm-prefix": z3.string(),
      "crossref-lem-prefix": z3.string(),
      "crossref-cor-prefix": z3.string(),
      "crossref-prp-prefix": z3.string(),
      "crossref-cnj-prefix": z3.string(),
      "crossref-def-prefix": z3.string(),
      "crossref-exm-prefix": z3.string(),
      "crossref-exr-prefix": z3.string(),
      "crossref-lof-title": z3.string(),
      "crossref-lot-title": z3.string(),
      "crossref-lol-title": z3.string()
    }).passthrough().partial();
    ZodWebsiteAbout = z3.object({
      id: z3.string(),
      template: z3.union([
        z3.enum(["jolla", "trestles", "solana", "marquee", "broadside"]),
        z3.string()
      ]),
      image: z3.string(),
      "image-alt": z3.string(),
      "image-title": z3.string(),
      "image-width": z3.string(),
      "image-shape": z3.enum(["rectangle", "round", "rounded"]),
      links: z3.array(z3.lazy(() => ZodNavigationItem))
    }).strict().partial().required({ template: true });
    ZodWebsiteListing = z3.object({
      id: z3.string(),
      type: z3.enum(["default", "table", "grid", "custom"]),
      contents: z3.union([
        z3.union([z3.string(), z3.lazy(() => ZodWebsiteListingContentsObject)]),
        z3.array(
          z3.union([z3.string(), z3.lazy(() => ZodWebsiteListingContentsObject)])
        )
      ]),
      sort: z3.union([z3.boolean(), z3.union([z3.string(), z3.array(z3.string())])]),
      "max-items": z3.number(),
      "page-size": z3.number(),
      "sort-ui": z3.union([z3.boolean(), z3.array(z3.string())]),
      "filter-ui": z3.union([z3.boolean(), z3.array(z3.string())]),
      categories: z3.union([
        z3.boolean(),
        z3.enum(["numbered", "unnumbered", "cloud"])
      ]),
      feed: z3.union([
        z3.boolean(),
        z3.object({
          items: z3.number(),
          type: z3.enum(["full", "partial", "metadata"]),
          title: z3.string(),
          image: z3.string(),
          description: z3.string(),
          language: z3.string(),
          categories: z3.union([z3.string(), z3.array(z3.string())]),
          "xml-stylesheet": z3.string()
        }).strict().partial()
      ]),
      "date-format": z3.string(),
      "max-description-length": z3.number(),
      "image-placeholder": z3.string(),
      "image-lazy-loading": z3.boolean(),
      "image-align": z3.enum(["left", "right"]),
      "image-height": z3.string(),
      "grid-columns": z3.number(),
      "grid-item-border": z3.boolean(),
      "grid-item-align": z3.enum(["left", "right", "center"]),
      "table-striped": z3.boolean(),
      "table-hover": z3.boolean(),
      template: z3.string(),
      "template-params": z3.object({}).passthrough(),
      fields: z3.array(z3.string()),
      "field-display-names": z3.object({}).passthrough().partial(),
      "field-types": z3.object({}).passthrough().partial(),
      "field-links": z3.array(z3.string()),
      "field-required": z3.array(z3.string()),
      include: z3.union([
        z3.object({}).passthrough(),
        z3.array(z3.object({}).passthrough())
      ]),
      exclude: z3.union([
        z3.object({}).passthrough(),
        z3.array(z3.object({}).passthrough())
      ])
    }).strict().partial();
    ZodWebsiteListingContentsObject = z3.object({
      author: z3.union([z3.string(), z3.array(z3.string())]),
      date: z3.string(),
      title: z3.string(),
      subtitle: z3.string()
    }).passthrough().partial();
    ZodCslDate = z3.union([
      z3.string(),
      z3.union([z3.number(), z3.array(z3.number())]),
      z3.object({ year: z3.number(), month: z3.number(), day: z3.number() }).passthrough().partial()
    ]);
    ZodCslPerson = z3.union([
      z3.union([z3.string(), z3.array(z3.string())]),
      z3.union([
        z3.object({ "family-name": z3.string(), "given-name": z3.string() }).passthrough().partial(),
        z3.array(
          z3.object({ "family-name": z3.string(), "given-name": z3.string() }).passthrough().partial()
        )
      ])
    ]);
    ZodCslNumber = z3.union([z3.number(), z3.string()]);
    ZodCslItemShared = z3.object({
      "abstract-url": z3.string(),
      accessed: z3.lazy(() => ZodCslDate),
      annote: z3.string(),
      archive: z3.string(),
      "archive-collection": z3.string(),
      archive_collection: z3.string(),
      "archive-location": z3.string(),
      archive_location: z3.string(),
      "archive-place": z3.string(),
      authority: z3.string(),
      "available-date": z3.lazy(() => ZodCslDate),
      "call-number": z3.string(),
      chair: z3.lazy(() => ZodCslPerson),
      "chapter-number": z3.lazy(() => ZodCslNumber),
      "citation-key": z3.string(),
      "citation-label": z3.string(),
      "citation-number": z3.lazy(() => ZodCslNumber),
      "collection-editor": z3.lazy(() => ZodCslPerson),
      "collection-number": z3.lazy(() => ZodCslNumber),
      "collection-title": z3.string(),
      compiler: z3.lazy(() => ZodCslPerson),
      composer: z3.lazy(() => ZodCslPerson),
      "container-author": z3.lazy(() => ZodCslPerson),
      "container-title": z3.string(),
      "container-title-short": z3.string(),
      contributor: z3.lazy(() => ZodCslPerson),
      curator: z3.lazy(() => ZodCslPerson),
      dimensions: z3.string(),
      director: z3.lazy(() => ZodCslPerson),
      division: z3.string(),
      DOI: z3.string(),
      edition: z3.lazy(() => ZodCslNumber),
      editor: z3.lazy(() => ZodCslPerson),
      "editorial-director": z3.lazy(() => ZodCslPerson),
      "editor-translator": z3.lazy(() => ZodCslPerson),
      event: z3.string(),
      "event-date": z3.lazy(() => ZodCslDate),
      "event-title": z3.string(),
      "event-place": z3.string(),
      "executive-producer": z3.lazy(() => ZodCslPerson),
      "first-reference-note-number": z3.lazy(() => ZodCslNumber),
      "fulltext-url": z3.string(),
      genre: z3.string(),
      guest: z3.lazy(() => ZodCslPerson),
      host: z3.lazy(() => ZodCslPerson),
      id: z3.union([z3.string(), z3.number()]),
      illustrator: z3.lazy(() => ZodCslPerson),
      interviewer: z3.lazy(() => ZodCslPerson),
      isbn: z3.string(),
      ISBN: z3.string(),
      issn: z3.string(),
      ISSN: z3.string(),
      issue: z3.lazy(() => ZodCslNumber),
      issued: z3.lazy(() => ZodCslDate),
      jurisdiction: z3.string(),
      keyword: z3.string(),
      language: z3.string(),
      license: z3.string(),
      locator: z3.lazy(() => ZodCslNumber),
      medium: z3.string(),
      narrator: z3.lazy(() => ZodCslPerson),
      note: z3.string(),
      number: z3.lazy(() => ZodCslNumber),
      "number-of-pages": z3.lazy(() => ZodCslNumber),
      "number-of-volumes": z3.lazy(() => ZodCslNumber),
      organizer: z3.lazy(() => ZodCslPerson),
      "original-author": z3.lazy(() => ZodCslPerson),
      "original-date": z3.lazy(() => ZodCslDate),
      "original-publisher": z3.string(),
      "original-publisher-place": z3.string(),
      "original-title": z3.string(),
      page: z3.lazy(() => ZodCslNumber),
      "page-first": z3.lazy(() => ZodCslNumber),
      "page-last": z3.lazy(() => ZodCslNumber),
      "part-number": z3.lazy(() => ZodCslNumber),
      "part-title": z3.string(),
      "pdf-url": z3.string(),
      performer: z3.lazy(() => ZodCslPerson),
      pmcid: z3.string(),
      PMCID: z3.string(),
      pmid: z3.string(),
      PMID: z3.string(),
      "printing-number": z3.lazy(() => ZodCslNumber),
      producer: z3.lazy(() => ZodCslPerson),
      "public-url": z3.string(),
      publisher: z3.string(),
      "publisher-place": z3.string(),
      recipient: z3.lazy(() => ZodCslPerson),
      "reviewed-author": z3.lazy(() => ZodCslPerson),
      "reviewed-genre": z3.string(),
      "reviewed-title": z3.string(),
      scale: z3.string(),
      "script-writer": z3.lazy(() => ZodCslPerson),
      section: z3.lazy(() => ZodCslNumber),
      "series-creator": z3.lazy(() => ZodCslPerson),
      source: z3.string(),
      status: z3.string(),
      submitted: z3.lazy(() => ZodCslDate),
      "supplement-number": z3.lazy(() => ZodCslNumber),
      "title-short": z3.string(),
      translator: z3.lazy(() => ZodCslPerson),
      type: z3.enum(
        [
          "article",
          "article-journal",
          "article-magazine",
          "article-newspaper",
          "bill",
          "book",
          "broadcast",
          "chapter",
          "classic",
          "collection",
          "dataset",
          "document",
          "entry",
          "entry-dictionary",
          "entry-encyclopedia",
          "event",
          "figure",
          "graphic",
          "hearing",
          "interview",
          "legal_case",
          "legislation",
          "manuscript",
          "map",
          "motion_picture",
          "musical_score",
          "pamphlet",
          "paper-conference",
          "patent",
          "performance",
          "periodical",
          "personal_communication",
          "post",
          "post-weblog",
          "regulation",
          "report",
          "review",
          "review-book",
          "software",
          "song",
          "speech",
          "standard",
          "thesis",
          "treaty",
          "webpage"
        ]
      ),
      url: z3.string(),
      URL: z3.string(),
      version: z3.lazy(() => ZodCslNumber),
      volume: z3.lazy(() => ZodCslNumber),
      "volume-title": z3.string(),
      "year-suffix": z3.string()
    }).passthrough().partial();
    ZodCslItem = z3.object({
      "abstract-url": z3.string(),
      accessed: z3.lazy(() => ZodCslDate),
      annote: z3.string(),
      archive: z3.string(),
      "archive-collection": z3.string(),
      archive_collection: z3.string(),
      "archive-location": z3.string(),
      archive_location: z3.string(),
      "archive-place": z3.string(),
      authority: z3.string(),
      "available-date": z3.lazy(() => ZodCslDate),
      "call-number": z3.string(),
      chair: z3.lazy(() => ZodCslPerson),
      "chapter-number": z3.lazy(() => ZodCslNumber),
      "citation-key": z3.string(),
      "citation-label": z3.string(),
      "citation-number": z3.lazy(() => ZodCslNumber),
      "collection-editor": z3.lazy(() => ZodCslPerson),
      "collection-number": z3.lazy(() => ZodCslNumber),
      "collection-title": z3.string(),
      compiler: z3.lazy(() => ZodCslPerson),
      composer: z3.lazy(() => ZodCslPerson),
      "container-author": z3.lazy(() => ZodCslPerson),
      "container-title": z3.string(),
      "container-title-short": z3.string(),
      contributor: z3.lazy(() => ZodCslPerson),
      curator: z3.lazy(() => ZodCslPerson),
      dimensions: z3.string(),
      director: z3.lazy(() => ZodCslPerson),
      division: z3.string(),
      DOI: z3.string(),
      edition: z3.lazy(() => ZodCslNumber),
      editor: z3.lazy(() => ZodCslPerson),
      "editorial-director": z3.lazy(() => ZodCslPerson),
      "editor-translator": z3.lazy(() => ZodCslPerson),
      event: z3.string(),
      "event-date": z3.lazy(() => ZodCslDate),
      "event-title": z3.string(),
      "event-place": z3.string(),
      "executive-producer": z3.lazy(() => ZodCslPerson),
      "first-reference-note-number": z3.lazy(() => ZodCslNumber),
      "fulltext-url": z3.string(),
      genre: z3.string(),
      guest: z3.lazy(() => ZodCslPerson),
      host: z3.lazy(() => ZodCslPerson),
      id: z3.union([z3.string(), z3.number()]),
      illustrator: z3.lazy(() => ZodCslPerson),
      interviewer: z3.lazy(() => ZodCslPerson),
      isbn: z3.string(),
      ISBN: z3.string(),
      issn: z3.string(),
      ISSN: z3.string(),
      issue: z3.lazy(() => ZodCslNumber),
      issued: z3.lazy(() => ZodCslDate),
      jurisdiction: z3.string(),
      keyword: z3.string(),
      language: z3.string(),
      license: z3.string(),
      locator: z3.lazy(() => ZodCslNumber),
      medium: z3.string(),
      narrator: z3.lazy(() => ZodCslPerson),
      note: z3.string(),
      number: z3.lazy(() => ZodCslNumber),
      "number-of-pages": z3.lazy(() => ZodCslNumber),
      "number-of-volumes": z3.lazy(() => ZodCslNumber),
      organizer: z3.lazy(() => ZodCslPerson),
      "original-author": z3.lazy(() => ZodCslPerson),
      "original-date": z3.lazy(() => ZodCslDate),
      "original-publisher": z3.string(),
      "original-publisher-place": z3.string(),
      "original-title": z3.string(),
      page: z3.lazy(() => ZodCslNumber),
      "page-first": z3.lazy(() => ZodCslNumber),
      "page-last": z3.lazy(() => ZodCslNumber),
      "part-number": z3.lazy(() => ZodCslNumber),
      "part-title": z3.string(),
      "pdf-url": z3.string(),
      performer: z3.lazy(() => ZodCslPerson),
      pmcid: z3.string(),
      PMCID: z3.string(),
      pmid: z3.string(),
      PMID: z3.string(),
      "printing-number": z3.lazy(() => ZodCslNumber),
      producer: z3.lazy(() => ZodCslPerson),
      "public-url": z3.string(),
      publisher: z3.string(),
      "publisher-place": z3.string(),
      recipient: z3.lazy(() => ZodCslPerson),
      "reviewed-author": z3.lazy(() => ZodCslPerson),
      "reviewed-genre": z3.string(),
      "reviewed-title": z3.string(),
      scale: z3.string(),
      "script-writer": z3.lazy(() => ZodCslPerson),
      section: z3.lazy(() => ZodCslNumber),
      "series-creator": z3.lazy(() => ZodCslPerson),
      source: z3.string(),
      status: z3.string(),
      submitted: z3.lazy(() => ZodCslDate),
      "supplement-number": z3.lazy(() => ZodCslNumber),
      "title-short": z3.string(),
      translator: z3.lazy(() => ZodCslPerson),
      type: z3.enum(
        [
          "article",
          "article-journal",
          "article-magazine",
          "article-newspaper",
          "bill",
          "book",
          "broadcast",
          "chapter",
          "classic",
          "collection",
          "dataset",
          "document",
          "entry",
          "entry-dictionary",
          "entry-encyclopedia",
          "event",
          "figure",
          "graphic",
          "hearing",
          "interview",
          "legal_case",
          "legislation",
          "manuscript",
          "map",
          "motion_picture",
          "musical_score",
          "pamphlet",
          "paper-conference",
          "patent",
          "performance",
          "periodical",
          "personal_communication",
          "post",
          "post-weblog",
          "regulation",
          "report",
          "review",
          "review-book",
          "software",
          "song",
          "speech",
          "standard",
          "thesis",
          "treaty",
          "webpage"
        ]
      ),
      url: z3.string(),
      URL: z3.string(),
      version: z3.lazy(() => ZodCslNumber),
      volume: z3.lazy(() => ZodCslNumber),
      "volume-title": z3.string(),
      "year-suffix": z3.string(),
      abstract: z3.string(),
      author: z3.lazy(() => ZodCslPerson),
      doi: z3.string(),
      references: z3.string(),
      title: z3.string()
    }).strict().partial();
    ZodCitationItem = z3.object({
      abstract: z3.string(),
      author: z3.lazy(() => ZodCslPerson),
      doi: z3.string(),
      references: z3.string(),
      title: z3.string(),
      id: z3.union([z3.string(), z3.number()]),
      "article-id": z3.union([
        z3.union([
          z3.string(),
          z3.object({ type: z3.string(), value: z3.string() }).passthrough().partial()
        ]),
        z3.array(
          z3.union([
            z3.string(),
            z3.object({ type: z3.string(), value: z3.string() }).passthrough().partial()
          ])
        )
      ]),
      "elocation-id": z3.string(),
      eissn: z3.string(),
      pissn: z3.string(),
      "art-access-id": z3.string(),
      "publisher-location": z3.string(),
      subject: z3.string(),
      categories: z3.union([z3.string(), z3.array(z3.string())]),
      "container-id": z3.union([
        z3.union([
          z3.string(),
          z3.object({ type: z3.string(), value: z3.string() }).passthrough().partial()
        ]),
        z3.array(
          z3.union([
            z3.string(),
            z3.object({ type: z3.string(), value: z3.string() }).passthrough().partial()
          ])
        )
      ]),
      "jats-type": z3.string()
    }).strict().partial();
    ZodSmartInclude = z3.union([
      z3.object({ text: z3.string() }).strict(),
      z3.object({ file: z3.string() }).strict()
    ]);
    ZodSemver = z3.string().regex(
      new RegExp(
        "^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$"
      )
    );
    ZodQuartoDate = z3.union([
      z3.string(),
      z3.object({ format: z3.string(), value: z3.string() }).strict().partial().required({ value: true })
    ]);
    ZodProjectProfile = z3.object({
      default: z3.union([z3.string(), z3.array(z3.string())]),
      group: z3.union([z3.array(z3.string()), z3.array(z3.array(z3.string()))])
    }).strict().partial();
    ZodBadParseSchema = z3.object({}).passthrough().partial();
    ZodQuartoDevSchema = z3.object({
      _quarto: z3.object({
        "trace-filters": z3.string(),
        tests: z3.object({
          run: z3.object({
            ci: z3.boolean(),
            skip: z3.union([z3.boolean(), z3.string()]),
            os: z3.union([
              z3.enum(["linux", "darwin", "windows"]),
              z3.array(z3.enum(["linux", "darwin", "windows"]))
            ]),
            not_os: z3.union([
              z3.enum(["linux", "darwin", "windows"]),
              z3.array(z3.enum(["linux", "darwin", "windows"]))
            ])
          }).passthrough().partial()
        }).passthrough().partial()
      }).passthrough().partial()
    }).passthrough().partial();
    ZodNotebookViewSchema = z3.object({
      notebook: z3.string(),
      title: z3.union([z3.string(), z3.boolean()]),
      url: z3.string(),
      "download-url": z3.string()
    }).passthrough().partial().required({ notebook: true });
    ZodCodeLinksSchema = z3.union([
      z3.boolean(),
      z3.union([
        z3.union([
          z3.object({
            icon: z3.string(),
            text: z3.string(),
            href: z3.string(),
            rel: z3.string(),
            target: z3.string()
          }).passthrough().partial(),
          z3.enum(["repo", "binder", "devcontainer"])
        ]),
        z3.array(
          z3.union([
            z3.object({
              icon: z3.string(),
              text: z3.string(),
              href: z3.string(),
              rel: z3.string(),
              target: z3.string()
            }).passthrough().partial(),
            z3.enum(["repo", "binder", "devcontainer"])
          ])
        )
      ])
    ]);
    ZodManuscriptSchema = z3.object({
      article: z3.string(),
      "code-links": z3.lazy(() => ZodCodeLinksSchema),
      "manuscript-url": z3.string(),
      "meca-bundle": z3.union([z3.boolean(), z3.string()]),
      notebooks: z3.array(
        z3.union([z3.string(), z3.lazy(() => ZodNotebookViewSchema)])
      ),
      resources: z3.union([z3.string(), z3.array(z3.string())]),
      environment: z3.union([z3.string(), z3.array(z3.string())])
    }).strict().partial();
    ZodBrandMeta = z3.object({
      name: z3.union([
        z3.string(),
        z3.object({ full: z3.string(), short: z3.string() }).passthrough().partial()
      ]),
      link: z3.union([
        z3.string(),
        z3.object({
          home: z3.string(),
          mastodon: z3.string(),
          bluesky: z3.string(),
          github: z3.string(),
          linkedin: z3.string(),
          twitter: z3.string(),
          facebook: z3.string()
        }).passthrough().partial()
      ])
    }).passthrough().partial();
    ZodBrandStringLightDark = z3.union([
      z3.string(),
      z3.object({ light: z3.string(), dark: z3.string() }).strict().partial()
    ]);
    ZodBrandLogoExplicitResource = z3.object({
      path: z3.string(),
      alt: z3.string()
    }).strict().partial().required({ path: true });
    ZodBrandLogoResource = z3.union([
      z3.string(),
      z3.lazy(() => ZodBrandLogoExplicitResource)
    ]);
    ZodBrandLogoSingle = z3.object({
      images: z3.record(z3.lazy(() => ZodBrandLogoResource)).and(
        z3.object({}).passthrough().partial()
      ),
      small: z3.string(),
      medium: z3.string(),
      large: z3.string()
    }).strict().partial();
    ZodBrandLogoUnified = z3.object({
      images: z3.record(z3.lazy(() => ZodBrandLogoResource)).and(
        z3.object({}).passthrough().partial()
      ),
      small: z3.lazy(() => ZodBrandStringLightDark),
      medium: z3.lazy(() => ZodBrandStringLightDark),
      large: z3.lazy(() => ZodBrandStringLightDark)
    }).strict().partial();
    ZodBrandNamedLogo = z3.enum(["small", "medium", "large"]);
    ZodLogoOptions = z3.object({ path: z3.string(), alt: z3.string() }).passthrough().partial().required({ path: true });
    ZodLogoSpecifier = z3.union([
      z3.string(),
      z3.lazy(() => ZodLogoOptions)
    ]);
    ZodLogoOptionsPathOptional = z3.object({
      path: z3.string(),
      alt: z3.string()
    }).passthrough().partial();
    ZodLogoSpecifierPathOptional = z3.union([
      z3.string(),
      z3.lazy(() => ZodLogoOptionsPathOptional)
    ]);
    ZodLogoLightDarkSpecifier = z3.union([
      z3.literal(false),
      z3.lazy(() => ZodLogoSpecifier),
      z3.object({
        light: z3.lazy(() => ZodLogoSpecifier),
        dark: z3.lazy(() => ZodLogoSpecifier)
      }).strict().partial()
    ]);
    ZodLogoLightDarkSpecifierPathOptional = z3.union([
      z3.literal(false),
      z3.lazy(() => ZodLogoSpecifierPathOptional),
      z3.object({
        light: z3.lazy(() => ZodLogoSpecifierPathOptional),
        dark: z3.lazy(() => ZodLogoSpecifierPathOptional)
      }).strict().partial()
    ]);
    ZodNormalizedLogoLightDarkSpecifier = z3.object({
      light: z3.lazy(() => ZodLogoOptions),
      dark: z3.lazy(() => ZodLogoOptions)
    }).strict().partial();
    ZodBrandColorValue = z3.string();
    ZodBrandColorSingle = z3.object({
      palette: z3.record(z3.lazy(() => ZodBrandColorValue)).and(
        z3.object({}).passthrough().partial()
      ),
      foreground: z3.lazy(() => ZodBrandColorValue),
      background: z3.lazy(() => ZodBrandColorValue),
      primary: z3.lazy(() => ZodBrandColorValue),
      secondary: z3.lazy(() => ZodBrandColorValue),
      tertiary: z3.lazy(() => ZodBrandColorValue),
      success: z3.lazy(() => ZodBrandColorValue),
      info: z3.lazy(() => ZodBrandColorValue),
      warning: z3.lazy(() => ZodBrandColorValue),
      danger: z3.lazy(() => ZodBrandColorValue),
      light: z3.lazy(() => ZodBrandColorValue),
      dark: z3.lazy(() => ZodBrandColorValue),
      link: z3.lazy(() => ZodBrandColorValue)
    }).strict().partial();
    ZodBrandColorLightDark = z3.union([
      z3.lazy(() => ZodBrandColorValue),
      z3.object({
        light: z3.lazy(() => ZodBrandColorValue),
        dark: z3.lazy(() => ZodBrandColorValue)
      }).strict().partial()
    ]);
    ZodBrandColorUnified = z3.object({
      palette: z3.record(z3.lazy(() => ZodBrandColorValue)).and(
        z3.object({}).passthrough().partial()
      ),
      foreground: z3.lazy(() => ZodBrandColorLightDark),
      background: z3.lazy(() => ZodBrandColorLightDark),
      primary: z3.lazy(() => ZodBrandColorLightDark),
      secondary: z3.lazy(() => ZodBrandColorLightDark),
      tertiary: z3.lazy(() => ZodBrandColorLightDark),
      success: z3.lazy(() => ZodBrandColorLightDark),
      info: z3.lazy(() => ZodBrandColorLightDark),
      warning: z3.lazy(() => ZodBrandColorLightDark),
      danger: z3.lazy(() => ZodBrandColorLightDark),
      light: z3.lazy(() => ZodBrandColorLightDark),
      dark: z3.lazy(() => ZodBrandColorLightDark),
      link: z3.lazy(() => ZodBrandColorLightDark)
    }).strict().partial();
    ZodBrandMaybeNamedColor = z3.union([
      z3.lazy(() => ZodBrandNamedThemeColor),
      z3.string()
    ]);
    ZodBrandMaybeNamedColorLightDark = z3.union([
      z3.lazy(() => ZodBrandMaybeNamedColor),
      z3.object({
        light: z3.lazy(() => ZodBrandMaybeNamedColor),
        dark: z3.lazy(() => ZodBrandMaybeNamedColor)
      }).strict().partial()
    ]);
    ZodBrandNamedThemeColor = z3.enum(
      [
        "foreground",
        "background",
        "primary",
        "secondary",
        "tertiary",
        "success",
        "info",
        "warning",
        "danger",
        "light",
        "dark",
        "link"
      ]
    );
    ZodBrandTypographySingle = z3.object({
      fonts: z3.array(z3.lazy(() => ZodBrandFont)),
      base: z3.lazy(() => ZodBrandTypographyOptionsBase),
      headings: z3.lazy(() => ZodBrandTypographyOptionsHeadingsSingle),
      monospace: z3.lazy(() => ZodBrandTypographyOptionsMonospaceSingle),
      "monospace-inline": z3.lazy(
        () => ZodBrandTypographyOptionsMonospaceInlineSingle
      ),
      "monospace-block": z3.lazy(
        () => ZodBrandTypographyOptionsMonospaceBlockSingle
      ),
      link: z3.lazy(() => ZodBrandTypographyOptionsLinkSingle)
    }).strict().partial();
    ZodBrandTypographyUnified = z3.object({
      fonts: z3.array(z3.lazy(() => ZodBrandFont)),
      base: z3.lazy(() => ZodBrandTypographyOptionsBase),
      headings: z3.lazy(() => ZodBrandTypographyOptionsHeadingsUnified),
      monospace: z3.lazy(() => ZodBrandTypographyOptionsMonospaceUnified),
      "monospace-inline": z3.lazy(
        () => ZodBrandTypographyOptionsMonospaceInlineUnified
      ),
      "monospace-block": z3.lazy(
        () => ZodBrandTypographyOptionsMonospaceBlockUnified
      ),
      link: z3.lazy(() => ZodBrandTypographyOptionsLinkUnified)
    }).strict().partial();
    ZodBrandTypographyOptionsBase = z3.union([
      z3.string(),
      z3.object({
        family: z3.string(),
        size: z3.string(),
        weight: z3.lazy(() => ZodBrandFontWeight),
        "line-height": z3.lazy(() => ZodLineHeightNumberString)
      }).strict().partial()
    ]);
    ZodBrandTypographyOptionsHeadingsSingle = z3.union([
      z3.string(),
      z3.object({
        family: z3.string(),
        weight: z3.lazy(() => ZodBrandFontWeight),
        style: z3.lazy(() => ZodBrandFontStyle),
        color: z3.lazy(() => ZodBrandMaybeNamedColor),
        "line-height": z3.lazy(() => ZodLineHeightNumberString)
      }).strict().partial()
    ]);
    ZodBrandTypographyOptionsHeadingsUnified = z3.union([
      z3.string(),
      z3.object({
        family: z3.string(),
        weight: z3.lazy(() => ZodBrandFontWeight),
        style: z3.lazy(() => ZodBrandFontStyle),
        color: z3.lazy(() => ZodBrandMaybeNamedColorLightDark),
        "line-height": z3.lazy(() => ZodLineHeightNumberString)
      }).strict().partial()
    ]);
    ZodBrandTypographyOptionsMonospaceSingle = z3.union([
      z3.string(),
      z3.object({
        family: z3.string(),
        size: z3.string(),
        weight: z3.lazy(() => ZodBrandFontWeight),
        color: z3.lazy(() => ZodBrandMaybeNamedColor),
        "background-color": z3.lazy(() => ZodBrandMaybeNamedColor)
      }).strict().partial()
    ]);
    ZodBrandTypographyOptionsMonospaceUnified = z3.union([
      z3.string(),
      z3.object({
        family: z3.string(),
        size: z3.string(),
        weight: z3.lazy(() => ZodBrandFontWeight),
        color: z3.lazy(() => ZodBrandMaybeNamedColorLightDark),
        "background-color": z3.lazy(() => ZodBrandMaybeNamedColorLightDark)
      }).strict().partial()
    ]);
    ZodBrandTypographyOptionsMonospaceInlineSingle = z3.union([
      z3.string(),
      z3.object({
        family: z3.string(),
        size: z3.string(),
        weight: z3.lazy(() => ZodBrandFontWeight),
        color: z3.lazy(() => ZodBrandMaybeNamedColor),
        "background-color": z3.lazy(() => ZodBrandMaybeNamedColor)
      }).strict().partial()
    ]);
    ZodBrandTypographyOptionsMonospaceInlineUnified = z3.union([
      z3.string(),
      z3.object({
        family: z3.string(),
        size: z3.string(),
        weight: z3.lazy(() => ZodBrandFontWeight),
        color: z3.lazy(() => ZodBrandMaybeNamedColorLightDark),
        "background-color": z3.lazy(() => ZodBrandMaybeNamedColorLightDark)
      }).strict().partial()
    ]);
    ZodLineHeightNumberString = z3.union([z3.number(), z3.string()]);
    ZodBrandTypographyOptionsMonospaceBlockSingle = z3.union([
      z3.string(),
      z3.object({
        family: z3.string(),
        size: z3.string(),
        weight: z3.lazy(() => ZodBrandFontWeight),
        color: z3.lazy(() => ZodBrandMaybeNamedColor),
        "background-color": z3.lazy(() => ZodBrandMaybeNamedColor),
        "line-height": z3.lazy(() => ZodLineHeightNumberString)
      }).strict().partial()
    ]);
    ZodBrandTypographyOptionsMonospaceBlockUnified = z3.union([
      z3.string(),
      z3.object({
        family: z3.string(),
        size: z3.string(),
        weight: z3.lazy(() => ZodBrandFontWeight),
        color: z3.lazy(() => ZodBrandMaybeNamedColorLightDark),
        "background-color": z3.lazy(() => ZodBrandMaybeNamedColorLightDark),
        "line-height": z3.lazy(() => ZodLineHeightNumberString)
      }).strict().partial()
    ]);
    ZodBrandTypographyOptionsLinkSingle = z3.union([
      z3.string(),
      z3.object({
        weight: z3.lazy(() => ZodBrandFontWeight),
        color: z3.lazy(() => ZodBrandMaybeNamedColor),
        "background-color": z3.lazy(() => ZodBrandMaybeNamedColor),
        decoration: z3.string()
      }).strict().partial()
    ]);
    ZodBrandTypographyOptionsLinkUnified = z3.union([
      z3.string(),
      z3.object({
        weight: z3.lazy(() => ZodBrandFontWeight),
        color: z3.lazy(() => ZodBrandMaybeNamedColorLightDark),
        "background-color": z3.lazy(() => ZodBrandMaybeNamedColorLightDark),
        decoration: z3.string()
      }).strict().partial()
    ]);
    ZodBrandNamedTypographyElements = z3.enum(
      [
        "base",
        "headings",
        "monospace",
        "monospace-inline",
        "monospace-block",
        "link"
      ]
    );
    ZodBrandFont = z3.union([
      z3.lazy(() => ZodBrandFontGoogle),
      z3.lazy(() => ZodBrandFontBunny),
      z3.lazy(() => ZodBrandFontFile),
      z3.lazy(() => ZodBrandFontSystem)
    ]);
    ZodBrandFontWeight = z3.union([
      z3.enum(
        [
          "thin",
          "extra-light",
          "ultra-light",
          "light",
          "normal",
          "regular",
          "medium",
          "semi-bold",
          "demi-bold",
          "bold",
          "extra-bold",
          "ultra-bold",
          "black"
        ]
      ),
      z3.literal(100),
      z3.literal(200),
      z3.literal(300),
      z3.literal(400),
      z3.literal(500),
      z3.literal(600),
      z3.literal(700),
      z3.literal(800),
      z3.literal(900)
    ]);
    ZodBrandFontStyle = z3.enum(
      ["normal", "italic", "oblique"]
    );
    ZodBrandFontCommon = z3.object({
      family: z3.string(),
      weight: z3.union([
        z3.lazy(() => ZodBrandFontWeight),
        z3.array(z3.lazy(() => ZodBrandFontWeight))
      ]),
      style: z3.union([
        z3.lazy(() => ZodBrandFontStyle),
        z3.array(z3.lazy(() => ZodBrandFontStyle))
      ]),
      display: z3.enum(["auto", "block", "swap", "fallback", "optional"])
    }).strict().partial();
    ZodBrandFontSystem = z3.object({
      family: z3.string(),
      weight: z3.union([
        z3.lazy(() => ZodBrandFontWeight),
        z3.array(z3.lazy(() => ZodBrandFontWeight))
      ]),
      style: z3.union([
        z3.lazy(() => ZodBrandFontStyle),
        z3.array(z3.lazy(() => ZodBrandFontStyle))
      ]),
      display: z3.enum(["auto", "block", "swap", "fallback", "optional"]),
      source: z3.enum(["system"])
    }).strict().partial().required({ source: true });
    ZodBrandFontGoogle = z3.object({
      family: z3.string(),
      weight: z3.union([
        z3.lazy(() => ZodBrandFontWeight),
        z3.array(z3.lazy(() => ZodBrandFontWeight))
      ]),
      style: z3.union([
        z3.lazy(() => ZodBrandFontStyle),
        z3.array(z3.lazy(() => ZodBrandFontStyle))
      ]),
      display: z3.enum(["auto", "block", "swap", "fallback", "optional"]),
      source: z3.enum(["google"])
    }).strict().partial().required({ source: true });
    ZodBrandFontBunny = z3.object({
      family: z3.string(),
      weight: z3.union([
        z3.lazy(() => ZodBrandFontWeight),
        z3.array(z3.lazy(() => ZodBrandFontWeight))
      ]),
      style: z3.union([
        z3.lazy(() => ZodBrandFontStyle),
        z3.array(z3.lazy(() => ZodBrandFontStyle))
      ]),
      display: z3.enum(["auto", "block", "swap", "fallback", "optional"]),
      source: z3.enum(["bunny"])
    }).strict().partial().required({ source: true });
    ZodBrandFontFile = z3.object({
      source: z3.enum(["file"]),
      family: z3.string(),
      files: z3.array(
        z3.union([
          z3.string(),
          z3.object({
            path: z3.string(),
            weight: z3.lazy(() => ZodBrandFontWeight),
            style: z3.lazy(() => ZodBrandFontStyle)
          }).passthrough().partial().required({ path: true })
        ])
      )
    }).strict().partial().required({ files: true, family: true, source: true });
    ZodBrandFontFamily = z3.string();
    ZodBrandSingle = z3.object({
      meta: z3.lazy(() => ZodBrandMeta),
      logo: z3.lazy(() => ZodBrandLogoSingle),
      color: z3.lazy(() => ZodBrandColorSingle),
      typography: z3.lazy(() => ZodBrandTypographySingle),
      defaults: z3.lazy(() => ZodBrandDefaults)
    }).strict().partial();
    ZodBrandUnified = z3.object({
      meta: z3.lazy(() => ZodBrandMeta),
      logo: z3.lazy(() => ZodBrandLogoUnified),
      color: z3.lazy(() => ZodBrandColorUnified),
      typography: z3.lazy(() => ZodBrandTypographyUnified),
      defaults: z3.lazy(() => ZodBrandDefaults)
    }).strict().partial();
    ZodBrandPathOnlyLightDark = z3.union([
      z3.string(),
      z3.object({ light: z3.string(), dark: z3.string() }).strict().partial()
    ]);
    ZodBrandPathBoolLightDark = z3.union([
      z3.string(),
      z3.boolean(),
      z3.object({
        light: z3.union([z3.string(), z3.lazy(() => ZodBrandSingle)]),
        dark: z3.union([z3.string(), z3.lazy(() => ZodBrandSingle)])
      }).strict().partial(),
      z3.lazy(() => ZodBrandUnified)
    ]);
    ZodBrandDefaults = z3.object({
      bootstrap: z3.lazy(() => ZodBrandDefaultsBootstrap),
      quarto: z3.object({}).passthrough()
    }).passthrough().partial();
    ZodBrandDefaultsBootstrap = z3.object({
      defaults: z3.record(z3.union([z3.string(), z3.boolean(), z3.number()])).and(
        z3.object({}).passthrough().partial()
      )
    }).passthrough().partial();
    ZodMarginaliaSideGeometry = z3.object({
      far: z3.string(),
      width: z3.string(),
      separation: z3.string()
    }).strict().partial();
    ZodProjectConfig = z3.object({
      title: z3.string(),
      type: z3.string(),
      render: z3.array(z3.string()),
      "execute-dir": z3.enum(["file", "project"]),
      "output-dir": z3.string(),
      "lib-dir": z3.string(),
      resources: z3.union([z3.string(), z3.array(z3.string())]),
      brand: z3.lazy(() => ZodBrandPathOnlyLightDark),
      preview: z3.lazy(() => ZodProjectPreview),
      "pre-render": z3.union([z3.string(), z3.array(z3.string())]),
      "post-render": z3.union([z3.string(), z3.array(z3.string())]),
      detect: z3.array(z3.array(z3.string()))
    }).strict().partial();
    ZodBookProject = z3.object({}).passthrough().partial();
    Zod = {
      Date: ZodDate2,
      DateFormat: ZodDateFormat,
      MathMethods: ZodMathMethods,
      PandocFormatRequestHeaders: ZodPandocFormatRequestHeaders,
      PandocFormatOutputFile: ZodPandocFormatOutputFile,
      FilterEntryPoint: ZodFilterEntryPoint,
      PandocFormatFilters: ZodPandocFormatFilters,
      PandocShortcodes: ZodPandocShortcodes,
      PageColumn: ZodPageColumn,
      ContentsAuto: ZodContentsAuto,
      NavigationItem: ZodNavigationItem,
      NavigationItemObject: ZodNavigationItemObject,
      GiscusThemes: ZodGiscusThemes,
      GiscusConfiguration: ZodGiscusConfiguration,
      ExternalEngine: ZodExternalEngine,
      DocumentCommentsConfiguration: ZodDocumentCommentsConfiguration,
      SocialMetadata: ZodSocialMetadata,
      PageFooterRegion: ZodPageFooterRegion,
      SidebarContents: ZodSidebarContents,
      ProjectPreview: ZodProjectPreview,
      ProjectServe: ZodProjectServe,
      Publish: ZodPublish,
      PublishRecord: ZodPublishRecord,
      TwitterCardConfig: ZodTwitterCardConfig,
      OpenGraphConfig: ZodOpenGraphConfig,
      PageFooter: ZodPageFooter,
      BaseWebsite: ZodBaseWebsite,
      BookSchema: ZodBookSchema,
      ChapterItem: ZodChapterItem,
      ChapterList: ZodChapterList,
      OtherLinks: ZodOtherLinks,
      CrossrefLabelsSchema: ZodCrossrefLabelsSchema,
      EpubContributor: ZodEpubContributor,
      FormatLanguage: ZodFormatLanguage,
      WebsiteAbout: ZodWebsiteAbout,
      WebsiteListing: ZodWebsiteListing,
      WebsiteListingContentsObject: ZodWebsiteListingContentsObject,
      CslDate: ZodCslDate,
      CslPerson: ZodCslPerson,
      CslNumber: ZodCslNumber,
      CslItemShared: ZodCslItemShared,
      CslItem: ZodCslItem,
      CitationItem: ZodCitationItem,
      SmartInclude: ZodSmartInclude,
      Semver: ZodSemver,
      QuartoDate: ZodQuartoDate,
      ProjectProfile: ZodProjectProfile,
      BadParseSchema: ZodBadParseSchema,
      QuartoDevSchema: ZodQuartoDevSchema,
      NotebookViewSchema: ZodNotebookViewSchema,
      CodeLinksSchema: ZodCodeLinksSchema,
      ManuscriptSchema: ZodManuscriptSchema,
      BrandMeta: ZodBrandMeta,
      BrandStringLightDark: ZodBrandStringLightDark,
      BrandLogoExplicitResource: ZodBrandLogoExplicitResource,
      BrandLogoResource: ZodBrandLogoResource,
      BrandLogoSingle: ZodBrandLogoSingle,
      BrandLogoUnified: ZodBrandLogoUnified,
      BrandNamedLogo: ZodBrandNamedLogo,
      LogoOptions: ZodLogoOptions,
      LogoSpecifier: ZodLogoSpecifier,
      LogoOptionsPathOptional: ZodLogoOptionsPathOptional,
      LogoSpecifierPathOptional: ZodLogoSpecifierPathOptional,
      LogoLightDarkSpecifier: ZodLogoLightDarkSpecifier,
      LogoLightDarkSpecifierPathOptional: ZodLogoLightDarkSpecifierPathOptional,
      NormalizedLogoLightDarkSpecifier: ZodNormalizedLogoLightDarkSpecifier,
      BrandColorValue: ZodBrandColorValue,
      BrandColorSingle: ZodBrandColorSingle,
      BrandColorLightDark: ZodBrandColorLightDark,
      BrandColorUnified: ZodBrandColorUnified,
      BrandMaybeNamedColor: ZodBrandMaybeNamedColor,
      BrandMaybeNamedColorLightDark: ZodBrandMaybeNamedColorLightDark,
      BrandNamedThemeColor: ZodBrandNamedThemeColor,
      BrandTypographySingle: ZodBrandTypographySingle,
      BrandTypographyUnified: ZodBrandTypographyUnified,
      BrandTypographyOptionsBase: ZodBrandTypographyOptionsBase,
      BrandTypographyOptionsHeadingsSingle: ZodBrandTypographyOptionsHeadingsSingle,
      BrandTypographyOptionsHeadingsUnified: ZodBrandTypographyOptionsHeadingsUnified,
      BrandTypographyOptionsMonospaceSingle: ZodBrandTypographyOptionsMonospaceSingle,
      BrandTypographyOptionsMonospaceUnified: ZodBrandTypographyOptionsMonospaceUnified,
      BrandTypographyOptionsMonospaceInlineSingle: ZodBrandTypographyOptionsMonospaceInlineSingle,
      BrandTypographyOptionsMonospaceInlineUnified: ZodBrandTypographyOptionsMonospaceInlineUnified,
      LineHeightNumberString: ZodLineHeightNumberString,
      BrandTypographyOptionsMonospaceBlockSingle: ZodBrandTypographyOptionsMonospaceBlockSingle,
      BrandTypographyOptionsMonospaceBlockUnified: ZodBrandTypographyOptionsMonospaceBlockUnified,
      BrandTypographyOptionsLinkSingle: ZodBrandTypographyOptionsLinkSingle,
      BrandTypographyOptionsLinkUnified: ZodBrandTypographyOptionsLinkUnified,
      BrandNamedTypographyElements: ZodBrandNamedTypographyElements,
      BrandFont: ZodBrandFont,
      BrandFontWeight: ZodBrandFontWeight,
      BrandFontStyle: ZodBrandFontStyle,
      BrandFontCommon: ZodBrandFontCommon,
      BrandFontSystem: ZodBrandFontSystem,
      BrandFontGoogle: ZodBrandFontGoogle,
      BrandFontBunny: ZodBrandFontBunny,
      BrandFontFile: ZodBrandFontFile,
      BrandFontFamily: ZodBrandFontFamily,
      BrandSingle: ZodBrandSingle,
      BrandUnified: ZodBrandUnified,
      BrandPathOnlyLightDark: ZodBrandPathOnlyLightDark,
      BrandPathBoolLightDark: ZodBrandPathBoolLightDark,
      BrandDefaults: ZodBrandDefaults,
      BrandDefaultsBootstrap: ZodBrandDefaultsBootstrap,
      MarginaliaSideGeometry: ZodMarginaliaSideGeometry,
      ProjectConfig: ZodProjectConfig,
      BookProject: ZodBookProject
    };
  }
});

// core/css/color-names.ts
var isCssColorName;
var init_color_names = __esm({
  "core/css/color-names.ts"() {
    isCssColorName = (name2) => {
      if (name2.startsWith("#")) return true;
      if (name2.startsWith("rgb")) return true;
      if (name2.startsWith("hsl")) return true;
      if (name2.startsWith("hwb")) return true;
      return [
        "aliceblue",
        "antiquewhite",
        "aqua",
        "aquamarine",
        "azure",
        "beige",
        "bisque",
        "black",
        "blanchedalmond",
        "blue",
        "blueviolet",
        "brown",
        "burlywood",
        "cadetblue",
        "chartreuse",
        "chocolate",
        "coral",
        "cornflowerblue",
        "cornsilk",
        "crimson",
        "cyan",
        "darkblue",
        "darkcyan",
        "darkgoldenrod",
        "darkgray",
        "darkgreen",
        "darkgrey",
        "darkkhaki",
        "darkmagenta",
        "darkolivegreen",
        "darkorange",
        "darkorchid",
        "darkred",
        "darksalmon",
        "darkseagreen",
        "darkslateblue",
        "darkslategray",
        "darkslategrey",
        "darkturquoise",
        "darkviolet",
        "deeppink",
        "deepskyblue",
        "dimgray",
        "dimgrey",
        "dodgerblue",
        "firebrick",
        "floralwhite",
        "forestgreen",
        "fuchsia",
        "gainsboro",
        "ghostwhite",
        "gold",
        "goldenrod",
        "gray",
        "green",
        "greenyellow",
        "grey",
        "honeydew",
        "hotpink",
        "indianred",
        "indigo",
        "ivory",
        "khaki",
        "lavender",
        "lavenderblush",
        "lawngreen",
        "lemonchiffon",
        "lightblue",
        "lightcoral",
        "lightcyan",
        "lightgoldenrodyellow",
        "lightgray",
        "lightgreen",
        "lightgrey",
        "lightpink",
        "lightsalmon",
        "lightseagreen",
        "lightskyblue",
        "lightslategray",
        "lightslategrey",
        "lightsteelblue",
        "lightyellow",
        "lime",
        "limegreen",
        "linen",
        "magenta",
        "maroon",
        "mediumaquamarine",
        "mediumblue",
        "mediumorchid",
        "mediumpurple",
        "mediumseagreen",
        "mediumslateblue",
        "mediumspringgreen",
        "mediumturquoise",
        "mediumvioletred",
        "midnightblue",
        "mintcream",
        "mistyrose",
        "moccasin",
        "navajowhite",
        "navy",
        "oldlace",
        "olive",
        "olivedrab",
        "orange",
        "orangered",
        "orchid",
        "palegoldenrod",
        "palegreen",
        "paleturquoise",
        "palevioletred",
        "papayawhip",
        "peachpuff",
        "peru",
        "pink",
        "plum",
        "powderblue",
        "purple",
        "red",
        "rosybrown",
        "royalblue",
        "saddlebrown",
        "salmon",
        "sandybrown",
        "seagreen",
        "seashell",
        "sienna",
        "silver",
        "skyblue",
        "slateblue",
        "slategray",
        "slategrey",
        "snow",
        "springgreen",
        "steelblue",
        "tan",
        "teal",
        "thistle",
        "tomato",
        "turquoise",
        "violet",
        "wheat",
        "white",
        "whitesmoke",
        "yellow",
        "yellowgreen"
      ].includes(name2);
    };
  }
});

// core/url.ts
function isHttpUrl(url) {
  return /^https?:/i.test(url);
}
function isExternalPath(path3) {
  return /^\w+:/.test(path3);
}
function joinUrl(baseUrl, path3) {
  const baseHasSlash = baseUrl.endsWith("/");
  path3 = pathWithForwardSlashes(path3);
  const pathHasSlash = path3.startsWith("/");
  if (baseHasSlash && pathHasSlash) {
    return `${baseUrl}${path3.slice(1)}`;
  } else if (!baseHasSlash && !pathHasSlash) {
    return `${baseUrl}/${path3}`;
  } else {
    return `${baseUrl}${path3}`;
  }
}
function ensureProtocolAndTrailingSlash(url) {
  if (!url.startsWith("http")) {
    url = `https://${url}`;
  }
  url = ensureTrailingSlash(url);
  return url;
}
var init_url = __esm({
  "core/url.ts"() {
    init_path2();
  }
});

// core/brand/brand.ts
function resolveLogo(brand, spec, order) {
  const resolveBrandLogo = (mode, name2) => {
    const logo = brand?.[mode]?.processedData?.logo;
    return logo && (Zod.BrandNamedLogo.options.includes(name2) && logo[name2] || logo.images[name2]) || { path: name2 };
  };
  function findLogo(mode, order2) {
    if (brand?.[mode]) {
      for (const size of order2) {
        const logo = brand[mode].processedData.logo[size];
        if (logo) {
          return logo;
        }
      }
    }
    return void 0;
  }
  const resolveLogoOptions = (mode, logo) => {
    const logo2 = resolveBrandLogo(mode, logo.path);
    if (logo2) {
      const { path: _3, ...rest } = logo;
      return {
        ...logo2,
        ...rest
      };
    }
    return logo;
  };
  if (spec === false) {
    return void 0;
  }
  if (!spec) {
    const lightLogo = findLogo("light", order);
    const darkLogo = findLogo("dark", order);
    if (!lightLogo && !darkLogo) {
      return void 0;
    }
    return {
      light: lightLogo || darkLogo,
      dark: darkLogo || lightLogo
    };
  }
  if (typeof spec === "string") {
    return {
      light: resolveBrandLogo("light", spec),
      dark: resolveBrandLogo("light", spec)
    };
  }
  if ("path" in spec) {
    return {
      light: resolveLogoOptions("light", spec),
      dark: resolveLogoOptions("dark", spec)
    };
  }
  let light, dark;
  if (!spec.light) {
    light = findLogo("light", order);
  } else if (typeof spec.light === "string") {
    light = resolveBrandLogo("light", spec.light);
  } else {
    light = resolveLogoOptions("light", spec.light);
  }
  if (!spec.dark) {
    dark = findLogo("dark", order);
  } else if (typeof spec.dark === "string") {
    dark = resolveBrandLogo("dark", spec.dark);
  } else {
    dark = resolveLogoOptions("dark", spec.dark);
  }
  if (!light && dark) {
    light = { ...dark };
  }
  if (!dark && light && brand && brand.dark) {
    dark = { ...light };
  }
  return {
    light,
    dark
  };
}
function logoAddLeadingSlashes(spec, brand, input) {
  if (!spec) {
    return spec;
  }
  if (input) {
    const inputDir = dirname4(resolve4(input));
    if (!brand || inputDir === brand.light?.projectDir) {
      return spec;
    }
  }
  return {
    light: spec.light && {
      ...spec.light,
      path: ensureLeadingSlashIfNotExternal(spec.light.path)
    },
    dark: spec.dark && {
      ...spec.dark,
      path: ensureLeadingSlashIfNotExternal(spec.dark.path)
    }
  };
}
function brandWithAbsoluteLogoPaths(brand) {
  if (!brand) {
    return brand;
  }
  const transformBrand = (b3) => {
    if (!b3) return b3;
    const oldLogo = b3.processedData.logo;
    const logo = { images: {} };
    for (const size of Zod.BrandNamedLogo.options) {
      if (oldLogo[size]) {
        logo[size] = {
          ...oldLogo[size],
          path: ensureLeadingSlashIfNotExternal(oldLogo[size].path)
        };
      }
    }
    for (const [key, value] of Object.entries(oldLogo.images)) {
      logo.images[key] = {
        ...value,
        path: ensureLeadingSlashIfNotExternal(value.path)
      };
    }
    const copy6 = Object.create(b3);
    copy6.processedData = { ...b3.processedData, logo };
    return copy6;
  };
  return {
    light: transformBrand(brand.light),
    dark: transformBrand(brand.dark)
  };
}
function fillLogoPaths(brand, spec, order) {
  function findLogoSize(mode) {
    if (brand?.[mode]) {
      for (const size of order) {
        if (brand[mode].processedData.logo[size]) {
          return size;
        }
      }
    }
    return void 0;
  }
  function resolveMode(mode, spec2) {
    if (!spec2) {
      return void 0;
    }
    if (!spec2 || typeof spec2 === "string") {
      return spec2;
    } else if (spec2.path) {
      return spec2;
    } else {
      const size = findLogoSize(mode) || findLogoSize(mode === "light" ? "dark" : "light");
      if (size) {
        return {
          path: size,
          ...spec2
        };
      }
    }
    return void 0;
  }
  if (!spec) {
    return void 0;
  }
  if (typeof spec === "string") {
    return spec;
  }
  if ("light" in spec || "dark" in spec) {
    return {
      light: resolveMode("light", spec.light),
      dark: resolveMode("dark", spec.dark)
    };
  }
  return {
    light: resolveMode("light", spec),
    dark: resolveMode("dark", spec)
  };
}
function splitColorLightDark(bcld) {
  if (typeof bcld === "string") {
    return { light: bcld, dark: bcld };
  }
  return bcld;
}
function brandHasDarkMode(brand) {
  if (brand.color) {
    for (const colorName of Zod.BrandNamedThemeColor.options) {
      if (!brand.color[colorName]) {
        continue;
      }
      if (enablesDarkMode(brand.color[colorName])) {
        return true;
      }
    }
  }
  if (brand.typography) {
    for (const elementName of Zod.BrandNamedTypographyElements.options) {
      const element = brand.typography[elementName];
      if (!element || typeof element === "string") {
        continue;
      }
      if ("background-color" in element && element["background-color"] && enablesDarkMode(element["background-color"])) {
        return true;
      }
      if ("color" in element && element["color"] && enablesDarkMode(element["color"])) {
        return true;
      }
    }
  }
  if (brand.logo) {
    for (const logoName of Zod.BrandNamedLogo.options) {
      const logo = brand.logo[logoName];
      if (!logo || typeof logo === "string") {
        continue;
      }
      if (enablesDarkMode(logo)) {
        return true;
      }
    }
  }
  return false;
}
function sharedTypography(unified) {
  const ret = {
    fonts: unified.fonts
  };
  for (const elementName of Zod.BrandNamedTypographyElements.options) {
    if (!unified[elementName]) {
      continue;
    }
    if (typeof unified[elementName] === "string") {
      ret[elementName] = unified[elementName];
      continue;
    }
    ret[elementName] = Object.fromEntries(
      Object.entries(unified[elementName]).filter(
        ([key, _3]) => !["color", "background-color"].includes(key)
      )
    );
  }
  return ret;
}
function splitLogo(unifiedLogo) {
  const light = { images: unifiedLogo.images }, dark = { images: unifiedLogo.images };
  for (const logoName of Zod.BrandNamedLogo.options) {
    if (unifiedLogo[logoName]) {
      if (typeof unifiedLogo[logoName] === "string") {
        light[logoName] = dark[logoName] = unifiedLogo[logoName];
        continue;
      }
      ({ light: light[logoName], dark: dark[logoName] } = unifiedLogo[logoName]);
    }
  }
  return { light, dark };
}
function splitUnifiedBrand(unified, brandDir, projectDir) {
  const unifiedBrand = Zod.BrandUnified.parse(unified);
  let typography = void 0;
  let headingsColor = void 0;
  let monospaceColor = void 0;
  let monospaceBackgroundColor = void 0;
  let monospaceInlineColor = void 0;
  let monospaceInlineBackgroundColor = void 0;
  let monospaceBlockColor = void 0;
  let monospaceBlockBackgroundColor = void 0;
  let linkColor = void 0;
  let linkBackgroundColor = void 0;
  if (unifiedBrand.typography) {
    typography = sharedTypography(unifiedBrand.typography);
    if (unifiedBrand.typography.headings && typeof unifiedBrand.typography.headings !== "string" && unifiedBrand.typography.headings.color) {
      headingsColor = splitColorLightDark(
        unifiedBrand.typography.headings.color
      );
    }
    if (unifiedBrand.typography.monospace && typeof unifiedBrand.typography.monospace !== "string") {
      if (unifiedBrand.typography.monospace.color) {
        monospaceColor = splitColorLightDark(
          unifiedBrand.typography.monospace.color
        );
      }
      if (unifiedBrand.typography.monospace["background-color"]) {
        monospaceBackgroundColor = splitColorLightDark(
          unifiedBrand.typography.monospace["background-color"]
        );
      }
    }
    if (unifiedBrand.typography["monospace-inline"] && typeof unifiedBrand.typography["monospace-inline"] !== "string") {
      if (unifiedBrand.typography["monospace-inline"].color) {
        monospaceInlineColor = splitColorLightDark(
          unifiedBrand.typography["monospace-inline"].color
        );
      }
      if (unifiedBrand.typography["monospace-inline"]["background-color"]) {
        monospaceInlineBackgroundColor = splitColorLightDark(
          unifiedBrand.typography["monospace-inline"]["background-color"]
        );
      }
    }
    if (unifiedBrand.typography["monospace-block"] && typeof unifiedBrand.typography["monospace-block"] !== "string") {
      if (unifiedBrand.typography["monospace-block"].color) {
        monospaceBlockColor = splitColorLightDark(
          unifiedBrand.typography["monospace-block"].color
        );
      }
      if (unifiedBrand.typography["monospace-block"]["background-color"]) {
        monospaceBlockBackgroundColor = splitColorLightDark(
          unifiedBrand.typography["monospace-block"]["background-color"]
        );
      }
    }
    if (unifiedBrand.typography.link && typeof unifiedBrand.typography.link !== "string") {
      if (unifiedBrand.typography.link.color) {
        linkColor = splitColorLightDark(
          unifiedBrand.typography.link.color
        );
      }
      if (unifiedBrand.typography.link["background-color"]) {
        linkBackgroundColor = splitColorLightDark(
          unifiedBrand.typography.link["background-color"]
        );
      }
    }
  }
  const specializeTypography = (typography2, mode) => typography2 && {
    fonts: typography2.fonts && [...typography2.fonts],
    base: !typography2.base || typeof typography2.base === "string" ? typography2.base : { ...typography2.base },
    headings: !typography2.headings || typeof typography2.headings === "string" ? typography2.headings : {
      ...typography2.headings,
      ...headingsColor?.[mode] && { color: headingsColor[mode] }
    },
    monospace: !typography2.monospace || typeof typography2.monospace === "string" ? typography2.monospace : {
      ...typography2.monospace,
      ...monospaceColor?.[mode] && { color: monospaceColor[mode] },
      ...monospaceBackgroundColor?.[mode] && { "background-color": monospaceBackgroundColor[mode] }
    },
    "monospace-inline": !typography2["monospace-inline"] || typeof typography2["monospace-inline"] === "string" ? typography2["monospace-inline"] : {
      ...typography2["monospace-inline"],
      ...monospaceInlineColor?.[mode] && { color: monospaceInlineColor[mode] },
      ...monospaceInlineBackgroundColor?.[mode] && { "background-color": monospaceInlineBackgroundColor[mode] }
    },
    "monospace-block": !typography2["monospace-block"] || typeof typography2["monospace-block"] === "string" ? typography2["monospace-block"] : {
      ...typography2["monospace-block"],
      ...monospaceBlockColor?.[mode] && { color: monospaceBlockColor[mode] },
      ...monospaceBlockBackgroundColor?.[mode] && { "background-color": monospaceBlockBackgroundColor[mode] }
    },
    link: !typography2.link || typeof typography2.link === "string" ? typography2.link : {
      ...typography2.link,
      ...linkColor?.[mode] && { color: linkColor[mode] },
      ...linkBackgroundColor?.[mode] && { "background-color": linkBackgroundColor[mode] }
    }
  };
  const logos = unifiedBrand.logo && splitLogo(unifiedBrand.logo);
  const lightBrand = {
    meta: unifiedBrand.meta,
    color: { palette: unifiedBrand.color && { ...unifiedBrand.color.palette } },
    typography: typography && specializeTypography(typography, "light"),
    logo: logos && logos.light,
    defaults: unifiedBrand.defaults
  };
  const darkBrand = {
    meta: unifiedBrand.meta,
    color: { palette: unifiedBrand.color && { ...unifiedBrand.color.palette } },
    typography: typography && specializeTypography(typography, "dark"),
    logo: logos && logos.dark,
    defaults: unifiedBrand.defaults
  };
  if (unifiedBrand.color) {
    for (const colorName of Zod.BrandNamedThemeColor.options) {
      if (!unifiedBrand.color[colorName]) {
        continue;
      }
      const { light, dark } = splitColorLightDark(
        unifiedBrand.color[colorName]
      );
      if (light !== void 0) lightBrand.color[colorName] = light;
      if (dark !== void 0) darkBrand.color[colorName] = dark;
    }
  }
  return {
    light: new Brand(lightBrand, brandDir, projectDir),
    dark: new Brand(darkBrand, brandDir, projectDir),
    enablesDarkMode: brandHasDarkMode(unifiedBrand)
  };
}
var Brand, getFavicon, ensureLeadingSlashIfNotExternal, enablesDarkMode;
var init_brand = __esm({
  "core/brand/brand.ts"() {
    init_schema_types();
    init_error2();
    init_path();
    init_log2();
    init_color_names();
    init_url();
    init_path2();
    Brand = class {
      constructor(brand, brandDir, projectDir) {
        this.brand = brand;
        this.data = Zod.BrandSingle.parse(brand);
        this.brandDir = brandDir;
        this.projectDir = projectDir;
        this.processedData = this.processData(this.data);
      }
      data;
      brandDir;
      projectDir;
      processedData;
      processData(data3) {
        const color = {};
        for (const colorName of Object.keys(data3.color?.palette ?? {})) {
          color[colorName] = this.getColor(colorName);
        }
        for (const colorName of Object.keys(data3.color ?? {})) {
          if (colorName === "palette") {
            continue;
          }
          color[colorName] = this.getColor(colorName);
        }
        const typography = {};
        const base3 = this.getFont("base");
        if (base3) {
          typography.base = base3;
        }
        const headings = this.getFont("headings");
        if (headings) {
          typography.headings = headings;
        }
        const link2 = data3.typography?.link;
        if (link2) {
          typography.link = link2;
        }
        let monospace = this.getFont("monospace");
        let monospaceInline = this.getFont("monospace-inline");
        let monospaceBlock = this.getFont("monospace-block");
        if (monospace) {
          if (typeof monospace === "string") {
            monospace = { family: monospace };
          }
          typography.monospace = monospace;
        }
        if (monospaceInline && typeof monospaceInline === "string") {
          monospaceInline = { family: monospaceInline };
        }
        if (monospaceBlock && typeof monospaceBlock === "string") {
          monospaceBlock = { family: monospaceBlock };
        }
        if (typeof monospace === "string") {
          throw new InternalError("should never happen");
        }
        if (typeof monospaceInline === "string") {
          throw new InternalError("should never happen");
        }
        if (typeof monospaceBlock === "string") {
          throw new InternalError("should never happen");
        }
        if (monospace || monospaceInline) {
          typography["monospace-inline"] = {
            ...monospace ?? {},
            ...monospaceInline ?? {}
          };
        }
        if (monospaceBlock) {
          if (typeof monospaceBlock === "string") {
            monospaceBlock = { family: monospaceBlock };
          }
        }
        if (monospace || monospaceBlock) {
          typography["monospace-block"] = {
            ...monospace ?? {},
            ...monospaceBlock ?? {}
          };
        }
        const logo = { images: {} };
        for (const size of Zod.BrandNamedLogo.options) {
          const v4 = this.getLogo(size);
          if (v4) {
            logo[size] = v4;
          }
        }
        for (const [key, value] of Object.entries(data3.logo?.images ?? {})) {
          logo.images[key] = this.resolvePath(value);
        }
        return {
          color,
          typography,
          logo
        };
      }
      // semantics of name resolution for colors:
      // - if the name is in the "palette" key, use that value as they key for a recursive call (so color names can be aliased or redefined away from scss defaults)
      // - if the name is a default color name, call getColor recursively (so defaults can use named values)
      // - otherwise, assume it's a color value and return it
      getColor(name2, quiet = false) {
        const seenValues = /* @__PURE__ */ new Set();
        do {
          if (seenValues.has(name2)) {
            throw new Error(
              `Circular reference in _brand.yml color definitions: ${Array.from(seenValues).join(
                " -> "
              )}`
            );
          }
          seenValues.add(name2);
          if (this.data.color?.palette?.[name2]) {
            name2 = this.data.color.palette[name2];
          } else if (Zod.BrandNamedThemeColor.options.includes(
            name2
          ) && this.data.color?.[name2]) {
            name2 = this.data.color[name2];
          } else {
            if (!isCssColorName(name2) && !quiet) {
              warnOnce(
                `"${name2}" is not a valid CSS color name.
This might cause SCSS compilation to fail, or the color to have no effect.`
              );
            }
            return name2;
          }
        } while (seenValues.size < 100);
        throw new Error(
          "Recursion depth exceeded 100 in _brand.yml color definitions"
        );
      }
      getFont(name2) {
        if (!this.data.typography) {
          return void 0;
        }
        const typography = this.data.typography;
        switch (name2) {
          case "base":
            return typography.base;
          case "headings":
            return typography.headings;
          case "link":
            return typography.link;
          case "monospace":
            return typography.monospace;
          case "monospace-inline":
            return typography["monospace-inline"];
          case "monospace-block":
            return typography["monospace-block"];
        }
        return void 0;
      }
      getFontResources(name2) {
        if (name2 === "fonts") {
          throw new Error(
            "'fonts' is a reserved name in _brand.yml typography definitions"
          );
        }
        if (!this.data.typography) {
          return [];
        }
        const typography = this.data.typography;
        const fonts = typography.fonts;
        return fonts ?? [];
      }
      resolvePath(entry) {
        const pathPrefix = relative4(this.projectDir, this.brandDir);
        if (typeof entry === "string") {
          return { path: isExternalPath(entry) ? entry : join4(pathPrefix, entry) };
        }
        return {
          ...entry,
          path: isExternalPath(entry.path) ? entry.path : join4(pathPrefix, entry.path)
        };
      }
      getLogoResource(name2) {
        const entry = this.data.logo?.images?.[name2];
        if (!entry) {
          return this.resolvePath(name2);
        }
        return this.resolvePath(entry);
      }
      getLogo(name2) {
        const entry = this.data.logo?.[name2];
        if (!entry) {
          return void 0;
        }
        return this.getLogoResource(entry);
      }
    };
    getFavicon = (brand) => {
      const logoInfo = brand.getLogo("small");
      if (!logoInfo) {
        return void 0;
      }
      return logoInfo.path;
    };
    ensureLeadingSlashIfNotExternal = (path3) => isExternalPath(path3) ? path3 : ensureLeadingSlash(path3);
    enablesDarkMode = (x3) => typeof x3 === "object" && x3?.dark;
  }
});

// project/project-shared.ts
function projectExcludeDirs(context) {
  const outputDir = projectOutputDir(context);
  if (outputDir) {
    return [outputDir];
  } else {
    return [];
  }
}
function projectFormatOutputDir(format14, context, type4) {
  const projOutputDir = projectOutputDir(context);
  if (type4.formatOutputDirectory) {
    const formatOutputDir = type4.formatOutputDirectory(format14);
    if (formatOutputDir) {
      return join4(projOutputDir, formatOutputDir);
    } else {
      return projOutputDir;
    }
  } else {
    return projOutputDir;
  }
}
function projectOutputDir(context) {
  let outputDir = context.config?.project[kProjectOutputDir];
  if (outputDir) {
    if (!isAbsolute4(outputDir)) {
      outputDir = join4(context.dir, outputDir);
    }
  } else {
    outputDir = context.dir;
  }
  if (existsSync2(outputDir)) {
    return normalizePath(outputDir);
  } else {
    return outputDir;
  }
}
function hasProjectOutputDir(context) {
  return !!context.config?.project[kProjectOutputDir];
}
function isProjectInputFile(path3, context) {
  if (existsSync2(path3)) {
    const renderPath = normalizePath(path3);
    return context.files.input.map((file) => normalizePath(file)).includes(
      renderPath
    );
  } else {
    return false;
  }
}
function projectConfigFile(dir) {
  return ["_quarto.yml", "_quarto.yaml"].map((file) => join4(dir, file)).find(existsSync1);
}
function projectVarsFile(dir) {
  return ["_variables.yml", "_variables.yaml"].map((file) => join4(dir, file)).find(existsSync1);
}
function projectOffset(context, input) {
  const projDir = normalizePath(context.dir);
  const inputDir = normalizePath(dirname4(input));
  const offset3 = relative4(inputDir, projDir) || ".";
  return pathWithForwardSlashes(offset3);
}
function toInputRelativePaths(type4, baseDir, inputDir, collection, ignoreResources) {
  const existsCache = /* @__PURE__ */ new Map();
  const resourceIgnoreFields = ignoreResources || ignoreFieldsForProjectType(type4) || [];
  const offset3 = relative4(inputDir, baseDir);
  const fixup = (value) => {
    if (!existsCache.has(value)) {
      const projectPath = join4(baseDir, value);
      try {
        if (existsSync2(projectPath)) {
          existsCache.set(
            value,
            pathWithForwardSlashes(join4(offset3, value))
          );
        } else {
          existsCache.set(value, value);
        }
      } catch {
        existsCache.set(value, value);
      }
    }
    return existsCache.get(value);
  };
  const inner = (collection2, parentKey) => {
    if (Array.isArray(collection2)) {
      for (let index2 = 0; index2 < collection2.length; ++index2) {
        const value = collection2[index2];
        if (Array.isArray(value) || value instanceof Object) {
          inner(value);
        } else if (typeof value === "string") {
          if (value.length > 0 && !isAbsolute4(value)) {
            collection2[index2] = fixup(value);
          }
        }
      }
    } else {
      for (const index2 of Object.keys(collection2)) {
        const value = collection2[index2];
        if (parentKey === kHtmlMathMethod && index2 === "method" || resourceIgnoreFields.includes(index2)) {
        } else if (Array.isArray(value) || value instanceof Object) {
          inner(value, index2);
        } else if (typeof value === "string") {
          if (value.length > 0 && !isAbsolute4(value)) {
            collection2[index2] = fixup(value);
          }
        }
      }
    }
  };
  inner(collection);
  return collection;
}
function ignoreFieldsForProjectType(type4) {
  const resourceIgnoreFields = type4 ? ["project"].concat(
    type4.resourceIgnoreFields ? type4.resourceIgnoreFields() : []
  ) : [];
  return resourceIgnoreFields;
}
function projectIsWebsite(context) {
  if (context) {
    const projType = projectType(context.config?.project?.[kProjectType]);
    return projectTypeIsWebsite(projType);
  } else {
    return false;
  }
}
function projectIsManuscript(context) {
  if (context) {
    const projType = projectType(context.config?.project?.[kProjectType]);
    return projType.type === kManuscriptType;
  } else {
    return false;
  }
}
function projectPreviewServe(context) {
  return context?.config?.project?.preview?.serve;
}
function projectIsServeable(context) {
  return projectIsWebsite(context) || projectIsManuscript(context) || !!projectPreviewServe(context);
}
function projectTypeIsWebsite(projType) {
  return projType.type === kWebsite || projType.inheritsType === kWebsite;
}
function projectIsBook(context) {
  if (context) {
    const projType = projectType(context.config?.project?.[kProjectType]);
    return projType.type === "book";
  } else {
    return false;
  }
}
function deleteProjectMetadata(metadata) {
  const projType = projectType(
    metadata.project?.[kProjectType]
  );
  if (projType.metadataFields) {
    for (const field of projType.metadataFields().concat("project")) {
      if (typeof field === "string") {
        delete metadata[field];
      } else {
        for (const key of Object.keys(metadata)) {
          if (field.test(key)) {
            delete metadata[key];
          }
        }
      }
    }
  }
  delete metadata.project;
}
function normalizeFormatYaml(yamlFormat) {
  if (yamlFormat) {
    if (typeof yamlFormat === "string") {
      yamlFormat = {
        [yamlFormat]: {}
      };
    } else if (typeof yamlFormat === "object") {
      const formats2 = Object.keys(yamlFormat);
      for (const format14 of formats2) {
        if (yamlFormat[format14] === "default") {
          yamlFormat[format14] = {};
        }
      }
    }
  }
  return yamlFormat || {};
}
async function directoryMetadataForInputFile(project, inputDir) {
  const projectDir = project.dir;
  const metadataFile = (dir) => {
    return ["_metadata.yml", "_metadata.yaml"].map((file) => join4(dir, file)).find(existsSync1);
  };
  const relativePath = relative4(projectDir, inputDir);
  const dirs = relativePath.split(SEP_PATTERN);
  let config2 = {};
  let currentDir = projectDir;
  const frontMatterSchema = await getFrontMatterSchema();
  for (let i6 = 0; i6 < dirs.length; i6++) {
    const dir = dirs[i6];
    currentDir = join4(currentDir, dir);
    const file = metadataFile(currentDir);
    if (file) {
      const errMsg = "Directory metadata validation failed for " + file + ".";
      const yaml = await readAndValidateYamlFromFile(
        file,
        frontMatterSchema,
        errMsg
      ) || {};
      if (yaml.format) {
        yaml.format = normalizeFormatYaml(yaml.format);
      }
      config2 = mergeConfigs(
        config2,
        toInputRelativePaths(
          projectType(project?.config?.project?.[kProjectType]),
          currentDir,
          inputDir,
          yaml
        )
      );
    }
  }
  return config2;
}
async function projectResolveCodeCellsForFile(project, engine, file, markdown, force) {
  const cache3 = ensureFileInformationCache(project, file);
  if (!force && cache3.codeCells) {
    return cache3.codeCells || [];
  }
  if (!markdown) {
    markdown = await mdForFile(project, engine, file);
  }
  const result2 = [];
  const fileStack = [];
  const inner = async (file2, cells) => {
    if (fileStack.includes(file2)) {
      throw new Error(
        "Circular include detected:\n  " + fileStack.join(" ->\n  ")
      );
    }
    fileStack.push(file2);
    for (const cell of cells) {
      if (typeof cell.cell_type === "string") {
        continue;
      }
      if (cell.cell_type.language === "_directive") {
        const directiveCell = cell.cell_type;
        if (directiveCell.name !== "include") {
          continue;
        }
        const arg = directiveCell.shortcode.params[0];
        const paths = arg.startsWith("/") ? [project.dir, arg] : [project.dir, relative4(project.dir, dirname4(file2)), arg];
        const innerFile = join4(...paths);
        await inner(
          innerFile,
          (await breakQuartoMd(
            await mdForFile(project, engine, innerFile)
          )).cells
        );
      }
      if (cell.cell_type.language !== "_directive") {
        const cellOptions = partitionCellOptionsText(
          cell.cell_type.language,
          cell.sourceWithYaml ?? cell.source
        );
        const metadata = cellOptions.yaml ? parse3(cellOptions.yaml.value, {
          schema: QuartoJSONSchema2
        }) : {};
        const lineLocator = mappedIndexToLineCol(cell.sourceVerbatim);
        result2.push({
          start: lineLocator(0).line,
          end: lineLocator(cell.sourceVerbatim.value.length - 1).line,
          file: file2,
          source: normalizeNewlines(cell.source.value),
          language: cell.cell_type.language,
          metadata
        });
      }
    }
    fileStack.pop();
  };
  await inner(file, (await breakQuartoMd(markdown)).cells);
  cache3.codeCells = result2;
  return result2;
}
async function projectFileMetadata(project, file, force) {
  const cache3 = ensureFileInformationCache(project, file);
  if (!force && cache3.metadata) {
    return cache3.metadata;
  }
  const { engine } = await project.fileExecutionEngineAndTarget(file);
  const markdown = await mdForFile(project, engine, file);
  const metadata = readYamlFromMarkdown(markdown.value);
  cache3.metadata = metadata;
  return metadata;
}
async function projectResolveFullMarkdownForFile(project, engine, file, markdown, force) {
  const cache3 = ensureFileInformationCache(project, file);
  if (!force && cache3.fullMarkdown) {
    return cache3.fullMarkdown;
  }
  const temp = createTempContext();
  if (!markdown) {
    markdown = await mdForFile(project, engine, file);
  }
  const options = {
    name: "",
    temp,
    stage: "pre-engine",
    format: void 0,
    markdown,
    context: {
      project,
      target: {
        source: file
      }
    },
    flags: {}
  };
  try {
    const result2 = await expandIncludes(markdown, options, file);
    cache3.fullMarkdown = result2;
    cache3.includeMap = options.state?.include.includes;
    return result2;
  } finally {
    temp.cleanup();
  }
}
async function projectResolveBrand(project, fileName) {
  async function loadSingleBrand(brandPath) {
    const brand = await readAndValidateYamlFromFile(
      brandPath,
      refSchema("brand-single", "Format-independent brand configuration."),
      "Brand validation failed for " + brandPath + "."
    );
    return new Brand(brand, dirname4(brandPath), project.dir);
  }
  async function loadUnifiedBrand(brandPath) {
    const brand = await readAndValidateYamlFromFile(
      brandPath,
      refSchema("brand-unified", "Format-independent brand configuration."),
      "Brand validation failed for " + brandPath + "."
    );
    return splitUnifiedBrand(brand, dirname4(brandPath), project.dir);
  }
  function resolveBrandPath(brandPath, dir = dirname4(fileName)) {
    let resolved = "";
    if (brandPath.startsWith("/")) {
      resolved = join4(project.dir, brandPath);
    } else {
      resolved = join4(dir, brandPath);
    }
    return resolved;
  }
  if (fileName === void 0) {
    if (project.brandCache) {
      return project.brandCache.brand;
    }
    project.brandCache = {};
    let fileNames = [
      "_brand.yml",
      "_brand.yaml",
      "_brand/_brand.yml",
      "_brand/_brand.yaml"
    ].map((file) => join4(project.dir, file));
    const brand = project?.config?.brand ?? project?.config?.project.brand;
    if (brand === false) {
      project.brandCache.brand = void 0;
      return project.brandCache.brand;
    }
    if (typeof brand === "object" && brand && ("light" in brand || "dark" in brand)) {
      project.brandCache.brand = {
        light: brand.light ? await loadSingleBrand(resolveBrandPath(brand.light, project.dir)) : void 0,
        dark: brand.dark ? await loadSingleBrand(resolveBrandPath(brand.dark, project.dir)) : void 0,
        enablesDarkMode: !!brand.dark
      };
      return project.brandCache.brand;
    }
    if (typeof brand === "string") {
      fileNames = [join4(project.dir, brand)];
    }
    for (const brandPath of fileNames) {
      if (!existsSync2(brandPath)) {
        continue;
      }
      project.brandCache.brand = await loadUnifiedBrand(brandPath);
    }
    return project.brandCache.brand;
  } else {
    const metadata = await project.fileMetadata(fileName);
    if (metadata.brand === void 0) {
      return project.resolveBrand();
    }
    const brand = Zod.BrandPathBoolLightDark.parse(metadata.brand);
    if (brand === false) {
      return void 0;
    }
    if (brand === true) {
      return project.resolveBrand();
    }
    const fileInformation = ensureFileInformationCache(project, fileName);
    if (fileInformation.brand) {
      return fileInformation.brand;
    }
    if (typeof brand === "string") {
      fileInformation.brand = await loadUnifiedBrand(resolveBrandPath(brand));
      return fileInformation.brand;
    } else {
      assert7(typeof brand === "object");
      if ("light" in brand || "dark" in brand) {
        let light, dark;
        if (typeof brand.light === "string") {
          light = await loadSingleBrand(resolveBrandPath(brand.light));
        } else if (brand.light) {
          light = new Brand(
            brand.light,
            dirname4(fileName),
            project.dir
          );
        }
        if (typeof brand.dark === "string") {
          dark = await loadSingleBrand(resolveBrandPath(brand.dark));
        } else if (brand.dark) {
          dark = new Brand(
            brand.dark,
            dirname4(fileName),
            project.dir
          );
        }
        fileInformation.brand = { light, dark, enablesDarkMode: !!dark };
      } else {
        fileInformation.brand = splitUnifiedBrand(
          brand,
          dirname4(fileName),
          project.dir
        );
      }
      return fileInformation.brand;
    }
  }
}
function cleanupFileInformationCache(project) {
  for (const key of [...project.fileInformationCache.keys()]) {
    project.fileInformationCache.invalidateForFile(key);
  }
}
async function withProjectCleanup(project, fn) {
  try {
    return await fn(project);
  } finally {
    project.cleanup();
  }
}
var mdForFile, ensureFileInformationCache, FileInformationCacheMap;
var init_project_shared = __esm({
  async "project/project-shared.ts"() {
    init_fs();
    init_path();
    init_constants6();
    init_config2();
    init_front_matter();
    init_path2();
    init_validated_yaml2();
    init_types4();
    init_project_types();
    init_website_constants();
    init_file();
    init_manuscript_types();
    await init_base();
    init_mapped_text2();
    init_temp();
    init_break_quarto_md();
    init_partition_cell_options();
    init_yaml();
    init_mapped_text();
    init_text();
    init_yaml();
    init_common4();
    init_schema_types();
    init_brand();
    init_asserts();
    mdForFile = async (_project, engine, file) => {
      if (engine) {
        return await engine.markdownForFile(file);
      } else {
        return Promise.resolve(mappedStringFromFile(file));
      }
    };
    ensureFileInformationCache = (project, file) => {
      if (!project.fileInformationCache) {
        project.fileInformationCache = new FileInformationCacheMap();
      }
      assert7(
        project.fileInformationCache instanceof Map,
        JSON.stringify(project.fileInformationCache)
      );
      if (!project.fileInformationCache.has(file)) {
        project.fileInformationCache.set(file, {});
      }
      return project.fileInformationCache.get(file);
    };
    FileInformationCacheMap = class extends Map {
      get(key) {
        return super.get(normalizePath(key));
      }
      has(key) {
        return super.has(normalizePath(key));
      }
      set(key, value) {
        return super.set(normalizePath(key), value);
      }
      delete(key) {
        return super.delete(normalizePath(key));
      }
      // Note: Iterator methods (keys(), entries(), forEach(), [Symbol.iterator])
      // return normalized keys as stored. Code iterating over the cache sees
      // normalized paths, which is consistent with how keys are stored.
      // Removes a cache entry and cleans up any associated transient files.
      // In preview mode, this should be used instead of delete() to ensure
      // transient notebooks (.quarto_ipynb) are removed from disk before the
      // cache entry is dropped. Without this, the collision-avoidance logic
      // in jupyter.ts target() creates numbered variants on each re-render.
      invalidateForFile(key) {
        const existing = this.get(key);
        if (existing?.target?.data) {
          const data3 = existing.target.data;
          if (data3.transient && existing.target.input) {
            safeRemoveSync(existing.target.input);
          }
        }
        this.delete(key);
      }
      // Returns this instance (shared reference) rather than a copy.
      // This is intentional: in preview mode, project context is cloned for
      // each render but the cache must be shared so invalidations persist.
      clone() {
        return this;
      }
    };
  }
});

// project/engine-project-context.ts
function engineProjectContext(context) {
  const project = {
    // Core properties
    dir: context.dir,
    isSingleFile: context.isSingleFile,
    config: context.config ? {
      engines: context.config.engines,
      project: context.config.project ? {
        "output-dir": context.config.project["output-dir"]
      } : void 0
    } : void 0,
    fileInformationCache: context.fileInformationCache,
    // Path utilities
    getOutputDirectory: () => {
      return projectOutputDir(context);
    },
    // Core methods
    resolveFullMarkdownForFile: (engine, file, markdown, force) => context.resolveFullMarkdownForFile(engine, file, markdown, force)
  };
  return project;
}
var init_engine_project_context = __esm({
  async "project/engine-project-context.ts"() {
    await init_project_shared();
  }
});

// execute/engine.ts
function checkEngineVersionRequirement(engine) {
  if (engine.quartoRequired) {
    const ourVersion = quartoConfig.version();
    try {
      if (!satisfies(ourVersion, engine.quartoRequired)) {
        throw new Error(
          `Execution engine '${engine.name}' requires Quarto ${engine.quartoRequired}, but you have ${ourVersion}. Please upgrade Quarto to use this engine.`
        );
      }
    } catch (e5) {
      if (e5 instanceof Error && e5.message.includes("Invalid")) {
        throw new Error(
          `Execution engine '${engine.name}' has invalid version constraint: ${engine.quartoRequired}`
        );
      }
      throw e5;
    }
  }
}
function executionEngines() {
  return [...kEngines.values()];
}
function executionEngine(name2) {
  return kEngines.get(name2);
}
function registerExecutionEngine(engine) {
  if (kEngines.has(engine.name)) {
    throw new Error(`Execution engine ${engine.name} already registered`);
  }
  checkEngineVersionRequirement(engine);
  kEngines.set(engine.name, engine);
  if (engine.init) {
    engine.init(getQuartoAPI());
  }
}
function executionEngineKeepMd(context) {
  const { input } = context.target;
  const baseFormat = context.format.identifier[kBaseFormat] || "html";
  const keepSuffix = `.${baseFormat}.md`;
  if (!input.endsWith(keepSuffix)) {
    const [dir, stem] = dirAndStem(input);
    return join4(dir, stem + keepSuffix);
  }
}
function executionEngineIntermediateFiles(engine, input) {
  const files = [];
  const [dir, stem] = dirAndStem(input);
  files.push(
    ...pandocBuiltInFormats().flatMap((format14) => [`-${format14}.md`, `.${format14}.md`]).map((suffix) => join4(dir, stem + suffix))
  );
  const engineKeepFiles = engine.intermediateFiles ? engine.intermediateFiles(input) : void 0;
  if (engineKeepFiles) {
    return files.concat(engineKeepFiles);
  } else {
    return files;
  }
}
function engineValidExtensions() {
  return uniq(
    executionEngines().flatMap((engine) => engine.validExtensions())
  );
}
function markdownExecutionEngine(project, markdown, reorderedEngines, flags) {
  const result2 = partitionYamlFrontMatter(markdown);
  if (result2) {
    let yaml = readYamlFromMarkdown(result2.yaml);
    if (yaml) {
      yaml = mergeConfigs(yaml, flags?.metadata);
      for (const [_3, engine] of reorderedEngines) {
        if (yaml[engine.name]) {
          return engine.launch(engineProjectContext(project));
        }
        const format14 = metadataAsFormat(yaml);
        if (format14.execute?.[kEngine] === engine.name) {
          return engine.launch(engineProjectContext(project));
        }
      }
    }
  }
  const languagesWithClassesMap = languagesWithClasses(markdown);
  for (const [language, firstClass] of languagesWithClassesMap) {
    let bestEngine;
    let bestScore = -Infinity;
    for (const [_3, engine] of reorderedEngines) {
      const claim = engine.claimsLanguage(language, firstClass);
      if (claim === false) {
        continue;
      }
      const score = claim === true ? 1 : claim;
      if (score > bestScore) {
        bestScore = score;
        bestEngine = engine;
      }
    }
    if (bestEngine) {
      return bestEngine.launch(engineProjectContext(project));
    }
  }
  const handlerLanguagesVal = languages();
  for (const language of languagesWithClassesMap.keys()) {
    if (language !== "ojs" && !handlerLanguagesVal.includes(language)) {
      return jupyterEngineDiscovery.launch(engineProjectContext(project));
    }
  }
  return markdownEngineDiscovery.launch(engineProjectContext(project));
}
async function resolveEngines(project) {
  if (!enginesRegistered) {
    enginesRegistered = true;
    for (const engine of kStandardEngines) {
      registerExecutionEngine(engine);
    }
  }
  const userSpecifiedOrder = [];
  const projectEngines = project.config?.engines;
  for (const engine of projectEngines ?? []) {
    if (typeof engine === "object") {
      try {
        const extEngine = (await import(toFileUrl4(engine.path).href)).default;
        if (!extEngine) {
          throw new Error(
            `Engine module must export a default ExecutionEngineDiscovery object. Check that your engine file exports 'export default yourEngineDiscovery;'`
          );
        }
        const missing = [];
        if (!extEngine.name) missing.push("name");
        if (!extEngine.launch) missing.push("launch");
        if (!extEngine.claimsLanguage) missing.push("claimsLanguage");
        if (missing.length > 0) {
          throw new Error(
            `Engine is missing required properties: ${missing.join(", ")}. Ensure your engine implements the ExecutionEngineDiscovery interface.`
          );
        }
        checkEngineVersionRequirement(extEngine);
        userSpecifiedOrder.push(extEngine.name);
        kEngines.set(extEngine.name, extEngine);
        if (extEngine.init) {
          extEngine.init(getQuartoAPI());
        }
      } catch (err2) {
        throw new Error(
          `Failed to import engine from ${engine.path}: ${err2.message || "Unknown error"}`
        );
      }
    } else {
      userSpecifiedOrder.push(engine);
    }
  }
  for (const key of userSpecifiedOrder) {
    if (!kEngines.has(key)) {
      throw new Error(
        `'${key}' was specified in the list of engines in the project settings but it is not a valid engine. Available engines are ${Array.from(kEngines.keys()).join(", ")}`
      );
    }
  }
  const reorderedEngines = /* @__PURE__ */ new Map();
  for (const key of userSpecifiedOrder) {
    reorderedEngines.set(key, kEngines.get(key));
  }
  for (const [key, value] of kEngines) {
    if (!reorderedEngines.has(key)) {
      reorderedEngines.set(key, value);
    }
  }
  return reorderedEngines;
}
async function fileExecutionEngine(file, flags, project) {
  const engines = await resolveEngines(project);
  const ext = extname4(file).toLowerCase();
  if (!executionEngines().some(
    (engine) => engine.validExtensions().includes(ext)
  )) {
    return void 0;
  }
  for (const [_3, engine] of engines) {
    if (engine.claimsFile(file, ext)) {
      return engine.launch(engineProjectContext(project));
    }
  }
  if (kMdExtensions.includes(ext) || kQmdExtensions.includes(ext)) {
    const markdown = await project.resolveFullMarkdownForFile(void 0, file);
    try {
      return markdownExecutionEngine(
        project,
        markdown ? markdown.value : Deno.readTextFileSync(file),
        engines,
        flags
      );
    } catch (error2) {
      if (!(error2 instanceof Error)) throw error2;
      if (error2.name === "YAMLError") {
        error2.message = `${file}:
${error2.message}`;
      }
      throw error2;
    }
  } else {
    return void 0;
  }
}
async function fileExecutionEngineAndTarget(file, flags, project) {
  const cached = ensureFileInformationCache(project, file);
  if (cached && cached.engine && cached.target) {
    return { engine: cached.engine, target: cached.target };
  }
  const engine = await fileExecutionEngine(file, flags, project);
  if (!engine) {
    throw new Error("Can't determine execution engine for " + file);
  }
  const markdown = await project.resolveFullMarkdownForFile(engine, file);
  const target = await engine.target(file, flags?.quiet, markdown);
  if (!target) {
    throw new Error("Can't determine execution target for " + file);
  }
  cached.engine = engine;
  cached.target = target;
  return { engine, target };
}
function engineIgnoreDirs() {
  const ignoreDirs = ["node_modules"];
  executionEngines().forEach((engine) => {
    if (engine && engine.ignoreDirs) {
      const ignores = engine.ignoreDirs();
      if (ignores) {
        ignoreDirs.push(...ignores);
      }
    }
  });
  return ignoreDirs;
}
function engineIgnoreGlobs() {
  return engineIgnoreDirs().map((ignore3) => `**/${ignore3}/**`);
}
function projectIgnoreGlobs(dir) {
  return engineIgnoreGlobs().concat(
    gitignoreEntries(dir).map((ignore3) => `**/${ignore3}**`)
  );
}
var kEngines, kStandardEngines, enginesRegistered;
var init_engine = __esm({
  async "execute/engine.ts"() {
    init_path();
    init_lodash();
    init_yaml();
    init_path2();
    init_metadata();
    init_constants6();
    init_rmd();
    init_jupyter2();
    init_markdown();
    init_types3();
    init_pandoc_partition();
    await init_base();
    init_config2();
    init_pandoc_formats();
    init_project_gitignore();
    await init_project_shared();
    await init_engine_project_context();
    init_api2();
    init_mod6();
    init_quarto();
    kEngines = /* @__PURE__ */ new Map();
    kStandardEngines = [
      knitrEngineDiscovery,
      jupyterEngineDiscovery,
      markdownEngineDiscovery
    ];
    enginesRegistered = false;
  }
});

// core/copy.ts
function copyTo(src2, dest, options = {
  overwrite: true
}) {
  src2 = resolve4(src2);
  dest = resolve4(dest);
  if (src2 === dest) {
    throw new Error("Source and destination cannot be the same.");
  }
  const srcStat = Deno.lstatSync(src2);
  if (srcStat.isDirectory && isSubdir2(src2, dest)) {
    throw new Error(
      `Cannot copy '${src2}' to a subdirectory of itself, '${dest}'.`
    );
  }
  if (srcStat.isSymlink) {
    copySymlinkSync2(src2, dest, options);
  } else if (srcStat.isDirectory) {
    copyDirSync2(src2, dest, options);
  } else if (srcStat.isFile) {
    copyFileSync2(src2, dest, options);
  }
}
function copyMinimal(srcDir, destDir, skip, filter3) {
  skip = [...skip || [], /\.DS_Store/];
  const srcFiles = [];
  for (const walk5 of walkSync(
    srcDir,
    {
      includeDirs: false,
      followSymlinks: false,
      skip
    }
  )) {
    const srcFile = walk5.path;
    if (filter3 && !filter3(srcFile)) {
      continue;
    }
    srcFiles.push(srcFile);
  }
  for (const srcFile of srcFiles) {
    if (!existsSync2(srcFile)) {
      continue;
    }
    const destFile = join4(destDir, relative4(srcDir, srcFile));
    copyFileIfNewer(srcFile, destFile);
  }
}
function copyFileIfNewer(srcFile, destFile) {
  const doCopy = () => {
    copyTo(srcFile, destFile, {
      overwrite: true,
      preserveTimestamps: true
    });
  };
  ensureDirSync(dirname4(destFile));
  try {
    if (existsSync2(destFile)) {
      const srcInfo = Deno.statSync(srcFile);
      const destInfo = Deno.statSync(destFile);
      if (!srcInfo.mtime || !destInfo.mtime || destInfo.mtime < srcInfo.mtime) {
        doCopy();
      }
    } else {
      doCopy();
    }
  } catch {
    doCopy();
  }
}
function copyFileSync2(src2, dest, options) {
  ensureValidCopySync2(src2, dest, options);
  if (existsSync2(dest)) {
    safeRemoveSync(dest);
  }
  Deno.copyFileSync(src2, dest);
  if (options.preserveTimestamps) {
    const statInfo = Deno.statSync(src2);
    if (statInfo.atime && statInfo.mtime) {
      Deno.utimeSync(dest, statInfo.atime, statInfo.mtime);
    }
  }
}
function copyDirSync2(src2, dest, options) {
  const destStat = ensureValidCopySync2(src2, dest, {
    ...options,
    isFolder: true
  });
  if (!destStat) {
    ensureDirSync(dest);
  }
  if (options.preserveTimestamps) {
    const srcStatInfo = Deno.statSync(src2);
    if (srcStatInfo.atime && srcStatInfo.mtime) {
      Deno.utimeSync(dest, srcStatInfo.atime, srcStatInfo.mtime);
    }
  }
  for (const entry of Deno.readDirSync(src2)) {
    const srcPath = join4(src2, entry.name);
    const destPath = join4(dest, basename4(srcPath));
    if (entry.isSymlink) {
      copySymlinkSync2(srcPath, destPath, options);
    } else if (entry.isDirectory) {
      copyDirSync2(srcPath, destPath, options);
    } else if (entry.isFile) {
      copyFileSync2(srcPath, destPath, options);
    }
  }
}
function copySymlinkSync2(src2, dest, options) {
  ensureValidCopySync2(src2, dest, options);
  if (existsSync2(dest)) {
    safeRemoveSync(dest);
  }
  const originSrcFilePath = Deno.readLinkSync(src2);
  const type4 = getFileInfoType2(Deno.lstatSync(src2));
  if (isWindows4) {
    Deno.symlinkSync(originSrcFilePath, dest, {
      type: type4 === "dir" ? "dir" : "file"
    });
  } else {
    Deno.symlinkSync(originSrcFilePath, dest);
  }
  if (options.preserveTimestamps) {
    const statInfo = Deno.lstatSync(src2);
    if (statInfo.atime && statInfo.mtime) {
      Deno.utimeSync(dest, statInfo.atime, statInfo.mtime);
    }
  }
}
function ensureValidCopySync2(src2, dest, options) {
  let destStat;
  try {
    destStat = Deno.lstatSync(dest);
  } catch (err2) {
    if (err2 instanceof Deno.errors.NotFound) {
      return;
    }
    throw err2;
  }
  if (options.isFolder && !destStat.isDirectory) {
    throw new Error(
      `Cannot overwrite non-directory '${dest}' with directory '${src2}'.`
    );
  }
  if (!options.overwrite) {
    throw new Error(`'${dest}' already exists.`);
  }
  return destStat;
}
var init_copy5 = __esm({
  "core/copy.ts"() {
    init_path();
    init_fs();
    init_platform();
  }
});

// command/render/template.ts
function readPartials(metadata, inputDir) {
  if (typeof metadata?.[kTemplatePartials] === "string") {
    metadata[kTemplatePartials] = [metadata[kTemplatePartials]];
  }
  const result2 = metadata?.[kTemplatePartials] || [];
  inputDir = inputDir ? normalizePath(inputDir) : void 0;
  const resolvePath = (path3) => {
    if (!inputDir || isAbsolute4(path3)) {
      return path3;
    } else {
      return join4(inputDir, path3);
    }
  };
  return result2.flatMap((path3) => {
    const result3 = [];
    for (const walk5 of expandGlobSync(resolvePath(path3))) {
      result3.push(walk5.path);
    }
    if (!isGlob3(path3) && result3.length === 0) {
      throw new Error(
        `Template partial ${path3} was not found. Please confirm that the path to the file is correct.`
      );
    }
    return result3;
  });
}
function resolveTemplatePartialPaths(metadata, inputDir, project) {
  if (typeof metadata?.[kTemplatePartials] === "string") {
    metadata[kTemplatePartials] = [metadata[kTemplatePartials]];
  }
  const result2 = metadata?.[kTemplatePartials] || [];
  metadata[kTemplatePartials] = result2.map((path3) => {
    if (project && (path3.startsWith("/") || path3.startsWith("\\"))) {
      return join4(project.dir, path3.slice(1));
    } else if (!inputDir || isAbsolute4(path3)) {
      return path3;
    } else {
      if (isAbsolute4(inputDir)) {
        return join4(inputDir, path3);
      } else {
        return join4(Deno.cwd(), inputDir, path3);
      }
    }
  });
}
async function stageTemplate(options, extras, userContext) {
  const stagingDir = options.services.temp.createDir();
  const template2 = "template.patched";
  const stageContext = (dir, template3, context) => {
    if (context) {
      if (context.template) {
        const targetFile = join4(dir, template3);
        copyTo(context.template, targetFile);
        if (!isWindows4) {
          Deno.chmodSync(targetFile, 438);
        }
      }
      if (context.partials) {
        for (const partial of context.partials) {
          copyTo(partial, join4(stagingDir, basename4(partial)));
        }
      }
      return true;
    } else {
      return false;
    }
  };
  const formatStaged = stageContext(
    stagingDir,
    template2,
    extras.templateContext
  );
  const userStaged = await stageContext(stagingDir, template2, userContext);
  if (formatStaged || userStaged) {
    const stagedTemplatePath = join4(stagingDir, template2);
    applyTemplatePatches(stagedTemplatePath, options.format, options.flags);
    return stagedTemplatePath;
  } else {
    return void 0;
  }
}
function cleanTemplatePartialMetadata(metadata, builtIns) {
  const partials = metadata[kTemplatePartials];
  if (partials) {
    const cleansed = partials.filter((part) => builtIns.includes(part));
    if (cleansed.length === 0) {
      delete metadata[kTemplatePartials];
    } else {
      metadata[kTemplatePartials] = cleansed;
    }
  }
}
function applyTemplatePatches(template2, format14, flags) {
  const patches = [];
  if (isHtmlDocOutput(format14.pandoc) || isRevealjsOutput(format14.pandoc)) {
    if ((flags && flags[kSelfContained] || format14.pandoc[kSelfContained] || flags && flags[kEmbedResources] || format14.pandoc[kEmbedResources]) && !format14.render[kSelfContainedMath]) {
      const math = mathConfig(format14, flags);
      if (math) {
        const mathTemplate = math.method === "mathjax" ? mathjaxScript(math.url) : math.method == "katex" ? katexScript(math.url) : "";
        if (mathTemplate) {
          patches.push({
            searchValue: /\$math\$/,
            contents: mathTemplate
          });
        }
      }
    }
  }
  if (patches.length) {
    let templateContents = Deno.readTextFileSync(template2);
    patches.forEach((patch) => {
      templateContents = templateContents.replace(
        patch.searchValue,
        patch.contents
      );
    });
    Deno.writeTextFileSync(template2, templateContents);
  }
}
function mathConfig(format14, flags) {
  if (flags?.mathjax || flags?.katex || flags?.webtex || flags?.gladtex || flags?.mathml) {
    return void 0;
  }
  const math = format14.pandoc[kHtmlMathMethod];
  if (math === void 0 || math === "mathjax") {
    return {
      method: "mathjax",
      url: "https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml-full.js"
    };
  } else if (math === "katex") {
    return {
      method: "katex",
      url: "https://cdn.jsdelivr.net/npm/katex@0.13.11/dist/"
    };
  } else if (isObject(math)) {
    const mathMethod = math;
    if ((mathMethod.method === "mathjax" || mathMethod.method === "katex") && typeof mathMethod.url === "string") {
      return mathMethod;
    }
  }
}
function mathjaxScript(url) {
  return `
  <script>
    (function () {
      var script = document.createElement("script");
      script.type = "text/javascript";
      script.src  = "${url}";
      document.getElementsByTagName("head")[0].appendChild(script);
    })();
  <\/script>
`;
}
function katexScript(url) {
  url = url.trim();
  if (!url.endsWith("/")) {
    url += "/";
  }
  return `
  <script>
    document.addEventListener("DOMContentLoaded", function () {
      var head = document.getElementsByTagName("head")[0];
      var link = document.createElement("link");
      link.rel = "stylesheet";
      link.href = "${url}katex.min.css";
      head.appendChild(link);
      
      function renderMathElements() {
        var mathElements = document.getElementsByClassName("math");
        var macros = [];
        for (var i = 0; i < mathElements.length; i++) {
          var texText = mathElements[i].firstChild;
          if (mathElements[i].tagName == "SPAN") {
            if (window.katex) {
              window.katex.render(texText.data, mathElements[i], {
                displayMode: mathElements[i].classList.contains('display'),
                throwOnError: false,
                macros: macros,
                fleqn: false
              });
            } else {
              console.error("KaTeX has not been loaded correctly, as not found globally.");
            }
          }
        }
      }

      var script = document.createElement("script");
      script.src = "${url}katex.min.js";
      script.onload = renderMathElements;
      
      // Check for RequireJS and AMD detection as it conflicts with KaTeX loading.
      if (typeof require === 'function' && typeof define === 'function' && define.amd) {
        // Disable require.js AMD detection temporarily, as it conflicts with KaTeX loading using CommonJS
        var disableAmdScript = document.createElement("script");
        disableAmdScript.textContent = 'window._amd_backup = window.define.amd; window.define.amd = false;';
        head.appendChild(disableAmdScript);
        
        // overwrite onload to restore Require.js AMD detection
        script.onload = function() {
          // Restore Require.js AMD detection
          window.define.amd = window._amd_backup;
          delete window._amd_backup;
          renderMathElements();
        };
      }

      head.appendChild(script);
    });
  <\/script>
  `;
}
var kPatchedTemplateExt, kTemplatePartials;
var init_template = __esm({
  "command/render/template.ts"() {
    init_path();
    init_constants6();
    init_copy5();
    init_lodash();
    init_format5();
    init_fs();
    init_path2();
    init_glob();
    init_platform();
    kPatchedTemplateExt = ".patched";
    kTemplatePartials = "template-partials";
  }
});

// config/pdf.ts
function bibEngine(defaults, flags) {
  return flags?.natbib ? "natbib" : flags?.biblatex ? "biblatex" : defaults[kCiteMethod] === "natbib" ? "natbib" : defaults[kCiteMethod] == "biblatex" ? "biblatex" : void 0;
}
function pdfEngine(defaults, render2, flags) {
  const pdfEngine3 = flags?.pdfEngine || defaults[kPdfEngine] || "pdflatex";
  const pdfEngineOpts = defaults[kPdfEngineOpts] || [];
  if (defaults[kPdfEngineOpt]) {
    pdfEngineOpts.push(defaults[kPdfEngineOpt]);
  }
  if (flags?.pdfEngineOpts) {
    pdfEngineOpts.push(...flags?.pdfEngineOpts);
  }
  const indexEngine = render2[kLatexMakeIndex];
  const indexEngineOpts = render2[kLatexMakeIndexOpts] || [];
  if (flags?.makeIndexOpts) {
    indexEngineOpts?.push(...flags?.makeIndexOpts);
  }
  const tlmgrOpts = render2[kLatexTlmgrOpts] || [];
  if (flags?.tlmgrOpts) {
    tlmgrOpts?.push(...flags?.tlmgrOpts);
  }
  return {
    pdfEngine: pdfEngine3,
    pdfEngineOpts,
    bibEngine: bibEngine(defaults, flags),
    indexEngine,
    indexEngineOpts,
    tlmgrOpts
  };
}
function isLatexPdfEngine(engine) {
  return ["pdflatex", "xelatex", "lualatex", "latexmk"].includes(
    engine.pdfEngine
  );
}
var init_pdf = __esm({
  "config/pdf.ts"() {
    init_constants6();
  }
});

// command/render/render-paths.ts
function filesDirLibDir(input) {
  return join4(inputFilesDir(input), "libs");
}
function filesDirMediabagDir(input) {
  return join4(inputFilesDir(input), "mediabag");
}
function pandocMetadataPath(path3) {
  return pathWithForwardSlashes(path3);
}
var init_render_paths = __esm({
  "command/render/render-paths.ts"() {
    init_path();
    init_path2();
    init_render();
  }
});

// project/types/book/book-constants.ts
var kBookChapters, kBookAppendix, kBookReferences, kBookRender, kBookOutputFile, kBookDownloads, kBookTools, kBookSearch, kBookItemChapter, kBookItemAppendix, kBookItemPart;
var init_book_constants = __esm({
  "project/types/book/book-constants.ts"() {
    kBookChapters = "chapters";
    kBookAppendix = "appendices";
    kBookReferences = "references";
    kBookRender = "render";
    kBookOutputFile = "output-file";
    kBookDownloads = "downloads";
    kBookTools = "tools";
    kBookSearch = "search";
    kBookItemChapter = "chapter";
    kBookItemAppendix = "appendix";
    kBookItemPart = "part";
  }
});

// core/tex.ts
function texSafeFilename(file) {
  return file.replaceAll(/[ <>()|\:&;#?*'\\\/]/g, "-");
}
var init_tex = __esm({
  "core/tex.ts"() {
  }
});

// project/types/book/book-shared.ts
function bookConfig(name2, project) {
  const book = project?.[kBook];
  if (book) {
    return book[name2];
  } else {
    return void 0;
  }
}
function setBookConfig(name2, value, project) {
  const book = project?.[kBook];
  if (book) {
    book[name2] = value;
  }
}
function isBookIndexPage(target) {
  return target !== void 0 && target.startsWith("index.");
}
function isNumberedChapter(partitioned) {
  if (partitioned?.yaml) {
    const yaml = partitioned?.yaml;
    if (typeof yaml[kTitle] === "string") {
      const parsedTitle = parsePandocTitle(yaml[kTitle]);
      return !parsedTitle.attr?.classes.includes("unnumbered");
    }
  }
  return !partitioned.headingAttr || !partitioned.headingAttr.classes.includes("unnumbered");
}
function isMultiFileBookFormat(format14) {
  const extension = format14.extensions?.book;
  if (extension) {
    return !!extension.multiFile;
  } else {
    return false;
  }
}
function resolveVariables(value, config2) {
  variableRegex.lastIndex = 0;
  return value.replaceAll(variableRegex, (_3, varName) => {
    const vars = config2[kQuartoVarsKey];
    if (vars && vars[varName] !== void 0) {
      return String(vars[varName]);
    } else {
      return `?var:${varName}`;
    }
  });
}
function bookOutputStem(projectDir, config2) {
  const outputFile5 = bookConfig(kBookOutputFile, config2) || bookConfig(kTitle, config2) || basename4(projectDir);
  return texSafeFilename(
    config2 !== void 0 ? resolveVariables(outputFile5, config2) : outputFile5
  );
}
var kBook, kBookCoverImage, kBookCoverImageAlt, variableRegex;
var init_book_shared = __esm({
  "project/types/book/book-shared.ts"() {
    init_constants6();
    init_pandoc_partition();
    init_book_constants();
    init_path();
    init_tex();
    kBook = "book";
    kBookCoverImage = "cover-image";
    kBookCoverImageAlt = "cover-image-alt";
    variableRegex = /{{<\s*var\s+(.*?)\s*>}}/gm;
  }
});

// format/html/format-html-info.ts
function formatHasBootstrap(format14) {
  if (format14 && (isHtmlOutput(format14.pandoc, true) || isHtmlDashboardOutput(format14.identifier["base-format"]))) {
    return hasBootstrapTheme(format14.metadata);
  } else {
    return false;
  }
}
function hasBootstrapTheme(metadata) {
  const theme = metadata[kTheme];
  return theme !== "none" && theme !== "pandoc";
}
function formatDarkMode(format14) {
  const isBootstrap = formatHasBootstrap(format14);
  if (isBootstrap) {
    return darkModeDefault(format14);
  }
  return void 0;
}
function darkModeDefaultMetadata(metadata) {
  if (metadata[kTheme] && typeof metadata[kTheme] === "object") {
    const keys = Object.keys(metadata[kTheme]);
    if (keys.includes("dark")) {
      if (keys[0] === "dark") {
        return true;
      } else {
        return false;
      }
    }
  }
  if (metadata[kBrand] && typeof metadata[kBrand] === "object") {
    const keys = Object.keys(metadata[kBrand]);
    if (keys.includes("dark")) {
      if (keys[0] === "dark") {
        return true;
      } else {
        return false;
      }
    }
  }
  return void 0;
}
function darkModeDefault(format14) {
  const metadata = format14.metadata;
  if (metadata !== void 0) {
    const dmdm = darkModeDefaultMetadata(metadata);
    if (dmdm !== void 0) {
      return dmdm;
    }
  }
  const brand = format14.render.brand;
  if (brand && brand.dark) {
    return false;
  }
  return void 0;
}
var init_format_html_info = __esm({
  "format/html/format-html-info.ts"() {
    init_constants6();
    init_format5();
  }
});

// core/deno/expand-glob.ts
function expandGlobSync2(glob, options) {
  if (options === void 0) {
    return expandGlobSync(glob, { globstar: true });
  } else {
    return expandGlobSync(glob, {
      ...options,
      globstar: options.globstar ?? true
    });
  }
}
var init_expand_glob2 = __esm({
  "core/deno/expand-glob.ts"() {
    init_fs();
  }
});

// extension/constants.ts
var kBuiltInExtOrg, kCommon, kExtensionDir, kTitle2, kAuthor2, kVersion, kQuartoRequired2, kRevealJSPlugins, kBuiltInExtNames;
var init_constants12 = __esm({
  "extension/constants.ts"() {
    kBuiltInExtOrg = "quarto";
    kCommon = "common";
    kExtensionDir = "_extensions";
    kTitle2 = "title";
    kAuthor2 = "author";
    kVersion = "version";
    kQuartoRequired2 = "quarto-required";
    kRevealJSPlugins = "revealjs-plugins";
    kBuiltInExtNames = ["lightbox"];
  }
});

// extension/extension-shared.ts
function extensionIdString(extensionId) {
  if (extensionId.organization) {
    return `${extensionId.organization}/${extensionId.name}`;
  } else {
    return extensionId.name;
  }
}
var init_extension_shared = __esm({
  "extension/extension-shared.ts"() {
  }
});

// core/lib/yaml-schema/project-config.ts
function disallowTopLevelType(error2, parse24, _schema) {
  if (!(error2.instancePath.length === 1 && error2.instancePath[0] === "type")) {
    return error2;
  }
  const violatingObject = locateAnnotation(parse24, error2.instancePath, "key");
  const localizedError = createLocalizedError({
    ...error2,
    message: "top-level key 'type' is not allowed in project configuration.",
    violatingObject,
    source: mappedSubstring(
      parse24.source,
      violatingObject.start,
      violatingObject.end + 1
    )
  });
  localizedError.niceError.info["top-level-type-not-allowed"] = "Did you mean to use 'project: type: ...' instead?";
  return localizedError;
}
var getProjectConfigFieldsSchema, getExtensionConfigFieldsSchema, getProjectConfigSchema, getExtensionConfigSchema;
var init_project_config = __esm({
  "core/lib/yaml-schema/project-config.ts"() {
    init_common4();
    init_from_yaml();
    init_execute();
    init_front_matter();
    init_definitions();
    init_resources();
    init_annotated_yaml();
    init_errors2();
    init_mapped_text();
    getProjectConfigFieldsSchema = defineCached(
      // deno-lint-ignore require-await
      async () => {
        return {
          schema: objectSchemaFromFieldsObject(
            getYamlIntelligenceResource("schema/project.yml")
          ),
          errorHandlers: []
        };
      },
      "project-config-fields"
    );
    getExtensionConfigFieldsSchema = defineCached(
      // deno-lint-ignore require-await
      async () => {
        return {
          schema: objectSchemaFromFieldsObject(
            getYamlIntelligenceResource("schema/extension.yml")
          ),
          errorHandlers: []
        };
      },
      "extension-config-fields"
    );
    getProjectConfigSchema = defineCached(
      async () => {
        const projectConfigFields = await getProjectConfigFieldsSchema();
        const execute = await getFormatExecuteOptionsSchema();
        const format14 = await getFrontMatterFormatSchema();
        const profile = refSchema(
          "project-profile",
          "Specify a default profile and profile groups"
        );
        const result2 = allOfSchema(
          objectSchema({
            properties: {
              execute,
              format: format14,
              profile
            },
            description: "be a Quarto YAML front matter object"
          }),
          execute,
          await getFrontMatterSchema(),
          projectConfigFields
        );
        return {
          schema: describeSchema(result2, "a project configuration object"),
          errorHandlers: [disallowTopLevelType]
        };
      },
      "project-config"
    );
    getExtensionConfigSchema = defineCached(
      async () => {
        const extensionConfig = await getExtensionConfigFieldsSchema();
        return {
          schema: describeSchema(
            extensionConfig,
            "an extension configuration object"
          ),
          errorHandlers: []
        };
      },
      "extension-config"
    );
  }
});

// core/array.ts
function asArray(x3) {
  return x3 ? Array.isArray(x3) ? x3 : [x3] : [];
}
var init_array = __esm({
  "core/array.ts"() {
  }
});

// project/project-resources.ts
function projectResourceFiles(dir, config2) {
  let resourceGlobs = asArray(config2.project[kProjectResources]);
  const resourceFiles = [];
  const outputDir = config2.project[kProjectOutputDir];
  if (outputDir) {
    resourceGlobs = (resourceGlobs || []).concat(kQuartoIgnore.map((entry) => `!${entry}`));
    const exclude = outputDir ? [outputDir] : [];
    const projectResourceFiles2 = resolvePathGlobs(
      dir,
      resourceGlobs,
      exclude
    );
    resourceFiles.push(
      ...difference(
        projectResourceFiles2.include,
        projectResourceFiles2.exclude
      )
    );
    resourceFiles.push(
      ...["robots.txt", ".nojekyll", "CNAME", "_redirects", kProject404File].map((file) => join4(dir, file)).filter(existsSync1)
    );
  }
  return uniq(resourceFiles);
}
function copyResourceFile(rootDir, srcFile, destFile) {
  if (!normalizePath(srcFile).startsWith(normalizePath(rootDir))) {
    return;
  }
  ensureDirSync(dirname4(destFile));
  copyFileIfNewer(srcFile, destFile);
  if (extname4(srcFile).toLowerCase() === ".css") {
    handleCssReferences(rootDir, srcFile, destFile);
  }
}
function fixupCssReferences2(css, offset3, onRef) {
  let destCss = css.replaceAll(
    kCssUrlRegex,
    (_match, p1, p22) => {
      const ref3 = p22.startsWith("/") ? `${offset3}${p22.slice(1)}` : p22;
      return `url(${p1 || ""}${onRef(ref3)}${p1 || ""})`;
    }
  );
  destCss = destCss.replaceAll(
    kCssImportRegex,
    (_match, p1, p22) => {
      const ref3 = p22.startsWith("/") ? `${offset3}${p22.slice(1)}` : p22;
      return `@import ${p1 || ""}${onRef(ref3)}${p1 || ""}`;
    }
  );
  return destCss;
}
function handleCssReferences(rootDir, srcFile, destFile) {
  const css = Deno.readTextFileSync(destFile);
  const offset3 = relative4(dirname4(srcFile), rootDir);
  const copyRef = (ref3) => {
    const refPath = join4(dirname4(srcFile), ref3);
    if (safeExistsSync(refPath)) {
      const refDestPath = join4(dirname4(destFile), ref3);
      copyResourceFile(rootDir, refPath, refDestPath);
    }
    return ref3;
  };
  const destCss = fixupCssReferences2(css, offset3, copyRef);
  if (destCss !== css) {
    Deno.writeTextFileSync(destFile, destCss);
  }
}
var init_project_resources = __esm({
  "project/project-resources.ts"() {
    init_fs();
    init_path();
    init_lodash();
    init_array();
    init_path2();
    init_css();
    init_types4();
    init_project_gitignore();
    init_copy5();
    init_file();
  }
});

// extension/extension.ts
var extension_exports = {};
__export(extension_exports, {
  builtinSubtreeExtensions: () => builtinSubtreeExtensions,
  createExtensionContext: () => createExtensionContext,
  discoverExtensionPath: () => discoverExtensionPath,
  extensionFile: () => extensionFile,
  extensionFilesFromDirs: () => extensionFilesFromDirs,
  extensionProjectType: () => extensionProjectType,
  filterBuiltInExtensions: () => filterBuiltInExtensions,
  filterExtensions: () => filterExtensions,
  inputExtensionDirs: () => inputExtensionDirs,
  isPluginRaw: () => isPluginRaw,
  projectExtensionDirs: () => projectExtensionDirs,
  projectExtensionPathResolver: () => projectExtensionPathResolver,
  readExtensions: () => readExtensions,
  readSubtreeExtensions: () => readSubtreeExtensions
});
function createExtensionContext() {
  const extensionCache = {};
  const extensions2 = async (input, config2, projectDir, options) => {
    const extensions3 = await loadExtensions(
      extensionCache,
      input,
      projectDir
    );
    const results = Object.values(extensions3).filter(
      (ext) => options?.builtIn !== false || ext.id.organization !== kBuiltInExtOrg
    );
    return results.map((extension2) => {
      if (input) {
        return resolveExtensionPaths(extension2, input, config2);
      } else {
        return extension2;
      }
    });
  };
  const extension = async (name2, input, config2, projectDir, preferLocal = false) => {
    const unresolved = await loadExtension(
      name2,
      input,
      projectDir,
      preferLocal
    );
    return resolveExtensionPaths(unresolved, input, config2);
  };
  const find = async (name2, input, contributes, config2, projectDir, options) => {
    const extId = toExtensionId(name2);
    return findExtensions(
      await extensions2(input, config2, projectDir, options),
      extId,
      contributes
    );
  };
  return {
    extension,
    extensions: extensions2,
    find
  };
}
function projectExtensionPathResolver(libDir, projectDir) {
  return (href, projectOffset2) => {
    const projectRelativeHref = relative4(projectOffset2, href);
    if (projectRelativeHref.startsWith("_extensions/") || projectRelativeHref.startsWith("_extensions\\")) {
      const projectTargetHref = projectRelativeHref.replace(
        /^_extensions/,
        `${libDir}/quarto-contrib/quarto-project`
      );
      copyResourceFile(
        projectDir,
        join4(projectDir, projectRelativeHref),
        join4(projectDir, projectTargetHref)
      );
      return join4(projectOffset2, projectTargetHref);
    }
    return href;
  };
}
function filterBuiltInExtensions(extensions2) {
  const quartoExts = extensions2.filter((ext) => {
    return ext.id.organization === kBuiltInExtOrg;
  });
  const nowBuiltInExtensions = extensions2?.filter((ext) => {
    return ext.id.organization === "quarto-ext" && quartoExts.map((ext2) => ext2.id.name).includes(ext.id.name);
  });
  if (nowBuiltInExtensions.length > 0) {
    extensions2 = filterExtensionAndWarn(extensions2, nowBuiltInExtensions);
  }
  return extensions2;
}
function filterExtensionAndWarn(extensions2, filterOutExtensions) {
  warnToRemoveExtensions(filterOutExtensions);
  return extensions2.filter((ext) => {
    return !filterOutExtensions.map((ext2) => ext2.id.name).includes(
      ext.id.name
    );
  });
}
function warnToRemoveExtensions(extensions2) {
  const removeCommands = extensions2.map((ext) => {
    return `quarto remove extension ${extensionIdString(ext.id)}`;
  });
  warnOnce(
    `One or more extensions have been built in to Quarto. Please use the following command to remove the unneeded extension:
  ${removeCommands.join("\n  ")}`
  );
}
function filterExtensions(extensions2, extensionId, type4) {
  if (extensions2 && extensions2.length > 0) {
    extensions2 = filterBuiltInExtensions(extensions2);
    const ownedExtensions = extensions2.filter((ext) => {
      return ext.id.organization !== void 0;
    }).map((ext) => {
      return extensionIdString(ext.id);
    });
    if (ownedExtensions.length > 1) {
      warnOnce(
        `The ${type4} '${extensionId}' matched more than one extension. Please use a full name to disambiguate:
  ${ownedExtensions.join("\n  ")}`
      );
    }
    const oldBuiltInExt = extensions2?.filter((ext) => {
      return ext.id.organization === kQuartoExtOrganization && (kQuartoExtBuiltIn.includes(ext.id.name) || kBuiltInExtNames.includes(ext.id.name));
    });
    if (oldBuiltInExt.length > 0) {
      return filterExtensionAndWarn(extensions2, oldBuiltInExt);
    } else {
      return extensions2;
    }
  } else {
    return extensions2;
  }
}
async function readSubtreeExtensions(subtreeDir) {
  const extensions2 = [];
  const topLevelDirs = safeExistsSync(subtreeDir) && Deno.statSync(subtreeDir).isDirectory ? Deno.readDirSync(subtreeDir) : [];
  for (const topLevelDir of topLevelDirs) {
    if (!topLevelDir.isDirectory) continue;
    const dirPath = join4(subtreeDir, topLevelDir.name);
    const subtreeExtensionsPath = join4(dirPath, kExtensionDir);
    if (safeExistsSync(subtreeExtensionsPath)) {
      const exts = await readExtensions(subtreeExtensionsPath);
      extensions2.push(...exts);
    }
  }
  return extensions2;
}
function findExtensions(extensions2, extensionId, contributes) {
  const exts = extensions2.filter((ext) => {
    if (contributes === "shortcodes" && ext.contributes.shortcodes) {
      return true;
    } else if (contributes === "filters" && ext.contributes.filters) {
      return true;
    } else if (contributes === "formats" && ext.contributes.formats) {
      return true;
    } else if (contributes === "project" && ext.contributes.project) {
      return true;
    } else if (contributes === "metadata" && ext.contributes.metadata) {
      return true;
    } else if (contributes === kRevealJSPlugins && ext.contributes[kRevealJSPlugins]) {
      return true;
    } else if (contributes === "engines" && ext.contributes.engines) {
      return true;
    } else {
      return contributes === void 0;
    }
  });
  if (extensionId.organization) {
    const exact = exts.filter((ext) => {
      return ext.id.name === extensionId.name && ext.id.organization === extensionId.organization;
    });
    if (exact.length > 0) {
      return exact;
    }
  }
  const nameMatches = exts.filter((ext) => {
    return extensionId.name === ext.id.name;
  });
  const sortedMatches = nameMatches.sort((ext1, _ext2) => {
    return ext1.id.organization === void 0 ? -1 : 1;
  });
  return sortedMatches;
}
function extensionProjectType(extension, config2) {
  if (extension.contributes.project) {
    const projType = extension.contributes.project?.type || "default";
    return projectType(projType);
  } else {
    return projectType(config2?.project?.[kProjectType]);
  }
}
function resolveExtensionPaths(extension, input, config2) {
  const inputDir = Deno.statSync(input).isDirectory ? input : dirname4(input);
  return toInputRelativePaths(
    extensionProjectType(extension, config2),
    extension.path,
    inputDir,
    extension,
    kExtensionIgnoreFields
  );
}
async function readExtensions(extensionsDirectory, organization) {
  const extensions2 = [];
  const extensionDirs = safeExistsSync(extensionsDirectory) && Deno.statSync(extensionsDirectory).isDirectory ? Deno.readDirSync(extensionsDirectory) : [];
  for (const extensionDir2 of extensionDirs) {
    if (extensionDir2.isDirectory) {
      const extFile = extensionFile(
        join4(extensionsDirectory, extensionDir2.name)
      );
      if (extFile) {
        const extensionId = { name: extensionDir2.name, organization };
        const extension = await readExtension(
          extensionId,
          extFile
        );
        extensions2.push(extension);
      } else if (!organization) {
        const ownedExtensions = await readExtensions(
          join4(extensionsDirectory, extensionDir2.name),
          extensionDir2.name
        );
        if (ownedExtensions) {
          extensions2.push(...ownedExtensions);
        }
      }
    }
  }
  return extensions2;
}
function projectExtensionDirs(project) {
  const extensionDirs = [];
  for (const walk5 of expandGlobSync2(join4(project.dir, "**/_extensions"), {
    exclude: [...projectIgnoreGlobs(project.dir), "**/.*", "**/.*/**"]
  })) {
    extensionDirs.push(walk5.path);
  }
  return extensionDirs;
}
function extensionFilesFromDirs(dirs) {
  const files = [];
  for (const dir of dirs) {
    for (const walk5 of walkSync(
      dir,
      {
        includeDirs: false,
        followSymlinks: false,
        skip: [kSkipHidden]
      }
    )) {
      files.push(walk5.path);
    }
  }
  return files;
}
function inputExtensionDirs(input, projectDir) {
  const extensionsDirPath = (path3) => {
    const extPath = join4(path3, kExtensionDir);
    try {
      if (Deno.statSync(extPath).isDirectory) {
        return extPath;
      } else {
        return void 0;
      }
    } catch {
      return void 0;
    }
  };
  const inputDirName = (inputOrDir) => {
    if (Deno.statSync(inputOrDir).isDirectory) {
      return inputOrDir;
    } else {
      return dirname4(inputOrDir);
    }
  };
  const extensionDirectories = [
    builtinExtensions(),
    builtinSubtreeExtensions()
  ];
  if (projectDir && input) {
    let currentDir = normalizePath(inputDirName(input));
    do {
      const extensionPath = extensionsDirPath(currentDir);
      if (extensionPath) {
        extensionDirectories.push(extensionPath);
      }
      currentDir = dirname4(currentDir);
    } while (isSubdir2(projectDir, currentDir) || projectDir === currentDir);
    return extensionDirectories;
  } else if (input) {
    const dir = extensionsDirPath(inputDirName(input));
    if (dir) {
      extensionDirectories.push(dir);
    }
  } else if (projectDir) {
    const dir = extensionsDirPath(projectDir);
    if (dir) {
      extensionDirectories.push(dir);
    }
  }
  return extensionDirectories;
}
function discoverExtensionPath(input, extensionId, projectDir, preferLocal = false) {
  const extensionDirGlobs = [];
  if (extensionId.organization) {
    extensionDirGlobs.push(
      `${extensionId.organization}/${extensionId.name}/`
    );
  } else {
    extensionDirGlobs.push(`${extensionId.name}/`);
    extensionDirGlobs.push(`*/${extensionId.name}/`);
  }
  const findExtensionDir2 = (extDir, globs) => {
    const paths = resolvePathGlobs(extDir, globs, [], { mode: "strict" }).include.filter((path3) => {
      return extensionFile(path3);
    });
    if (paths.length > 0) {
      if (paths.length > 1) {
        warn(
          `More than one extension is available for ${extensionId.name} in the directory ${extDir}.
Extensions that match:
${paths.join("\n")}`
        );
      }
      return relative4(Deno.cwd(), paths[0]);
    } else {
      return void 0;
    }
  };
  const findLocalExtensionDir = () => {
    const sourceDir = Deno.statSync(input).isDirectory ? input : dirname4(input);
    const sourceDirAbs = normalizePath(sourceDir);
    if (projectDir && isSubdir2(projectDir, sourceDirAbs)) {
      let extensionDir2;
      let currentDir = normalize4(sourceDirAbs);
      const projDir = normalize4(projectDir);
      while (!extensionDir2) {
        extensionDir2 = findExtensionDir2(
          join4(currentDir, kExtensionDir),
          extensionDirGlobs
        );
        if (currentDir == projDir) {
          break;
        }
        currentDir = dirname4(currentDir);
      }
      return extensionDir2;
    } else {
      return findExtensionDir2(
        join4(sourceDirAbs, kExtensionDir),
        extensionDirGlobs
      );
    }
  };
  if (preferLocal) {
    const localDir = findLocalExtensionDir();
    if (localDir) {
      return localDir;
    }
  }
  const builtinExtensionDir = findExtensionDir2(
    builtinExtensions(),
    extensionDirGlobs
  );
  if (builtinExtensionDir) {
    return builtinExtensionDir;
  }
  const subtreePath = builtinSubtreeExtensions();
  if (safeExistsSync(subtreePath)) {
    for (const topLevelDir of Deno.readDirSync(subtreePath)) {
      if (!topLevelDir.isDirectory) continue;
      const subtreeExtDir = join4(subtreePath, topLevelDir.name, kExtensionDir);
      if (safeExistsSync(subtreeExtDir)) {
        const subtreeExtensionDir = findExtensionDir2(
          subtreeExtDir,
          extensionDirGlobs
        );
        if (subtreeExtensionDir) {
          return subtreeExtensionDir;
        }
      }
    }
  }
  if (!preferLocal) {
    return findLocalExtensionDir();
  }
}
function builtinExtensions() {
  return resourcePath("extensions");
}
function builtinSubtreeExtensions() {
  return resourcePath("extension-subtrees");
}
function validateExtension(extension) {
  let contribCount = 0;
  const contribs = [
    extension.contributes.filters,
    extension.contributes.shortcodes,
    extension.contributes.formats,
    extension.contributes.project,
    extension.contributes[kRevealJSPlugins],
    extension.contributes.metadata,
    extension.contributes.engines
  ];
  contribs.forEach((contrib) => {
    if (contrib) {
      if (Array.isArray(contrib)) {
        contribCount = contribCount + contrib.length;
      } else if (typeof contrib === "object") {
        contribCount = contribCount + Object.keys(contrib).length;
      }
    }
  });
  if (contribCount === 0) {
    throw new Error(
      `The extension ${extension.title || extension.id.name} is not valid- it does not contribute anything.`
    );
  }
  if (extension.quartoVersion && !satisfies(quartoConfig.version(), extension.quartoVersion)) {
    throw new Error(
      `The extension ${extension.title || extension.id.name} is incompatible with this quarto version.

Extension requires: ${extension.quartoVersion.raw}
Quarto version: ${quartoConfig.version()}`
    );
  }
}
async function readExtension(extensionId, extensionFile2) {
  const extensionSchema = await getExtensionConfigSchema();
  const yaml = await readAndValidateYamlFromFile(
    extensionFile2,
    extensionSchema,
    "YAML Validation Failed"
  );
  const readVersionRange = (str3) => {
    return new Range2(str3);
  };
  const contributes = yaml.contributes;
  const title3 = yaml[kTitle2];
  const author = yaml[kAuthor2];
  const versionRaw = yaml[kVersion];
  const quartoVersionRaw = yaml[kQuartoRequired2];
  const versionParsed = versionRaw ? coerce(versionRaw) : void 0;
  const quartoVersion = quartoVersionRaw ? readVersionRange(quartoVersionRaw) : void 0;
  const version4 = versionParsed ? versionParsed : void 0;
  const extensionDirRaw = dirname4(extensionFile2);
  const extensionDir2 = isAbsolute4(extensionDirRaw) ? extensionDirRaw : join4(Deno.cwd(), extensionDirRaw);
  const formats2 = contributes?.formats || contributes?.format || {};
  const embeddedExtensions = await readExtensions(
    join4(extensionDir2, kExtensionDir)
  );
  Object.keys(formats2).forEach((key) => {
    if (formats2[key] === "default") {
      formats2[key] = {};
    }
  });
  Object.keys(formats2).filter((key) => {
    return key !== kCommon;
  }).forEach((key) => {
    formats2[key] = mergeConfigs(
      formats2[kCommon] || {},
      formats2[key]
    );
    const formatMeta = formats2[key];
    if (formatMeta[kFormatResources]) {
      const resolved = resolvePathGlobs(
        extensionDir2,
        formatMeta[kFormatResources],
        [],
        { mode: "strict" }
      );
      if (resolved.include.length > 0) {
        formatMeta[kFormatResources] = resolved.include.map((include2) => {
          return relative4(extensionDir2, include2);
        });
      }
    }
    if (key.endsWith(".lua")) {
      const fullPath = join4(extensionDir2, key);
      if (existsSync2(fullPath)) {
        formatMeta.writer = fullPath;
      }
    }
    formatMeta.shortcodes = (formatMeta.shortcodes || []).flatMap((shortcode) => {
      return resolveShortcode(embeddedExtensions, extensionDir2, shortcode);
    });
    formatMeta.filters = (formatMeta.filters || []).flatMap(
      (filter3) => {
        return resolveFilter(embeddedExtensions, extensionDir2, filter3);
      }
    );
    formatMeta[kRevealJSPlugins] = (formatMeta?.[kRevealJSPlugins] || []).flatMap(
      (plugin) => {
        return resolveRevealJSPlugin(
          embeddedExtensions,
          extensionDir2,
          plugin
        );
      }
    );
  });
  delete formats2[kCommon];
  const shortcodes = (contributes?.shortcodes || []).map(
    (shortcode) => {
      return resolveShortcodePath(extensionDir2, shortcode);
    }
  );
  const filters = (contributes?.filters || []).map(
    (filter3) => {
      return resolveFilterPath(extensionDir2, filter3);
    }
  );
  const project = contributes?.project;
  const metadata = contributes?.metadata;
  for (const key of ["pre-render", "post-render", "brand"]) {
    for (const object of [metadata, project]) {
      if (!object?.project || typeof object.project !== "object") {
        continue;
      }
      const t5 = object.project[key];
      if (t5) {
        const value = Array.isArray(t5) ? t5 : [t5];
        const resolved = resolvePathGlobs(
          extensionDir2,
          value,
          []
        );
        if (resolved.include.length > 0) {
          if (key === "brand") {
            let projectDir = extensionDir2, last;
            do {
              last = basename4(projectDir);
              projectDir = dirname4(projectDir);
            } while (projectDir && last !== "_extensions");
            if (projectDir) {
              object.project[key] = relative4(
                projectDir,
                resolved.include[0]
              );
            }
          } else {
            object.project[key] = resolved.include;
          }
        }
      }
    }
  }
  const revealJSPlugins = (contributes?.[kRevealJSPlugins] || []).map((plugin) => {
    return resolveRevealPlugin(extensionDir2, plugin);
  });
  const engines = (contributes?.engines || []).map(
    (engine) => {
      if (typeof engine === "string") {
        return engine;
      } else if (typeof engine === "object" && engine.path) {
        return {
          ...engine,
          path: join4(extensionDir2, engine.path)
        };
      }
      return engine;
    }
  );
  const result2 = {
    title: title3,
    author,
    version: version4,
    quartoVersion,
    id: extensionId,
    path: extensionDir2,
    contributes: {
      metadata,
      shortcodes,
      filters,
      formats: formats2,
      project: project ?? {},
      [kRevealJSPlugins]: revealJSPlugins,
      engines: engines.length > 0 ? engines : void 0
    }
  };
  validateExtension(result2);
  return result2;
}
function resolveRevealJSPlugin(embeddedExtensions, dir, plugin) {
  if (typeof plugin === "string") {
    const extensionId = toExtensionId(plugin);
    const extensions2 = findExtensions(
      embeddedExtensions,
      extensionId,
      "revealjs-plugins"
    );
    if (extensions2.length > 0) {
      const plugins = [];
      for (const plugin2 of extensions2[0].contributes[kRevealJSPlugins] || []) {
        plugins.push(plugin2);
      }
      return plugins;
    } else {
      validateExtensionPath("revealjs-plugin", dir, plugin);
      return resolveRevealPlugin(dir, plugin);
    }
  } else {
    return plugin;
  }
}
function isPluginRaw(plugin) {
  return plugin.plugin === void 0;
}
function resolveRevealPlugin(extensionDir2, plugin) {
  if (typeof plugin === "string") {
    return join4(extensionDir2, plugin);
  } else if (isPluginRaw(plugin)) {
    return resolveRevealPluginInline(plugin, extensionDir2);
  } else {
    plugin.plugin = join4(extensionDir2, plugin.plugin);
    return plugin;
  }
}
function resolveRevealPluginInline(plugin, extensionDir2) {
  if (!plugin.name) {
    throw new Error(
      `Invalid revealjs-plugin in ${extensionDir2} - 'name' property is required.`
    );
  }
  const resolvedPlugin = {
    name: plugin.name,
    path: extensionDir2,
    register: plugin.register,
    config: plugin.config
  };
  if (plugin.script) {
    const pluginArr = Array.isArray(plugin.script) ? plugin.script : [plugin.script];
    resolvedPlugin.script = pluginArr.map((plug) => {
      if (typeof plug === "string") {
        return {
          path: plug
        };
      } else {
        return plug;
      }
    });
  }
  if (plugin.stylesheet) {
    resolvedPlugin.stylesheet = Array.isArray(plugin.stylesheet) ? plugin.stylesheet : [plugin.stylesheet];
  }
  return resolvedPlugin;
}
function resolveShortcode(embeddedExtensions, dir, shortcode) {
  const extensionId = toExtensionId(shortcode);
  const extensions2 = findExtensions(
    embeddedExtensions,
    extensionId,
    "shortcodes"
  );
  if (extensions2.length > 0) {
    const shortcodes = [];
    for (const shortcode2 of extensions2[0].contributes.shortcodes || []) {
      shortcodes.push(resolveShortcodePath(extensions2[0].path, shortcode2));
    }
    return shortcodes;
  } else {
    validateExtensionPath("shortcode", dir, shortcode);
    return resolveShortcodePath(dir, shortcode);
  }
}
function resolveShortcodePath(extensionDir2, shortcode) {
  if (isAbsolute4(shortcode)) {
    return shortcode;
  } else {
    return join4(extensionDir2, shortcode);
  }
}
function resolveFilter(embeddedExtensions, dir, filter3) {
  if (typeof filter3 === "string") {
    if (filter3 === "quarto") {
      return filter3;
    }
    const extensionId = toExtensionId(filter3);
    const extensions2 = findExtensions(
      embeddedExtensions,
      extensionId,
      "filters"
    );
    if (extensions2.length > 0) {
      const filters = [];
      for (const filter4 of extensions2[0].contributes.filters || []) {
        filters.push(resolveFilterPath(extensions2[0].path, filter4));
      }
      return filters;
    } else {
      validateExtensionPath("filter", dir, filter3);
      return resolveFilterPath(dir, filter3);
    }
  } else {
    validateExtensionPath("filter", dir, filter3.path);
    return resolveFilterPath(dir, filter3);
  }
}
function resolveFilterPath(extensionDir2, filter3) {
  if (typeof filter3 === "string") {
    if (isAbsolute4(filter3)) {
      return filter3;
    } else {
      return join4(extensionDir2, filter3);
    }
  } else {
    const filterAt = filter3.at;
    const result2 = {
      type: filter3.type,
      path: isAbsolute4(filter3.path) ? filter3.path : join4(extensionDir2, filter3.path)
    };
    if (filterAt === void 0) {
      return result2;
    } else {
      return {
        ...result2,
        at: filterAt
      };
    }
  }
}
function validateExtensionPath(type4, dir, path3) {
  const resolves = existsSync2(join4(dir, path3));
  if (!resolves) {
    throw Error(
      `Failed to resolve referenced ${type4} ${path3} - path does not exist.
If you are attempting to use another extension within this extension, please install the extension using the 'quarto install --embedded' command.`
    );
  }
  return resolves;
}
function toExtensionId(extension) {
  if (extension.indexOf("/") > -1) {
    const extParts = extension.split("/");
    if (extParts.length === 2) {
      return {
        name: extParts[1],
        organization: extParts[0]
      };
    } else {
      return {
        name: extension
      };
    }
  } else {
    return {
      name: extension
    };
  }
}
var kQuartoExtOrganization, kQuartoExtBuiltIn, loadExtensions, loadExtension, kExtensionIgnoreFields, extensionFile;
var init_extension = __esm({
  async "extension/extension.ts"() {
    init_fs();
    init_expand_glob2();
    init_log();
    init_fs();
    init_mod6();
    init_types4();
    init_path();
    init_path2();
    await init_project_shared();
    init_project_types();
    init_config2();
    init_quarto();
    init_constants12();
    init_extension_shared();
    init_lodash();
    init_validated_yaml2();
    init_project_config();
    await init_engine();
    init_project_resources();
    init_resources2();
    init_log2();
    init_file();
    init_constants6();
    kQuartoExtOrganization = "quarto-ext";
    kQuartoExtBuiltIn = ["code-filename", "grouped-tabsets"];
    loadExtensions = async (cache3, input, projectDir) => {
      const extensionPath = inputExtensionDirs(input, projectDir);
      const allExtensions = {};
      const subtreePath = builtinSubtreeExtensions();
      for (const extensionDir2 of extensionPath) {
        if (cache3[extensionDir2]) {
          cache3[extensionDir2].forEach((ext) => {
            allExtensions[extensionIdString(ext.id)] = cloneDeep(ext);
          });
        } else {
          const extensions2 = extensionDir2 === subtreePath ? await readSubtreeExtensions(extensionDir2) : await readExtensions(extensionDir2);
          extensions2.forEach((extension) => {
            allExtensions[extensionIdString(extension.id)] = cloneDeep(extension);
          });
          cache3[extensionDir2] = extensions2;
        }
      }
      return allExtensions;
    };
    loadExtension = async (extension, input, projectDir, preferLocal = false) => {
      const extensionId = toExtensionId(extension);
      const extensionPath = discoverExtensionPath(
        input,
        extensionId,
        projectDir,
        preferLocal
      );
      if (extensionPath) {
        const file = extensionFile(extensionPath);
        if (file) {
          const extension2 = await readExtension(extensionId, file);
          validateExtension(extension2);
          return extension2;
        } else {
          throw new Error(
            `The extension '${extension}' is missing the expected '_extension.yml' file.`
          );
        }
      } else {
        throw new Error(
          `Unable to read the extension '${extension}'.
Please ensure that you provided the correct id and that the extension is installed.`
        );
      }
    };
    kExtensionIgnoreFields = ["biblio-style", "revealjs-plugins"];
    extensionFile = (dir) => {
      return ["_extension.yml", "_extension.yaml"].map((file) => join4(dir, file)).find(existsSync1);
    };
  }
});

// core/dart-sass.ts
async function dartCompile(input, outputFilePath, temp, loadPaths, compressed) {
  const inputFilePath = temp.createFile({ suffix: ".scss" });
  Deno.writeTextFileSync(inputFilePath, input);
  const args = [
    inputFilePath,
    outputFilePath,
    "--style",
    compressed ? "compressed" : "expanded",
    "--quiet"
    // Remove this flag to get depedency warnings from SASS
  ];
  if (loadPaths) {
    loadPaths.forEach((loadPath) => {
      args.push(`--load-path=${loadPath}`);
    });
  }
  await dartCommand(args);
  return outputFilePath;
}
function resolveSassCommand(options) {
  const installDir4 = options?.installDir;
  if (installDir4 == null) {
    const dartOverrideCmd = Deno.env.get("QUARTO_DART_SASS");
    if (dartOverrideCmd) {
      if (!existsSync2(dartOverrideCmd)) {
        warnOnce(
          `Specified QUARTO_DART_SASS does not exist, using built in dart sass.`
        );
      } else {
        return { cmd: dartOverrideCmd, baseArgs: [] };
      }
    }
  }
  const sassDir = installDir4 ?? architectureToolsPath("dart-sass");
  if (isWindows4) {
    return {
      cmd: join4(sassDir, "src", "dart.exe"),
      baseArgs: [join4(sassDir, "src", "sass.snapshot")]
    };
  }
  return { cmd: join4(sassDir, "sass"), baseArgs: [] };
}
async function dartCommand(args, options) {
  const { cmd, baseArgs } = resolveSassCommand(options);
  const result2 = await execProcess({
    cmd,
    args: [...baseArgs, ...args],
    stdout: "piped",
    stderr: "piped"
  });
  if (result2.success) {
    if (result2.stderr) {
      info(result2.stderr);
    }
    return result2.stdout;
  } else {
    debug(`[DART cmd]    : ${cmd}`);
    debug(`[DART args]   : ${[...baseArgs, ...args].join(" ")}`);
    debug(`[DART stdout] : ${result2.stdout}`);
    debug(`[DART stderr] : ${result2.stderr}`);
    const errLines = lines(result2.stderr || "");
    const errMsg = errLines.slice(0, errLines.length - 2).join("\n");
    throw new Error("Theme file compilation failed:\n\n" + errMsg);
  }
}
var init_dart_sass = __esm({
  "core/dart-sass.ts"() {
    init_path();
    init_resources2();
    init_process();
    init_text2();
    init_log();
    init_fs();
    init_log2();
    init_platform();
  }
});

// https://jsr.io/@std/crypto/1.0.4/_wasm/lib/deno_std_wasm_crypto.generated.mjs
function getObject2(idx) {
  return heap2[idx];
}
function dropObject2(idx) {
  if (idx < 132) return;
  heap2[idx] = heap_next2;
  heap_next2 = idx;
}
function takeObject2(idx) {
  const ret = getObject2(idx);
  dropObject2(idx);
  return ret;
}
function addHeapObject2(obj) {
  if (heap_next2 === heap2.length) heap2.push(heap2.length + 1);
  const idx = heap_next2;
  heap_next2 = heap2[idx];
  heap2[idx] = obj;
  return idx;
}
function getUint8Memory03() {
  if (cachedUint8Memory0 === null || cachedUint8Memory0.byteLength === 0) {
    cachedUint8Memory0 = new Uint8Array(wasm3.memory.buffer);
  }
  return cachedUint8Memory0;
}
function getStringFromWasm03(ptr, len) {
  ptr = ptr >>> 0;
  return cachedTextDecoder3.decode(getUint8Memory03().subarray(ptr, ptr + len));
}
function passStringToWasm02(arg, malloc, realloc) {
  if (realloc === void 0) {
    const buf = cachedTextEncoder3.encode(arg);
    const ptr2 = malloc(buf.length, 1) >>> 0;
    getUint8Memory03().subarray(ptr2, ptr2 + buf.length).set(buf);
    WASM_VECTOR_LEN2 = buf.length;
    return ptr2;
  }
  let len = arg.length;
  let ptr = malloc(len, 1) >>> 0;
  const mem = getUint8Memory03();
  let offset3 = 0;
  for (; offset3 < len; offset3++) {
    const code5 = arg.charCodeAt(offset3);
    if (code5 > 127) break;
    mem[ptr + offset3] = code5;
  }
  if (offset3 !== len) {
    if (offset3 !== 0) {
      arg = arg.slice(offset3);
    }
    ptr = realloc(ptr, len, len = offset3 + arg.length * 3, 1) >>> 0;
    const view = getUint8Memory03().subarray(ptr + offset3, ptr + len);
    const ret = encodeString3(arg, view);
    offset3 += ret.written;
    ptr = realloc(ptr, len, offset3, 1) >>> 0;
  }
  WASM_VECTOR_LEN2 = offset3;
  return ptr;
}
function isLikeNone(x3) {
  return x3 === void 0 || x3 === null;
}
function getInt32Memory02() {
  if (cachedInt32Memory0 === null || cachedInt32Memory0.byteLength === 0) {
    cachedInt32Memory0 = new Int32Array(wasm3.memory.buffer);
  }
  return cachedInt32Memory0;
}
function getArrayU8FromWasm0(ptr, len) {
  ptr = ptr >>> 0;
  return getUint8Memory03().subarray(ptr / 1, ptr / 1 + len);
}
function digest(algorithm, data3, length) {
  try {
    const retptr = wasm3.__wbindgen_add_to_stack_pointer(-16);
    const ptr0 = passStringToWasm02(
      algorithm,
      wasm3.__wbindgen_malloc,
      wasm3.__wbindgen_realloc
    );
    const len0 = WASM_VECTOR_LEN2;
    wasm3.digest(
      retptr,
      ptr0,
      len0,
      addHeapObject2(data3),
      !isLikeNone(length),
      isLikeNone(length) ? 0 : length
    );
    var r0 = getInt32Memory02()[retptr / 4 + 0];
    var r1 = getInt32Memory02()[retptr / 4 + 1];
    var r22 = getInt32Memory02()[retptr / 4 + 2];
    var r32 = getInt32Memory02()[retptr / 4 + 3];
    if (r32) {
      throw takeObject2(r22);
    }
    var v22 = getArrayU8FromWasm0(r0, r1).slice();
    wasm3.__wbindgen_free(r0, r1 * 1, 1);
    return v22;
  } finally {
    wasm3.__wbindgen_add_to_stack_pointer(16);
  }
}
function instantiate() {
  return instantiateWithInstance().exports;
}
function instantiateWithInstance() {
  if (instanceWithExports == null) {
    const instance = instantiateInstance();
    wasm3 = instance.exports;
    cachedInt32Memory0 = new Int32Array(wasm3.memory.buffer);
    cachedUint8Memory0 = new Uint8Array(wasm3.memory.buffer);
    instanceWithExports = {
      instance,
      exports: { digest, DigestContext }
    };
  }
  return instanceWithExports;
}
function instantiateInstance() {
  const wasmBytes = base64decode(
    "     "
  );
  const wasmModule = new WebAssembly.Module(wasmBytes);
  return new WebAssembly.Instance(wasmModule, imports);
}
function base64decode(b64) {
  const binString = atob(b64);
  const size = binString.length;
  const bytes = new Uint8Array(size);
  for (let i6 = 0; i6 < size; i6++) {
    bytes[i6] = binString.charCodeAt(i6);
  }
  return bytes;
}
var wasm3, heap2, heap_next2, cachedTextDecoder3, cachedUint8Memory0, WASM_VECTOR_LEN2, cachedTextEncoder3, encodeString3, cachedInt32Memory0, DigestContextFinalization, DigestContext, imports, instanceWithExports;
var init_deno_std_wasm_crypto_generated = __esm({
  "https://jsr.io/@std/crypto/1.0.4/_wasm/lib/deno_std_wasm_crypto.generated.mjs"() {
    heap2 = new Array(128).fill(void 0);
    heap2.push(void 0, null, true, false);
    heap_next2 = heap2.length;
    cachedTextDecoder3 = typeof TextDecoder !== "undefined" ? new TextDecoder("utf-8", { ignoreBOM: true, fatal: true }) : {
      decode: () => {
        throw Error("TextDecoder not available");
      }
    };
    if (typeof TextDecoder !== "undefined") cachedTextDecoder3.decode();
    cachedUint8Memory0 = null;
    WASM_VECTOR_LEN2 = 0;
    cachedTextEncoder3 = typeof TextEncoder !== "undefined" ? new TextEncoder("utf-8") : {
      encode: () => {
        throw Error("TextEncoder not available");
      }
    };
    encodeString3 = function(arg, view) {
      return cachedTextEncoder3.encodeInto(arg, view);
    };
    cachedInt32Memory0 = null;
    DigestContextFinalization = typeof FinalizationRegistry === "undefined" ? { register: () => {
    }, unregister: () => {
    } } : new FinalizationRegistry((ptr) => wasm3.__wbg_digestcontext_free(ptr >>> 0));
    DigestContext = class {
      __destroy_into_raw() {
        const ptr = this.__wbg_ptr;
        this.__wbg_ptr = 0;
        DigestContextFinalization.unregister(this);
        return ptr;
      }
      free() {
        const ptr = this.__destroy_into_raw();
        wasm3.__wbg_digestcontext_free(ptr);
      }
      /**
       * Creates a new context incrementally computing a digest using the given
       * hash algorithm.
       *
       * An error will be thrown if `algorithm` is not a supported hash algorithm.
       * @param {string} algorithm
       */
      constructor(algorithm) {
        try {
          const retptr = wasm3.__wbindgen_add_to_stack_pointer(-16);
          const ptr0 = passStringToWasm02(
            algorithm,
            wasm3.__wbindgen_malloc,
            wasm3.__wbindgen_realloc
          );
          const len0 = WASM_VECTOR_LEN2;
          wasm3.digestcontext_new(retptr, ptr0, len0);
          var r0 = getInt32Memory02()[retptr / 4 + 0];
          var r1 = getInt32Memory02()[retptr / 4 + 1];
          var r22 = getInt32Memory02()[retptr / 4 + 2];
          if (r22) {
            throw takeObject2(r1);
          }
          this.__wbg_ptr = r0 >>> 0;
          return this;
        } finally {
          wasm3.__wbindgen_add_to_stack_pointer(16);
        }
      }
      /**
       * Update the digest's internal state with the additional input `data`.
       *
       * If the `data` array view is large, it will be split into subarrays (via
       * JavaScript bindings) which will be processed sequentially in order to
       * limit the amount of memory that needs to be allocated in the Wasm heap.
       * @param {Uint8Array} data
       */
      update(data3) {
        try {
          const retptr = wasm3.__wbindgen_add_to_stack_pointer(-16);
          wasm3.digestcontext_update(retptr, this.__wbg_ptr, addHeapObject2(data3));
          var r0 = getInt32Memory02()[retptr / 4 + 0];
          var r1 = getInt32Memory02()[retptr / 4 + 1];
          if (r1) {
            throw takeObject2(r0);
          }
        } finally {
          wasm3.__wbindgen_add_to_stack_pointer(16);
        }
      }
      /**
       * Returns the digest of the input data so far, and then drops the context
       * from memory on the Wasm side. This context must no longer be used, and any
       * further method calls will result in null pointer errors being thrown.
       * https://github.com/rustwasm/wasm-bindgen/blob/bf39cfd8/crates/backend/src/codegen.rs#L186
       *
       * `length` will usually be left `undefined` to use the default length for
       * the algorithm. For algorithms with variable-length output, it can be used
       * to specify a non-negative integer number of bytes.
       *
       * An error will be thrown if `length` is not a supported length for the algorithm.
       * @param {number | undefined} [length]
       * @returns {Uint8Array}
       */
      digestAndDrop(length) {
        try {
          const ptr = this.__destroy_into_raw();
          const retptr = wasm3.__wbindgen_add_to_stack_pointer(-16);
          wasm3.digestcontext_digestAndDrop(
            retptr,
            ptr,
            !isLikeNone(length),
            isLikeNone(length) ? 0 : length
          );
          var r0 = getInt32Memory02()[retptr / 4 + 0];
          var r1 = getInt32Memory02()[retptr / 4 + 1];
          var r22 = getInt32Memory02()[retptr / 4 + 2];
          var r32 = getInt32Memory02()[retptr / 4 + 3];
          if (r32) {
            throw takeObject2(r22);
          }
          var v1 = getArrayU8FromWasm0(r0, r1).slice();
          wasm3.__wbindgen_free(r0, r1 * 1, 1);
          return v1;
        } finally {
          wasm3.__wbindgen_add_to_stack_pointer(16);
        }
      }
    };
    imports = {
      __wbindgen_placeholder__: {
        __wbg_new_5dd86ebc917d9f52: function(arg0, arg1) {
          const ret = new TypeError(getStringFromWasm03(arg0, arg1));
          return addHeapObject2(ret);
        },
        __wbindgen_object_drop_ref: function(arg0) {
          takeObject2(arg0);
        },
        __wbg_byteLength_58f7b4fab1919d44: function(arg0) {
          const ret = getObject2(arg0).byteLength;
          return ret;
        },
        __wbg_byteOffset_81d60f7392524f62: function(arg0) {
          const ret = getObject2(arg0).byteOffset;
          return ret;
        },
        __wbg_buffer_dd7f74bc60f1faab: function(arg0) {
          const ret = getObject2(arg0).buffer;
          return addHeapObject2(ret);
        },
        __wbg_newwithbyteoffsetandlength_aa4a17c33a06e5cb: function(arg0, arg1, arg2) {
          const ret = new Uint8Array(getObject2(arg0), arg1 >>> 0, arg2 >>> 0);
          return addHeapObject2(ret);
        },
        __wbg_length_c20a40f15020d68a: function(arg0) {
          const ret = getObject2(arg0).length;
          return ret;
        },
        __wbindgen_memory: function() {
          const ret = wasm3.memory;
          return addHeapObject2(ret);
        },
        __wbg_buffer_12d079cc21e14bdb: function(arg0) {
          const ret = getObject2(arg0).buffer;
          return addHeapObject2(ret);
        },
        __wbg_new_63b92bc8671ed464: function(arg0) {
          const ret = new Uint8Array(getObject2(arg0));
          return addHeapObject2(ret);
        },
        __wbg_set_a47bac70306a19a7: function(arg0, arg1, arg2) {
          getObject2(arg0).set(getObject2(arg1), arg2 >>> 0);
        },
        __wbindgen_throw: function(arg0, arg1) {
          throw new Error(getStringFromWasm03(arg0, arg1));
        }
      }
    };
  }
});

// https://jsr.io/@std/crypto/1.0.4/_wasm/mod.ts
var DIGEST_ALGORITHM_NAMES;
var init_mod19 = __esm({
  "https://jsr.io/@std/crypto/1.0.4/_wasm/mod.ts"() {
    init_deno_std_wasm_crypto_generated();
    DIGEST_ALGORITHM_NAMES = [
      "BLAKE2B",
      "BLAKE2B-128",
      "BLAKE2B-160",
      "BLAKE2B-224",
      "BLAKE2B-256",
      "BLAKE2B-384",
      "BLAKE2S",
      "BLAKE3",
      "KECCAK-224",
      "KECCAK-256",
      "KECCAK-384",
      "KECCAK-512",
      "SHA-384",
      "SHA3-224",
      "SHA3-256",
      "SHA3-384",
      "SHA3-512",
      "SHAKE128",
      "SHAKE256",
      "TIGER",
      // insecure (length-extendable):
      "RIPEMD-160",
      "SHA-224",
      "SHA-256",
      "SHA-512",
      // insecure (length-extendable and collidable):
      "MD4",
      "MD5",
      "SHA-1",
      // insecure (non-cryptographic)
      "FNV32",
      "FNV32A",
      "FNV64",
      "FNV64A"
    ];
  }
});

// https://jsr.io/@std/crypto/1.0.4/crypto.ts
function toUint8Array(data3) {
  if (data3 instanceof Uint8Array) {
    return data3;
  } else if (ArrayBuffer.isView(data3)) {
    return new Uint8Array(data3.buffer, data3.byteOffset, data3.byteLength);
  } else if (data3 instanceof ArrayBuffer) {
    return new Uint8Array(data3);
  }
  return void 0;
}
function assertValidDigestLength(value) {
  if (value !== void 0 && (value < 0 || value > MAX_DIGEST_LENGTH || !Number.isInteger(value))) {
    throw new RangeError(
      `length must be an integer between 0 and ${MAX_DIGEST_LENGTH}, inclusive`
    );
  }
}
function normalizeAlgorithm(algorithm) {
  return typeof algorithm === "string" ? { name: algorithm.toUpperCase() } : {
    ...algorithm,
    name: algorithm.name.toUpperCase()
  };
}
function isBufferSource(obj) {
  return obj instanceof ArrayBuffer || ArrayBuffer.isView(obj);
}
function isIterable(obj) {
  return typeof obj[Symbol.iterator] === "function";
}
function isAsyncIterable(obj) {
  return typeof obj[Symbol.asyncIterator] === "function";
}
var WEB_CRYPTO_DIGEST_ALGORITHM_NAMES, webCrypto, stdCrypto, MAX_DIGEST_LENGTH;
var init_crypto = __esm({
  "https://jsr.io/@std/crypto/1.0.4/crypto.ts"() {
    init_mod19();
    WEB_CRYPTO_DIGEST_ALGORITHM_NAMES = [
      "SHA-384",
      "SHA-256",
      "SHA-512",
      // insecure (length-extendable and collidable):
      "SHA-1"
    ];
    webCrypto = ((crypto2) => ({
      getRandomValues: crypto2.getRandomValues?.bind(crypto2),
      randomUUID: crypto2.randomUUID?.bind(crypto2),
      subtle: {
        decrypt: crypto2.subtle?.decrypt?.bind(crypto2.subtle),
        deriveBits: crypto2.subtle?.deriveBits?.bind(crypto2.subtle),
        deriveKey: crypto2.subtle?.deriveKey?.bind(crypto2.subtle),
        digest: crypto2.subtle?.digest?.bind(crypto2.subtle),
        encrypt: crypto2.subtle?.encrypt?.bind(crypto2.subtle),
        exportKey: crypto2.subtle?.exportKey?.bind(crypto2.subtle),
        generateKey: crypto2.subtle?.generateKey?.bind(crypto2.subtle),
        importKey: crypto2.subtle?.importKey?.bind(crypto2.subtle),
        sign: crypto2.subtle?.sign?.bind(crypto2.subtle),
        unwrapKey: crypto2.subtle?.unwrapKey?.bind(crypto2.subtle),
        verify: crypto2.subtle?.verify?.bind(crypto2.subtle),
        wrapKey: crypto2.subtle?.wrapKey?.bind(crypto2.subtle)
      }
    }))(globalThis.crypto);
    stdCrypto = /* @__PURE__ */ ((x3) => x3)({
      ...webCrypto,
      subtle: {
        ...webCrypto.subtle,
        /**
         * Polyfills stream support until the Web Crypto API does so:
         * @see {@link https://github.com/wintercg/proposal-webcrypto-streams}
         */
        async digest(algorithm, data3) {
          const { name: name2, length } = normalizeAlgorithm(algorithm);
          assertValidDigestLength(length);
          if (
            // if the algorithm is supported by the WebCrypto standard,
            WEB_CRYPTO_DIGEST_ALGORITHM_NAMES.includes(
              name2
            ) && // and the data is a single buffer,
            isBufferSource(data3)
          ) {
            return await webCrypto.subtle.digest(algorithm, data3);
          } else if (DIGEST_ALGORITHM_NAMES.includes(name2)) {
            if (isBufferSource(data3)) {
              return stdCrypto.subtle.digestSync(algorithm, data3);
            } else if (isIterable(data3)) {
              return stdCrypto.subtle.digestSync(
                algorithm,
                data3
              );
            } else if (isAsyncIterable(data3)) {
              const wasmCrypto = instantiate();
              const context = new wasmCrypto.DigestContext(name2);
              for await (const chunk of data3) {
                const chunkBytes = toUint8Array(chunk);
                if (!chunkBytes) {
                  throw new TypeError(
                    "Cannot digest the data: A chunk is not ArrayBuffer nor ArrayBufferView"
                  );
                }
                context.update(chunkBytes);
              }
              return context.digestAndDrop(length).buffer;
            } else {
              throw new TypeError(
                "data must be a BufferSource or [Async]Iterable<BufferSource>"
              );
            }
          }
          return await webCrypto.subtle.digest(algorithm, data3);
        },
        digestSync(algorithm, data3) {
          const { name: name2, length } = normalizeAlgorithm(algorithm);
          assertValidDigestLength(length);
          const wasmCrypto = instantiate();
          if (isBufferSource(data3)) {
            const bytes = toUint8Array(data3);
            return wasmCrypto.digest(name2, bytes, length).buffer;
          }
          if (isIterable(data3)) {
            const context = new wasmCrypto.DigestContext(name2);
            for (const chunk of data3) {
              const chunkBytes = toUint8Array(chunk);
              if (!chunkBytes) {
                throw new TypeError(
                  "Cannot digest the data: A chunk is not ArrayBuffer nor ArrayBufferView"
                );
              }
              context.update(chunkBytes);
            }
            return context.digestAndDrop(length).buffer;
          }
          throw new TypeError(
            "data must be a BufferSource or Iterable<BufferSource>"
          );
        }
      }
    });
    MAX_DIGEST_LENGTH = 2147483647;
  }
});

// https://cdn.skypack.dev/-/blueimp-md5@v2.19.0-FsBtHB6ITwdC3L5Giq4Q/dist=es2019,mode=imports/optimized/blueimp-md5.js
function createCommonjsModule(fn, basedir, module2) {
  return module2 = {
    path: basedir,
    exports: {},
    require: function(path3, base3) {
      return commonjsRequire(path3, base3 === void 0 || base3 === null ? module2.path : base3);
    }
  }, fn(module2, module2.exports), module2.exports;
}
function commonjsRequire() {
  throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs");
}
var commonjsGlobal, md5, blueimp_md5_default;
var init_blueimp_md5 = __esm({
  "https://cdn.skypack.dev/-/blueimp-md5@v2.19.0-FsBtHB6ITwdC3L5Giq4Q/dist=es2019,mode=imports/optimized/blueimp-md5.js"() {
    commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
    md5 = createCommonjsModule(function(module2) {
      (function($2) {
        function safeAdd(x3, y4) {
          var lsw = (x3 & 65535) + (y4 & 65535);
          var msw = (x3 >> 16) + (y4 >> 16) + (lsw >> 16);
          return msw << 16 | lsw & 65535;
        }
        function bitRotateLeft(num, cnt) {
          return num << cnt | num >>> 32 - cnt;
        }
        function md5cmn(q2, a5, b3, x3, s5, t5) {
          return safeAdd(bitRotateLeft(safeAdd(safeAdd(a5, q2), safeAdd(x3, t5)), s5), b3);
        }
        function md5ff(a5, b3, c6, d4, x3, s5, t5) {
          return md5cmn(b3 & c6 | ~b3 & d4, a5, b3, x3, s5, t5);
        }
        function md5gg(a5, b3, c6, d4, x3, s5, t5) {
          return md5cmn(b3 & d4 | c6 & ~d4, a5, b3, x3, s5, t5);
        }
        function md5hh(a5, b3, c6, d4, x3, s5, t5) {
          return md5cmn(b3 ^ c6 ^ d4, a5, b3, x3, s5, t5);
        }
        function md5ii(a5, b3, c6, d4, x3, s5, t5) {
          return md5cmn(c6 ^ (b3 | ~d4), a5, b3, x3, s5, t5);
        }
        function binlMD5(x3, len) {
          x3[len >> 5] |= 128 << len % 32;
          x3[(len + 64 >>> 9 << 4) + 14] = len;
          var i6;
          var olda;
          var oldb;
          var oldc;
          var oldd;
          var a5 = 1732584193;
          var b3 = -271733879;
          var c6 = -1732584194;
          var d4 = 271733878;
          for (i6 = 0; i6 < x3.length; i6 += 16) {
            olda = a5;
            oldb = b3;
            oldc = c6;
            oldd = d4;
            a5 = md5ff(a5, b3, c6, d4, x3[i6], 7, -680876936);
            d4 = md5ff(d4, a5, b3, c6, x3[i6 + 1], 12, -389564586);
            c6 = md5ff(c6, d4, a5, b3, x3[i6 + 2], 17, 606105819);
            b3 = md5ff(b3, c6, d4, a5, x3[i6 + 3], 22, -1044525330);
            a5 = md5ff(a5, b3, c6, d4, x3[i6 + 4], 7, -176418897);
            d4 = md5ff(d4, a5, b3, c6, x3[i6 + 5], 12, 1200080426);
            c6 = md5ff(c6, d4, a5, b3, x3[i6 + 6], 17, -1473231341);
            b3 = md5ff(b3, c6, d4, a5, x3[i6 + 7], 22, -45705983);
            a5 = md5ff(a5, b3, c6, d4, x3[i6 + 8], 7, 1770035416);
            d4 = md5ff(d4, a5, b3, c6, x3[i6 + 9], 12, -1958414417);
            c6 = md5ff(c6, d4, a5, b3, x3[i6 + 10], 17, -42063);
            b3 = md5ff(b3, c6, d4, a5, x3[i6 + 11], 22, -1990404162);
            a5 = md5ff(a5, b3, c6, d4, x3[i6 + 12], 7, 1804603682);
            d4 = md5ff(d4, a5, b3, c6, x3[i6 + 13], 12, -40341101);
            c6 = md5ff(c6, d4, a5, b3, x3[i6 + 14], 17, -1502002290);
            b3 = md5ff(b3, c6, d4, a5, x3[i6 + 15], 22, 1236535329);
            a5 = md5gg(a5, b3, c6, d4, x3[i6 + 1], 5, -165796510);
            d4 = md5gg(d4, a5, b3, c6, x3[i6 + 6], 9, -1069501632);
            c6 = md5gg(c6, d4, a5, b3, x3[i6 + 11], 14, 643717713);
            b3 = md5gg(b3, c6, d4, a5, x3[i6], 20, -373897302);
            a5 = md5gg(a5, b3, c6, d4, x3[i6 + 5], 5, -701558691);
            d4 = md5gg(d4, a5, b3, c6, x3[i6 + 10], 9, 38016083);
            c6 = md5gg(c6, d4, a5, b3, x3[i6 + 15], 14, -660478335);
            b3 = md5gg(b3, c6, d4, a5, x3[i6 + 4], 20, -405537848);
            a5 = md5gg(a5, b3, c6, d4, x3[i6 + 9], 5, 568446438);
            d4 = md5gg(d4, a5, b3, c6, x3[i6 + 14], 9, -1019803690);
            c6 = md5gg(c6, d4, a5, b3, x3[i6 + 3], 14, -187363961);
            b3 = md5gg(b3, c6, d4, a5, x3[i6 + 8], 20, 1163531501);
            a5 = md5gg(a5, b3, c6, d4, x3[i6 + 13], 5, -1444681467);
            d4 = md5gg(d4, a5, b3, c6, x3[i6 + 2], 9, -51403784);
            c6 = md5gg(c6, d4, a5, b3, x3[i6 + 7], 14, 1735328473);
            b3 = md5gg(b3, c6, d4, a5, x3[i6 + 12], 20, -1926607734);
            a5 = md5hh(a5, b3, c6, d4, x3[i6 + 5], 4, -378558);
            d4 = md5hh(d4, a5, b3, c6, x3[i6 + 8], 11, -2022574463);
            c6 = md5hh(c6, d4, a5, b3, x3[i6 + 11], 16, 1839030562);
            b3 = md5hh(b3, c6, d4, a5, x3[i6 + 14], 23, -35309556);
            a5 = md5hh(a5, b3, c6, d4, x3[i6 + 1], 4, -1530992060);
            d4 = md5hh(d4, a5, b3, c6, x3[i6 + 4], 11, 1272893353);
            c6 = md5hh(c6, d4, a5, b3, x3[i6 + 7], 16, -155497632);
            b3 = md5hh(b3, c6, d4, a5, x3[i6 + 10], 23, -1094730640);
            a5 = md5hh(a5, b3, c6, d4, x3[i6 + 13], 4, 681279174);
            d4 = md5hh(d4, a5, b3, c6, x3[i6], 11, -358537222);
            c6 = md5hh(c6, d4, a5, b3, x3[i6 + 3], 16, -722521979);
            b3 = md5hh(b3, c6, d4, a5, x3[i6 + 6], 23, 76029189);
            a5 = md5hh(a5, b3, c6, d4, x3[i6 + 9], 4, -640364487);
            d4 = md5hh(d4, a5, b3, c6, x3[i6 + 12], 11, -421815835);
            c6 = md5hh(c6, d4, a5, b3, x3[i6 + 15], 16, 530742520);
            b3 = md5hh(b3, c6, d4, a5, x3[i6 + 2], 23, -995338651);
            a5 = md5ii(a5, b3, c6, d4, x3[i6], 6, -198630844);
            d4 = md5ii(d4, a5, b3, c6, x3[i6 + 7], 10, 1126891415);
            c6 = md5ii(c6, d4, a5, b3, x3[i6 + 14], 15, -1416354905);
            b3 = md5ii(b3, c6, d4, a5, x3[i6 + 5], 21, -57434055);
            a5 = md5ii(a5, b3, c6, d4, x3[i6 + 12], 6, 1700485571);
            d4 = md5ii(d4, a5, b3, c6, x3[i6 + 3], 10, -1894986606);
            c6 = md5ii(c6, d4, a5, b3, x3[i6 + 10], 15, -1051523);
            b3 = md5ii(b3, c6, d4, a5, x3[i6 + 1], 21, -2054922799);
            a5 = md5ii(a5, b3, c6, d4, x3[i6 + 8], 6, 1873313359);
            d4 = md5ii(d4, a5, b3, c6, x3[i6 + 15], 10, -30611744);
            c6 = md5ii(c6, d4, a5, b3, x3[i6 + 6], 15, -1560198380);
            b3 = md5ii(b3, c6, d4, a5, x3[i6 + 13], 21, 1309151649);
            a5 = md5ii(a5, b3, c6, d4, x3[i6 + 4], 6, -145523070);
            d4 = md5ii(d4, a5, b3, c6, x3[i6 + 11], 10, -1120210379);
            c6 = md5ii(c6, d4, a5, b3, x3[i6 + 2], 15, 718787259);
            b3 = md5ii(b3, c6, d4, a5, x3[i6 + 9], 21, -343485551);
            a5 = safeAdd(a5, olda);
            b3 = safeAdd(b3, oldb);
            c6 = safeAdd(c6, oldc);
            d4 = safeAdd(d4, oldd);
          }
          return [a5, b3, c6, d4];
        }
        function binl2rstr(input) {
          var i6;
          var output = "";
          var length32 = input.length * 32;
          for (i6 = 0; i6 < length32; i6 += 8) {
            output += String.fromCharCode(input[i6 >> 5] >>> i6 % 32 & 255);
          }
          return output;
        }
        function rstr2binl(input) {
          var i6;
          var output = [];
          output[(input.length >> 2) - 1] = void 0;
          for (i6 = 0; i6 < output.length; i6 += 1) {
            output[i6] = 0;
          }
          var length8 = input.length * 8;
          for (i6 = 0; i6 < length8; i6 += 8) {
            output[i6 >> 5] |= (input.charCodeAt(i6 / 8) & 255) << i6 % 32;
          }
          return output;
        }
        function rstrMD5(s5) {
          return binl2rstr(binlMD5(rstr2binl(s5), s5.length * 8));
        }
        function rstrHMACMD5(key, data3) {
          var i6;
          var bkey = rstr2binl(key);
          var ipad = [];
          var opad = [];
          var hash;
          ipad[15] = opad[15] = void 0;
          if (bkey.length > 16) {
            bkey = binlMD5(bkey, key.length * 8);
          }
          for (i6 = 0; i6 < 16; i6 += 1) {
            ipad[i6] = bkey[i6] ^ 909522486;
            opad[i6] = bkey[i6] ^ 1549556828;
          }
          hash = binlMD5(ipad.concat(rstr2binl(data3)), 512 + data3.length * 8);
          return binl2rstr(binlMD5(opad.concat(hash), 512 + 128));
        }
        function rstr2hex(input) {
          var hexTab = "0123456789abcdef";
          var output = "";
          var x3;
          var i6;
          for (i6 = 0; i6 < input.length; i6 += 1) {
            x3 = input.charCodeAt(i6);
            output += hexTab.charAt(x3 >>> 4 & 15) + hexTab.charAt(x3 & 15);
          }
          return output;
        }
        function str2rstrUTF8(input) {
          return unescape(encodeURIComponent(input));
        }
        function rawMD5(s5) {
          return rstrMD5(str2rstrUTF8(s5));
        }
        function hexMD5(s5) {
          return rstr2hex(rawMD5(s5));
        }
        function rawHMACMD5(k3, d4) {
          return rstrHMACMD5(str2rstrUTF8(k3), str2rstrUTF8(d4));
        }
        function hexHMACMD5(k3, d4) {
          return rstr2hex(rawHMACMD5(k3, d4));
        }
        function md52(string2, key, raw) {
          if (!key) {
            if (!raw) {
              return hexMD5(string2);
            }
            return rawMD5(string2);
          }
          if (!raw) {
            return hexHMACMD5(key, string2);
          }
          return rawHMACMD5(key, string2);
        }
        if (module2.exports) {
          module2.exports = md52;
        } else {
          $2.md5 = md52;
        }
      })(commonjsGlobal);
    });
    blueimp_md5_default = md5;
  }
});

// https://cdn.skypack.dev/blueimp-md5@2.19.0
var init_blueimp_md5_2_19 = __esm({
  "https://cdn.skypack.dev/blueimp-md5@2.19.0"() {
    init_blueimp_md5();
    init_blueimp_md5();
  }
});

// core/hash.ts
function md5HashSync(content) {
  return blueimp_md5_default(content);
}
async function md5HashAsync(content) {
  const buffer2 = new TextEncoder().encode(content);
  return md5HashBytes(buffer2);
}
async function md5HashBytes(content) {
  const buffer2 = await stdCrypto.subtle.digest(
    "MD5",
    content
  );
  return Array.from(new Uint8Array(buffer2)).map((b3) => b3.toString(16).padStart(2, "0")).join("");
}
function insecureHash(content) {
  let hash = 0;
  for (let i6 = 0; i6 < content.length; i6++) {
    const char = content.charCodeAt(i6);
    hash = (hash << 5) - hash + char;
    hash &= hash;
  }
  return new Uint32Array([hash])[0].toString(36);
}
var init_hash2 = __esm({
  "core/hash.ts"() {
    init_crypto();
    init_blueimp_md5_2_19();
  }
});

// core/sass/cache.ts
async function checkVersion2(kv, path3) {
  const version4 = await kv.get(["version"]);
  if (version4.value === null) {
    await kv.set(["version"], 1);
  } else {
    if (typeof version4.value !== "number") {
      throw new Error(
        `Unsupported SassCache version type in ${path3}
Expected number, got ${typeof version4.value}`
      );
    }
    if (version4.value < currentSassCacheVersion) {
      throw new Error(
        `Found outdated SassCache version. Please clear ${path3}.`
      );
    }
    if (version4.value > currentSassCacheVersion) {
      throw new Error(
        `Found a SassCache version that's newer than supported. Please clear ${path3} or upgrade Quarto to ${requiredQuartoVersions[currentSassCacheVersion]} or later.`
      );
    }
  }
}
async function sassCache(path3, temp) {
  if (!_sassCache[path3]) {
    debug(`Creating SassCache at ${path3}`);
    ensureDirSync(path3);
    const kvFile = join4(path3, "sass.kv");
    const kv = await Deno.openKv(kvFile);
    await checkVersion2(kv, kvFile);
    _sassCache[path3] = new SassCache(kv, path3);
    _sassCache[path3].cleanup(temp);
  }
  debug(`Returning SassCache at ${path3}`);
  const result2 = _sassCache[path3];
  return result2;
}
var SassCache, currentSassCacheVersion, requiredQuartoVersions, _sassCache;
var init_cache2 = __esm({
  "core/sass/cache.ts"() {
    init_error2();
    init_hash2();
    init_path();
    init_fs();
    init_path2();
    init_log();
    init_cleanup();
    SassCache = class {
      kv;
      path;
      clone() {
        return this;
      }
      constructor(kv, path3) {
        this.kv = kv;
        this.path = path3;
      }
      async getFromHash(hash, inputHash, force) {
        debug(
          `SassCache.getFromHash(hash=${hash}, inputHash=${inputHash}, force=${force})`
        );
        if (hash.length !== 32 || !/^[0-9a-f]{32}$/.test(hash)) {
          throw new InternalError(`Invalid hash length: ${hash.length}`);
        }
        const result2 = await this.kv.get(["entry", hash]);
        if (result2.value === null) {
          debug(`  cache miss`);
          return null;
        }
        if (typeof result2.value !== "object") {
          throw new InternalError(
            `Unsupported SassCache entry type
Expected SassCacheEntry, got ${typeof result2.value}`
          );
        }
        const v4 = result2.value;
        if (typeof v4.key !== "string" || typeof v4.hash !== "string") {
          throw new InternalError(
            `Unsupported SassCache entry type
Expected SassCacheEntry, got ${typeof result2.value}`
          );
        }
        const outputFilePath = join4(this.path, `${hash}.css`);
        if (v4.hash !== inputHash && !force || !existsSync2(outputFilePath)) {
          if (v4.hash !== inputHash) {
            debug(`  hash mismatch: ${v4.hash} !== ${inputHash}`);
          } else if (force) {
            debug(`  forcing recomputation`);
          } else {
            debug(`  output file missing: ${outputFilePath}`);
          }
          return null;
        }
        debug(`  cache hit`);
        return outputFilePath;
      }
      async setFromHash(identifierHash, inputHash, cacheIdentifier, compilationThunk) {
        debug(`SassCache.setFromHash(${identifierHash}, ${inputHash}), ...`);
        const outputFilePath = join4(this.path, `${identifierHash}.css`);
        try {
          await compilationThunk(outputFilePath);
        } catch (error2) {
          try {
            safeRemoveIfExists(outputFilePath);
          } finally {
          }
          throw error2;
        }
        await this.kv.set(["entry", identifierHash], {
          key: cacheIdentifier,
          hash: inputHash
        });
        return outputFilePath;
      }
      async set(input, cacheIdentifier, compilationThunk) {
        const identifierHash = await md5HashAsync(cacheIdentifier);
        const inputHash = await md5HashAsync(input);
        return this.setFromHash(
          identifierHash,
          inputHash,
          cacheIdentifier,
          compilationThunk
        );
      }
      async getOrSet(input, cacheIdentifier, compilationThunk) {
        debug(`SassCache.getOrSet(...)`);
        const identifierHash = await md5HashAsync(cacheIdentifier);
        const inputHash = await md5HashAsync(input);
        const existing = await this.getFromHash(identifierHash, inputHash);
        if (existing !== null) {
          debug(`  cache hit`);
          return existing;
        }
        debug(`  cache miss, setting`);
        return this.setFromHash(
          identifierHash,
          inputHash,
          cacheIdentifier,
          compilationThunk
        );
      }
      // add a cleanup method to register a cleanup handler
      cleanup(temp) {
        const registerCleanup = temp ? temp.onCleanup : onCleanup;
        const cachePath2 = this.path;
        registerCleanup(() => {
          debug(`SassCache cleanup executing for ${cachePath2}`);
          try {
            this.kv.close();
            if (temp) safeRemoveIfExists(this.path);
          } catch (error2) {
            info(
              `Error occurred during sass cache cleanup for ${this.path}: ${error2}`
            );
          }
        });
      }
    };
    currentSassCacheVersion = 1;
    requiredQuartoVersions = {
      1: "1.6.0"
    };
    _sassCache = {};
  }
});

// https://cdn.skypack.dev/-/invariant@v2.2.4-dATvH51LFSHlzMqhAQS8/dist=es2019,mode=imports/optimized/invariant.js
var invariant, browser, invariant_default;
var init_invariant = __esm({
  "https://cdn.skypack.dev/-/invariant@v2.2.4-dATvH51LFSHlzMqhAQS8/dist=es2019,mode=imports/optimized/invariant.js"() {
    invariant = function(condition, format14, a5, b3, c6, d4, e5, f5) {
      if (!condition) {
        var error2;
        if (format14 === void 0) {
          error2 = new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");
        } else {
          var args = [a5, b3, c6, d4, e5, f5];
          var argIndex = 0;
          error2 = new Error(format14.replace(/%s/g, function() {
            return args[argIndex++];
          }));
          error2.name = "Invariant Violation";
        }
        error2.framesToPop = 1;
        throw error2;
      }
    };
    browser = invariant;
    invariant_default = browser;
  }
});

// https://cdn.skypack.dev/-/scss-parser@v1.0.6-hrwwdU1eImlkqs8SqYeB/dist=es2019,mode=imports/optimized/scss-parser.js
function createCommonjsModule2(fn, basedir, module2) {
  return module2 = {
    path: basedir,
    exports: {},
    require: function(path3, base3) {
      return commonjsRequire2(path3, base3 === void 0 || base3 === null ? module2.path : base3);
    }
  }, fn(module2, module2.exports), module2.exports;
}
function commonjsRequire2() {
  throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs");
}
var commonjsGlobal2, lodash, InputStream, inputStream, HEX_PATTERN, not, is_char, is_whitespace, is_newline, is_operator, is_operator_repeatable, is_punctuation, is_digit, is_comment_start, is_ident_start, is_ident, is_number_start, is_hex, TokenStream, tokenStream, Parser, parse10, type3, walkNode, walkValue, stringify3, parse$1, stringify$1, lib, parse$2, stringify$2;
var init_scss_parser = __esm({
  "https://cdn.skypack.dev/-/scss-parser@v1.0.6-hrwwdU1eImlkqs8SqYeB/dist=es2019,mode=imports/optimized/scss-parser.js"() {
    init_invariant();
    commonjsGlobal2 = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
    lodash = createCommonjsModule2(function(module2, exports23) {
      (function() {
        var undefined$1;
        var VERSION = "4.17.20";
        var LARGE_ARRAY_SIZE = 200;
        var CORE_ERROR_TEXT = "Unsupported core-js use. Try https://npms.io/search?q=ponyfill.", FUNC_ERROR_TEXT = "Expected a function";
        var HASH_UNDEFINED = "__lodash_hash_undefined__";
        var MAX_MEMOIZE_SIZE = 500;
        var PLACEHOLDER = "__lodash_placeholder__";
        var CLONE_DEEP_FLAG = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG = 4;
        var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2;
        var WRAP_BIND_FLAG = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_BOUND_FLAG = 4, WRAP_CURRY_FLAG = 8, WRAP_CURRY_RIGHT_FLAG = 16, WRAP_PARTIAL_FLAG = 32, WRAP_PARTIAL_RIGHT_FLAG = 64, WRAP_ARY_FLAG = 128, WRAP_REARG_FLAG = 256, WRAP_FLIP_FLAG = 512;
        var DEFAULT_TRUNC_LENGTH = 30, DEFAULT_TRUNC_OMISSION = "...";
        var HOT_COUNT = 800, HOT_SPAN = 16;
        var LAZY_FILTER_FLAG = 1, LAZY_MAP_FLAG = 2, LAZY_WHILE_FLAG = 3;
        var INFINITY = 1 / 0, MAX_SAFE_INTEGER2 = 9007199254740991, MAX_INTEGER = 17976931348623157e292, NAN = 0 / 0;
        var MAX_ARRAY_LENGTH = 4294967295, MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1;
        var wrapFlags = [
          ["ary", WRAP_ARY_FLAG],
          ["bind", WRAP_BIND_FLAG],
          ["bindKey", WRAP_BIND_KEY_FLAG],
          ["curry", WRAP_CURRY_FLAG],
          ["curryRight", WRAP_CURRY_RIGHT_FLAG],
          ["flip", WRAP_FLIP_FLAG],
          ["partial", WRAP_PARTIAL_FLAG],
          ["partialRight", WRAP_PARTIAL_RIGHT_FLAG],
          ["rearg", WRAP_REARG_FLAG]
        ];
        var argsTag = "[object Arguments]", arrayTag = "[object Array]", asyncTag = "[object AsyncFunction]", boolTag = "[object Boolean]", dateTag = "[object Date]", domExcTag = "[object DOMException]", errorTag = "[object Error]", funcTag = "[object Function]", genTag = "[object GeneratorFunction]", mapTag = "[object Map]", numberTag = "[object Number]", nullTag = "[object Null]", objectTag = "[object Object]", promiseTag = "[object Promise]", proxyTag = "[object Proxy]", regexpTag = "[object RegExp]", setTag = "[object Set]", stringTag = "[object String]", symbolTag = "[object Symbol]", undefinedTag = "[object Undefined]", weakMapTag = "[object WeakMap]", weakSetTag = "[object WeakSet]";
        var arrayBufferTag = "[object ArrayBuffer]", dataViewTag = "[object DataView]", float32Tag = "[object Float32Array]", float64Tag = "[object Float64Array]", int8Tag = "[object Int8Array]", int16Tag = "[object Int16Array]", int32Tag = "[object Int32Array]", uint8Tag = "[object Uint8Array]", uint8ClampedTag = "[object Uint8ClampedArray]", uint16Tag = "[object Uint16Array]", uint32Tag = "[object Uint32Array]";
        var reEmptyStringLeading = /\b__p \+= '';/g, reEmptyStringMiddle = /\b(__p \+=) '' \+/g, reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
        var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, reUnescapedHtml = /[&<>"']/g, reHasEscapedHtml = RegExp(reEscapedHtml.source), reHasUnescapedHtml = RegExp(reUnescapedHtml.source);
        var reEscape = /<%-([\s\S]+?)%>/g, reEvaluate = /<%([\s\S]+?)%>/g, reInterpolate = /<%=([\s\S]+?)%>/g;
        var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
        var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, reHasRegExpChar = RegExp(reRegExpChar.source);
        var reTrim = /^\s+|\s+$/g, reTrimStart = /^\s+/, reTrimEnd = /\s+$/;
        var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, reSplitDetails = /,? & /;
        var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;
        var reEscapeChar = /\\(\\)?/g;
        var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
        var reFlags = /\w*$/;
        var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
        var reIsBinary = /^0b[01]+$/i;
        var reIsHostCtor = /^\[object .+?Constructor\]$/;
        var reIsOctal = /^0o[0-7]+$/i;
        var reIsUint = /^(?:0|[1-9]\d*)$/;
        var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;
        var reNoMatch = /($^)/;
        var reUnescapedString = /['\n\r\u2028\u2029\\]/g;
        var rsAstralRange = "\\ud800-\\udfff", rsComboMarksRange = "\\u0300-\\u036f", reComboHalfMarksRange = "\\ufe20-\\ufe2f", rsComboSymbolsRange = "\\u20d0-\\u20ff", rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, rsDingbatRange = "\\u2700-\\u27bf", rsLowerRange = "a-z\\xdf-\\xf6\\xf8-\\xff", rsMathOpRange = "\\xac\\xb1\\xd7\\xf7", rsNonCharRange = "\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf", rsPunctuationRange = "\\u2000-\\u206f", rsSpaceRange = " \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000", rsUpperRange = "A-Z\\xc0-\\xd6\\xd8-\\xde", rsVarRange = "\\ufe0e\\ufe0f", rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;
        var rsApos = "['\u2019]", rsAstral = "[" + rsAstralRange + "]", rsBreak = "[" + rsBreakRange + "]", rsCombo = "[" + rsComboRange + "]", rsDigits = "\\d+", rsDingbat = "[" + rsDingbatRange + "]", rsLower = "[" + rsLowerRange + "]", rsMisc = "[^" + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + "]", rsFitz = "\\ud83c[\\udffb-\\udfff]", rsModifier = "(?:" + rsCombo + "|" + rsFitz + ")", rsNonAstral = "[^" + rsAstralRange + "]", rsRegional = "(?:\\ud83c[\\udde6-\\uddff]){2}", rsSurrPair = "[\\ud800-\\udbff][\\udc00-\\udfff]", rsUpper = "[" + rsUpperRange + "]", rsZWJ = "\\u200d";
        var rsMiscLower = "(?:" + rsLower + "|" + rsMisc + ")", rsMiscUpper = "(?:" + rsUpper + "|" + rsMisc + ")", rsOptContrLower = "(?:" + rsApos + "(?:d|ll|m|re|s|t|ve))?", rsOptContrUpper = "(?:" + rsApos + "(?:D|LL|M|RE|S|T|VE))?", reOptMod = rsModifier + "?", rsOptVar = "[" + rsVarRange + "]?", rsOptJoin = "(?:" + rsZWJ + "(?:" + [rsNonAstral, rsRegional, rsSurrPair].join("|") + ")" + rsOptVar + reOptMod + ")*", rsOrdLower = "\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])", rsOrdUpper = "\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])", rsSeq = rsOptVar + reOptMod + rsOptJoin, rsEmoji = "(?:" + [rsDingbat, rsRegional, rsSurrPair].join("|") + ")" + rsSeq, rsSymbol = "(?:" + [rsNonAstral + rsCombo + "?", rsCombo, rsRegional, rsSurrPair, rsAstral].join("|") + ")";
        var reApos = RegExp(rsApos, "g");
        var reComboMark = RegExp(rsCombo, "g");
        var reUnicode = RegExp(rsFitz + "(?=" + rsFitz + ")|" + rsSymbol + rsSeq, "g");
        var reUnicodeWord = RegExp([
          rsUpper + "?" + rsLower + "+" + rsOptContrLower + "(?=" + [rsBreak, rsUpper, "$"].join("|") + ")",
          rsMiscUpper + "+" + rsOptContrUpper + "(?=" + [rsBreak, rsUpper + rsMiscLower, "$"].join("|") + ")",
          rsUpper + "?" + rsMiscLower + "+" + rsOptContrLower,
          rsUpper + "+" + rsOptContrUpper,
          rsOrdUpper,
          rsOrdLower,
          rsDigits,
          rsEmoji
        ].join("|"), "g");
        var reHasUnicode = RegExp("[" + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + "]");
        var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;
        var contextProps = [
          "Array",
          "Buffer",
          "DataView",
          "Date",
          "Error",
          "Float32Array",
          "Float64Array",
          "Function",
          "Int8Array",
          "Int16Array",
          "Int32Array",
          "Map",
          "Math",
          "Object",
          "Promise",
          "RegExp",
          "Set",
          "String",
          "Symbol",
          "TypeError",
          "Uint8Array",
          "Uint8ClampedArray",
          "Uint16Array",
          "Uint32Array",
          "WeakMap",
          "_",
          "clearTimeout",
          "isFinite",
          "parseInt",
          "setTimeout"
        ];
        var templateCounter = -1;
        var typedArrayTags = {};
        typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true;
        typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
        var cloneableTags = {};
        cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[mapTag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[setTag] = cloneableTags[stringTag] = cloneableTags[symbolTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
        cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[weakMapTag] = false;
        var deburredLetters = {
          \u00C0: "A",
          \u00C1: "A",
          \u00C2: "A",
          \u00C3: "A",
          \u00C4: "A",
          \u00C5: "A",
          \u00E0: "a",
          \u00E1: "a",
          \u00E2: "a",
          \u00E3: "a",
          \u00E4: "a",
          \u00E5: "a",
          \u00C7: "C",
          \u00E7: "c",
          \u00D0: "D",
          \u00F0: "d",
          \u00C8: "E",
          \u00C9: "E",
          \u00CA: "E",
          \u00CB: "E",
          \u00E8: "e",
          \u00E9: "e",
          \u00EA: "e",
          \u00EB: "e",
          \u00CC: "I",
          \u00CD: "I",
          \u00CE: "I",
          \u00CF: "I",
          \u00EC: "i",
          \u00ED: "i",
          \u00EE: "i",
          \u00EF: "i",
          \u00D1: "N",
          \u00F1: "n",
          \u00D2: "O",
          \u00D3: "O",
          \u00D4: "O",
          \u00D5: "O",
          \u00D6: "O",
          \u00D8: "O",
          \u00F2: "o",
          \u00F3: "o",
          \u00F4: "o",
          \u00F5: "o",
          \u00F6: "o",
          \u00F8: "o",
          \u00D9: "U",
          \u00DA: "U",
          \u00DB: "U",
          \u00DC: "U",
          \u00F9: "u",
          \u00FA: "u",
          \u00FB: "u",
          \u00FC: "u",
          \u00DD: "Y",
          \u00FD: "y",
          \u00FF: "y",
          \u00C6: "Ae",
          \u00E6: "ae",
          \u00DE: "Th",
          \u00FE: "th",
          \u00DF: "ss",
          \u0100: "A",
          \u0102: "A",
          \u0104: "A",
          \u0101: "a",
          \u0103: "a",
          \u0105: "a",
          \u0106: "C",
          \u0108: "C",
          \u010A: "C",
          \u010C: "C",
          \u0107: "c",
          \u0109: "c",
          \u010B: "c",
          \u010D: "c",
          \u010E: "D",
          \u0110: "D",
          \u010F: "d",
          \u0111: "d",
          \u0112: "E",
          \u0114: "E",
          \u0116: "E",
          \u0118: "E",
          \u011A: "E",
          \u0113: "e",
          \u0115: "e",
          \u0117: "e",
          \u0119: "e",
          \u011B: "e",
          \u011C: "G",
          \u011E: "G",
          \u0120: "G",
          \u0122: "G",
          \u011D: "g",
          \u011F: "g",
          \u0121: "g",
          \u0123: "g",
          \u0124: "H",
          \u0126: "H",
          \u0125: "h",
          \u0127: "h",
          \u0128: "I",
          \u012A: "I",
          \u012C: "I",
          \u012E: "I",
          \u0130: "I",
          \u0129: "i",
          \u012B: "i",
          \u012D: "i",
          \u012F: "i",
          \u0131: "i",
          \u0134: "J",
          \u0135: "j",
          \u0136: "K",
          \u0137: "k",
          \u0138: "k",
          \u0139: "L",
          \u013B: "L",
          \u013D: "L",
          \u013F: "L",
          \u0141: "L",
          \u013A: "l",
          \u013C: "l",
          \u013E: "l",
          \u0140: "l",
          \u0142: "l",
          \u0143: "N",
          \u0145: "N",
          \u0147: "N",
          \u014A: "N",
          \u0144: "n",
          \u0146: "n",
          \u0148: "n",
          \u014B: "n",
          \u014C: "O",
          \u014E: "O",
          \u0150: "O",
          \u014D: "o",
          \u014F: "o",
          \u0151: "o",
          \u0154: "R",
          \u0156: "R",
          \u0158: "R",
          \u0155: "r",
          \u0157: "r",
          \u0159: "r",
          \u015A: "S",
          \u015C: "S",
          \u015E: "S",
          \u0160: "S",
          \u015B: "s",
          \u015D: "s",
          \u015F: "s",
          \u0161: "s",
          \u0162: "T",
          \u0164: "T",
          \u0166: "T",
          \u0163: "t",
          \u0165: "t",
          \u0167: "t",
          \u0168: "U",
          \u016A: "U",
          \u016C: "U",
          \u016E: "U",
          \u0170: "U",
          \u0172: "U",
          \u0169: "u",
          \u016B: "u",
          \u016D: "u",
          \u016F: "u",
          \u0171: "u",
          \u0173: "u",
          \u0174: "W",
          \u0175: "w",
          \u0176: "Y",
          \u0177: "y",
          \u0178: "Y",
          \u0179: "Z",
          \u017B: "Z",
          \u017D: "Z",
          \u017A: "z",
          \u017C: "z",
          \u017E: "z",
          \u0132: "IJ",
          \u0133: "ij",
          \u0152: "Oe",
          \u0153: "oe",
          \u0149: "'n",
          \u017F: "s"
        };
        var htmlEscapes = {
          "&": "&amp;",
          "<": "&lt;",
          ">": "&gt;",
          '"': "&quot;",
          "'": "&#39;"
        };
        var htmlUnescapes = {
          "&amp;": "&",
          "&lt;": "<",
          "&gt;": ">",
          "&quot;": '"',
          "&#39;": "'"
        };
        var stringEscapes = {
          "\\": "\\",
          "'": "'",
          "\n": "n",
          "\r": "r",
          "\u2028": "u2028",
          "\u2029": "u2029"
        };
        var freeParseFloat = parseFloat, freeParseInt = parseInt;
        var freeGlobal = typeof commonjsGlobal2 == "object" && commonjsGlobal2 && commonjsGlobal2.Object === Object && commonjsGlobal2;
        var freeSelf = typeof self == "object" && self && self.Object === Object && self;
        var root = freeGlobal || freeSelf || Function("return this")();
        var freeExports = exports23 && !exports23.nodeType && exports23;
        var freeModule = freeExports && true && module2 && !module2.nodeType && module2;
        var moduleExports = freeModule && freeModule.exports === freeExports;
        var freeProcess = moduleExports && freeGlobal.process;
        var nodeUtil = (function() {
          try {
            var types8 = freeModule && freeModule.require && freeModule.require("util").types;
            if (types8) {
              return types8;
            }
            return freeProcess && freeProcess.binding && freeProcess.binding("util");
          } catch (e5) {
          }
        })();
        var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, nodeIsDate = nodeUtil && nodeUtil.isDate, nodeIsMap = nodeUtil && nodeUtil.isMap, nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, nodeIsSet = nodeUtil && nodeUtil.isSet, nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
        function apply(func, thisArg, args) {
          switch (args.length) {
            case 0:
              return func.call(thisArg);
            case 1:
              return func.call(thisArg, args[0]);
            case 2:
              return func.call(thisArg, args[0], args[1]);
            case 3:
              return func.call(thisArg, args[0], args[1], args[2]);
          }
          return func.apply(thisArg, args);
        }
        function arrayAggregator(array, setter, iteratee, accumulator) {
          var index2 = -1, length = array == null ? 0 : array.length;
          while (++index2 < length) {
            var value = array[index2];
            setter(accumulator, value, iteratee(value), array);
          }
          return accumulator;
        }
        function arrayEach(array, iteratee) {
          var index2 = -1, length = array == null ? 0 : array.length;
          while (++index2 < length) {
            if (iteratee(array[index2], index2, array) === false) {
              break;
            }
          }
          return array;
        }
        function arrayEachRight(array, iteratee) {
          var length = array == null ? 0 : array.length;
          while (length--) {
            if (iteratee(array[length], length, array) === false) {
              break;
            }
          }
          return array;
        }
        function arrayEvery(array, predicate) {
          var index2 = -1, length = array == null ? 0 : array.length;
          while (++index2 < length) {
            if (!predicate(array[index2], index2, array)) {
              return false;
            }
          }
          return true;
        }
        function arrayFilter(array, predicate) {
          var index2 = -1, length = array == null ? 0 : array.length, resIndex = 0, result2 = [];
          while (++index2 < length) {
            var value = array[index2];
            if (predicate(value, index2, array)) {
              result2[resIndex++] = value;
            }
          }
          return result2;
        }
        function arrayIncludes(array, value) {
          var length = array == null ? 0 : array.length;
          return !!length && baseIndexOf(array, value, 0) > -1;
        }
        function arrayIncludesWith(array, value, comparator) {
          var index2 = -1, length = array == null ? 0 : array.length;
          while (++index2 < length) {
            if (comparator(value, array[index2])) {
              return true;
            }
          }
          return false;
        }
        function arrayMap(array, iteratee) {
          var index2 = -1, length = array == null ? 0 : array.length, result2 = Array(length);
          while (++index2 < length) {
            result2[index2] = iteratee(array[index2], index2, array);
          }
          return result2;
        }
        function arrayPush(array, values) {
          var index2 = -1, length = values.length, offset3 = array.length;
          while (++index2 < length) {
            array[offset3 + index2] = values[index2];
          }
          return array;
        }
        function arrayReduce(array, iteratee, accumulator, initAccum) {
          var index2 = -1, length = array == null ? 0 : array.length;
          if (initAccum && length) {
            accumulator = array[++index2];
          }
          while (++index2 < length) {
            accumulator = iteratee(accumulator, array[index2], index2, array);
          }
          return accumulator;
        }
        function arrayReduceRight(array, iteratee, accumulator, initAccum) {
          var length = array == null ? 0 : array.length;
          if (initAccum && length) {
            accumulator = array[--length];
          }
          while (length--) {
            accumulator = iteratee(accumulator, array[length], length, array);
          }
          return accumulator;
        }
        function arraySome(array, predicate) {
          var index2 = -1, length = array == null ? 0 : array.length;
          while (++index2 < length) {
            if (predicate(array[index2], index2, array)) {
              return true;
            }
          }
          return false;
        }
        var asciiSize = baseProperty("length");
        function asciiToArray(string2) {
          return string2.split("");
        }
        function asciiWords(string2) {
          return string2.match(reAsciiWord) || [];
        }
        function baseFindKey(collection, predicate, eachFunc) {
          var result2;
          eachFunc(collection, function(value, key, collection2) {
            if (predicate(value, key, collection2)) {
              result2 = key;
              return false;
            }
          });
          return result2;
        }
        function baseFindIndex(array, predicate, fromIndex, fromRight) {
          var length = array.length, index2 = fromIndex + (fromRight ? 1 : -1);
          while (fromRight ? index2-- : ++index2 < length) {
            if (predicate(array[index2], index2, array)) {
              return index2;
            }
          }
          return -1;
        }
        function baseIndexOf(array, value, fromIndex) {
          return value === value ? strictIndexOf(array, value, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex);
        }
        function baseIndexOfWith(array, value, fromIndex, comparator) {
          var index2 = fromIndex - 1, length = array.length;
          while (++index2 < length) {
            if (comparator(array[index2], value)) {
              return index2;
            }
          }
          return -1;
        }
        function baseIsNaN(value) {
          return value !== value;
        }
        function baseMean(array, iteratee) {
          var length = array == null ? 0 : array.length;
          return length ? baseSum(array, iteratee) / length : NAN;
        }
        function baseProperty(key) {
          return function(object) {
            return object == null ? undefined$1 : object[key];
          };
        }
        function basePropertyOf(object) {
          return function(key) {
            return object == null ? undefined$1 : object[key];
          };
        }
        function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) {
          eachFunc(collection, function(value, index2, collection2) {
            accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index2, collection2);
          });
          return accumulator;
        }
        function baseSortBy(array, comparer) {
          var length = array.length;
          array.sort(comparer);
          while (length--) {
            array[length] = array[length].value;
          }
          return array;
        }
        function baseSum(array, iteratee) {
          var result2, index2 = -1, length = array.length;
          while (++index2 < length) {
            var current3 = iteratee(array[index2]);
            if (current3 !== undefined$1) {
              result2 = result2 === undefined$1 ? current3 : result2 + current3;
            }
          }
          return result2;
        }
        function baseTimes(n5, iteratee) {
          var index2 = -1, result2 = Array(n5);
          while (++index2 < n5) {
            result2[index2] = iteratee(index2);
          }
          return result2;
        }
        function baseToPairs(object, props) {
          return arrayMap(props, function(key) {
            return [key, object[key]];
          });
        }
        function baseUnary(func) {
          return function(value) {
            return func(value);
          };
        }
        function baseValues(object, props) {
          return arrayMap(props, function(key) {
            return object[key];
          });
        }
        function cacheHas(cache3, key) {
          return cache3.has(key);
        }
        function charsStartIndex(strSymbols, chrSymbols) {
          var index2 = -1, length = strSymbols.length;
          while (++index2 < length && baseIndexOf(chrSymbols, strSymbols[index2], 0) > -1) {
          }
          return index2;
        }
        function charsEndIndex(strSymbols, chrSymbols) {
          var index2 = strSymbols.length;
          while (index2-- && baseIndexOf(chrSymbols, strSymbols[index2], 0) > -1) {
          }
          return index2;
        }
        function countHolders(array, placeholder2) {
          var length = array.length, result2 = 0;
          while (length--) {
            if (array[length] === placeholder2) {
              ++result2;
            }
          }
          return result2;
        }
        var deburrLetter = basePropertyOf(deburredLetters);
        var escapeHtmlChar = basePropertyOf(htmlEscapes);
        function escapeStringChar(chr) {
          return "\\" + stringEscapes[chr];
        }
        function getValue(object, key) {
          return object == null ? undefined$1 : object[key];
        }
        function hasUnicode(string2) {
          return reHasUnicode.test(string2);
        }
        function hasUnicodeWord(string2) {
          return reHasUnicodeWord.test(string2);
        }
        function iteratorToArray(iterator) {
          var data3, result2 = [];
          while (!(data3 = iterator.next()).done) {
            result2.push(data3.value);
          }
          return result2;
        }
        function mapToArray(map3) {
          var index2 = -1, result2 = Array(map3.size);
          map3.forEach(function(value, key) {
            result2[++index2] = [key, value];
          });
          return result2;
        }
        function overArg(func, transform) {
          return function(arg) {
            return func(transform(arg));
          };
        }
        function replaceHolders(array, placeholder2) {
          var index2 = -1, length = array.length, resIndex = 0, result2 = [];
          while (++index2 < length) {
            var value = array[index2];
            if (value === placeholder2 || value === PLACEHOLDER) {
              array[index2] = PLACEHOLDER;
              result2[resIndex++] = index2;
            }
          }
          return result2;
        }
        function setToArray(set3) {
          var index2 = -1, result2 = Array(set3.size);
          set3.forEach(function(value) {
            result2[++index2] = value;
          });
          return result2;
        }
        function setToPairs(set3) {
          var index2 = -1, result2 = Array(set3.size);
          set3.forEach(function(value) {
            result2[++index2] = [value, value];
          });
          return result2;
        }
        function strictIndexOf(array, value, fromIndex) {
          var index2 = fromIndex - 1, length = array.length;
          while (++index2 < length) {
            if (array[index2] === value) {
              return index2;
            }
          }
          return -1;
        }
        function strictLastIndexOf(array, value, fromIndex) {
          var index2 = fromIndex + 1;
          while (index2--) {
            if (array[index2] === value) {
              return index2;
            }
          }
          return index2;
        }
        function stringSize(string2) {
          return hasUnicode(string2) ? unicodeSize(string2) : asciiSize(string2);
        }
        function stringToArray(string2) {
          return hasUnicode(string2) ? unicodeToArray(string2) : asciiToArray(string2);
        }
        var unescapeHtmlChar = basePropertyOf(htmlUnescapes);
        function unicodeSize(string2) {
          var result2 = reUnicode.lastIndex = 0;
          while (reUnicode.test(string2)) {
            ++result2;
          }
          return result2;
        }
        function unicodeToArray(string2) {
          return string2.match(reUnicode) || [];
        }
        function unicodeWords(string2) {
          return string2.match(reUnicodeWord) || [];
        }
        var runInContext = function runInContext2(context) {
          context = context == null ? root : _3.defaults(root.Object(), context, _3.pick(root, contextProps));
          var Array2 = context.Array, Date2 = context.Date, Error2 = context.Error, Function2 = context.Function, Math2 = context.Math, Object2 = context.Object, RegExp2 = context.RegExp, String2 = context.String, TypeError2 = context.TypeError;
          var arrayProto = Array2.prototype, funcProto = Function2.prototype, objectProto = Object2.prototype;
          var coreJsData = context["__core-js_shared__"];
          var funcToString = funcProto.toString;
          var hasOwnProperty3 = objectProto.hasOwnProperty;
          var idCounter = 0;
          var maskSrcKey = (function() {
            var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || "");
            return uid ? "Symbol(src)_1." + uid : "";
          })();
          var nativeObjectToString = objectProto.toString;
          var objectCtorString = funcToString.call(Object2);
          var oldDash = root._;
          var reIsNative = RegExp2("^" + funcToString.call(hasOwnProperty3).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$");
          var Buffer4 = moduleExports ? context.Buffer : undefined$1, Symbol2 = context.Symbol, Uint8Array2 = context.Uint8Array, allocUnsafe = Buffer4 ? Buffer4.allocUnsafe : undefined$1, getPrototype = overArg(Object2.getPrototypeOf, Object2), objectCreate = Object2.create, propertyIsEnumerable = objectProto.propertyIsEnumerable, splice2 = arrayProto.splice, spreadableSymbol = Symbol2 ? Symbol2.isConcatSpreadable : undefined$1, symIterator = Symbol2 ? Symbol2.iterator : undefined$1, symToStringTag = Symbol2 ? Symbol2.toStringTag : undefined$1;
          var defineProperty = (function() {
            try {
              var func = getNative(Object2, "defineProperty");
              func({}, "", {});
              return func;
            } catch (e5) {
            }
          })();
          var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, ctxNow = Date2 && Date2.now !== root.Date.now && Date2.now, ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout;
          var nativeCeil = Math2.ceil, nativeFloor = Math2.floor, nativeGetSymbols = Object2.getOwnPropertySymbols, nativeIsBuffer = Buffer4 ? Buffer4.isBuffer : undefined$1, nativeIsFinite = context.isFinite, nativeJoin = arrayProto.join, nativeKeys = overArg(Object2.keys, Object2), nativeMax = Math2.max, nativeMin = Math2.min, nativeNow = Date2.now, nativeParseInt = context.parseInt, nativeRandom = Math2.random, nativeReverse = arrayProto.reverse;
          var DataView2 = getNative(context, "DataView"), Map2 = getNative(context, "Map"), Promise3 = getNative(context, "Promise"), Set2 = getNative(context, "Set"), WeakMap2 = getNative(context, "WeakMap"), nativeCreate = getNative(Object2, "create");
          var metaMap = WeakMap2 && new WeakMap2();
          var realNames = {};
          var dataViewCtorString = toSource(DataView2), mapCtorString = toSource(Map2), promiseCtorString = toSource(Promise3), setCtorString = toSource(Set2), weakMapCtorString = toSource(WeakMap2);
          var symbolProto = Symbol2 ? Symbol2.prototype : undefined$1, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined$1, symbolToString = symbolProto ? symbolProto.toString : undefined$1;
          function lodash2(value) {
            if (isObjectLike(value) && !isArray6(value) && !(value instanceof LazyWrapper)) {
              if (value instanceof LodashWrapper) {
                return value;
              }
              if (hasOwnProperty3.call(value, "__wrapped__")) {
                return wrapperClone(value);
              }
            }
            return new LodashWrapper(value);
          }
          var baseCreate = /* @__PURE__ */ (function() {
            function object() {
            }
            return function(proto2) {
              if (!isObject7(proto2)) {
                return {};
              }
              if (objectCreate) {
                return objectCreate(proto2);
              }
              object.prototype = proto2;
              var result22 = new object();
              object.prototype = undefined$1;
              return result22;
            };
          })();
          function baseLodash() {
          }
          function LodashWrapper(value, chainAll) {
            this.__wrapped__ = value;
            this.__actions__ = [];
            this.__chain__ = !!chainAll;
            this.__index__ = 0;
            this.__values__ = undefined$1;
          }
          lodash2.templateSettings = {
            escape: reEscape,
            evaluate: reEvaluate,
            interpolate: reInterpolate,
            variable: "",
            imports: {
              _: lodash2
            }
          };
          lodash2.prototype = baseLodash.prototype;
          lodash2.prototype.constructor = lodash2;
          LodashWrapper.prototype = baseCreate(baseLodash.prototype);
          LodashWrapper.prototype.constructor = LodashWrapper;
          function LazyWrapper(value) {
            this.__wrapped__ = value;
            this.__actions__ = [];
            this.__dir__ = 1;
            this.__filtered__ = false;
            this.__iteratees__ = [];
            this.__takeCount__ = MAX_ARRAY_LENGTH;
            this.__views__ = [];
          }
          function lazyClone() {
            var result22 = new LazyWrapper(this.__wrapped__);
            result22.__actions__ = copyArray(this.__actions__);
            result22.__dir__ = this.__dir__;
            result22.__filtered__ = this.__filtered__;
            result22.__iteratees__ = copyArray(this.__iteratees__);
            result22.__takeCount__ = this.__takeCount__;
            result22.__views__ = copyArray(this.__views__);
            return result22;
          }
          function lazyReverse() {
            if (this.__filtered__) {
              var result22 = new LazyWrapper(this);
              result22.__dir__ = -1;
              result22.__filtered__ = true;
            } else {
              result22 = this.clone();
              result22.__dir__ *= -1;
            }
            return result22;
          }
          function lazyValue() {
            var array = this.__wrapped__.value(), dir = this.__dir__, isArr = isArray6(array), isRight = dir < 0, arrLength = isArr ? array.length : 0, view = getView(0, arrLength, this.__views__), start = view.start, end = view.end, length = end - start, index2 = isRight ? end : start - 1, iteratees = this.__iteratees__, iterLength = iteratees.length, resIndex = 0, takeCount = nativeMin(length, this.__takeCount__);
            if (!isArr || !isRight && arrLength == length && takeCount == length) {
              return baseWrapperValue(array, this.__actions__);
            }
            var result22 = [];
            outer:
              while (length-- && resIndex < takeCount) {
                index2 += dir;
                var iterIndex = -1, value = array[index2];
                while (++iterIndex < iterLength) {
                  var data3 = iteratees[iterIndex], iteratee2 = data3.iteratee, type22 = data3.type, computed = iteratee2(value);
                  if (type22 == LAZY_MAP_FLAG) {
                    value = computed;
                  } else if (!computed) {
                    if (type22 == LAZY_FILTER_FLAG) {
                      continue outer;
                    } else {
                      break outer;
                    }
                  }
                }
                result22[resIndex++] = value;
              }
            return result22;
          }
          LazyWrapper.prototype = baseCreate(baseLodash.prototype);
          LazyWrapper.prototype.constructor = LazyWrapper;
          function Hash2(entries) {
            var index2 = -1, length = entries == null ? 0 : entries.length;
            this.clear();
            while (++index2 < length) {
              var entry = entries[index2];
              this.set(entry[0], entry[1]);
            }
          }
          function hashClear() {
            this.__data__ = nativeCreate ? nativeCreate(null) : {};
            this.size = 0;
          }
          function hashDelete(key) {
            var result22 = this.has(key) && delete this.__data__[key];
            this.size -= result22 ? 1 : 0;
            return result22;
          }
          function hashGet(key) {
            var data3 = this.__data__;
            if (nativeCreate) {
              var result22 = data3[key];
              return result22 === HASH_UNDEFINED ? undefined$1 : result22;
            }
            return hasOwnProperty3.call(data3, key) ? data3[key] : undefined$1;
          }
          function hashHas(key) {
            var data3 = this.__data__;
            return nativeCreate ? data3[key] !== undefined$1 : hasOwnProperty3.call(data3, key);
          }
          function hashSet(key, value) {
            var data3 = this.__data__;
            this.size += this.has(key) ? 0 : 1;
            data3[key] = nativeCreate && value === undefined$1 ? HASH_UNDEFINED : value;
            return this;
          }
          Hash2.prototype.clear = hashClear;
          Hash2.prototype["delete"] = hashDelete;
          Hash2.prototype.get = hashGet;
          Hash2.prototype.has = hashHas;
          Hash2.prototype.set = hashSet;
          function ListCache(entries) {
            var index2 = -1, length = entries == null ? 0 : entries.length;
            this.clear();
            while (++index2 < length) {
              var entry = entries[index2];
              this.set(entry[0], entry[1]);
            }
          }
          function listCacheClear() {
            this.__data__ = [];
            this.size = 0;
          }
          function listCacheDelete(key) {
            var data3 = this.__data__, index2 = assocIndexOf(data3, key);
            if (index2 < 0) {
              return false;
            }
            var lastIndex = data3.length - 1;
            if (index2 == lastIndex) {
              data3.pop();
            } else {
              splice2.call(data3, index2, 1);
            }
            --this.size;
            return true;
          }
          function listCacheGet(key) {
            var data3 = this.__data__, index2 = assocIndexOf(data3, key);
            return index2 < 0 ? undefined$1 : data3[index2][1];
          }
          function listCacheHas(key) {
            return assocIndexOf(this.__data__, key) > -1;
          }
          function listCacheSet(key, value) {
            var data3 = this.__data__, index2 = assocIndexOf(data3, key);
            if (index2 < 0) {
              ++this.size;
              data3.push([key, value]);
            } else {
              data3[index2][1] = value;
            }
            return this;
          }
          ListCache.prototype.clear = listCacheClear;
          ListCache.prototype["delete"] = listCacheDelete;
          ListCache.prototype.get = listCacheGet;
          ListCache.prototype.has = listCacheHas;
          ListCache.prototype.set = listCacheSet;
          function MapCache(entries) {
            var index2 = -1, length = entries == null ? 0 : entries.length;
            this.clear();
            while (++index2 < length) {
              var entry = entries[index2];
              this.set(entry[0], entry[1]);
            }
          }
          function mapCacheClear() {
            this.size = 0;
            this.__data__ = {
              hash: new Hash2(),
              map: new (Map2 || ListCache)(),
              string: new Hash2()
            };
          }
          function mapCacheDelete(key) {
            var result22 = getMapData(this, key)["delete"](key);
            this.size -= result22 ? 1 : 0;
            return result22;
          }
          function mapCacheGet(key) {
            return getMapData(this, key).get(key);
          }
          function mapCacheHas(key) {
            return getMapData(this, key).has(key);
          }
          function mapCacheSet(key, value) {
            var data3 = getMapData(this, key), size2 = data3.size;
            data3.set(key, value);
            this.size += data3.size == size2 ? 0 : 1;
            return this;
          }
          MapCache.prototype.clear = mapCacheClear;
          MapCache.prototype["delete"] = mapCacheDelete;
          MapCache.prototype.get = mapCacheGet;
          MapCache.prototype.has = mapCacheHas;
          MapCache.prototype.set = mapCacheSet;
          function SetCache(values2) {
            var index2 = -1, length = values2 == null ? 0 : values2.length;
            this.__data__ = new MapCache();
            while (++index2 < length) {
              this.add(values2[index2]);
            }
          }
          function setCacheAdd(value) {
            this.__data__.set(value, HASH_UNDEFINED);
            return this;
          }
          function setCacheHas(value) {
            return this.__data__.has(value);
          }
          SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
          SetCache.prototype.has = setCacheHas;
          function Stack(entries) {
            var data3 = this.__data__ = new ListCache(entries);
            this.size = data3.size;
          }
          function stackClear() {
            this.__data__ = new ListCache();
            this.size = 0;
          }
          function stackDelete(key) {
            var data3 = this.__data__, result22 = data3["delete"](key);
            this.size = data3.size;
            return result22;
          }
          function stackGet(key) {
            return this.__data__.get(key);
          }
          function stackHas(key) {
            return this.__data__.has(key);
          }
          function stackSet(key, value) {
            var data3 = this.__data__;
            if (data3 instanceof ListCache) {
              var pairs3 = data3.__data__;
              if (!Map2 || pairs3.length < LARGE_ARRAY_SIZE - 1) {
                pairs3.push([key, value]);
                this.size = ++data3.size;
                return this;
              }
              data3 = this.__data__ = new MapCache(pairs3);
            }
            data3.set(key, value);
            this.size = data3.size;
            return this;
          }
          Stack.prototype.clear = stackClear;
          Stack.prototype["delete"] = stackDelete;
          Stack.prototype.get = stackGet;
          Stack.prototype.has = stackHas;
          Stack.prototype.set = stackSet;
          function arrayLikeKeys(value, inherited) {
            var isArr = isArray6(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer3(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result22 = skipIndexes ? baseTimes(value.length, String2) : [], length = result22.length;
            for (var key in value) {
              if ((inherited || hasOwnProperty3.call(value, key)) && !(skipIndexes && (key == "length" || isBuff && (key == "offset" || key == "parent") || isType && (key == "buffer" || key == "byteLength" || key == "byteOffset") || isIndex(key, length)))) {
                result22.push(key);
              }
            }
            return result22;
          }
          function arraySample(array) {
            var length = array.length;
            return length ? array[baseRandom(0, length - 1)] : undefined$1;
          }
          function arraySampleSize(array, n5) {
            return shuffleSelf(copyArray(array), baseClamp(n5, 0, array.length));
          }
          function arrayShuffle(array) {
            return shuffleSelf(copyArray(array));
          }
          function assignMergeValue(object, key, value) {
            if (value !== undefined$1 && !eq2(object[key], value) || value === undefined$1 && !(key in object)) {
              baseAssignValue(object, key, value);
            }
          }
          function assignValue(object, key, value) {
            var objValue = object[key];
            if (!(hasOwnProperty3.call(object, key) && eq2(objValue, value)) || value === undefined$1 && !(key in object)) {
              baseAssignValue(object, key, value);
            }
          }
          function assocIndexOf(array, key) {
            var length = array.length;
            while (length--) {
              if (eq2(array[length][0], key)) {
                return length;
              }
            }
            return -1;
          }
          function baseAggregator(collection, setter, iteratee2, accumulator) {
            baseEach(collection, function(value, key, collection2) {
              setter(accumulator, value, iteratee2(value), collection2);
            });
            return accumulator;
          }
          function baseAssign(object, source2) {
            return object && copyObject(source2, keys(source2), object);
          }
          function baseAssignIn(object, source2) {
            return object && copyObject(source2, keysIn(source2), object);
          }
          function baseAssignValue(object, key, value) {
            if (key == "__proto__" && defineProperty) {
              defineProperty(object, key, {
                configurable: true,
                enumerable: true,
                value,
                writable: true
              });
            } else {
              object[key] = value;
            }
          }
          function baseAt(object, paths) {
            var index2 = -1, length = paths.length, result22 = Array2(length), skip = object == null;
            while (++index2 < length) {
              result22[index2] = skip ? undefined$1 : get2(object, paths[index2]);
            }
            return result22;
          }
          function baseClamp(number2, lower, upper) {
            if (number2 === number2) {
              if (upper !== undefined$1) {
                number2 = number2 <= upper ? number2 : upper;
              }
              if (lower !== undefined$1) {
                number2 = number2 >= lower ? number2 : lower;
              }
            }
            return number2;
          }
          function baseClone(value, bitmask, customizer, key, object, stack) {
            var result22, isDeep = bitmask & CLONE_DEEP_FLAG, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG;
            if (customizer) {
              result22 = object ? customizer(value, key, object, stack) : customizer(value);
            }
            if (result22 !== undefined$1) {
              return result22;
            }
            if (!isObject7(value)) {
              return value;
            }
            var isArr = isArray6(value);
            if (isArr) {
              result22 = initCloneArray(value);
              if (!isDeep) {
                return copyArray(value, result22);
              }
            } else {
              var tag = getTag(value), isFunc = tag == funcTag || tag == genTag;
              if (isBuffer3(value)) {
                return cloneBuffer(value, isDeep);
              }
              if (tag == objectTag || tag == argsTag || isFunc && !object) {
                result22 = isFlat || isFunc ? {} : initCloneObject(value);
                if (!isDeep) {
                  return isFlat ? copySymbolsIn(value, baseAssignIn(result22, value)) : copySymbols(value, baseAssign(result22, value));
                }
              } else {
                if (!cloneableTags[tag]) {
                  return object ? value : {};
                }
                result22 = initCloneByTag(value, tag, isDeep);
              }
            }
            stack || (stack = new Stack());
            var stacked = stack.get(value);
            if (stacked) {
              return stacked;
            }
            stack.set(value, result22);
            if (isSet(value)) {
              value.forEach(function(subValue) {
                result22.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));
              });
            } else if (isMap(value)) {
              value.forEach(function(subValue, key2) {
                result22.set(key2, baseClone(subValue, bitmask, customizer, key2, value, stack));
              });
            }
            var keysFunc = isFull ? isFlat ? getAllKeysIn : getAllKeys : isFlat ? keysIn : keys;
            var props = isArr ? undefined$1 : keysFunc(value);
            arrayEach(props || value, function(subValue, key2) {
              if (props) {
                key2 = subValue;
                subValue = value[key2];
              }
              assignValue(result22, key2, baseClone(subValue, bitmask, customizer, key2, value, stack));
            });
            return result22;
          }
          function baseConforms(source2) {
            var props = keys(source2);
            return function(object) {
              return baseConformsTo(object, source2, props);
            };
          }
          function baseConformsTo(object, source2, props) {
            var length = props.length;
            if (object == null) {
              return !length;
            }
            object = Object2(object);
            while (length--) {
              var key = props[length], predicate = source2[key], value = object[key];
              if (value === undefined$1 && !(key in object) || !predicate(value)) {
                return false;
              }
            }
            return true;
          }
          function baseDelay(func, wait, args) {
            if (typeof func != "function") {
              throw new TypeError2(FUNC_ERROR_TEXT);
            }
            return setTimeout2(function() {
              func.apply(undefined$1, args);
            }, wait);
          }
          function baseDifference(array, values2, iteratee2, comparator) {
            var index2 = -1, includes2 = arrayIncludes, isCommon = true, length = array.length, result22 = [], valuesLength = values2.length;
            if (!length) {
              return result22;
            }
            if (iteratee2) {
              values2 = arrayMap(values2, baseUnary(iteratee2));
            }
            if (comparator) {
              includes2 = arrayIncludesWith;
              isCommon = false;
            } else if (values2.length >= LARGE_ARRAY_SIZE) {
              includes2 = cacheHas;
              isCommon = false;
              values2 = new SetCache(values2);
            }
            outer:
              while (++index2 < length) {
                var value = array[index2], computed = iteratee2 == null ? value : iteratee2(value);
                value = comparator || value !== 0 ? value : 0;
                if (isCommon && computed === computed) {
                  var valuesIndex = valuesLength;
                  while (valuesIndex--) {
                    if (values2[valuesIndex] === computed) {
                      continue outer;
                    }
                  }
                  result22.push(value);
                } else if (!includes2(values2, computed, comparator)) {
                  result22.push(value);
                }
              }
            return result22;
          }
          var baseEach = createBaseEach(baseForOwn);
          var baseEachRight = createBaseEach(baseForOwnRight, true);
          function baseEvery(collection, predicate) {
            var result22 = true;
            baseEach(collection, function(value, index2, collection2) {
              result22 = !!predicate(value, index2, collection2);
              return result22;
            });
            return result22;
          }
          function baseExtremum(array, iteratee2, comparator) {
            var index2 = -1, length = array.length;
            while (++index2 < length) {
              var value = array[index2], current3 = iteratee2(value);
              if (current3 != null && (computed === undefined$1 ? current3 === current3 && !isSymbol3(current3) : comparator(current3, computed))) {
                var computed = current3, result22 = value;
              }
            }
            return result22;
          }
          function baseFill(array, value, start, end) {
            var length = array.length;
            start = toInteger(start);
            if (start < 0) {
              start = -start > length ? 0 : length + start;
            }
            end = end === undefined$1 || end > length ? length : toInteger(end);
            if (end < 0) {
              end += length;
            }
            end = start > end ? 0 : toLength(end);
            while (start < end) {
              array[start++] = value;
            }
            return array;
          }
          function baseFilter(collection, predicate) {
            var result22 = [];
            baseEach(collection, function(value, index2, collection2) {
              if (predicate(value, index2, collection2)) {
                result22.push(value);
              }
            });
            return result22;
          }
          function baseFlatten(array, depth, predicate, isStrict, result22) {
            var index2 = -1, length = array.length;
            predicate || (predicate = isFlattenable);
            result22 || (result22 = []);
            while (++index2 < length) {
              var value = array[index2];
              if (depth > 0 && predicate(value)) {
                if (depth > 1) {
                  baseFlatten(value, depth - 1, predicate, isStrict, result22);
                } else {
                  arrayPush(result22, value);
                }
              } else if (!isStrict) {
                result22[result22.length] = value;
              }
            }
            return result22;
          }
          var baseFor = createBaseFor();
          var baseForRight = createBaseFor(true);
          function baseForOwn(object, iteratee2) {
            return object && baseFor(object, iteratee2, keys);
          }
          function baseForOwnRight(object, iteratee2) {
            return object && baseForRight(object, iteratee2, keys);
          }
          function baseFunctions(object, props) {
            return arrayFilter(props, function(key) {
              return isFunction3(object[key]);
            });
          }
          function baseGet(object, path3) {
            path3 = castPath(path3, object);
            var index2 = 0, length = path3.length;
            while (object != null && index2 < length) {
              object = object[toKey(path3[index2++])];
            }
            return index2 && index2 == length ? object : undefined$1;
          }
          function baseGetAllKeys(object, keysFunc, symbolsFunc) {
            var result22 = keysFunc(object);
            return isArray6(object) ? result22 : arrayPush(result22, symbolsFunc(object));
          }
          function baseGetTag(value) {
            if (value == null) {
              return value === undefined$1 ? undefinedTag : nullTag;
            }
            return symToStringTag && symToStringTag in Object2(value) ? getRawTag(value) : objectToString(value);
          }
          function baseGt(value, other) {
            return value > other;
          }
          function baseHas(object, key) {
            return object != null && hasOwnProperty3.call(object, key);
          }
          function baseHasIn(object, key) {
            return object != null && key in Object2(object);
          }
          function baseInRange(number2, start, end) {
            return number2 >= nativeMin(start, end) && number2 < nativeMax(start, end);
          }
          function baseIntersection(arrays, iteratee2, comparator) {
            var includes2 = comparator ? arrayIncludesWith : arrayIncludes, length = arrays[0].length, othLength = arrays.length, othIndex = othLength, caches = Array2(othLength), maxLength = Infinity, result22 = [];
            while (othIndex--) {
              var array = arrays[othIndex];
              if (othIndex && iteratee2) {
                array = arrayMap(array, baseUnary(iteratee2));
              }
              maxLength = nativeMin(array.length, maxLength);
              caches[othIndex] = !comparator && (iteratee2 || length >= 120 && array.length >= 120) ? new SetCache(othIndex && array) : undefined$1;
            }
            array = arrays[0];
            var index2 = -1, seen = caches[0];
            outer:
              while (++index2 < length && result22.length < maxLength) {
                var value = array[index2], computed = iteratee2 ? iteratee2(value) : value;
                value = comparator || value !== 0 ? value : 0;
                if (!(seen ? cacheHas(seen, computed) : includes2(result22, computed, comparator))) {
                  othIndex = othLength;
                  while (--othIndex) {
                    var cache3 = caches[othIndex];
                    if (!(cache3 ? cacheHas(cache3, computed) : includes2(arrays[othIndex], computed, comparator))) {
                      continue outer;
                    }
                  }
                  if (seen) {
                    seen.push(computed);
                  }
                  result22.push(value);
                }
              }
            return result22;
          }
          function baseInverter(object, setter, iteratee2, accumulator) {
            baseForOwn(object, function(value, key, object2) {
              setter(accumulator, iteratee2(value), key, object2);
            });
            return accumulator;
          }
          function baseInvoke(object, path3, args) {
            path3 = castPath(path3, object);
            object = parent(object, path3);
            var func = object == null ? object : object[toKey(last(path3))];
            return func == null ? undefined$1 : apply(func, object, args);
          }
          function baseIsArguments(value) {
            return isObjectLike(value) && baseGetTag(value) == argsTag;
          }
          function baseIsArrayBuffer(value) {
            return isObjectLike(value) && baseGetTag(value) == arrayBufferTag;
          }
          function baseIsDate(value) {
            return isObjectLike(value) && baseGetTag(value) == dateTag;
          }
          function baseIsEqual(value, other, bitmask, customizer, stack) {
            if (value === other) {
              return true;
            }
            if (value == null || other == null || !isObjectLike(value) && !isObjectLike(other)) {
              return value !== value && other !== other;
            }
            return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
          }
          function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
            var objIsArr = isArray6(object), othIsArr = isArray6(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other);
            objTag = objTag == argsTag ? objectTag : objTag;
            othTag = othTag == argsTag ? objectTag : othTag;
            var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag;
            if (isSameTag && isBuffer3(object)) {
              if (!isBuffer3(other)) {
                return false;
              }
              objIsArr = true;
              objIsObj = false;
            }
            if (isSameTag && !objIsObj) {
              stack || (stack = new Stack());
              return objIsArr || isTypedArray(object) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
            }
            if (!(bitmask & COMPARE_PARTIAL_FLAG)) {
              var objIsWrapped = objIsObj && hasOwnProperty3.call(object, "__wrapped__"), othIsWrapped = othIsObj && hasOwnProperty3.call(other, "__wrapped__");
              if (objIsWrapped || othIsWrapped) {
                var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other;
                stack || (stack = new Stack());
                return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
              }
            }
            if (!isSameTag) {
              return false;
            }
            stack || (stack = new Stack());
            return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
          }
          function baseIsMap(value) {
            return isObjectLike(value) && getTag(value) == mapTag;
          }
          function baseIsMatch(object, source2, matchData, customizer) {
            var index2 = matchData.length, length = index2, noCustomizer = !customizer;
            if (object == null) {
              return !length;
            }
            object = Object2(object);
            while (index2--) {
              var data3 = matchData[index2];
              if (noCustomizer && data3[2] ? data3[1] !== object[data3[0]] : !(data3[0] in object)) {
                return false;
              }
            }
            while (++index2 < length) {
              data3 = matchData[index2];
              var key = data3[0], objValue = object[key], srcValue = data3[1];
              if (noCustomizer && data3[2]) {
                if (objValue === undefined$1 && !(key in object)) {
                  return false;
                }
              } else {
                var stack = new Stack();
                if (customizer) {
                  var result22 = customizer(objValue, srcValue, key, object, source2, stack);
                }
                if (!(result22 === undefined$1 ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) : result22)) {
                  return false;
                }
              }
            }
            return true;
          }
          function baseIsNative(value) {
            if (!isObject7(value) || isMasked(value)) {
              return false;
            }
            var pattern = isFunction3(value) ? reIsNative : reIsHostCtor;
            return pattern.test(toSource(value));
          }
          function baseIsRegExp(value) {
            return isObjectLike(value) && baseGetTag(value) == regexpTag;
          }
          function baseIsSet(value) {
            return isObjectLike(value) && getTag(value) == setTag;
          }
          function baseIsTypedArray(value) {
            return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
          }
          function baseIteratee(value) {
            if (typeof value == "function") {
              return value;
            }
            if (value == null) {
              return identity;
            }
            if (typeof value == "object") {
              return isArray6(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value);
            }
            return property(value);
          }
          function baseKeys(object) {
            if (!isPrototype(object)) {
              return nativeKeys(object);
            }
            var result22 = [];
            for (var key in Object2(object)) {
              if (hasOwnProperty3.call(object, key) && key != "constructor") {
                result22.push(key);
              }
            }
            return result22;
          }
          function baseKeysIn(object) {
            if (!isObject7(object)) {
              return nativeKeysIn(object);
            }
            var isProto = isPrototype(object), result22 = [];
            for (var key in object) {
              if (!(key == "constructor" && (isProto || !hasOwnProperty3.call(object, key)))) {
                result22.push(key);
              }
            }
            return result22;
          }
          function baseLt(value, other) {
            return value < other;
          }
          function baseMap(collection, iteratee2) {
            var index2 = -1, result22 = isArrayLike(collection) ? Array2(collection.length) : [];
            baseEach(collection, function(value, key, collection2) {
              result22[++index2] = iteratee2(value, key, collection2);
            });
            return result22;
          }
          function baseMatches(source2) {
            var matchData = getMatchData(source2);
            if (matchData.length == 1 && matchData[0][2]) {
              return matchesStrictComparable(matchData[0][0], matchData[0][1]);
            }
            return function(object) {
              return object === source2 || baseIsMatch(object, source2, matchData);
            };
          }
          function baseMatchesProperty(path3, srcValue) {
            if (isKey(path3) && isStrictComparable(srcValue)) {
              return matchesStrictComparable(toKey(path3), srcValue);
            }
            return function(object) {
              var objValue = get2(object, path3);
              return objValue === undefined$1 && objValue === srcValue ? hasIn(object, path3) : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);
            };
          }
          function baseMerge(object, source2, srcIndex, customizer, stack) {
            if (object === source2) {
              return;
            }
            baseFor(source2, function(srcValue, key) {
              stack || (stack = new Stack());
              if (isObject7(srcValue)) {
                baseMergeDeep(object, source2, key, srcIndex, baseMerge, customizer, stack);
              } else {
                var newValue = customizer ? customizer(safeGet(object, key), srcValue, key + "", object, source2, stack) : undefined$1;
                if (newValue === undefined$1) {
                  newValue = srcValue;
                }
                assignMergeValue(object, key, newValue);
              }
            }, keysIn);
          }
          function baseMergeDeep(object, source2, key, srcIndex, mergeFunc, customizer, stack) {
            var objValue = safeGet(object, key), srcValue = safeGet(source2, key), stacked = stack.get(srcValue);
            if (stacked) {
              assignMergeValue(object, key, stacked);
              return;
            }
            var newValue = customizer ? customizer(objValue, srcValue, key + "", object, source2, stack) : undefined$1;
            var isCommon = newValue === undefined$1;
            if (isCommon) {
              var isArr = isArray6(srcValue), isBuff = !isArr && isBuffer3(srcValue), isTyped = !isArr && !isBuff && isTypedArray(srcValue);
              newValue = srcValue;
              if (isArr || isBuff || isTyped) {
                if (isArray6(objValue)) {
                  newValue = objValue;
                } else if (isArrayLikeObject(objValue)) {
                  newValue = copyArray(objValue);
                } else if (isBuff) {
                  isCommon = false;
                  newValue = cloneBuffer(srcValue, true);
                } else if (isTyped) {
                  isCommon = false;
                  newValue = cloneTypedArray(srcValue, true);
                } else {
                  newValue = [];
                }
              } else if (isPlainObject(srcValue) || isArguments(srcValue)) {
                newValue = objValue;
                if (isArguments(objValue)) {
                  newValue = toPlainObject(objValue);
                } else if (!isObject7(objValue) || isFunction3(objValue)) {
                  newValue = initCloneObject(srcValue);
                }
              } else {
                isCommon = false;
              }
            }
            if (isCommon) {
              stack.set(srcValue, newValue);
              mergeFunc(newValue, srcValue, srcIndex, customizer, stack);
              stack["delete"](srcValue);
            }
            assignMergeValue(object, key, newValue);
          }
          function baseNth(array, n5) {
            var length = array.length;
            if (!length) {
              return;
            }
            n5 += n5 < 0 ? length : 0;
            return isIndex(n5, length) ? array[n5] : undefined$1;
          }
          function baseOrderBy(collection, iteratees, orders) {
            if (iteratees.length) {
              iteratees = arrayMap(iteratees, function(iteratee2) {
                if (isArray6(iteratee2)) {
                  return function(value) {
                    return baseGet(value, iteratee2.length === 1 ? iteratee2[0] : iteratee2);
                  };
                }
                return iteratee2;
              });
            } else {
              iteratees = [identity];
            }
            var index2 = -1;
            iteratees = arrayMap(iteratees, baseUnary(getIteratee()));
            var result22 = baseMap(collection, function(value, key, collection2) {
              var criteria = arrayMap(iteratees, function(iteratee2) {
                return iteratee2(value);
              });
              return { criteria, index: ++index2, value };
            });
            return baseSortBy(result22, function(object, other) {
              return compareMultiple(object, other, orders);
            });
          }
          function basePick(object, paths) {
            return basePickBy(object, paths, function(value, path3) {
              return hasIn(object, path3);
            });
          }
          function basePickBy(object, paths, predicate) {
            var index2 = -1, length = paths.length, result22 = {};
            while (++index2 < length) {
              var path3 = paths[index2], value = baseGet(object, path3);
              if (predicate(value, path3)) {
                baseSet(result22, castPath(path3, object), value);
              }
            }
            return result22;
          }
          function basePropertyDeep(path3) {
            return function(object) {
              return baseGet(object, path3);
            };
          }
          function basePullAll(array, values2, iteratee2, comparator) {
            var indexOf22 = comparator ? baseIndexOfWith : baseIndexOf, index2 = -1, length = values2.length, seen = array;
            if (array === values2) {
              values2 = copyArray(values2);
            }
            if (iteratee2) {
              seen = arrayMap(array, baseUnary(iteratee2));
            }
            while (++index2 < length) {
              var fromIndex = 0, value = values2[index2], computed = iteratee2 ? iteratee2(value) : value;
              while ((fromIndex = indexOf22(seen, computed, fromIndex, comparator)) > -1) {
                if (seen !== array) {
                  splice2.call(seen, fromIndex, 1);
                }
                splice2.call(array, fromIndex, 1);
              }
            }
            return array;
          }
          function basePullAt(array, indexes) {
            var length = array ? indexes.length : 0, lastIndex = length - 1;
            while (length--) {
              var index2 = indexes[length];
              if (length == lastIndex || index2 !== previous) {
                var previous = index2;
                if (isIndex(index2)) {
                  splice2.call(array, index2, 1);
                } else {
                  baseUnset(array, index2);
                }
              }
            }
            return array;
          }
          function baseRandom(lower, upper) {
            return lower + nativeFloor(nativeRandom() * (upper - lower + 1));
          }
          function baseRange(start, end, step, fromRight) {
            var index2 = -1, length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), result22 = Array2(length);
            while (length--) {
              result22[fromRight ? length : ++index2] = start;
              start += step;
            }
            return result22;
          }
          function baseRepeat(string2, n5) {
            var result22 = "";
            if (!string2 || n5 < 1 || n5 > MAX_SAFE_INTEGER2) {
              return result22;
            }
            do {
              if (n5 % 2) {
                result22 += string2;
              }
              n5 = nativeFloor(n5 / 2);
              if (n5) {
                string2 += string2;
              }
            } while (n5);
            return result22;
          }
          function baseRest(func, start) {
            return setToString(overRest(func, start, identity), func + "");
          }
          function baseSample(collection) {
            return arraySample(values(collection));
          }
          function baseSampleSize(collection, n5) {
            var array = values(collection);
            return shuffleSelf(array, baseClamp(n5, 0, array.length));
          }
          function baseSet(object, path3, value, customizer) {
            if (!isObject7(object)) {
              return object;
            }
            path3 = castPath(path3, object);
            var index2 = -1, length = path3.length, lastIndex = length - 1, nested = object;
            while (nested != null && ++index2 < length) {
              var key = toKey(path3[index2]), newValue = value;
              if (key === "__proto__" || key === "constructor" || key === "prototype") {
                return object;
              }
              if (index2 != lastIndex) {
                var objValue = nested[key];
                newValue = customizer ? customizer(objValue, key, nested) : undefined$1;
                if (newValue === undefined$1) {
                  newValue = isObject7(objValue) ? objValue : isIndex(path3[index2 + 1]) ? [] : {};
                }
              }
              assignValue(nested, key, newValue);
              nested = nested[key];
            }
            return object;
          }
          var baseSetData = !metaMap ? identity : function(func, data3) {
            metaMap.set(func, data3);
            return func;
          };
          var baseSetToString = !defineProperty ? identity : function(func, string2) {
            return defineProperty(func, "toString", {
              configurable: true,
              enumerable: false,
              value: constant(string2),
              writable: true
            });
          };
          function baseShuffle(collection) {
            return shuffleSelf(values(collection));
          }
          function baseSlice(array, start, end) {
            var index2 = -1, length = array.length;
            if (start < 0) {
              start = -start > length ? 0 : length + start;
            }
            end = end > length ? length : end;
            if (end < 0) {
              end += length;
            }
            length = start > end ? 0 : end - start >>> 0;
            start >>>= 0;
            var result22 = Array2(length);
            while (++index2 < length) {
              result22[index2] = array[index2 + start];
            }
            return result22;
          }
          function baseSome(collection, predicate) {
            var result22;
            baseEach(collection, function(value, index2, collection2) {
              result22 = predicate(value, index2, collection2);
              return !result22;
            });
            return !!result22;
          }
          function baseSortedIndex(array, value, retHighest) {
            var low = 0, high = array == null ? low : array.length;
            if (typeof value == "number" && value === value && high <= HALF_MAX_ARRAY_LENGTH) {
              while (low < high) {
                var mid = low + high >>> 1, computed = array[mid];
                if (computed !== null && !isSymbol3(computed) && (retHighest ? computed <= value : computed < value)) {
                  low = mid + 1;
                } else {
                  high = mid;
                }
              }
              return high;
            }
            return baseSortedIndexBy(array, value, identity, retHighest);
          }
          function baseSortedIndexBy(array, value, iteratee2, retHighest) {
            var low = 0, high = array == null ? 0 : array.length;
            if (high === 0) {
              return 0;
            }
            value = iteratee2(value);
            var valIsNaN = value !== value, valIsNull = value === null, valIsSymbol = isSymbol3(value), valIsUndefined = value === undefined$1;
            while (low < high) {
              var mid = nativeFloor((low + high) / 2), computed = iteratee2(array[mid]), othIsDefined = computed !== undefined$1, othIsNull = computed === null, othIsReflexive = computed === computed, othIsSymbol = isSymbol3(computed);
              if (valIsNaN) {
                var setLow = retHighest || othIsReflexive;
              } else if (valIsUndefined) {
                setLow = othIsReflexive && (retHighest || othIsDefined);
              } else if (valIsNull) {
                setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull);
              } else if (valIsSymbol) {
                setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol);
              } else if (othIsNull || othIsSymbol) {
                setLow = false;
              } else {
                setLow = retHighest ? computed <= value : computed < value;
              }
              if (setLow) {
                low = mid + 1;
              } else {
                high = mid;
              }
            }
            return nativeMin(high, MAX_ARRAY_INDEX);
          }
          function baseSortedUniq(array, iteratee2) {
            var index2 = -1, length = array.length, resIndex = 0, result22 = [];
            while (++index2 < length) {
              var value = array[index2], computed = iteratee2 ? iteratee2(value) : value;
              if (!index2 || !eq2(computed, seen)) {
                var seen = computed;
                result22[resIndex++] = value === 0 ? 0 : value;
              }
            }
            return result22;
          }
          function baseToNumber(value) {
            if (typeof value == "number") {
              return value;
            }
            if (isSymbol3(value)) {
              return NAN;
            }
            return +value;
          }
          function baseToString(value) {
            if (typeof value == "string") {
              return value;
            }
            if (isArray6(value)) {
              return arrayMap(value, baseToString) + "";
            }
            if (isSymbol3(value)) {
              return symbolToString ? symbolToString.call(value) : "";
            }
            var result22 = value + "";
            return result22 == "0" && 1 / value == -INFINITY ? "-0" : result22;
          }
          function baseUniq(array, iteratee2, comparator) {
            var index2 = -1, includes2 = arrayIncludes, length = array.length, isCommon = true, result22 = [], seen = result22;
            if (comparator) {
              isCommon = false;
              includes2 = arrayIncludesWith;
            } else if (length >= LARGE_ARRAY_SIZE) {
              var set22 = iteratee2 ? null : createSet(array);
              if (set22) {
                return setToArray(set22);
              }
              isCommon = false;
              includes2 = cacheHas;
              seen = new SetCache();
            } else {
              seen = iteratee2 ? [] : result22;
            }
            outer:
              while (++index2 < length) {
                var value = array[index2], computed = iteratee2 ? iteratee2(value) : value;
                value = comparator || value !== 0 ? value : 0;
                if (isCommon && computed === computed) {
                  var seenIndex = seen.length;
                  while (seenIndex--) {
                    if (seen[seenIndex] === computed) {
                      continue outer;
                    }
                  }
                  if (iteratee2) {
                    seen.push(computed);
                  }
                  result22.push(value);
                } else if (!includes2(seen, computed, comparator)) {
                  if (seen !== result22) {
                    seen.push(computed);
                  }
                  result22.push(value);
                }
              }
            return result22;
          }
          function baseUnset(object, path3) {
            path3 = castPath(path3, object);
            object = parent(object, path3);
            return object == null || delete object[toKey(last(path3))];
          }
          function baseUpdate(object, path3, updater, customizer) {
            return baseSet(object, path3, updater(baseGet(object, path3)), customizer);
          }
          function baseWhile(array, predicate, isDrop, fromRight) {
            var length = array.length, index2 = fromRight ? length : -1;
            while ((fromRight ? index2-- : ++index2 < length) && predicate(array[index2], index2, array)) {
            }
            return isDrop ? baseSlice(array, fromRight ? 0 : index2, fromRight ? index2 + 1 : length) : baseSlice(array, fromRight ? index2 + 1 : 0, fromRight ? length : index2);
          }
          function baseWrapperValue(value, actions) {
            var result22 = value;
            if (result22 instanceof LazyWrapper) {
              result22 = result22.value();
            }
            return arrayReduce(actions, function(result3, action) {
              return action.func.apply(action.thisArg, arrayPush([result3], action.args));
            }, result22);
          }
          function baseXor(arrays, iteratee2, comparator) {
            var length = arrays.length;
            if (length < 2) {
              return length ? baseUniq(arrays[0]) : [];
            }
            var index2 = -1, result22 = Array2(length);
            while (++index2 < length) {
              var array = arrays[index2], othIndex = -1;
              while (++othIndex < length) {
                if (othIndex != index2) {
                  result22[index2] = baseDifference(result22[index2] || array, arrays[othIndex], iteratee2, comparator);
                }
              }
            }
            return baseUniq(baseFlatten(result22, 1), iteratee2, comparator);
          }
          function baseZipObject(props, values2, assignFunc) {
            var index2 = -1, length = props.length, valsLength = values2.length, result22 = {};
            while (++index2 < length) {
              var value = index2 < valsLength ? values2[index2] : undefined$1;
              assignFunc(result22, props[index2], value);
            }
            return result22;
          }
          function castArrayLikeObject(value) {
            return isArrayLikeObject(value) ? value : [];
          }
          function castFunction(value) {
            return typeof value == "function" ? value : identity;
          }
          function castPath(value, object) {
            if (isArray6(value)) {
              return value;
            }
            return isKey(value, object) ? [value] : stringToPath(toString8(value));
          }
          var castRest = baseRest;
          function castSlice(array, start, end) {
            var length = array.length;
            end = end === undefined$1 ? length : end;
            return !start && end >= length ? array : baseSlice(array, start, end);
          }
          var clearTimeout2 = ctxClearTimeout || function(id) {
            return root.clearTimeout(id);
          };
          function cloneBuffer(buffer2, isDeep) {
            if (isDeep) {
              return buffer2.slice();
            }
            var length = buffer2.length, result22 = allocUnsafe ? allocUnsafe(length) : new buffer2.constructor(length);
            buffer2.copy(result22);
            return result22;
          }
          function cloneArrayBuffer(arrayBuffer) {
            var result22 = new arrayBuffer.constructor(arrayBuffer.byteLength);
            new Uint8Array2(result22).set(new Uint8Array2(arrayBuffer));
            return result22;
          }
          function cloneDataView(dataView, isDeep) {
            var buffer2 = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;
            return new dataView.constructor(buffer2, dataView.byteOffset, dataView.byteLength);
          }
          function cloneRegExp(regexp) {
            var result22 = new regexp.constructor(regexp.source, reFlags.exec(regexp));
            result22.lastIndex = regexp.lastIndex;
            return result22;
          }
          function cloneSymbol(symbol) {
            return symbolValueOf ? Object2(symbolValueOf.call(symbol)) : {};
          }
          function cloneTypedArray(typedArray, isDeep) {
            var buffer2 = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
            return new typedArray.constructor(buffer2, typedArray.byteOffset, typedArray.length);
          }
          function compareAscending(value, other) {
            if (value !== other) {
              var valIsDefined = value !== undefined$1, valIsNull = value === null, valIsReflexive = value === value, valIsSymbol = isSymbol3(value);
              var othIsDefined = other !== undefined$1, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = isSymbol3(other);
              if (!othIsNull && !othIsSymbol && !valIsSymbol && value > other || valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol || valIsNull && othIsDefined && othIsReflexive || !valIsDefined && othIsReflexive || !valIsReflexive) {
                return 1;
              }
              if (!valIsNull && !valIsSymbol && !othIsSymbol && value < other || othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol || othIsNull && valIsDefined && valIsReflexive || !othIsDefined && valIsReflexive || !othIsReflexive) {
                return -1;
              }
            }
            return 0;
          }
          function compareMultiple(object, other, orders) {
            var index2 = -1, objCriteria = object.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length;
            while (++index2 < length) {
              var result22 = compareAscending(objCriteria[index2], othCriteria[index2]);
              if (result22) {
                if (index2 >= ordersLength) {
                  return result22;
                }
                var order = orders[index2];
                return result22 * (order == "desc" ? -1 : 1);
              }
            }
            return object.index - other.index;
          }
          function composeArgs(args, partials, holders, isCurried) {
            var argsIndex = -1, argsLength = args.length, holdersLength = holders.length, leftIndex = -1, leftLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result22 = Array2(leftLength + rangeLength), isUncurried = !isCurried;
            while (++leftIndex < leftLength) {
              result22[leftIndex] = partials[leftIndex];
            }
            while (++argsIndex < holdersLength) {
              if (isUncurried || argsIndex < argsLength) {
                result22[holders[argsIndex]] = args[argsIndex];
              }
            }
            while (rangeLength--) {
              result22[leftIndex++] = args[argsIndex++];
            }
            return result22;
          }
          function composeArgsRight(args, partials, holders, isCurried) {
            var argsIndex = -1, argsLength = args.length, holdersIndex = -1, holdersLength = holders.length, rightIndex = -1, rightLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result22 = Array2(rangeLength + rightLength), isUncurried = !isCurried;
            while (++argsIndex < rangeLength) {
              result22[argsIndex] = args[argsIndex];
            }
            var offset3 = argsIndex;
            while (++rightIndex < rightLength) {
              result22[offset3 + rightIndex] = partials[rightIndex];
            }
            while (++holdersIndex < holdersLength) {
              if (isUncurried || argsIndex < argsLength) {
                result22[offset3 + holders[holdersIndex]] = args[argsIndex++];
              }
            }
            return result22;
          }
          function copyArray(source2, array) {
            var index2 = -1, length = source2.length;
            array || (array = Array2(length));
            while (++index2 < length) {
              array[index2] = source2[index2];
            }
            return array;
          }
          function copyObject(source2, props, object, customizer) {
            var isNew = !object;
            object || (object = {});
            var index2 = -1, length = props.length;
            while (++index2 < length) {
              var key = props[index2];
              var newValue = customizer ? customizer(object[key], source2[key], key, object, source2) : undefined$1;
              if (newValue === undefined$1) {
                newValue = source2[key];
              }
              if (isNew) {
                baseAssignValue(object, key, newValue);
              } else {
                assignValue(object, key, newValue);
              }
            }
            return object;
          }
          function copySymbols(source2, object) {
            return copyObject(source2, getSymbols(source2), object);
          }
          function copySymbolsIn(source2, object) {
            return copyObject(source2, getSymbolsIn(source2), object);
          }
          function createAggregator(setter, initializer2) {
            return function(collection, iteratee2) {
              var func = isArray6(collection) ? arrayAggregator : baseAggregator, accumulator = initializer2 ? initializer2() : {};
              return func(collection, setter, getIteratee(iteratee2, 2), accumulator);
            };
          }
          function createAssigner(assigner) {
            return baseRest(function(object, sources) {
              var index2 = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined$1, guard = length > 2 ? sources[2] : undefined$1;
              customizer = assigner.length > 3 && typeof customizer == "function" ? (length--, customizer) : undefined$1;
              if (guard && isIterateeCall(sources[0], sources[1], guard)) {
                customizer = length < 3 ? undefined$1 : customizer;
                length = 1;
              }
              object = Object2(object);
              while (++index2 < length) {
                var source2 = sources[index2];
                if (source2) {
                  assigner(object, source2, index2, customizer);
                }
              }
              return object;
            });
          }
          function createBaseEach(eachFunc, fromRight) {
            return function(collection, iteratee2) {
              if (collection == null) {
                return collection;
              }
              if (!isArrayLike(collection)) {
                return eachFunc(collection, iteratee2);
              }
              var length = collection.length, index2 = fromRight ? length : -1, iterable = Object2(collection);
              while (fromRight ? index2-- : ++index2 < length) {
                if (iteratee2(iterable[index2], index2, iterable) === false) {
                  break;
                }
              }
              return collection;
            };
          }
          function createBaseFor(fromRight) {
            return function(object, iteratee2, keysFunc) {
              var index2 = -1, iterable = Object2(object), props = keysFunc(object), length = props.length;
              while (length--) {
                var key = props[fromRight ? length : ++index2];
                if (iteratee2(iterable[key], key, iterable) === false) {
                  break;
                }
              }
              return object;
            };
          }
          function createBind(func, bitmask, thisArg) {
            var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func);
            function wrapper() {
              var fn = this && this !== root && this instanceof wrapper ? Ctor : func;
              return fn.apply(isBind ? thisArg : this, arguments);
            }
            return wrapper;
          }
          function createCaseFirst(methodName) {
            return function(string2) {
              string2 = toString8(string2);
              var strSymbols = hasUnicode(string2) ? stringToArray(string2) : undefined$1;
              var chr = strSymbols ? strSymbols[0] : string2.charAt(0);
              var trailing = strSymbols ? castSlice(strSymbols, 1).join("") : string2.slice(1);
              return chr[methodName]() + trailing;
            };
          }
          function createCompounder(callback) {
            return function(string2) {
              return arrayReduce(words(deburr(string2).replace(reApos, "")), callback, "");
            };
          }
          function createCtor(Ctor) {
            return function() {
              var args = arguments;
              switch (args.length) {
                case 0:
                  return new Ctor();
                case 1:
                  return new Ctor(args[0]);
                case 2:
                  return new Ctor(args[0], args[1]);
                case 3:
                  return new Ctor(args[0], args[1], args[2]);
                case 4:
                  return new Ctor(args[0], args[1], args[2], args[3]);
                case 5:
                  return new Ctor(args[0], args[1], args[2], args[3], args[4]);
                case 6:
                  return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);
                case 7:
                  return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
              }
              var thisBinding = baseCreate(Ctor.prototype), result22 = Ctor.apply(thisBinding, args);
              return isObject7(result22) ? result22 : thisBinding;
            };
          }
          function createCurry(func, bitmask, arity) {
            var Ctor = createCtor(func);
            function wrapper() {
              var length = arguments.length, args = Array2(length), index2 = length, placeholder2 = getHolder(wrapper);
              while (index2--) {
                args[index2] = arguments[index2];
              }
              var holders = length < 3 && args[0] !== placeholder2 && args[length - 1] !== placeholder2 ? [] : replaceHolders(args, placeholder2);
              length -= holders.length;
              if (length < arity) {
                return createRecurry(func, bitmask, createHybrid, wrapper.placeholder, undefined$1, args, holders, undefined$1, undefined$1, arity - length);
              }
              var fn = this && this !== root && this instanceof wrapper ? Ctor : func;
              return apply(fn, this, args);
            }
            return wrapper;
          }
          function createFind(findIndexFunc) {
            return function(collection, predicate, fromIndex) {
              var iterable = Object2(collection);
              if (!isArrayLike(collection)) {
                var iteratee2 = getIteratee(predicate, 3);
                collection = keys(collection);
                predicate = function(key) {
                  return iteratee2(iterable[key], key, iterable);
                };
              }
              var index2 = findIndexFunc(collection, predicate, fromIndex);
              return index2 > -1 ? iterable[iteratee2 ? collection[index2] : index2] : undefined$1;
            };
          }
          function createFlow(fromRight) {
            return flatRest(function(funcs) {
              var length = funcs.length, index2 = length, prereq = LodashWrapper.prototype.thru;
              if (fromRight) {
                funcs.reverse();
              }
              while (index2--) {
                var func = funcs[index2];
                if (typeof func != "function") {
                  throw new TypeError2(FUNC_ERROR_TEXT);
                }
                if (prereq && !wrapper && getFuncName(func) == "wrapper") {
                  var wrapper = new LodashWrapper([], true);
                }
              }
              index2 = wrapper ? index2 : length;
              while (++index2 < length) {
                func = funcs[index2];
                var funcName = getFuncName(func), data3 = funcName == "wrapper" ? getData2(func) : undefined$1;
                if (data3 && isLaziable(data3[0]) && data3[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && !data3[4].length && data3[9] == 1) {
                  wrapper = wrapper[getFuncName(data3[0])].apply(wrapper, data3[3]);
                } else {
                  wrapper = func.length == 1 && isLaziable(func) ? wrapper[funcName]() : wrapper.thru(func);
                }
              }
              return function() {
                var args = arguments, value = args[0];
                if (wrapper && args.length == 1 && isArray6(value)) {
                  return wrapper.plant(value).value();
                }
                var index22 = 0, result22 = length ? funcs[index22].apply(this, args) : value;
                while (++index22 < length) {
                  result22 = funcs[index22].call(this, result22);
                }
                return result22;
              };
            });
          }
          function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary2, arity) {
            var isAry = bitmask & WRAP_ARY_FLAG, isBind = bitmask & WRAP_BIND_FLAG, isBindKey = bitmask & WRAP_BIND_KEY_FLAG, isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), isFlip = bitmask & WRAP_FLIP_FLAG, Ctor = isBindKey ? undefined$1 : createCtor(func);
            function wrapper() {
              var length = arguments.length, args = Array2(length), index2 = length;
              while (index2--) {
                args[index2] = arguments[index2];
              }
              if (isCurried) {
                var placeholder2 = getHolder(wrapper), holdersCount = countHolders(args, placeholder2);
              }
              if (partials) {
                args = composeArgs(args, partials, holders, isCurried);
              }
              if (partialsRight) {
                args = composeArgsRight(args, partialsRight, holdersRight, isCurried);
              }
              length -= holdersCount;
              if (isCurried && length < arity) {
                var newHolders = replaceHolders(args, placeholder2);
                return createRecurry(func, bitmask, createHybrid, wrapper.placeholder, thisArg, args, newHolders, argPos, ary2, arity - length);
              }
              var thisBinding = isBind ? thisArg : this, fn = isBindKey ? thisBinding[func] : func;
              length = args.length;
              if (argPos) {
                args = reorder(args, argPos);
              } else if (isFlip && length > 1) {
                args.reverse();
              }
              if (isAry && ary2 < length) {
                args.length = ary2;
              }
              if (this && this !== root && this instanceof wrapper) {
                fn = Ctor || createCtor(fn);
              }
              return fn.apply(thisBinding, args);
            }
            return wrapper;
          }
          function createInverter(setter, toIteratee) {
            return function(object, iteratee2) {
              return baseInverter(object, setter, toIteratee(iteratee2), {});
            };
          }
          function createMathOperation(operator, defaultValue) {
            return function(value, other) {
              var result22;
              if (value === undefined$1 && other === undefined$1) {
                return defaultValue;
              }
              if (value !== undefined$1) {
                result22 = value;
              }
              if (other !== undefined$1) {
                if (result22 === undefined$1) {
                  return other;
                }
                if (typeof value == "string" || typeof other == "string") {
                  value = baseToString(value);
                  other = baseToString(other);
                } else {
                  value = baseToNumber(value);
                  other = baseToNumber(other);
                }
                result22 = operator(value, other);
              }
              return result22;
            };
          }
          function createOver(arrayFunc) {
            return flatRest(function(iteratees) {
              iteratees = arrayMap(iteratees, baseUnary(getIteratee()));
              return baseRest(function(args) {
                var thisArg = this;
                return arrayFunc(iteratees, function(iteratee2) {
                  return apply(iteratee2, thisArg, args);
                });
              });
            });
          }
          function createPadding(length, chars) {
            chars = chars === undefined$1 ? " " : baseToString(chars);
            var charsLength = chars.length;
            if (charsLength < 2) {
              return charsLength ? baseRepeat(chars, length) : chars;
            }
            var result22 = baseRepeat(chars, nativeCeil(length / stringSize(chars)));
            return hasUnicode(chars) ? castSlice(stringToArray(result22), 0, length).join("") : result22.slice(0, length);
          }
          function createPartial(func, bitmask, thisArg, partials) {
            var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func);
            function wrapper() {
              var argsIndex = -1, argsLength = arguments.length, leftIndex = -1, leftLength = partials.length, args = Array2(leftLength + argsLength), fn = this && this !== root && this instanceof wrapper ? Ctor : func;
              while (++leftIndex < leftLength) {
                args[leftIndex] = partials[leftIndex];
              }
              while (argsLength--) {
                args[leftIndex++] = arguments[++argsIndex];
              }
              return apply(fn, isBind ? thisArg : this, args);
            }
            return wrapper;
          }
          function createRange(fromRight) {
            return function(start, end, step) {
              if (step && typeof step != "number" && isIterateeCall(start, end, step)) {
                end = step = undefined$1;
              }
              start = toFinite(start);
              if (end === undefined$1) {
                end = start;
                start = 0;
              } else {
                end = toFinite(end);
              }
              step = step === undefined$1 ? start < end ? 1 : -1 : toFinite(step);
              return baseRange(start, end, step, fromRight);
            };
          }
          function createRelationalOperation(operator) {
            return function(value, other) {
              if (!(typeof value == "string" && typeof other == "string")) {
                value = toNumber(value);
                other = toNumber(other);
              }
              return operator(value, other);
            };
          }
          function createRecurry(func, bitmask, wrapFunc, placeholder2, thisArg, partials, holders, argPos, ary2, arity) {
            var isCurry = bitmask & WRAP_CURRY_FLAG, newHolders = isCurry ? holders : undefined$1, newHoldersRight = isCurry ? undefined$1 : holders, newPartials = isCurry ? partials : undefined$1, newPartialsRight = isCurry ? undefined$1 : partials;
            bitmask |= isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG;
            bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG);
            if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) {
              bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG);
            }
            var newData = [
              func,
              bitmask,
              thisArg,
              newPartials,
              newHolders,
              newPartialsRight,
              newHoldersRight,
              argPos,
              ary2,
              arity
            ];
            var result22 = wrapFunc.apply(undefined$1, newData);
            if (isLaziable(func)) {
              setData(result22, newData);
            }
            result22.placeholder = placeholder2;
            return setWrapToString(result22, func, bitmask);
          }
          function createRound(methodName) {
            var func = Math2[methodName];
            return function(number2, precision) {
              number2 = toNumber(number2);
              precision = precision == null ? 0 : nativeMin(toInteger(precision), 292);
              if (precision && nativeIsFinite(number2)) {
                var pair = (toString8(number2) + "e").split("e"), value = func(pair[0] + "e" + (+pair[1] + precision));
                pair = (toString8(value) + "e").split("e");
                return +(pair[0] + "e" + (+pair[1] - precision));
              }
              return func(number2);
            };
          }
          var createSet = !(Set2 && 1 / setToArray(new Set2([, -0]))[1] == INFINITY) ? noop2 : function(values2) {
            return new Set2(values2);
          };
          function createToPairs(keysFunc) {
            return function(object) {
              var tag = getTag(object);
              if (tag == mapTag) {
                return mapToArray(object);
              }
              if (tag == setTag) {
                return setToPairs(object);
              }
              return baseToPairs(object, keysFunc(object));
            };
          }
          function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary2, arity) {
            var isBindKey = bitmask & WRAP_BIND_KEY_FLAG;
            if (!isBindKey && typeof func != "function") {
              throw new TypeError2(FUNC_ERROR_TEXT);
            }
            var length = partials ? partials.length : 0;
            if (!length) {
              bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG);
              partials = holders = undefined$1;
            }
            ary2 = ary2 === undefined$1 ? ary2 : nativeMax(toInteger(ary2), 0);
            arity = arity === undefined$1 ? arity : toInteger(arity);
            length -= holders ? holders.length : 0;
            if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) {
              var partialsRight = partials, holdersRight = holders;
              partials = holders = undefined$1;
            }
            var data3 = isBindKey ? undefined$1 : getData2(func);
            var newData = [
              func,
              bitmask,
              thisArg,
              partials,
              holders,
              partialsRight,
              holdersRight,
              argPos,
              ary2,
              arity
            ];
            if (data3) {
              mergeData(newData, data3);
            }
            func = newData[0];
            bitmask = newData[1];
            thisArg = newData[2];
            partials = newData[3];
            holders = newData[4];
            arity = newData[9] = newData[9] === undefined$1 ? isBindKey ? 0 : func.length : nativeMax(newData[9] - length, 0);
            if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) {
              bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG);
            }
            if (!bitmask || bitmask == WRAP_BIND_FLAG) {
              var result22 = createBind(func, bitmask, thisArg);
            } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) {
              result22 = createCurry(func, bitmask, arity);
            } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) {
              result22 = createPartial(func, bitmask, thisArg, partials);
            } else {
              result22 = createHybrid.apply(undefined$1, newData);
            }
            var setter = data3 ? baseSetData : setData;
            return setWrapToString(setter(result22, newData), func, bitmask);
          }
          function customDefaultsAssignIn(objValue, srcValue, key, object) {
            if (objValue === undefined$1 || eq2(objValue, objectProto[key]) && !hasOwnProperty3.call(object, key)) {
              return srcValue;
            }
            return objValue;
          }
          function customDefaultsMerge(objValue, srcValue, key, object, source2, stack) {
            if (isObject7(objValue) && isObject7(srcValue)) {
              stack.set(srcValue, objValue);
              baseMerge(objValue, srcValue, undefined$1, customDefaultsMerge, stack);
              stack["delete"](srcValue);
            }
            return objValue;
          }
          function customOmitClone(value) {
            return isPlainObject(value) ? undefined$1 : value;
          }
          function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
            var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length;
            if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
              return false;
            }
            var arrStacked = stack.get(array);
            var othStacked = stack.get(other);
            if (arrStacked && othStacked) {
              return arrStacked == other && othStacked == array;
            }
            var index2 = -1, result22 = true, seen = bitmask & COMPARE_UNORDERED_FLAG ? new SetCache() : undefined$1;
            stack.set(array, other);
            stack.set(other, array);
            while (++index2 < arrLength) {
              var arrValue = array[index2], othValue = other[index2];
              if (customizer) {
                var compared = isPartial ? customizer(othValue, arrValue, index2, other, array, stack) : customizer(arrValue, othValue, index2, array, other, stack);
              }
              if (compared !== undefined$1) {
                if (compared) {
                  continue;
                }
                result22 = false;
                break;
              }
              if (seen) {
                if (!arraySome(other, function(othValue2, othIndex) {
                  if (!cacheHas(seen, othIndex) && (arrValue === othValue2 || equalFunc(arrValue, othValue2, bitmask, customizer, stack))) {
                    return seen.push(othIndex);
                  }
                })) {
                  result22 = false;
                  break;
                }
              } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
                result22 = false;
                break;
              }
            }
            stack["delete"](array);
            stack["delete"](other);
            return result22;
          }
          function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
            switch (tag) {
              case dataViewTag:
                if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) {
                  return false;
                }
                object = object.buffer;
                other = other.buffer;
              case arrayBufferTag:
                if (object.byteLength != other.byteLength || !equalFunc(new Uint8Array2(object), new Uint8Array2(other))) {
                  return false;
                }
                return true;
              case boolTag:
              case dateTag:
              case numberTag:
                return eq2(+object, +other);
              case errorTag:
                return object.name == other.name && object.message == other.message;
              case regexpTag:
              case stringTag:
                return object == other + "";
              case mapTag:
                var convert = mapToArray;
              case setTag:
                var isPartial = bitmask & COMPARE_PARTIAL_FLAG;
                convert || (convert = setToArray);
                if (object.size != other.size && !isPartial) {
                  return false;
                }
                var stacked = stack.get(object);
                if (stacked) {
                  return stacked == other;
                }
                bitmask |= COMPARE_UNORDERED_FLAG;
                stack.set(object, other);
                var result22 = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
                stack["delete"](object);
                return result22;
              case symbolTag:
                if (symbolValueOf) {
                  return symbolValueOf.call(object) == symbolValueOf.call(other);
                }
            }
            return false;
          }
          function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
            var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length;
            if (objLength != othLength && !isPartial) {
              return false;
            }
            var index2 = objLength;
            while (index2--) {
              var key = objProps[index2];
              if (!(isPartial ? key in other : hasOwnProperty3.call(other, key))) {
                return false;
              }
            }
            var objStacked = stack.get(object);
            var othStacked = stack.get(other);
            if (objStacked && othStacked) {
              return objStacked == other && othStacked == object;
            }
            var result22 = true;
            stack.set(object, other);
            stack.set(other, object);
            var skipCtor = isPartial;
            while (++index2 < objLength) {
              key = objProps[index2];
              var objValue = object[key], othValue = other[key];
              if (customizer) {
                var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack);
              }
              if (!(compared === undefined$1 ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) {
                result22 = false;
                break;
              }
              skipCtor || (skipCtor = key == "constructor");
            }
            if (result22 && !skipCtor) {
              var objCtor = object.constructor, othCtor = other.constructor;
              if (objCtor != othCtor && ("constructor" in object && "constructor" in other) && !(typeof objCtor == "function" && objCtor instanceof objCtor && typeof othCtor == "function" && othCtor instanceof othCtor)) {
                result22 = false;
              }
            }
            stack["delete"](object);
            stack["delete"](other);
            return result22;
          }
          function flatRest(func) {
            return setToString(overRest(func, undefined$1, flatten), func + "");
          }
          function getAllKeys(object) {
            return baseGetAllKeys(object, keys, getSymbols);
          }
          function getAllKeysIn(object) {
            return baseGetAllKeys(object, keysIn, getSymbolsIn);
          }
          var getData2 = !metaMap ? noop2 : function(func) {
            return metaMap.get(func);
          };
          function getFuncName(func) {
            var result22 = func.name + "", array = realNames[result22], length = hasOwnProperty3.call(realNames, result22) ? array.length : 0;
            while (length--) {
              var data3 = array[length], otherFunc = data3.func;
              if (otherFunc == null || otherFunc == func) {
                return data3.name;
              }
            }
            return result22;
          }
          function getHolder(func) {
            var object = hasOwnProperty3.call(lodash2, "placeholder") ? lodash2 : func;
            return object.placeholder;
          }
          function getIteratee() {
            var result22 = lodash2.iteratee || iteratee;
            result22 = result22 === iteratee ? baseIteratee : result22;
            return arguments.length ? result22(arguments[0], arguments[1]) : result22;
          }
          function getMapData(map22, key) {
            var data3 = map22.__data__;
            return isKeyable(key) ? data3[typeof key == "string" ? "string" : "hash"] : data3.map;
          }
          function getMatchData(object) {
            var result22 = keys(object), length = result22.length;
            while (length--) {
              var key = result22[length], value = object[key];
              result22[length] = [key, value, isStrictComparable(value)];
            }
            return result22;
          }
          function getNative(object, key) {
            var value = getValue(object, key);
            return baseIsNative(value) ? value : undefined$1;
          }
          function getRawTag(value) {
            var isOwn = hasOwnProperty3.call(value, symToStringTag), tag = value[symToStringTag];
            try {
              value[symToStringTag] = undefined$1;
              var unmasked = true;
            } catch (e5) {
            }
            var result22 = nativeObjectToString.call(value);
            if (unmasked) {
              if (isOwn) {
                value[symToStringTag] = tag;
              } else {
                delete value[symToStringTag];
              }
            }
            return result22;
          }
          var getSymbols = !nativeGetSymbols ? stubArray : function(object) {
            if (object == null) {
              return [];
            }
            object = Object2(object);
            return arrayFilter(nativeGetSymbols(object), function(symbol) {
              return propertyIsEnumerable.call(object, symbol);
            });
          };
          var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {
            var result22 = [];
            while (object) {
              arrayPush(result22, getSymbols(object));
              object = getPrototype(object);
            }
            return result22;
          };
          var getTag = baseGetTag;
          if (DataView2 && getTag(new DataView2(new ArrayBuffer(1))) != dataViewTag || Map2 && getTag(new Map2()) != mapTag || Promise3 && getTag(Promise3.resolve()) != promiseTag || Set2 && getTag(new Set2()) != setTag || WeakMap2 && getTag(new WeakMap2()) != weakMapTag) {
            getTag = function(value) {
              var result22 = baseGetTag(value), Ctor = result22 == objectTag ? value.constructor : undefined$1, ctorString = Ctor ? toSource(Ctor) : "";
              if (ctorString) {
                switch (ctorString) {
                  case dataViewCtorString:
                    return dataViewTag;
                  case mapCtorString:
                    return mapTag;
                  case promiseCtorString:
                    return promiseTag;
                  case setCtorString:
                    return setTag;
                  case weakMapCtorString:
                    return weakMapTag;
                }
              }
              return result22;
            };
          }
          function getView(start, end, transforms) {
            var index2 = -1, length = transforms.length;
            while (++index2 < length) {
              var data3 = transforms[index2], size2 = data3.size;
              switch (data3.type) {
                case "drop":
                  start += size2;
                  break;
                case "dropRight":
                  end -= size2;
                  break;
                case "take":
                  end = nativeMin(end, start + size2);
                  break;
                case "takeRight":
                  start = nativeMax(start, end - size2);
                  break;
              }
            }
            return { start, end };
          }
          function getWrapDetails(source2) {
            var match = source2.match(reWrapDetails);
            return match ? match[1].split(reSplitDetails) : [];
          }
          function hasPath(object, path3, hasFunc) {
            path3 = castPath(path3, object);
            var index2 = -1, length = path3.length, result22 = false;
            while (++index2 < length) {
              var key = toKey(path3[index2]);
              if (!(result22 = object != null && hasFunc(object, key))) {
                break;
              }
              object = object[key];
            }
            if (result22 || ++index2 != length) {
              return result22;
            }
            length = object == null ? 0 : object.length;
            return !!length && isLength(length) && isIndex(key, length) && (isArray6(object) || isArguments(object));
          }
          function initCloneArray(array) {
            var length = array.length, result22 = new array.constructor(length);
            if (length && typeof array[0] == "string" && hasOwnProperty3.call(array, "index")) {
              result22.index = array.index;
              result22.input = array.input;
            }
            return result22;
          }
          function initCloneObject(object) {
            return typeof object.constructor == "function" && !isPrototype(object) ? baseCreate(getPrototype(object)) : {};
          }
          function initCloneByTag(object, tag, isDeep) {
            var Ctor = object.constructor;
            switch (tag) {
              case arrayBufferTag:
                return cloneArrayBuffer(object);
              case boolTag:
              case dateTag:
                return new Ctor(+object);
              case dataViewTag:
                return cloneDataView(object, isDeep);
              case float32Tag:
              case float64Tag:
              case int8Tag:
              case int16Tag:
              case int32Tag:
              case uint8Tag:
              case uint8ClampedTag:
              case uint16Tag:
              case uint32Tag:
                return cloneTypedArray(object, isDeep);
              case mapTag:
                return new Ctor();
              case numberTag:
              case stringTag:
                return new Ctor(object);
              case regexpTag:
                return cloneRegExp(object);
              case setTag:
                return new Ctor();
              case symbolTag:
                return cloneSymbol(object);
            }
          }
          function insertWrapDetails(source2, details) {
            var length = details.length;
            if (!length) {
              return source2;
            }
            var lastIndex = length - 1;
            details[lastIndex] = (length > 1 ? "& " : "") + details[lastIndex];
            details = details.join(length > 2 ? ", " : " ");
            return source2.replace(reWrapComment, "{\n/* [wrapped with " + details + "] */\n");
          }
          function isFlattenable(value) {
            return isArray6(value) || isArguments(value) || !!(spreadableSymbol && value && value[spreadableSymbol]);
          }
          function isIndex(value, length) {
            var type22 = typeof value;
            length = length == null ? MAX_SAFE_INTEGER2 : length;
            return !!length && (type22 == "number" || type22 != "symbol" && reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length);
          }
          function isIterateeCall(value, index2, object) {
            if (!isObject7(object)) {
              return false;
            }
            var type22 = typeof index2;
            if (type22 == "number" ? isArrayLike(object) && isIndex(index2, object.length) : type22 == "string" && index2 in object) {
              return eq2(object[index2], value);
            }
            return false;
          }
          function isKey(value, object) {
            if (isArray6(value)) {
              return false;
            }
            var type22 = typeof value;
            if (type22 == "number" || type22 == "symbol" || type22 == "boolean" || value == null || isSymbol3(value)) {
              return true;
            }
            return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object2(object);
          }
          function isKeyable(value) {
            var type22 = typeof value;
            return type22 == "string" || type22 == "number" || type22 == "symbol" || type22 == "boolean" ? value !== "__proto__" : value === null;
          }
          function isLaziable(func) {
            var funcName = getFuncName(func), other = lodash2[funcName];
            if (typeof other != "function" || !(funcName in LazyWrapper.prototype)) {
              return false;
            }
            if (func === other) {
              return true;
            }
            var data3 = getData2(other);
            return !!data3 && func === data3[0];
          }
          function isMasked(func) {
            return !!maskSrcKey && maskSrcKey in func;
          }
          var isMaskable = coreJsData ? isFunction3 : stubFalse;
          function isPrototype(value) {
            var Ctor = value && value.constructor, proto2 = typeof Ctor == "function" && Ctor.prototype || objectProto;
            return value === proto2;
          }
          function isStrictComparable(value) {
            return value === value && !isObject7(value);
          }
          function matchesStrictComparable(key, srcValue) {
            return function(object) {
              if (object == null) {
                return false;
              }
              return object[key] === srcValue && (srcValue !== undefined$1 || key in Object2(object));
            };
          }
          function memoizeCapped(func) {
            var result22 = memoize2(func, function(key) {
              if (cache3.size === MAX_MEMOIZE_SIZE) {
                cache3.clear();
              }
              return key;
            });
            var cache3 = result22.cache;
            return result22;
          }
          function mergeData(data3, source2) {
            var bitmask = data3[1], srcBitmask = source2[1], newBitmask = bitmask | srcBitmask, isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG);
            var isCombo = srcBitmask == WRAP_ARY_FLAG && bitmask == WRAP_CURRY_FLAG || srcBitmask == WRAP_ARY_FLAG && bitmask == WRAP_REARG_FLAG && data3[7].length <= source2[8] || srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG) && source2[7].length <= source2[8] && bitmask == WRAP_CURRY_FLAG;
            if (!(isCommon || isCombo)) {
              return data3;
            }
            if (srcBitmask & WRAP_BIND_FLAG) {
              data3[2] = source2[2];
              newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG;
            }
            var value = source2[3];
            if (value) {
              var partials = data3[3];
              data3[3] = partials ? composeArgs(partials, value, source2[4]) : value;
              data3[4] = partials ? replaceHolders(data3[3], PLACEHOLDER) : source2[4];
            }
            value = source2[5];
            if (value) {
              partials = data3[5];
              data3[5] = partials ? composeArgsRight(partials, value, source2[6]) : value;
              data3[6] = partials ? replaceHolders(data3[5], PLACEHOLDER) : source2[6];
            }
            value = source2[7];
            if (value) {
              data3[7] = value;
            }
            if (srcBitmask & WRAP_ARY_FLAG) {
              data3[8] = data3[8] == null ? source2[8] : nativeMin(data3[8], source2[8]);
            }
            if (data3[9] == null) {
              data3[9] = source2[9];
            }
            data3[0] = source2[0];
            data3[1] = newBitmask;
            return data3;
          }
          function nativeKeysIn(object) {
            var result22 = [];
            if (object != null) {
              for (var key in Object2(object)) {
                result22.push(key);
              }
            }
            return result22;
          }
          function objectToString(value) {
            return nativeObjectToString.call(value);
          }
          function overRest(func, start, transform2) {
            start = nativeMax(start === undefined$1 ? func.length - 1 : start, 0);
            return function() {
              var args = arguments, index2 = -1, length = nativeMax(args.length - start, 0), array = Array2(length);
              while (++index2 < length) {
                array[index2] = args[start + index2];
              }
              index2 = -1;
              var otherArgs = Array2(start + 1);
              while (++index2 < start) {
                otherArgs[index2] = args[index2];
              }
              otherArgs[start] = transform2(array);
              return apply(func, this, otherArgs);
            };
          }
          function parent(object, path3) {
            return path3.length < 2 ? object : baseGet(object, baseSlice(path3, 0, -1));
          }
          function reorder(array, indexes) {
            var arrLength = array.length, length = nativeMin(indexes.length, arrLength), oldArray = copyArray(array);
            while (length--) {
              var index2 = indexes[length];
              array[length] = isIndex(index2, arrLength) ? oldArray[index2] : undefined$1;
            }
            return array;
          }
          function safeGet(object, key) {
            if (key === "constructor" && typeof object[key] === "function") {
              return;
            }
            if (key == "__proto__") {
              return;
            }
            return object[key];
          }
          var setData = shortOut(baseSetData);
          var setTimeout2 = ctxSetTimeout || function(func, wait) {
            return root.setTimeout(func, wait);
          };
          var setToString = shortOut(baseSetToString);
          function setWrapToString(wrapper, reference, bitmask) {
            var source2 = reference + "";
            return setToString(wrapper, insertWrapDetails(source2, updateWrapDetails(getWrapDetails(source2), bitmask)));
          }
          function shortOut(func) {
            var count = 0, lastCalled = 0;
            return function() {
              var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled);
              lastCalled = stamp;
              if (remaining > 0) {
                if (++count >= HOT_COUNT) {
                  return arguments[0];
                }
              } else {
                count = 0;
              }
              return func.apply(undefined$1, arguments);
            };
          }
          function shuffleSelf(array, size2) {
            var index2 = -1, length = array.length, lastIndex = length - 1;
            size2 = size2 === undefined$1 ? length : size2;
            while (++index2 < size2) {
              var rand = baseRandom(index2, lastIndex), value = array[rand];
              array[rand] = array[index2];
              array[index2] = value;
            }
            array.length = size2;
            return array;
          }
          var stringToPath = memoizeCapped(function(string2) {
            var result22 = [];
            if (string2.charCodeAt(0) === 46) {
              result22.push("");
            }
            string2.replace(rePropName, function(match, number2, quote, subString) {
              result22.push(quote ? subString.replace(reEscapeChar, "$1") : number2 || match);
            });
            return result22;
          });
          function toKey(value) {
            if (typeof value == "string" || isSymbol3(value)) {
              return value;
            }
            var result22 = value + "";
            return result22 == "0" && 1 / value == -INFINITY ? "-0" : result22;
          }
          function toSource(func) {
            if (func != null) {
              try {
                return funcToString.call(func);
              } catch (e5) {
              }
              try {
                return func + "";
              } catch (e5) {
              }
            }
            return "";
          }
          function updateWrapDetails(details, bitmask) {
            arrayEach(wrapFlags, function(pair) {
              var value = "_." + pair[0];
              if (bitmask & pair[1] && !arrayIncludes(details, value)) {
                details.push(value);
              }
            });
            return details.sort();
          }
          function wrapperClone(wrapper) {
            if (wrapper instanceof LazyWrapper) {
              return wrapper.clone();
            }
            var result22 = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);
            result22.__actions__ = copyArray(wrapper.__actions__);
            result22.__index__ = wrapper.__index__;
            result22.__values__ = wrapper.__values__;
            return result22;
          }
          function chunk(array, size2, guard) {
            if (guard ? isIterateeCall(array, size2, guard) : size2 === undefined$1) {
              size2 = 1;
            } else {
              size2 = nativeMax(toInteger(size2), 0);
            }
            var length = array == null ? 0 : array.length;
            if (!length || size2 < 1) {
              return [];
            }
            var index2 = 0, resIndex = 0, result22 = Array2(nativeCeil(length / size2));
            while (index2 < length) {
              result22[resIndex++] = baseSlice(array, index2, index2 += size2);
            }
            return result22;
          }
          function compact(array) {
            var index2 = -1, length = array == null ? 0 : array.length, resIndex = 0, result22 = [];
            while (++index2 < length) {
              var value = array[index2];
              if (value) {
                result22[resIndex++] = value;
              }
            }
            return result22;
          }
          function concat3() {
            var length = arguments.length;
            if (!length) {
              return [];
            }
            var args = Array2(length - 1), array = arguments[0], index2 = length;
            while (index2--) {
              args[index2 - 1] = arguments[index2];
            }
            return arrayPush(isArray6(array) ? copyArray(array) : [array], baseFlatten(args, 1));
          }
          var difference2 = baseRest(function(array, values2) {
            return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values2, 1, isArrayLikeObject, true)) : [];
          });
          var differenceBy = baseRest(function(array, values2) {
            var iteratee2 = last(values2);
            if (isArrayLikeObject(iteratee2)) {
              iteratee2 = undefined$1;
            }
            return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values2, 1, isArrayLikeObject, true), getIteratee(iteratee2, 2)) : [];
          });
          var differenceWith = baseRest(function(array, values2) {
            var comparator = last(values2);
            if (isArrayLikeObject(comparator)) {
              comparator = undefined$1;
            }
            return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values2, 1, isArrayLikeObject, true), undefined$1, comparator) : [];
          });
          function drop(array, n5, guard) {
            var length = array == null ? 0 : array.length;
            if (!length) {
              return [];
            }
            n5 = guard || n5 === undefined$1 ? 1 : toInteger(n5);
            return baseSlice(array, n5 < 0 ? 0 : n5, length);
          }
          function dropRight(array, n5, guard) {
            var length = array == null ? 0 : array.length;
            if (!length) {
              return [];
            }
            n5 = guard || n5 === undefined$1 ? 1 : toInteger(n5);
            n5 = length - n5;
            return baseSlice(array, 0, n5 < 0 ? 0 : n5);
          }
          function dropRightWhile(array, predicate) {
            return array && array.length ? baseWhile(array, getIteratee(predicate, 3), true, true) : [];
          }
          function dropWhile(array, predicate) {
            return array && array.length ? baseWhile(array, getIteratee(predicate, 3), true) : [];
          }
          function fill(array, value, start, end) {
            var length = array == null ? 0 : array.length;
            if (!length) {
              return [];
            }
            if (start && typeof start != "number" && isIterateeCall(array, value, start)) {
              start = 0;
              end = length;
            }
            return baseFill(array, value, start, end);
          }
          function findIndex(array, predicate, fromIndex) {
            var length = array == null ? 0 : array.length;
            if (!length) {
              return -1;
            }
            var index2 = fromIndex == null ? 0 : toInteger(fromIndex);
            if (index2 < 0) {
              index2 = nativeMax(length + index2, 0);
            }
            return baseFindIndex(array, getIteratee(predicate, 3), index2);
          }
          function findLastIndex(array, predicate, fromIndex) {
            var length = array == null ? 0 : array.length;
            if (!length) {
              return -1;
            }
            var index2 = length - 1;
            if (fromIndex !== undefined$1) {
              index2 = toInteger(fromIndex);
              index2 = fromIndex < 0 ? nativeMax(length + index2, 0) : nativeMin(index2, length - 1);
            }
            return baseFindIndex(array, getIteratee(predicate, 3), index2, true);
          }
          function flatten(array) {
            var length = array == null ? 0 : array.length;
            return length ? baseFlatten(array, 1) : [];
          }
          function flattenDeep(array) {
            var length = array == null ? 0 : array.length;
            return length ? baseFlatten(array, INFINITY) : [];
          }
          function flattenDepth(array, depth) {
            var length = array == null ? 0 : array.length;
            if (!length) {
              return [];
            }
            depth = depth === undefined$1 ? 1 : toInteger(depth);
            return baseFlatten(array, depth);
          }
          function fromPairs(pairs3) {
            var index2 = -1, length = pairs3 == null ? 0 : pairs3.length, result22 = {};
            while (++index2 < length) {
              var pair = pairs3[index2];
              result22[pair[0]] = pair[1];
            }
            return result22;
          }
          function head(array) {
            return array && array.length ? array[0] : undefined$1;
          }
          function indexOf2(array, value, fromIndex) {
            var length = array == null ? 0 : array.length;
            if (!length) {
              return -1;
            }
            var index2 = fromIndex == null ? 0 : toInteger(fromIndex);
            if (index2 < 0) {
              index2 = nativeMax(length + index2, 0);
            }
            return baseIndexOf(array, value, index2);
          }
          function initial(array) {
            var length = array == null ? 0 : array.length;
            return length ? baseSlice(array, 0, -1) : [];
          }
          var intersection = baseRest(function(arrays) {
            var mapped = arrayMap(arrays, castArrayLikeObject);
            return mapped.length && mapped[0] === arrays[0] ? baseIntersection(mapped) : [];
          });
          var intersectionBy = baseRest(function(arrays) {
            var iteratee2 = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject);
            if (iteratee2 === last(mapped)) {
              iteratee2 = undefined$1;
            } else {
              mapped.pop();
            }
            return mapped.length && mapped[0] === arrays[0] ? baseIntersection(mapped, getIteratee(iteratee2, 2)) : [];
          });
          var intersectionWith = baseRest(function(arrays) {
            var comparator = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject);
            comparator = typeof comparator == "function" ? comparator : undefined$1;
            if (comparator) {
              mapped.pop();
            }
            return mapped.length && mapped[0] === arrays[0] ? baseIntersection(mapped, undefined$1, comparator) : [];
          });
          function join17(array, separator) {
            return array == null ? "" : nativeJoin.call(array, separator);
          }
          function last(array) {
            var length = array == null ? 0 : array.length;
            return length ? array[length - 1] : undefined$1;
          }
          function lastIndexOf(array, value, fromIndex) {
            var length = array == null ? 0 : array.length;
            if (!length) {
              return -1;
            }
            var index2 = length;
            if (fromIndex !== undefined$1) {
              index2 = toInteger(fromIndex);
              index2 = index2 < 0 ? nativeMax(length + index2, 0) : nativeMin(index2, length - 1);
            }
            return value === value ? strictLastIndexOf(array, value, index2) : baseFindIndex(array, baseIsNaN, index2, true);
          }
          function nth(array, n5) {
            return array && array.length ? baseNth(array, toInteger(n5)) : undefined$1;
          }
          var pull = baseRest(pullAll);
          function pullAll(array, values2) {
            return array && array.length && values2 && values2.length ? basePullAll(array, values2) : array;
          }
          function pullAllBy(array, values2, iteratee2) {
            return array && array.length && values2 && values2.length ? basePullAll(array, values2, getIteratee(iteratee2, 2)) : array;
          }
          function pullAllWith(array, values2, comparator) {
            return array && array.length && values2 && values2.length ? basePullAll(array, values2, undefined$1, comparator) : array;
          }
          var pullAt = flatRest(function(array, indexes) {
            var length = array == null ? 0 : array.length, result22 = baseAt(array, indexes);
            basePullAt(array, arrayMap(indexes, function(index2) {
              return isIndex(index2, length) ? +index2 : index2;
            }).sort(compareAscending));
            return result22;
          });
          function remove(array, predicate) {
            var result22 = [];
            if (!(array && array.length)) {
              return result22;
            }
            var index2 = -1, indexes = [], length = array.length;
            predicate = getIteratee(predicate, 3);
            while (++index2 < length) {
              var value = array[index2];
              if (predicate(value, index2, array)) {
                result22.push(value);
                indexes.push(index2);
              }
            }
            basePullAt(array, indexes);
            return result22;
          }
          function reverse(array) {
            return array == null ? array : nativeReverse.call(array);
          }
          function slice2(array, start, end) {
            var length = array == null ? 0 : array.length;
            if (!length) {
              return [];
            }
            if (end && typeof end != "number" && isIterateeCall(array, start, end)) {
              start = 0;
              end = length;
            } else {
              start = start == null ? 0 : toInteger(start);
              end = end === undefined$1 ? length : toInteger(end);
            }
            return baseSlice(array, start, end);
          }
          function sortedIndex(array, value) {
            return baseSortedIndex(array, value);
          }
          function sortedIndexBy(array, value, iteratee2) {
            return baseSortedIndexBy(array, value, getIteratee(iteratee2, 2));
          }
          function sortedIndexOf(array, value) {
            var length = array == null ? 0 : array.length;
            if (length) {
              var index2 = baseSortedIndex(array, value);
              if (index2 < length && eq2(array[index2], value)) {
                return index2;
              }
            }
            return -1;
          }
          function sortedLastIndex(array, value) {
            return baseSortedIndex(array, value, true);
          }
          function sortedLastIndexBy(array, value, iteratee2) {
            return baseSortedIndexBy(array, value, getIteratee(iteratee2, 2), true);
          }
          function sortedLastIndexOf(array, value) {
            var length = array == null ? 0 : array.length;
            if (length) {
              var index2 = baseSortedIndex(array, value, true) - 1;
              if (eq2(array[index2], value)) {
                return index2;
              }
            }
            return -1;
          }
          function sortedUniq(array) {
            return array && array.length ? baseSortedUniq(array) : [];
          }
          function sortedUniqBy(array, iteratee2) {
            return array && array.length ? baseSortedUniq(array, getIteratee(iteratee2, 2)) : [];
          }
          function tail(array) {
            var length = array == null ? 0 : array.length;
            return length ? baseSlice(array, 1, length) : [];
          }
          function take(array, n5, guard) {
            if (!(array && array.length)) {
              return [];
            }
            n5 = guard || n5 === undefined$1 ? 1 : toInteger(n5);
            return baseSlice(array, 0, n5 < 0 ? 0 : n5);
          }
          function takeRight(array, n5, guard) {
            var length = array == null ? 0 : array.length;
            if (!length) {
              return [];
            }
            n5 = guard || n5 === undefined$1 ? 1 : toInteger(n5);
            n5 = length - n5;
            return baseSlice(array, n5 < 0 ? 0 : n5, length);
          }
          function takeRightWhile(array, predicate) {
            return array && array.length ? baseWhile(array, getIteratee(predicate, 3), false, true) : [];
          }
          function takeWhile(array, predicate) {
            return array && array.length ? baseWhile(array, getIteratee(predicate, 3)) : [];
          }
          var union = baseRest(function(arrays) {
            return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true));
          });
          var unionBy = baseRest(function(arrays) {
            var iteratee2 = last(arrays);
            if (isArrayLikeObject(iteratee2)) {
              iteratee2 = undefined$1;
            }
            return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee2, 2));
          });
          var unionWith = baseRest(function(arrays) {
            var comparator = last(arrays);
            comparator = typeof comparator == "function" ? comparator : undefined$1;
            return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined$1, comparator);
          });
          function uniq2(array) {
            return array && array.length ? baseUniq(array) : [];
          }
          function uniqBy2(array, iteratee2) {
            return array && array.length ? baseUniq(array, getIteratee(iteratee2, 2)) : [];
          }
          function uniqWith(array, comparator) {
            comparator = typeof comparator == "function" ? comparator : undefined$1;
            return array && array.length ? baseUniq(array, undefined$1, comparator) : [];
          }
          function unzip2(array) {
            if (!(array && array.length)) {
              return [];
            }
            var length = 0;
            array = arrayFilter(array, function(group) {
              if (isArrayLikeObject(group)) {
                length = nativeMax(group.length, length);
                return true;
              }
            });
            return baseTimes(length, function(index2) {
              return arrayMap(array, baseProperty(index2));
            });
          }
          function unzipWith(array, iteratee2) {
            if (!(array && array.length)) {
              return [];
            }
            var result22 = unzip2(array);
            if (iteratee2 == null) {
              return result22;
            }
            return arrayMap(result22, function(group) {
              return apply(iteratee2, undefined$1, group);
            });
          }
          var without = baseRest(function(array, values2) {
            return isArrayLikeObject(array) ? baseDifference(array, values2) : [];
          });
          var xor = baseRest(function(arrays) {
            return baseXor(arrayFilter(arrays, isArrayLikeObject));
          });
          var xorBy = baseRest(function(arrays) {
            var iteratee2 = last(arrays);
            if (isArrayLikeObject(iteratee2)) {
              iteratee2 = undefined$1;
            }
            return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee2, 2));
          });
          var xorWith = baseRest(function(arrays) {
            var comparator = last(arrays);
            comparator = typeof comparator == "function" ? comparator : undefined$1;
            return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined$1, comparator);
          });
          var zip2 = baseRest(unzip2);
          function zipObject(props, values2) {
            return baseZipObject(props || [], values2 || [], assignValue);
          }
          function zipObjectDeep(props, values2) {
            return baseZipObject(props || [], values2 || [], baseSet);
          }
          var zipWith = baseRest(function(arrays) {
            var length = arrays.length, iteratee2 = length > 1 ? arrays[length - 1] : undefined$1;
            iteratee2 = typeof iteratee2 == "function" ? (arrays.pop(), iteratee2) : undefined$1;
            return unzipWith(arrays, iteratee2);
          });
          function chain(value) {
            var result22 = lodash2(value);
            result22.__chain__ = true;
            return result22;
          }
          function tap(value, interceptor) {
            interceptor(value);
            return value;
          }
          function thru(value, interceptor) {
            return interceptor(value);
          }
          var wrapperAt = flatRest(function(paths) {
            var length = paths.length, start = length ? paths[0] : 0, value = this.__wrapped__, interceptor = function(object) {
              return baseAt(object, paths);
            };
            if (length > 1 || this.__actions__.length || !(value instanceof LazyWrapper) || !isIndex(start)) {
              return this.thru(interceptor);
            }
            value = value.slice(start, +start + (length ? 1 : 0));
            value.__actions__.push({
              func: thru,
              args: [interceptor],
              thisArg: undefined$1
            });
            return new LodashWrapper(value, this.__chain__).thru(function(array) {
              if (length && !array.length) {
                array.push(undefined$1);
              }
              return array;
            });
          });
          function wrapperChain() {
            return chain(this);
          }
          function wrapperCommit() {
            return new LodashWrapper(this.value(), this.__chain__);
          }
          function wrapperNext() {
            if (this.__values__ === undefined$1) {
              this.__values__ = toArray3(this.value());
            }
            var done = this.__index__ >= this.__values__.length, value = done ? undefined$1 : this.__values__[this.__index__++];
            return { done, value };
          }
          function wrapperToIterator() {
            return this;
          }
          function wrapperPlant(value) {
            var result22, parent2 = this;
            while (parent2 instanceof baseLodash) {
              var clone2 = wrapperClone(parent2);
              clone2.__index__ = 0;
              clone2.__values__ = undefined$1;
              if (result22) {
                previous.__wrapped__ = clone2;
              } else {
                result22 = clone2;
              }
              var previous = clone2;
              parent2 = parent2.__wrapped__;
            }
            previous.__wrapped__ = value;
            return result22;
          }
          function wrapperReverse() {
            var value = this.__wrapped__;
            if (value instanceof LazyWrapper) {
              var wrapped = value;
              if (this.__actions__.length) {
                wrapped = new LazyWrapper(this);
              }
              wrapped = wrapped.reverse();
              wrapped.__actions__.push({
                func: thru,
                args: [reverse],
                thisArg: undefined$1
              });
              return new LodashWrapper(wrapped, this.__chain__);
            }
            return this.thru(reverse);
          }
          function wrapperValue() {
            return baseWrapperValue(this.__wrapped__, this.__actions__);
          }
          var countBy = createAggregator(function(result22, value, key) {
            if (hasOwnProperty3.call(result22, key)) {
              ++result22[key];
            } else {
              baseAssignValue(result22, key, 1);
            }
          });
          function every(collection, predicate, guard) {
            var func = isArray6(collection) ? arrayEvery : baseEvery;
            if (guard && isIterateeCall(collection, predicate, guard)) {
              predicate = undefined$1;
            }
            return func(collection, getIteratee(predicate, 3));
          }
          function filter3(collection, predicate) {
            var func = isArray6(collection) ? arrayFilter : baseFilter;
            return func(collection, getIteratee(predicate, 3));
          }
          var find = createFind(findIndex);
          var findLast = createFind(findLastIndex);
          function flatMap(collection, iteratee2) {
            return baseFlatten(map3(collection, iteratee2), 1);
          }
          function flatMapDeep(collection, iteratee2) {
            return baseFlatten(map3(collection, iteratee2), INFINITY);
          }
          function flatMapDepth(collection, iteratee2, depth) {
            depth = depth === undefined$1 ? 1 : toInteger(depth);
            return baseFlatten(map3(collection, iteratee2), depth);
          }
          function forEach2(collection, iteratee2) {
            var func = isArray6(collection) ? arrayEach : baseEach;
            return func(collection, getIteratee(iteratee2, 3));
          }
          function forEachRight(collection, iteratee2) {
            var func = isArray6(collection) ? arrayEachRight : baseEachRight;
            return func(collection, getIteratee(iteratee2, 3));
          }
          var groupBy = createAggregator(function(result22, value, key) {
            if (hasOwnProperty3.call(result22, key)) {
              result22[key].push(value);
            } else {
              baseAssignValue(result22, key, [value]);
            }
          });
          function includes(collection, value, fromIndex, guard) {
            collection = isArrayLike(collection) ? collection : values(collection);
            fromIndex = fromIndex && !guard ? toInteger(fromIndex) : 0;
            var length = collection.length;
            if (fromIndex < 0) {
              fromIndex = nativeMax(length + fromIndex, 0);
            }
            return isString5(collection) ? fromIndex <= length && collection.indexOf(value, fromIndex) > -1 : !!length && baseIndexOf(collection, value, fromIndex) > -1;
          }
          var invokeMap = baseRest(function(collection, path3, args) {
            var index2 = -1, isFunc = typeof path3 == "function", result22 = isArrayLike(collection) ? Array2(collection.length) : [];
            baseEach(collection, function(value) {
              result22[++index2] = isFunc ? apply(path3, value, args) : baseInvoke(value, path3, args);
            });
            return result22;
          });
          var keyBy = createAggregator(function(result22, value, key) {
            baseAssignValue(result22, key, value);
          });
          function map3(collection, iteratee2) {
            var func = isArray6(collection) ? arrayMap : baseMap;
            return func(collection, getIteratee(iteratee2, 3));
          }
          function orderBy2(collection, iteratees, orders, guard) {
            if (collection == null) {
              return [];
            }
            if (!isArray6(iteratees)) {
              iteratees = iteratees == null ? [] : [iteratees];
            }
            orders = guard ? undefined$1 : orders;
            if (!isArray6(orders)) {
              orders = orders == null ? [] : [orders];
            }
            return baseOrderBy(collection, iteratees, orders);
          }
          var partition = createAggregator(function(result22, value, key) {
            result22[key ? 0 : 1].push(value);
          }, function() {
            return [[], []];
          });
          function reduce(collection, iteratee2, accumulator) {
            var func = isArray6(collection) ? arrayReduce : baseReduce, initAccum = arguments.length < 3;
            return func(collection, getIteratee(iteratee2, 4), accumulator, initAccum, baseEach);
          }
          function reduceRight(collection, iteratee2, accumulator) {
            var func = isArray6(collection) ? arrayReduceRight : baseReduce, initAccum = arguments.length < 3;
            return func(collection, getIteratee(iteratee2, 4), accumulator, initAccum, baseEachRight);
          }
          function reject2(collection, predicate) {
            var func = isArray6(collection) ? arrayFilter : baseFilter;
            return func(collection, negate(getIteratee(predicate, 3)));
          }
          function sample(collection) {
            var func = isArray6(collection) ? arraySample : baseSample;
            return func(collection);
          }
          function sampleSize(collection, n5, guard) {
            if (guard ? isIterateeCall(collection, n5, guard) : n5 === undefined$1) {
              n5 = 1;
            } else {
              n5 = toInteger(n5);
            }
            var func = isArray6(collection) ? arraySampleSize : baseSampleSize;
            return func(collection, n5);
          }
          function shuffle2(collection) {
            var func = isArray6(collection) ? arrayShuffle : baseShuffle;
            return func(collection);
          }
          function size(collection) {
            if (collection == null) {
              return 0;
            }
            if (isArrayLike(collection)) {
              return isString5(collection) ? stringSize(collection) : collection.length;
            }
            var tag = getTag(collection);
            if (tag == mapTag || tag == setTag) {
              return collection.size;
            }
            return baseKeys(collection).length;
          }
          function some(collection, predicate, guard) {
            var func = isArray6(collection) ? arraySome : baseSome;
            if (guard && isIterateeCall(collection, predicate, guard)) {
              predicate = undefined$1;
            }
            return func(collection, getIteratee(predicate, 3));
          }
          var sortBy = baseRest(function(collection, iteratees) {
            if (collection == null) {
              return [];
            }
            var length = iteratees.length;
            if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) {
              iteratees = [];
            } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) {
              iteratees = [iteratees[0]];
            }
            return baseOrderBy(collection, baseFlatten(iteratees, 1), []);
          });
          var now = ctxNow || function() {
            return root.Date.now();
          };
          function after(n5, func) {
            if (typeof func != "function") {
              throw new TypeError2(FUNC_ERROR_TEXT);
            }
            n5 = toInteger(n5);
            return function() {
              if (--n5 < 1) {
                return func.apply(this, arguments);
              }
            };
          }
          function ary(func, n5, guard) {
            n5 = guard ? undefined$1 : n5;
            n5 = func && n5 == null ? func.length : n5;
            return createWrap(func, WRAP_ARY_FLAG, undefined$1, undefined$1, undefined$1, undefined$1, n5);
          }
          function before(n5, func) {
            var result22;
            if (typeof func != "function") {
              throw new TypeError2(FUNC_ERROR_TEXT);
            }
            n5 = toInteger(n5);
            return function() {
              if (--n5 > 0) {
                result22 = func.apply(this, arguments);
              }
              if (n5 <= 1) {
                func = undefined$1;
              }
              return result22;
            };
          }
          var bind = baseRest(function(func, thisArg, partials) {
            var bitmask = WRAP_BIND_FLAG;
            if (partials.length) {
              var holders = replaceHolders(partials, getHolder(bind));
              bitmask |= WRAP_PARTIAL_FLAG;
            }
            return createWrap(func, bitmask, thisArg, partials, holders);
          });
          var bindKey = baseRest(function(object, key, partials) {
            var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG;
            if (partials.length) {
              var holders = replaceHolders(partials, getHolder(bindKey));
              bitmask |= WRAP_PARTIAL_FLAG;
            }
            return createWrap(key, bitmask, object, partials, holders);
          });
          function curry(func, arity, guard) {
            arity = guard ? undefined$1 : arity;
            var result22 = createWrap(func, WRAP_CURRY_FLAG, undefined$1, undefined$1, undefined$1, undefined$1, undefined$1, arity);
            result22.placeholder = curry.placeholder;
            return result22;
          }
          function curryRight(func, arity, guard) {
            arity = guard ? undefined$1 : arity;
            var result22 = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined$1, undefined$1, undefined$1, undefined$1, undefined$1, arity);
            result22.placeholder = curryRight.placeholder;
            return result22;
          }
          function debounce2(func, wait, options) {
            var lastArgs, lastThis, maxWait, result22, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true;
            if (typeof func != "function") {
              throw new TypeError2(FUNC_ERROR_TEXT);
            }
            wait = toNumber(wait) || 0;
            if (isObject7(options)) {
              leading = !!options.leading;
              maxing = "maxWait" in options;
              maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
              trailing = "trailing" in options ? !!options.trailing : trailing;
            }
            function invokeFunc(time) {
              var args = lastArgs, thisArg = lastThis;
              lastArgs = lastThis = undefined$1;
              lastInvokeTime = time;
              result22 = func.apply(thisArg, args);
              return result22;
            }
            function leadingEdge(time) {
              lastInvokeTime = time;
              timerId = setTimeout2(timerExpired, wait);
              return leading ? invokeFunc(time) : result22;
            }
            function remainingWait(time) {
              var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, timeWaiting = wait - timeSinceLastCall;
              return maxing ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting;
            }
            function shouldInvoke(time) {
              var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime;
              return lastCallTime === undefined$1 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
            }
            function timerExpired() {
              var time = now();
              if (shouldInvoke(time)) {
                return trailingEdge(time);
              }
              timerId = setTimeout2(timerExpired, remainingWait(time));
            }
            function trailingEdge(time) {
              timerId = undefined$1;
              if (trailing && lastArgs) {
                return invokeFunc(time);
              }
              lastArgs = lastThis = undefined$1;
              return result22;
            }
            function cancel() {
              if (timerId !== undefined$1) {
                clearTimeout2(timerId);
              }
              lastInvokeTime = 0;
              lastArgs = lastCallTime = lastThis = timerId = undefined$1;
            }
            function flush() {
              return timerId === undefined$1 ? result22 : trailingEdge(now());
            }
            function debounced() {
              var time = now(), isInvoking = shouldInvoke(time);
              lastArgs = arguments;
              lastThis = this;
              lastCallTime = time;
              if (isInvoking) {
                if (timerId === undefined$1) {
                  return leadingEdge(lastCallTime);
                }
                if (maxing) {
                  clearTimeout2(timerId);
                  timerId = setTimeout2(timerExpired, wait);
                  return invokeFunc(lastCallTime);
                }
              }
              if (timerId === undefined$1) {
                timerId = setTimeout2(timerExpired, wait);
              }
              return result22;
            }
            debounced.cancel = cancel;
            debounced.flush = flush;
            return debounced;
          }
          var defer = baseRest(function(func, args) {
            return baseDelay(func, 1, args);
          });
          var delay = baseRest(function(func, wait, args) {
            return baseDelay(func, toNumber(wait) || 0, args);
          });
          function flip(func) {
            return createWrap(func, WRAP_FLIP_FLAG);
          }
          function memoize2(func, resolver) {
            if (typeof func != "function" || resolver != null && typeof resolver != "function") {
              throw new TypeError2(FUNC_ERROR_TEXT);
            }
            var memoized = function() {
              var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache3 = memoized.cache;
              if (cache3.has(key)) {
                return cache3.get(key);
              }
              var result22 = func.apply(this, args);
              memoized.cache = cache3.set(key, result22) || cache3;
              return result22;
            };
            memoized.cache = new (memoize2.Cache || MapCache)();
            return memoized;
          }
          memoize2.Cache = MapCache;
          function negate(predicate) {
            if (typeof predicate != "function") {
              throw new TypeError2(FUNC_ERROR_TEXT);
            }
            return function() {
              var args = arguments;
              switch (args.length) {
                case 0:
                  return !predicate.call(this);
                case 1:
                  return !predicate.call(this, args[0]);
                case 2:
                  return !predicate.call(this, args[0], args[1]);
                case 3:
                  return !predicate.call(this, args[0], args[1], args[2]);
              }
              return !predicate.apply(this, args);
            };
          }
          function once3(func) {
            return before(2, func);
          }
          var overArgs = castRest(function(func, transforms) {
            transforms = transforms.length == 1 && isArray6(transforms[0]) ? arrayMap(transforms[0], baseUnary(getIteratee())) : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee()));
            var funcsLength = transforms.length;
            return baseRest(function(args) {
              var index2 = -1, length = nativeMin(args.length, funcsLength);
              while (++index2 < length) {
                args[index2] = transforms[index2].call(this, args[index2]);
              }
              return apply(func, this, args);
            });
          });
          var partial = baseRest(function(func, partials) {
            var holders = replaceHolders(partials, getHolder(partial));
            return createWrap(func, WRAP_PARTIAL_FLAG, undefined$1, partials, holders);
          });
          var partialRight = baseRest(function(func, partials) {
            var holders = replaceHolders(partials, getHolder(partialRight));
            return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined$1, partials, holders);
          });
          var rearg = flatRest(function(func, indexes) {
            return createWrap(func, WRAP_REARG_FLAG, undefined$1, undefined$1, undefined$1, indexes);
          });
          function rest(func, start) {
            if (typeof func != "function") {
              throw new TypeError2(FUNC_ERROR_TEXT);
            }
            start = start === undefined$1 ? start : toInteger(start);
            return baseRest(func, start);
          }
          function spread(func, start) {
            if (typeof func != "function") {
              throw new TypeError2(FUNC_ERROR_TEXT);
            }
            start = start == null ? 0 : nativeMax(toInteger(start), 0);
            return baseRest(function(args) {
              var array = args[start], otherArgs = castSlice(args, 0, start);
              if (array) {
                arrayPush(otherArgs, array);
              }
              return apply(func, this, otherArgs);
            });
          }
          function throttle(func, wait, options) {
            var leading = true, trailing = true;
            if (typeof func != "function") {
              throw new TypeError2(FUNC_ERROR_TEXT);
            }
            if (isObject7(options)) {
              leading = "leading" in options ? !!options.leading : leading;
              trailing = "trailing" in options ? !!options.trailing : trailing;
            }
            return debounce2(func, wait, {
              leading,
              maxWait: wait,
              trailing
            });
          }
          function unary(func) {
            return ary(func, 1);
          }
          function wrap(value, wrapper) {
            return partial(castFunction(wrapper), value);
          }
          function castArray() {
            if (!arguments.length) {
              return [];
            }
            var value = arguments[0];
            return isArray6(value) ? value : [value];
          }
          function clone(value) {
            return baseClone(value, CLONE_SYMBOLS_FLAG);
          }
          function cloneWith(value, customizer) {
            customizer = typeof customizer == "function" ? customizer : undefined$1;
            return baseClone(value, CLONE_SYMBOLS_FLAG, customizer);
          }
          function cloneDeep2(value) {
            return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG);
          }
          function cloneDeepWith(value, customizer) {
            customizer = typeof customizer == "function" ? customizer : undefined$1;
            return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer);
          }
          function conformsTo(object, source2) {
            return source2 == null || baseConformsTo(object, source2, keys(source2));
          }
          function eq2(value, other) {
            return value === other || value !== value && other !== other;
          }
          var gt2 = createRelationalOperation(baseGt);
          var gte2 = createRelationalOperation(function(value, other) {
            return value >= other;
          });
          var isArguments = baseIsArguments(/* @__PURE__ */ (function() {
            return arguments;
          })()) ? baseIsArguments : function(value) {
            return isObjectLike(value) && hasOwnProperty3.call(value, "callee") && !propertyIsEnumerable.call(value, "callee");
          };
          var isArray6 = Array2.isArray;
          var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer;
          function isArrayLike(value) {
            return value != null && isLength(value.length) && !isFunction3(value);
          }
          function isArrayLikeObject(value) {
            return isObjectLike(value) && isArrayLike(value);
          }
          function isBoolean5(value) {
            return value === true || value === false || isObjectLike(value) && baseGetTag(value) == boolTag;
          }
          var isBuffer3 = nativeIsBuffer || stubFalse;
          var isDate3 = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate;
          function isElement(value) {
            return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value);
          }
          function isEmpty(value) {
            if (value == null) {
              return true;
            }
            if (isArrayLike(value) && (isArray6(value) || typeof value == "string" || typeof value.splice == "function" || isBuffer3(value) || isTypedArray(value) || isArguments(value))) {
              return !value.length;
            }
            var tag = getTag(value);
            if (tag == mapTag || tag == setTag) {
              return !value.size;
            }
            if (isPrototype(value)) {
              return !baseKeys(value).length;
            }
            for (var key in value) {
              if (hasOwnProperty3.call(value, key)) {
                return false;
              }
            }
            return true;
          }
          function isEqual2(value, other) {
            return baseIsEqual(value, other);
          }
          function isEqualWith(value, other, customizer) {
            customizer = typeof customizer == "function" ? customizer : undefined$1;
            var result22 = customizer ? customizer(value, other) : undefined$1;
            return result22 === undefined$1 ? baseIsEqual(value, other, undefined$1, customizer) : !!result22;
          }
          function isError3(value) {
            if (!isObjectLike(value)) {
              return false;
            }
            var tag = baseGetTag(value);
            return tag == errorTag || tag == domExcTag || typeof value.message == "string" && typeof value.name == "string" && !isPlainObject(value);
          }
          function isFinite2(value) {
            return typeof value == "number" && nativeIsFinite(value);
          }
          function isFunction3(value) {
            if (!isObject7(value)) {
              return false;
            }
            var tag = baseGetTag(value);
            return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
          }
          function isInteger3(value) {
            return typeof value == "number" && value == toInteger(value);
          }
          function isLength(value) {
            return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER2;
          }
          function isObject7(value) {
            var type22 = typeof value;
            return value != null && (type22 == "object" || type22 == "function");
          }
          function isObjectLike(value) {
            return value != null && typeof value == "object";
          }
          var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap;
          function isMatch(object, source2) {
            return object === source2 || baseIsMatch(object, source2, getMatchData(source2));
          }
          function isMatchWith(object, source2, customizer) {
            customizer = typeof customizer == "function" ? customizer : undefined$1;
            return baseIsMatch(object, source2, getMatchData(source2), customizer);
          }
          function isNaN2(value) {
            return isNumber5(value) && value != +value;
          }
          function isNative(value) {
            if (isMaskable(value)) {
              throw new Error2(CORE_ERROR_TEXT);
            }
            return baseIsNative(value);
          }
          function isNull5(value) {
            return value === null;
          }
          function isNil(value) {
            return value == null;
          }
          function isNumber5(value) {
            return typeof value == "number" || isObjectLike(value) && baseGetTag(value) == numberTag;
          }
          function isPlainObject(value) {
            if (!isObjectLike(value) || baseGetTag(value) != objectTag) {
              return false;
            }
            var proto2 = getPrototype(value);
            if (proto2 === null) {
              return true;
            }
            var Ctor = hasOwnProperty3.call(proto2, "constructor") && proto2.constructor;
            return typeof Ctor == "function" && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString;
          }
          var isRegExp3 = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp;
          function isSafeInteger(value) {
            return isInteger3(value) && value >= -MAX_SAFE_INTEGER2 && value <= MAX_SAFE_INTEGER2;
          }
          var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;
          function isString5(value) {
            return typeof value == "string" || !isArray6(value) && isObjectLike(value) && baseGetTag(value) == stringTag;
          }
          function isSymbol3(value) {
            return typeof value == "symbol" || isObjectLike(value) && baseGetTag(value) == symbolTag;
          }
          var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
          function isUndefined3(value) {
            return value === undefined$1;
          }
          function isWeakMap(value) {
            return isObjectLike(value) && getTag(value) == weakMapTag;
          }
          function isWeakSet(value) {
            return isObjectLike(value) && baseGetTag(value) == weakSetTag;
          }
          var lt2 = createRelationalOperation(baseLt);
          var lte2 = createRelationalOperation(function(value, other) {
            return value <= other;
          });
          function toArray3(value) {
            if (!value) {
              return [];
            }
            if (isArrayLike(value)) {
              return isString5(value) ? stringToArray(value) : copyArray(value);
            }
            if (symIterator && value[symIterator]) {
              return iteratorToArray(value[symIterator]());
            }
            var tag = getTag(value), func = tag == mapTag ? mapToArray : tag == setTag ? setToArray : values;
            return func(value);
          }
          function toFinite(value) {
            if (!value) {
              return value === 0 ? value : 0;
            }
            value = toNumber(value);
            if (value === INFINITY || value === -INFINITY) {
              var sign = value < 0 ? -1 : 1;
              return sign * MAX_INTEGER;
            }
            return value === value ? value : 0;
          }
          function toInteger(value) {
            var result22 = toFinite(value), remainder = result22 % 1;
            return result22 === result22 ? remainder ? result22 - remainder : result22 : 0;
          }
          function toLength(value) {
            return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0;
          }
          function toNumber(value) {
            if (typeof value == "number") {
              return value;
            }
            if (isSymbol3(value)) {
              return NAN;
            }
            if (isObject7(value)) {
              var other = typeof value.valueOf == "function" ? value.valueOf() : value;
              value = isObject7(other) ? other + "" : other;
            }
            if (typeof value != "string") {
              return value === 0 ? value : +value;
            }
            value = value.replace(reTrim, "");
            var isBinary3 = reIsBinary.test(value);
            return isBinary3 || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary3 ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
          }
          function toPlainObject(value) {
            return copyObject(value, keysIn(value));
          }
          function toSafeInteger(value) {
            return value ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER2, MAX_SAFE_INTEGER2) : value === 0 ? value : 0;
          }
          function toString8(value) {
            return value == null ? "" : baseToString(value);
          }
          var assign3 = createAssigner(function(object, source2) {
            if (isPrototype(source2) || isArrayLike(source2)) {
              copyObject(source2, keys(source2), object);
              return;
            }
            for (var key in source2) {
              if (hasOwnProperty3.call(source2, key)) {
                assignValue(object, key, source2[key]);
              }
            }
          });
          var assignIn = createAssigner(function(object, source2) {
            copyObject(source2, keysIn(source2), object);
          });
          var assignInWith = createAssigner(function(object, source2, srcIndex, customizer) {
            copyObject(source2, keysIn(source2), object, customizer);
          });
          var assignWith = createAssigner(function(object, source2, srcIndex, customizer) {
            copyObject(source2, keys(source2), object, customizer);
          });
          var at3 = flatRest(baseAt);
          function create2(prototype, properties) {
            var result22 = baseCreate(prototype);
            return properties == null ? result22 : baseAssign(result22, properties);
          }
          var defaults = baseRest(function(object, sources) {
            object = Object2(object);
            var index2 = -1;
            var length = sources.length;
            var guard = length > 2 ? sources[2] : undefined$1;
            if (guard && isIterateeCall(sources[0], sources[1], guard)) {
              length = 1;
            }
            while (++index2 < length) {
              var source2 = sources[index2];
              var props = keysIn(source2);
              var propsIndex = -1;
              var propsLength = props.length;
              while (++propsIndex < propsLength) {
                var key = props[propsIndex];
                var value = object[key];
                if (value === undefined$1 || eq2(value, objectProto[key]) && !hasOwnProperty3.call(object, key)) {
                  object[key] = source2[key];
                }
              }
            }
            return object;
          });
          var defaultsDeep = baseRest(function(args) {
            args.push(undefined$1, customDefaultsMerge);
            return apply(mergeWith2, undefined$1, args);
          });
          function findKey(object, predicate) {
            return baseFindKey(object, getIteratee(predicate, 3), baseForOwn);
          }
          function findLastKey(object, predicate) {
            return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight);
          }
          function forIn(object, iteratee2) {
            return object == null ? object : baseFor(object, getIteratee(iteratee2, 3), keysIn);
          }
          function forInRight(object, iteratee2) {
            return object == null ? object : baseForRight(object, getIteratee(iteratee2, 3), keysIn);
          }
          function forOwn(object, iteratee2) {
            return object && baseForOwn(object, getIteratee(iteratee2, 3));
          }
          function forOwnRight(object, iteratee2) {
            return object && baseForOwnRight(object, getIteratee(iteratee2, 3));
          }
          function functions(object) {
            return object == null ? [] : baseFunctions(object, keys(object));
          }
          function functionsIn(object) {
            return object == null ? [] : baseFunctions(object, keysIn(object));
          }
          function get2(object, path3, defaultValue) {
            var result22 = object == null ? undefined$1 : baseGet(object, path3);
            return result22 === undefined$1 ? defaultValue : result22;
          }
          function has3(object, path3) {
            return object != null && hasPath(object, path3, baseHas);
          }
          function hasIn(object, path3) {
            return object != null && hasPath(object, path3, baseHasIn);
          }
          var invert = createInverter(function(result22, value, key) {
            if (value != null && typeof value.toString != "function") {
              value = nativeObjectToString.call(value);
            }
            result22[value] = key;
          }, constant(identity));
          var invertBy = createInverter(function(result22, value, key) {
            if (value != null && typeof value.toString != "function") {
              value = nativeObjectToString.call(value);
            }
            if (hasOwnProperty3.call(result22, value)) {
              result22[value].push(key);
            } else {
              result22[value] = [key];
            }
          }, getIteratee);
          var invoke = baseRest(baseInvoke);
          function keys(object) {
            return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
          }
          function keysIn(object) {
            return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);
          }
          function mapKeys(object, iteratee2) {
            var result22 = {};
            iteratee2 = getIteratee(iteratee2, 3);
            baseForOwn(object, function(value, key, object2) {
              baseAssignValue(result22, iteratee2(value, key, object2), value);
            });
            return result22;
          }
          function mapValues(object, iteratee2) {
            var result22 = {};
            iteratee2 = getIteratee(iteratee2, 3);
            baseForOwn(object, function(value, key, object2) {
              baseAssignValue(result22, key, iteratee2(value, key, object2));
            });
            return result22;
          }
          var merge3 = createAssigner(function(object, source2, srcIndex) {
            baseMerge(object, source2, srcIndex);
          });
          var mergeWith2 = createAssigner(function(object, source2, srcIndex, customizer) {
            baseMerge(object, source2, srcIndex, customizer);
          });
          var omit = flatRest(function(object, paths) {
            var result22 = {};
            if (object == null) {
              return result22;
            }
            var isDeep = false;
            paths = arrayMap(paths, function(path3) {
              path3 = castPath(path3, object);
              isDeep || (isDeep = path3.length > 1);
              return path3;
            });
            copyObject(object, getAllKeysIn(object), result22);
            if (isDeep) {
              result22 = baseClone(result22, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone);
            }
            var length = paths.length;
            while (length--) {
              baseUnset(result22, paths[length]);
            }
            return result22;
          });
          function omitBy(object, predicate) {
            return pickBy(object, negate(getIteratee(predicate)));
          }
          var pick = flatRest(function(object, paths) {
            return object == null ? {} : basePick(object, paths);
          });
          function pickBy(object, predicate) {
            if (object == null) {
              return {};
            }
            var props = arrayMap(getAllKeysIn(object), function(prop) {
              return [prop];
            });
            predicate = getIteratee(predicate);
            return basePickBy(object, props, function(value, path3) {
              return predicate(value, path3[0]);
            });
          }
          function result2(object, path3, defaultValue) {
            path3 = castPath(path3, object);
            var index2 = -1, length = path3.length;
            if (!length) {
              length = 1;
              object = undefined$1;
            }
            while (++index2 < length) {
              var value = object == null ? undefined$1 : object[toKey(path3[index2])];
              if (value === undefined$1) {
                index2 = length;
                value = defaultValue;
              }
              object = isFunction3(value) ? value.call(object) : value;
            }
            return object;
          }
          function set3(object, path3, value) {
            return object == null ? object : baseSet(object, path3, value);
          }
          function setWith(object, path3, value, customizer) {
            customizer = typeof customizer == "function" ? customizer : undefined$1;
            return object == null ? object : baseSet(object, path3, value, customizer);
          }
          var toPairs = createToPairs(keys);
          var toPairsIn = createToPairs(keysIn);
          function transform(object, iteratee2, accumulator) {
            var isArr = isArray6(object), isArrLike = isArr || isBuffer3(object) || isTypedArray(object);
            iteratee2 = getIteratee(iteratee2, 4);
            if (accumulator == null) {
              var Ctor = object && object.constructor;
              if (isArrLike) {
                accumulator = isArr ? new Ctor() : [];
              } else if (isObject7(object)) {
                accumulator = isFunction3(Ctor) ? baseCreate(getPrototype(object)) : {};
              } else {
                accumulator = {};
              }
            }
            (isArrLike ? arrayEach : baseForOwn)(object, function(value, index2, object2) {
              return iteratee2(accumulator, value, index2, object2);
            });
            return accumulator;
          }
          function unset(object, path3) {
            return object == null ? true : baseUnset(object, path3);
          }
          function update(object, path3, updater) {
            return object == null ? object : baseUpdate(object, path3, castFunction(updater));
          }
          function updateWith(object, path3, updater, customizer) {
            customizer = typeof customizer == "function" ? customizer : undefined$1;
            return object == null ? object : baseUpdate(object, path3, castFunction(updater), customizer);
          }
          function values(object) {
            return object == null ? [] : baseValues(object, keys(object));
          }
          function valuesIn(object) {
            return object == null ? [] : baseValues(object, keysIn(object));
          }
          function clamp(number2, lower, upper) {
            if (upper === undefined$1) {
              upper = lower;
              lower = undefined$1;
            }
            if (upper !== undefined$1) {
              upper = toNumber(upper);
              upper = upper === upper ? upper : 0;
            }
            if (lower !== undefined$1) {
              lower = toNumber(lower);
              lower = lower === lower ? lower : 0;
            }
            return baseClamp(toNumber(number2), lower, upper);
          }
          function inRange(number2, start, end) {
            start = toFinite(start);
            if (end === undefined$1) {
              end = start;
              start = 0;
            } else {
              end = toFinite(end);
            }
            number2 = toNumber(number2);
            return baseInRange(number2, start, end);
          }
          function random2(lower, upper, floating) {
            if (floating && typeof floating != "boolean" && isIterateeCall(lower, upper, floating)) {
              upper = floating = undefined$1;
            }
            if (floating === undefined$1) {
              if (typeof upper == "boolean") {
                floating = upper;
                upper = undefined$1;
              } else if (typeof lower == "boolean") {
                floating = lower;
                lower = undefined$1;
              }
            }
            if (lower === undefined$1 && upper === undefined$1) {
              lower = 0;
              upper = 1;
            } else {
              lower = toFinite(lower);
              if (upper === undefined$1) {
                upper = lower;
                lower = 0;
              } else {
                upper = toFinite(upper);
              }
            }
            if (lower > upper) {
              var temp = lower;
              lower = upper;
              upper = temp;
            }
            if (floating || lower % 1 || upper % 1) {
              var rand = nativeRandom();
              return nativeMin(lower + rand * (upper - lower + freeParseFloat("1e-" + ((rand + "").length - 1))), upper);
            }
            return baseRandom(lower, upper);
          }
          var camelCase = createCompounder(function(result22, word, index2) {
            word = word.toLowerCase();
            return result22 + (index2 ? capitalize2(word) : word);
          });
          function capitalize2(string2) {
            return upperFirst(toString8(string2).toLowerCase());
          }
          function deburr(string2) {
            string2 = toString8(string2);
            return string2 && string2.replace(reLatin, deburrLetter).replace(reComboMark, "");
          }
          function endsWith(string2, target, position) {
            string2 = toString8(string2);
            target = baseToString(target);
            var length = string2.length;
            position = position === undefined$1 ? length : baseClamp(toInteger(position), 0, length);
            var end = position;
            position -= target.length;
            return position >= 0 && string2.slice(position, end) == target;
          }
          function escape2(string2) {
            string2 = toString8(string2);
            return string2 && reHasUnescapedHtml.test(string2) ? string2.replace(reUnescapedHtml, escapeHtmlChar) : string2;
          }
          function escapeRegExp3(string2) {
            string2 = toString8(string2);
            return string2 && reHasRegExpChar.test(string2) ? string2.replace(reRegExpChar, "\\$&") : string2;
          }
          var kebabCase = createCompounder(function(result22, word, index2) {
            return result22 + (index2 ? "-" : "") + word.toLowerCase();
          });
          var lowerCase = createCompounder(function(result22, word, index2) {
            return result22 + (index2 ? " " : "") + word.toLowerCase();
          });
          var lowerFirst = createCaseFirst("toLowerCase");
          function pad(string2, length, chars) {
            string2 = toString8(string2);
            length = toInteger(length);
            var strLength2 = length ? stringSize(string2) : 0;
            if (!length || strLength2 >= length) {
              return string2;
            }
            var mid = (length - strLength2) / 2;
            return createPadding(nativeFloor(mid), chars) + string2 + createPadding(nativeCeil(mid), chars);
          }
          function padEnd(string2, length, chars) {
            string2 = toString8(string2);
            length = toInteger(length);
            var strLength2 = length ? stringSize(string2) : 0;
            return length && strLength2 < length ? string2 + createPadding(length - strLength2, chars) : string2;
          }
          function padStart3(string2, length, chars) {
            string2 = toString8(string2);
            length = toInteger(length);
            var strLength2 = length ? stringSize(string2) : 0;
            return length && strLength2 < length ? createPadding(length - strLength2, chars) + string2 : string2;
          }
          function parseInt2(string2, radix, guard) {
            if (guard || radix == null) {
              radix = 0;
            } else if (radix) {
              radix = +radix;
            }
            return nativeParseInt(toString8(string2).replace(reTrimStart, ""), radix || 0);
          }
          function repeat3(string2, n5, guard) {
            if (guard ? isIterateeCall(string2, n5, guard) : n5 === undefined$1) {
              n5 = 1;
            } else {
              n5 = toInteger(n5);
            }
            return baseRepeat(toString8(string2), n5);
          }
          function replace() {
            var args = arguments, string2 = toString8(args[0]);
            return args.length < 3 ? string2 : string2.replace(args[1], args[2]);
          }
          var snakeCase = createCompounder(function(result22, word, index2) {
            return result22 + (index2 ? "_" : "") + word.toLowerCase();
          });
          function split2(string2, separator, limit) {
            if (limit && typeof limit != "number" && isIterateeCall(string2, separator, limit)) {
              separator = limit = undefined$1;
            }
            limit = limit === undefined$1 ? MAX_ARRAY_LENGTH : limit >>> 0;
            if (!limit) {
              return [];
            }
            string2 = toString8(string2);
            if (string2 && (typeof separator == "string" || separator != null && !isRegExp3(separator))) {
              separator = baseToString(separator);
              if (!separator && hasUnicode(string2)) {
                return castSlice(stringToArray(string2), 0, limit);
              }
            }
            return string2.split(separator, limit);
          }
          var startCase = createCompounder(function(result22, word, index2) {
            return result22 + (index2 ? " " : "") + upperFirst(word);
          });
          function startsWith(string2, target, position) {
            string2 = toString8(string2);
            position = position == null ? 0 : baseClamp(toInteger(position), 0, string2.length);
            target = baseToString(target);
            return string2.slice(position, position + target.length) == target;
          }
          function template2(string2, options, guard) {
            var settings = lodash2.templateSettings;
            if (guard && isIterateeCall(string2, options, guard)) {
              options = undefined$1;
            }
            string2 = toString8(string2);
            options = assignInWith({}, options, settings, customDefaultsAssignIn);
            var imports2 = assignInWith({}, options.imports, settings.imports, customDefaultsAssignIn), importsKeys = keys(imports2), importsValues = baseValues(imports2, importsKeys);
            var isEscaping, isEvaluating, index2 = 0, interpolate = options.interpolate || reNoMatch, source2 = "__p += '";
            var reDelimiters = RegExp2((options.escape || reNoMatch).source + "|" + interpolate.source + "|" + (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + "|" + (options.evaluate || reNoMatch).source + "|$", "g");
            var sourceURL = "//# sourceURL=" + (hasOwnProperty3.call(options, "sourceURL") ? (options.sourceURL + "").replace(/\s/g, " ") : "lodash.templateSources[" + ++templateCounter + "]") + "\n";
            string2.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset3) {
              interpolateValue || (interpolateValue = esTemplateValue);
              source2 += string2.slice(index2, offset3).replace(reUnescapedString, escapeStringChar);
              if (escapeValue) {
                isEscaping = true;
                source2 += "' +\n__e(" + escapeValue + ") +\n'";
              }
              if (evaluateValue) {
                isEvaluating = true;
                source2 += "';\n" + evaluateValue + ";\n__p += '";
              }
              if (interpolateValue) {
                source2 += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
              }
              index2 = offset3 + match.length;
              return match;
            });
            source2 += "';\n";
            var variable = hasOwnProperty3.call(options, "variable") && options.variable;
            if (!variable) {
              source2 = "with (obj) {\n" + source2 + "\n}\n";
            }
            source2 = (isEvaluating ? source2.replace(reEmptyStringLeading, "") : source2).replace(reEmptyStringMiddle, "$1").replace(reEmptyStringTrailing, "$1;");
            source2 = "function(" + (variable || "obj") + ") {\n" + (variable ? "" : "obj || (obj = {});\n") + "var __t, __p = ''" + (isEscaping ? ", __e = _.escape" : "") + (isEvaluating ? ", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n" : ";\n") + source2 + "return __p\n}";
            var result22 = attempt(function() {
              return Function2(importsKeys, sourceURL + "return " + source2).apply(undefined$1, importsValues);
            });
            result22.source = source2;
            if (isError3(result22)) {
              throw result22;
            }
            return result22;
          }
          function toLower(value) {
            return toString8(value).toLowerCase();
          }
          function toUpper(value) {
            return toString8(value).toUpperCase();
          }
          function trim(string2, chars, guard) {
            string2 = toString8(string2);
            if (string2 && (guard || chars === undefined$1)) {
              return string2.replace(reTrim, "");
            }
            if (!string2 || !(chars = baseToString(chars))) {
              return string2;
            }
            var strSymbols = stringToArray(string2), chrSymbols = stringToArray(chars), start = charsStartIndex(strSymbols, chrSymbols), end = charsEndIndex(strSymbols, chrSymbols) + 1;
            return castSlice(strSymbols, start, end).join("");
          }
          function trimEnd(string2, chars, guard) {
            string2 = toString8(string2);
            if (string2 && (guard || chars === undefined$1)) {
              return string2.replace(reTrimEnd, "");
            }
            if (!string2 || !(chars = baseToString(chars))) {
              return string2;
            }
            var strSymbols = stringToArray(string2), end = charsEndIndex(strSymbols, stringToArray(chars)) + 1;
            return castSlice(strSymbols, 0, end).join("");
          }
          function trimStart(string2, chars, guard) {
            string2 = toString8(string2);
            if (string2 && (guard || chars === undefined$1)) {
              return string2.replace(reTrimStart, "");
            }
            if (!string2 || !(chars = baseToString(chars))) {
              return string2;
            }
            var strSymbols = stringToArray(string2), start = charsStartIndex(strSymbols, stringToArray(chars));
            return castSlice(strSymbols, start).join("");
          }
          function truncate(string2, options) {
            var length = DEFAULT_TRUNC_LENGTH, omission = DEFAULT_TRUNC_OMISSION;
            if (isObject7(options)) {
              var separator = "separator" in options ? options.separator : separator;
              length = "length" in options ? toInteger(options.length) : length;
              omission = "omission" in options ? baseToString(options.omission) : omission;
            }
            string2 = toString8(string2);
            var strLength2 = string2.length;
            if (hasUnicode(string2)) {
              var strSymbols = stringToArray(string2);
              strLength2 = strSymbols.length;
            }
            if (length >= strLength2) {
              return string2;
            }
            var end = length - stringSize(omission);
            if (end < 1) {
              return omission;
            }
            var result22 = strSymbols ? castSlice(strSymbols, 0, end).join("") : string2.slice(0, end);
            if (separator === undefined$1) {
              return result22 + omission;
            }
            if (strSymbols) {
              end += result22.length - end;
            }
            if (isRegExp3(separator)) {
              if (string2.slice(end).search(separator)) {
                var match, substring = result22;
                if (!separator.global) {
                  separator = RegExp2(separator.source, toString8(reFlags.exec(separator)) + "g");
                }
                separator.lastIndex = 0;
                while (match = separator.exec(substring)) {
                  var newEnd = match.index;
                }
                result22 = result22.slice(0, newEnd === undefined$1 ? end : newEnd);
              }
            } else if (string2.indexOf(baseToString(separator), end) != end) {
              var index2 = result22.lastIndexOf(separator);
              if (index2 > -1) {
                result22 = result22.slice(0, index2);
              }
            }
            return result22 + omission;
          }
          function unescape2(string2) {
            string2 = toString8(string2);
            return string2 && reHasEscapedHtml.test(string2) ? string2.replace(reEscapedHtml, unescapeHtmlChar) : string2;
          }
          var upperCase = createCompounder(function(result22, word, index2) {
            return result22 + (index2 ? " " : "") + word.toUpperCase();
          });
          var upperFirst = createCaseFirst("toUpperCase");
          function words(string2, pattern, guard) {
            string2 = toString8(string2);
            pattern = guard ? undefined$1 : pattern;
            if (pattern === undefined$1) {
              return hasUnicodeWord(string2) ? unicodeWords(string2) : asciiWords(string2);
            }
            return string2.match(pattern) || [];
          }
          var attempt = baseRest(function(func, args) {
            try {
              return apply(func, undefined$1, args);
            } catch (e5) {
              return isError3(e5) ? e5 : new Error2(e5);
            }
          });
          var bindAll = flatRest(function(object, methodNames2) {
            arrayEach(methodNames2, function(key) {
              key = toKey(key);
              baseAssignValue(object, key, bind(object[key], object));
            });
            return object;
          });
          function cond(pairs3) {
            var length = pairs3 == null ? 0 : pairs3.length, toIteratee = getIteratee();
            pairs3 = !length ? [] : arrayMap(pairs3, function(pair) {
              if (typeof pair[1] != "function") {
                throw new TypeError2(FUNC_ERROR_TEXT);
              }
              return [toIteratee(pair[0]), pair[1]];
            });
            return baseRest(function(args) {
              var index2 = -1;
              while (++index2 < length) {
                var pair = pairs3[index2];
                if (apply(pair[0], this, args)) {
                  return apply(pair[1], this, args);
                }
              }
            });
          }
          function conforms(source2) {
            return baseConforms(baseClone(source2, CLONE_DEEP_FLAG));
          }
          function constant(value) {
            return function() {
              return value;
            };
          }
          function defaultTo(value, defaultValue) {
            return value == null || value !== value ? defaultValue : value;
          }
          var flow = createFlow();
          var flowRight = createFlow(true);
          function identity(value) {
            return value;
          }
          function iteratee(func) {
            return baseIteratee(typeof func == "function" ? func : baseClone(func, CLONE_DEEP_FLAG));
          }
          function matches(source2) {
            return baseMatches(baseClone(source2, CLONE_DEEP_FLAG));
          }
          function matchesProperty(path3, srcValue) {
            return baseMatchesProperty(path3, baseClone(srcValue, CLONE_DEEP_FLAG));
          }
          var method = baseRest(function(path3, args) {
            return function(object) {
              return baseInvoke(object, path3, args);
            };
          });
          var methodOf = baseRest(function(object, args) {
            return function(path3) {
              return baseInvoke(object, path3, args);
            };
          });
          function mixin(object, source2, options) {
            var props = keys(source2), methodNames2 = baseFunctions(source2, props);
            if (options == null && !(isObject7(source2) && (methodNames2.length || !props.length))) {
              options = source2;
              source2 = object;
              object = this;
              methodNames2 = baseFunctions(source2, keys(source2));
            }
            var chain2 = !(isObject7(options) && "chain" in options) || !!options.chain, isFunc = isFunction3(object);
            arrayEach(methodNames2, function(methodName) {
              var func = source2[methodName];
              object[methodName] = func;
              if (isFunc) {
                object.prototype[methodName] = function() {
                  var chainAll = this.__chain__;
                  if (chain2 || chainAll) {
                    var result22 = object(this.__wrapped__), actions = result22.__actions__ = copyArray(this.__actions__);
                    actions.push({ func, args: arguments, thisArg: object });
                    result22.__chain__ = chainAll;
                    return result22;
                  }
                  return func.apply(object, arrayPush([this.value()], arguments));
                };
              }
            });
            return object;
          }
          function noConflict() {
            if (root._ === this) {
              root._ = oldDash;
            }
            return this;
          }
          function noop2() {
          }
          function nthArg(n5) {
            n5 = toInteger(n5);
            return baseRest(function(args) {
              return baseNth(args, n5);
            });
          }
          var over = createOver(arrayMap);
          var overEvery = createOver(arrayEvery);
          var overSome = createOver(arraySome);
          function property(path3) {
            return isKey(path3) ? baseProperty(toKey(path3)) : basePropertyDeep(path3);
          }
          function propertyOf(object) {
            return function(path3) {
              return object == null ? undefined$1 : baseGet(object, path3);
            };
          }
          var range = createRange();
          var rangeRight = createRange(true);
          function stubArray() {
            return [];
          }
          function stubFalse() {
            return false;
          }
          function stubObject() {
            return {};
          }
          function stubString() {
            return "";
          }
          function stubTrue() {
            return true;
          }
          function times(n5, iteratee2) {
            n5 = toInteger(n5);
            if (n5 < 1 || n5 > MAX_SAFE_INTEGER2) {
              return [];
            }
            var index2 = MAX_ARRAY_LENGTH, length = nativeMin(n5, MAX_ARRAY_LENGTH);
            iteratee2 = getIteratee(iteratee2);
            n5 -= MAX_ARRAY_LENGTH;
            var result22 = baseTimes(length, iteratee2);
            while (++index2 < n5) {
              iteratee2(index2);
            }
            return result22;
          }
          function toPath(value) {
            if (isArray6(value)) {
              return arrayMap(value, toKey);
            }
            return isSymbol3(value) ? [value] : copyArray(stringToPath(toString8(value)));
          }
          function uniqueId(prefix) {
            var id = ++idCounter;
            return toString8(prefix) + id;
          }
          var add = createMathOperation(function(augend, addend) {
            return augend + addend;
          }, 0);
          var ceil = createRound("ceil");
          var divide = createMathOperation(function(dividend, divisor) {
            return dividend / divisor;
          }, 1);
          var floor = createRound("floor");
          function max(array) {
            return array && array.length ? baseExtremum(array, identity, baseGt) : undefined$1;
          }
          function maxBy(array, iteratee2) {
            return array && array.length ? baseExtremum(array, getIteratee(iteratee2, 2), baseGt) : undefined$1;
          }
          function mean(array) {
            return baseMean(array, identity);
          }
          function meanBy(array, iteratee2) {
            return baseMean(array, getIteratee(iteratee2, 2));
          }
          function min2(array) {
            return array && array.length ? baseExtremum(array, identity, baseLt) : undefined$1;
          }
          function minBy(array, iteratee2) {
            return array && array.length ? baseExtremum(array, getIteratee(iteratee2, 2), baseLt) : undefined$1;
          }
          var multiply = createMathOperation(function(multiplier, multiplicand) {
            return multiplier * multiplicand;
          }, 1);
          var round = createRound("round");
          var subtract = createMathOperation(function(minuend, subtrahend) {
            return minuend - subtrahend;
          }, 0);
          function sum(array) {
            return array && array.length ? baseSum(array, identity) : 0;
          }
          function sumBy(array, iteratee2) {
            return array && array.length ? baseSum(array, getIteratee(iteratee2, 2)) : 0;
          }
          lodash2.after = after;
          lodash2.ary = ary;
          lodash2.assign = assign3;
          lodash2.assignIn = assignIn;
          lodash2.assignInWith = assignInWith;
          lodash2.assignWith = assignWith;
          lodash2.at = at3;
          lodash2.before = before;
          lodash2.bind = bind;
          lodash2.bindAll = bindAll;
          lodash2.bindKey = bindKey;
          lodash2.castArray = castArray;
          lodash2.chain = chain;
          lodash2.chunk = chunk;
          lodash2.compact = compact;
          lodash2.concat = concat3;
          lodash2.cond = cond;
          lodash2.conforms = conforms;
          lodash2.constant = constant;
          lodash2.countBy = countBy;
          lodash2.create = create2;
          lodash2.curry = curry;
          lodash2.curryRight = curryRight;
          lodash2.debounce = debounce2;
          lodash2.defaults = defaults;
          lodash2.defaultsDeep = defaultsDeep;
          lodash2.defer = defer;
          lodash2.delay = delay;
          lodash2.difference = difference2;
          lodash2.differenceBy = differenceBy;
          lodash2.differenceWith = differenceWith;
          lodash2.drop = drop;
          lodash2.dropRight = dropRight;
          lodash2.dropRightWhile = dropRightWhile;
          lodash2.dropWhile = dropWhile;
          lodash2.fill = fill;
          lodash2.filter = filter3;
          lodash2.flatMap = flatMap;
          lodash2.flatMapDeep = flatMapDeep;
          lodash2.flatMapDepth = flatMapDepth;
          lodash2.flatten = flatten;
          lodash2.flattenDeep = flattenDeep;
          lodash2.flattenDepth = flattenDepth;
          lodash2.flip = flip;
          lodash2.flow = flow;
          lodash2.flowRight = flowRight;
          lodash2.fromPairs = fromPairs;
          lodash2.functions = functions;
          lodash2.functionsIn = functionsIn;
          lodash2.groupBy = groupBy;
          lodash2.initial = initial;
          lodash2.intersection = intersection;
          lodash2.intersectionBy = intersectionBy;
          lodash2.intersectionWith = intersectionWith;
          lodash2.invert = invert;
          lodash2.invertBy = invertBy;
          lodash2.invokeMap = invokeMap;
          lodash2.iteratee = iteratee;
          lodash2.keyBy = keyBy;
          lodash2.keys = keys;
          lodash2.keysIn = keysIn;
          lodash2.map = map3;
          lodash2.mapKeys = mapKeys;
          lodash2.mapValues = mapValues;
          lodash2.matches = matches;
          lodash2.matchesProperty = matchesProperty;
          lodash2.memoize = memoize2;
          lodash2.merge = merge3;
          lodash2.mergeWith = mergeWith2;
          lodash2.method = method;
          lodash2.methodOf = methodOf;
          lodash2.mixin = mixin;
          lodash2.negate = negate;
          lodash2.nthArg = nthArg;
          lodash2.omit = omit;
          lodash2.omitBy = omitBy;
          lodash2.once = once3;
          lodash2.orderBy = orderBy2;
          lodash2.over = over;
          lodash2.overArgs = overArgs;
          lodash2.overEvery = overEvery;
          lodash2.overSome = overSome;
          lodash2.partial = partial;
          lodash2.partialRight = partialRight;
          lodash2.partition = partition;
          lodash2.pick = pick;
          lodash2.pickBy = pickBy;
          lodash2.property = property;
          lodash2.propertyOf = propertyOf;
          lodash2.pull = pull;
          lodash2.pullAll = pullAll;
          lodash2.pullAllBy = pullAllBy;
          lodash2.pullAllWith = pullAllWith;
          lodash2.pullAt = pullAt;
          lodash2.range = range;
          lodash2.rangeRight = rangeRight;
          lodash2.rearg = rearg;
          lodash2.reject = reject2;
          lodash2.remove = remove;
          lodash2.rest = rest;
          lodash2.reverse = reverse;
          lodash2.sampleSize = sampleSize;
          lodash2.set = set3;
          lodash2.setWith = setWith;
          lodash2.shuffle = shuffle2;
          lodash2.slice = slice2;
          lodash2.sortBy = sortBy;
          lodash2.sortedUniq = sortedUniq;
          lodash2.sortedUniqBy = sortedUniqBy;
          lodash2.split = split2;
          lodash2.spread = spread;
          lodash2.tail = tail;
          lodash2.take = take;
          lodash2.takeRight = takeRight;
          lodash2.takeRightWhile = takeRightWhile;
          lodash2.takeWhile = takeWhile;
          lodash2.tap = tap;
          lodash2.throttle = throttle;
          lodash2.thru = thru;
          lodash2.toArray = toArray3;
          lodash2.toPairs = toPairs;
          lodash2.toPairsIn = toPairsIn;
          lodash2.toPath = toPath;
          lodash2.toPlainObject = toPlainObject;
          lodash2.transform = transform;
          lodash2.unary = unary;
          lodash2.union = union;
          lodash2.unionBy = unionBy;
          lodash2.unionWith = unionWith;
          lodash2.uniq = uniq2;
          lodash2.uniqBy = uniqBy2;
          lodash2.uniqWith = uniqWith;
          lodash2.unset = unset;
          lodash2.unzip = unzip2;
          lodash2.unzipWith = unzipWith;
          lodash2.update = update;
          lodash2.updateWith = updateWith;
          lodash2.values = values;
          lodash2.valuesIn = valuesIn;
          lodash2.without = without;
          lodash2.words = words;
          lodash2.wrap = wrap;
          lodash2.xor = xor;
          lodash2.xorBy = xorBy;
          lodash2.xorWith = xorWith;
          lodash2.zip = zip2;
          lodash2.zipObject = zipObject;
          lodash2.zipObjectDeep = zipObjectDeep;
          lodash2.zipWith = zipWith;
          lodash2.entries = toPairs;
          lodash2.entriesIn = toPairsIn;
          lodash2.extend = assignIn;
          lodash2.extendWith = assignInWith;
          mixin(lodash2, lodash2);
          lodash2.add = add;
          lodash2.attempt = attempt;
          lodash2.camelCase = camelCase;
          lodash2.capitalize = capitalize2;
          lodash2.ceil = ceil;
          lodash2.clamp = clamp;
          lodash2.clone = clone;
          lodash2.cloneDeep = cloneDeep2;
          lodash2.cloneDeepWith = cloneDeepWith;
          lodash2.cloneWith = cloneWith;
          lodash2.conformsTo = conformsTo;
          lodash2.deburr = deburr;
          lodash2.defaultTo = defaultTo;
          lodash2.divide = divide;
          lodash2.endsWith = endsWith;
          lodash2.eq = eq2;
          lodash2.escape = escape2;
          lodash2.escapeRegExp = escapeRegExp3;
          lodash2.every = every;
          lodash2.find = find;
          lodash2.findIndex = findIndex;
          lodash2.findKey = findKey;
          lodash2.findLast = findLast;
          lodash2.findLastIndex = findLastIndex;
          lodash2.findLastKey = findLastKey;
          lodash2.floor = floor;
          lodash2.forEach = forEach2;
          lodash2.forEachRight = forEachRight;
          lodash2.forIn = forIn;
          lodash2.forInRight = forInRight;
          lodash2.forOwn = forOwn;
          lodash2.forOwnRight = forOwnRight;
          lodash2.get = get2;
          lodash2.gt = gt2;
          lodash2.gte = gte2;
          lodash2.has = has3;
          lodash2.hasIn = hasIn;
          lodash2.head = head;
          lodash2.identity = identity;
          lodash2.includes = includes;
          lodash2.indexOf = indexOf2;
          lodash2.inRange = inRange;
          lodash2.invoke = invoke;
          lodash2.isArguments = isArguments;
          lodash2.isArray = isArray6;
          lodash2.isArrayBuffer = isArrayBuffer;
          lodash2.isArrayLike = isArrayLike;
          lodash2.isArrayLikeObject = isArrayLikeObject;
          lodash2.isBoolean = isBoolean5;
          lodash2.isBuffer = isBuffer3;
          lodash2.isDate = isDate3;
          lodash2.isElement = isElement;
          lodash2.isEmpty = isEmpty;
          lodash2.isEqual = isEqual2;
          lodash2.isEqualWith = isEqualWith;
          lodash2.isError = isError3;
          lodash2.isFinite = isFinite2;
          lodash2.isFunction = isFunction3;
          lodash2.isInteger = isInteger3;
          lodash2.isLength = isLength;
          lodash2.isMap = isMap;
          lodash2.isMatch = isMatch;
          lodash2.isMatchWith = isMatchWith;
          lodash2.isNaN = isNaN2;
          lodash2.isNative = isNative;
          lodash2.isNil = isNil;
          lodash2.isNull = isNull5;
          lodash2.isNumber = isNumber5;
          lodash2.isObject = isObject7;
          lodash2.isObjectLike = isObjectLike;
          lodash2.isPlainObject = isPlainObject;
          lodash2.isRegExp = isRegExp3;
          lodash2.isSafeInteger = isSafeInteger;
          lodash2.isSet = isSet;
          lodash2.isString = isString5;
          lodash2.isSymbol = isSymbol3;
          lodash2.isTypedArray = isTypedArray;
          lodash2.isUndefined = isUndefined3;
          lodash2.isWeakMap = isWeakMap;
          lodash2.isWeakSet = isWeakSet;
          lodash2.join = join17;
          lodash2.kebabCase = kebabCase;
          lodash2.last = last;
          lodash2.lastIndexOf = lastIndexOf;
          lodash2.lowerCase = lowerCase;
          lodash2.lowerFirst = lowerFirst;
          lodash2.lt = lt2;
          lodash2.lte = lte2;
          lodash2.max = max;
          lodash2.maxBy = maxBy;
          lodash2.mean = mean;
          lodash2.meanBy = meanBy;
          lodash2.min = min2;
          lodash2.minBy = minBy;
          lodash2.stubArray = stubArray;
          lodash2.stubFalse = stubFalse;
          lodash2.stubObject = stubObject;
          lodash2.stubString = stubString;
          lodash2.stubTrue = stubTrue;
          lodash2.multiply = multiply;
          lodash2.nth = nth;
          lodash2.noConflict = noConflict;
          lodash2.noop = noop2;
          lodash2.now = now;
          lodash2.pad = pad;
          lodash2.padEnd = padEnd;
          lodash2.padStart = padStart3;
          lodash2.parseInt = parseInt2;
          lodash2.random = random2;
          lodash2.reduce = reduce;
          lodash2.reduceRight = reduceRight;
          lodash2.repeat = repeat3;
          lodash2.replace = replace;
          lodash2.result = result2;
          lodash2.round = round;
          lodash2.runInContext = runInContext2;
          lodash2.sample = sample;
          lodash2.size = size;
          lodash2.snakeCase = snakeCase;
          lodash2.some = some;
          lodash2.sortedIndex = sortedIndex;
          lodash2.sortedIndexBy = sortedIndexBy;
          lodash2.sortedIndexOf = sortedIndexOf;
          lodash2.sortedLastIndex = sortedLastIndex;
          lodash2.sortedLastIndexBy = sortedLastIndexBy;
          lodash2.sortedLastIndexOf = sortedLastIndexOf;
          lodash2.startCase = startCase;
          lodash2.startsWith = startsWith;
          lodash2.subtract = subtract;
          lodash2.sum = sum;
          lodash2.sumBy = sumBy;
          lodash2.template = template2;
          lodash2.times = times;
          lodash2.toFinite = toFinite;
          lodash2.toInteger = toInteger;
          lodash2.toLength = toLength;
          lodash2.toLower = toLower;
          lodash2.toNumber = toNumber;
          lodash2.toSafeInteger = toSafeInteger;
          lodash2.toString = toString8;
          lodash2.toUpper = toUpper;
          lodash2.trim = trim;
          lodash2.trimEnd = trimEnd;
          lodash2.trimStart = trimStart;
          lodash2.truncate = truncate;
          lodash2.unescape = unescape2;
          lodash2.uniqueId = uniqueId;
          lodash2.upperCase = upperCase;
          lodash2.upperFirst = upperFirst;
          lodash2.each = forEach2;
          lodash2.eachRight = forEachRight;
          lodash2.first = head;
          mixin(lodash2, (function() {
            var source2 = {};
            baseForOwn(lodash2, function(func, methodName) {
              if (!hasOwnProperty3.call(lodash2.prototype, methodName)) {
                source2[methodName] = func;
              }
            });
            return source2;
          })(), { chain: false });
          lodash2.VERSION = VERSION;
          arrayEach(["bind", "bindKey", "curry", "curryRight", "partial", "partialRight"], function(methodName) {
            lodash2[methodName].placeholder = lodash2;
          });
          arrayEach(["drop", "take"], function(methodName, index2) {
            LazyWrapper.prototype[methodName] = function(n5) {
              n5 = n5 === undefined$1 ? 1 : nativeMax(toInteger(n5), 0);
              var result22 = this.__filtered__ && !index2 ? new LazyWrapper(this) : this.clone();
              if (result22.__filtered__) {
                result22.__takeCount__ = nativeMin(n5, result22.__takeCount__);
              } else {
                result22.__views__.push({
                  size: nativeMin(n5, MAX_ARRAY_LENGTH),
                  type: methodName + (result22.__dir__ < 0 ? "Right" : "")
                });
              }
              return result22;
            };
            LazyWrapper.prototype[methodName + "Right"] = function(n5) {
              return this.reverse()[methodName](n5).reverse();
            };
          });
          arrayEach(["filter", "map", "takeWhile"], function(methodName, index2) {
            var type22 = index2 + 1, isFilter = type22 == LAZY_FILTER_FLAG || type22 == LAZY_WHILE_FLAG;
            LazyWrapper.prototype[methodName] = function(iteratee2) {
              var result22 = this.clone();
              result22.__iteratees__.push({
                iteratee: getIteratee(iteratee2, 3),
                type: type22
              });
              result22.__filtered__ = result22.__filtered__ || isFilter;
              return result22;
            };
          });
          arrayEach(["head", "last"], function(methodName, index2) {
            var takeName = "take" + (index2 ? "Right" : "");
            LazyWrapper.prototype[methodName] = function() {
              return this[takeName](1).value()[0];
            };
          });
          arrayEach(["initial", "tail"], function(methodName, index2) {
            var dropName = "drop" + (index2 ? "" : "Right");
            LazyWrapper.prototype[methodName] = function() {
              return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1);
            };
          });
          LazyWrapper.prototype.compact = function() {
            return this.filter(identity);
          };
          LazyWrapper.prototype.find = function(predicate) {
            return this.filter(predicate).head();
          };
          LazyWrapper.prototype.findLast = function(predicate) {
            return this.reverse().find(predicate);
          };
          LazyWrapper.prototype.invokeMap = baseRest(function(path3, args) {
            if (typeof path3 == "function") {
              return new LazyWrapper(this);
            }
            return this.map(function(value) {
              return baseInvoke(value, path3, args);
            });
          });
          LazyWrapper.prototype.reject = function(predicate) {
            return this.filter(negate(getIteratee(predicate)));
          };
          LazyWrapper.prototype.slice = function(start, end) {
            start = toInteger(start);
            var result22 = this;
            if (result22.__filtered__ && (start > 0 || end < 0)) {
              return new LazyWrapper(result22);
            }
            if (start < 0) {
              result22 = result22.takeRight(-start);
            } else if (start) {
              result22 = result22.drop(start);
            }
            if (end !== undefined$1) {
              end = toInteger(end);
              result22 = end < 0 ? result22.dropRight(-end) : result22.take(end - start);
            }
            return result22;
          };
          LazyWrapper.prototype.takeRightWhile = function(predicate) {
            return this.reverse().takeWhile(predicate).reverse();
          };
          LazyWrapper.prototype.toArray = function() {
            return this.take(MAX_ARRAY_LENGTH);
          };
          baseForOwn(LazyWrapper.prototype, function(func, methodName) {
            var checkIteratee = /^(?:filter|find|map|reject)|While$/.test(methodName), isTaker = /^(?:head|last)$/.test(methodName), lodashFunc = lodash2[isTaker ? "take" + (methodName == "last" ? "Right" : "") : methodName], retUnwrapped = isTaker || /^find/.test(methodName);
            if (!lodashFunc) {
              return;
            }
            lodash2.prototype[methodName] = function() {
              var value = this.__wrapped__, args = isTaker ? [1] : arguments, isLazy = value instanceof LazyWrapper, iteratee2 = args[0], useLazy = isLazy || isArray6(value);
              var interceptor = function(value2) {
                var result3 = lodashFunc.apply(lodash2, arrayPush([value2], args));
                return isTaker && chainAll ? result3[0] : result3;
              };
              if (useLazy && checkIteratee && typeof iteratee2 == "function" && iteratee2.length != 1) {
                isLazy = useLazy = false;
              }
              var chainAll = this.__chain__, isHybrid = !!this.__actions__.length, isUnwrapped = retUnwrapped && !chainAll, onlyLazy = isLazy && !isHybrid;
              if (!retUnwrapped && useLazy) {
                value = onlyLazy ? value : new LazyWrapper(this);
                var result22 = func.apply(value, args);
                result22.__actions__.push({ func: thru, args: [interceptor], thisArg: undefined$1 });
                return new LodashWrapper(result22, chainAll);
              }
              if (isUnwrapped && onlyLazy) {
                return func.apply(this, args);
              }
              result22 = this.thru(interceptor);
              return isUnwrapped ? isTaker ? result22.value()[0] : result22.value() : result22;
            };
          });
          arrayEach(["pop", "push", "shift", "sort", "splice", "unshift"], function(methodName) {
            var func = arrayProto[methodName], chainName = /^(?:push|sort|unshift)$/.test(methodName) ? "tap" : "thru", retUnwrapped = /^(?:pop|shift)$/.test(methodName);
            lodash2.prototype[methodName] = function() {
              var args = arguments;
              if (retUnwrapped && !this.__chain__) {
                var value = this.value();
                return func.apply(isArray6(value) ? value : [], args);
              }
              return this[chainName](function(value2) {
                return func.apply(isArray6(value2) ? value2 : [], args);
              });
            };
          });
          baseForOwn(LazyWrapper.prototype, function(func, methodName) {
            var lodashFunc = lodash2[methodName];
            if (lodashFunc) {
              var key = lodashFunc.name + "";
              if (!hasOwnProperty3.call(realNames, key)) {
                realNames[key] = [];
              }
              realNames[key].push({ name: methodName, func: lodashFunc });
            }
          });
          realNames[createHybrid(undefined$1, WRAP_BIND_KEY_FLAG).name] = [{
            name: "wrapper",
            func: undefined$1
          }];
          LazyWrapper.prototype.clone = lazyClone;
          LazyWrapper.prototype.reverse = lazyReverse;
          LazyWrapper.prototype.value = lazyValue;
          lodash2.prototype.at = wrapperAt;
          lodash2.prototype.chain = wrapperChain;
          lodash2.prototype.commit = wrapperCommit;
          lodash2.prototype.next = wrapperNext;
          lodash2.prototype.plant = wrapperPlant;
          lodash2.prototype.reverse = wrapperReverse;
          lodash2.prototype.toJSON = lodash2.prototype.valueOf = lodash2.prototype.value = wrapperValue;
          lodash2.prototype.first = lodash2.prototype.head;
          if (symIterator) {
            lodash2.prototype[symIterator] = wrapperToIterator;
          }
          return lodash2;
        };
        var _3 = runInContext();
        if (freeModule) {
          (freeModule.exports = _3)._ = _3;
          freeExports._ = _3;
        } else {
          root._ = _3;
        }
      }).call(commonjsGlobal2);
    });
    InputStream = class {
      constructor(input) {
        this.input = input;
        this.cursor = 0;
        this.line = 1;
        this.column = 0;
      }
      position() {
        return Object.freeze({
          cursor: this.cursor,
          line: this.line,
          column: this.column
        });
      }
      peek(offset3) {
        const cursor = lodash.isInteger(offset3) ? this.cursor + offset3 : this.cursor;
        return this.input.charAt(cursor);
      }
      next() {
        const c6 = this.input.charAt(this.cursor++);
        if (c6 === "\n") {
          this.line++;
          this.column = 0;
        } else {
          this.column++;
        }
        return c6;
      }
      eof() {
        return this.peek() === "";
      }
      err(msg5) {
        throw new Error(`${msg5} (${this.line}:${this.column})`);
      }
    };
    inputStream = (input) => {
      const i6 = new InputStream(input);
      const InputStreamProxy = {
        position() {
          return i6.position();
        },
        peek() {
          return i6.peek(...arguments);
        },
        next() {
          return i6.next();
        },
        eof() {
          return i6.eof();
        },
        err() {
          return i6.err(...arguments);
        }
      };
      return InputStreamProxy;
    };
    HEX_PATTERN = /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/;
    not = (p5) => (c6) => !p5(c6);
    is_char = (c6) => (cc) => c6 === cc;
    is_whitespace = (c6) => "	\r\n ".indexOf(c6) >= 0;
    is_newline = (c6) => c6 === "\n";
    is_operator = (c6) => "+-*/%=&|!~><^".indexOf(c6) >= 0;
    is_operator_repeatable = (c6) => "&|=".indexOf(c6) >= 0;
    is_punctuation = (c6) => ",;(){}[]:#.".indexOf(c6) >= 0;
    is_digit = (c6) => /[0-9]/i.test(c6);
    is_comment_start = (input) => input.peek() === "/" && (input.peek(1) === "/" || input.peek(1) === "*");
    is_ident_start = (c6) => /[a-z_]/i.test(c6);
    is_ident = (c6) => /[a-z0-9_-]/i.test(c6);
    is_number_start = (input) => is_digit(input.peek()) || input.peek() === "." && is_digit(input.peek(1));
    is_hex = (input) => {
      let hex = input.peek();
      if (hex === "#") {
        let _3 = false;
        let _6 = false;
        while (hex.length < 7) {
          const c6 = input.peek(hex.length);
          if (lodash.isEmpty(c6))
            break;
          hex += c6;
          if (hex.length === 4)
            _3 = HEX_PATTERN.test(hex);
          if (hex.length === 7)
            _6 = HEX_PATTERN.test(hex);
        }
        return _6 ? 6 : _3 ? 3 : false;
      }
      return false;
    };
    TokenStream = class {
      constructor(input) {
        invariant_default(lodash.isPlainObject(input) && lodash.has(input, "next"), "TokenStream requires an InputStream");
        this.input = input;
        this.tokens = [];
      }
      createToken(type22, value, start) {
        return Object.freeze({
          type: type22,
          value,
          start,
          next: this.input.position()
        });
      }
      peek(offset3) {
        if (!this.tokens.length) {
          const token = this.read_next();
          if (token)
            this.tokens.push(token);
        }
        if (!offset3)
          return this.tokens[0];
        if (offset3 < this.tokens.length)
          return this.tokens[offset3];
        while (this.tokens.length <= offset3) {
          const token = this.read_next();
          if (token)
            this.tokens.push(token);
          else
            break;
        }
        return this.tokens[offset3];
      }
      next() {
        const token = this.tokens.shift();
        return token || this.read_next();
      }
      eof() {
        return typeof this.peek() === "undefined";
      }
      err() {
        return this.input.err(...arguments);
      }
      read_next() {
        if (this.input.eof())
          return null;
        const c6 = this.input.peek();
        if (is_whitespace(c6)) {
          return this.read_whitespace();
        }
        if (is_comment_start(this.input)) {
          return this.read_comment();
        }
        if (is_number_start(this.input)) {
          return this.read_number();
        }
        const hex_length = is_hex(this.input);
        if (hex_length) {
          return this.read_hex(hex_length);
        }
        if (is_punctuation(c6)) {
          return this.read_punctuation();
        }
        if (is_ident_start(c6)) {
          return this.read_ident();
        }
        if (is_operator(c6)) {
          return this.read_operator();
        }
        if (c6 === '"' || c6 === "'") {
          return this.read_string(c6);
        }
        if (c6 === "@") {
          return this.read_atkeyword();
        }
        if (c6 === "$") {
          return this.read_variable();
        }
        this.err(`Can't handle character: "${c6}"`);
      }
      read_while(predicate) {
        let s5 = "";
        while (!this.input.eof() && predicate(this.input.peek())) {
          s5 += this.input.next();
        }
        return s5;
      }
      read_escaped(end) {
        let escaped = false;
        let str3 = "";
        this.input.next();
        while (!this.input.eof()) {
          const c6 = this.input.next();
          if (escaped) {
            str3 += c6;
            escaped = false;
          } else if (c6 === "\\") {
            str3 += c6;
            escaped = true;
          } else if (c6 === end) {
            break;
          } else {
            str3 += c6;
          }
        }
        return str3;
      }
      read_whitespace() {
        const start = this.input.position();
        const value = this.read_while(is_whitespace);
        return this.createToken("space", value, start);
      }
      read_comment() {
        const start = this.input.position();
        this.input.next();
        switch (this.input.next()) {
          case "/":
            return this.read_comment_single(start);
          case "*":
            return this.read_comment_multi(start);
        }
      }
      read_comment_single(start) {
        const value = this.read_while(not(is_newline));
        return this.createToken("comment_singleline", value, start);
      }
      read_comment_multi(start) {
        let prev = "";
        let value = "";
        while (!this.input.eof()) {
          const next = this.input.next();
          if (next === "/" && prev === "*")
            break;
          value += prev;
          prev = next;
        }
        return this.createToken("comment_multiline", value, start);
      }
      read_punctuation() {
        const start = this.input.position();
        const value = this.input.next();
        return this.createToken("punctuation", value, start);
      }
      read_operator() {
        const start = this.input.position();
        const c6 = this.input.peek();
        const value = is_operator_repeatable(c6) ? this.read_while(is_char(c6)) : this.input.next();
        return this.createToken("operator", value, start);
      }
      read_ident() {
        const start = this.input.position();
        const value = this.read_while(is_ident);
        return this.createToken("identifier", value, start);
      }
      read_string(c6) {
        const start = this.input.position();
        const value = this.read_escaped(c6);
        let type22 = "string";
        if (c6 === '"')
          type22 = "string_double";
        if (c6 === "'")
          type22 = "string_single";
        return this.createToken(type22, value, start);
      }
      read_number() {
        const start = this.input.position();
        let hasPoint = false;
        const value = this.read_while((c6) => {
          if (c6 === ".") {
            if (hasPoint)
              return false;
            hasPoint = true;
            return true;
          }
          return is_digit(c6);
        });
        return this.createToken("number", value, start);
      }
      read_hex(length) {
        const start = this.input.position();
        this.input.next();
        let value = "";
        for (let i6 = 0; i6 < length; i6++) {
          value += this.input.next();
        }
        return this.createToken("color_hex", value, start);
      }
      read_atkeyword() {
        const start = this.input.position();
        this.input.next();
        const value = this.read_while(is_ident);
        return this.createToken("atkeyword", value, start);
      }
      read_variable() {
        const start = this.input.position();
        this.input.next();
        const value = this.read_while(is_ident);
        return this.createToken("variable", value, start);
      }
    };
    tokenStream = (input) => {
      const t5 = new TokenStream(input);
      const TokenStreamProxy = {
        peek() {
          return t5.peek(...arguments);
        },
        next() {
          return t5.next();
        },
        eof() {
          return t5.eof();
        },
        err() {
          return t5.err(...arguments);
        },
        all() {
          const tokens2 = [];
          while (!t5.eof())
            tokens2.push(t5.next());
          return tokens2;
        }
      };
      return TokenStreamProxy;
    };
    Parser = class {
      constructor(tokens2) {
        this.tokens = tokens2;
      }
      createNode(type22, value, start, next) {
        return { type: type22, value, start, next };
      }
      is_type(type22, ...values) {
        const t5 = this.tokens.peek();
        if (!values.length)
          return t5 ? type22.test(t5.type) : false;
        return values.reduce((a5, c6, i6) => {
          const t22 = this.tokens.peek(i6);
          return !t22 ? false : a5 && type22.test(t22.type) && t22.value === c6;
        }, true);
      }
      is_space() {
        return this.is_type(/space/);
      }
      is_comment() {
        return this.is_type(/comment/);
      }
      is_punctuation() {
        return this.is_type(/punctuation/, ...arguments);
      }
      is_operator() {
        return this.is_type(/operator/, ...arguments);
      }
      is_identifier() {
        return this.is_type(/identifier/, ...arguments);
      }
      is_atkeyword() {
        return this.is_type(/atkeyword/, ...arguments);
      }
      is_interpolation() {
        return this.is_punctuation("#", "{");
      }
      skip_type(type22, isType, ...chars) {
        if (isType.apply(this, chars)) {
          return { start: this.tokens.peek(), next: this.tokens.next() };
        } else {
          this.tokens.err(`Expecting ${type22}: "${chars.join("")}"`);
        }
      }
      skip_punctuation() {
        return this.skip_type("punctuation", this.is_punctuation, ...arguments);
      }
      skip_operator() {
        return this.skip_type("operator", this.is_operator, ...arguments);
      }
      skip_atkeyword() {
        return this.skip_type("atkeyword", this.is_atkeyword);
      }
      unexpected() {
        this.tokens.err(`Unexpected token: "${JSON.stringify(this.input.peek())}"`);
      }
      parse_stylesheet() {
        const value = [];
        while (!this.tokens.eof()) {
          const node = this.parse_node();
          if (lodash.isArray(node)) {
            value.push(...node);
          } else {
            value.push(node);
          }
        }
        return this.createNode("stylesheet", value);
      }
      parse_node() {
        if (this.is_space() || this.is_comment())
          return this.tokens.next();
        const value = [];
        const maybe_declaration = (punctuation) => {
          let expandedPseudo = false;
          if (punctuation === ";") {
            const pseudoIndex = lodash.findIndex(value, {
              type: "pseudo_class"
            });
            if (pseudoIndex > 0) {
              const a5 = value[pseudoIndex];
              const b3 = this.createNode("punctuation", ":", a5.start, lodash.first(a5.value).start);
              const nodes = [b3].concat(a5.value);
              value.splice(pseudoIndex, 1, ...nodes);
              expandedPseudo = true;
            }
          }
          const puncIndex = lodash.findIndex(value, {
            type: "punctuation",
            value: ":"
          });
          if (puncIndex >= 0) {
            const maybeSpace = value[puncIndex + 1];
            if (maybeSpace.type === "space" || expandedPseudo) {
              const start = lodash.first(value).start;
              let next = lodash.last(value).next;
              const property_ = lodash.take(value, puncIndex);
              const propertyNode = this.createNode("property", property_, lodash.first(property_).start, lodash.last(property_).next);
              const value_ = lodash.drop(value, puncIndex + 1);
              if (punctuation === "{") {
                const block = this.parse_block();
                value_.push(block);
                next = block.next;
              }
              const valueNode = this.createNode("value", value_, lodash.first(value_).start, lodash.last(value_).next);
              const declarationValue = [propertyNode, value[puncIndex], valueNode];
              if (punctuation === ";") {
                const { start: start2 } = this.skip_punctuation(";");
                declarationValue.push(start2);
                next = next.start;
              }
              return this.createNode("declaration", declarationValue, start, next);
            }
          }
          return false;
        };
        while (!this.tokens.eof()) {
          if (this.is_atkeyword()) {
            return value.concat(this.parse_at_rule());
          }
          value.push(this.parse_atom());
          if (this.is_punctuation("{")) {
            if (value.length) {
              return maybe_declaration("{") || this.parse_rule(value);
            } else {
              return value.concat(this.parse_block());
            }
          }
          if (this.is_punctuation(";")) {
            return maybe_declaration(";");
          }
        }
        return value;
      }
      parse_expression(predicate) {
        let value = [];
        let declaration = [];
        while (true) {
          if (this.tokens.eof() || !predicate())
            break;
          if (this.is_punctuation(":") && declaration.length) {
            value.push(this.parse_declaration(declaration));
            value = lodash.xor(value, declaration);
            declaration = [];
          }
          if (this.tokens.eof() || !predicate())
            break;
          const atom = this.parse_atom();
          value.push(atom);
          switch (atom.type) {
            case "space":
            case "punctuation":
              break;
            default:
              declaration.push(atom);
          }
        }
        return value;
      }
      parse_atom() {
        return this.maybe_function(() => {
          if (this.is_punctuation("(")) {
            return this.parse_wrapped("parentheses", "(", ")");
          }
          if (this.is_interpolation()) {
            return this.parse_interolation();
          }
          if (this.is_punctuation("[")) {
            return this.parse_wrapped("attribute", "[", "]");
          }
          if (this.is_punctuation(".")) {
            return this.parse_selector("class", ".");
          }
          if (this.is_punctuation("#")) {
            return this.parse_selector("id", "#");
          }
          if (this.is_punctuation("::")) {
            return this.parse_selector("pseudo_element", ":");
          }
          if (this.is_punctuation(":")) {
            const next = this.tokens.peek(1);
            if (next.type === "identifier" || next.type === "punctuation" && next.value === "#") {
              return this.parse_selector("pseudo_class", ":");
            }
          }
          return this.tokens.next();
        });
      }
      parse_declaration(property) {
        const { start: firstSeparator } = this.skip_punctuation(":");
        let secondSeparator;
        const value = this.parse_expression(() => {
          if (this.is_punctuation(";")) {
            secondSeparator = this.tokens.next();
            return false;
          }
          if (this.is_punctuation(",")) {
            secondSeparator = this.tokens.next();
            return false;
          }
          if (this.is_punctuation(")"))
            return false;
          return true;
        });
        const propertyNode = this.createNode("property", property, lodash.first(property).start, lodash.last(property).next);
        const valueNode = this.createNode("value", value, lodash.first(value).start, lodash.last(value).next);
        const declarationValue = [propertyNode, firstSeparator, valueNode];
        if (secondSeparator)
          declarationValue.push(secondSeparator);
        return this.createNode("declaration", declarationValue, lodash.first(property).start, lodash.last(value).next);
      }
      parse_wrapped(type22, open, close, _start) {
        const { start } = this.skip_punctuation(open);
        const value = this.parse_expression(() => !this.is_punctuation(close));
        const { next } = this.skip_punctuation(close);
        return this.createNode(type22, value, (_start || start).start, next.next);
      }
      parse_block() {
        const { start } = this.skip_punctuation("{");
        const value = [];
        while (!this.tokens.eof() && !this.is_punctuation("}")) {
          const node = this.parse_node();
          if (lodash.isArray(node)) {
            value.push(...node);
          } else {
            value.push(node);
          }
        }
        const { next } = this.skip_punctuation("}");
        if (this.is_punctuation(";")) {
          this.skip_punctuation(";");
        }
        return this.createNode("block", value, start.start, next.next);
      }
      parse_arguments(type22) {
        const { start } = this.skip_punctuation("(");
        let value = [];
        if (type22 === "pseudo_class") {
          while (!this.tokens.eof() && !this.is_punctuation(")")) {
            value.push(this.parse_atom());
          }
        } else {
          while (!this.tokens.eof() && !this.is_punctuation(")")) {
            value = value.concat(this.parse_expression(() => {
              if (this.is_punctuation(","))
                return false;
              if (this.is_punctuation(")"))
                return false;
              return true;
            }));
            if (this.is_punctuation(",")) {
              value.push(this.tokens.next());
            }
          }
        }
        const { next } = this.skip_punctuation(")");
        return this.createNode("arguments", value, start.start, next.next);
      }
      maybe_function(node) {
        node = node();
        const types8 = ["identifier", "function", "interpolation", "pseudo_class"];
        return this.is_punctuation("(") && lodash.includes(types8, node.type) ? this.parse_function(node) : node;
      }
      parse_function(node) {
        const args = this.parse_arguments(node.type);
        return this.createNode("function", [node, args], node.start, args.next);
      }
      parse_interolation() {
        const { start } = this.skip_punctuation("#");
        return this.parse_wrapped("interpolation", "{", "}", start);
      }
      parse_at_rule() {
        const { start } = this.skip_atkeyword();
        const value = [start];
        if (this.is_space())
          value.push(this.tokens.next());
        if (this.is_identifier())
          value.push(this.tokens.next());
        while (!this.tokens.eof()) {
          if (this.is_punctuation("(") && /mixin|include|function/.test(start.value)) {
            value.push(this.parse_arguments());
          }
          if (this.is_punctuation("{")) {
            value.push(this.parse_block());
            break;
          }
          if (this.is_punctuation(";")) {
            value.push(this.tokens.next());
            break;
          } else {
            value.push(this.parse_atom());
          }
        }
        return this.createNode("atrule", value, start.start, lodash.last(value).next);
      }
      parse_rule(selectors) {
        const selector = this.createNode("selector", selectors, lodash.first(selectors).start, lodash.last(selectors).next);
        const block = this.parse_block();
        return this.createNode("rule", [selector, block], selector.start, block.next);
      }
      parse_selector(type22, punctuation) {
        const { start } = this.skip_punctuation(punctuation);
        if (this.is_punctuation(":")) {
          this.skip_punctuation(":");
        }
        const value = [];
        let next = this.is_interpolation() ? this.parse_interolation() : this.tokens.next();
        while (next.type === "identifier" || next.type === "interpolation" || next.type === "operator") {
          value.push(next);
          next = this.is_interpolation() ? this.parse_interolation() : this.tokens.peek();
          if (!next)
            break;
          if (next.type === "identifier")
            this.tokens.next();
          if (next.type === "operator")
            this.tokens.next();
        }
        if (!value.length) {
          this.tokens.err(`Selector ("${type22}") expected "identifier" or "interpolation"`);
        }
        return this.createNode(type22, value, start.start, lodash.last(value).next);
      }
    };
    parse10 = (tokenStream2) => {
      invariant_default(lodash.isPlainObject(tokenStream2) && lodash.has(tokenStream2, "next"), "Parser requires a TokenStream");
      const parser = new Parser(tokenStream2);
      return parser.parse_stylesheet();
    };
    type3 = {
      arguments: (n5) => "(" + walkValue(n5.value) + ")",
      atkeyword: (n5) => "@" + n5.value,
      attribute: (n5) => "[" + walkValue(n5.value) + "]",
      block: (n5) => "{" + walkValue(n5.value) + "}",
      class: (n5) => "." + walkValue(n5.value),
      color_hex: (n5) => "#" + n5.value,
      id: (n5) => "#" + walkValue(n5.value),
      interpolation: (n5) => "#{" + walkValue(n5.value) + "}",
      comment_multiline: (n5) => "/*" + n5.value + "*/",
      comment_singleline: (n5) => "//" + n5.value,
      parentheses: (n5) => "(" + walkValue(n5.value) + ")",
      pseudo_class: (n5) => ":" + walkValue(n5.value),
      psuedo_element: (n5) => "::" + walkValue(n5.value),
      string_double: (n5) => `"${n5.value}"`,
      string_single: (n5) => `'${n5.value}'`,
      variable: (n5) => "$" + n5.value
    };
    walkNode = (node) => {
      if (type3[node.type])
        return type3[node.type](node);
      if (lodash.isString(node.value))
        return node.value;
      if (lodash.isArray(node.value))
        return walkValue(node.value);
      return "";
    };
    walkValue = (value) => {
      if (!lodash.isArray(value))
        return "";
      return value.reduce((s5, node) => {
        return s5 + walkNode(node);
      }, "");
    };
    stringify3 = (node) => walkNode(node);
    parse$1 = (css) => parse10(tokenStream(inputStream(css)));
    stringify$1 = (node) => stringify3(node);
    lib = {
      parse: parse$1,
      stringify: stringify$1
    };
    parse$2 = lib.parse;
    stringify$2 = lib.stringify;
  }
});

// https://cdn.skypack.dev/scss-parser@1.0.6
var init_scss_parser_1_0 = __esm({
  "https://cdn.skypack.dev/scss-parser@1.0.6"() {
    init_scss_parser();
    init_scss_parser();
  }
});

// core/sass/analyzer/ast-utils.ts
var walk3, withType, withTypeAndArray, filterDeep, mapDeep, annotateNode;
var init_ast_utils = __esm({
  "core/sass/analyzer/ast-utils.ts"() {
    walk3 = (node, cb) => {
      if (!node || typeof node !== "object") return;
      if (!cb(node)) {
        return;
      }
      ;
      for (const key of Object.keys(node)) {
        walk3(node[key], cb);
      }
    };
    withType = (node, func) => {
      if (!node?.type) {
        return node;
      }
      return func(node);
    };
    withTypeAndArray = (node, func) => {
      if (!node?.type) {
        return node;
      }
      if (!node?.children || !Array.isArray(node.children)) {
        return node;
      }
      return func(node);
    };
    filterDeep = (outer, cb) => withType(outer, (ast) => {
      return Object.fromEntries(Object.entries(ast).map(([k3, v4]) => {
        if (Array.isArray(v4)) {
          return [k3, v4.filter(cb).map((v5) => filterDeep(v5, cb))];
        } else if (v4 && typeof v4 === "object") {
          return [k3, filterDeep(v4, cb)];
        } else {
          return [k3, v4];
        }
      }));
    });
    mapDeep = (outer, cb) => withType(outer, (ast) => {
      if (Array.isArray(ast.children)) {
        ast.children = ast.children.map((v4) => mapDeep(v4, cb));
      }
      if (Array.isArray(ast.value)) {
        ast.value = ast.value.map((v4) => mapDeep(v4, cb));
      }
      return cb(ast);
    });
    annotateNode = (node, annotation) => {
      if (!node.annotation) {
        node.annotation = {};
      }
      Object.assign(node.annotation, annotation);
      return node;
    };
  }
});

// core/sass/analyzer/parse.ts
var makeParserModule;
var init_parse8 = __esm({
  "core/sass/analyzer/parse.ts"() {
    init_ast_utils();
    makeParserModule = (parse24) => {
      return {
        getSassAst: (contents) => {
          contents = contents.replaceAll(".$", "_dot_dollar");
          contents = contents.replaceAll("...", "_dot_dot_dot");
          contents = contents.replaceAll("@import url", "//@import url");
          contents = contents.replaceAll(
            /^[\t\f\v \u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]*([^\n{]+)([{])\s*([}])$/mg,
            "$1$2 /* empty rule */ $3"
          );
          contents = contents.replaceAll(
            /^(?!(?=\/\/)|(?=\s*[@#$]))(.*[^}/\s\n;])([\s\n]*)}(\n|$)/mg,
            "$1;$2}$3"
          );
          contents = contents.replaceAll(
            /(^\s*[A-Za-z0-9-]+):([^ \n])/mg,
            "$1: $2"
          );
          contents = contents.replaceAll(
            /[^\x00-\x7F]/g,
            (ch) => `_u${ch.codePointAt(0).toString(16)}_`
          );
          const ast = JSON.parse(JSON.stringify(parse24(contents)));
          if (!(ast.type === "stylesheet")) {
            throw new Error("Expected AST to have type 'stylesheet'");
          }
          if (!Array.isArray(ast.value)) {
            throw new Error("Expected AST to have an array value");
          }
          walk3(ast, (node) => {
            if (Array.isArray(node)) {
              return true;
            }
            if (["value", "identifier", "operator"].includes(node?.type)) {
              return true;
            }
            if (!node?.value || !Array.isArray(node.value)) {
              return true;
            }
            node.children = node.value;
            delete node.value;
            return true;
          });
          return ast;
        }
      };
    };
  }
});

// core/sass/analyzer/remove-nonsemantic-entries.ts
var isRealContent, isNotPunctuation;
var init_remove_nonsemantic_entries = __esm({
  "core/sass/analyzer/remove-nonsemantic-entries.ts"() {
    isRealContent = (v4) => {
      if (!v4?.type) {
        return true;
      }
      if (["space", "comment_singleline", "comment_multiline"].includes(v4.type)) {
        return false;
      }
      return true;
    };
    isNotPunctuation = (v4) => {
      if (!v4?.type) {
        return true;
      }
      if (v4.type === "punctuation") {
        return false;
      }
      return true;
    };
  }
});

// core/sass/analyzer/line-info.ts
var simplifyLineInfo;
var init_line_info = __esm({
  "core/sass/analyzer/line-info.ts"() {
    init_ast_utils();
    simplifyLineInfo = (outer) => withType(outer, (node) => {
      const start = node?.start;
      const next = node?.next;
      return {
        ...node,
        start: void 0,
        next: void 0,
        line: start?.line,
        lineEnd: next?.line
      };
    });
  }
});

// core/sass/analyzer/default-declarations.ts
var explicitlyTagDefaultValues;
var init_default_declarations = __esm({
  "core/sass/analyzer/default-declarations.ts"() {
    init_ast_utils();
    explicitlyTagDefaultValues = (outer) => withType(outer, (node) => {
      const l6 = node.value?.length;
      if (node?.type !== "value" || l6 < 2) {
        return node;
      }
      if (node.value[l6 - 1]?.type !== "identifier" || node.value[l6 - 1]?.value !== "default" || node.value[l6 - 2]?.type !== "operator" || node.value[l6 - 2]?.value !== "!") {
        return node;
      }
      return {
        ...node,
        value: node.value.slice(0, -2),
        isDefault: true
      };
    });
  }
});

// core/sass/analyzer/css-information.ts
var units, namedColors;
var init_css_information = __esm({
  "core/sass/analyzer/css-information.ts"() {
    units = /* @__PURE__ */ new Set([
      // found in 2024-07-29
      // length https://developer.mozilla.org/en-US/docs/Web/CSS/length,
      "cap",
      "ic",
      "lh",
      "rcap",
      "rch",
      "rex",
      "ric",
      "rlh",
      "vb",
      "vi",
      "cqw",
      "cqh",
      "cqi",
      "cqmin",
      "cqmax",
      "Q",
      "rem",
      "em",
      "px",
      "pt",
      "pc",
      "cm",
      "mm",
      "in",
      "ex",
      "ch",
      "vw",
      "vh",
      "vmin",
      "vmax",
      // angle https://developer.mozilla.org/en-US/docs/Web/CSS/angle
      "deg",
      "grad",
      "rad",
      "turn",
      // time https://developer.mozilla.org/en-US/docs/Web/CSS/time
      "s",
      "ms",
      // resolution https://developer.mozilla.org/en-US/docs/Web/CSS/resolution
      "dpi",
      "dpcm",
      "dppx",
      "x",
      // frequency https://developer.mozilla.org/en-US/docs/Web/CSS/frequency
      "Hz",
      "kHz"
    ]);
    namedColors = /* @__PURE__ */ new Set([
      "black",
      "silver",
      "gray",
      "white",
      "maroon",
      "red",
      "purple",
      "fuchsia",
      "green",
      "lime",
      "olive",
      "yellow",
      "navy",
      "blue",
      "teal",
      "aqua",
      "aliceblue",
      "antiquewhite",
      "aqua",
      "aquamarine",
      "azure",
      "beige",
      "bisque",
      "black",
      "blanchedalmond",
      "blue",
      "blueviolet",
      "brown",
      "burlywood",
      "cadetblue",
      "chartreuse",
      "chocolate",
      "coral",
      "cornflowerblue",
      "cornsilk",
      "crimson",
      "cyan",
      "darkblue",
      "darkcyan",
      "darkgoldenrod",
      "darkgray",
      "darkgreen",
      "darkgrey",
      "darkkhaki",
      "darkmagenta",
      "darkolivegreen",
      "darkorange",
      "darkorchid",
      "darkred",
      "darksalmon",
      "darkseagreen",
      "darkslateblue",
      "darkslategray",
      "darkslategrey",
      "darkturquoise",
      "darkviolet",
      "deeppink",
      "deepskyblue",
      "dimgray",
      "dimgrey",
      "dodgerblue",
      "firebrick",
      "floralwhite",
      "forestgreen",
      "fuchsia",
      "gainsboro",
      "ghostwhite",
      "gold",
      "goldenrod",
      "gray",
      "green",
      "greenyellow",
      "grey",
      "honeydew",
      "hotpink",
      "indianred",
      "indigo",
      "ivory",
      "khaki",
      "lavender",
      "lavenderblush",
      "lawngreen",
      "lemonchiffon",
      "lightblue",
      "lightcoral",
      "lightcyan",
      "lightgoldenrodyellow",
      "lightgray",
      "lightgreen",
      "lightgrey",
      "lightpink",
      "lightsalmon",
      "lightseagreen",
      "lightskyblue",
      "lightslategray",
      "lightslategrey",
      "lightsteelblue",
      "lightyellow",
      "lime",
      "limegreen",
      "linen",
      "magenta",
      "maroon",
      "mediumaquamarine",
      "mediumblue",
      "mediumorchid",
      "mediumpurple",
      "mediumseagreen",
      "mediumslateblue",
      "mediumspringgreen",
      "mediumturquoise",
      "mediumvioletred",
      "midnightblue",
      "mintcream",
      "mistyrose",
      "moccasin",
      "navajowhite",
      "navy",
      "oldlace",
      "olive",
      "olivedrab",
      "orange",
      "orangered",
      "orchid",
      "palegoldenrod",
      "palegreen",
      "paleturquoise",
      "palevioletred",
      "papayawhip",
      "peachpuff",
      "peru",
      "pink",
      "plum",
      "powderblue",
      "purple",
      "rebeccapurple",
      "red",
      "rosybrown",
      "royalblue",
      "saddlebrown",
      "salmon",
      "sandybrown",
      "seagreen",
      "seashell",
      "sienna",
      "silver",
      "skyblue",
      "slateblue",
      "slategray",
      "slategrey",
      "snow",
      "springgreen",
      "steelblue",
      "tan",
      "teal",
      "thistle",
      "tomato",
      "transparent",
      "turquoise",
      "violet",
      "wheat",
      "white",
      "whitesmoke",
      "yellow",
      "yellowgreen",
      "currentcolor"
      // this is a bit of a hack, but it's used in color contexts
    ]);
  }
});

// core/sass/analyzer/value-types.ts
var typedImmediateValues, fixImmediateTypes, tagNamedColors, tagColorConstructors, findDimensionValues;
var init_value_types = __esm({
  "core/sass/analyzer/value-types.ts"() {
    init_ast_utils();
    init_css_information();
    typedImmediateValues = {
      false: { type: "boolean", value: false },
      true: { type: "boolean", value: true },
      null: { type: "null", value: null }
    };
    fixImmediateTypes = (outer) => withType(outer, (node) => {
      if (node.type === "identifier" && typedImmediateValues[node.value]) {
        return { ...node, ...typedImmediateValues[node.value] };
      }
      return node;
    });
    tagNamedColors = (outer) => withType(outer, (node) => {
      if (node.type !== "identifier" || !namedColors.has(node?.value)) {
        return node;
      }
      return {
        ...node,
        type: "named_color"
      };
    });
    tagColorConstructors = (outer) => withType(outer, (node) => {
      if (node.type !== "function") {
        return node;
      }
      const name2 = node.children[0].value;
      if (node.children[0].type !== "identifier" || !name2) {
        return node;
      }
      const colorConstructors = /* @__PURE__ */ new Set([
        "rgb",
        "rgba",
        "hsl",
        "hsla"
      ]);
      if (colorConstructors.has(name2)) {
        return {
          ...node,
          valueType: "color"
        };
      }
      return node;
    });
    findDimensionValues = (outer) => withType(outer, (node) => {
      const replace = (value) => {
        const newValues = [];
        for (let i6 = 0; i6 < value.length; ++i6) {
          const thisValue = value[i6];
          const nextValue = value[i6 + 1];
          if (thisValue?.type === "number" && nextValue?.type === "identifier" && units.has(nextValue?.value)) {
            newValues.push({
              ...thisValue,
              type: "dimension",
              unit: nextValue.value
            });
            ++i6;
          } else if (thisValue?.type === "number" && nextValue?.type === "operator" && nextValue?.value === "%") {
            newValues.push({
              ...thisValue,
              type: "percentage"
            });
            ++i6;
          } else {
            newValues.push(thisValue);
          }
        }
        return newValues;
      };
      if (node.type === "value" && Array.isArray(node.value)) {
        return {
          ...node,
          value: replace(node.value)
        };
      }
      if (node.type === "node_group") {
        return {
          ...node,
          children: replace(node.children)
        };
      }
      return node;
    });
  }
});

// core/sass/analyzer/group-arguments.ts
var groupArguments;
var init_group_arguments = __esm({
  "core/sass/analyzer/group-arguments.ts"() {
    init_ast_utils();
    groupArguments = (outer) => withType(outer, (node) => {
      if (node.type !== "function") {
        return node;
      }
      const newArguments = [];
      const newGroup = () => {
        return {
          type: "node_group",
          start: node.start,
          // just so that simplifyLineInfo can handle it later
          next: node.next,
          children: []
        };
      };
      let thisArgument = newGroup();
      const flushGroup = () => {
        if (thisArgument.children.length > 1) {
          newArguments.push(thisArgument);
        } else {
          newArguments.push(thisArgument.children[0]);
        }
        thisArgument = newGroup();
      };
      if (node.children.length < 2) {
        throw new Error("function node has no arguments");
      }
      for (const arg of node.children[1].children) {
        if (arg.type === "punctuation" && arg.value === ",") {
          flushGroup();
        } else {
          thisArgument.children.push(arg);
        }
      }
      if (thisArgument.children.length > 0) {
        flushGroup();
      }
      node.children[1].children = newArguments;
      return node;
    });
  }
});

// core/sass/analyzer/forward-annotations.ts
var forwardAnnotations;
var init_forward_annotations = __esm({
  "core/sass/analyzer/forward-annotations.ts"() {
    init_ast_utils();
    forwardAnnotations = (ast) => {
      const pragmaAnnotation = "quarto-scss-analysis-annotation";
      const annotationStack = [{}];
      let currentAnnotation = annotationStack[0];
      let hasAnnotations = false;
      for (const node of ast.children) {
        if (node.type === "comment_singleline") {
          const value = node?.value?.trim();
          if (value.startsWith(pragmaAnnotation)) {
            let payload = {};
            try {
              payload = JSON.parse(value.slice(pragmaAnnotation.length).trim());
            } catch (e5) {
              console.error("Could not parse annotation payload", e5);
              continue;
            }
            if (payload.action === "push") {
              annotationStack.push(JSON.parse(JSON.stringify(currentAnnotation)));
              currentAnnotation = annotationStack[annotationStack.length - 1];
            } else if (payload.action === "pop" && annotationStack.length) {
              annotationStack.pop();
              currentAnnotation = annotationStack[annotationStack.length - 1];
            }
            for (const [key, value2] of Object.entries(payload)) {
              if (key === "action") {
                continue;
              }
              if (value2 === null) {
                delete currentAnnotation[key];
              } else {
                currentAnnotation[key] = value2;
              }
            }
            hasAnnotations = Object.keys(currentAnnotation).length > 0;
          }
        }
        if (node.type === "declaration" && hasAnnotations) {
          annotateNode(node, currentAnnotation);
        }
      }
      return ast;
    };
  }
});

// core/sass/analyzer/clean-ast.ts
var valueArrayToObjectKeys, cleanSassAst;
var init_clean_ast = __esm({
  "core/sass/analyzer/clean-ast.ts"() {
    init_ast_utils();
    init_remove_nonsemantic_entries();
    init_line_info();
    init_default_declarations();
    init_value_types();
    init_group_arguments();
    init_forward_annotations();
    valueArrayToObjectKeys = (outer) => withTypeAndArray(outer, (node) => {
      const keys = node.children.map((v4) => v4.type);
      if (keys.length !== new Set(keys).size) {
        return node;
      }
      return {
        ...node,
        ...Object.fromEntries(node.children.map((v4) => {
          const key = v4.type;
          let children = v4.children;
          return [key, { ...v4, children }];
        }))
      };
    });
    cleanSassAst = (ast) => {
      ast = forwardAnnotations(ast);
      ast = filterDeep(ast, isRealContent);
      ast = mapDeep(ast, groupArguments);
      ast = filterDeep(ast, isNotPunctuation);
      ast = mapDeep(ast, simplifyLineInfo);
      ast = mapDeep(ast, explicitlyTagDefaultValues);
      ast = mapDeep(ast, findDimensionValues);
      ast = mapDeep(ast, fixImmediateTypes);
      ast = mapDeep(ast, tagColorConstructors);
      ast = mapDeep(ast, tagNamedColors);
      ast = mapDeep(ast, valueArrayToObjectKeys);
      return ast;
    };
  }
});

// core/sass/analyzer/declaration-types.ts
var propagateDeclarationTypes;
var init_declaration_types = __esm({
  "core/sass/analyzer/declaration-types.ts"() {
    propagateDeclarationTypes = (ast) => {
      const declarationsToTrack = /* @__PURE__ */ new Map();
      const typesToSkip = /* @__PURE__ */ new Set([
        "identifier",
        "boolean",
        "number",
        "dimension",
        "percentage",
        "string",
        "string_double",
        "string_single"
      ]);
      const namesToIgnore = /* @__PURE__ */ new Set([
        "title-banner-image",
        // with this hack, we can assume all other instances of 'null' are color
        "theme",
        "theme-name",
        "enable-grid-classes",
        "enable-cssgrid",
        "nav-tabs-link-active-border-color",
        "navbar-light-bg",
        "navbar-dark-bg",
        "navbar-light-color",
        "navbar-light-hover-color",
        "navbar-light-active-color",
        "navbar-light-disabled-color",
        "navbar-light-toggler-icon-bg",
        "navbar-light-toggler-border-color",
        "navbar-light-brand-color",
        "navbar-light-brand-hover-color",
        "navbar-dark-color",
        "navbar-dark-hover-color",
        "navbar-dark-active-color",
        "navbar-dark-disabled-color",
        "navbar-dark-toggler-icon-bg",
        "navbar-dark-toggler-border-color",
        "navbar-dark-brand-color",
        "navbar-dark-brand-hover-color"
      ]);
      const speciallyKnownTypes = {
        "link-color": "color",
        "input-border-color": "color",
        "title-banner-color": "color",
        "theme": "string"
      };
      for (const node of ast.children) {
        if (node?.type !== "declaration") {
          continue;
        }
        const varName = node?.property?.variable?.value;
        if (namesToIgnore.has(varName)) {
          continue;
        }
        const varValue = node?.value?.value;
        if (declarationsToTrack.has(varName)) {
          const prevDeclaration = declarationsToTrack.get(varName);
          if (prevDeclaration?.value?.isDefault && node?.value?.isDefault) {
          } else if (!prevDeclaration?.value?.isDefault && !node?.value?.isDefault) {
            declarationsToTrack.set(varName, node);
          } else {
            if (speciallyKnownTypes[varName]) {
              node.valueType = speciallyKnownTypes[varName];
              declarationsToTrack.set(varName, node);
            }
          }
        } else {
          declarationsToTrack.set(varName, node);
        }
      }
      const valueTypeMap = {
        "number": "number",
        "boolean": "boolean",
        "string": "string",
        "dimension": "dimension",
        "percentage": "percentage",
        "identifier": "identifier",
        "color_hex": "color",
        "named_color": "color",
        "string_double": "string",
        "string_single": "string",
        "null": "color"
        // This is specific to our themes, and requires excluding 'title-banner-image' above
      };
      const functionTypeResolver = {
        "theme-contrast": (_3) => "color",
        "quote": (_3) => "string",
        "url": (_3) => "string",
        "tint-color": (_3) => "color",
        "shade-color": (_3) => "color",
        "lighten": (_3) => "color",
        "darken": (_3) => "color",
        "mix": (_3) => "color",
        "shift-color": (_3) => "color",
        "linear-gradient": (_3) => "image",
        "color-contrast": (_3) => "color",
        "translate3d": (_3) => "transform-function",
        "rotate": (_3) => "transform-function",
        "translate": (_3) => "transform-function",
        "scale": (_3) => "transform-function",
        "calc": (_3) => "calc-value",
        // this can be a number, percentage, or dimension, but we don't presently care
        "add": (_3) => "__unimplemented__",
        "subtract": (_3) => "__unimplemented__",
        "brightness": (_3) => "filter",
        "minmax": (_3) => "grid-template",
        "var": (valueNode) => "__unimplemented__",
        // This is used in bslib as an instance of the hack described here:
        // https://css-tricks.com/when-sass-and-new-css-features-collide/
        // it's truly atrocious and we'll never be able to track this kind of thing properly,
        // but we can at least make sure it doesn't break the rest of the analysis
        "Min": (_3) => "__unimplemented__",
        "theme-override-value": (valueNode) => {
          const defaultValue = valueNode?.arguments?.children[2];
          if (defaultValue && typeForValue(defaultValue)) {
            return typeForValue(defaultValue);
          } else {
            return void 0;
          }
        },
        "if": (valueNode) => {
          const _condition = valueNode?.arguments?.children[0];
          const trueValue = valueNode?.arguments?.children[1];
          const falseValue = valueNode?.arguments?.children[2];
          if (trueValue) {
            const trueType = typeForValue(trueValue);
            if (trueType) {
              return trueType;
            }
          }
          if (falseValue) {
            const falseType = typeForValue(falseValue);
            if (falseType) {
              return falseType;
            }
          }
          return void 0;
        }
      };
      const typeForValue = (valueNode) => {
        const nodeValueType = valueNode?.type;
        if (valueTypeMap[nodeValueType]) {
          return valueTypeMap[nodeValueType];
        }
        if (nodeValueType === "variable") {
          const nodeVariableName = valueNode?.value;
          if (!declarationsToTrack.has(nodeVariableName) && !namesToIgnore.has(nodeVariableName)) {
            console.log("Warning: variable used before declaration");
            console.log("variable: ", nodeVariableName, valueNode.line);
            return void 0;
          } else {
            const valueType = declarationsToTrack.get(nodeVariableName)?.valueType;
            if (valueType) {
              return valueType;
            }
          }
        }
        if (nodeValueType === "function") {
          const functionName = valueNode?.identifier?.value;
          if (functionTypeResolver[functionName]) {
            return functionTypeResolver[functionName](valueNode);
          }
        }
      };
      for (const [name2, node] of declarationsToTrack) {
        if (node?.value?.type === "value") {
          const valueType = node.value.value[0].valueType || typeForValue(node.value.value[0]);
          if (valueType) {
            node.valueType = valueType;
          }
        }
      }
      return declarationsToTrack;
    };
  }
});

// core/sass/analyzer/get-dependencies.ts
var assert8, getVariableDependencies;
var init_get_dependencies = __esm({
  "core/sass/analyzer/get-dependencies.ts"() {
    init_ast_utils();
    assert8 = (condition) => {
      if (!condition) {
        throw new Error("Assertion failed");
      }
    };
    getVariableDependencies = (declarations) => {
      const dependencies = /* @__PURE__ */ new Map();
      for (const [name2, node] of declarations) {
        assert8(node?.type === "declaration");
        const varName = node?.property?.variable?.value;
        assert8(varName === name2);
        if (!dependencies.has(varName)) {
          dependencies.set(varName, { node, dependencies: /* @__PURE__ */ new Set() });
        }
        const varValue = node?.value;
        walk3(varValue, (inner) => {
          if (inner?.type === "variable") {
            const innerName = inner?.value;
            if (!innerName) {
              console.log(inner);
              throw new Error("stop");
            }
            dependencies.get(varName).dependencies.add(innerName);
          }
          return true;
        });
      }
      return dependencies;
    };
  }
});

// core/sass/add-css-vars.ts
var getSassAst, decodeScssName, SCSSParsingError, cssVarsBlock;
var init_add_css_vars = __esm({
  "core/sass/add-css-vars.ts"() {
    init_scss_parser_1_0();
    init_parse8();
    init_clean_ast();
    init_declaration_types();
    init_get_dependencies();
    ({ getSassAst } = makeParserModule(parse$2));
    decodeScssName = (name2) => name2.replace(
      /_u([0-9a-f]+)_/g,
      (_3, hex) => String.fromCodePoint(parseInt(hex, 16))
    );
    SCSSParsingError = class extends Error {
      constructor(message) {
        super(`SCSS Parsing Error: ${message}`);
        this.name = "SCSSParsingError";
      }
    };
    cssVarsBlock = (scssSource) => {
      let astOriginal;
      try {
        astOriginal = getSassAst(scssSource);
      } catch (e5) {
        if (!(e5 instanceof Error)) throw e5;
        throw new SCSSParsingError(e5.message);
      }
      const ast = propagateDeclarationTypes(cleanSassAst(astOriginal));
      const deps = getVariableDependencies(ast);
      const output = [":root {"];
      for (const [dep, _3] of deps) {
        const decl = ast.get(dep);
        if (decl.valueType === "color") {
          const originalName = decodeScssName(dep);
          output.push(`--quarto-scss-export-${originalName}: #{$${originalName}};`);
        }
      }
      output.push("}");
      return output.join("\n");
    };
  }
});

// core/cache/cache.ts
var currentCacheVersion, requiredQuartoVersions2, ProjectCacheImpl, createProjectCache, memoizeStringFunction;
var init_cache3 = __esm({
  "core/cache/cache.ts"() {
    init_asserts();
    init_fs();
    init_path();
    init_hash2();
    init_mod6();
    init_quarto();
    currentCacheVersion = "1";
    requiredQuartoVersions2 = {
      "1": ">1.7.0"
    };
    ProjectCacheImpl = class {
      projectScratchDir;
      index;
      constructor(_projectScratchDir) {
        this.projectScratchDir = _projectScratchDir;
        this.index = null;
      }
      clone() {
        return this;
      }
      close() {
        if (this.index) {
          this.index.close();
          this.index = null;
        }
      }
      async clear() {
        assert7(this.index);
        const entries = this.index.list({ prefix: [] });
        for await (const entry of entries) {
          const diskValue = entry.value;
          if (entry.key[0] !== "version") {
            Deno.removeSync(
              join4(this.projectScratchDir, "project-cache", diskValue)
            );
          }
          await this.index.delete(entry.key);
        }
      }
      async createOnDisk() {
        assert7(this.index);
        this.index.set(["version"], currentCacheVersion);
      }
      async init() {
        const indexPath2 = join4(this.projectScratchDir, "project-cache");
        ensureDirSync(indexPath2);
        this.index = await Deno.openKv(join4(indexPath2, "deno-kv-file"));
        let version4 = await this.index.get(["version"]);
        if (version4.value === null) {
          await this.createOnDisk();
          version4 = await this.index.get(["version"]);
        }
        assert7(typeof version4.value === "string");
        const requiredVersion = requiredQuartoVersions2[version4.value];
        if (!requiredVersion || !satisfies(quartoConfig.version(), requiredVersion)) {
          console.warn("Unknown project cache version.");
          console.warn(
            "Project cache was likely created by a newer version of Quarto."
          );
          console.warn("Quarto will clear the project cache.");
          await this.clear();
          await this.createOnDisk();
        }
      }
      async addBuffer(key, value) {
        assert7(this.index);
        const hash = await md5HashBytes(value);
        Deno.writeFileSync(
          join4(this.projectScratchDir, "project-cache", hash),
          value
        );
        const result2 = await this.index.set(key, {
          hash,
          type: "buffer"
        });
        assert7(result2.ok);
      }
      async addString(key, value) {
        assert7(this.index);
        const buffer2 = new TextEncoder().encode(value);
        const hash = await md5HashBytes(buffer2);
        Deno.writeTextFileSync(
          join4(this.projectScratchDir, "project-cache", hash),
          value
        );
        const result2 = await this.index.set(key, {
          hash,
          type: "string"
        });
        assert7(result2.ok);
      }
      async addSmallBuffer(key, value) {
        assert7(this.index);
        const result2 = await this.index.set(key, {
          value,
          type: "buffer-immediate"
        });
        assert7(result2.ok);
      }
      async addSmallString(key, value) {
        assert7(this.index);
        const result2 = await this.index.set(key, {
          value,
          type: "string-immediate"
        });
        assert7(result2.ok);
      }
      async get(key) {
        assert7(this.index);
        const kvResult = await this.index.get(key);
        if (kvResult.value === null) {
          return null;
        }
        return kvResult.value;
      }
      async _getAs(key, getter) {
        assert7(this.index);
        const result2 = await this.get(key);
        if (result2 === null) {
          return null;
        }
        try {
          return getter(result2);
        } catch (e5) {
          if (!(e5 instanceof Deno.errors.NotFound)) {
            throw e5;
          }
          console.warn(
            `Entry ${result2} not found -- clearing entry in index`
          );
          await this.index.delete(key);
          return null;
        }
      }
      async getSmallString(key) {
        return this._getAs(key, (result2) => {
          assert7(result2.type === "string-immediate", "Expected string");
          return result2.value;
        });
      }
      async getSmallBuffer(key) {
        return this._getAs(key, (result2) => {
          assert7(result2.type === "buffer-immediate", "Expected buffer");
          return result2.value;
        });
      }
      async getBuffer(key) {
        return this._getAs(key, (result2) => {
          assert7(result2.type === "buffer", "Expected buffer");
          const { hash } = result2;
          return Deno.readFileSync(
            join4(this.projectScratchDir, "project-cache", hash)
          );
        });
      }
      async getString(key) {
        return this._getAs(key, (result2) => {
          assert7(result2.type === "string", "Expected string");
          const { hash } = result2;
          return Deno.readTextFileSync(
            join4(this.projectScratchDir, "project-cache", hash)
          );
        });
      }
      memoizeStringFunction(key, fn) {
        return async (param) => {
          const paramHash = await md5HashBytes(new TextEncoder().encode(param));
          const memoizationKey = [...key, paramHash];
          const cached = await this.getString(memoizationKey);
          if (cached !== null) {
            return cached;
          }
          const result2 = await fn(param);
          await this.addString(memoizationKey, result2);
          return result2;
        };
      }
    };
    createProjectCache = async (projectScratchDir) => {
      const result2 = new ProjectCacheImpl(projectScratchDir);
      await result2.init();
      return result2;
    };
    memoizeStringFunction = (key, fn) => {
      return async (project, param) => {
        return project.diskCache.memoizeStringFunction(
          key,
          fn
        )(param);
      };
    };
  }
});

// core/sass.ts
function sassVariable(name2, value, formatter) {
  return {
    name: name2,
    value: formatter ? formatter(value) : value
  };
}
function outputVariable(variable, isDefault = true) {
  return `$${variable.name}: ${variable.value}${isDefault ? " !default" : ""};`;
}
async function compileSass(bundles, project, minified = true) {
  const frameWorkUses = bundles.map(
    (bundle2) => bundle2.framework?.uses || ""
  );
  const frameworkFunctions = bundles.map(
    (bundle2) => bundle2.framework?.functions || ""
  );
  const frameworkDefaults = bundles.map(
    (bundle2) => bundle2.framework?.defaults || ""
  );
  const frameworkRules = bundles.map(
    (bundle2) => bundle2.framework?.rules || ""
  );
  const frameworkMixins = bundles.map(
    (bundle2) => bundle2.framework?.mixins || ""
  );
  const quartoUses2 = bundles.map((bundle2) => bundle2.quarto?.uses || "");
  const quartoFunctions2 = bundles.map(
    (bundle2) => bundle2.quarto?.functions || ""
  );
  const quartoDefaults2 = bundles.map((bundle2) => bundle2.quarto?.defaults || "");
  const quartoRules2 = bundles.map((bundle2) => bundle2.quarto?.rules || "");
  const quartoMixins = bundles.map((bundle2) => bundle2.quarto?.mixins || "");
  const userLayers = mergeLayers(
    ...bundles.map((bundle2) => bundle2.user || []).flat()
  );
  const userUses = userLayers.uses;
  const userFunctions = userLayers.functions;
  const userDefaults = userLayers.defaults;
  const userRules = userLayers.rules;
  const userMixins = userLayers.mixins;
  const loadPaths = [];
  bundles.forEach((bundle2) => {
    if (bundle2.loadPaths) {
      loadPaths.push(...bundle2.loadPaths);
    }
  });
  let scssInput = [
    `// quarto-scss-analysis-annotation { "quarto-version": "${quartoConfig.version()}" }`,
    `// quarto-scss-analysis-annotation { "origin": "'use' section from format" }`,
    ...frameWorkUses,
    `// quarto-scss-analysis-annotation { "origin": "'use' section from Quarto" }`,
    ...quartoUses2,
    `// quarto-scss-analysis-annotation { "origin": "'use' section from user-defined SCSS" }`,
    userUses,
    `// quarto-scss-analysis-annotation { "origin": "'functions' section from format" }`,
    ...frameworkFunctions,
    `// quarto-scss-analysis-annotation { "origin": "'functions' section from Quarto" }`,
    ...quartoFunctions2,
    `// quarto-scss-analysis-annotation { "origin": "'functions' section from user-defined SCSS" }`,
    userFunctions,
    '// quarto-scss-analysis-annotation { "origin": "Defaults from user-defined SCSS" }',
    userDefaults,
    `// quarto-scss-analysis-annotation { "origin": "Defaults from Quarto's SCSS" }`,
    ...quartoDefaults2.reverse(),
    '// quarto-scss-analysis-annotation { "origin": "Defaults from the format SCSS" }',
    ...frameworkDefaults.reverse(),
    `// quarto-scss-analysis-annotation { "origin": "'mixins' section from format" }`,
    ...frameworkMixins,
    `// quarto-scss-analysis-annotation { "origin": "'mixins' section from Quarto" }`,
    ...quartoMixins,
    `// quarto-scss-analysis-annotation { "origin": "'mixins' section from user-defined SCSS" }`,
    userMixins,
    `// quarto-scss-analysis-annotation { "origin": "'rules' section from format" }`,
    ...frameworkRules,
    `// quarto-scss-analysis-annotation { "origin": "'rules' section from Quarto" }`,
    ...quartoRules2,
    `// quarto-scss-analysis-annotation { "origin": "'rules' section from user-defined SCSS" }`,
    userRules,
    '// quarto-scss-analysis-annotation { "origin": null }'
  ].join("\n\n");
  const saveScssPrefix = Deno.env.get("QUARTO_SAVE_SCSS");
  if (saveScssPrefix) {
    const counterValue = counter++;
    Deno.writeTextFileSync(
      `${saveScssPrefix}-${counterValue}.scss`,
      scssInput
    );
  }
  const result2 = await compileWithCache(
    scssInput,
    loadPaths,
    project,
    {
      compressed: minified,
      cacheIdentifier: await md5HashBytes(new TextEncoder().encode(scssInput)),
      addVarsBlock: true
    }
  );
  if (saveScssPrefix) {
    const partialOutput = Deno.readTextFileSync(result2);
    const scssToWrite = [scssInput];
    const internalVars = Array.from(
      partialOutput.matchAll(/(--quarto-scss-export-[^;}]+;?)/g)
    ).map((m4) => m4[0]);
    const annotation = {
      "css-vars": internalVars
    };
    scssToWrite.push(
      `// quarto-scss-analysis-annotation ${JSON.stringify(annotation)}`
    );
    scssInput = scssToWrite.join("\n");
    Deno.writeTextFileSync(
      `${saveScssPrefix}-${counter - 1}.scss`,
      scssInput
    );
  }
  return result2;
}
function mergeLayers(...layers) {
  const themeUses = [];
  const themeDefaults = [];
  const themeRules = [];
  const themeFunctions = [];
  const themeMixins = [];
  layers.forEach((theme) => {
    if (theme.uses) {
      themeUses.push(theme.uses);
    }
    if (theme.defaults) {
      themeDefaults.push(theme.defaults);
    }
    if (theme.rules) {
      themeRules.push(theme.rules);
    }
    if (theme.functions) {
      themeFunctions.push(theme.functions);
    }
    if (theme.mixins) {
      themeMixins.push(theme.mixins);
    }
  });
  return {
    uses: themeUses.join("\n"),
    // We need to reverse the order of defaults
    // since defaults override one another by being
    // set first
    defaults: themeDefaults.reverse().join("\n"),
    functions: themeFunctions.join("\n"),
    mixins: themeMixins.join("\n"),
    rules: themeRules.join("\n")
  };
}
function sassLayer(path3) {
  if (Deno.statSync(path3).isFile) {
    return sassLayerFile(path3);
  } else {
    return sassLayerDir(
      path3,
      {
        uses: "_use.scss",
        functions: "_functions.scss",
        defaults: "_defaults.scss",
        mixins: "_mixins.scss",
        rules: "_rules.scss"
      }
    );
  }
}
function sassLayerFile(theme) {
  const rawContents = Deno.readTextFileSync(theme);
  return sassLayerStr(rawContents, theme);
}
function sassLayerStr(rawContents, errorHint) {
  if (!kLayerBoundaryTest.test(rawContents)) {
    throw new Error(
      `The file ${errorHint} doesn't contain at least one layer boundary (/*-- scss:defaults --*/, /*-- scss:rules --*/, /*-- scss:mixins --*/, /*-- scss:functions --*/, or /*-- scss:uses --*/)`
    );
  }
  const uses = [];
  const defaults = [];
  const rules = [];
  const functions = [];
  const mixins = [];
  let accum = defaults;
  lines(rawContents).forEach((line) => {
    const scopeMatch = line.match(kLayerBoundaryLine);
    if (scopeMatch) {
      const scope = scopeMatch[1];
      switch (scope) {
        case "uses":
          accum = uses;
          break;
        case "defaults":
          accum = defaults;
          break;
        case "rules":
          accum = rules;
          break;
        case "functions":
          accum = functions;
          break;
        case "mixins":
          accum = mixins;
          break;
      }
    } else {
      accum.push(line);
    }
  });
  return {
    uses: uses.join("\n"),
    defaults: defaults.join("\n"),
    rules: rules.join("\n"),
    mixins: mixins.join("\n"),
    functions: functions.join("\n")
  };
}
function sassLayerDir(dir, names) {
  const read = (path3) => {
    if (path3) {
      path3 = join4(dir, path3);
      if (existsSync2(path3)) {
        return Deno.readTextFileSync(path3);
      } else {
        return "";
      }
    } else {
      return "";
    }
  };
  return {
    uses: read(names.uses),
    defaults: read(names.defaults),
    rules: read(names.rules),
    mixins: read(names.mixins),
    functions: read(names.functions)
  };
}
async function compileWithCache(input, loadPaths, project, options) {
  const { temp } = project;
  const {
    compressed,
    cacheIdentifier,
    addVarsBlock
  } = options || {};
  const handleVarsBlock = async (input2) => {
    if (!addVarsBlock) {
      return input2;
    }
    try {
      const result2 = await memoizedGetVarsBlock(project, input2);
      return input2 + "\n" + result2;
    } catch (e5) {
      if (!(e5 instanceof Error)) throw e5;
      if (e5.name !== "SCSSParsingError") {
        throw e5;
      }
      console.warn("Error adding css vars block", e5);
      console.warn(
        "The resulting CSS file will not have SCSS color variables exported as CSS."
      );
      Deno.writeTextFileSync("_quarto_internal_scss_error.scss", input2);
      console.warn(
        "This is likely a Quarto bug.\nPlease consider reporting it at https://github.com/quarto-dev/quarto-cli,\nalong with the _quarto_internal_scss_error.scss file that can be found in the current working directory."
      );
    }
    return input2;
  };
  if (cacheIdentifier) {
    const useSessionCache = input.match(/@import/);
    const cacheDir = useSessionCache ? join4(temp.baseDir, "sass") : quartoCacheDir("sass");
    const cache3 = await sassCache(cacheDir, useSessionCache ? temp : void 0);
    return cache3.getOrSet(
      input,
      cacheIdentifier,
      async (outputFilePath) => {
        input = await handleVarsBlock(input);
        await dartCompile(input, outputFilePath, temp, loadPaths, compressed);
      }
    );
  } else {
    input = await handleVarsBlock(input);
    const outputFilePath = temp.createFile({ suffix: ".css" });
    await dartCompile(
      input,
      outputFilePath,
      temp,
      uniq(loadPaths),
      compressed
    );
    return outputFilePath;
  }
}
function cleanSourceMappingUrl(cssPath) {
  const cleaned = Deno.readTextFileSync(cssPath).replaceAll(
    kSourceMappingRegexes[0],
    ""
  ).replaceAll(
    kSourceMappingRegexes[1],
    ""
  );
  Deno.writeTextFileSync(cssPath, cleaned.trim(), {
    mode: safeModeFromFile(cssPath)
  });
}
var counter, layoutBoundary, kLayerBoundaryLine, kLayerBoundaryTest, memoizedGetVarsBlock;
var init_sass = __esm({
  "core/sass.ts"() {
    init_fs();
    init_path();
    init_appdirs();
    init_dart_sass();
    init_lodash();
    init_text2();
    init_cache2();
    init_add_css_vars();
    init_hash2();
    init_constants6();
    init_quarto();
    init_fs();
    init_cache3();
    counter = 1;
    layoutBoundary = "^/\\*\\-\\-[ \\t]*scss:(uses|functions|rules|defaults|mixins)[ \\t]*\\-\\-\\*\\/$";
    kLayerBoundaryLine = RegExp(layoutBoundary);
    kLayerBoundaryTest = RegExp(layoutBoundary, "m");
    memoizedGetVarsBlock = memoizeStringFunction([
      "core",
      "sass",
      "cssVarsBlock"
    ], (input) => Promise.resolve(cssVarsBlock(input)));
  }
});

// format/html/format-html-shared.ts
function insertFootnotesTitle(doc, footnotesEl, language, level = 2, classes = []) {
  prependHeading(
    doc,
    footnotesEl,
    language[kSectionTitleFootnotes],
    level,
    classes
  );
}
function insertReferencesTitle(doc, refsEl, language, level = 2, classes = []) {
  prependHeading(
    doc,
    refsEl,
    language[kSectionTitleReferences],
    level,
    classes
  );
}
function insertTitle(doc, el, title3, level = 2, headingClasses = []) {
  prependHeading(doc, el, title3, level, headingClasses);
}
function prependHeading(doc, el, title3, level, classes) {
  const heading = doc.createElement("h" + level);
  if (typeof title3 == "string" && title3 !== "none") {
    heading.innerHTML = title3;
  }
  if (classes) {
    classes.forEach((clz) => {
      heading.classList.add(clz);
    });
  }
  el.insertBefore(heading, el.firstChild);
  const hr = el.querySelector("hr");
  if (hr) {
    hr.remove();
  }
}
function removeFootnoteBacklinks(footnotesEl) {
  const backlinks = footnotesEl.querySelectorAll(".footnote-back");
  for (const backlink of backlinks) {
    backlink.remove();
  }
}
function setMainColumn(doc, column) {
  const selectors = [
    "main.content",
    ".page-navigation",
    ".quarto-title-banner .quarto-title",
    ".quarto-title-block .quarto-title-meta-author",
    ".quarto-title-block .quarto-title-meta",
    "div[class^='quarto-about-']",
    "div[class*=' quarto-about-']"
  ];
  selectors.forEach((selector) => {
    const el = doc.querySelector(selector);
    if (el) {
      for (const clz of el.classList) {
        if (clz.startsWith("column-")) {
          el.classList.remove(clz);
        }
      }
      el.classList.add(column);
    }
  });
}
function hasMarginRefs(format14, flags) {
  return format14.pandoc[kReferenceLocation] === "margin" || flags[kReferenceLocation] === "margin";
}
function hasMarginCites(format14) {
  return format14.metadata[kCitationLocation] === "margin";
}
function hasMarginFigCaps(format14) {
  return format14.metadata[kFigCapLoc] === "margin";
}
function createCodeCopyButton(doc, format14) {
  const copyButton = doc.createElement("button");
  const title3 = format14.language[kCopyButtonTooltip];
  copyButton.setAttribute("title", title3);
  copyButton.classList.add("code-copy-button");
  const copyIcon = doc.createElement("i");
  copyIcon.classList.add("bi");
  copyButton.appendChild(copyIcon);
  return copyButton;
}
function createCodeBlock(doc, htmlContents, language) {
  const preEl = doc.createElement("PRE");
  preEl.classList.add("sourceCode");
  preEl.classList.add("code-with-copy");
  const codeEl = doc.createElement("CODE");
  codeEl.classList.add("sourceCode");
  if (language) {
    codeEl.classList.add(language);
  }
  codeEl.innerHTML = htmlContents;
  preEl.appendChild(codeEl);
  return preEl;
}
function writeMetaTag(name2, content, doc) {
  const m4 = doc.createElement("META");
  if (name2.startsWith("og:")) {
    m4.setAttribute("property", name2);
  } else {
    m4.setAttribute("name", name2);
  }
  m4.setAttribute("content", content);
  const nl = doc.createTextNode("\n");
  doc.querySelector("head")?.appendChild(m4);
  doc.querySelector("head")?.appendChild(nl);
}
function writeLinkTag(rel, href, doc) {
  const l6 = doc.createElement("LINK");
  l6.setAttribute("rel", rel);
  l6.setAttribute("href", href);
  const nl = doc.createTextNode("\n");
  doc.querySelector("head")?.appendChild(l6);
  doc.querySelector("head")?.appendChild(nl);
}
function formatPageLayout(format14) {
  return format14.metadata[kPageLayout] || kPageLayoutArticle;
}
function formatHasFullLayout(format14) {
  return format14.metadata[kPageLayout] === kPageLayoutFull;
}
function formatHasArticleLayout(format14) {
  return format14.metadata[kPageLayout] === void 0 || format14.metadata[kPageLayout] === kPageLayoutArticle || format14.metadata[kPageLayout] === kPageLayoutFull;
}
var kTabsets, kCodeCopy, kAnchorSections, kCitationsHover, kFootnotesHover, kXrefsHover, kSmoothScroll, kCodeAnnotations, kMinimal, kPageLayout, kPageLayoutArticle, kPageLayoutCustom, kPageLayoutFull, kComments, kHypothesis, kUtterances, kGiscus, kAxe, kGiscusRepoId, kGiscusCategoryId, kDraft, kAppendixStyle, kAppendixCiteAs, kLicense, kCopyright, kCitation, kDocumentCss, kBootstrapDependencyName, clipboardDependency, bootstrapFunctions, bootstrapMixins, bootstrapVariables, bootstrapRules, bslibComponentMixins, bslibComponentRules, htmlToolsRules, bootstrapResourceDir, bslibResourceDir, sassUtilFunctions, quartoRules, quartoCopyCodeDefaults, quartoCopyCodeRules, quartoLinkExternalRules, quartoCodeFilenameRules, quartoTabbyRules, quartoFigResponsiveRules, quartoGlobalCssVariableRules, quartoBootstrapCustomizationLayer, quartoBootstrapRules, quartoBootstrapMixins, quartoBootstrapFunctions, quartoBaseLayer, quartoVariables, quartoUses, quartoFunctions, quartoDefaults;
var init_format_html_shared = __esm({
  "format/html/format-html-shared.ts"() {
    init_path();
    init_sass();
    init_constants6();
    init_resources2();
    init_path2();
    kTabsets = "tabsets";
    kCodeCopy = "code-copy";
    kAnchorSections = "anchor-sections";
    kCitationsHover = "citations-hover";
    kFootnotesHover = "footnotes-hover";
    kXrefsHover = "crossrefs-hover";
    kSmoothScroll = "smooth-scroll";
    kCodeAnnotations = "code-annotations";
    kMinimal = "minimal";
    kPageLayout = "page-layout";
    kPageLayoutArticle = "article";
    kPageLayoutCustom = "custom";
    kPageLayoutFull = "full";
    kComments = "comments";
    kHypothesis = "hypothesis";
    kUtterances = "utterances";
    kGiscus = "giscus";
    kAxe = "axe";
    kGiscusRepoId = "repo-id";
    kGiscusCategoryId = "category-id";
    kDraft = "draft";
    kAppendixStyle = "appendix-style";
    kAppendixCiteAs = "appendix-cite-as";
    kLicense = "license";
    kCopyright = "copyright";
    kCitation = "citation";
    kDocumentCss = "document-css";
    kBootstrapDependencyName = "bootstrap";
    clipboardDependency = () => {
      const dependency = { name: "clipboard" };
      dependency.scripts = [];
      dependency.scripts.push({
        name: "clipboard.min.js",
        path: formatResourcePath("html", join4("clipboard", "clipboard.min.js"))
      });
      return dependency;
    };
    bootstrapFunctions = () => {
      return Deno.readTextFileSync(
        join4(bootstrapResourceDir(), "_functions.scss")
      );
    };
    bootstrapMixins = () => {
      return Deno.readTextFileSync(
        join4(bootstrapResourceDir(), "_mixins.scss")
      );
    };
    bootstrapVariables = () => {
      return Deno.readTextFileSync(
        join4(bootstrapResourceDir(), "_variables.scss")
      );
    };
    bootstrapRules = () => {
      return Deno.readTextFileSync(
        join4(bootstrapResourceDir(), "bootstrap.scss")
      );
    };
    bslibComponentMixins = () => {
      const bootstrapDistDir = formatResourcePath(
        "html",
        "bslib"
      );
      const mixinsDir = join4(bootstrapDistDir, "components", "scss", "mixins");
      return Deno.readTextFileSync(join4(mixinsDir, "_mixins.scss"));
    };
    bslibComponentRules = () => {
      const bslibDistDir = formatResourcePath(
        "html",
        join4("bslib")
      );
      const bslibDirs = [
        join4(bslibDistDir, "bslib-scss"),
        join4(bslibDistDir, "components", "scss")
      ];
      const scss = [];
      for (const bsLibDir of bslibDirs) {
        for (const walk5 of Deno.readDirSync(bsLibDir)) {
          if (walk5.isFile) {
            const contents = Deno.readTextFileSync(join4(bsLibDir, walk5.name));
            scss.push(contents);
          }
        }
      }
      return scss.join("\n");
    };
    htmlToolsRules = () => {
      const htmlToolsDir = formatResourcePath(
        "html",
        join4("htmltools")
      );
      const fillCss = Deno.readTextFileSync(join4(htmlToolsDir, "fill.css"));
      return fillCss;
    };
    bootstrapResourceDir = () => {
      return formatResourcePath(
        "html",
        join4("bootstrap", "dist", "scss")
      );
    };
    bslibResourceDir = () => {
      return formatResourcePath(
        "html",
        join4("bslib", "bslib-scss")
      );
    };
    sassUtilFunctions = (name2) => {
      const bootstrapDistDir = formatResourcePath(
        "html",
        join4("bootstrap", "dist")
      );
      const path3 = join4(bootstrapDistDir, "sass-utils", name2);
      return Deno.readTextFileSync(path3);
    };
    quartoRules = () => Deno.readTextFileSync(formatResourcePath(
      "html",
      "_quarto-rules.scss"
    ));
    quartoCopyCodeDefaults = () => Deno.readTextFileSync(formatResourcePath(
      "html",
      "_quarto-variables-copy-code.scss"
    ));
    quartoCopyCodeRules = () => Deno.readTextFileSync(formatResourcePath(
      "html",
      "_quarto-rules-copy-code.scss"
    ));
    quartoLinkExternalRules = () => Deno.readTextFileSync(formatResourcePath(
      "html",
      "_quarto-rules-link-external.scss"
    ));
    quartoCodeFilenameRules = () => Deno.readTextFileSync(formatResourcePath(
      "html",
      "_quarto-rules-code-filename.scss"
    ));
    quartoTabbyRules = () => Deno.readTextFileSync(formatResourcePath(
      "html",
      "_quarto-rules-tabby.scss"
    ));
    quartoFigResponsiveRules = () => {
      return [
        ".img-fluid {",
        "  max-width: 100%;",
        "  height: auto;",
        "}"
      ].join("\n");
    };
    quartoGlobalCssVariableRules = () => {
      return `
  $font-family-monospace: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace !default;
  /*! quarto-variables-start */
  :root {
    --quarto-font-monospace: #{inspect($font-family-monospace)};
  }
  /*! quarto-variables-end */
  `;
    };
    quartoBootstrapCustomizationLayer = () => {
      const path3 = formatResourcePath(
        "html",
        join4("bootstrap", "_bootstrap-customize.scss")
      );
      return sassLayer(path3);
    };
    quartoBootstrapRules = () => Deno.readTextFileSync(formatResourcePath(
      "html",
      join4("bootstrap", "_bootstrap-rules.scss")
    ));
    quartoBootstrapMixins = () => Deno.readTextFileSync(formatResourcePath(
      "html",
      join4("bootstrap", "_bootstrap-mixins.scss")
    ));
    quartoBootstrapFunctions = () => Deno.readTextFileSync(formatResourcePath(
      "html",
      join4("bootstrap", "_bootstrap-functions.scss")
    ));
    quartoBaseLayer = (format14, codeCopy = false, tabby = false, figResponsive = false, codeFilename = false) => {
      const rules = [quartoRules()];
      const defaults = [quartoDefaults(format14), quartoVariables()];
      if (codeCopy) {
        rules.push(quartoCopyCodeRules());
        defaults.push(quartoCopyCodeDefaults());
      }
      if (tabby) {
        rules.push(quartoTabbyRules());
      }
      if (figResponsive) {
        rules.push(quartoFigResponsiveRules());
      }
      if (codeFilename) {
        rules.push(quartoCodeFilenameRules());
      }
      if (format14.render[kLinkExternalIcon]) {
        rules.push(quartoLinkExternalRules());
      }
      return {
        uses: quartoUses(),
        defaults: defaults.join("\n"),
        functions: quartoFunctions(),
        mixins: "",
        rules: rules.join("\n")
      };
    };
    quartoVariables = () => Deno.readTextFileSync(formatResourcePath(
      "html",
      "_quarto-variables.scss"
    ));
    quartoUses = () => Deno.readTextFileSync(formatResourcePath(
      "html",
      "_quarto-uses.scss"
    ));
    quartoFunctions = () => Deno.readTextFileSync(formatResourcePath(
      "html",
      "_quarto-functions.scss"
    ));
    quartoDefaults = (format14) => {
      const defaults = [];
      defaults.push(
        outputVariable(
          sassVariable(
            "code-copy-selector",
            format14.metadata[kCodeCopy] === void 0 || format14.metadata[kCodeCopy] === "hover" ? '"div.code-copy-outer-scaffold:hover > "' : '""'
          )
        )
      );
      defaults.push(
        outputVariable(
          sassVariable(
            "code-white-space",
            format14.render[kCodeOverflow] === "wrap" ? "pre-wrap" : "pre"
          )
        )
      );
      defaults.push(
        outputVariable(
          sassVariable(
            kTblCapLoc,
            format14.metadata[kTblCapLoc] || format14.metadata[kCapLoc] || kCapTop
          )
        )
      );
      return defaults.join("\n");
    };
  }
});

// format/jats/format-jats-types.ts
function jatsTagset(to) {
  return kTagSets[to];
}
function jatsDtd(tagset) {
  return kDJatsDtds[tagset];
}
function xmlPlaceholder(token, input) {
  return `<!-- (F2ED4C6E)[${token}]:${input} -->`;
}
var kJatsSubarticle, kLintXml, kSubArticles, kTagSets, kDJatsDtds;
var init_format_jats_types = __esm({
  "format/jats/format-jats-types.ts"() {
    kJatsSubarticle = "jats-subarticle";
    kLintXml = "_lint-jats-xml-output";
    kSubArticles = "subarticles";
    kTagSets = {
      "jats": "archiving",
      "jats_archiving": "archiving",
      "jats_publishing": "publishing",
      "jats_articleauthoring": "authoring"
    };
    kDJatsDtds = {
      "archiving": {
        name: "-//NLM//DTD JATS (Z39.96) Journal Archiving and Interchange DTD v1.2 20190208//EN",
        location: "JATS-archivearticle1.dtd"
      },
      "publishing": {
        name: "-//NLM//DTD JATS (Z39.96) Journal Publishing DTD v1.2 20190208//EN",
        location: "JATS-publishing1.dtd"
      },
      "authoring": {
        name: "-//NLM//DTD JATS (Z39.96) Article Authoring DTD v1.2 20190208//EN",
        location: "JATS-articleauthoring1.dtd"
      }
    };
  }
});

// core/safe-clone-deep.ts
function safeCloneDeep(obj) {
  if (obj === null || typeof obj !== "object") {
    return obj;
  }
  if (Array.isArray(obj)) {
    return obj.map((item) => safeCloneDeep(item));
  }
  if (obj && "clone" in obj && typeof obj.clone === "function") {
    return obj.clone();
  }
  if (obj instanceof Map) {
    const clonedMap = /* @__PURE__ */ new Map();
    for (const [key, value] of obj.entries()) {
      clonedMap.set(key, safeCloneDeep(value));
    }
    return clonedMap;
  }
  if (obj instanceof Set) {
    const clonedSet = /* @__PURE__ */ new Set();
    for (const value of obj.values()) {
      clonedSet.add(safeCloneDeep(value));
    }
    return clonedSet;
  }
  const result2 = {};
  for (const key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      result2[key] = safeCloneDeep(obj[key]);
    }
  }
  return result2;
}
var init_safe_clone_deep = __esm({
  "core/safe-clone-deep.ts"() {
  }
});

// format/formats-shared.ts
function createFormat(displayName, ext, ...formats2) {
  return mergeConfigs(
    defaultFormat(displayName),
    ...formats2,
    {
      render: {
        [kOutputExt]: ext
      }
    }
  );
}
function createHtmlFormat(displayName, figwidth, figheight) {
  return createFormat(displayName, "html", {
    metadata: {
      [kLang]: "en",
      [kFigResponsive]: true,
      [kQuartoVersion]: quartoConfig.version()
    },
    execute: {
      [kFigFormat]: "retina",
      [kFigWidth]: figwidth,
      [kFigHeight]: figheight
    },
    render: {
      [kTblColwidths]: "auto"
    },
    pandoc: {
      [kStandalone]: true,
      [kWrap]: "none",
      [kDefaultImageExtension]: "png"
    }
  });
}
function createHtmlPresentationFormat(displayName, figwidth, figheight) {
  return mergeConfigs(
    createHtmlFormat(displayName, figwidth, figheight),
    {
      metadata: {
        [kFigResponsive]: false
      },
      execute: {
        [kEcho]: false,
        [kWarning]: false
      }
    }
  );
}
function createEbookFormat(displayName, ext) {
  return createFormat(displayName, ext, {
    formatExtras: () => {
      return {
        [kIncludeInHeader]: [
          formatResourcePath("html", "styles-callout.html"),
          formatResourcePath("epub", "styles.html")
        ]
      };
    },
    render: {
      [kMergeIncludes]: false
    },
    execute: {
      [kFigWidth]: 5,
      [kFigHeight]: 4
    },
    pandoc: {
      [kDefaultImageExtension]: "png"
    }
  });
}
function createWordprocessorFormat(displayName, ext) {
  return createFormat(displayName, ext, {
    render: {
      [kPageWidth]: 6.5
    },
    execute: {
      [kFigWidth]: 5,
      [kFigHeight]: 4
    },
    pandoc: {
      [kDefaultImageExtension]: "png"
    }
  });
}
function plaintextFormat(displayName, ext) {
  return createFormat(displayName, ext, {
    pandoc: {
      standalone: true,
      [kDefaultImageExtension]: "png"
    }
  });
}
function defaultFormat(displayName) {
  return {
    identifier: {
      [kDisplayName]: displayName
    },
    execute: {
      [kFigWidth]: 7,
      [kFigHeight]: 5,
      [kFigFormat]: "png",
      [kFigDpi]: 96,
      [kFigAsp]: void 0,
      [kMermaidFormat]: void 0,
      [kDfPrint]: "default",
      [kError]: false,
      [kEval]: true,
      [kCache]: null,
      [kFreeze]: false,
      [kEcho]: true,
      [kOutput]: true,
      [kWarning]: true,
      [kInclude]: true,
      [kKeepMd]: false,
      [kKeepIpynb]: false,
      [kExecuteIpynb]: null,
      [kExecuteEnabled]: null,
      [kExecuteDaemon]: null,
      [kExecuteDaemonRestart]: false,
      [kExecuteDebug]: false,
      [kIpynbFilters]: [],
      [kIpynbShellInteractivity]: null,
      [kPlotlyConnected]: true
    },
    render: {
      [kKeepTex]: false,
      [kKeepTyp]: false,
      [kKeepSource]: false,
      [kKeepHidden]: false,
      [kPreferHtml]: false,
      [kOutputDivs]: true,
      [kOutputExt]: "html",
      [kFigAlign]: "default",
      [kFigPos]: null,
      [kFigEnv]: null,
      [kCodeFold]: "none",
      [kCodeOverflow]: "scroll",
      [kCodeLink]: false,
      [kCodeLineNumbers]: false,
      [kCodeTools]: false,
      [kTblColwidths]: true,
      [kMergeIncludes]: true,
      [kInlineIncludes]: false,
      [kPreserveYaml]: false,
      [kLatexAutoMk]: true,
      [kLatexAutoInstall]: true,
      [kLatexClean]: true,
      [kLatexMinRuns]: 1,
      [kLatexMaxRuns]: 10,
      [kLatexMakeIndex]: "makeindex",
      [kLatexMakeIndexOpts]: [],
      [kLatexTlmgrOpts]: [],
      [kLatexInputPaths]: [],
      [kLatexOutputDir]: null,
      [kLinkExternalIcon]: false,
      [kLinkExternalNewwindow]: false,
      [kSelfContainedMath]: false,
      [kFormatResources]: [],
      [kVariant]: ""
    },
    pandoc: {},
    language: {},
    metadata: {}
  };
}
var init_formats_shared = __esm({
  "format/formats-shared.ts"() {
    init_config2();
    init_constants6();
    init_resources2();
    init_quarto();
  }
});

// format/markdown/format-markdown.ts
function requiresShortcodeUnescapePostprocessor(markdown) {
  return markdown.includes("{{{<");
}
function shortcodeUnescapePostprocessor(output) {
  Deno.writeTextFileSync(
    output,
    Deno.readTextFileSync(output).replaceAll("{{\\<", "{{<").replaceAll("\\>}}", ">}}")
  );
  return Promise.resolve();
}
function gfmFormat() {
  return createFormat(kDisplayNameGFM, "md", markdownFormat(kDisplayNameGFM), {
    pandoc: {
      to: "commonmark"
    },
    render: {
      [kVariant]: kGfmCommonmarkVariant
    },
    resolveFormat: (format14) => {
      if (format14.pandoc[kToc] === true) {
        format14.pandoc[kFrom] = pandocFormat(
          format14.pandoc[kFrom] || "markdown",
          ["gfm_auto_identifiers"],
          []
        );
      }
    }
  });
}
function markdownWithCommonmarkExtensionsFormat() {
  return createFormat(
    kDisplayNameCommonMark,
    "md",
    markdownFormat(kDisplayNameCommonMark),
    {
      pandoc: {
        to: [
          "markdown_strict",
          "+raw_html",
          "+all_symbols_escapable",
          "+backtick_code_blocks",
          "+fenced_code_blocks",
          "+space_in_atx_header",
          "+intraword_underscores",
          "+lists_without_preceding_blankline",
          "+shortcut_reference_links"
        ].join("")
      }
    }
  );
}
function commonmarkFormat(to) {
  return createFormat(
    kDisplayNameCommonMark,
    "md",
    markdownFormat(kDisplayNameCommonMark),
    {
      pandoc: {
        to
      }
    }
  );
}
function pandocMarkdownFormat() {
  return createFormat(
    kDisplayNameMarkdown,
    "md",
    plaintextFormat(kDisplayNameMarkdown, "md"),
    {}
  );
}
function markdownFormat(displayName) {
  return createFormat(displayName, "md", plaintextFormat(displayName, "md"), {
    // markdown shouldn't include cell divs (even if it
    // technically supports raw html)
    render: {
      [kOutputDivs]: false
    }
  });
}
var kDisplayNameGFM, kDisplayNameCommonMark, kDisplayNameMarkdown;
var init_format_markdown = __esm({
  "format/markdown/format-markdown.ts"() {
    init_constants6();
    init_pandoc_formats();
    init_formats_shared();
    init_format_markdown_consts();
    kDisplayNameGFM = "Github (GFM)";
    kDisplayNameCommonMark = "CommonMark";
    kDisplayNameMarkdown = "Markdown";
  }
});

// format/ipynb/format-ipynb.ts
function ipynbTitleTemplatePath() {
  return formatResourcePath(
    "ipynb",
    join4("templates", "title-block.md")
  );
}
function ipynbFormat() {
  return createFormat("Jupyter", "ipynb", {
    pandoc: {
      standalone: true,
      [kDefaultImageExtension]: "png"
    },
    formatExtras: (input, _markdown, _flags, format14) => {
      const resolveTemplate2 = () => {
        const titleTemplate = ipynbTitleTemplatePath();
        const partials = readPartials(format14.metadata, dirname4(input));
        if (partials.length > 0) {
          const userTitleTemplate = partials.find((part) => {
            return basename4(part) === "title-block.md";
          });
          if (userTitleTemplate) {
            return userTitleTemplate;
          } else {
            return titleTemplate;
          }
        } else {
          return titleTemplate;
        }
      };
      return {
        metadata: {
          [kIPynbTitleBlockTemplate]: resolveTemplate2()
        },
        postprocessors: [(output) => {
          const nb = jupyterFromFile(output);
          const widgets = nb.metadata.widgets;
          if (widgets && typeof widgets === "string") {
            nb.metadata.widgets = JSON.parse(
              new TextDecoder().decode(decodeBase64(widgets))
            );
          }
          nb.cells = nb.cells.map((cell) => {
            if (cell.cell_type == "raw") {
              if (cell.metadata[kCellFormat]) {
                const format15 = cell.metadata[kCellFormat];
                delete cell.metadata[kCellFormat];
                if (format15 === kTextHtml) {
                  cell.metadata[kCellRawMimeType] = format15;
                } else if (format15 === "tex") {
                  cell.metadata[kCellRawMimeType] = kTextLatex;
                } else if (format15 === "rst") {
                  cell.metadata[kCellRawMimeType] = kRestructuredText;
                } else if (format15 === "rtf") {
                  cell.metadata[kCellRawMimeType] = kApplicationRtf;
                } else {
                  cell.metadata[kCellFormat] = format15;
                }
              }
            }
            cell.outputs?.forEach((output2) => {
              const cellOutput = output2;
              if (cellOutput.output_type === "display_data") {
                const cellDisplayOutput = cellOutput;
                if (cellDisplayOutput.data["application/json"]) {
                  const jsonData = cellDisplayOutput.data["application/json"];
                  if (jsonData[kQuartoMimeType]) {
                    const realMimetype = jsonData[kQuartoMimeType];
                    delete jsonData[kQuartoMimeType];
                    cellDisplayOutput.data[realMimetype] = jsonData;
                    delete cellDisplayOutput.data["application/json"];
                  }
                }
              }
            });
            return cell;
          });
          Deno.writeTextFileSync(output, JSON.stringify(nb, null, 2));
          return Promise.resolve();
        }]
      };
    }
  });
}
var init_format_ipynb = __esm({
  "format/ipynb/format-ipynb.ts"() {
    init_path();
    init_template();
    init_constants6();
    init_jupyter();
    init_mime();
    init_resources2();
    init_formats_shared();
    init_base64();
  }
});

// render/notebook/notebook-types.ts
var kHtmlPreview, kJatsSubarticle2, kRenderedIPynb, kQmdIPynb;
var init_notebook_types = __esm({
  "render/notebook/notebook-types.ts"() {
    kHtmlPreview = "html-preview";
    kJatsSubarticle2 = "jats-subarticle";
    kRenderedIPynb = "rendered-ipynb";
    kQmdIPynb = "qmd-ipynb";
  }
});

// core/cache.ts
function cacheMap(f5) {
  const map3 = /* @__PURE__ */ new Map();
  return async (key) => {
    if (!map3.has(key)) {
      map3.set(key, await f5(key));
    }
    return map3.get(key);
  };
}
var init_cache4 = __esm({
  "core/cache.ts"() {
  }
});

// core/language.ts
function escapeRegExp2(str3) {
  return str3.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
async function readLanguageTranslations(translationFile, lang) {
  const files = [];
  const {
    file,
    language
  } = await translationCache(translationFile);
  if (file) {
    files.push(file);
  }
  const ext = extname4(translationFile);
  let [dir, stem] = dirAndStem(translationFile);
  stem = escapeRegExp2(stem);
  const variations = [];
  if (lang) {
    const subtags = lang.split("-");
    for (let i6 = 0; i6 < subtags.length; i6++) {
      variations.push(subtags.slice(0, i6 + 1).join("-"));
    }
  } else {
    const glob = stem + "-*" + ext;
    const variationRe = new RegExp(
      "^" + stem + "-(.*?)" + ext
    );
    for (const entry of expandGlobSync(glob, {
      root: dir,
      includeDirs: false,
      caseInsensitive: true
    })) {
      const match = entry.name.match(variationRe);
      if (match) {
        variations.push(match[1]);
      }
    }
  }
  for (const variation of variations) {
    const {
      file: variationFile,
      language: translations
    } = await translationCache(join4(dir, stem + "-" + variation + ext));
    if (variationFile) {
      files.push(variationFile);
    }
    Object.keys(translations).forEach((key) => {
      if (kLanguageDefaultsKeys.includes(key)) {
        language[variation] = language[variation] || {};
        language[variation][key] = translations[key];
      } else if (typeof translations[key] === "object") {
        const targetKey = variation + "-" + key;
        language[targetKey] = language[targetKey] || {};
        language[targetKey] = {
          ...language[targetKey],
          ...translations[key]
        };
      }
    });
  }
  return { language, files };
}
function readDefaultLanguageTranslations(lang) {
  return readLanguageTranslations(
    resourcePath(join4("language", "_language.yml")),
    lang
  );
}
async function resolveLanguageMetadata(metadata, dir) {
  if (typeof metadata[kLanguageDefaults] === "string") {
    const translationsFile = join4(dir, metadata[kLanguageDefaults]);
    if (!existsSync2(translationsFile)) {
      throw new Error(
        "Specified 'language' file does not exist: " + translationsFile
      );
    }
    const translations = await readLanguageTranslations(translationsFile);
    metadata[kLanguageDefaults] = translations.language;
    return translations.files;
  } else if (typeof metadata[kLanguageDefaults] !== "object") {
    metadata[kLanguageDefaults] = {};
    return [];
  } else {
    return [];
  }
}
function translationsForLang(language, lang) {
  let translations = {};
  Object.keys(language).forEach((key) => {
    if (kLanguageDefaultsKeys.includes(key) || key.match(/^crossref-.*-title$/) || key.match(/^crossref-.*-prefix$/)) {
      translations[key] = language[key];
    }
  });
  const subtags = lang.split("-");
  for (let i6 = 0; i6 < subtags.length; i6++) {
    const variation = subtags.slice(0, i6 + 1).join("-");
    if (typeof language[variation] === "object") {
      translations = mergeConfigs(
        translations,
        language[variation]
      );
    }
  }
  return translations;
}
async function formatLanguage(metadata, language, flags) {
  const langCode = flags?.pandocMetadata?.[kLang] || metadata[kLang] || "en";
  const defaultLanguage = translationsForLang(
    (await readDefaultLanguageTranslations(langCode)).language,
    langCode
  );
  language = mergeConfigs(defaultLanguage, language);
  return translationsForLang(language, langCode);
}
var translationCache;
var init_language = __esm({
  "core/language.ts"() {
    init_fs();
    init_path();
    init_constants6();
    init_path2();
    init_resources2();
    init_config2();
    init_validated_yaml2();
    init_schema();
    init_cache4();
    translationCache = cacheMap(
      async (file) => {
        if (existsSync2(file)) {
          const errMsg = "Validation of format language object failed.";
          const formatLanguageSchema = getSchemaDefinition("format-language");
          const result2 = await readAndValidateYamlFromFile(
            file,
            formatLanguageSchema,
            errMsg
          );
          return {
            file: normalizePath(file),
            language: result2
          };
        } else {
          return {
            language: {}
          };
        }
      }
    );
  }
});

// project/types/confluence/confluence.ts
var buildConfluenceFiles;
var init_confluence = __esm({
  "project/types/confluence/confluence.ts"() {
    buildConfluenceFiles = () => {
      const file = [
        {
          name: "index",
          content: `This project provides provides a simple scaffold for creating a Quarto Confluence Project. You'll almost certainly want to remove the sample files, they are just here as examples. When you add you own documents (including ones in subfolders) they will be automatically added to the site navigation sidebar.`,
          title: "Example"
        },
        {
          name: "project-roadmap",
          content: `## Overview

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla id accumsan justo. Nulla ut lectus efficitur, aliquet tellus elementum, hendrerit mi. Aenean risus purus, finibus eu consectetur sit amet, maximus ut tortor. Vivamus congue mollis ante in interdum. In at semper turpis, sed faucibus arcu. Nullam ultrices, neque nec mattis dictum, risus ante mattis diam, sit amet sagittis arcu ante ut urna.

Quisque cursus eros dictum justo varius condimentum a ac risus. Vestibulum sodales, quam quis dignissim scelerisque, tellus turpis mollis sapien, tempor lacinia quam elit at urna. Etiam pharetra sapien at tristique tincidunt. Duis vitae lectus nisl. Proin pharetra, ante a iaculis interdum, lectus massa tempor leo, eu luctus lorem sapien vel sem. Morbi vitae tincidunt libero, eget tincidunt quam.

## Key Milestones

Donec elementum a neque a rutrum. Nulla a quam in eros ornare fringilla at eget mi. Sed dui dolor, porta mollis auctor in, finibus vel tellus. Nunc quis ipsum sit amet magna vulputate tincidunt. Vivamus eget ornare dolor, eget rhoncus purus.

Praesent ac mauris quis magna placerat hendrerit. Fusce viverra nulla nec urna pulvinar semper.

Nunc sit amet libero ut ligula venenatis volutpat. Integer scelerisque iaculis lacus, et ornare velit placerat nec.

Phasellus nisi ante, dignissim quis metus nec, consequat bibendum lacus.`,
          title: "Project Roadmap"
        },
        {
          name: "2022-01",
          subdirectory: "reports",
          title: "January 2022",
          content: "## Project Status\nFusce tristique, elit vel tincidunt vehicula, est tortor laoreet sem, nec sagittis ipsum nisl eget ipsum. Ut fringilla facilisis tincidunt:\n\n1. Cras fermentum sagittis tincidunt. Vestibulum nunc nisi, consequat sed nunc vitae, mollis sodales urna.\n2. Curabitur venenatis, sem sed sodales fermentum, ante mauris posuere nisl, eu pretium velit magna a ex. Duis malesuada vitae nisl sit amet aliquam.\n3. Nullam scelerisque condimentum leo in convallis. Phasellus eu mauris enim.\n\nSed volutpat orci eu ligula gravida, et congue lacus efficitur. Vivamus eget mi nisl. Nam tristique eros nec elit commodo, at vehicula purus venenatis. Donec imperdiet interdum erat at dignissim. Nullam odio ante, pellentesque id commodo et, sodales eget diam.\n\n## Challenges and Opportunities\nIn scelerisque non dolor at congue. Donec neque lorem, consectetur sed consectetur ut, pulvinar sit amet justo. Donec at mi erat. Maecenas luctus sem orci, eu ullamcorper arcu porta sed. Nam dapibus risus ligula, non tempor leo convallis vel. Mauris pretium, arcu ut bibendum egestas, nisi tellus cursus tortor, vel interdum turpis ipsum in nisi.\n\nAliquam ac egestas mi. Nulla ut porttitor justo. Proin id fermentum nunc:\n\n1. In odio justo, scelerisque at augue at, blandit rhoncus nibh.\n2. Mauris ut tristique elit. Suspendisse pretium tempor mauris non luctus.\n3. Mauris posuere nulla purus, quis dapibus urna suscipit ac.\n\nLorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam at risus blandit, aliquet leo sed, pretium lectus. Vivamus in tortor in velit consequat sodales. Integer eleifend dictum vestibulum. Nullam ac augue ultrices, consectetur velit pretium, tincidunt elit. Aliquam mollis nulla erat, vitae scelerisque ante ultrices eu. Fusce maximus libero eget viverra ornare. Proin eu augue placerat, sodales nibh et, laoreet ex."
        },
        {
          name: "2022-03",
          subdirectory: "reports",
          title: "March 2023",
          content: "## Project Status\nSed at auctor lacus, ut porta tellus. Curabitur luctus sem nec ipsum elementum, non congue erat ultrices. Vivamus fringilla nulla lacus, sit amet tincidunt quam cursus vel. Nunc ligula lacus, sollicitudin vitae imperdiet vel, aliquet nec elit.\n\nQuisque non magna sodales, pellentesque neque quis, varius orci. Aliquam pharetra velit accumsan libero mattis, vitae aliquet justo facilisis. Fusce feugiat tincidunt ante vel lacinia. Curabitur imperdiet cursus iaculis. Nulla posuere neque ac sem euismod pharetra. Morbi massa augue, consectetur sed luctus sagittis, sagittis ac sapien. Sed tempor nisl urna, a sollicitudin tellus rutrum a.\n\nChallenges and Opportunities\nAenean imperdiet tellus non neque placerat pellentesque. Morbi ac pulvinar arcu. In eget eleifend justo. Pellentesque porttitor consectetur consectetur:\n\n1. Sed et velit erat.\n2. Nunc ullamcorper hendrerit convallis.\n3. Curabitur sagittis ex purus.\n4. Nulla porta sem sem, vel rutrum tortor.\n\nFusce semper est sit amet finibus dictum. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Praesent vehicula, augue eu posuere imperdiet, magna ipsum tristique nisl, ut mollis ipsum ligula sed orci. Sed vitae auctor urna. Fusce pellentesque odio vel enim posuere, sollicitudin viverra quam dictum. Ut eget laoreet eros. Integer vitae imperdiet velit, a cursus lorem.\n\nPhasellus varius, libero et viverra eleifend, sem orci condimentum turpis, in condimentum sapien est vitae urna. Sed auctor condimentum tortor in egestas. Pellentesque turpis urna, commodo ut ipsum nec, fermentum venenatis risus. Quisque at dictum tortor. Curabitur gravida suscipit nisl, rutrum sagittis mauris ultricies sed.\n\nPhasellus commodo id nisl sit amet dignissim. Mauris facilisis nunc ut nibh faucibus sagittis. Integer at molestie odio, nec fermentum lectus. Donec quis purus id nisi viverra dapibus vitae eget turpis. Maecenas ut lorem malesuada nunc commodo vulputate. Nunc vulputate quam sapien, eget finibus nunc lobortis vitae. Ut gravida hendrerit lorem vitae consectetur. Quisque eget massa risus. Maecenas fringilla augue congue, lobortis neque sed, consectetur neque. Vivamus auctor nisl et placerat feugiat."
        }
      ];
      return file;
    };
  }
});

// project/types/project-default.ts
var kDefaultProjectFileContents, kConfluence, defaultProjectType;
var init_project_default = __esm({
  "project/types/project-default.ts"() {
    init_path();
    init_resources2();
    init_types3();
    init_confluence();
    kDefaultProjectFileContents = "{ project: { type: 'default' } }";
    kConfluence = "confluence";
    defaultProjectType = {
      type: "default",
      templates: [kConfluence],
      formatLibDirs: () => [
        "bootstrap",
        "quarto-html",
        "quarto-ojs",
        "quarto-diagram",
        "quarto-contrib"
      ],
      create: (title3, template2) => {
        let resourceDirectory = "default";
        if (template2 === kConfluence) {
          resourceDirectory = "confluence";
        }
        const resourceDir = resourcePath(join4("projects", resourceDirectory));
        return {
          configTemplate: join4(resourceDir, "templates", "_quarto.ejs.yml"),
          resourceDir,
          scaffold: (engine, kernel, packages) => {
            if (template2 === kConfluence) {
              return buildConfluenceFiles();
            }
            const file = [
              {
                name: title3,
                content: `## Quarto

Quarto enables you to weave together content and executable code into a finished document. To learn more about Quarto see <https://quarto.org>.`,
                title: title3
              }
            ];
            if (engine === kJupyterEngine && (!kernel || kernel.startsWith("python")) && packages) {
              file[0].content += `
  
## Running Code

You can embed executable code like this:

\`\`\`{python}
1 + 1
\`\`\`

You can add options to executable code like this

\`\`\`{python}
#| echo: false
2 * 2
\`\`\`

The \`echo: false\` option disables the printing of code (only output is displayed).`;
              if (packages.includes("matplotlib")) {
                file[0].noEngineContent = true;
                file[0].content += `

## Plots

See @fig-polar for an example of rendering plots as figures:

\`\`\`{python}
#| label: fig-polar
#| fig-cap: "A line plot on a polar axis"
#| code-fold: true

import numpy as np
import matplotlib.pyplot as plt

r = np.arange(0, 2, 0.01)
theta = 2 * np.pi * r
fig, ax = plt.subplots(subplot_kw={'projection': 'polar'})
ax.plot(theta, r)
ax.set_rticks([0.5, 1, 1.5, 2])
ax.grid(True)
plt.show()
\`\`\`

Note that we included the cell option \`fold: true\` to hide the code by default (click the *Code* button to show it).`;
              }
            }
            return file;
          }
        };
      }
    };
  }
});

// https://jsr.io/@std/bytes/0.224.0/copy.ts
function copy5(src2, dst, offset3 = 0) {
  offset3 = Math.max(0, Math.min(offset3, dst.byteLength));
  const dstBytesAvailable = dst.byteLength - offset3;
  if (src2.byteLength > dstBytesAvailable) {
    src2 = src2.subarray(0, dstBytesAvailable);
  }
  dst.set(src2, offset3);
  return src2.byteLength;
}
var init_copy6 = __esm({
  "https://jsr.io/@std/bytes/0.224.0/copy.ts"() {
  }
});

// https://jsr.io/@std/io/0.224.0/buf_reader.ts
var DEFAULT_BUF_SIZE2, MIN_BUF_SIZE2, MAX_CONSECUTIVE_EMPTY_READS2, CR2, LF3, BufferFullError2, PartialReadError2, BufReader2;
var init_buf_reader2 = __esm({
  "https://jsr.io/@std/io/0.224.0/buf_reader.ts"() {
    init_assert();
    init_copy6();
    DEFAULT_BUF_SIZE2 = 4096;
    MIN_BUF_SIZE2 = 16;
    MAX_CONSECUTIVE_EMPTY_READS2 = 100;
    CR2 = "\r".charCodeAt(0);
    LF3 = "\n".charCodeAt(0);
    BufferFullError2 = class extends Error {
      constructor(partial) {
        super("Buffer full");
        this.partial = partial;
      }
      name = "BufferFullError";
    };
    PartialReadError2 = class extends Error {
      name = "PartialReadError";
      partial;
      constructor() {
        super("Encountered UnexpectedEof, data only partially read");
      }
    };
    BufReader2 = class _BufReader {
      #buf;
      #rd;
      // Reader provided by caller.
      #r = 0;
      // buf read position.
      #w = 0;
      // buf write position.
      #eof = false;
      // private lastByte: number;
      // private lastCharSize: number;
      /** return new BufReader unless r is BufReader */
      static create(r5, size = DEFAULT_BUF_SIZE2) {
        return r5 instanceof _BufReader ? r5 : new _BufReader(r5, size);
      }
      constructor(rd, size = DEFAULT_BUF_SIZE2) {
        if (size < MIN_BUF_SIZE2) {
          size = MIN_BUF_SIZE2;
        }
        this.#reset(new Uint8Array(size), rd);
      }
      /** Returns the size of the underlying buffer in bytes. */
      size() {
        return this.#buf.byteLength;
      }
      buffered() {
        return this.#w - this.#r;
      }
      // Reads a new chunk into the buffer.
      #fill = async () => {
        if (this.#r > 0) {
          this.#buf.copyWithin(0, this.#r, this.#w);
          this.#w -= this.#r;
          this.#r = 0;
        }
        if (this.#w >= this.#buf.byteLength) {
          throw Error("bufio: tried to fill full buffer");
        }
        for (let i6 = MAX_CONSECUTIVE_EMPTY_READS2; i6 > 0; i6--) {
          const rr = await this.#rd.read(this.#buf.subarray(this.#w));
          if (rr === null) {
            this.#eof = true;
            return;
          }
          assert(rr >= 0, "negative read");
          this.#w += rr;
          if (rr > 0) {
            return;
          }
        }
        throw new Error(
          `No progress after ${MAX_CONSECUTIVE_EMPTY_READS2} read() calls`
        );
      };
      /** Discards any buffered data, resets all state, and switches
       * the buffered reader to read from r.
       */
      reset(r5) {
        this.#reset(this.#buf, r5);
      }
      #reset = (buf, rd) => {
        this.#buf = buf;
        this.#rd = rd;
        this.#eof = false;
      };
      /** reads data into p.
       * It returns the number of bytes read into p.
       * The bytes are taken from at most one Read on the underlying Reader,
       * hence n may be less than len(p).
       * To read exactly len(p) bytes, use io.ReadFull(b, p).
       */
      async read(p5) {
        let rr = p5.byteLength;
        if (p5.byteLength === 0) return rr;
        if (this.#r === this.#w) {
          if (p5.byteLength >= this.#buf.byteLength) {
            const rr2 = await this.#rd.read(p5);
            const nread = rr2 ?? 0;
            assert(nread >= 0, "negative read");
            return rr2;
          }
          this.#r = 0;
          this.#w = 0;
          rr = await this.#rd.read(this.#buf);
          if (rr === 0 || rr === null) return rr;
          assert(rr >= 0, "negative read");
          this.#w += rr;
        }
        const copied = copy5(this.#buf.subarray(this.#r, this.#w), p5, 0);
        this.#r += copied;
        return copied;
      }
      /** reads exactly `p.length` bytes into `p`.
       *
       * If successful, `p` is returned.
       *
       * If the end of the underlying stream has been reached, and there are no more
       * bytes available in the buffer, `readFull()` returns `null` instead.
       *
       * An error is thrown if some bytes could be read, but not enough to fill `p`
       * entirely before the underlying stream reported an error or EOF. Any error
       * thrown will have a `partial` property that indicates the slice of the
       * buffer that has been successfully filled with data.
       *
       * Ported from https://golang.org/pkg/io/#ReadFull
       */
      async readFull(p5) {
        let bytesRead = 0;
        while (bytesRead < p5.length) {
          try {
            const rr = await this.read(p5.subarray(bytesRead));
            if (rr === null) {
              if (bytesRead === 0) {
                return null;
              } else {
                throw new PartialReadError2();
              }
            }
            bytesRead += rr;
          } catch (err2) {
            if (err2 instanceof PartialReadError2) {
              err2.partial = p5.subarray(0, bytesRead);
            }
            throw err2;
          }
        }
        return p5;
      }
      /** Returns the next byte [0, 255] or `null`. */
      async readByte() {
        while (this.#r === this.#w) {
          if (this.#eof) return null;
          await this.#fill();
        }
        const c6 = this.#buf[this.#r];
        this.#r++;
        return c6;
      }
      /** readString() reads until the first occurrence of delim in the input,
       * returning a string containing the data up to and including the delimiter.
       * If ReadString encounters an error before finding a delimiter,
       * it returns the data read before the error and the error itself
       * (often `null`).
       * ReadString returns err !== null if and only if the returned data does not end
       * in delim.
       * For simple uses, a Scanner may be more convenient.
       */
      async readString(delim) {
        if (delim.length !== 1) {
          throw new Error("Delimiter should be a single character");
        }
        const buffer2 = await this.readSlice(delim.charCodeAt(0));
        if (buffer2 === null) return null;
        return new TextDecoder().decode(buffer2);
      }
      /** `readLine()` is a low-level line-reading primitive. Most callers should
       * use `readString('\n')` instead or use a Scanner.
       *
       * `readLine()` tries to return a single line, not including the end-of-line
       * bytes. If the line was too long for the buffer then `more` is set and the
       * beginning of the line is returned. The rest of the line will be returned
       * from future calls. `more` will be false when returning the last fragment
       * of the line. The returned buffer is only valid until the next call to
       * `readLine()`.
       *
       * The text returned from ReadLine does not include the line end ("\r\n" or
       * "\n").
       *
       * When the end of the underlying stream is reached, the final bytes in the
       * stream are returned. No indication or error is given if the input ends
       * without a final line end. When there are no more trailing bytes to read,
       * `readLine()` returns `null`.
       *
       * Calling `unreadByte()` after `readLine()` will always unread the last byte
       * read (possibly a character belonging to the line end) even if that byte is
       * not part of the line returned by `readLine()`.
       */
      async readLine() {
        let line = null;
        try {
          line = await this.readSlice(LF3);
        } catch (err2) {
          let partial;
          if (err2 instanceof PartialReadError2) {
            partial = err2.partial;
            assert(
              partial instanceof Uint8Array,
              "bufio: caught error from `readSlice()` without `partial` property"
            );
          }
          if (!(err2 instanceof BufferFullError2)) {
            throw err2;
          }
          partial = err2.partial;
          if (!this.#eof && partial && partial.byteLength > 0 && partial[partial.byteLength - 1] === CR2) {
            assert(this.#r > 0, "bufio: tried to rewind past start of buffer");
            this.#r--;
            partial = partial.subarray(0, partial.byteLength - 1);
          }
          if (partial) {
            return { line: partial, more: !this.#eof };
          }
        }
        if (line === null) {
          return null;
        }
        if (line.byteLength === 0) {
          return { line, more: false };
        }
        if (line[line.byteLength - 1] === LF3) {
          let drop = 1;
          if (line.byteLength > 1 && line[line.byteLength - 2] === CR2) {
            drop = 2;
          }
          line = line.subarray(0, line.byteLength - drop);
        }
        return { line, more: false };
      }
      /** `readSlice()` reads until the first occurrence of `delim` in the input,
       * returning a slice pointing at the bytes in the buffer. The bytes stop
       * being valid at the next read.
       *
       * If `readSlice()` encounters an error before finding a delimiter, or the
       * buffer fills without finding a delimiter, it throws an error with a
       * `partial` property that contains the entire buffer.
       *
       * If `readSlice()` encounters the end of the underlying stream and there are
       * any bytes left in the buffer, the rest of the buffer is returned. In other
       * words, EOF is always treated as a delimiter. Once the buffer is empty,
       * it returns `null`.
       *
       * Because the data returned from `readSlice()` will be overwritten by the
       * next I/O operation, most clients should use `readString()` instead.
       */
      async readSlice(delim) {
        let s5 = 0;
        let slice2;
        while (true) {
          let i6 = this.#buf.subarray(this.#r + s5, this.#w).indexOf(delim);
          if (i6 >= 0) {
            i6 += s5;
            slice2 = this.#buf.subarray(this.#r, this.#r + i6 + 1);
            this.#r += i6 + 1;
            break;
          }
          if (this.#eof) {
            if (this.#r === this.#w) {
              return null;
            }
            slice2 = this.#buf.subarray(this.#r, this.#w);
            this.#r = this.#w;
            break;
          }
          if (this.buffered() >= this.#buf.byteLength) {
            this.#r = this.#w;
            const oldbuf = this.#buf;
            const newbuf = this.#buf.slice(0);
            this.#buf = newbuf;
            throw new BufferFullError2(oldbuf);
          }
          s5 = this.#w - this.#r;
          try {
            await this.#fill();
          } catch (err2) {
            if (err2 instanceof PartialReadError2) {
              err2.partial = slice2;
            }
            throw err2;
          }
        }
        return slice2;
      }
      /** `peek()` returns the next `n` bytes without advancing the reader. The
       * bytes stop being valid at the next read call.
       *
       * When the end of the underlying stream is reached, but there are unread
       * bytes left in the buffer, those bytes are returned. If there are no bytes
       * left in the buffer, it returns `null`.
       *
       * If an error is encountered before `n` bytes are available, `peek()` throws
       * an error with the `partial` property set to a slice of the buffer that
       * contains the bytes that were available before the error occurred.
       */
      async peek(n5) {
        if (n5 < 0) {
          throw Error("negative count");
        }
        let avail = this.#w - this.#r;
        while (avail < n5 && avail < this.#buf.byteLength && !this.#eof) {
          try {
            await this.#fill();
          } catch (err2) {
            if (err2 instanceof PartialReadError2) {
              err2.partial = this.#buf.subarray(this.#r, this.#w);
            }
            throw err2;
          }
          avail = this.#w - this.#r;
        }
        if (avail === 0 && this.#eof) {
          return null;
        } else if (avail < n5 && this.#eof) {
          return this.#buf.subarray(this.#r, this.#r + avail);
        } else if (avail < n5) {
          throw new BufferFullError2(this.#buf.subarray(this.#r, this.#w));
        }
        return this.#buf.subarray(this.#r, this.#r + n5);
      }
    };
  }
});

// https://jsr.io/@std/bytes/0.224.0/concat.ts
function concat2(buffers) {
  let length = 0;
  for (const buffer2 of buffers) {
    length += buffer2.length;
  }
  const output = new Uint8Array(length);
  let index2 = 0;
  for (const buffer2 of buffers) {
    output.set(buffer2, index2);
    index2 += buffer2.length;
  }
  return output;
}
var init_concat2 = __esm({
  "https://jsr.io/@std/bytes/0.224.0/concat.ts"() {
  }
});

// https://jsr.io/@std/io/0.224.0/read_lines.ts
async function* readLines2(reader, decoderOpts) {
  const bufReader = new BufReader2(reader);
  let chunks = [];
  const decoder3 = new TextDecoder(decoderOpts?.encoding, decoderOpts);
  while (true) {
    const res = await bufReader.readLine();
    if (!res) {
      if (chunks.length > 0) {
        yield decoder3.decode(concat2(chunks));
      }
      break;
    }
    chunks.push(res.line);
    if (!res.more) {
      yield decoder3.decode(concat2(chunks));
      chunks = [];
    }
  }
}
var init_read_lines2 = __esm({
  "https://jsr.io/@std/io/0.224.0/read_lines.ts"() {
    init_buf_reader2();
    init_concat2();
  }
});

// core/lib/markdown-analysis/level-one-headings.ts
async function hasLevelOneHeadings(markdown) {
  const path3 = pandocBinaryPath();
  const filterPath = resourcePath(
    join4("filters", "quarto-internals", "leveloneanalysis.lua")
  );
  const result2 = await execProcess({
    cmd: path3,
    args: ["-f", "markdown", "-t", "markdown", "-L", filterPath],
    stdout: "piped"
  }, markdown);
  return result2.stdout?.trim() === "true";
}
var init_level_one_headings = __esm({
  "core/lib/markdown-analysis/level-one-headings.ts"() {
    init_path();
    init_process();
    init_resources2();
  }
});

// format/pdf/format-pdf.ts
function pdfFormat() {
  return mergeConfigs(
    createPdfFormat("PDF"),
    {
      extensions: {
        book: pdfBookExtension
      }
    }
  );
}
function beamerFormat() {
  return createFormat(
    "Beamer",
    "pdf",
    createPdfFormat("Beamer", false, false),
    {
      execute: {
        [kFigWidth]: 10,
        [kFigHeight]: 7,
        [kEcho]: false,
        [kWarning]: false
      },
      classoption: ["notheorems"]
    }
  );
}
function latexFormat(displayName) {
  return createFormat(
    displayName,
    "tex",
    mergeConfigs(
      createPdfFormat(displayName),
      {
        extensions: {
          book: {
            onSingleFilePreRender: (format14, _config) => {
              format14.render[kKeepTex] = true;
              return format14;
            },
            formatOutputDirectory: () => {
              return "book-latex";
            }
          }
        }
      }
    )
  );
}
function createPdfFormat(displayName, autoShiftHeadings = true, koma = true) {
  return createFormat(
    displayName,
    "pdf",
    {
      execute: {
        [kFigWidth]: 5.5,
        [kFigHeight]: 3.5,
        [kFigFormat]: "pdf",
        [kFigDpi]: 300
      },
      pandoc: {
        [kPdfEngine]: "lualatex",
        standalone: true,
        variables: {
          graphics: true,
          tables: true
        },
        [kDefaultImageExtension]: "pdf"
      },
      metadata: {
        ["block-headings"]: true
      },
      formatExtras: async (_input, markdown, flags, format14, _libDir, services) => {
        const extras = {};
        const engine = pdfEngine(format14.pandoc, format14.render, flags);
        if (!isLatexPdfEngine(engine)) {
          return extras;
        }
        extras.postprocessors = [
          pdfLatexPostProcessor(flags, format14, services.temp)
        ];
        const documentclass = format14.metadata[kDocumentClass];
        const usingCustomTemplates = format14.pandoc.template !== void 0 || format14.metadata[kTemplatePartials] !== void 0;
        if (usingCustomTemplates || documentclass && ![
          "srcbook",
          "scrreprt",
          "scrreport",
          "scrartcl",
          "scrarticle"
        ].includes(
          documentclass
        )) {
          koma = false;
        }
        if (koma) {
          const captionOptions = [];
          const tblCaploc = tblCapLocation(format14);
          captionOptions.push(
            tblCaploc === kCapTop ? "tableheading" : "tablesignature"
          );
          if (figCapLocation(format14) === kCapTop) {
            captionOptions.push("figureheading");
          }
          const defaultClassOptions = ["DIV=11"];
          if (format14.metadata[kLang] !== "de") {
            defaultClassOptions.push("numbers=noendperiod");
          }
          const userClassOptions = format14.metadata[kClassOption];
          const classOptions = defaultClassOptions.filter((option) => {
            if (Array.isArray(userClassOptions)) {
              const name2 = option.split("=")[0];
              return !userClassOptions.some(
                (userOption) => String(userOption).startsWith(name2 + "=")
              );
            } else {
              return true;
            }
          });
          const headerIncludes = [];
          headerIncludes.push(
            "\\KOMAoption{captions}{" + captionOptions.join(",") + "}"
          );
          extras.metadata = {
            [kDocumentClass]: "scrartcl",
            [kClassOption]: classOptions,
            [kPaperSize]: "letter",
            [kHeaderIncludes]: headerIncludes
          };
        }
        const partialNamesQuarto = [
          "babel-lang",
          "before-bib",
          "biblio",
          "biblio-config",
          "citations",
          "doc-class",
          "graphics",
          "after-body",
          "before-body",
          "pandoc",
          "tables",
          "tightlist",
          "before-title",
          "title",
          "toc"
        ];
        const partialNamesPandoc = [
          "after-header-includes",
          "common",
          "document-metadata",
          "font-settings",
          "fonts",
          "hypersetup",
          "passoptions"
        ];
        const createTemplateContext = function(to, partialNamesQuarto2, partialNamesPandoc2) {
          return {
            template: formatResourcePath(to, "pandoc/template.tex"),
            partials: [
              ...partialNamesQuarto2.map((name2) => {
                return formatResourcePath(to, `pandoc/${name2}.tex`);
              }),
              ...partialNamesPandoc2.map((name2) => {
                return formatResourcePath(to, `pandoc/${name2}.latex`);
              })
            ]
          };
        };
        const beamerPartialNamesPandoc = partialNamesPandoc.filter(
          (name2) => name2 !== "document-metadata"
        );
        extras.templateContext = createTemplateContext(
          displayName === "Beamer" ? "beamer" : "pdf",
          partialNamesQuarto,
          displayName === "Beamer" ? beamerPartialNamesPandoc : partialNamesPandoc
        );
        const hasLevelOneHeadings2 = await hasLevelOneHeadings(markdown);
        if (!hasLevelOneHeadings2 && autoShiftHeadings && (flags?.[kNumberSections] === true || format14.pandoc[kNumberSections] === true) && flags?.[kTopLevelDivision] === void 0 && format14.pandoc?.[kTopLevelDivision] === void 0 && flags?.[kShiftHeadingLevelBy] === void 0 && format14.pandoc?.[kShiftHeadingLevelBy] === void 0) {
          extras.pandoc = {
            [kShiftHeadingLevelBy]: -1
          };
        }
        extras.pandoc = extras.pandoc || {};
        if (documentclass === "scrbook" && format14.pandoc[kNumberSections] !== false && flags[kNumberSections] !== false) {
          extras.pandoc[kNumberSections] = true;
        }
        const pdfStandard = asArray(
          format14.render?.[kPdfStandard] ?? format14.metadata?.[kPdfStandard] ?? pdfStandardEnv()
        );
        if (pdfStandard.length > 0) {
          const { version: version4, standards, needsTagging } = normalizePdfStandardForLatex(pdfStandard);
          if (standards.length > 0 || version4) {
            extras.pandoc.variables = extras.pandoc.variables || {};
            const pdfstandardMap = {};
            if (standards.length > 0) {
              pdfstandardMap.standards = standards;
            }
            if (version4) {
              pdfstandardMap.version = version4;
            }
            if (needsTagging) {
              pdfstandardMap.tagging = true;
            }
            extras.pandoc.variables["pdfstandard"] = pdfstandardMap;
          }
          if (standards.length > 0) {
            extras.metadata = extras.metadata || {};
            extras.metadata[kPdfStandardApplied] = standards;
          }
        }
        return extras;
      }
    }
  );
}
function pdfLatexPostProcessor(flags, format14, temp) {
  return async (output) => {
    const lineProcessors = [
      sidecaptionLineProcessor(),
      calloutFloatHoldLineProcessor(),
      tableColumnMarginLineProcessor(),
      guidsProcessor()
    ];
    if (format14.pandoc[kCiteMethod] === "biblatex") {
      lineProcessors.push(bibLatexBibligraphyRefsDivProcessor());
    } else if (format14.pandoc[kCiteMethod] === "natbib") {
      lineProcessors.push(
        natbibBibligraphyRefsDivProcessor(
          format14.metadata[kBibliography]
        )
      );
    }
    const marginCites = format14.metadata[kCitationLocation] === "margin";
    const renderedCites = {};
    if (marginCites) {
      if (format14.pandoc[kCiteMethod] === "biblatex") {
        lineProcessors.push(suppressBibLatexBibliographyLineProcessor());
        lineProcessors.push(bibLatexCiteLineProcessor());
      } else if (format14.pandoc[kCiteMethod] === "natbib") {
        lineProcessors.push(suppressNatbibBibliographyLineProcessor());
        lineProcessors.push(natbibCiteLineProcessor());
      } else {
        lineProcessors.push(
          indexAndSuppressPandocBibliography(renderedCites),
          cleanReferencesChapter()
        );
      }
    }
    if (tblCapLocation(format14) === kCapBottom) {
      lineProcessors.push(longtableBottomCaptionProcessor());
    }
    if (marginRefs(flags, format14)) {
      lineProcessors.push(sideNoteLineProcessor());
    }
    lineProcessors.push(captionFootnoteLineProcessor());
    if (format14.metadata[kCodeAnnotations] !== false && format14.metadata[kCodeAnnotations] !== "none") {
      lineProcessors.push(codeAnnotationPostProcessor());
      lineProcessors.push(codeListAnnotationPostProcessor());
    }
    lineProcessors.push(tableSidenoteProcessor());
    await processLines(output, lineProcessors, temp);
    const pass2Processors = [
      longTableSidenoteProcessor()
    ];
    if (Object.keys(renderedCites).length > 0) {
      pass2Processors.push(placePandocBibliographyEntries(renderedCites));
    }
    await processLines(output, pass2Processors, temp);
  };
}
function tblCapLocation(format14) {
  return format14.metadata[kTblCapLoc] || format14.metadata[kCapLoc] || kCapTop;
}
function figCapLocation(format14) {
  return format14.metadata[kFigCapLoc] || format14.metadata[kCapLoc] || kCapBottom;
}
function marginRefs(flags, format14) {
  return format14.pandoc[kReferenceLocation] === "margin" || flags[kReferenceLocation] === "margin";
}
async function processLines(inputFile, lineProcessors, temp) {
  const outputFile5 = temp.createFile({ suffix: ".tex" });
  const file = await Deno.open(inputFile);
  const mode = safeModeFromFile(inputFile);
  try {
    for await (const line of readLines2(file)) {
      let processedLine = line;
      for (const processor of lineProcessors) {
        if (processedLine !== void 0) {
          processedLine = processor(processedLine);
        }
      }
      if (processedLine !== void 0) {
        Deno.writeTextFileSync(outputFile5, processedLine + "\n", {
          append: true,
          mode
        });
      }
    }
  } finally {
    file.close();
    copyTo(outputFile5, inputFile);
  }
}
function normalizePdfStandardForLatex(standards) {
  let version4;
  const result2 = [];
  let needsTagging = false;
  for (const s5 of standards) {
    let str3;
    if (typeof s5 === "number") {
      str3 = Number.isInteger(s5) ? `${s5}.0` : String(s5);
    } else if (typeof s5 === "string") {
      str3 = s5;
    } else {
      continue;
    }
    const normalized = str3.toLowerCase().replace(/^pdf[/-]?/, "");
    if (kVersionPattern.test(normalized)) {
      if (!version4) {
        version4 = normalized;
      }
    } else if (kLatexSupportedStandards.has(normalized)) {
      result2.push(normalized);
      if (kTaggingRequiredStandards.has(normalized)) {
        needsTagging = true;
      }
      if (!version4 && kStandardRequiredVersion[normalized]) {
        version4 = kStandardRequiredVersion[normalized];
      }
    } else {
      warn(
        `PDF standard '${s5}' is not supported by LaTeX and will be ignored`
      );
    }
  }
  return { version: version4, standards: result2, needsTagging };
}
var pdfBookExtension, kBeginScanRegex, kEndScanRegex, sidecaptionLineProcessor, readBalancedCommand, processElementCaptionFootnotes, kMatchLongTableSize, kStartLongTable, kEndLongTable, guidsProcessor, tableColumnMarginLineProcessor, captionFootnoteLineProcessor, processSideNotes, processLongTableSidenotes, processTableSidenotes, sideNoteProcessor, longTableSidenoteProcessor, tableSidenoteProcessor, calloutFloatHoldLineProcessor, kQuartoBibPlaceholderRegex, bibLatexBibligraphyRefsDivProcessor, natbibBibligraphyRefsDivProcessor, suppressBibLatexBibliographyLineProcessor, suppressNatbibBibliographyLineProcessor, kQuartoCiteRegex, bibLatexCiteLineProcessor, natbibCiteLineProcessor, sideNoteLineProcessor, longtableBottomCaptionProcessor, kChapterRefNameRegex, cleanReferencesChapter, indexAndSuppressPandocBibliography, kInSideCaptionRegex, kBeginFigureRegex, kEndFigureRegex, placePandocBibliographyEntries, kCodeAnnotationRegex, kCodePlainAnnotationRegex, codeAnnotationPostProcessor, kListAnnotationRegex, codeListAnnotationPostProcessor, kbeginLongTablesideCap, kEndLongTableSideCap, kLatexSupportedStandards, kTaggingRequiredStandards, kVersionPattern, kStandardRequiredVersion;
var init_format_pdf = __esm({
  "format/pdf/format-pdf.ts"() {
    init_path();
    init_config2();
    init_tex();
    init_constants6();
    init_log();
    init_array();
    init_formats_shared();
    init_read_lines2();
    init_pdf();
    init_resources2();
    init_template();
    init_copy5();
    init_format_html_shared();
    init_fs();
    init_level_one_headings();
    pdfBookExtension = {
      selfContainedOutput: true,
      onSingleFilePostRender: (project, renderedFile) => {
        if (renderedFile.format.render[kKeepTex]) {
          const finalOutputFile = renderedFile.file;
          const texOutputFile = texSafeFilename(basename4(finalOutputFile, extname4(finalOutputFile))) + ".tex";
          Deno.renameSync(
            join4(project.dir, "index.tex"),
            join4(project.dir, texOutputFile)
          );
        }
      }
    };
    kBeginScanRegex = /^%quartopost-sidecaption-206BE349/;
    kEndScanRegex = /^%\/quartopost-sidecaption-206BE349/;
    sidecaptionLineProcessor = () => {
      let state2 = "scanning";
      return (line) => {
        switch (state2) {
          case "scanning":
            if (line.match(kBeginScanRegex)) {
              state2 = "replacing";
              return kbeginLongTablesideCap;
            } else {
              return line;
            }
          case "replacing":
            if (line.match(kEndScanRegex)) {
              state2 = "scanning";
              return kEndLongTableSideCap;
            } else {
              return line;
            }
        }
      };
    };
    readBalancedCommand = (latex) => {
      let braceCount = 0;
      let entered = false;
      const chars = [];
      for (let i6 = 0; i6 < latex.length; i6++) {
        const char = latex.charAt(i6);
        if (char === "{") {
          braceCount++;
          entered = true;
        } else if (char === "}") {
          braceCount--;
        }
        chars.push(char);
        if (entered && braceCount === 0) {
          break;
        }
      }
      return chars.join("");
    };
    processElementCaptionFootnotes = (latexFigure) => {
      const footnoteMark = "\\footnote{";
      const captionMark = "\\caption{";
      const contents = [];
      const captionIndex = latexFigure.indexOf(captionMark);
      if (captionIndex > -1) {
        contents.push(latexFigure.substring(0, captionIndex));
        const captionStartStr = latexFigure.slice(captionIndex);
        const captionLatex = readBalancedCommand(captionStartStr);
        const figureSuffix = captionStartStr.slice(captionLatex.length);
        let captionContents = captionLatex.slice(
          captionMark.length,
          captionLatex.length - 1
        );
        let footNoteIndex = captionContents.indexOf(footnoteMark);
        if (footNoteIndex > -1) {
          const captionText = [];
          const captionWithNote = [];
          const footNotes = [];
          while (footNoteIndex > -1) {
            const prefix = captionContents.substring(0, footNoteIndex);
            captionContents = captionContents.slice(footNoteIndex);
            captionText.push(prefix);
            captionWithNote.push(prefix);
            const footnoteLatex = readBalancedCommand(captionContents);
            captionContents = captionContents.slice(footnoteLatex.length);
            footNoteIndex = captionContents.indexOf(footnoteMark);
            captionWithNote.push("\\footnotemark{}");
            footNotes.push(
              footnoteLatex.slice(footnoteMark.length, footnoteLatex.length - 1)
            );
          }
          captionText.push(captionContents);
          captionWithNote.push(captionContents);
          contents.push(
            `\\caption[${captionText.join("")}]{${captionWithNote.join("")}}`
          );
          contents.push(figureSuffix);
          contents.push("\n");
          if (footNotes.length > 1) {
            contents.push(`\\addtocounter{footnote}{-${footNotes.length - 1}}`);
          }
          for (let i6 = 0; i6 < footNotes.length; i6++) {
            contents.push(`\\footnotetext{${footNotes[i6]}}`);
            if (footNotes.length > 1 && i6 < footNotes.length - 1) {
              contents.push(`\\addtocounter{footnote}{1}`);
            }
          }
          return contents.join("");
        } else {
          return latexFigure;
        }
      } else {
        return latexFigure;
      }
    };
    kMatchLongTableSize = /^(.*)p{\(\\columnwidth - (\d+\\tabcolsep\).*$)/;
    kStartLongTable = /^\\begin{longtable}/;
    kEndLongTable = /^\\end{longtable}/;
    guidsProcessor = () => {
      let state2 = "looking-for-definition-start";
      const guidDefinitions = [];
      let guidBeingProcessed;
      let guidContents = [];
      return (line) => {
        switch (state2) {
          case "looking-for-definition-start": {
            if (line.startsWith("%quarto-define-uuid: ")) {
              state2 = "looking-for-definition-end";
              line = line.replace(/^%quarto-define-uuid:\s*/, "");
              guidBeingProcessed = line.trim();
              return void 0;
            }
            for (const [key, value] of guidDefinitions) {
              line = line.replaceAll(key, value);
            }
            return line;
          }
          case "looking-for-definition-end": {
            if (line === "%quarto-end-define-uuid") {
              state2 = "looking-for-definition-start";
              if (guidBeingProcessed === void 0) {
                throw new Error("guidBeingProcessed is undefined");
              }
              guidDefinitions.push([
                guidBeingProcessed,
                guidContents.join("").trim()
              ]);
              guidContents = [];
              guidBeingProcessed = void 0;
              return void 0;
            } else {
              guidContents.push(line);
              return void 0;
            }
          }
        }
      };
    };
    tableColumnMarginLineProcessor = () => {
      let state2 = "looking-for-boundaries";
      return (line) => {
        switch (state2) {
          case "looking-for-boundaries": {
            if (line === "% quarto-tables-in-margin-AB1927C9:begin") {
              state2 = "looking-for-tables";
              return void 0;
            }
            return line;
          }
          case "looking-for-tables": {
            if (line.match(kStartLongTable)) {
              state2 = "processing";
              return line;
            } else if (line === "% quarto-tables-in-margin-AB1927C9:end") {
              state2 = "looking-for-boundaries";
              return void 0;
            }
            return line;
          }
          case "processing": {
            if (line.match(kEndLongTable)) {
              state2 = "looking-for-tables";
              return line;
            } else {
              const match = line.match(kMatchLongTableSize);
              if (match) {
                return `${match[1]}p{(\\marginparwidth + \\marginparsep + \\columnwidth - ${match[2]}`;
              } else {
                return line;
              }
            }
          }
          default: {
            return line;
          }
        }
      };
    };
    captionFootnoteLineProcessor = () => {
      let state2 = "scanning";
      let capturedLines = [];
      return (line) => {
        switch (state2) {
          case "scanning":
            if (line.match(/^\\begin{figure}.*$/)) {
              state2 = "capturing";
              capturedLines = [line];
              return void 0;
            } else {
              return line;
            }
          case "capturing":
            capturedLines.push(line);
            if (line.match(/^\\end{figure}%*$/)) {
              state2 = "scanning";
              const lines2 = capturedLines.join("\n");
              capturedLines = [];
              return processElementCaptionFootnotes(lines2);
            } else {
              return void 0;
            }
        }
      };
    };
    processSideNotes = (endMarker) => {
      return (latexLongTable) => {
        const sideNoteMarker = "\\sidenote{\\footnotesize ";
        let strProcessing = latexLongTable;
        const strOutput = [];
        const sidenotes = [];
        let sidenotePos = strProcessing.indexOf(sideNoteMarker);
        while (sidenotePos > -1) {
          strOutput.push(strProcessing.substring(0, sidenotePos));
          const remainingStr = strProcessing.substring(
            sidenotePos + sideNoteMarker.length
          );
          let escaped = false;
          let sideNoteEnd = -1;
          for (let i6 = 0; i6 < remainingStr.length; i6++) {
            const ch = remainingStr[i6];
            if (ch === "\\") {
              escaped = true;
            } else {
              if (!escaped && ch === "}") {
                sideNoteEnd = i6;
                break;
              } else {
                escaped = false;
              }
            }
          }
          if (sideNoteEnd > -1) {
            strOutput.push("\\sidenotemark{}");
            const contents = remainingStr.substring(0, sideNoteEnd);
            sidenotes.push(contents);
            strProcessing = remainingStr.substring(sideNoteEnd + 1);
            sidenotePos = strProcessing.indexOf(sideNoteMarker);
          } else {
            strOutput.push(remainingStr);
          }
        }
        const endTable = endMarker;
        const endPos = strProcessing.indexOf(endTable);
        const prefix = strProcessing.substring(0, endPos + endTable.length);
        const suffix = strProcessing.substring(
          endPos + endTable.length,
          strProcessing.length
        );
        strOutput.push(prefix);
        for (const note of sidenotes) {
          strOutput.push(`\\sidenotetext{${note}}
`);
        }
        if (suffix) {
          strOutput.push(suffix);
        }
        return strOutput.join("");
      };
    };
    processLongTableSidenotes = processSideNotes("\\end{longtable}");
    processTableSidenotes = processSideNotes("\\end{table}");
    sideNoteProcessor = (beginRegex, endRegex, callback) => {
      return () => {
        let state2 = "scanning";
        let capturedLines = [];
        return (line) => {
          switch (state2) {
            case "scanning":
              if (line.match(beginRegex)) {
                state2 = "capturing";
                capturedLines = [line];
                return void 0;
              } else {
                return line;
              }
            case "capturing":
              capturedLines.push(line);
              if (line.match(endRegex)) {
                state2 = "scanning";
                const lines2 = capturedLines.join("\n");
                capturedLines = [];
                return callback(lines2);
              } else {
                return void 0;
              }
          }
        };
      };
    };
    longTableSidenoteProcessor = sideNoteProcessor(
      /^\\begin{longtable}.*$/,
      /^\\end{longtable}%*$/,
      processLongTableSidenotes
    );
    tableSidenoteProcessor = sideNoteProcessor(
      /^\\begin{table}.*$/,
      /^\\end{table}%*$/,
      processTableSidenotes
    );
    calloutFloatHoldLineProcessor = () => {
      let state2 = "scanning";
      return (line) => {
        switch (state2) {
          case "scanning":
            if (line.match(/^\\begin{tcolorbox}/)) {
              state2 = "replacing";
              return line;
            } else {
              return line;
            }
          case "replacing":
            if (line.match(/^\\end{tcolorbox}/)) {
              state2 = "scanning";
              return line;
            } else if (line.match(/^\\begin{figure}$/)) {
              return "\\begin{figure}[H]";
            } else if (line.match(/^\\begin{codelisting}$/)) {
              return "\\begin{codelisting}[H]";
            } else {
              return line;
            }
        }
      };
    };
    kQuartoBibPlaceholderRegex = "%bib-loc-124C8010";
    bibLatexBibligraphyRefsDivProcessor = () => {
      let hasRefsDiv = false;
      return (line) => {
        if (line === kQuartoBibPlaceholderRegex) {
          if (!hasRefsDiv) {
            hasRefsDiv = true;
            return "\\printbibliography[heading=none]";
          } else {
            return void 0;
          }
        } else if (hasRefsDiv && line.match(/^\\printbibliography$/)) {
          return void 0;
        } else {
          return line;
        }
      };
    };
    natbibBibligraphyRefsDivProcessor = (bibs) => {
      let hasRefsDiv = false;
      return (line) => {
        if (line === kQuartoBibPlaceholderRegex) {
          if (bibs && !hasRefsDiv) {
            hasRefsDiv = true;
            return `\\renewcommand{\\bibsection}{}
\\bibliography{${bibs.join(",")}}`;
          } else {
            return void 0;
          }
        } else if (hasRefsDiv && line.match(/^\s*\\bibliography{.*}$/)) {
          return void 0;
        } else {
          return line;
        }
      };
    };
    suppressBibLatexBibliographyLineProcessor = () => {
      return (line) => {
        if (line.match(/^\\printbibliography$/)) {
          return "";
        }
        return line;
      };
    };
    suppressNatbibBibliographyLineProcessor = () => {
      return (line) => {
        return line.replace(/^\s*\\bibliography{(.*)}$/, (_match, bib) => {
          return `\\newsavebox\\mytempbib
\\savebox\\mytempbib{\\parbox{\\textwidth}{\\bibliography{${bib}}}}`;
        });
      };
    };
    kQuartoCiteRegex = /{\?quarto-cite:(.*?)}/g;
    bibLatexCiteLineProcessor = () => {
      return (line) => {
        return line.replaceAll(kQuartoCiteRegex, (_match, citeKey) => {
          return `\\fullcite{${citeKey}}`;
        });
      };
    };
    natbibCiteLineProcessor = () => {
      return (line) => {
        return line.replaceAll(kQuartoCiteRegex, (_match, citeKey) => {
          return `\\bibentry{${citeKey}}`;
        });
      };
    };
    sideNoteLineProcessor = () => {
      return (line) => {
        return line.replaceAll(/\\footnote{/g, "\\sidenote{\\footnotesize ");
      };
    };
    longtableBottomCaptionProcessor = () => {
      let scanning = false;
      let capturing = false;
      let caption;
      return (line) => {
        const isEndOfDocument = !!line.match(/^\\end{document}/);
        if (isEndOfDocument && caption) {
          return `${caption}
${line}`;
        } else if (scanning) {
          if (capturing) {
            caption = `${caption}
${line}`;
            capturing = !line.match(/\\tabularnewline$/);
            return void 0;
          } else {
            if (line.match(/^\\caption.*?\\tabularnewline$/) || line.match(/^\\caption{.*}\\\\$/)) {
              caption = line;
              return void 0;
            } else if (line.match(/^\\caption.*?/)) {
              caption = line;
              capturing = true;
              return void 0;
            } else if (line.match(/^\\endlastfoot/) && caption) {
              line = `\\tabularnewline
${caption}
${line}`;
              caption = void 0;
              return line;
            } else if (line.match(/^\\end{longtable}$/)) {
              scanning = false;
              if (caption) {
                line = caption + "\n" + line;
                caption = void 0;
                return line;
              }
            }
          }
        } else {
          scanning = !!line.match(/^\\begin{longtable}/);
        }
        return line;
      };
    };
    kChapterRefNameRegex = /^\\chapter\*?{(.*?)}\\label{references.*?}$/;
    cleanReferencesChapter = () => {
      let refChapterName;
      let refChapterContentsRegex;
      let refChapterMarkRegex;
      return (line) => {
        const chapterRefMatch = line.match(kChapterRefNameRegex);
        if (chapterRefMatch) {
          refChapterName = chapterRefMatch[1];
          refChapterContentsRegex = new RegExp(
            `\\\\addcontentsline{toc}{chapter}{${refChapterName}}`
          );
          refChapterMarkRegex = new RegExp(
            `\\\\markboth{${refChapterName}}{${refChapterName}}`
          );
          return void 0;
        } else if (refChapterContentsRegex && line.match(refChapterContentsRegex)) {
          return void 0;
        } else if (refChapterMarkRegex && line.match(refChapterMarkRegex)) {
          return void 0;
        }
        return line;
      };
    };
    indexAndSuppressPandocBibliography = (renderedCites) => {
      let readingBibliography = false;
      let currentCiteKey = void 0;
      return (line) => {
        if (!readingBibliography && line.match(/^(\\protect)?\\phantomsection\\label{refs}$/)) {
          readingBibliography = true;
          return void 0;
        } else if (readingBibliography && line.match(/^\\end{CSLReferences}$/)) {
          readingBibliography = false;
          return void 0;
        } else if (readingBibliography) {
          const matches = line.match(/\\bibitem\[\\citeproctext\]{ref\-(.*?)}/);
          if (matches && matches[1]) {
            currentCiteKey = matches[1];
            renderedCites[currentCiteKey] = [line];
          } else if (line.length === 0) {
            currentCiteKey = void 0;
          } else if (currentCiteKey) {
            renderedCites[currentCiteKey].push(line);
          }
        }
        if (readingBibliography) {
          return void 0;
        } else {
          return line;
        }
      };
    };
    kInSideCaptionRegex = /^\\sidecaption{/;
    kBeginFigureRegex = /^\\begin{figure}\[.*?\]$/;
    kEndFigureRegex = /^\\end{figure}\%?$/;
    placePandocBibliographyEntries = (renderedCites) => {
      let biblioEntryState = "scanning";
      let pendingCiteKeys = [];
      return (line) => {
        switch (biblioEntryState) {
          case "scanning": {
            if (line.match(kBeginFigureRegex)) {
              biblioEntryState = "in-figure";
            }
            break;
          }
          case "in-figure": {
            if (line.match(kInSideCaptionRegex)) {
              biblioEntryState = "in-sidecaption";
            } else {
              if (line.match(kEndFigureRegex)) {
                biblioEntryState = "scanning";
              }
            }
            break;
          }
          case "in-sidecaption": {
            if (line.match(kEndFigureRegex)) {
              biblioEntryState = "scanning";
            }
            break;
          }
          default:
            break;
        }
        if (biblioEntryState === "scanning" && pendingCiteKeys.length > 0) {
          const result2 = [
            line,
            "\n\\begin{CSLReferences}{2}{0}",
            ...pendingCiteKeys,
            "\\end{CSLReferences}\n"
          ].join("\n");
          pendingCiteKeys = [];
          return result2;
        }
        return line.replaceAll(kQuartoCiteRegex, (_match, citeKey) => {
          const citeLines = renderedCites[citeKey];
          if (citeLines) {
            if (biblioEntryState === "in-sidecaption" && citeLines.length > 0) {
              pendingCiteKeys.push(citeLines[0]);
              return ["", ...citeLines.slice(1)].join("\n");
            } else {
              return [
                "\n\\begin{CSLReferences}{2}{0}",
                ...citeLines,
                "\\end{CSLReferences}\n"
              ].join("\n");
            }
          } else {
            return citeKey;
          }
        });
      };
    };
    kCodeAnnotationRegex = /(.*)\\CommentTok\{(.*?)[^\s]+? +\\textless\{\}(\d+)\\textgreater\{\}.*\}$/gm;
    kCodePlainAnnotationRegex = /(.*)% \((\d+)\)$/g;
    codeAnnotationPostProcessor = () => {
      let lastAnnotation;
      return (line) => {
        if (line === "\\begin{Shaded}") {
          lastAnnotation = void 0;
        }
        line = line.replaceAll(
          kCodeAnnotationRegex,
          (_match, prefix, comment, annotationNumber) => {
            if (annotationNumber !== lastAnnotation) {
              lastAnnotation = annotationNumber;
              if (comment.length > 0) {
                prefix = `${prefix}\\CommentTok{${comment}}`;
              }
              return `${prefix}\\hspace*{\\fill}\\NormalTok{\\circled{${annotationNumber}}}`;
            } else {
              return `${prefix}`;
            }
          }
        );
        line = line.replaceAll(
          kCodePlainAnnotationRegex,
          (_match, prefix, annotationNumber) => {
            if (annotationNumber !== lastAnnotation) {
              lastAnnotation = annotationNumber;
              const replaceValue = `(${annotationNumber})`;
              const paddingNumber = Math.max(
                0,
                75 - prefix.length - replaceValue.length
              );
              const padding3 = " ".repeat(paddingNumber);
              return `${prefix}${padding3}${replaceValue}`;
            } else {
              return `${prefix}`;
            }
          }
        );
        return line;
      };
    };
    kListAnnotationRegex = /(.*)5CB6E08D-list-annote-(\d+)(.*)/g;
    codeListAnnotationPostProcessor = () => {
      return (line) => {
        return line.replaceAll(
          kListAnnotationRegex,
          (_match, prefix, annotationNumber, suffix) => {
            return `${prefix}\\circled{${annotationNumber}}${suffix}`;
          }
        );
      };
    };
    kbeginLongTablesideCap = `{
\\makeatletter
\\def\\LT@makecaption#1#2#3{%
  \\noalign{\\smash{\\hbox{\\kern\\textwidth\\rlap{\\kern\\marginparsep
  \\parbox[t]{\\marginparwidth}{%
    \\footnotesize{%
      \\vspace{(1.1\\baselineskip)}
    #1{#2: }\\ignorespaces #3}}}}}}%
    }
\\makeatother`;
    kEndLongTableSideCap = "}";
    kLatexSupportedStandards = /* @__PURE__ */ new Set([
      // PDF/A standards (note: a-1a is NOT supported, only a-1b)
      "a-1b",
      "a-2a",
      "a-2b",
      "a-2u",
      "a-3a",
      "a-3b",
      "a-3u",
      "a-4",
      "a-4e",
      "a-4f",
      // PDF/X standards
      "x-4",
      "x-4p",
      "x-5g",
      "x-5n",
      "x-5pg",
      "x-6",
      "x-6n",
      "x-6p",
      // PDF/UA standards (only ua-2 is supported by LaTeX)
      "ua-2"
    ]);
    kTaggingRequiredStandards = /* @__PURE__ */ new Set([
      "a-2a",
      "a-3a",
      "ua-1",
      "ua-2"
    ]);
    kVersionPattern = /^(1\.[4-7]|2\.0)$/;
    kStandardRequiredVersion = {
      // PDF/A-1 requires exactly PDF 1.4 (only a-1b supported by LaTeX)
      "a-1b": "1.4",
      // PDF/A-2 and PDF/A-3 have maximum version of 1.7
      "a-2a": "1.7",
      "a-2b": "1.7",
      "a-2u": "1.7",
      "a-3a": "1.7",
      "a-3b": "1.7",
      "a-3u": "1.7"
      // PDF/A-4, PDF/UA-1, PDF/UA-2 all work with PDF 2.0 (the default)
    };
  }
});

// format/epub/format-epub.ts
function epubFormat(to) {
  return mergeConfigs(
    createEbookFormat("ePub", "epub"),
    {
      pandoc: {
        [kHtmlMathMethod]: to === "epub2" ? "webtex" : "mathml"
      },
      extensions: {
        book: epubBookExtension
      }
    }
  );
}
var epubBookExtension;
var init_format_epub = __esm({
  "format/epub/format-epub.ts"() {
    init_constants6();
    init_config2();
    init_book_shared();
    init_formats_shared();
    epubBookExtension = {
      selfContainedOutput: true,
      onSingleFilePreRender: (format14, config2) => {
        if (!format14.pandoc[kEPubCoverImage] && !format14.metadata[kBookCoverImage]) {
          const coverImage = bookConfig(kBookCoverImage, config2);
          if (coverImage) {
            format14.metadata[kBookCoverImage] = coverImage;
          }
        }
        return format14;
      }
    };
  }
});

// format/docx/format-docx.ts
function docxFormat() {
  return mergeConfigs(
    createWordprocessorFormat("MS Word", "docx"),
    {
      formatExtras: () => {
        return {
          [kFilterParams]: {
            [kIconCaution]: iconPath("caution.png"),
            [kIconImportant]: iconPath("important.png"),
            [kIconNote]: iconPath("note.png"),
            [kIconTip]: iconPath("tip.png"),
            [kIconWarning]: iconPath("warning.png")
          }
        };
      },
      extensions: {
        book: {
          selfContainedOutput: true
        }
      }
    }
  );
}
function iconPath(icon) {
  return formatResourcePath("docx", icon);
}
var kIconCaution, kIconImportant, kIconNote, kIconTip, kIconWarning;
var init_format_docx = __esm({
  "format/docx/format-docx.ts"() {
    init_constants6();
    init_config2();
    init_resources2();
    init_formats_shared();
    kIconCaution = "icon-caution";
    kIconImportant = "icon-important";
    kIconNote = "icon-note";
    kIconTip = "icon-tip";
    kIconWarning = "icon-warning";
  }
});

// core/xml.ts
async function reformat(xmlFile) {
  if (!isWindows4) {
    const xmlLint = await which(kXmlLint);
    if (xmlLint) {
      const result2 = await execProcess({
        cmd: kXmlLint,
        args: [
          xmlFile,
          "--format",
          "-o",
          xmlFile
        ]
      });
      if (!result2.success) {
        warn("Unable to reformat the XML file " + xmlFile);
      }
    }
  }
}
var kXmlLint;
var init_xml = __esm({
  "core/xml.ts"() {
    init_path2();
    init_process();
    init_log();
    init_platform();
    kXmlLint = "xmllint";
  }
});

// format/jats/format-jats-postprocess.ts
var reformatXmlPostProcessor, renderSubarticlePostProcessor, kIdRegex, kRidRegex;
var init_format_jats_postprocess = __esm({
  "format/jats/format-jats-postprocess.ts"() {
    init_xml();
    init_format_jats_types();
    init_path();
    init_fs();
    init_read_lines2();
    init_log2();
    init_notebook_types();
    reformatXmlPostProcessor = async (output) => {
      await reformat(output);
    };
    renderSubarticlePostProcessor = (input, format14, subArticles, services, project, quiet) => {
      return async (output) => {
        const subArticlesToRender = subArticles.filter((subArticle) => {
          return services.notebook.get(subArticle.input, project) === void 0;
        });
        const total = subArticlesToRender.length;
        if (subArticlesToRender.length > 0 && !quiet) {
          logProgress("Rendering JATS sub-articles");
        }
        let count = 0;
        for (const subArticle of subArticlesToRender) {
          const subArticlePath = subArticle.input;
          const nbRelPath = relative4(dirname4(input), subArticlePath);
          if (!quiet) {
            logProgress(`[${++count}/${total}] ${nbRelPath}`);
          }
          await services.notebook.render(
            subArticlePath,
            format14,
            kJatsSubarticle2,
            services,
            void 0,
            project
          );
        }
        const supportingOut = [];
        for (const subArticle of subArticles) {
          const nb = services.notebook.get(subArticle.input, project);
          if (nb && nb[kJatsSubarticle2]) {
            let outputContents = Deno.readTextFileSync(output);
            const notebook = nb[kJatsSubarticle2];
            const jatsSubarticlePath = notebook.path;
            const placeholder2 = xmlPlaceholder(
              subArticle.token,
              subArticle.input
            );
            const subArtReader = await Deno.open(jatsSubarticlePath);
            const subArtLines = [];
            for await (let line of readLines2(subArtReader)) {
              line = line.replaceAll(kIdRegex, `$1id="$2-${subArticle.token}"`);
              line = line.replaceAll(kRidRegex, `$1rid="$2-${subArticle.token}"`);
              subArtLines.push(line);
            }
            outputContents = outputContents.replaceAll(
              placeholder2,
              () => subArtLines.join("\n")
            );
            for (const support of notebook.supporting) {
              const basePath = project ? project.dir : dirname4(notebook.path);
              const fromPath = join4(basePath, support);
              const toPath = join4(
                dirname4(output),
                relative4(dirname4(notebook.path), fromPath)
              );
              if (fromPath !== toPath) {
                copySync(fromPath, toPath, { overwrite: true });
              }
              supportingOut.push(toPath);
            }
            Deno.writeTextFileSync(output, outputContents);
          }
        }
        for (const subArticle of subArticles) {
          services.notebook.removeRendering(
            subArticle.input,
            kJatsSubarticle2,
            supportingOut
          );
        }
        return {
          supporting: supportingOut
        };
      };
    };
    kIdRegex = /(\s+)id="([^"]*)"/g;
    kRidRegex = /(\s+)rid="([^"]*)"/g;
  }
});

// format/jats/format-jats.ts
function jatsFormat(displayName, ext) {
  return createFormat(displayName, ext, {
    pandoc: {
      standalone: true,
      [kDefaultImageExtension]: "png"
    },
    render: {
      [kVariant]: kElementsVariant
    },
    formatExtras: (input, _markdown, _flags, format14, _libDir, services, _offset, project, quiet) => {
      const templateDir = formatResourcePath("jats", "pandoc");
      const partials = [
        "front.xml",
        "authors.xml",
        "institution.xml",
        "affiliation.xml",
        "name.xml"
      ];
      const templateContext = {
        template: join4(templateDir, "template.xml"),
        partials: partials.map((partial) => join4(templateDir, partial))
      };
      const tagset = jatsTagset(format14.identifier["base-format"] || "jats");
      const metadataOverride = {
        // Link citations produces `xrefs` for the citations to the references in the bibliography so
        // must be enabled
        [kLinkCitations]: true
      };
      if (format14.metadata[kLinkCitations] === false) {
        warn(
          "JATS formats require that `link-citations` is enabled to emit well formed JATS. Explicitly set value is being ignored."
        );
      }
      const postprocessors = [];
      const internalMetadata = format14.metadata[kQuartoInternal];
      const afterBody = [];
      const subArticleResources = [];
      if (internalMetadata && !format14.metadata[kJatsSubarticle]) {
        const subArticles = internalMetadata[kSubArticles];
        if (subArticles && format14.render[kNotebookSubarticles] !== false) {
          const placeholderFile = services.temp.createFile({
            suffix: ".placeholder.xml"
          });
          const placeholders = [];
          subArticles.forEach((subArticle) => {
            const placeholder2 = xmlPlaceholder(
              subArticle.token,
              subArticle.input
            );
            placeholders.push(placeholder2);
          });
          Deno.writeTextFileSync(placeholderFile, placeholders.join("\n"));
          afterBody.push(placeholderFile);
          if (subArticles.length > 0 && !format14.metadata[kJatsSubarticle]) {
            postprocessors.push(
              renderSubarticlePostProcessor(
                input,
                format14,
                subArticles,
                services,
                project,
                quiet
              )
            );
          }
        }
      }
      if (format14.metadata[kLintXml] !== false) {
        postprocessors.push(reformatXmlPostProcessor);
      }
      return {
        [kIncludeAfterBody]: afterBody,
        metadata: {
          [kQuartoInternal]: {
            // These signal the template with flags controlling the tagset to be output
            [kJatsExtended]: tagset === "archiving" || tagset === "publishing",
            [kJatsDtd]: jatsDtd(tagset)
          },
          [kResources]: subArticleResources
        },
        templateContext,
        metadataOverride,
        postprocessors
      };
    }
  });
}
var kJatsExtended, kJatsDtd, kElementsVariant;
var init_format_jats = __esm({
  "format/jats/format-jats.ts"() {
    init_constants6();
    init_formats_shared();
    init_resources2();
    init_format_jats_types();
    init_path();
    init_log();
    init_format_jats_postprocess();
    kJatsExtended = "jats-extended";
    kJatsDtd = "jats-dtd";
    kElementsVariant = "+element_citations";
  }
});

// format/typst/format-typst.ts
function typstFormat() {
  return createFormat("Typst", "pdf", {
    execute: {
      [kFigWidth]: 5.5,
      [kFigHeight]: 3.5,
      [kFigFormat]: "svg"
    },
    pandoc: {
      standalone: true,
      [kDefaultImageExtension]: "svg",
      [kWrap]: "none",
      [kCiteproc]: false
    },
    extensions: {
      book: typstBookExtension
    },
    resolveFormat: typstResolveFormat,
    formatExtras: async (_input, markdown, flags, format14, _libDir, _services, _offset, _project) => {
      const pandoc2 = {};
      const metadata = {};
      if (flags?.[kNumberSections] === true || format14.pandoc[kNumberSections] === true) {
        if (!format14.metadata?.[kSectionNumbering]) {
          metadata[kSectionNumbering] = "1.1.a";
        }
      }
      const hasLevelOneHeadings2 = await hasLevelOneHeadings(markdown);
      if (!hasLevelOneHeadings2 && flags?.[kShiftHeadingLevelBy] === void 0 && format14.pandoc?.[kShiftHeadingLevelBy] === void 0) {
        pandoc2[kShiftHeadingLevelBy] = -1;
      }
      const brand = format14.render.brand;
      const typstBrand = brandWithAbsoluteLogoPaths(brand);
      const logoSpec = format14.metadata[kLogo];
      const sizeOrder = [
        "small",
        "medium",
        "large"
      ];
      const logo = fillLogoPaths(typstBrand, logoSpec, sizeOrder);
      format14.metadata[kLogo] = resolveLogo(typstBrand, logo, sizeOrder);
      const columns = format14.pandoc[kColumns];
      if (columns) {
        pandoc2[kColumns] = void 0;
        metadata[kColumns] = columns;
      }
      const templateDir = formatResourcePath("typst", join4("pandoc", "quarto"));
      const templateContext = {
        template: join4(templateDir, "template.typ"),
        partials: [
          "numbering.typ",
          "definitions.typ",
          "typst-template.typ",
          "page.typ",
          "typst-show.typ",
          "notes.typ",
          "biblio.typ"
        ].map((partial) => join4(templateDir, partial))
      };
      const brandData = format14.render[kBrand]?.[kLight];
      const monospaceBlock = brandData?.processedData?.typography?.["monospace-block"];
      let brandBgColor = monospaceBlock && typeof monospaceBlock !== "string" ? monospaceBlock["background-color"] : void 0;
      if (brandBgColor && brandData?.data?.color?.palette) {
        const palette = brandData.data.color.palette;
        let resolved = brandBgColor;
        while (palette[resolved]) {
          resolved = palette[resolved];
        }
        brandBgColor = resolved;
      }
      return {
        pandoc: pandoc2,
        metadata,
        templateContext,
        postprocessors: [
          skylightingPostProcessor(brandBgColor)
        ]
      };
    }
  });
}
function skylightingPostProcessor(brandBgColor) {
  const skylightingFnRe = /(#let Skylighting\(fill: none, number: false, start: 1, sourcelines\) = \{[\s\S]*?\n\})/;
  return async (output) => {
    const content = Deno.readTextFileSync(output);
    const match = skylightingFnRe.exec(content);
    if (!match) {
      return;
    }
    let fn = match[1];
    fn = fn.replace(
      "block(fill: bgcolor, blocks)",
      "block(fill: bgcolor, width: 100%, inset: 8pt, radius: 2pt, blocks)"
    );
    if (brandBgColor) {
      fn = fn.replace(
        /let bgcolor = rgb\("[^"]*"\)/,
        `let bgcolor = rgb("${brandBgColor}")`
      );
    }
    if (fn !== match[1]) {
      Deno.writeTextFileSync(output, content.replace(match[1], fn));
    }
  };
}
function typstResolveFormat(format14) {
  if (format14.pandoc?.[kCiteproc] === true && !format14.pandoc.to?.includes("-citations") && !format14.render[kVariant]?.includes("-citations")) {
    format14.render[kVariant] = [format14.render?.[kVariant], "-citations"].join(
      ""
    );
  }
}
var typstBookExtension;
var init_format_typst = __esm({
  "format/typst/format-typst.ts"() {
    init_path();
    init_constants6();
    init_resources2();
    init_formats_shared();
    init_level_one_headings();
    init_brand();
    typstBookExtension = {
      selfContainedOutput: true
      // multiFile defaults to false (single-file book)
    };
  }
});

// format/format-handlers.ts
function registerWriterFormatHandler(handler) {
  writerFormatHandlers.push(handler);
}
var writerFormatHandlers;
var init_format_handlers = __esm({
  "format/format-handlers.ts"() {
    writerFormatHandlers = [];
  }
});

// format/formats.ts
function defaultWriterFormat(to) {
  const formatDescriptor = parseFormatString(to);
  let lookupTo = formatDescriptor.baseFormat;
  let pandocTo = lookupTo;
  let writerFormat;
  let handled = false;
  for (const handler of writerFormatHandlers) {
    const result2 = handler(lookupTo);
    if (result2) {
      handled = true;
      if (result2.pandocTo) {
        pandocTo = result2.pandocTo;
      }
      writerFormat = result2.format;
      break;
    }
  }
  if (!handled) {
    switch (lookupTo) {
      // these have been moved to imports.ts and imported from top-level quarto.ts
      // to avoid circular dependencies
      //
      // case "html":
      // case "html4":
      // case "html5":
      //   writerFormat = htmlFormat(7, 5);
      //   break;
      // case "revealjs":
      //   writerFormat = revealjsFormat();
      //   break;
      // case "asciidoc":
      // case "asciidoctor":
      //   writerFormat = asciidocFormat();
      //   break;
      case "pdf":
        writerFormat = pdfFormat();
        break;
      case "beamer":
        writerFormat = beamerFormat();
        break;
      case "latex":
        writerFormat = latexFormat("LaTeX");
        break;
      case "context":
        writerFormat = latexFormat("ConTeXt");
        break;
      case "s5":
        writerFormat = createHtmlPresentationFormat("S5", 9.5, 6.5);
        break;
      case "dzslides":
        writerFormat = createHtmlPresentationFormat("DZSlides", 9.5, 6.5);
        break;
      case "slidy":
        writerFormat = createHtmlPresentationFormat("Slidy", 9.5, 6.5);
        break;
      case "slideous":
        writerFormat = createHtmlPresentationFormat("Slideous", 9.5, 6.5);
        break;
      case "markdown":
        writerFormat = pandocMarkdownFormat();
        pandocTo = to;
        break;
      case "markdown_phpextra":
      case "markdown_github":
      case "markdown_mmd":
      case "markdown_strict":
        writerFormat = markdownFormat("Markdown");
        pandocTo = to;
        break;
      case "markua":
        writerFormat = markdownFormat("Markua");
        pandocTo = to;
        break;
      case "md":
        writerFormat = markdownWithCommonmarkExtensionsFormat();
        lookupTo = "commonmark";
        pandocTo = "markdown_strict";
        break;
      case "commonmark":
      case "commonmark_x":
        writerFormat = commonmarkFormat(to);
        pandocTo = to;
        break;
      case "gfm":
        writerFormat = gfmFormat();
        pandocTo = to;
        break;
      case "docbook":
      case "docbook4":
      case "docbook5":
        writerFormat = plaintextFormat("DocBook", "xml");
        break;
      case "docx":
        writerFormat = docxFormat();
        break;
      case "pptx":
        writerFormat = powerpointFormat();
        break;
      case "odt":
        writerFormat = createWordprocessorFormat("OpenOffice", "odt");
        break;
      case "opendocument":
        writerFormat = createWordprocessorFormat("OpenDocument", "xml");
        break;
      case "rtf":
        writerFormat = rtfFormat();
        break;
      case "plain":
        writerFormat = plaintextFormat("Text", "txt");
        break;
      case "epub":
      case "epub2":
      case "epub3":
        writerFormat = epubFormat(lookupTo);
        break;
      case "fb2":
        writerFormat = createEbookFormat("FictionBook", "fb2");
        break;
      case "zimwiki":
        writerFormat = plaintextFormat("Zim Wiki", "zim");
        break;
      case "jats":
        writerFormat = jatsFormat("JATS", "xml");
        break;
      case "jats_archiving":
        writerFormat = jatsFormat("JATS Archiving", "xml");
        break;
      case "jats_articleauthoring":
        writerFormat = jatsFormat("JATS Authoring", "xml");
        break;
      case "jats_publishing":
        writerFormat = jatsFormat("JATS Publising", "xml");
        break;
      case "ipynb":
        writerFormat = ipynbFormat();
        break;
      case "biblatex":
        writerFormat = bibliographyFormat("BibLaTeX", "bib");
        break;
      case "bibtex":
        writerFormat = bibliographyFormat("BibTeX", "bib");
        break;
      case "csljson":
        writerFormat = bibliographyFormat("CSL-JSON", "csl");
        break;
      case "typst":
        writerFormat = typstFormat();
        break;
      case "texttile":
        writerFormat = plaintextFormat("Textile", to);
        break;
      case "texinfo":
        writerFormat = plaintextFormat("GNU TexInfo", to);
        break;
      case "tei":
        writerFormat = plaintextFormat("TEI Simple", to);
        break;
      case "rst":
        writerFormat = plaintextFormat("reST", to);
        break;
      case "org":
        writerFormat = plaintextFormat("Org-Mode", to);
        break;
      case "opml":
        writerFormat = plaintextFormat("OPML", to);
        break;
      case "muse":
        writerFormat = plaintextFormat("Muse", to);
        break;
      case "ms":
        writerFormat = plaintextFormat("Groff Manuscript", to);
        break;
      case "native":
        writerFormat = plaintextFormat("Native", to);
        break;
      case "man":
        writerFormat = plaintextFormat("Groff Man Page", to);
        break;
      case "dokuwiki":
        writerFormat = plaintextFormat("DocuWiki", to);
        break;
      case "haddock":
        writerFormat = plaintextFormat("Haddock markup", to);
        break;
      case "json":
        writerFormat = plaintextFormat("JSON", to);
        break;
      case "icml":
        writerFormat = plaintextFormat("InDesign", to);
        break;
      case "jira":
        writerFormat = plaintextFormat("Jira Wiki", to);
        break;
      case "mediawiki":
        writerFormat = plaintextFormat("MediaWiki", to);
        break;
      case "xwiki":
        writerFormat = plaintextFormat("XWiki", to);
        break;
      default:
        writerFormat = unknownFormat("txt");
    }
  }
  if (writerFormat === void 0) {
    throw new Error(
      "Should never get here, but TypeScript's analysis doesn't know."
    );
  }
  writerFormat.pandoc = writerFormat.pandoc || {};
  if (!writerFormat.pandoc.to) {
    writerFormat.pandoc.to = pandocTo;
  }
  writerFormat.identifier[kTargetFormat] = to;
  writerFormat.identifier[kBaseFormat] = lookupTo;
  writerFormat.render[kVariant] = mergePandocVariant(
    writerFormat.render[kVariant],
    formatDescriptor.variants.join("")
  );
  return writerFormat;
}
function powerpointFormat() {
  return createFormat("Powerpoint", "pptx", {
    render: {
      [kPageWidth]: 10,
      [kOutputDivs]: false
    },
    execute: {
      [kFigWidth]: 11,
      [kFigHeight]: 5.5,
      [kEcho]: false,
      [kWarning]: false
    },
    pandoc: {
      [kDefaultImageExtension]: "png"
    }
  });
}
function rtfFormat() {
  return createFormat("RTF", "rtf", createWordprocessorFormat("RTF", "rtf"), {
    pandoc: {
      standalone: true
    }
  });
}
function unknownFormat(ext) {
  return createFormat("Unknown", ext);
}
function bibliographyFormat(displayName, ext) {
  return createFormat(displayName, ext);
}
var init_formats = __esm({
  "format/formats.ts"() {
    init_constants6();
    init_format_pdf();
    init_format_epub();
    init_format_docx();
    init_formats_shared();
    init_format_ipynb();
    init_pandoc_formats();
    init_format_markdown();
    init_format_jats();
    init_format_typst();
    init_metadata();
    init_format_handlers();
  }
});

// command/render/render-contexts.ts
async function resolveFormatsFromMetadata(metadata, input, formats2, flags) {
  const includeDir = dirname4(input);
  const frontMatterSchema = await getFrontMatterSchema();
  const included = await includedMetadata(
    includeDir,
    metadata,
    frontMatterSchema
  );
  const allMetadata = mergeQuartoConfigs(
    metadata,
    included.metadata,
    flags?.metadata || {}
  );
  await resolveLanguageMetadata(allMetadata, includeDir);
  const baseFormat = metadataAsFormat(allMetadata);
  if (formats2 === void 0) {
    formats2 = formatKeys(allMetadata);
  }
  if (formats2.length === 0) {
    formats2.push(baseFormat.pandoc.to || baseFormat.pandoc.writer || "html");
  }
  const renderFormats2 = [];
  if (flags?.to === void 0) {
    renderFormats2.push(...formats2);
  } else if (flags?.to === "default") {
    renderFormats2.push(formats2[0]);
  } else {
    const toFormats = flags.to.split(",").flatMap((to) => {
      if (to === "all") {
        return formats2;
      } else {
        return [to];
      }
    });
    renderFormats2.push(...toFormats);
  }
  formats2 = uniq(formats2.concat(renderFormats2));
  const resolved = {};
  formats2.forEach((to) => {
    const format14 = formatFromMetadata(
      baseFormat,
      to,
      flags?.debug
    );
    const config2 = mergeFormatMetadata(baseFormat, format14);
    const defaultFormat2 = defaultWriterFormat(to);
    const resolveFormat = defaultFormat2.resolveFormat;
    if (resolveFormat) {
      resolveFormat(config2);
    }
    if (flags?.execute !== void 0) {
      config2.execute[kExecuteEnabled] = flags?.execute;
    }
    if (flags?.executeCache !== void 0) {
      config2.execute[kCache] = flags?.executeCache;
    }
    if (flags?.executeDaemon !== void 0) {
      config2.execute[kExecuteDaemon] = flags.executeDaemon;
    }
    if (flags?.executeDaemonRestart !== void 0) {
      config2.execute[kExecuteDaemonRestart] = flags.executeDaemonRestart;
    }
    if (flags?.executeDebug !== void 0) {
      config2.execute[kExecuteDebug] = flags.executeDebug;
    }
    resolved[to] = {
      format: config2,
      active: renderFormats2.includes(to)
    };
  });
  return resolved;
}
async function renderContexts(file, options, forExecute, notebookContext2, project, cloneOptions = true, enforceProjectFormats = true) {
  if (cloneOptions) {
    options = safeCloneDeep(options);
  }
  const { engine, target } = await fileExecutionEngineAndTarget(
    file.path,
    options.flags,
    project
  );
  const formats2 = await resolveFormats(
    file,
    target,
    engine,
    options,
    notebookContext2,
    project,
    enforceProjectFormats
  );
  options = removePandocTo(options);
  let libDir = project?.config?.project[kProjectLibDir];
  if (project && libDir) {
    libDir = relative4(dirname4(file.path), join4(project.dir, libDir));
  } else {
    libDir = filesDirLibDir(file.path);
  }
  const contexts = {};
  for (const formatKey of Object.keys(formats2)) {
    formats2[formatKey].format.language = await formatLanguage(
      formats2[formatKey].format.metadata,
      formats2[formatKey].format.language,
      options.flags
    );
    const context = {
      target,
      options,
      engine,
      format: formats2[formatKey].format,
      active: formats2[formatKey].active,
      project,
      libDir
    };
    contexts[formatKey] = context;
    if (!isJupyterNotebook(context.target.source)) {
      const preEngineCellHandlerOptions = {
        name: "",
        // this gets filled out by handleLanguageCells later.
        temp: options.services.temp,
        format: context.format,
        markdown: context.target.markdown,
        context,
        flags: options.flags || {},
        stage: "pre-engine"
      };
      const { markdown, results } = await handleLanguageCells(
        preEngineCellHandlerOptions
      );
      context.target.markdown = markdown;
      if (results) {
        context.target.preEngineExecuteResults = results;
      }
    }
    if (!forExecute && engine.executeTargetSkipped) {
      engine.executeTargetSkipped(target, formats2[formatKey].format);
    }
  }
  return contexts;
}
async function renderFormats(file, services, to = "all", project) {
  const contexts = await renderContexts(
    { path: file },
    { services, flags: { to } },
    false,
    services.notebook,
    project
  );
  const formats2 = {};
  Object.keys(contexts).forEach((formatName) => {
    const context = contexts[formatName];
    const format14 = context.format;
    delete format14.metadata.format;
    deleteProjectMetadata(format14.metadata);
    if (!format14.pandoc[kOutputFile]) {
      const [_dir, stem] = dirAndStem(file);
      format14.pandoc[kOutputFile] = `${stem}.${format14.render[kOutputExt]}`;
    }
    format14.execute[kEngine] = context.engine.name;
    formats2[formatName] = format14;
  });
  return formats2;
}
function mergeQuartoConfigs(config2, ...configs) {
  config2 = safeCloneDeep(config2);
  configs = safeCloneDeep(configs);
  const fixupMergeableScalars = (metadata) => {
    if (metadata === null) return metadata;
    [
      kBibliography,
      kCss,
      kHeaderIncludes,
      kIncludeBefore,
      kIncludeAfter,
      kIncludeInHeader,
      kIncludeBeforeBody,
      kIncludeAfterBody
    ].forEach((key) => {
      if (typeof metadata[key] === "string") {
        metadata[key] = [metadata[key]];
      }
    });
  };
  const fixupFormat = (config3) => {
    const format14 = config3[kMetadataFormat];
    if (typeof format14 === "string") {
      config3.format = { [format14]: {} };
    } else if (format14 instanceof Object) {
      Object.keys(format14).forEach((key) => {
        if (typeof Reflect.get(format14, key) !== "object") {
          Reflect.set(format14, key, {});
        }
        fixupMergeableScalars(Reflect.get(format14, key));
      });
    }
    fixupMergeableScalars(config3);
    return config3;
  };
  return mergeConfigs(
    fixupFormat(config2),
    ...configs.map((c6) => fixupFormat(c6))
  );
}
async function resolveFormats(file, target, engine, options, _notebookContext, project, enforceProjectFormats = true) {
  const inputMetadata = target.metadata;
  const directoryMetadata = project?.dir ? await directoryMetadataForInputFile(
    project,
    dirname4(target.input)
  ) : {};
  const projMetadata = project === void 0 ? {} : await projectMetadataForInputFile(
    target.input,
    project
  );
  let formats2 = [];
  const projFormatKeys = formatKeys(projMetadata);
  const dirFormatKeys = formatKeys(directoryMetadata);
  const inputFormatKeys = uniq(
    formatKeys(inputMetadata).concat(dirFormatKeys)
  );
  const projType = projectType(project?.config?.project?.[kProjectType]);
  if (projType.projectFormatsOnly) {
    formats2 = projFormatKeys;
  } else if (inputFormatKeys.length > 0) {
    formats2 = inputFormatKeys;
  } else {
    formats2 = projFormatKeys;
  }
  if (file.formats) {
    formats2 = formats2.filter((format14) => {
      return file.formats?.includes(format14);
    });
    options = safeCloneDeep(options);
    delete options.flags?.to;
  }
  const projFormats = await resolveFormatsFromMetadata(
    projMetadata,
    target.input,
    formats2,
    options.flags
  );
  const directoryFormats = await resolveFormatsFromMetadata(
    directoryMetadata,
    target.input,
    formats2,
    options.flags
  );
  const inputFormats = await resolveFormatsFromMetadata(
    inputMetadata,
    target.input,
    formats2,
    options.flags
  );
  const activeKeys = (formats3) => {
    return Object.keys(formats3).filter((key) => {
      return formats3[key].active;
    });
  };
  const activeFormatKeys = uniq(
    activeKeys(projFormats).concat(activeKeys(directoryFormats)).concat(
      activeKeys(inputFormats)
    )
  );
  const allFormatKeys = uniq(
    Object.keys(projFormats).concat(Object.keys(directoryFormats)).concat(
      Object.keys(inputFormats)
    )
  );
  const mergedFormats = {};
  for (const format14 of allFormatKeys) {
    const projFormat = projFormats[format14].format;
    const directoryFormat = directoryFormats[format14].format;
    const inputFormat = inputFormats[format14].format;
    const userFormat = mergeFormatMetadata(
      projFormat || {},
      directoryFormat || {},
      inputFormat || {}
    );
    if (userFormat.metadata[kServer] !== void 0) {
      if (userFormat.execute[kEcho] === void 0) {
        userFormat.execute[kEcho] = false;
      }
      if (userFormat.execute[kIpynbShellInteractivity] === void 0) {
        userFormat.execute[kIpynbShellInteractivity] = "all";
      }
    }
    if (options.echo) {
      userFormat.execute[kEcho] = true;
    }
    if (options.warning) {
      userFormat.execute[kWarning] = true;
    }
    const formatDesc = parseFormatString(format14);
    const extensionMetadata = await readExtensionFormat(
      target.source,
      formatDesc,
      options.services.extension,
      project
    );
    mergedFormats[format14] = mergeFormatMetadata(
      defaultWriterFormat(formatDesc.formatWithVariants),
      extensionMetadata[formatDesc.baseFormat] ? extensionMetadata[formatDesc.baseFormat].format : {},
      userFormat
    );
    mergedFormats[format14].identifier[kTargetFormat] = format14;
    mergedFormats[format14].mergeAdditionalFormats = (...configs) => {
      return mergeFormatMetadata(
        defaultWriterFormat(formatDesc.formatWithVariants),
        extensionMetadata[formatDesc.baseFormat] ? extensionMetadata[formatDesc.baseFormat].format : {},
        ...configs,
        userFormat
      );
    };
    const brand = await project.resolveBrand(target.source);
    if (brand) {
      mergedFormats[format14].render.brand = {
        light: brand.light,
        dark: brand.enablesDarkMode || darkModeDefaultMetadata(mergedFormats[format14].metadata) !== void 0 ? brand.dark : void 0
      };
    }
    const brandFormatDefaults = brand?.light?.data?.defaults?.quarto?.format?.[format14];
    if (brandFormatDefaults) {
      mergedFormats[format14].metadata = mergeConfigs(
        brandFormatDefaults,
        mergedFormats[format14].metadata
      );
    }
    const formatIsValid = isValidFormat(
      formatDesc,
      mergedFormats[format14].pandoc
    );
    if (!formatIsValid) {
      throw new Error(`Unknown format ${format14}`);
    }
  }
  if (enforceProjectFormats) {
    for (const formatName of Object.keys(mergedFormats)) {
      const format14 = mergedFormats[formatName];
      if (projType.isSupportedFormat) {
        if (!projType.isSupportedFormat(format14)) {
          delete mergedFormats[formatName];
          warnOnce(
            `The ${formatName} format is not supported by ${projType.type} projects`
          );
        }
      }
    }
  }
  for (const formatName of Object.keys(mergedFormats)) {
    let format14 = mergedFormats[formatName];
    if (hasIpynbFilters(format14.execute)) {
      const markdown = await engine.partitionedMarkdown(target.source, format14);
      if (markdown.yaml) {
        const nbFormats = await resolveFormatsFromMetadata(
          markdown.yaml,
          target.source,
          [formatName],
          { ...options.flags, to: void 0 }
        );
        format14 = mergeConfigs(format14, nbFormats[formatName]);
      }
    }
    if (engine.filterFormat) {
      format14 = engine.filterFormat(
        target.source,
        options,
        format14
      );
    }
    if (projType.filterFormat) {
      format14 = projType.filterFormat(target.source, format14, project);
    }
    mergedFormats[formatName] = format14;
  }
  const finalFormats = {};
  for (const key of Object.keys(mergedFormats)) {
    const active = activeFormatKeys.includes(key);
    finalFormats[key] = {
      format: mergedFormats[key],
      active
    };
  }
  return finalFormats;
}
function hasIpynbFilters(execute) {
  return execute[kIpynbFilters] && execute[kIpynbFilters]?.length;
}
async function projectMetadataForInputFile(input, project) {
  if (project.dir && project.config) {
    return toInputRelativePaths(
      projectType(project.config?.project?.[kProjectType]),
      project.dir,
      dirname4(input),
      safeCloneDeep(project.config)
    );
  } else {
    return safeCloneDeep(project.config) || {};
  }
}
var readExtensionFormat;
var init_render_contexts = __esm({
  async "command/render/render-contexts.ts"() {
    init_path();
    init_lodash();
    init_project_types();
    init_front_matter();
    init_metadata();
    init_constants6();
    init_language();
    init_formats();
    init_config2();
    await init_project_shared();
    init_types4();
    init_log2();
    init_path2();
    await init_engine();
    init_flags2();
    init_render_paths();
    init_jupyter();
    await init_base();
    init_pandoc_formats();
    init_safe_clone_deep();
    init_format_html_info();
    readExtensionFormat = async (file, formatDesc, extensionContext, project) => {
      let effectiveExtension = formatDesc.extension;
      let preferLocal = false;
      if (formatDesc.baseFormat === "typst" && project?.config?.project?.[kProjectType] === "book") {
        if (effectiveExtension) {
          preferLocal = true;
        } else {
          effectiveExtension = "orange-book";
        }
      }
      if (effectiveExtension) {
        const extension = await extensionContext.extension(
          effectiveExtension,
          file,
          project?.config,
          project?.dir,
          preferLocal
        );
        const extensionFormat = extension?.contributes.formats;
        if (extensionFormat) {
          const fmtTarget = formatDesc.modifiers ? `${formatDesc.baseFormat}${formatDesc.modifiers.join("")}` : formatDesc.baseFormat;
          const extensionMetadata = extensionFormat[fmtTarget] || extensionFormat[formatDesc.baseFormat] || {};
          extensionMetadata[kExtensionName] = extensionMetadata[kExtensionName] || effectiveExtension;
          const formats2 = await resolveFormatsFromMetadata(
            extensionMetadata,
            extension.path,
            [formatDesc.baseFormat]
          );
          return formats2;
        } else {
          throw new Error(
            `No valid format ${formatDesc.baseFormat} is provided by the extension ${effectiveExtension}`
          );
        }
      } else {
        return {};
      }
    };
  }
});

// core/git.ts
async function gitCmds(dir, argsArray) {
  for (const args of argsArray) {
    if (!(await execProcess({
      cmd: "git",
      args,
      cwd: dir
    })).success) {
      throw new Error();
    }
  }
}
async function gitVersion() {
  const result2 = await execProcess(
    {
      cmd: "git",
      args: ["--version"],
      stdout: "piped"
    }
  );
  if (!result2.success) {
    throw new Error(
      "Unable to determine git version. Please check that git is installed and available on your PATH."
    );
  }
  const match = result2.stdout?.match(/git version (\d+\.\d+\.\d+)/);
  if (match) {
    return new mod_default(match[1]);
  } else {
    throw new Error(
      `Unable to determine git version from string ${result2.stdout}`
    );
  }
}
async function lsFiles(cwd2, args) {
  if (await which("git")) {
    const result2 = await execProcess({
      cmd: "git",
      args: ["ls-files", ...args || []],
      cwd: cwd2,
      stdout: "piped",
      stderr: "piped"
    });
    if (result2.success) {
      return result2.stdout?.split("\n").filter((file) => {
        return file.length > 0;
      });
    }
  }
  return Promise.resolve(void 0);
}
async function gitBranchExists(branch, cwd2) {
  if (await which("git")) {
    const result2 = await execProcess({
      cmd: "git",
      args: ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`],
      cwd: cwd2,
      stdout: "piped",
      stderr: "piped"
    });
    return result2.code === 0;
  }
  return Promise.resolve(void 0);
}
async function gitUserIdentityConfigured(dir) {
  const name2 = await execProcess({
    cmd: "git",
    args: ["config", "user.name"],
    cwd: dir,
    stdout: "piped",
    stderr: "piped"
  });
  const email = await execProcess({
    cmd: "git",
    args: ["config", "user.email"],
    cwd: dir,
    stdout: "piped",
    stderr: "piped"
  });
  const hasName = name2.success && (name2.stdout?.trim().length ?? 0) > 0 || (Deno.env.get("GIT_AUTHOR_NAME")?.trim().length ?? 0) > 0 || (Deno.env.get("GIT_COMMITTER_NAME")?.trim().length ?? 0) > 0;
  const hasEmail = email.success && (email.stdout?.trim().length ?? 0) > 0 || (Deno.env.get("GIT_AUTHOR_EMAIL")?.trim().length ?? 0) > 0 || (Deno.env.get("GIT_COMMITTER_EMAIL")?.trim().length ?? 0) > 0;
  return hasName && hasEmail;
}
async function gitCmdOutput(dir, args) {
  const result2 = await execProcess({
    cmd: "git",
    args,
    cwd: dir,
    stdout: "piped",
    stderr: "piped"
  });
  if (!result2.success) {
    throw new Error(
      `Git command failed: git ${args.join(" ")}
${result2.stderr || ""}`
    );
  }
  return result2.stdout?.trim() || "";
}
var init_git = __esm({
  "core/git.ts"() {
    init_path2();
    init_process();
    init_mod6();
  }
});

// core/github.ts
async function gitHubContext(dir) {
  const context = {
    git: false,
    repo: false
  };
  context.git = !!await which("git");
  if (context.git) {
    context.repo = (await execProcess({
      cmd: "git",
      args: ["rev-parse"],
      cwd: dir,
      stdout: "piped",
      stderr: "piped"
    })).success;
    if (context.repo) {
      const result2 = await execProcess({
        cmd: "git",
        args: ["config", "--get", "remote.origin.url"],
        cwd: dir,
        stdout: "piped",
        stderr: "piped"
      });
      if (result2.success) {
        context.originUrl = result2.stdout?.trim();
        const ghPagesRemote = await execProcess({
          cmd: "git",
          args: [
            "ls-remote",
            "--quiet",
            "--exit-code",
            "origin",
            "gh-pages"
          ],
          stdout: "piped",
          stderr: "piped"
        });
        context.ghPagesRemote = ghPagesRemote.success;
        if (!ghPagesRemote.success) {
          if (ghPagesRemote.code === 2) {
            context.ghPagesLocal = await gitBranchExists("gh-pages");
          } else {
            throw new Error(
              `There is an error while retrieving information from remote 'origin'.
 Git error: ${ghPagesRemote.stderr}. 
 Git status code: ${ghPagesRemote.code}.`
            );
          }
        }
        context.siteUrl = siteUrl(
          dir,
          context.originUrl
        );
        const repo = repoInfo(context.originUrl);
        if (repo) {
          context.repoUrl = repo.repoUrl;
          context.organization = repo.organization;
          context.repository = repo.repository;
        }
      }
    }
  }
  return context;
}
function repoInfo(originUrl) {
  const match = originUrl?.match(kGithubGitPattern) || originUrl?.match(kGithubHttpsPattern);
  if (match && match.includes(kGithubCom)) {
    return {
      repoUrl: `https://${match[1]}/${match[2]}/${match[3]}/`,
      organization: match[2],
      repository: match[3]
    };
  }
}
function siteUrl(dir, originUrl) {
  const cname = join4(dir, "CNAME");
  if (existsSync2(cname)) {
    const url = Deno.readTextFileSync(cname).trim();
    if (isHttpUrl(url)) {
      return url;
    } else {
      return `https://${url}`;
    }
  } else {
    const match = originUrl?.match(kGithubGitPattern) || originUrl?.match(kGithubHttpsPattern);
    if (match && match.includes(kGithubCom)) {
      const server = match[1].replace(kGithubCom, kGithubIo);
      const domain2 = `${match[2]}.${server}`;
      if (domain2 === match[3]) {
        return `https://${domain2}/`;
      } else {
        return `https://${domain2}/${match[3]}/`;
      }
    }
  }
}
var kGithubCom, kGithubIo, kGithubGitPattern, kGithubHttpsPattern;
var init_github2 = __esm({
  "core/github.ts"() {
    init_path2();
    init_process();
    init_path();
    init_fs();
    init_url();
    init_git();
    kGithubCom = "github.com";
    kGithubIo = "github.io";
    kGithubGitPattern = /^git@([^:]+):([^\/]+)\/(.+?)(?:\.git)?$/;
    kGithubHttpsPattern = /^https:\/\/([^\/]+)\/([^\/]+)\/(.+?)(?:\.git)?$/;
  }
});

// command/render/render-services.ts
function renderServices(notebook) {
  const temp = createTempContext();
  const extension = createExtensionContext();
  if (getNamedLifetime(kRenderServicesLifetime)) {
    return {
      temp,
      extension,
      notebook,
      lifetime: getNamedLifetime(kRenderServicesLifetime),
      cleanup: () => {
      }
    };
  } else {
    const lifetime = createNamedLifetime(kRenderServicesLifetime);
    lifetime.attach(temp);
    lifetime.attach(notebook);
    return {
      temp,
      extension,
      notebook,
      lifetime,
      cleanup: () => {
        lifetime.cleanup();
      }
    };
  }
}
function withRenderServices(notebook, fn) {
  const services = renderServices(notebook);
  return fn(services).finally(() => {
    services.cleanup();
  });
}
var init_render_services = __esm({
  async "command/render/render-services.ts"() {
    init_constants6();
    init_lifetimes();
    init_temp();
    await init_extension();
  }
});

// project/project-environment.ts
var kDefaultContainerTitle, makeProjectEnvironmentMemoizer, computeProjectEnvironment, environmentCommands, kChromiumHint, projectTools, projectEditor;
var init_project_environment = __esm({
  async "project/project-environment.ts"() {
    init_path();
    init_fs();
    init_project_types();
    init_manuscript_types();
    init_format5();
    init_quarto();
    init_github2();
    init_mod6();
    await init_render_services();
    kDefaultContainerTitle = "Default Container";
    makeProjectEnvironmentMemoizer = (notebookContext2) => {
      let cachedEnv = void 0;
      return async (project) => {
        if (cachedEnv) {
          return Promise.resolve(cachedEnv);
        } else {
          cachedEnv = await computeProjectEnvironment(notebookContext2, project);
          return cachedEnv;
        }
      };
    };
    computeProjectEnvironment = async (notebookContext2, context) => {
      const version4 = quartoConfig.version();
      const quarto5 = version4 === kLocalDevelopment ? "prerelease" : new SemVer(version4);
      const github = await gitHubContext(context.dir);
      const containerCtx = {
        title: kDefaultContainerTitle,
        engines: context.engines,
        tools: [],
        codeEnvironment: "vscode",
        quarto: quarto5,
        environments: [],
        openFiles: [],
        envVars: {},
        github
      };
      const editorContext = projectEditor(context);
      containerCtx.codeEnvironment = editorContext.editor;
      containerCtx.openFiles.push(...editorContext.openFiles);
      const title3 = context.config?.project.title;
      if (title3) {
        containerCtx.title = title3;
      }
      const tools = await projectTools(notebookContext2, context);
      containerCtx.tools.push(...tools);
      const envFiles = Object.keys(environmentCommands);
      for (const envFile of envFiles) {
        if (existsSync2(envFile)) {
          containerCtx.environments.push(envFile);
        }
      }
      return containerCtx;
    };
    environmentCommands = {
      // TODO: this needs to happen in correct directory post setup
      // options(repos = c(REPO_NAME = "https://packagemanager.posit.co/cran/__linux__/jammy/latest"))
      "renv.lock": {
        restore: `Rscript -e 'renv::restore();'`
      },
      "requirements.txt": {
        restore: `python3 -m pip install -r requirements.txt`
      },
      "DESCRIPTION": {
        restore: `Rscript -e 'devtools::install_local(getwd())'`
      },
      "install.R": {
        restore: `Rscript install.R`
      },
      "environment.yml": {
        restore: "conda env create -f environment.yml",
        features: {
          "ghcr.io/devcontainers/features/conda:1": {
            addCondaForge: true
          }
        }
      },
      "PipFile": {},
      "PipFile.lock": {},
      "setup.py": {},
      "Project.toml": {},
      "REQUIRE": {}
    };
    kChromiumHint = /````*{mermaid}|{dot}/gm;
    projectTools = async (notebookContext2, context) => {
      let tinytex = false;
      let chromium = false;
      for (const input of context.files.input) {
        if (!tinytex) {
          const formats2 = await withRenderServices(
            notebookContext2,
            (services) => context.renderFormats(input, services, "all", context)
          );
          const hasPdf = Object.values(formats2).some((format14) => {
            return isPdfOutput(format14.pandoc);
          });
          tinytex = hasPdf;
        }
        if (!chromium) {
          const contents = Deno.readTextFileSync(input);
          if (contents.match(kChromiumHint)) {
            chromium = true;
          }
        }
        if (tinytex && chromium) {
          break;
        }
      }
      const tools = [];
      if (tinytex) {
        tools.push("tinytex");
      }
      if (chromium) {
        tools.push("chromium");
      }
      return tools;
    };
    projectEditor = (context) => {
      const qmdCodeTool = context.engines.includes("knitr") ? "rstudio" : "vscode";
      const ipynbCodeTool = "jupyterlab";
      const openFiles = [];
      let editor = qmdCodeTool;
      if (projectType(context.config?.project.type).type === kManuscriptType) {
        const manuscriptConfig = context.config?.[kManuscriptType];
        if (extname4(manuscriptConfig.article) === ".qmd") {
          editor = qmdCodeTool;
        } else {
          editor = ipynbCodeTool;
        }
        openFiles.push(manuscriptConfig.article);
      } else {
        const exts = {};
        const inputs = context.files.input;
        for (const input of inputs) {
          const ext = extname4(input);
          exts[ext] = (exts[ext] || 0) + 1;
        }
        const qmdCount = exts[".qmd"] || 0;
        const ipynbCount = exts[".ipynb"] || 0;
        if (qmdCount >= ipynbCount) {
          editor = qmdCodeTool;
        } else {
          editor = ipynbCodeTool;
        }
      }
      return {
        editor,
        openFiles
      };
    };
  }
});

// project/project-context.ts
var project_context_exports = {};
__export(project_context_exports, {
  mergeExtensionMetadata: () => mergeExtensionMetadata,
  projectContext: () => projectContext,
  projectContextForDirectory: () => projectContextForDirectory,
  projectInputFiles: () => projectInputFiles,
  projectYamlFiles: () => projectYamlFiles,
  resolveEngineExtensions: () => resolveEngineExtensions
});
async function projectContext(path3, notebookContext2, renderOptions, force = false) {
  const flags = renderOptions?.flags;
  let dir = normalizePath(
    Deno.statSync(path3).isDirectory ? path3 : dirname4(path3)
  );
  const originalDir = dir;
  const extensionContext = renderOptions?.services.extension || createExtensionContext();
  const configSchema = await getProjectConfigSchema();
  const configResolvers = [
    quartoYamlProjectConfigResolver(configSchema),
    await projectExtensionsConfigResolver(extensionContext, dir)
  ];
  let cachedEnv = void 0;
  const environment = async (project) => {
    if (cachedEnv) {
      return Promise.resolve(cachedEnv);
    } else {
      cachedEnv = await computeProjectEnvironment(notebookContext2, project);
      return cachedEnv;
    }
  };
  const returnResult = async (context) => {
    if (renderOptions) {
      await mergeExtensionMetadata(context, renderOptions);
    }
    onCleanup(context.cleanup);
    return context;
  };
  while (true) {
    const resolver = configResolvers[0];
    const resolved = await resolver(dir);
    if (resolved) {
      let projectConfig = resolved.config;
      const configFiles = resolved.files;
      projectConfig = migrateProjectConfig(projectConfig);
      const projType = projectConfig.project[kProjectType];
      if (projType && !projectTypes().includes(projType)) {
        projectConfig = await resolveProjectExtension(
          extensionContext,
          projType,
          projectConfig,
          dir
        );
        const configSchema2 = await getProjectConfigSchema();
        const includedMeta = await includedMetadata(
          dir,
          projectConfig,
          configSchema2
        );
        const metadata = includedMeta.metadata;
        projectConfig = mergeProjectMetadata(projectConfig, metadata);
      }
      if (extensionContext) {
        projectConfig = await resolveEngineExtensions(
          extensionContext,
          projectConfig,
          dir
        );
      }
      const result2 = await initializeProfileConfig(
        dir,
        projectConfig,
        configSchema
      );
      projectConfig = result2.config;
      configFiles.push(...result2.files);
      const dotenvFiles = await dotenvSetVariables(dir);
      configFiles.push(...dotenvFiles);
      const varsFile = projectVarsFile(dir);
      if (varsFile) {
        configFiles.push(varsFile);
        const vars = readYaml(varsFile);
        projectConfig[kQuartoVarsKey] = mergeConfigs(
          projectConfig[kQuartoVarsKey] || {},
          vars
        );
      }
      const translationFiles = await resolveLanguageTranslations(
        projectConfig,
        dir
      );
      configFiles.push(...translationFiles);
      if (flags?.to && flags?.to !== "all" && flags?.to !== "default") {
        const projectFormats = normalizeFormatYaml(
          projectConfig[kMetadataFormat]
        );
        const toFormat = projectFormats[flags?.to] || {};
        delete projectFormats[flags?.to];
        const formats2 = {
          [flags?.to]: toFormat
        };
        Object.keys(projectFormats).forEach((format14) => {
          formats2[format14] = projectFormats[format14];
        });
        projectConfig[kMetadataFormat] = formats2;
      }
      if (projectConfig?.project) {
        if (flags?.outputDir) {
          projectConfig.project[kProjectOutputDir] = flags.outputDir;
        }
        if (typeof projectConfig.project[kProjectPreRender] === "string") {
          projectConfig.project[kProjectPreRender] = [
            projectConfig.project[kProjectPreRender]
          ];
        }
        if (typeof projectConfig.project[kProjectPostRender] === "string") {
          projectConfig.project[kProjectPostRender] = [
            projectConfig.project[kProjectPostRender]
          ];
        }
        const type4 = projectType(projectConfig.project?.[kProjectType]);
        if (projectConfig.project[kProjectLibDir] === void 0 && type4.libDir) {
          projectConfig.project[kProjectLibDir] = type4.libDir;
        }
        if (!projectConfig.project[kProjectOutputDir] && type4.outputDir) {
          projectConfig.project[kProjectOutputDir] = type4.outputDir;
        }
        const outputDir = projectConfig.project[kProjectOutputDir];
        if (outputDir) {
          const resolvedOutputDir = resolve4(dir, outputDir);
          const resolvedDir = resolve4(dir);
          if (resolvedOutputDir === resolvedDir) {
            delete projectConfig.project[kProjectOutputDir];
          }
        }
        const projOutputDir = projectConfig.project[kProjectOutputDir];
        if (projOutputDir && isAbsolute4(projOutputDir)) {
          projectConfig.project[kProjectOutputDir] = relative4(
            dir,
            projOutputDir
          );
        }
        const temp = createTempContext({
          dir: join4(dir, ".quarto"),
          prefix: "quarto-session-temp"
        });
        const fileInformationCache = new FileInformationCacheMap();
        const result3 = {
          clone: () => result3,
          resolveBrand: async (fileName) => projectResolveBrand(result3, fileName),
          resolveFullMarkdownForFile: (engine, file, markdown, force2) => {
            return projectResolveFullMarkdownForFile(
              result3,
              engine,
              file,
              markdown,
              force2
            );
          },
          dir,
          engines: [],
          fileInformationCache,
          files: {
            input: []
          },
          config: projectConfig,
          // this is a relatively ugly hack to avoid a circular import chain
          // that causes a deno bundler bug;
          renderFormats,
          environment: () => environment(result3),
          notebookContext: notebookContext2,
          fileExecutionEngineAndTarget: (file) => {
            return fileExecutionEngineAndTarget(
              file,
              flags,
              result3
            );
          },
          fileMetadata: async (file, force2) => {
            return projectFileMetadata(result3, file, force2);
          },
          isSingleFile: false,
          previewServer: renderOptions?.previewServer,
          diskCache: await createProjectCache(join4(dir, ".quarto")),
          temp,
          cleanup: () => {
            cleanupFileInformationCache(result3);
            result3.diskCache.close();
            temp.cleanup();
          }
        };
        if (type4.config) {
          result3.config = await type4.config(
            result3,
            projectConfig,
            flags
          );
        }
        const { files, engines } = await projectInputFiles(
          result3,
          projectConfig
        );
        const fullPath = normalizePath(path3);
        if (Deno.statSync(fullPath).isFile && !files.includes(fullPath)) {
          return void 0;
        }
        if (type4.formatExtras) {
          result3.formatExtras = async (source2, flags2, format14, services) => type4.formatExtras(result3, source2, flags2, format14, services);
        }
        result3.engines = engines;
        result3.files = {
          input: files,
          resources: projectResourceFiles(dir, projectConfig),
          config: configFiles,
          configResources: projectConfigResources(dir, projectConfig, type4)
        };
        return await returnResult(result3);
      } else {
        const temp = createTempContext({
          dir: join4(dir, ".quarto"),
          prefix: "quarto-session-temp"
        });
        const fileInformationCache = new FileInformationCacheMap();
        const result3 = {
          clone: () => result3,
          resolveBrand: async (fileName) => projectResolveBrand(result3, fileName),
          resolveFullMarkdownForFile: (engine, file, markdown, force2) => {
            return projectResolveFullMarkdownForFile(
              result3,
              engine,
              file,
              markdown,
              force2
            );
          },
          dir,
          config: projectConfig,
          engines: [],
          fileInformationCache,
          files: {
            input: []
          },
          renderFormats,
          environment: () => environment(result3),
          fileExecutionEngineAndTarget: (file) => {
            return fileExecutionEngineAndTarget(
              file,
              flags,
              result3
            );
          },
          fileMetadata: async (file, force2) => {
            return projectFileMetadata(result3, file, force2);
          },
          notebookContext: notebookContext2,
          isSingleFile: false,
          previewServer: renderOptions?.previewServer,
          diskCache: await createProjectCache(join4(dir, ".quarto")),
          temp,
          cleanup: () => {
            cleanupFileInformationCache(result3);
            result3.diskCache.close();
            temp.cleanup();
          }
        };
        const { files, engines } = await projectInputFiles(
          result3,
          projectConfig
        );
        result3.engines = engines;
        result3.files = {
          input: files,
          resources: projectResourceFiles(dir, projectConfig),
          config: configFiles,
          configResources: projectConfigResources(dir, projectConfig)
        };
        return await returnResult(result3);
      }
    } else {
      const nextDir = dirname4(dir);
      if (nextDir === dir) {
        if (configResolvers.length > 1) {
          dir = originalDir;
          configResolvers.shift();
        } else if (force) {
          const temp = createTempContext({
            dir: join4(originalDir, ".quarto"),
            prefix: "quarto-session-temp"
          });
          const fileInformationCache = new FileInformationCacheMap();
          const context = {
            clone: () => context,
            resolveBrand: async (fileName) => projectResolveBrand(context, fileName),
            resolveFullMarkdownForFile: (engine, file, markdown, force2) => {
              return projectResolveFullMarkdownForFile(
                context,
                engine,
                file,
                markdown,
                force2
              );
            },
            dir: originalDir,
            engines: [],
            config: {
              project: {
                [kProjectOutputDir]: flags?.outputDir
              }
            },
            fileInformationCache,
            files: {
              input: []
            },
            renderFormats,
            environment: () => environment(context),
            notebookContext: notebookContext2,
            fileExecutionEngineAndTarget: (file) => {
              return fileExecutionEngineAndTarget(
                file,
                flags,
                context
              );
            },
            fileMetadata: async (file, force2) => {
              return projectFileMetadata(context, file, force2);
            },
            isSingleFile: false,
            previewServer: renderOptions?.previewServer,
            diskCache: await createProjectCache(join4(temp.baseDir, ".quarto")),
            temp,
            cleanup: () => {
              cleanupFileInformationCache(context);
              context.diskCache.close();
              temp.cleanup();
            }
          };
          if (Deno.statSync(path3).isDirectory) {
            const { files, engines } = await projectInputFiles(context);
            context.engines = engines;
            context.files.input = files;
          } else {
            const input = normalizePath(path3);
            const engine = await fileExecutionEngine(input, void 0, context);
            context.engines = [engine?.name ?? kMarkdownEngine];
            context.files.input = [input];
          }
          return await returnResult(context);
        } else {
          return void 0;
        }
      } else {
        dir = nextDir;
      }
    }
  }
}
function quartoYamlProjectConfigResolver(configSchema) {
  return async (dir) => {
    let configFile = void 0;
    try {
      configFile = projectConfigFile(dir);
    } catch (e5) {
      if (e5 instanceof Deno.errors.PermissionDenied) {
      } else {
        throw e5;
      }
    }
    if (configFile) {
      const files = [configFile];
      const errMsg = `Project ${configFile} validation failed.`;
      let config2 = await readAndValidateYamlFromFile(
        configFile,
        configSchema,
        errMsg,
        kDefaultProjectFileContents
      );
      config2.project = config2.project || {};
      const includedMeta = await includedMetadata(
        dir,
        config2,
        configSchema
      );
      const metadata = includedMeta.metadata;
      files.push(...includedMeta.files);
      config2 = mergeProjectMetadata(config2, metadata);
      delete config2[kMetadataFile];
      delete config2[kMetadataFiles];
      return { config: config2, files };
    } else {
      return void 0;
    }
  };
}
async function projectExtensionsConfigResolver(context, dir) {
  const projectTypeDetectors = (await context.extensions(dir)).reduce(
    (projectTypeDetectors2, extension) => {
      if (extension.contributes.project) {
        const project = extension.contributes.project;
        if (project?.project?.detect) {
          const detect = asArray(project?.project.detect);
          projectTypeDetectors2.push({
            type: extension.id.name,
            detect
          });
        }
      }
      return projectTypeDetectors2;
    },
    []
  );
  return (dir2) => {
    for (const detector of projectTypeDetectors) {
      if (detector.detect.some(
        (files) => files.every((file) => safeExistsSync(join4(dir2, file)))
      )) {
        return Promise.resolve({
          config: {
            project: {
              type: detector.type
            }
          },
          files: []
        });
      }
    }
    return Promise.resolve(void 0);
  };
}
async function resolveProjectExtension(context, projectType2, projectConfig, dir) {
  const extensions2 = await context.find(
    projectType2,
    dir,
    "project",
    projectConfig,
    dir
  );
  const filtered = filterExtensions(extensions2, projectType2, "project");
  if (filtered.length > 0) {
    const extension = filtered[0];
    const projectExt = extension.contributes.project;
    if (projectExt) {
      const projectExtConfig = cloneDeep(projectExt);
      delete projectExtConfig.project.detect;
      if (projectConfig.project.render) {
        delete projectExtConfig.project.render;
      }
      const extProjType = () => {
        const projectMeta = projectExt.project;
        if (projectMeta && typeof projectMeta === "object") {
          const extType = projectMeta.type;
          if (typeof extType === "string") {
            return extType;
          } else {
            return "default";
          }
        } else {
          return "default";
        }
      };
      projectConfig.project[kProjectType] = extProjType();
      projectConfig = mergeProjectMetadata(
        projectExtConfig,
        projectConfig
      );
    }
  }
  return projectConfig;
}
async function resolveEngineExtensions(context, projectConfig, dir) {
  if (projectConfig.engines) {
    projectConfig.engines = projectConfig.engines.map(
      (engine) => {
        if (typeof engine === "object" && engine.path && !isAbsolute4(engine.path)) {
          return {
            ...engine,
            path: join4(dir, engine.path)
          };
        }
        return engine;
      }
    );
  }
  const extensions2 = await context.extensions(
    void 0,
    projectConfig,
    dir
  );
  const engineExtensions = extensions2.filter(
    (extension) => extension.contributes.engines !== void 0 && extension.contributes.engines.length > 0
  );
  if (engineExtensions.length > 0) {
    if (!projectConfig.engines) {
      projectConfig.engines = [];
    }
    const existingEngines = projectConfig.engines;
    const extensionEngines = engineExtensions.map((extension) => extension.contributes.engines).flat();
    projectConfig.engines = [...existingEngines, ...extensionEngines];
  }
  return projectConfig;
}
function migrateProjectConfig(projectConfig) {
  const kSite = "site";
  if (projectConfig.project[kProjectType] !== kSite && projectConfig[kSite] === void 0) {
    return projectConfig;
  }
  projectConfig = cloneDeep(projectConfig);
  if (projectConfig.project[kProjectType] === kSite) {
    projectConfig.project[kProjectType] = kWebsite;
  }
  if (projectConfig[kSite]) {
    projectConfig[kWebsite] = cloneDeep(projectConfig[kSite]);
    delete projectConfig[kSite];
  }
  return projectConfig;
}
async function resolveLanguageTranslations(projectConfig, dir) {
  const files = [];
  files.push(...await resolveLanguageMetadata(projectConfig, dir));
  const translations = await readLanguageTranslations(
    join4(dir, "_language.yml")
  );
  projectConfig[kLanguageDefaults] = mergeConfigs(
    translations.language,
    projectConfig[kLanguageDefaults]
  );
  files.push(...translations.files);
  return files;
}
function projectContextForDirectory(path3, notebookContext2, renderOptions) {
  return projectContext(path3, notebookContext2, renderOptions, true);
}
function projectYamlFiles(dir) {
  const files = [];
  const projIgnoreGlobs = projectHiddenIgnoreGlob(dir);
  for (const walk5 of walkSync(dir, {
    includeDirs: true,
    // this was done b/c some directories e.g. renv/packrat and potentially python
    // virtualenvs include symblinks to R or Python libraries that are in turn
    // circular. much safer to not follow symlinks!
    followSymlinks: false,
    skip: [kSkipHidden].concat(
      projIgnoreGlobs.map((ignore3) => globToRegExp4(join4(dir, ignore3) + SEP))
    )
  })) {
    if (walk5.isFile && isYamlPath(walk5.path)) {
      files.push(walk5.path);
    }
  }
  return files;
}
function projectHiddenIgnoreGlob(dir) {
  return projectIgnoreGlobs(dir).concat(["**/_*", "**/_*/**"]).concat(["**/.*", "**/.*/**"]).concat(["**/README.?([Rrq])md"]).concat(["**/CLAUDE.md", "**/CLAUDE.local.md"]).concat(["**/AGENTS.md", "**/AGENTS.local.md"]).concat(["**/*.llms.md"]);
}
async function projectInputFilesInternal(project, metadata) {
  await resolveEngines(project);
  const { dir } = project;
  const outputDir = metadata?.project[kProjectOutputDir];
  const projIgnoreGlobs = projectHiddenIgnoreGlob(dir);
  const projectIgnores = projIgnoreGlobs.map(
    (glob) => globToRegExp4(glob, { extended: true, globstar: true })
  );
  const addFile = async (file) => {
    if (outputDir && ensureTrailingSlash(dirname4(file)).startsWith(
      ensureTrailingSlash(join4(dir, outputDir))
    ) && ensureTrailingSlash(join4(dir, outputDir)).startsWith(
      ensureTrailingSlash(dir)
    )) {
      return [];
    }
    const engine = await fileExecutionEngine(file, void 0, project);
    if (!engine) {
      return [];
    }
    const engineIntermediates = executionEngineIntermediateFiles(
      engine,
      file
    );
    return [{
      file,
      engineName: engine.name,
      engineIntermediates
    }];
  };
  const addDir = async (dir2) => {
    const promises2 = [];
    for await (const walkEntry of walk(dir2, {
      includeDirs: false,
      // this was done b/c some directories e.g. renv/packrat and potentially python
      // virtualenvs include symblinks to R or Python libraries that are in turn
      // circular. much safer to not follow symlinks!
      followSymlinks: false,
      skip: [kSkipHidden].concat(
        engineIgnoreDirs().map(
          (ignore3) => globToRegExp4(join4(dir2, ignore3) + SEP)
        )
      )
    })) {
      const pathRelative = pathWithForwardSlashes(
        relative4(dir2, walkEntry.path)
      );
      if (projectIgnores.some((regex) => regex.test(pathRelative))) {
        continue;
      }
      promises2.push(addFile(walkEntry.path));
    }
    const inclusions2 = await Promise.all(promises2);
    return inclusions2.flat();
  };
  const addEntry = async (entry) => {
    if (Deno.statSync(entry).isDirectory) {
      return addDir(entry);
    } else {
      return addFile(entry);
    }
  };
  const renderFiles2 = metadata?.project[kProjectRender];
  let inclusions;
  if (renderFiles2) {
    const exclude = projIgnoreGlobs.concat(outputDir ? [outputDir] : []);
    const resolved = resolvePathGlobs(dir, renderFiles2, exclude, {
      mode: "auto"
    });
    const toInclude = difference(
      resolved.include,
      resolved.exclude
    );
    inclusions = (await Promise.all(toInclude.map(addEntry))).flat();
  } else {
    inclusions = await addDir(dir);
  }
  const files = inclusions.map((inclusion) => inclusion.file);
  const engines = uniq(inclusions.map((inclusion) => inclusion.engineName));
  const intermediateFiles = inclusions.map(
    (inclusion) => inclusion.engineIntermediates
  ).flat();
  const inputFiles = Array.from(
    new Set(files).difference(new Set(intermediateFiles))
  );
  return { files: inputFiles, engines };
}
function projectConfigResources(dir, metadata, type4) {
  const resourceIgnoreFields = ignoreFieldsForProjectType(type4);
  const resources = [];
  const findResources = (collection, parentKey) => {
    forEach(
      collection,
      (value, index2) => {
        if (parentKey === kHtmlMathMethod && index2 === "method") {
        } else if (resourceIgnoreFields.includes(index2)) {
        } else if (Array.isArray(value)) {
          findResources(value);
        } else if (typeof value === "object") {
          findResources(value, index2);
        } else if (typeof value === "string") {
          const path3 = isAbsolute4(value) ? value : join4(dir, value);
          try {
            if (existsSync2(path3) && !Deno.statSync(path3).isDirectory) {
              resources.push(normalizePath(path3));
            }
          } catch {
          }
        }
      }
    );
  };
  findResources(metadata);
  return resources;
}
var mergeExtensionMetadata, projectInputFiles;
var init_project_context = __esm({
  async "project/project-context.ts"() {
    init_path();
    init_fs();
    init_lodash();
    init_types4();
    init_yaml();
    init_config2();
    init_path2();
    init_metadata();
    init_constants6();
    init_project_types();
    init_path2();
    init_language();
    await init_engine();
    init_types3();
    init_project_resources();
    await init_project_shared();
    init_website_constants();
    init_validated_yaml2();
    init_project_config();
    init_project_default();
    await init_extension();
    init_project_profile();
    init_dotenv();
    init_array();
    await init_render_contexts();
    await init_project_environment();
    init_function_times();
    init_cache3();
    init_temp();
    init_cleanup();
    init_schema_types();
    mergeExtensionMetadata = async (context, pOptions) => {
      if (context.config) {
        const extensions2 = await pOptions.services.extension.extensions(
          void 0,
          context.config,
          context.dir,
          { builtIn: false }
        );
        const projectMetadata = extensions2.filter(
          (extension) => extension.contributes.metadata?.project
        ).map((extension) => {
          return Zod.ProjectConfig.parse(extension.contributes.metadata.project);
        });
        context.config.project = mergeProjectMetadata(
          context.config.project,
          ...projectMetadata
        );
      }
    };
    projectInputFiles = makeTimedFunctionAsync(
      "projectInputFiles",
      projectInputFilesInternal
    );
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/acorn@8.16.0/node_modules/acorn/dist/acorn.js
var require_acorn = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/acorn@8.16.0/node_modules/acorn/dist/acorn.js"(exports23, module2) {
    (function(global2, factory4) {
      typeof exports23 === "object" && typeof module2 !== "undefined" ? factory4(exports23) : typeof define === "function" && define.amd ? define(["exports"], factory4) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, factory4(global2.acorn = {}));
    })(exports23, (function(exports24) {
      "use strict";
      var astralIdentifierCodes3 = [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];
      var astralIdentifierStartCodes3 = [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 nonASCIIidentifierChars3 = "\u200C\u200D\xB7\u0300-\u036F\u0387\u0483-\u0487\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u0669\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07C0-\u07C9\u07EB-\u07F3\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 nonASCIIidentifierStartChars3 = "\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 reservedWords3 = {
        3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",
        5: "class enum extends super const export import",
        6: "enum",
        strict: "implements interface let package private protected public static yield",
        strictBind: "eval arguments"
      };
      var ecma5AndLessKeywords3 = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";
      var keywords$13 = {
        5: ecma5AndLessKeywords3,
        "5module": ecma5AndLessKeywords3 + " export import",
        6: ecma5AndLessKeywords3 + " const class extends export import super"
      };
      var keywordRelationalOperator3 = /^in(stanceof)?$/;
      var nonASCIIidentifierStart3 = new RegExp("[" + nonASCIIidentifierStartChars3 + "]");
      var nonASCIIidentifier3 = new RegExp("[" + nonASCIIidentifierStartChars3 + nonASCIIidentifierChars3 + "]");
      function isInAstralSet3(code5, set3) {
        var pos = 65536;
        for (var i7 = 0; i7 < set3.length; i7 += 2) {
          pos += set3[i7];
          if (pos > code5) {
            return false;
          }
          pos += set3[i7 + 1];
          if (pos >= code5) {
            return true;
          }
        }
        return false;
      }
      function isIdentifierStart3(code5, astral) {
        if (code5 < 65) {
          return code5 === 36;
        }
        if (code5 < 91) {
          return true;
        }
        if (code5 < 97) {
          return code5 === 95;
        }
        if (code5 < 123) {
          return true;
        }
        if (code5 <= 65535) {
          return code5 >= 170 && nonASCIIidentifierStart3.test(String.fromCharCode(code5));
        }
        if (astral === false) {
          return false;
        }
        return isInAstralSet3(code5, astralIdentifierStartCodes3);
      }
      function isIdentifierChar3(code5, astral) {
        if (code5 < 48) {
          return code5 === 36;
        }
        if (code5 < 58) {
          return true;
        }
        if (code5 < 65) {
          return false;
        }
        if (code5 < 91) {
          return true;
        }
        if (code5 < 97) {
          return code5 === 95;
        }
        if (code5 < 123) {
          return true;
        }
        if (code5 <= 65535) {
          return code5 >= 170 && nonASCIIidentifier3.test(String.fromCharCode(code5));
        }
        if (astral === false) {
          return false;
        }
        return isInAstralSet3(code5, astralIdentifierStartCodes3) || isInAstralSet3(code5, astralIdentifierCodes3);
      }
      var TokenType4 = function TokenType5(label, conf) {
        if (conf === void 0) conf = {};
        this.label = label;
        this.keyword = conf.keyword;
        this.beforeExpr = !!conf.beforeExpr;
        this.startsExpr = !!conf.startsExpr;
        this.isLoop = !!conf.isLoop;
        this.isAssign = !!conf.isAssign;
        this.prefix = !!conf.prefix;
        this.postfix = !!conf.postfix;
        this.binop = conf.binop || null;
        this.updateContext = null;
      };
      function binop3(name2, prec) {
        return new TokenType4(name2, { beforeExpr: true, binop: prec });
      }
      var beforeExpr3 = { beforeExpr: true }, startsExpr3 = { startsExpr: true };
      var keywords3 = {};
      function kw3(name2, options) {
        if (options === void 0) options = {};
        options.keyword = name2;
        return keywords3[name2] = new TokenType4(name2, options);
      }
      var types$13 = {
        num: new TokenType4("num", startsExpr3),
        regexp: new TokenType4("regexp", startsExpr3),
        string: new TokenType4("string", startsExpr3),
        name: new TokenType4("name", startsExpr3),
        privateId: new TokenType4("privateId", startsExpr3),
        eof: new TokenType4("eof"),
        // Punctuation token types.
        bracketL: new TokenType4("[", { beforeExpr: true, startsExpr: true }),
        bracketR: new TokenType4("]"),
        braceL: new TokenType4("{", { beforeExpr: true, startsExpr: true }),
        braceR: new TokenType4("}"),
        parenL: new TokenType4("(", { beforeExpr: true, startsExpr: true }),
        parenR: new TokenType4(")"),
        comma: new TokenType4(",", beforeExpr3),
        semi: new TokenType4(";", beforeExpr3),
        colon: new TokenType4(":", beforeExpr3),
        dot: new TokenType4("."),
        question: new TokenType4("?", beforeExpr3),
        questionDot: new TokenType4("?."),
        arrow: new TokenType4("=>", beforeExpr3),
        template: new TokenType4("template"),
        invalidTemplate: new TokenType4("invalidTemplate"),
        ellipsis: new TokenType4("...", beforeExpr3),
        backQuote: new TokenType4("`", startsExpr3),
        dollarBraceL: new TokenType4("${", { beforeExpr: true, startsExpr: true }),
        // Operators. These carry several kinds of properties to help the
        // parser use them properly (the presence of these properties is
        // what categorizes them as operators).
        //
        // `binop`, when present, specifies that this operator is a binary
        // operator, and will refer to its precedence.
        //
        // `prefix` and `postfix` mark the operator as a prefix or postfix
        // unary operator.
        //
        // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
        // binary operators with a very low precedence, that should result
        // in AssignmentExpression nodes.
        eq: new TokenType4("=", { beforeExpr: true, isAssign: true }),
        assign: new TokenType4("_=", { beforeExpr: true, isAssign: true }),
        incDec: new TokenType4("++/--", { prefix: true, postfix: true, startsExpr: true }),
        prefix: new TokenType4("!/~", { beforeExpr: true, prefix: true, startsExpr: true }),
        logicalOR: binop3("||", 1),
        logicalAND: binop3("&&", 2),
        bitwiseOR: binop3("|", 3),
        bitwiseXOR: binop3("^", 4),
        bitwiseAND: binop3("&", 5),
        equality: binop3("==/!=/===/!==", 6),
        relational: binop3("</>/<=/>=", 7),
        bitShift: binop3("<</>>/>>>", 8),
        plusMin: new TokenType4("+/-", { beforeExpr: true, binop: 9, prefix: true, startsExpr: true }),
        modulo: binop3("%", 10),
        star: binop3("*", 10),
        slash: binop3("/", 10),
        starstar: new TokenType4("**", { beforeExpr: true }),
        coalesce: binop3("??", 1),
        // Keyword token types.
        _break: kw3("break"),
        _case: kw3("case", beforeExpr3),
        _catch: kw3("catch"),
        _continue: kw3("continue"),
        _debugger: kw3("debugger"),
        _default: kw3("default", beforeExpr3),
        _do: kw3("do", { isLoop: true, beforeExpr: true }),
        _else: kw3("else", beforeExpr3),
        _finally: kw3("finally"),
        _for: kw3("for", { isLoop: true }),
        _function: kw3("function", startsExpr3),
        _if: kw3("if"),
        _return: kw3("return", beforeExpr3),
        _switch: kw3("switch"),
        _throw: kw3("throw", beforeExpr3),
        _try: kw3("try"),
        _var: kw3("var"),
        _const: kw3("const"),
        _while: kw3("while", { isLoop: true }),
        _with: kw3("with"),
        _new: kw3("new", { beforeExpr: true, startsExpr: true }),
        _this: kw3("this", startsExpr3),
        _super: kw3("super", startsExpr3),
        _class: kw3("class", startsExpr3),
        _extends: kw3("extends", beforeExpr3),
        _export: kw3("export"),
        _import: kw3("import", startsExpr3),
        _null: kw3("null", startsExpr3),
        _true: kw3("true", startsExpr3),
        _false: kw3("false", startsExpr3),
        _in: kw3("in", { beforeExpr: true, binop: 7 }),
        _instanceof: kw3("instanceof", { beforeExpr: true, binop: 7 }),
        _typeof: kw3("typeof", { beforeExpr: true, prefix: true, startsExpr: true }),
        _void: kw3("void", { beforeExpr: true, prefix: true, startsExpr: true }),
        _delete: kw3("delete", { beforeExpr: true, prefix: true, startsExpr: true })
      };
      var lineBreak3 = /\r\n?|\n|\u2028|\u2029/;
      var lineBreakG3 = new RegExp(lineBreak3.source, "g");
      function isNewLine3(code5) {
        return code5 === 10 || code5 === 13 || code5 === 8232 || code5 === 8233;
      }
      function nextLineBreak(code5, from, end) {
        if (end === void 0) end = code5.length;
        for (var i7 = from; i7 < end; i7++) {
          var next = code5.charCodeAt(i7);
          if (isNewLine3(next)) {
            return i7 < end - 1 && next === 13 && code5.charCodeAt(i7 + 1) === 10 ? i7 + 2 : i7 + 1;
          }
        }
        return -1;
      }
      var nonASCIIwhitespace3 = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
      var skipWhiteSpace3 = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
      var ref3 = Object.prototype;
      var hasOwnProperty3 = ref3.hasOwnProperty;
      var toString8 = ref3.toString;
      var hasOwn2 = Object.hasOwn || (function(obj, propName) {
        return hasOwnProperty3.call(obj, propName);
      });
      var isArray6 = Array.isArray || (function(obj) {
        return toString8.call(obj) === "[object Array]";
      });
      var regexpCache = /* @__PURE__ */ Object.create(null);
      function wordsRegexp3(words) {
        return regexpCache[words] || (regexpCache[words] = new RegExp("^(?:" + words.replace(/ /g, "|") + ")$"));
      }
      function codePointToString3(code5) {
        if (code5 <= 65535) {
          return String.fromCharCode(code5);
        }
        code5 -= 65536;
        return String.fromCharCode((code5 >> 10) + 55296, (code5 & 1023) + 56320);
      }
      var loneSurrogate = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/;
      var Position4 = function Position5(line, col) {
        this.line = line;
        this.column = col;
      };
      Position4.prototype.offset = function offset3(n5) {
        return new Position4(this.line, this.column + n5);
      };
      var SourceLocation4 = function SourceLocation5(p5, start, end) {
        this.start = start;
        this.end = end;
        if (p5.sourceFile !== null) {
          this.source = p5.sourceFile;
        }
      };
      function getLineInfo3(input, offset3) {
        for (var line = 1, cur = 0; ; ) {
          var nextBreak = nextLineBreak(input, cur, offset3);
          if (nextBreak < 0) {
            return new Position4(line, offset3 - cur);
          }
          ++line;
          cur = nextBreak;
        }
      }
      var defaultOptions3 = {
        // `ecmaVersion` indicates the ECMAScript version to parse. Must be
        // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10
        // (2019), 11 (2020), 12 (2021), 13 (2022), 14 (2023), or `"latest"`
        // (the latest version the library supports). This influences
        // support for strict mode, the set of reserved words, and support
        // for new syntax features.
        ecmaVersion: null,
        // `sourceType` indicates the mode the code should be parsed in.
        // Can be either `"script"`, `"module"` or `"commonjs"`. This influences global
        // strict mode and parsing of `import` and `export` declarations.
        sourceType: "script",
        // `onInsertedSemicolon` can be a callback that will be called when
        // a semicolon is automatically inserted. It will be passed the
        // position of the inserted semicolon as an offset, and if
        // `locations` is enabled, it is given the location as a `{line,
        // column}` object as second argument.
        onInsertedSemicolon: null,
        // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
        // trailing commas.
        onTrailingComma: null,
        // By default, reserved words are only enforced if ecmaVersion >= 5.
        // Set `allowReserved` to a boolean value to explicitly turn this on
        // an off. When this option has the value "never", reserved words
        // and keywords can also not be used as property names.
        allowReserved: null,
        // When enabled, a return at the top level is not considered an
        // error.
        allowReturnOutsideFunction: false,
        // When enabled, import/export statements are not constrained to
        // appearing at the top of the program, and an import.meta expression
        // in a script isn't considered an error.
        allowImportExportEverywhere: false,
        // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022.
        // When enabled, await identifiers are allowed to appear at the top-level scope,
        // but they are still not allowed in non-async functions.
        allowAwaitOutsideFunction: null,
        // When enabled, super identifiers are not constrained to
        // appearing in methods and do not raise an error when they appear elsewhere.
        allowSuperOutsideMethod: null,
        // When enabled, hashbang directive in the beginning of file is
        // allowed and treated as a line comment. Enabled by default when
        // `ecmaVersion` >= 2023.
        allowHashBang: false,
        // By default, the parser will verify that private properties are
        // only used in places where they are valid and have been declared.
        // Set this to false to turn such checks off.
        checkPrivateFields: true,
        // When `locations` is on, `loc` properties holding objects with
        // `start` and `end` properties in `{line, column}` form (with
        // line being 1-based and column 0-based) will be attached to the
        // nodes.
        locations: false,
        // A function can be passed as `onToken` option, which will
        // cause Acorn to call that function with object in the same
        // format as tokens returned from `tokenizer().getToken()`. Note
        // that you are not allowed to call the parser from the
        // callback—that will corrupt its internal state.
        onToken: null,
        // A function can be passed as `onComment` option, which will
        // cause Acorn to call that function with `(block, text, start,
        // end)` parameters whenever a comment is skipped. `block` is a
        // boolean indicating whether this is a block (`/* */`) comment,
        // `text` is the content of the comment, and `start` and `end` are
        // character offsets that denote the start and end of the comment.
        // When the `locations` option is on, two more parameters are
        // passed, the full `{line, column}` locations of the start and
        // end of the comments. Note that you are not allowed to call the
        // parser from the callback—that will corrupt its internal state.
        // When this option has an array as value, objects representing the
        // comments are pushed to it.
        onComment: null,
        // Nodes have their start and end characters offsets recorded in
        // `start` and `end` properties (directly on the node, rather than
        // the `loc` object, which holds line/column data. To also add a
        // [semi-standardized][range] `range` property holding a `[start,
        // end]` array with the same numbers, set the `ranges` option to
        // `true`.
        //
        // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
        ranges: false,
        // It is possible to parse multiple files into a single AST by
        // passing the tree produced by parsing the first file as
        // `program` option in subsequent parses. This will add the
        // toplevel forms of the parsed file to the `Program` (top) node
        // of an existing parse tree.
        program: null,
        // When `locations` is on, you can pass this to record the source
        // file in every node's `loc` object.
        sourceFile: null,
        // This value, if given, is stored in every node, whether
        // `locations` is on or off.
        directSourceFile: null,
        // When enabled, parenthesized expressions are represented by
        // (non-standard) ParenthesizedExpression nodes
        preserveParens: false
      };
      var warnedAboutEcmaVersion2 = false;
      function getOptions3(opts) {
        var options = {};
        for (var opt in defaultOptions3) {
          options[opt] = opts && hasOwn2(opts, opt) ? opts[opt] : defaultOptions3[opt];
        }
        if (options.ecmaVersion === "latest") {
          options.ecmaVersion = 1e8;
        } else if (options.ecmaVersion == null) {
          if (!warnedAboutEcmaVersion2 && typeof console === "object" && console.warn) {
            warnedAboutEcmaVersion2 = true;
            console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.");
          }
          options.ecmaVersion = 11;
        } else if (options.ecmaVersion >= 2015) {
          options.ecmaVersion -= 2009;
        }
        if (options.allowReserved == null) {
          options.allowReserved = options.ecmaVersion < 5;
        }
        if (!opts || opts.allowHashBang == null) {
          options.allowHashBang = options.ecmaVersion >= 14;
        }
        if (isArray6(options.onToken)) {
          var tokens2 = options.onToken;
          options.onToken = function(token) {
            return tokens2.push(token);
          };
        }
        if (isArray6(options.onComment)) {
          options.onComment = pushComment3(options, options.onComment);
        }
        if (options.sourceType === "commonjs" && options.allowAwaitOutsideFunction) {
          throw new Error("Cannot use allowAwaitOutsideFunction with sourceType: commonjs");
        }
        return options;
      }
      function pushComment3(options, array) {
        return function(block, text, start, end, startLoc, endLoc) {
          var comment = {
            type: block ? "Block" : "Line",
            value: text,
            start,
            end
          };
          if (options.locations) {
            comment.loc = new SourceLocation4(this, startLoc, endLoc);
          }
          if (options.ranges) {
            comment.range = [start, end];
          }
          array.push(comment);
        };
      }
      var SCOPE_TOP3 = 1, SCOPE_FUNCTION4 = 2, SCOPE_ASYNC4 = 4, SCOPE_GENERATOR4 = 8, SCOPE_ARROW3 = 16, SCOPE_SIMPLE_CATCH3 = 32, SCOPE_SUPER3 = 64, SCOPE_DIRECT_SUPER3 = 128, SCOPE_CLASS_STATIC_BLOCK = 256, SCOPE_CLASS_FIELD_INIT = 512, SCOPE_SWITCH = 1024, SCOPE_VAR3 = SCOPE_TOP3 | SCOPE_FUNCTION4 | SCOPE_CLASS_STATIC_BLOCK;
      function functionFlags3(async, generator) {
        return SCOPE_FUNCTION4 | (async ? SCOPE_ASYNC4 : 0) | (generator ? SCOPE_GENERATOR4 : 0);
      }
      var BIND_NONE3 = 0, BIND_VAR3 = 1, BIND_LEXICAL3 = 2, BIND_FUNCTION3 = 3, BIND_SIMPLE_CATCH3 = 4, BIND_OUTSIDE3 = 5;
      var Parser6 = function Parser7(options, input, startPos) {
        this.options = options = getOptions3(options);
        this.sourceFile = options.sourceFile;
        this.keywords = wordsRegexp3(keywords$13[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
        var reserved = "";
        if (options.allowReserved !== true) {
          reserved = reservedWords3[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3];
          if (options.sourceType === "module") {
            reserved += " await";
          }
        }
        this.reservedWords = wordsRegexp3(reserved);
        var reservedStrict = (reserved ? reserved + " " : "") + reservedWords3.strict;
        this.reservedWordsStrict = wordsRegexp3(reservedStrict);
        this.reservedWordsStrictBind = wordsRegexp3(reservedStrict + " " + reservedWords3.strictBind);
        this.input = String(input);
        this.containsEsc = false;
        if (startPos) {
          this.pos = startPos;
          this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
          this.curLine = this.input.slice(0, this.lineStart).split(lineBreak3).length;
        } else {
          this.pos = this.lineStart = 0;
          this.curLine = 1;
        }
        this.type = types$13.eof;
        this.value = null;
        this.start = this.end = this.pos;
        this.startLoc = this.endLoc = this.curPosition();
        this.lastTokEndLoc = this.lastTokStartLoc = null;
        this.lastTokStart = this.lastTokEnd = this.pos;
        this.context = this.initialContext();
        this.exprAllowed = true;
        this.inModule = options.sourceType === "module";
        this.strict = this.inModule || this.strictDirective(this.pos);
        this.potentialArrowAt = -1;
        this.potentialArrowInForAwait = false;
        this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
        this.labels = [];
        this.undefinedExports = /* @__PURE__ */ Object.create(null);
        if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!") {
          this.skipLineComment(2);
        }
        this.scopeStack = [];
        this.enterScope(
          this.options.sourceType === "commonjs" ? SCOPE_FUNCTION4 : SCOPE_TOP3
        );
        this.regexpState = null;
        this.privateNameStack = [];
      };
      var prototypeAccessors3 = { inFunction: { configurable: true }, inGenerator: { configurable: true }, inAsync: { configurable: true }, canAwait: { configurable: true }, allowReturn: { configurable: true }, allowSuper: { configurable: true }, allowDirectSuper: { configurable: true }, treatFunctionsAsVar: { configurable: true }, allowNewDotTarget: { configurable: true }, allowUsing: { configurable: true }, inClassStaticBlock: { configurable: true } };
      Parser6.prototype.parse = function parse25() {
        var node = this.options.program || this.startNode();
        this.nextToken();
        return this.parseTopLevel(node);
      };
      prototypeAccessors3.inFunction.get = function() {
        return (this.currentVarScope().flags & SCOPE_FUNCTION4) > 0;
      };
      prototypeAccessors3.inGenerator.get = function() {
        return (this.currentVarScope().flags & SCOPE_GENERATOR4) > 0;
      };
      prototypeAccessors3.inAsync.get = function() {
        return (this.currentVarScope().flags & SCOPE_ASYNC4) > 0;
      };
      prototypeAccessors3.canAwait.get = function() {
        for (var i7 = this.scopeStack.length - 1; i7 >= 0; i7--) {
          var ref4 = this.scopeStack[i7];
          var flags = ref4.flags;
          if (flags & (SCOPE_CLASS_STATIC_BLOCK | SCOPE_CLASS_FIELD_INIT)) {
            return false;
          }
          if (flags & SCOPE_FUNCTION4) {
            return (flags & SCOPE_ASYNC4) > 0;
          }
        }
        return this.inModule && this.options.ecmaVersion >= 13 || this.options.allowAwaitOutsideFunction;
      };
      prototypeAccessors3.allowReturn.get = function() {
        if (this.inFunction) {
          return true;
        }
        if (this.options.allowReturnOutsideFunction && this.currentVarScope().flags & SCOPE_TOP3) {
          return true;
        }
        return false;
      };
      prototypeAccessors3.allowSuper.get = function() {
        var ref4 = this.currentThisScope();
        var flags = ref4.flags;
        return (flags & SCOPE_SUPER3) > 0 || this.options.allowSuperOutsideMethod;
      };
      prototypeAccessors3.allowDirectSuper.get = function() {
        return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER3) > 0;
      };
      prototypeAccessors3.treatFunctionsAsVar.get = function() {
        return this.treatFunctionsAsVarInScope(this.currentScope());
      };
      prototypeAccessors3.allowNewDotTarget.get = function() {
        for (var i7 = this.scopeStack.length - 1; i7 >= 0; i7--) {
          var ref4 = this.scopeStack[i7];
          var flags = ref4.flags;
          if (flags & (SCOPE_CLASS_STATIC_BLOCK | SCOPE_CLASS_FIELD_INIT) || flags & SCOPE_FUNCTION4 && !(flags & SCOPE_ARROW3)) {
            return true;
          }
        }
        return false;
      };
      prototypeAccessors3.allowUsing.get = function() {
        var ref4 = this.currentScope();
        var flags = ref4.flags;
        if (flags & SCOPE_SWITCH) {
          return false;
        }
        if (!this.inModule && flags & SCOPE_TOP3) {
          return false;
        }
        return true;
      };
      prototypeAccessors3.inClassStaticBlock.get = function() {
        return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK) > 0;
      };
      Parser6.extend = function extend7() {
        var plugins = [], len = arguments.length;
        while (len--) plugins[len] = arguments[len];
        var cls = this;
        for (var i7 = 0; i7 < plugins.length; i7++) {
          cls = plugins[i7](cls);
        }
        return cls;
      };
      Parser6.parse = function parse25(input, options) {
        return new this(options, input).parse();
      };
      Parser6.parseExpressionAt = function parseExpressionAt4(input, pos, options) {
        var parser = new this(options, input, pos);
        parser.nextToken();
        return parser.parseExpression();
      };
      Parser6.tokenizer = function tokenizer4(input, options) {
        return new this(options, input);
      };
      Object.defineProperties(Parser6.prototype, prototypeAccessors3);
      var pp$93 = Parser6.prototype;
      var literal3 = /^(?:'((?:\\[^]|[^'\\])*?)'|"((?:\\[^]|[^"\\])*?)")/;
      pp$93.strictDirective = function(start) {
        if (this.options.ecmaVersion < 5) {
          return false;
        }
        for (; ; ) {
          skipWhiteSpace3.lastIndex = start;
          start += skipWhiteSpace3.exec(this.input)[0].length;
          var match = literal3.exec(this.input.slice(start));
          if (!match) {
            return false;
          }
          if ((match[1] || match[2]) === "use strict") {
            skipWhiteSpace3.lastIndex = start + match[0].length;
            var spaceAfter = skipWhiteSpace3.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;
            var next = this.input.charAt(end);
            return next === ";" || next === "}" || lineBreak3.test(spaceAfter[0]) && !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "=");
          }
          start += match[0].length;
          skipWhiteSpace3.lastIndex = start;
          start += skipWhiteSpace3.exec(this.input)[0].length;
          if (this.input[start] === ";") {
            start++;
          }
        }
      };
      pp$93.eat = function(type4) {
        if (this.type === type4) {
          this.next();
          return true;
        } else {
          return false;
        }
      };
      pp$93.isContextual = function(name2) {
        return this.type === types$13.name && this.value === name2 && !this.containsEsc;
      };
      pp$93.eatContextual = function(name2) {
        if (!this.isContextual(name2)) {
          return false;
        }
        this.next();
        return true;
      };
      pp$93.expectContextual = function(name2) {
        if (!this.eatContextual(name2)) {
          this.unexpected();
        }
      };
      pp$93.canInsertSemicolon = function() {
        return this.type === types$13.eof || this.type === types$13.braceR || lineBreak3.test(this.input.slice(this.lastTokEnd, this.start));
      };
      pp$93.insertSemicolon = function() {
        if (this.canInsertSemicolon()) {
          if (this.options.onInsertedSemicolon) {
            this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc);
          }
          return true;
        }
      };
      pp$93.semicolon = function() {
        if (!this.eat(types$13.semi) && !this.insertSemicolon()) {
          this.unexpected();
        }
      };
      pp$93.afterTrailingComma = function(tokType, notNext) {
        if (this.type === tokType) {
          if (this.options.onTrailingComma) {
            this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc);
          }
          if (!notNext) {
            this.next();
          }
          return true;
        }
      };
      pp$93.expect = function(type4) {
        this.eat(type4) || this.unexpected();
      };
      pp$93.unexpected = function(pos) {
        this.raise(pos != null ? pos : this.start, "Unexpected token");
      };
      var DestructuringErrors3 = function DestructuringErrors4() {
        this.shorthandAssign = this.trailingComma = this.parenthesizedAssign = this.parenthesizedBind = this.doubleProto = -1;
      };
      pp$93.checkPatternErrors = function(refDestructuringErrors, isAssign) {
        if (!refDestructuringErrors) {
          return;
        }
        if (refDestructuringErrors.trailingComma > -1) {
          this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element");
        }
        var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
        if (parens > -1) {
          this.raiseRecoverable(parens, isAssign ? "Assigning to rvalue" : "Parenthesized pattern");
        }
      };
      pp$93.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
        if (!refDestructuringErrors) {
          return false;
        }
        var shorthandAssign = refDestructuringErrors.shorthandAssign;
        var doubleProto = refDestructuringErrors.doubleProto;
        if (!andThrow) {
          return shorthandAssign >= 0 || doubleProto >= 0;
        }
        if (shorthandAssign >= 0) {
          this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns");
        }
        if (doubleProto >= 0) {
          this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property");
        }
      };
      pp$93.checkYieldAwaitInDefaultParams = function() {
        if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos)) {
          this.raise(this.yieldPos, "Yield expression cannot be a default value");
        }
        if (this.awaitPos) {
          this.raise(this.awaitPos, "Await expression cannot be a default value");
        }
      };
      pp$93.isSimpleAssignTarget = function(expr) {
        if (expr.type === "ParenthesizedExpression") {
          return this.isSimpleAssignTarget(expr.expression);
        }
        return expr.type === "Identifier" || expr.type === "MemberExpression";
      };
      var pp$83 = Parser6.prototype;
      pp$83.parseTopLevel = function(node) {
        var exports25 = /* @__PURE__ */ Object.create(null);
        if (!node.body) {
          node.body = [];
        }
        while (this.type !== types$13.eof) {
          var stmt = this.parseStatement(null, true, exports25);
          node.body.push(stmt);
        }
        if (this.inModule) {
          for (var i7 = 0, list2 = Object.keys(this.undefinedExports); i7 < list2.length; i7 += 1) {
            var name2 = list2[i7];
            this.raiseRecoverable(this.undefinedExports[name2].start, "Export '" + name2 + "' is not defined");
          }
        }
        this.adaptDirectivePrologue(node.body);
        this.next();
        node.sourceType = this.options.sourceType === "commonjs" ? "script" : this.options.sourceType;
        return this.finishNode(node, "Program");
      };
      var loopLabel3 = { kind: "loop" }, switchLabel3 = { kind: "switch" };
      pp$83.isLet = function(context) {
        if (this.options.ecmaVersion < 6 || !this.isContextual("let")) {
          return false;
        }
        skipWhiteSpace3.lastIndex = this.pos;
        var skip = skipWhiteSpace3.exec(this.input);
        var next = this.pos + skip[0].length, nextCh = this.fullCharCodeAt(next);
        if (nextCh === 91 || nextCh === 92) {
          return true;
        }
        if (context) {
          return false;
        }
        if (nextCh === 123) {
          return true;
        }
        if (isIdentifierStart3(nextCh)) {
          var start = next;
          do {
            next += nextCh <= 65535 ? 1 : 2;
          } while (isIdentifierChar3(nextCh = this.fullCharCodeAt(next)));
          if (nextCh === 92) {
            return true;
          }
          var ident = this.input.slice(start, next);
          if (!keywordRelationalOperator3.test(ident)) {
            return true;
          }
        }
        return false;
      };
      pp$83.isAsyncFunction = function() {
        if (this.options.ecmaVersion < 8 || !this.isContextual("async")) {
          return false;
        }
        skipWhiteSpace3.lastIndex = this.pos;
        var skip = skipWhiteSpace3.exec(this.input);
        var next = this.pos + skip[0].length, after;
        return !lineBreak3.test(this.input.slice(this.pos, next)) && this.input.slice(next, next + 8) === "function" && (next + 8 === this.input.length || !(isIdentifierChar3(after = this.fullCharCodeAt(next + 8)) || after === 92));
      };
      pp$83.isUsingKeyword = function(isAwaitUsing, isFor) {
        if (this.options.ecmaVersion < 17 || !this.isContextual(isAwaitUsing ? "await" : "using")) {
          return false;
        }
        skipWhiteSpace3.lastIndex = this.pos;
        var skip = skipWhiteSpace3.exec(this.input);
        var next = this.pos + skip[0].length;
        if (lineBreak3.test(this.input.slice(this.pos, next))) {
          return false;
        }
        if (isAwaitUsing) {
          var usingEndPos = next + 5, after;
          if (this.input.slice(next, usingEndPos) !== "using" || usingEndPos === this.input.length || isIdentifierChar3(after = this.fullCharCodeAt(usingEndPos)) || after === 92) {
            return false;
          }
          skipWhiteSpace3.lastIndex = usingEndPos;
          var skipAfterUsing = skipWhiteSpace3.exec(this.input);
          next = usingEndPos + skipAfterUsing[0].length;
          if (skipAfterUsing && lineBreak3.test(this.input.slice(usingEndPos, next))) {
            return false;
          }
        }
        var ch = this.fullCharCodeAt(next);
        if (!isIdentifierStart3(ch) && ch !== 92) {
          return false;
        }
        var idStart = next;
        do {
          next += ch <= 65535 ? 1 : 2;
        } while (isIdentifierChar3(ch = this.fullCharCodeAt(next)));
        if (ch === 92) {
          return true;
        }
        var id = this.input.slice(idStart, next);
        if (keywordRelationalOperator3.test(id) || isFor && id === "of") {
          return false;
        }
        return true;
      };
      pp$83.isAwaitUsing = function(isFor) {
        return this.isUsingKeyword(true, isFor);
      };
      pp$83.isUsing = function(isFor) {
        return this.isUsingKeyword(false, isFor);
      };
      pp$83.parseStatement = function(context, topLevel, exports25) {
        var starttype = this.type, node = this.startNode(), kind;
        if (this.isLet(context)) {
          starttype = types$13._var;
          kind = "let";
        }
        switch (starttype) {
          case types$13._break:
          case types$13._continue:
            return this.parseBreakContinueStatement(node, starttype.keyword);
          case types$13._debugger:
            return this.parseDebuggerStatement(node);
          case types$13._do:
            return this.parseDoStatement(node);
          case types$13._for:
            return this.parseForStatement(node);
          case types$13._function:
            if (context && (this.strict || context !== "if" && context !== "label") && this.options.ecmaVersion >= 6) {
              this.unexpected();
            }
            return this.parseFunctionStatement(node, false, !context);
          case types$13._class:
            if (context) {
              this.unexpected();
            }
            return this.parseClass(node, true);
          case types$13._if:
            return this.parseIfStatement(node);
          case types$13._return:
            return this.parseReturnStatement(node);
          case types$13._switch:
            return this.parseSwitchStatement(node);
          case types$13._throw:
            return this.parseThrowStatement(node);
          case types$13._try:
            return this.parseTryStatement(node);
          case types$13._const:
          case types$13._var:
            kind = kind || this.value;
            if (context && kind !== "var") {
              this.unexpected();
            }
            return this.parseVarStatement(node, kind);
          case types$13._while:
            return this.parseWhileStatement(node);
          case types$13._with:
            return this.parseWithStatement(node);
          case types$13.braceL:
            return this.parseBlock(true, node);
          case types$13.semi:
            return this.parseEmptyStatement(node);
          case types$13._export:
          case types$13._import:
            if (this.options.ecmaVersion > 10 && starttype === types$13._import) {
              skipWhiteSpace3.lastIndex = this.pos;
              var skip = skipWhiteSpace3.exec(this.input);
              var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
              if (nextCh === 40 || nextCh === 46) {
                return this.parseExpressionStatement(node, this.parseExpression());
              }
            }
            if (!this.options.allowImportExportEverywhere) {
              if (!topLevel) {
                this.raise(this.start, "'import' and 'export' may only appear at the top level");
              }
              if (!this.inModule) {
                this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'");
              }
            }
            return starttype === types$13._import ? this.parseImport(node) : this.parseExport(node, exports25);
          // If the statement does not start with a statement keyword or a
          // brace, it's an ExpressionStatement or LabeledStatement. We
          // simply start parsing an expression, and afterwards, if the
          // next token is a colon and the expression was a simple
          // Identifier node, we switch to interpreting it as a label.
          default:
            if (this.isAsyncFunction()) {
              if (context) {
                this.unexpected();
              }
              this.next();
              return this.parseFunctionStatement(node, true, !context);
            }
            var usingKind = this.isAwaitUsing(false) ? "await using" : this.isUsing(false) ? "using" : null;
            if (usingKind) {
              if (!this.allowUsing) {
                this.raise(this.start, "Using declaration cannot appear in the top level when source type is `script` or in the bare case statement");
              }
              if (usingKind === "await using") {
                if (!this.canAwait) {
                  this.raise(this.start, "Await using cannot appear outside of async function");
                }
                this.next();
              }
              this.next();
              this.parseVar(node, false, usingKind);
              this.semicolon();
              return this.finishNode(node, "VariableDeclaration");
            }
            var maybeName = this.value, expr = this.parseExpression();
            if (starttype === types$13.name && expr.type === "Identifier" && this.eat(types$13.colon)) {
              return this.parseLabeledStatement(node, maybeName, expr, context);
            } else {
              return this.parseExpressionStatement(node, expr);
            }
        }
      };
      pp$83.parseBreakContinueStatement = function(node, keyword) {
        var isBreak = keyword === "break";
        this.next();
        if (this.eat(types$13.semi) || this.insertSemicolon()) {
          node.label = null;
        } else if (this.type !== types$13.name) {
          this.unexpected();
        } else {
          node.label = this.parseIdent();
          this.semicolon();
        }
        var i7 = 0;
        for (; i7 < this.labels.length; ++i7) {
          var lab = this.labels[i7];
          if (node.label == null || lab.name === node.label.name) {
            if (lab.kind != null && (isBreak || lab.kind === "loop")) {
              break;
            }
            if (node.label && isBreak) {
              break;
            }
          }
        }
        if (i7 === this.labels.length) {
          this.raise(node.start, "Unsyntactic " + keyword);
        }
        return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
      };
      pp$83.parseDebuggerStatement = function(node) {
        this.next();
        this.semicolon();
        return this.finishNode(node, "DebuggerStatement");
      };
      pp$83.parseDoStatement = function(node) {
        this.next();
        this.labels.push(loopLabel3);
        node.body = this.parseStatement("do");
        this.labels.pop();
        this.expect(types$13._while);
        node.test = this.parseParenExpression();
        if (this.options.ecmaVersion >= 6) {
          this.eat(types$13.semi);
        } else {
          this.semicolon();
        }
        return this.finishNode(node, "DoWhileStatement");
      };
      pp$83.parseForStatement = function(node) {
        this.next();
        var awaitAt = this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await") ? this.lastTokStart : -1;
        this.labels.push(loopLabel3);
        this.enterScope(0);
        this.expect(types$13.parenL);
        if (this.type === types$13.semi) {
          if (awaitAt > -1) {
            this.unexpected(awaitAt);
          }
          return this.parseFor(node, null);
        }
        var isLet = this.isLet();
        if (this.type === types$13._var || this.type === types$13._const || isLet) {
          var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
          this.next();
          this.parseVar(init$1, true, kind);
          this.finishNode(init$1, "VariableDeclaration");
          return this.parseForAfterInit(node, init$1, awaitAt);
        }
        var startsWithLet = this.isContextual("let"), isForOf = false;
        var usingKind = this.isUsing(true) ? "using" : this.isAwaitUsing(true) ? "await using" : null;
        if (usingKind) {
          var init$2 = this.startNode();
          this.next();
          if (usingKind === "await using") {
            if (!this.canAwait) {
              this.raise(this.start, "Await using cannot appear outside of async function");
            }
            this.next();
          }
          this.parseVar(init$2, true, usingKind);
          this.finishNode(init$2, "VariableDeclaration");
          return this.parseForAfterInit(node, init$2, awaitAt);
        }
        var containsEsc = this.containsEsc;
        var refDestructuringErrors = new DestructuringErrors3();
        var initPos = this.start;
        var init5 = awaitAt > -1 ? this.parseExprSubscripts(refDestructuringErrors, "await") : this.parseExpression(true, refDestructuringErrors);
        if (this.type === types$13._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
          if (awaitAt > -1) {
            if (this.type === types$13._in) {
              this.unexpected(awaitAt);
            }
            node.await = true;
          } else if (isForOf && this.options.ecmaVersion >= 8) {
            if (init5.start === initPos && !containsEsc && init5.type === "Identifier" && init5.name === "async") {
              this.unexpected();
            } else if (this.options.ecmaVersion >= 9) {
              node.await = false;
            }
          }
          if (startsWithLet && isForOf) {
            this.raise(init5.start, "The left-hand side of a for-of loop may not start with 'let'.");
          }
          this.toAssignable(init5, false, refDestructuringErrors);
          this.checkLValPattern(init5);
          return this.parseForIn(node, init5);
        } else {
          this.checkExpressionErrors(refDestructuringErrors, true);
        }
        if (awaitAt > -1) {
          this.unexpected(awaitAt);
        }
        return this.parseFor(node, init5);
      };
      pp$83.parseForAfterInit = function(node, init5, awaitAt) {
        if ((this.type === types$13._in || this.options.ecmaVersion >= 6 && this.isContextual("of")) && init5.declarations.length === 1) {
          if (this.options.ecmaVersion >= 9) {
            if (this.type === types$13._in) {
              if (awaitAt > -1) {
                this.unexpected(awaitAt);
              }
            } else {
              node.await = awaitAt > -1;
            }
          }
          return this.parseForIn(node, init5);
        }
        if (awaitAt > -1) {
          this.unexpected(awaitAt);
        }
        return this.parseFor(node, init5);
      };
      pp$83.parseFunctionStatement = function(node, isAsync2, declarationPosition) {
        this.next();
        return this.parseFunction(node, FUNC_STATEMENT3 | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT3), false, isAsync2);
      };
      pp$83.parseIfStatement = function(node) {
        this.next();
        node.test = this.parseParenExpression();
        node.consequent = this.parseStatement("if");
        node.alternate = this.eat(types$13._else) ? this.parseStatement("if") : null;
        return this.finishNode(node, "IfStatement");
      };
      pp$83.parseReturnStatement = function(node) {
        if (!this.allowReturn) {
          this.raise(this.start, "'return' outside of function");
        }
        this.next();
        if (this.eat(types$13.semi) || this.insertSemicolon()) {
          node.argument = null;
        } else {
          node.argument = this.parseExpression();
          this.semicolon();
        }
        return this.finishNode(node, "ReturnStatement");
      };
      pp$83.parseSwitchStatement = function(node) {
        this.next();
        node.discriminant = this.parseParenExpression();
        node.cases = [];
        this.expect(types$13.braceL);
        this.labels.push(switchLabel3);
        this.enterScope(SCOPE_SWITCH);
        var cur;
        for (var sawDefault = false; this.type !== types$13.braceR; ) {
          if (this.type === types$13._case || this.type === types$13._default) {
            var isCase = this.type === types$13._case;
            if (cur) {
              this.finishNode(cur, "SwitchCase");
            }
            node.cases.push(cur = this.startNode());
            cur.consequent = [];
            this.next();
            if (isCase) {
              cur.test = this.parseExpression();
            } else {
              if (sawDefault) {
                this.raiseRecoverable(this.lastTokStart, "Multiple default clauses");
              }
              sawDefault = true;
              cur.test = null;
            }
            this.expect(types$13.colon);
          } else {
            if (!cur) {
              this.unexpected();
            }
            cur.consequent.push(this.parseStatement(null));
          }
        }
        this.exitScope();
        if (cur) {
          this.finishNode(cur, "SwitchCase");
        }
        this.next();
        this.labels.pop();
        return this.finishNode(node, "SwitchStatement");
      };
      pp$83.parseThrowStatement = function(node) {
        this.next();
        if (lineBreak3.test(this.input.slice(this.lastTokEnd, this.start))) {
          this.raise(this.lastTokEnd, "Illegal newline after throw");
        }
        node.argument = this.parseExpression();
        this.semicolon();
        return this.finishNode(node, "ThrowStatement");
      };
      var empty$13 = [];
      pp$83.parseCatchClauseParam = function() {
        var param = this.parseBindingAtom();
        var simple3 = param.type === "Identifier";
        this.enterScope(simple3 ? SCOPE_SIMPLE_CATCH3 : 0);
        this.checkLValPattern(param, simple3 ? BIND_SIMPLE_CATCH3 : BIND_LEXICAL3);
        this.expect(types$13.parenR);
        return param;
      };
      pp$83.parseTryStatement = function(node) {
        this.next();
        node.block = this.parseBlock();
        node.handler = null;
        if (this.type === types$13._catch) {
          var clause = this.startNode();
          this.next();
          if (this.eat(types$13.parenL)) {
            clause.param = this.parseCatchClauseParam();
          } else {
            if (this.options.ecmaVersion < 10) {
              this.unexpected();
            }
            clause.param = null;
            this.enterScope(0);
          }
          clause.body = this.parseBlock(false);
          this.exitScope();
          node.handler = this.finishNode(clause, "CatchClause");
        }
        node.finalizer = this.eat(types$13._finally) ? this.parseBlock() : null;
        if (!node.handler && !node.finalizer) {
          this.raise(node.start, "Missing catch or finally clause");
        }
        return this.finishNode(node, "TryStatement");
      };
      pp$83.parseVarStatement = function(node, kind, allowMissingInitializer) {
        this.next();
        this.parseVar(node, false, kind, allowMissingInitializer);
        this.semicolon();
        return this.finishNode(node, "VariableDeclaration");
      };
      pp$83.parseWhileStatement = function(node) {
        this.next();
        node.test = this.parseParenExpression();
        this.labels.push(loopLabel3);
        node.body = this.parseStatement("while");
        this.labels.pop();
        return this.finishNode(node, "WhileStatement");
      };
      pp$83.parseWithStatement = function(node) {
        if (this.strict) {
          this.raise(this.start, "'with' in strict mode");
        }
        this.next();
        node.object = this.parseParenExpression();
        node.body = this.parseStatement("with");
        return this.finishNode(node, "WithStatement");
      };
      pp$83.parseEmptyStatement = function(node) {
        this.next();
        return this.finishNode(node, "EmptyStatement");
      };
      pp$83.parseLabeledStatement = function(node, maybeName, expr, context) {
        for (var i$13 = 0, list2 = this.labels; i$13 < list2.length; i$13 += 1) {
          var label = list2[i$13];
          if (label.name === maybeName) {
            this.raise(expr.start, "Label '" + maybeName + "' is already declared");
          }
        }
        var kind = this.type.isLoop ? "loop" : this.type === types$13._switch ? "switch" : null;
        for (var i7 = this.labels.length - 1; i7 >= 0; i7--) {
          var label$1 = this.labels[i7];
          if (label$1.statementStart === node.start) {
            label$1.statementStart = this.start;
            label$1.kind = kind;
          } else {
            break;
          }
        }
        this.labels.push({ name: maybeName, kind, statementStart: this.start });
        node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
        this.labels.pop();
        node.label = expr;
        return this.finishNode(node, "LabeledStatement");
      };
      pp$83.parseExpressionStatement = function(node, expr) {
        node.expression = expr;
        this.semicolon();
        return this.finishNode(node, "ExpressionStatement");
      };
      pp$83.parseBlock = function(createNewLexicalScope, node, exitStrict) {
        if (createNewLexicalScope === void 0) createNewLexicalScope = true;
        if (node === void 0) node = this.startNode();
        node.body = [];
        this.expect(types$13.braceL);
        if (createNewLexicalScope) {
          this.enterScope(0);
        }
        while (this.type !== types$13.braceR) {
          var stmt = this.parseStatement(null);
          node.body.push(stmt);
        }
        if (exitStrict) {
          this.strict = false;
        }
        this.next();
        if (createNewLexicalScope) {
          this.exitScope();
        }
        return this.finishNode(node, "BlockStatement");
      };
      pp$83.parseFor = function(node, init5) {
        node.init = init5;
        this.expect(types$13.semi);
        node.test = this.type === types$13.semi ? null : this.parseExpression();
        this.expect(types$13.semi);
        node.update = this.type === types$13.parenR ? null : this.parseExpression();
        this.expect(types$13.parenR);
        node.body = this.parseStatement("for");
        this.exitScope();
        this.labels.pop();
        return this.finishNode(node, "ForStatement");
      };
      pp$83.parseForIn = function(node, init5) {
        var isForIn = this.type === types$13._in;
        this.next();
        if (init5.type === "VariableDeclaration" && init5.declarations[0].init != null && (!isForIn || this.options.ecmaVersion < 8 || this.strict || init5.kind !== "var" || init5.declarations[0].id.type !== "Identifier")) {
          this.raise(
            init5.start,
            (isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer"
          );
        }
        node.left = init5;
        node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
        this.expect(types$13.parenR);
        node.body = this.parseStatement("for");
        this.exitScope();
        this.labels.pop();
        return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement");
      };
      pp$83.parseVar = function(node, isFor, kind, allowMissingInitializer) {
        node.declarations = [];
        node.kind = kind;
        for (; ; ) {
          var decl = this.startNode();
          this.parseVarId(decl, kind);
          if (this.eat(types$13.eq)) {
            decl.init = this.parseMaybeAssign(isFor);
          } else if (!allowMissingInitializer && kind === "const" && !(this.type === types$13._in || this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
            this.unexpected();
          } else if (!allowMissingInitializer && (kind === "using" || kind === "await using") && this.options.ecmaVersion >= 17 && this.type !== types$13._in && !this.isContextual("of")) {
            this.raise(this.lastTokEnd, "Missing initializer in " + kind + " declaration");
          } else if (!allowMissingInitializer && decl.id.type !== "Identifier" && !(isFor && (this.type === types$13._in || this.isContextual("of")))) {
            this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
          } else {
            decl.init = null;
          }
          node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
          if (!this.eat(types$13.comma)) {
            break;
          }
        }
        return node;
      };
      pp$83.parseVarId = function(decl, kind) {
        decl.id = kind === "using" || kind === "await using" ? this.parseIdent() : this.parseBindingAtom();
        this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR3 : BIND_LEXICAL3, false);
      };
      var FUNC_STATEMENT3 = 1, FUNC_HANGING_STATEMENT3 = 2, FUNC_NULLABLE_ID3 = 4;
      pp$83.parseFunction = function(node, statement, allowExpressionBody, isAsync2, forInit) {
        this.initFunction(node);
        if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync2) {
          if (this.type === types$13.star && statement & FUNC_HANGING_STATEMENT3) {
            this.unexpected();
          }
          node.generator = this.eat(types$13.star);
        }
        if (this.options.ecmaVersion >= 8) {
          node.async = !!isAsync2;
        }
        if (statement & FUNC_STATEMENT3) {
          node.id = statement & FUNC_NULLABLE_ID3 && this.type !== types$13.name ? null : this.parseIdent();
          if (node.id && !(statement & FUNC_HANGING_STATEMENT3)) {
            this.checkLValSimple(node.id, this.strict || node.generator || node.async ? this.treatFunctionsAsVar ? BIND_VAR3 : BIND_LEXICAL3 : BIND_FUNCTION3);
          }
        }
        var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
        this.yieldPos = 0;
        this.awaitPos = 0;
        this.awaitIdentPos = 0;
        this.enterScope(functionFlags3(node.async, node.generator));
        if (!(statement & FUNC_STATEMENT3)) {
          node.id = this.type === types$13.name ? this.parseIdent() : null;
        }
        this.parseFunctionParams(node);
        this.parseFunctionBody(node, allowExpressionBody, false, forInit);
        this.yieldPos = oldYieldPos;
        this.awaitPos = oldAwaitPos;
        this.awaitIdentPos = oldAwaitIdentPos;
        return this.finishNode(node, statement & FUNC_STATEMENT3 ? "FunctionDeclaration" : "FunctionExpression");
      };
      pp$83.parseFunctionParams = function(node) {
        this.expect(types$13.parenL);
        node.params = this.parseBindingList(types$13.parenR, false, this.options.ecmaVersion >= 8);
        this.checkYieldAwaitInDefaultParams();
      };
      pp$83.parseClass = function(node, isStatement) {
        this.next();
        var oldStrict = this.strict;
        this.strict = true;
        this.parseClassId(node, isStatement);
        this.parseClassSuper(node);
        var privateNameMap = this.enterClassBody();
        var classBody = this.startNode();
        var hadConstructor = false;
        classBody.body = [];
        this.expect(types$13.braceL);
        while (this.type !== types$13.braceR) {
          var element = this.parseClassElement(node.superClass !== null);
          if (element) {
            classBody.body.push(element);
            if (element.type === "MethodDefinition" && element.kind === "constructor") {
              if (hadConstructor) {
                this.raiseRecoverable(element.start, "Duplicate constructor in the same class");
              }
              hadConstructor = true;
            } else if (element.key && element.key.type === "PrivateIdentifier" && isPrivateNameConflicted2(privateNameMap, element)) {
              this.raiseRecoverable(element.key.start, "Identifier '#" + element.key.name + "' has already been declared");
            }
          }
        }
        this.strict = oldStrict;
        this.next();
        node.body = this.finishNode(classBody, "ClassBody");
        this.exitClassBody();
        return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");
      };
      pp$83.parseClassElement = function(constructorAllowsSuper) {
        if (this.eat(types$13.semi)) {
          return null;
        }
        var ecmaVersion2 = this.options.ecmaVersion;
        var node = this.startNode();
        var keyName = "";
        var isGenerator = false;
        var isAsync2 = false;
        var kind = "method";
        var isStatic = false;
        if (this.eatContextual("static")) {
          if (ecmaVersion2 >= 13 && this.eat(types$13.braceL)) {
            this.parseClassStaticBlock(node);
            return node;
          }
          if (this.isClassElementNameStart() || this.type === types$13.star) {
            isStatic = true;
          } else {
            keyName = "static";
          }
        }
        node.static = isStatic;
        if (!keyName && ecmaVersion2 >= 8 && this.eatContextual("async")) {
          if ((this.isClassElementNameStart() || this.type === types$13.star) && !this.canInsertSemicolon()) {
            isAsync2 = true;
          } else {
            keyName = "async";
          }
        }
        if (!keyName && (ecmaVersion2 >= 9 || !isAsync2) && this.eat(types$13.star)) {
          isGenerator = true;
        }
        if (!keyName && !isAsync2 && !isGenerator) {
          var lastValue = this.value;
          if (this.eatContextual("get") || this.eatContextual("set")) {
            if (this.isClassElementNameStart()) {
              kind = lastValue;
            } else {
              keyName = lastValue;
            }
          }
        }
        if (keyName) {
          node.computed = false;
          node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc);
          node.key.name = keyName;
          this.finishNode(node.key, "Identifier");
        } else {
          this.parseClassElementName(node);
        }
        if (ecmaVersion2 < 13 || this.type === types$13.parenL || kind !== "method" || isGenerator || isAsync2) {
          var isConstructor = !node.static && checkKeyName2(node, "constructor");
          var allowsDirectSuper = isConstructor && constructorAllowsSuper;
          if (isConstructor && kind !== "method") {
            this.raise(node.key.start, "Constructor can't have get/set modifier");
          }
          node.kind = isConstructor ? "constructor" : kind;
          this.parseClassMethod(node, isGenerator, isAsync2, allowsDirectSuper);
        } else {
          this.parseClassField(node);
        }
        return node;
      };
      pp$83.isClassElementNameStart = function() {
        return this.type === types$13.name || this.type === types$13.privateId || this.type === types$13.num || this.type === types$13.string || this.type === types$13.bracketL || this.type.keyword;
      };
      pp$83.parseClassElementName = function(element) {
        if (this.type === types$13.privateId) {
          if (this.value === "constructor") {
            this.raise(this.start, "Classes can't have an element named '#constructor'");
          }
          element.computed = false;
          element.key = this.parsePrivateIdent();
        } else {
          this.parsePropertyName(element);
        }
      };
      pp$83.parseClassMethod = function(method, isGenerator, isAsync2, allowsDirectSuper) {
        var key = method.key;
        if (method.kind === "constructor") {
          if (isGenerator) {
            this.raise(key.start, "Constructor can't be a generator");
          }
          if (isAsync2) {
            this.raise(key.start, "Constructor can't be an async method");
          }
        } else if (method.static && checkKeyName2(method, "prototype")) {
          this.raise(key.start, "Classes may not have a static property named prototype");
        }
        var value = method.value = this.parseMethod(isGenerator, isAsync2, allowsDirectSuper);
        if (method.kind === "get" && value.params.length !== 0) {
          this.raiseRecoverable(value.start, "getter should have no params");
        }
        if (method.kind === "set" && value.params.length !== 1) {
          this.raiseRecoverable(value.start, "setter should have exactly one param");
        }
        if (method.kind === "set" && value.params[0].type === "RestElement") {
          this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params");
        }
        return this.finishNode(method, "MethodDefinition");
      };
      pp$83.parseClassField = function(field) {
        if (checkKeyName2(field, "constructor")) {
          this.raise(field.key.start, "Classes can't have a field named 'constructor'");
        } else if (field.static && checkKeyName2(field, "prototype")) {
          this.raise(field.key.start, "Classes can't have a static field named 'prototype'");
        }
        if (this.eat(types$13.eq)) {
          this.enterScope(SCOPE_CLASS_FIELD_INIT | SCOPE_SUPER3);
          field.value = this.parseMaybeAssign();
          this.exitScope();
        } else {
          field.value = null;
        }
        this.semicolon();
        return this.finishNode(field, "PropertyDefinition");
      };
      pp$83.parseClassStaticBlock = function(node) {
        node.body = [];
        var oldLabels = this.labels;
        this.labels = [];
        this.enterScope(SCOPE_CLASS_STATIC_BLOCK | SCOPE_SUPER3);
        while (this.type !== types$13.braceR) {
          var stmt = this.parseStatement(null);
          node.body.push(stmt);
        }
        this.next();
        this.exitScope();
        this.labels = oldLabels;
        return this.finishNode(node, "StaticBlock");
      };
      pp$83.parseClassId = function(node, isStatement) {
        if (this.type === types$13.name) {
          node.id = this.parseIdent();
          if (isStatement) {
            this.checkLValSimple(node.id, BIND_LEXICAL3, false);
          }
        } else {
          if (isStatement === true) {
            this.unexpected();
          }
          node.id = null;
        }
      };
      pp$83.parseClassSuper = function(node) {
        node.superClass = this.eat(types$13._extends) ? this.parseExprSubscripts(null, false) : null;
      };
      pp$83.enterClassBody = function() {
        var element = { declared: /* @__PURE__ */ Object.create(null), used: [] };
        this.privateNameStack.push(element);
        return element.declared;
      };
      pp$83.exitClassBody = function() {
        var ref4 = this.privateNameStack.pop();
        var declared = ref4.declared;
        var used = ref4.used;
        if (!this.options.checkPrivateFields) {
          return;
        }
        var len = this.privateNameStack.length;
        var parent = len === 0 ? null : this.privateNameStack[len - 1];
        for (var i7 = 0; i7 < used.length; ++i7) {
          var id = used[i7];
          if (!hasOwn2(declared, id.name)) {
            if (parent) {
              parent.used.push(id);
            } else {
              this.raiseRecoverable(id.start, "Private field '#" + id.name + "' must be declared in an enclosing class");
            }
          }
        }
      };
      function isPrivateNameConflicted2(privateNameMap, element) {
        var name2 = element.key.name;
        var curr = privateNameMap[name2];
        var next = "true";
        if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) {
          next = (element.static ? "s" : "i") + element.kind;
        }
        if (curr === "iget" && next === "iset" || curr === "iset" && next === "iget" || curr === "sget" && next === "sset" || curr === "sset" && next === "sget") {
          privateNameMap[name2] = "true";
          return false;
        } else if (!curr) {
          privateNameMap[name2] = next;
          return false;
        } else {
          return true;
        }
      }
      function checkKeyName2(node, name2) {
        var computed = node.computed;
        var key = node.key;
        return !computed && (key.type === "Identifier" && key.name === name2 || key.type === "Literal" && key.value === name2);
      }
      pp$83.parseExportAllDeclaration = function(node, exports25) {
        if (this.options.ecmaVersion >= 11) {
          if (this.eatContextual("as")) {
            node.exported = this.parseModuleExportName();
            this.checkExport(exports25, node.exported, this.lastTokStart);
          } else {
            node.exported = null;
          }
        }
        this.expectContextual("from");
        if (this.type !== types$13.string) {
          this.unexpected();
        }
        node.source = this.parseExprAtom();
        if (this.options.ecmaVersion >= 16) {
          node.attributes = this.parseWithClause();
        }
        this.semicolon();
        return this.finishNode(node, "ExportAllDeclaration");
      };
      pp$83.parseExport = function(node, exports25) {
        this.next();
        if (this.eat(types$13.star)) {
          return this.parseExportAllDeclaration(node, exports25);
        }
        if (this.eat(types$13._default)) {
          this.checkExport(exports25, "default", this.lastTokStart);
          node.declaration = this.parseExportDefaultDeclaration();
          return this.finishNode(node, "ExportDefaultDeclaration");
        }
        if (this.shouldParseExportStatement()) {
          node.declaration = this.parseExportDeclaration(node);
          if (node.declaration.type === "VariableDeclaration") {
            this.checkVariableExport(exports25, node.declaration.declarations);
          } else {
            this.checkExport(exports25, node.declaration.id, node.declaration.id.start);
          }
          node.specifiers = [];
          node.source = null;
          if (this.options.ecmaVersion >= 16) {
            node.attributes = [];
          }
        } else {
          node.declaration = null;
          node.specifiers = this.parseExportSpecifiers(exports25);
          if (this.eatContextual("from")) {
            if (this.type !== types$13.string) {
              this.unexpected();
            }
            node.source = this.parseExprAtom();
            if (this.options.ecmaVersion >= 16) {
              node.attributes = this.parseWithClause();
            }
          } else {
            for (var i7 = 0, list2 = node.specifiers; i7 < list2.length; i7 += 1) {
              var spec = list2[i7];
              this.checkUnreserved(spec.local);
              this.checkLocalExport(spec.local);
              if (spec.local.type === "Literal") {
                this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`.");
              }
            }
            node.source = null;
            if (this.options.ecmaVersion >= 16) {
              node.attributes = [];
            }
          }
          this.semicolon();
        }
        return this.finishNode(node, "ExportNamedDeclaration");
      };
      pp$83.parseExportDeclaration = function(node) {
        return this.parseStatement(null);
      };
      pp$83.parseExportDefaultDeclaration = function() {
        var isAsync2;
        if (this.type === types$13._function || (isAsync2 = this.isAsyncFunction())) {
          var fNode = this.startNode();
          this.next();
          if (isAsync2) {
            this.next();
          }
          return this.parseFunction(fNode, FUNC_STATEMENT3 | FUNC_NULLABLE_ID3, false, isAsync2);
        } else if (this.type === types$13._class) {
          var cNode = this.startNode();
          return this.parseClass(cNode, "nullableID");
        } else {
          var declaration = this.parseMaybeAssign();
          this.semicolon();
          return declaration;
        }
      };
      pp$83.checkExport = function(exports25, name2, pos) {
        if (!exports25) {
          return;
        }
        if (typeof name2 !== "string") {
          name2 = name2.type === "Identifier" ? name2.name : name2.value;
        }
        if (hasOwn2(exports25, name2)) {
          this.raiseRecoverable(pos, "Duplicate export '" + name2 + "'");
        }
        exports25[name2] = true;
      };
      pp$83.checkPatternExport = function(exports25, pat) {
        var type4 = pat.type;
        if (type4 === "Identifier") {
          this.checkExport(exports25, pat, pat.start);
        } else if (type4 === "ObjectPattern") {
          for (var i7 = 0, list2 = pat.properties; i7 < list2.length; i7 += 1) {
            var prop = list2[i7];
            this.checkPatternExport(exports25, prop);
          }
        } else if (type4 === "ArrayPattern") {
          for (var i$13 = 0, list$1 = pat.elements; i$13 < list$1.length; i$13 += 1) {
            var elt = list$1[i$13];
            if (elt) {
              this.checkPatternExport(exports25, elt);
            }
          }
        } else if (type4 === "Property") {
          this.checkPatternExport(exports25, pat.value);
        } else if (type4 === "AssignmentPattern") {
          this.checkPatternExport(exports25, pat.left);
        } else if (type4 === "RestElement") {
          this.checkPatternExport(exports25, pat.argument);
        }
      };
      pp$83.checkVariableExport = function(exports25, decls) {
        if (!exports25) {
          return;
        }
        for (var i7 = 0, list2 = decls; i7 < list2.length; i7 += 1) {
          var decl = list2[i7];
          this.checkPatternExport(exports25, decl.id);
        }
      };
      pp$83.shouldParseExportStatement = function() {
        return this.type.keyword === "var" || this.type.keyword === "const" || this.type.keyword === "class" || this.type.keyword === "function" || this.isLet() || this.isAsyncFunction();
      };
      pp$83.parseExportSpecifier = function(exports25) {
        var node = this.startNode();
        node.local = this.parseModuleExportName();
        node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local;
        this.checkExport(
          exports25,
          node.exported,
          node.exported.start
        );
        return this.finishNode(node, "ExportSpecifier");
      };
      pp$83.parseExportSpecifiers = function(exports25) {
        var nodes = [], first = true;
        this.expect(types$13.braceL);
        while (!this.eat(types$13.braceR)) {
          if (!first) {
            this.expect(types$13.comma);
            if (this.afterTrailingComma(types$13.braceR)) {
              break;
            }
          } else {
            first = false;
          }
          nodes.push(this.parseExportSpecifier(exports25));
        }
        return nodes;
      };
      pp$83.parseImport = function(node) {
        this.next();
        if (this.type === types$13.string) {
          node.specifiers = empty$13;
          node.source = this.parseExprAtom();
        } else {
          node.specifiers = this.parseImportSpecifiers();
          this.expectContextual("from");
          node.source = this.type === types$13.string ? this.parseExprAtom() : this.unexpected();
        }
        if (this.options.ecmaVersion >= 16) {
          node.attributes = this.parseWithClause();
        }
        this.semicolon();
        return this.finishNode(node, "ImportDeclaration");
      };
      pp$83.parseImportSpecifier = function() {
        var node = this.startNode();
        node.imported = this.parseModuleExportName();
        if (this.eatContextual("as")) {
          node.local = this.parseIdent();
        } else {
          this.checkUnreserved(node.imported);
          node.local = node.imported;
        }
        this.checkLValSimple(node.local, BIND_LEXICAL3);
        return this.finishNode(node, "ImportSpecifier");
      };
      pp$83.parseImportDefaultSpecifier = function() {
        var node = this.startNode();
        node.local = this.parseIdent();
        this.checkLValSimple(node.local, BIND_LEXICAL3);
        return this.finishNode(node, "ImportDefaultSpecifier");
      };
      pp$83.parseImportNamespaceSpecifier = function() {
        var node = this.startNode();
        this.next();
        this.expectContextual("as");
        node.local = this.parseIdent();
        this.checkLValSimple(node.local, BIND_LEXICAL3);
        return this.finishNode(node, "ImportNamespaceSpecifier");
      };
      pp$83.parseImportSpecifiers = function() {
        var nodes = [], first = true;
        if (this.type === types$13.name) {
          nodes.push(this.parseImportDefaultSpecifier());
          if (!this.eat(types$13.comma)) {
            return nodes;
          }
        }
        if (this.type === types$13.star) {
          nodes.push(this.parseImportNamespaceSpecifier());
          return nodes;
        }
        this.expect(types$13.braceL);
        while (!this.eat(types$13.braceR)) {
          if (!first) {
            this.expect(types$13.comma);
            if (this.afterTrailingComma(types$13.braceR)) {
              break;
            }
          } else {
            first = false;
          }
          nodes.push(this.parseImportSpecifier());
        }
        return nodes;
      };
      pp$83.parseWithClause = function() {
        var nodes = [];
        if (!this.eat(types$13._with)) {
          return nodes;
        }
        this.expect(types$13.braceL);
        var attributeKeys = {};
        var first = true;
        while (!this.eat(types$13.braceR)) {
          if (!first) {
            this.expect(types$13.comma);
            if (this.afterTrailingComma(types$13.braceR)) {
              break;
            }
          } else {
            first = false;
          }
          var attr = this.parseImportAttribute();
          var keyName = attr.key.type === "Identifier" ? attr.key.name : attr.key.value;
          if (hasOwn2(attributeKeys, keyName)) {
            this.raiseRecoverable(attr.key.start, "Duplicate attribute key '" + keyName + "'");
          }
          attributeKeys[keyName] = true;
          nodes.push(attr);
        }
        return nodes;
      };
      pp$83.parseImportAttribute = function() {
        var node = this.startNode();
        node.key = this.type === types$13.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never");
        this.expect(types$13.colon);
        if (this.type !== types$13.string) {
          this.unexpected();
        }
        node.value = this.parseExprAtom();
        return this.finishNode(node, "ImportAttribute");
      };
      pp$83.parseModuleExportName = function() {
        if (this.options.ecmaVersion >= 13 && this.type === types$13.string) {
          var stringLiteral = this.parseLiteral(this.value);
          if (loneSurrogate.test(stringLiteral.value)) {
            this.raise(stringLiteral.start, "An export name cannot include a lone surrogate.");
          }
          return stringLiteral;
        }
        return this.parseIdent(true);
      };
      pp$83.adaptDirectivePrologue = function(statements) {
        for (var i7 = 0; i7 < statements.length && this.isDirectiveCandidate(statements[i7]); ++i7) {
          statements[i7].directive = statements[i7].expression.raw.slice(1, -1);
        }
      };
      pp$83.isDirectiveCandidate = function(statement) {
        return this.options.ecmaVersion >= 5 && statement.type === "ExpressionStatement" && statement.expression.type === "Literal" && typeof statement.expression.value === "string" && // Reject parenthesized strings.
        (this.input[statement.start] === '"' || this.input[statement.start] === "'");
      };
      var pp$73 = Parser6.prototype;
      pp$73.toAssignable = function(node, isBinding, refDestructuringErrors) {
        if (this.options.ecmaVersion >= 6 && node) {
          switch (node.type) {
            case "Identifier":
              if (this.inAsync && node.name === "await") {
                this.raise(node.start, "Cannot use 'await' as identifier inside an async function");
              }
              break;
            case "ObjectPattern":
            case "ArrayPattern":
            case "AssignmentPattern":
            case "RestElement":
              break;
            case "ObjectExpression":
              node.type = "ObjectPattern";
              if (refDestructuringErrors) {
                this.checkPatternErrors(refDestructuringErrors, true);
              }
              for (var i7 = 0, list2 = node.properties; i7 < list2.length; i7 += 1) {
                var prop = list2[i7];
                this.toAssignable(prop, isBinding);
                if (prop.type === "RestElement" && (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")) {
                  this.raise(prop.argument.start, "Unexpected token");
                }
              }
              break;
            case "Property":
              if (node.kind !== "init") {
                this.raise(node.key.start, "Object pattern can't contain getter or setter");
              }
              this.toAssignable(node.value, isBinding);
              break;
            case "ArrayExpression":
              node.type = "ArrayPattern";
              if (refDestructuringErrors) {
                this.checkPatternErrors(refDestructuringErrors, true);
              }
              this.toAssignableList(node.elements, isBinding);
              break;
            case "SpreadElement":
              node.type = "RestElement";
              this.toAssignable(node.argument, isBinding);
              if (node.argument.type === "AssignmentPattern") {
                this.raise(node.argument.start, "Rest elements cannot have a default value");
              }
              break;
            case "AssignmentExpression":
              if (node.operator !== "=") {
                this.raise(node.left.end, "Only '=' operator can be used for specifying default value.");
              }
              node.type = "AssignmentPattern";
              delete node.operator;
              this.toAssignable(node.left, isBinding);
              break;
            case "ParenthesizedExpression":
              this.toAssignable(node.expression, isBinding, refDestructuringErrors);
              break;
            case "ChainExpression":
              this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side");
              break;
            case "MemberExpression":
              if (!isBinding) {
                break;
              }
            default:
              this.raise(node.start, "Assigning to rvalue");
          }
        } else if (refDestructuringErrors) {
          this.checkPatternErrors(refDestructuringErrors, true);
        }
        return node;
      };
      pp$73.toAssignableList = function(exprList, isBinding) {
        var end = exprList.length;
        for (var i7 = 0; i7 < end; i7++) {
          var elt = exprList[i7];
          if (elt) {
            this.toAssignable(elt, isBinding);
          }
        }
        if (end) {
          var last = exprList[end - 1];
          if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier") {
            this.unexpected(last.argument.start);
          }
        }
        return exprList;
      };
      pp$73.parseSpread = function(refDestructuringErrors) {
        var node = this.startNode();
        this.next();
        node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
        return this.finishNode(node, "SpreadElement");
      };
      pp$73.parseRestBinding = function() {
        var node = this.startNode();
        this.next();
        if (this.options.ecmaVersion === 6 && this.type !== types$13.name) {
          this.unexpected();
        }
        node.argument = this.parseBindingAtom();
        return this.finishNode(node, "RestElement");
      };
      pp$73.parseBindingAtom = function() {
        if (this.options.ecmaVersion >= 6) {
          switch (this.type) {
            case types$13.bracketL:
              var node = this.startNode();
              this.next();
              node.elements = this.parseBindingList(types$13.bracketR, true, true);
              return this.finishNode(node, "ArrayPattern");
            case types$13.braceL:
              return this.parseObj(true);
          }
        }
        return this.parseIdent();
      };
      pp$73.parseBindingList = function(close, allowEmpty, allowTrailingComma, allowModifiers) {
        var elts = [], first = true;
        while (!this.eat(close)) {
          if (first) {
            first = false;
          } else {
            this.expect(types$13.comma);
          }
          if (allowEmpty && this.type === types$13.comma) {
            elts.push(null);
          } else if (allowTrailingComma && this.afterTrailingComma(close)) {
            break;
          } else if (this.type === types$13.ellipsis) {
            var rest = this.parseRestBinding();
            this.parseBindingListItem(rest);
            elts.push(rest);
            if (this.type === types$13.comma) {
              this.raiseRecoverable(this.start, "Comma is not permitted after the rest element");
            }
            this.expect(close);
            break;
          } else {
            elts.push(this.parseAssignableListItem(allowModifiers));
          }
        }
        return elts;
      };
      pp$73.parseAssignableListItem = function(allowModifiers) {
        var elem = this.parseMaybeDefault(this.start, this.startLoc);
        this.parseBindingListItem(elem);
        return elem;
      };
      pp$73.parseBindingListItem = function(param) {
        return param;
      };
      pp$73.parseMaybeDefault = function(startPos, startLoc, left) {
        left = left || this.parseBindingAtom();
        if (this.options.ecmaVersion < 6 || !this.eat(types$13.eq)) {
          return left;
        }
        var node = this.startNodeAt(startPos, startLoc);
        node.left = left;
        node.right = this.parseMaybeAssign();
        return this.finishNode(node, "AssignmentPattern");
      };
      pp$73.checkLValSimple = function(expr, bindingType, checkClashes) {
        if (bindingType === void 0) bindingType = BIND_NONE3;
        var isBind = bindingType !== BIND_NONE3;
        switch (expr.type) {
          case "Identifier":
            if (this.strict && this.reservedWordsStrictBind.test(expr.name)) {
              this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode");
            }
            if (isBind) {
              if (bindingType === BIND_LEXICAL3 && expr.name === "let") {
                this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name");
              }
              if (checkClashes) {
                if (hasOwn2(checkClashes, expr.name)) {
                  this.raiseRecoverable(expr.start, "Argument name clash");
                }
                checkClashes[expr.name] = true;
              }
              if (bindingType !== BIND_OUTSIDE3) {
                this.declareName(expr.name, bindingType, expr.start);
              }
            }
            break;
          case "ChainExpression":
            this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side");
            break;
          case "MemberExpression":
            if (isBind) {
              this.raiseRecoverable(expr.start, "Binding member expression");
            }
            break;
          case "ParenthesizedExpression":
            if (isBind) {
              this.raiseRecoverable(expr.start, "Binding parenthesized expression");
            }
            return this.checkLValSimple(expr.expression, bindingType, checkClashes);
          default:
            this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue");
        }
      };
      pp$73.checkLValPattern = function(expr, bindingType, checkClashes) {
        if (bindingType === void 0) bindingType = BIND_NONE3;
        switch (expr.type) {
          case "ObjectPattern":
            for (var i7 = 0, list2 = expr.properties; i7 < list2.length; i7 += 1) {
              var prop = list2[i7];
              this.checkLValInnerPattern(prop, bindingType, checkClashes);
            }
            break;
          case "ArrayPattern":
            for (var i$13 = 0, list$1 = expr.elements; i$13 < list$1.length; i$13 += 1) {
              var elem = list$1[i$13];
              if (elem) {
                this.checkLValInnerPattern(elem, bindingType, checkClashes);
              }
            }
            break;
          default:
            this.checkLValSimple(expr, bindingType, checkClashes);
        }
      };
      pp$73.checkLValInnerPattern = function(expr, bindingType, checkClashes) {
        if (bindingType === void 0) bindingType = BIND_NONE3;
        switch (expr.type) {
          case "Property":
            this.checkLValInnerPattern(expr.value, bindingType, checkClashes);
            break;
          case "AssignmentPattern":
            this.checkLValPattern(expr.left, bindingType, checkClashes);
            break;
          case "RestElement":
            this.checkLValPattern(expr.argument, bindingType, checkClashes);
            break;
          default:
            this.checkLValPattern(expr, bindingType, checkClashes);
        }
      };
      var TokContext4 = function TokContext5(token, isExpr, preserveSpace, override, generator) {
        this.token = token;
        this.isExpr = !!isExpr;
        this.preserveSpace = !!preserveSpace;
        this.override = override;
        this.generator = !!generator;
      };
      var types8 = {
        b_stat: new TokContext4("{", false),
        b_expr: new TokContext4("{", true),
        b_tmpl: new TokContext4("${", false),
        p_stat: new TokContext4("(", false),
        p_expr: new TokContext4("(", true),
        q_tmpl: new TokContext4("`", true, true, function(p5) {
          return p5.tryReadTemplateToken();
        }),
        f_stat: new TokContext4("function", false),
        f_expr: new TokContext4("function", true),
        f_expr_gen: new TokContext4("function", true, false, null, true),
        f_gen: new TokContext4("function", false, false, null, true)
      };
      var pp$63 = Parser6.prototype;
      pp$63.initialContext = function() {
        return [types8.b_stat];
      };
      pp$63.curContext = function() {
        return this.context[this.context.length - 1];
      };
      pp$63.braceIsBlock = function(prevType) {
        var parent = this.curContext();
        if (parent === types8.f_expr || parent === types8.f_stat) {
          return true;
        }
        if (prevType === types$13.colon && (parent === types8.b_stat || parent === types8.b_expr)) {
          return !parent.isExpr;
        }
        if (prevType === types$13._return || prevType === types$13.name && this.exprAllowed) {
          return lineBreak3.test(this.input.slice(this.lastTokEnd, this.start));
        }
        if (prevType === types$13._else || prevType === types$13.semi || prevType === types$13.eof || prevType === types$13.parenR || prevType === types$13.arrow) {
          return true;
        }
        if (prevType === types$13.braceL) {
          return parent === types8.b_stat;
        }
        if (prevType === types$13._var || prevType === types$13._const || prevType === types$13.name) {
          return false;
        }
        return !this.exprAllowed;
      };
      pp$63.inGeneratorContext = function() {
        for (var i7 = this.context.length - 1; i7 >= 1; i7--) {
          var context = this.context[i7];
          if (context.token === "function") {
            return context.generator;
          }
        }
        return false;
      };
      pp$63.updateContext = function(prevType) {
        var update, type4 = this.type;
        if (type4.keyword && prevType === types$13.dot) {
          this.exprAllowed = false;
        } else if (update = type4.updateContext) {
          update.call(this, prevType);
        } else {
          this.exprAllowed = type4.beforeExpr;
        }
      };
      pp$63.overrideContext = function(tokenCtx) {
        if (this.curContext() !== tokenCtx) {
          this.context[this.context.length - 1] = tokenCtx;
        }
      };
      types$13.parenR.updateContext = types$13.braceR.updateContext = function() {
        if (this.context.length === 1) {
          this.exprAllowed = true;
          return;
        }
        var out = this.context.pop();
        if (out === types8.b_stat && this.curContext().token === "function") {
          out = this.context.pop();
        }
        this.exprAllowed = !out.isExpr;
      };
      types$13.braceL.updateContext = function(prevType) {
        this.context.push(this.braceIsBlock(prevType) ? types8.b_stat : types8.b_expr);
        this.exprAllowed = true;
      };
      types$13.dollarBraceL.updateContext = function() {
        this.context.push(types8.b_tmpl);
        this.exprAllowed = true;
      };
      types$13.parenL.updateContext = function(prevType) {
        var statementParens = prevType === types$13._if || prevType === types$13._for || prevType === types$13._with || prevType === types$13._while;
        this.context.push(statementParens ? types8.p_stat : types8.p_expr);
        this.exprAllowed = true;
      };
      types$13.incDec.updateContext = function() {
      };
      types$13._function.updateContext = types$13._class.updateContext = function(prevType) {
        if (prevType.beforeExpr && prevType !== types$13._else && !(prevType === types$13.semi && this.curContext() !== types8.p_stat) && !(prevType === types$13._return && lineBreak3.test(this.input.slice(this.lastTokEnd, this.start))) && !((prevType === types$13.colon || prevType === types$13.braceL) && this.curContext() === types8.b_stat)) {
          this.context.push(types8.f_expr);
        } else {
          this.context.push(types8.f_stat);
        }
        this.exprAllowed = false;
      };
      types$13.colon.updateContext = function() {
        if (this.curContext().token === "function") {
          this.context.pop();
        }
        this.exprAllowed = true;
      };
      types$13.backQuote.updateContext = function() {
        if (this.curContext() === types8.q_tmpl) {
          this.context.pop();
        } else {
          this.context.push(types8.q_tmpl);
        }
        this.exprAllowed = false;
      };
      types$13.star.updateContext = function(prevType) {
        if (prevType === types$13._function) {
          var index2 = this.context.length - 1;
          if (this.context[index2] === types8.f_expr) {
            this.context[index2] = types8.f_expr_gen;
          } else {
            this.context[index2] = types8.f_gen;
          }
        }
        this.exprAllowed = true;
      };
      types$13.name.updateContext = function(prevType) {
        var allowed = false;
        if (this.options.ecmaVersion >= 6 && prevType !== types$13.dot) {
          if (this.value === "of" && !this.exprAllowed || this.value === "yield" && this.inGeneratorContext()) {
            allowed = true;
          }
        }
        this.exprAllowed = allowed;
      };
      var pp$53 = Parser6.prototype;
      pp$53.checkPropClash = function(prop, propHash, refDestructuringErrors) {
        if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement") {
          return;
        }
        if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) {
          return;
        }
        var key = prop.key;
        var name2;
        switch (key.type) {
          case "Identifier":
            name2 = key.name;
            break;
          case "Literal":
            name2 = String(key.value);
            break;
          default:
            return;
        }
        var kind = prop.kind;
        if (this.options.ecmaVersion >= 6) {
          if (name2 === "__proto__" && kind === "init") {
            if (propHash.proto) {
              if (refDestructuringErrors) {
                if (refDestructuringErrors.doubleProto < 0) {
                  refDestructuringErrors.doubleProto = key.start;
                }
              } else {
                this.raiseRecoverable(key.start, "Redefinition of __proto__ property");
              }
            }
            propHash.proto = true;
          }
          return;
        }
        name2 = "$" + name2;
        var other = propHash[name2];
        if (other) {
          var redefinition;
          if (kind === "init") {
            redefinition = this.strict && other.init || other.get || other.set;
          } else {
            redefinition = other.init || other[kind];
          }
          if (redefinition) {
            this.raiseRecoverable(key.start, "Redefinition of property");
          }
        } else {
          other = propHash[name2] = {
            init: false,
            get: false,
            set: false
          };
        }
        other[kind] = true;
      };
      pp$53.parseExpression = function(forInit, refDestructuringErrors) {
        var startPos = this.start, startLoc = this.startLoc;
        var expr = this.parseMaybeAssign(forInit, refDestructuringErrors);
        if (this.type === types$13.comma) {
          var node = this.startNodeAt(startPos, startLoc);
          node.expressions = [expr];
          while (this.eat(types$13.comma)) {
            node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors));
          }
          return this.finishNode(node, "SequenceExpression");
        }
        return expr;
      };
      pp$53.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) {
        if (this.isContextual("yield")) {
          if (this.inGenerator) {
            return this.parseYield(forInit);
          } else {
            this.exprAllowed = false;
          }
        }
        var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1;
        if (refDestructuringErrors) {
          oldParenAssign = refDestructuringErrors.parenthesizedAssign;
          oldTrailingComma = refDestructuringErrors.trailingComma;
          oldDoubleProto = refDestructuringErrors.doubleProto;
          refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
        } else {
          refDestructuringErrors = new DestructuringErrors3();
          ownDestructuringErrors = true;
        }
        var startPos = this.start, startLoc = this.startLoc;
        if (this.type === types$13.parenL || this.type === types$13.name) {
          this.potentialArrowAt = this.start;
          this.potentialArrowInForAwait = forInit === "await";
        }
        var left = this.parseMaybeConditional(forInit, refDestructuringErrors);
        if (afterLeftParse) {
          left = afterLeftParse.call(this, left, startPos, startLoc);
        }
        if (this.type.isAssign) {
          var node = this.startNodeAt(startPos, startLoc);
          node.operator = this.value;
          if (this.type === types$13.eq) {
            left = this.toAssignable(left, false, refDestructuringErrors);
          }
          if (!ownDestructuringErrors) {
            refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;
          }
          if (refDestructuringErrors.shorthandAssign >= left.start) {
            refDestructuringErrors.shorthandAssign = -1;
          }
          if (this.type === types$13.eq) {
            this.checkLValPattern(left);
          } else {
            this.checkLValSimple(left);
          }
          node.left = left;
          this.next();
          node.right = this.parseMaybeAssign(forInit);
          if (oldDoubleProto > -1) {
            refDestructuringErrors.doubleProto = oldDoubleProto;
          }
          return this.finishNode(node, "AssignmentExpression");
        } else {
          if (ownDestructuringErrors) {
            this.checkExpressionErrors(refDestructuringErrors, true);
          }
        }
        if (oldParenAssign > -1) {
          refDestructuringErrors.parenthesizedAssign = oldParenAssign;
        }
        if (oldTrailingComma > -1) {
          refDestructuringErrors.trailingComma = oldTrailingComma;
        }
        return left;
      };
      pp$53.parseMaybeConditional = function(forInit, refDestructuringErrors) {
        var startPos = this.start, startLoc = this.startLoc;
        var expr = this.parseExprOps(forInit, refDestructuringErrors);
        if (this.checkExpressionErrors(refDestructuringErrors)) {
          return expr;
        }
        if (this.eat(types$13.question)) {
          var node = this.startNodeAt(startPos, startLoc);
          node.test = expr;
          node.consequent = this.parseMaybeAssign();
          this.expect(types$13.colon);
          node.alternate = this.parseMaybeAssign(forInit);
          return this.finishNode(node, "ConditionalExpression");
        }
        return expr;
      };
      pp$53.parseExprOps = function(forInit, refDestructuringErrors) {
        var startPos = this.start, startLoc = this.startLoc;
        var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit);
        if (this.checkExpressionErrors(refDestructuringErrors)) {
          return expr;
        }
        return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit);
      };
      pp$53.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) {
        var prec = this.type.binop;
        if (prec != null && (!forInit || this.type !== types$13._in)) {
          if (prec > minPrec) {
            var logical = this.type === types$13.logicalOR || this.type === types$13.logicalAND;
            var coalesce = this.type === types$13.coalesce;
            if (coalesce) {
              prec = types$13.logicalAND.binop;
            }
            var op = this.value;
            this.next();
            var startPos = this.start, startLoc = this.startLoc;
            var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit);
            var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);
            if (logical && this.type === types$13.coalesce || coalesce && (this.type === types$13.logicalOR || this.type === types$13.logicalAND)) {
              this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");
            }
            return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit);
          }
        }
        return left;
      };
      pp$53.buildBinary = function(startPos, startLoc, left, right, op, logical) {
        if (right.type === "PrivateIdentifier") {
          this.raise(right.start, "Private identifier can only be left side of binary expression");
        }
        var node = this.startNodeAt(startPos, startLoc);
        node.left = left;
        node.operator = op;
        node.right = right;
        return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression");
      };
      pp$53.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) {
        var startPos = this.start, startLoc = this.startLoc, expr;
        if (this.isContextual("await") && this.canAwait) {
          expr = this.parseAwait(forInit);
          sawUnary = true;
        } else if (this.type.prefix) {
          var node = this.startNode(), update = this.type === types$13.incDec;
          node.operator = this.value;
          node.prefix = true;
          this.next();
          node.argument = this.parseMaybeUnary(null, true, update, forInit);
          this.checkExpressionErrors(refDestructuringErrors, true);
          if (update) {
            this.checkLValSimple(node.argument);
          } else if (this.strict && node.operator === "delete" && isLocalVariableAccess(node.argument)) {
            this.raiseRecoverable(node.start, "Deleting local variable in strict mode");
          } else if (node.operator === "delete" && isPrivateFieldAccess2(node.argument)) {
            this.raiseRecoverable(node.start, "Private fields can not be deleted");
          } else {
            sawUnary = true;
          }
          expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
        } else if (!sawUnary && this.type === types$13.privateId) {
          if ((forInit || this.privateNameStack.length === 0) && this.options.checkPrivateFields) {
            this.unexpected();
          }
          expr = this.parsePrivateIdent();
          if (this.type !== types$13._in) {
            this.unexpected();
          }
        } else {
          expr = this.parseExprSubscripts(refDestructuringErrors, forInit);
          if (this.checkExpressionErrors(refDestructuringErrors)) {
            return expr;
          }
          while (this.type.postfix && !this.canInsertSemicolon()) {
            var node$1 = this.startNodeAt(startPos, startLoc);
            node$1.operator = this.value;
            node$1.prefix = false;
            node$1.argument = expr;
            this.checkLValSimple(expr);
            this.next();
            expr = this.finishNode(node$1, "UpdateExpression");
          }
        }
        if (!incDec && this.eat(types$13.starstar)) {
          if (sawUnary) {
            this.unexpected(this.lastTokStart);
          } else {
            return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false);
          }
        } else {
          return expr;
        }
      };
      function isLocalVariableAccess(node) {
        return node.type === "Identifier" || node.type === "ParenthesizedExpression" && isLocalVariableAccess(node.expression);
      }
      function isPrivateFieldAccess2(node) {
        return node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" || node.type === "ChainExpression" && isPrivateFieldAccess2(node.expression) || node.type === "ParenthesizedExpression" && isPrivateFieldAccess2(node.expression);
      }
      pp$53.parseExprSubscripts = function(refDestructuringErrors, forInit) {
        var startPos = this.start, startLoc = this.startLoc;
        var expr = this.parseExprAtom(refDestructuringErrors, forInit);
        if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")") {
          return expr;
        }
        var result2 = this.parseSubscripts(expr, startPos, startLoc, false, forInit);
        if (refDestructuringErrors && result2.type === "MemberExpression") {
          if (refDestructuringErrors.parenthesizedAssign >= result2.start) {
            refDestructuringErrors.parenthesizedAssign = -1;
          }
          if (refDestructuringErrors.parenthesizedBind >= result2.start) {
            refDestructuringErrors.parenthesizedBind = -1;
          }
          if (refDestructuringErrors.trailingComma >= result2.start) {
            refDestructuringErrors.trailingComma = -1;
          }
        }
        return result2;
      };
      pp$53.parseSubscripts = function(base3, startPos, startLoc, noCalls, forInit) {
        var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base3.type === "Identifier" && base3.name === "async" && this.lastTokEnd === base3.end && !this.canInsertSemicolon() && base3.end - base3.start === 5 && this.potentialArrowAt === base3.start;
        var optionalChained = false;
        while (true) {
          var element = this.parseSubscript(base3, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit);
          if (element.optional) {
            optionalChained = true;
          }
          if (element === base3 || element.type === "ArrowFunctionExpression") {
            if (optionalChained) {
              var chainNode = this.startNodeAt(startPos, startLoc);
              chainNode.expression = element;
              element = this.finishNode(chainNode, "ChainExpression");
            }
            return element;
          }
          base3 = element;
        }
      };
      pp$53.shouldParseAsyncArrow = function() {
        return !this.canInsertSemicolon() && this.eat(types$13.arrow);
      };
      pp$53.parseSubscriptAsyncArrow = function(startPos, startLoc, exprList, forInit) {
        return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit);
      };
      pp$53.parseSubscript = function(base3, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) {
        var optionalSupported = this.options.ecmaVersion >= 11;
        var optional = optionalSupported && this.eat(types$13.questionDot);
        if (noCalls && optional) {
          this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions");
        }
        var computed = this.eat(types$13.bracketL);
        if (computed || optional && this.type !== types$13.parenL && this.type !== types$13.backQuote || this.eat(types$13.dot)) {
          var node = this.startNodeAt(startPos, startLoc);
          node.object = base3;
          if (computed) {
            node.property = this.parseExpression();
            this.expect(types$13.bracketR);
          } else if (this.type === types$13.privateId && base3.type !== "Super") {
            node.property = this.parsePrivateIdent();
          } else {
            node.property = this.parseIdent(this.options.allowReserved !== "never");
          }
          node.computed = !!computed;
          if (optionalSupported) {
            node.optional = optional;
          }
          base3 = this.finishNode(node, "MemberExpression");
        } else if (!noCalls && this.eat(types$13.parenL)) {
          var refDestructuringErrors = new DestructuringErrors3(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
          this.yieldPos = 0;
          this.awaitPos = 0;
          this.awaitIdentPos = 0;
          var exprList = this.parseExprList(types$13.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
          if (maybeAsyncArrow && !optional && this.shouldParseAsyncArrow()) {
            this.checkPatternErrors(refDestructuringErrors, false);
            this.checkYieldAwaitInDefaultParams();
            if (this.awaitIdentPos > 0) {
              this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function");
            }
            this.yieldPos = oldYieldPos;
            this.awaitPos = oldAwaitPos;
            this.awaitIdentPos = oldAwaitIdentPos;
            return this.parseSubscriptAsyncArrow(startPos, startLoc, exprList, forInit);
          }
          this.checkExpressionErrors(refDestructuringErrors, true);
          this.yieldPos = oldYieldPos || this.yieldPos;
          this.awaitPos = oldAwaitPos || this.awaitPos;
          this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
          var node$1 = this.startNodeAt(startPos, startLoc);
          node$1.callee = base3;
          node$1.arguments = exprList;
          if (optionalSupported) {
            node$1.optional = optional;
          }
          base3 = this.finishNode(node$1, "CallExpression");
        } else if (this.type === types$13.backQuote) {
          if (optional || optionalChained) {
            this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions");
          }
          var node$2 = this.startNodeAt(startPos, startLoc);
          node$2.tag = base3;
          node$2.quasi = this.parseTemplate({ isTagged: true });
          base3 = this.finishNode(node$2, "TaggedTemplateExpression");
        }
        return base3;
      };
      pp$53.parseExprAtom = function(refDestructuringErrors, forInit, forNew) {
        if (this.type === types$13.slash) {
          this.readRegexp();
        }
        var node, canBeArrow = this.potentialArrowAt === this.start;
        switch (this.type) {
          case types$13._super:
            if (!this.allowSuper) {
              this.raise(this.start, "'super' keyword outside a method");
            }
            node = this.startNode();
            this.next();
            if (this.type === types$13.parenL && !this.allowDirectSuper) {
              this.raise(node.start, "super() call outside constructor of a subclass");
            }
            if (this.type !== types$13.dot && this.type !== types$13.bracketL && this.type !== types$13.parenL) {
              this.unexpected();
            }
            return this.finishNode(node, "Super");
          case types$13._this:
            node = this.startNode();
            this.next();
            return this.finishNode(node, "ThisExpression");
          case types$13.name:
            var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;
            var id = this.parseIdent(false);
            if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types$13._function)) {
              this.overrideContext(types8.f_expr);
              return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit);
            }
            if (canBeArrow && !this.canInsertSemicolon()) {
              if (this.eat(types$13.arrow)) {
                return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit);
              }
              if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types$13.name && !containsEsc && (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) {
                id = this.parseIdent(false);
                if (this.canInsertSemicolon() || !this.eat(types$13.arrow)) {
                  this.unexpected();
                }
                return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit);
              }
            }
            return id;
          case types$13.regexp:
            var value = this.value;
            node = this.parseLiteral(value.value);
            node.regex = { pattern: value.pattern, flags: value.flags };
            return node;
          case types$13.num:
          case types$13.string:
            return this.parseLiteral(this.value);
          case types$13._null:
          case types$13._true:
          case types$13._false:
            node = this.startNode();
            node.value = this.type === types$13._null ? null : this.type === types$13._true;
            node.raw = this.type.keyword;
            this.next();
            return this.finishNode(node, "Literal");
          case types$13.parenL:
            var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit);
            if (refDestructuringErrors) {
              if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr)) {
                refDestructuringErrors.parenthesizedAssign = start;
              }
              if (refDestructuringErrors.parenthesizedBind < 0) {
                refDestructuringErrors.parenthesizedBind = start;
              }
            }
            return expr;
          case types$13.bracketL:
            node = this.startNode();
            this.next();
            node.elements = this.parseExprList(types$13.bracketR, true, true, refDestructuringErrors);
            return this.finishNode(node, "ArrayExpression");
          case types$13.braceL:
            this.overrideContext(types8.b_expr);
            return this.parseObj(false, refDestructuringErrors);
          case types$13._function:
            node = this.startNode();
            this.next();
            return this.parseFunction(node, 0);
          case types$13._class:
            return this.parseClass(this.startNode(), false);
          case types$13._new:
            return this.parseNew();
          case types$13.backQuote:
            return this.parseTemplate();
          case types$13._import:
            if (this.options.ecmaVersion >= 11) {
              return this.parseExprImport(forNew);
            } else {
              return this.unexpected();
            }
          default:
            return this.parseExprAtomDefault();
        }
      };
      pp$53.parseExprAtomDefault = function() {
        this.unexpected();
      };
      pp$53.parseExprImport = function(forNew) {
        var node = this.startNode();
        if (this.containsEsc) {
          this.raiseRecoverable(this.start, "Escape sequence in keyword import");
        }
        this.next();
        if (this.type === types$13.parenL && !forNew) {
          return this.parseDynamicImport(node);
        } else if (this.type === types$13.dot) {
          var meta = this.startNodeAt(node.start, node.loc && node.loc.start);
          meta.name = "import";
          node.meta = this.finishNode(meta, "Identifier");
          return this.parseImportMeta(node);
        } else {
          this.unexpected();
        }
      };
      pp$53.parseDynamicImport = function(node) {
        this.next();
        node.source = this.parseMaybeAssign();
        if (this.options.ecmaVersion >= 16) {
          if (!this.eat(types$13.parenR)) {
            this.expect(types$13.comma);
            if (!this.afterTrailingComma(types$13.parenR)) {
              node.options = this.parseMaybeAssign();
              if (!this.eat(types$13.parenR)) {
                this.expect(types$13.comma);
                if (!this.afterTrailingComma(types$13.parenR)) {
                  this.unexpected();
                }
              }
            } else {
              node.options = null;
            }
          } else {
            node.options = null;
          }
        } else {
          if (!this.eat(types$13.parenR)) {
            var errorPos = this.start;
            if (this.eat(types$13.comma) && this.eat(types$13.parenR)) {
              this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
            } else {
              this.unexpected(errorPos);
            }
          }
        }
        return this.finishNode(node, "ImportExpression");
      };
      pp$53.parseImportMeta = function(node) {
        this.next();
        var containsEsc = this.containsEsc;
        node.property = this.parseIdent(true);
        if (node.property.name !== "meta") {
          this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'");
        }
        if (containsEsc) {
          this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters");
        }
        if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere) {
          this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module");
        }
        return this.finishNode(node, "MetaProperty");
      };
      pp$53.parseLiteral = function(value) {
        var node = this.startNode();
        node.value = value;
        node.raw = this.input.slice(this.start, this.end);
        if (node.raw.charCodeAt(node.raw.length - 1) === 110) {
          node.bigint = node.value != null ? node.value.toString() : node.raw.slice(0, -1).replace(/_/g, "");
        }
        this.next();
        return this.finishNode(node, "Literal");
      };
      pp$53.parseParenExpression = function() {
        this.expect(types$13.parenL);
        var val = this.parseExpression();
        this.expect(types$13.parenR);
        return val;
      };
      pp$53.shouldParseArrow = function(exprList) {
        return !this.canInsertSemicolon();
      };
      pp$53.parseParenAndDistinguishExpression = function(canBeArrow, forInit) {
        var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
        if (this.options.ecmaVersion >= 6) {
          this.next();
          var innerStartPos = this.start, innerStartLoc = this.startLoc;
          var exprList = [], first = true, lastIsComma = false;
          var refDestructuringErrors = new DestructuringErrors3(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;
          this.yieldPos = 0;
          this.awaitPos = 0;
          while (this.type !== types$13.parenR) {
            first ? first = false : this.expect(types$13.comma);
            if (allowTrailingComma && this.afterTrailingComma(types$13.parenR, true)) {
              lastIsComma = true;
              break;
            } else if (this.type === types$13.ellipsis) {
              spreadStart = this.start;
              exprList.push(this.parseParenItem(this.parseRestBinding()));
              if (this.type === types$13.comma) {
                this.raiseRecoverable(
                  this.start,
                  "Comma is not permitted after the rest element"
                );
              }
              break;
            } else {
              exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
            }
          }
          var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc;
          this.expect(types$13.parenR);
          if (canBeArrow && this.shouldParseArrow(exprList) && this.eat(types$13.arrow)) {
            this.checkPatternErrors(refDestructuringErrors, false);
            this.checkYieldAwaitInDefaultParams();
            this.yieldPos = oldYieldPos;
            this.awaitPos = oldAwaitPos;
            return this.parseParenArrowList(startPos, startLoc, exprList, forInit);
          }
          if (!exprList.length || lastIsComma) {
            this.unexpected(this.lastTokStart);
          }
          if (spreadStart) {
            this.unexpected(spreadStart);
          }
          this.checkExpressionErrors(refDestructuringErrors, true);
          this.yieldPos = oldYieldPos || this.yieldPos;
          this.awaitPos = oldAwaitPos || this.awaitPos;
          if (exprList.length > 1) {
            val = this.startNodeAt(innerStartPos, innerStartLoc);
            val.expressions = exprList;
            this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
          } else {
            val = exprList[0];
          }
        } else {
          val = this.parseParenExpression();
        }
        if (this.options.preserveParens) {
          var par = this.startNodeAt(startPos, startLoc);
          par.expression = val;
          return this.finishNode(par, "ParenthesizedExpression");
        } else {
          return val;
        }
      };
      pp$53.parseParenItem = function(item) {
        return item;
      };
      pp$53.parseParenArrowList = function(startPos, startLoc, exprList, forInit) {
        return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit);
      };
      var empty3 = [];
      pp$53.parseNew = function() {
        if (this.containsEsc) {
          this.raiseRecoverable(this.start, "Escape sequence in keyword new");
        }
        var node = this.startNode();
        this.next();
        if (this.options.ecmaVersion >= 6 && this.type === types$13.dot) {
          var meta = this.startNodeAt(node.start, node.loc && node.loc.start);
          meta.name = "new";
          node.meta = this.finishNode(meta, "Identifier");
          this.next();
          var containsEsc = this.containsEsc;
          node.property = this.parseIdent(true);
          if (node.property.name !== "target") {
            this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'");
          }
          if (containsEsc) {
            this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters");
          }
          if (!this.allowNewDotTarget) {
            this.raiseRecoverable(node.start, "'new.target' can only be used in functions and class static block");
          }
          return this.finishNode(node, "MetaProperty");
        }
        var startPos = this.start, startLoc = this.startLoc;
        node.callee = this.parseSubscripts(this.parseExprAtom(null, false, true), startPos, startLoc, true, false);
        if (this.eat(types$13.parenL)) {
          node.arguments = this.parseExprList(types$13.parenR, this.options.ecmaVersion >= 8, false);
        } else {
          node.arguments = empty3;
        }
        return this.finishNode(node, "NewExpression");
      };
      pp$53.parseTemplateElement = function(ref4) {
        var isTagged = ref4.isTagged;
        var elem = this.startNode();
        if (this.type === types$13.invalidTemplate) {
          if (!isTagged) {
            this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
          }
          elem.value = {
            raw: this.value.replace(/\r\n?/g, "\n"),
            cooked: null
          };
        } else {
          elem.value = {
            raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
            cooked: this.value
          };
        }
        this.next();
        elem.tail = this.type === types$13.backQuote;
        return this.finishNode(elem, "TemplateElement");
      };
      pp$53.parseTemplate = function(ref4) {
        if (ref4 === void 0) ref4 = {};
        var isTagged = ref4.isTagged;
        if (isTagged === void 0) isTagged = false;
        var node = this.startNode();
        this.next();
        node.expressions = [];
        var curElt = this.parseTemplateElement({ isTagged });
        node.quasis = [curElt];
        while (!curElt.tail) {
          if (this.type === types$13.eof) {
            this.raise(this.pos, "Unterminated template literal");
          }
          this.expect(types$13.dollarBraceL);
          node.expressions.push(this.parseExpression());
          this.expect(types$13.braceR);
          node.quasis.push(curElt = this.parseTemplateElement({ isTagged }));
        }
        this.next();
        return this.finishNode(node, "TemplateLiteral");
      };
      pp$53.isAsyncProp = function(prop) {
        return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" && (this.type === types$13.name || this.type === types$13.num || this.type === types$13.string || this.type === types$13.bracketL || this.type.keyword || this.options.ecmaVersion >= 9 && this.type === types$13.star) && !lineBreak3.test(this.input.slice(this.lastTokEnd, this.start));
      };
      pp$53.parseObj = function(isPattern, refDestructuringErrors) {
        var node = this.startNode(), first = true, propHash = {};
        node.properties = [];
        this.next();
        while (!this.eat(types$13.braceR)) {
          if (!first) {
            this.expect(types$13.comma);
            if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types$13.braceR)) {
              break;
            }
          } else {
            first = false;
          }
          var prop = this.parseProperty(isPattern, refDestructuringErrors);
          if (!isPattern) {
            this.checkPropClash(prop, propHash, refDestructuringErrors);
          }
          node.properties.push(prop);
        }
        return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression");
      };
      pp$53.parseProperty = function(isPattern, refDestructuringErrors) {
        var prop = this.startNode(), isGenerator, isAsync2, startPos, startLoc;
        if (this.options.ecmaVersion >= 9 && this.eat(types$13.ellipsis)) {
          if (isPattern) {
            prop.argument = this.parseIdent(false);
            if (this.type === types$13.comma) {
              this.raiseRecoverable(this.start, "Comma is not permitted after the rest element");
            }
            return this.finishNode(prop, "RestElement");
          }
          prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
          if (this.type === types$13.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
            refDestructuringErrors.trailingComma = this.start;
          }
          return this.finishNode(prop, "SpreadElement");
        }
        if (this.options.ecmaVersion >= 6) {
          prop.method = false;
          prop.shorthand = false;
          if (isPattern || refDestructuringErrors) {
            startPos = this.start;
            startLoc = this.startLoc;
          }
          if (!isPattern) {
            isGenerator = this.eat(types$13.star);
          }
        }
        var containsEsc = this.containsEsc;
        this.parsePropertyName(prop);
        if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
          isAsync2 = true;
          isGenerator = this.options.ecmaVersion >= 9 && this.eat(types$13.star);
          this.parsePropertyName(prop);
        } else {
          isAsync2 = false;
        }
        this.parsePropertyValue(prop, isPattern, isGenerator, isAsync2, startPos, startLoc, refDestructuringErrors, containsEsc);
        return this.finishNode(prop, "Property");
      };
      pp$53.parseGetterSetter = function(prop) {
        var kind = prop.key.name;
        this.parsePropertyName(prop);
        prop.value = this.parseMethod(false);
        prop.kind = kind;
        var paramCount = prop.kind === "get" ? 0 : 1;
        if (prop.value.params.length !== paramCount) {
          var start = prop.value.start;
          if (prop.kind === "get") {
            this.raiseRecoverable(start, "getter should have no params");
          } else {
            this.raiseRecoverable(start, "setter should have exactly one param");
          }
        } else {
          if (prop.kind === "set" && prop.value.params[0].type === "RestElement") {
            this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params");
          }
        }
      };
      pp$53.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync2, startPos, startLoc, refDestructuringErrors, containsEsc) {
        if ((isGenerator || isAsync2) && this.type === types$13.colon) {
          this.unexpected();
        }
        if (this.eat(types$13.colon)) {
          prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
          prop.kind = "init";
        } else if (this.options.ecmaVersion >= 6 && this.type === types$13.parenL) {
          if (isPattern) {
            this.unexpected();
          }
          prop.method = true;
          prop.value = this.parseMethod(isGenerator, isAsync2);
          prop.kind = "init";
        } else if (!isPattern && !containsEsc && this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && (prop.key.name === "get" || prop.key.name === "set") && (this.type !== types$13.comma && this.type !== types$13.braceR && this.type !== types$13.eq)) {
          if (isGenerator || isAsync2) {
            this.unexpected();
          }
          this.parseGetterSetter(prop);
        } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
          if (isGenerator || isAsync2) {
            this.unexpected();
          }
          this.checkUnreserved(prop.key);
          if (prop.key.name === "await" && !this.awaitIdentPos) {
            this.awaitIdentPos = startPos;
          }
          if (isPattern) {
            prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
          } else if (this.type === types$13.eq && refDestructuringErrors) {
            if (refDestructuringErrors.shorthandAssign < 0) {
              refDestructuringErrors.shorthandAssign = this.start;
            }
            prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
          } else {
            prop.value = this.copyNode(prop.key);
          }
          prop.kind = "init";
          prop.shorthand = true;
        } else {
          this.unexpected();
        }
      };
      pp$53.parsePropertyName = function(prop) {
        if (this.options.ecmaVersion >= 6) {
          if (this.eat(types$13.bracketL)) {
            prop.computed = true;
            prop.key = this.parseMaybeAssign();
            this.expect(types$13.bracketR);
            return prop.key;
          } else {
            prop.computed = false;
          }
        }
        return prop.key = this.type === types$13.num || this.type === types$13.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never");
      };
      pp$53.initFunction = function(node) {
        node.id = null;
        if (this.options.ecmaVersion >= 6) {
          node.generator = node.expression = false;
        }
        if (this.options.ecmaVersion >= 8) {
          node.async = false;
        }
      };
      pp$53.parseMethod = function(isGenerator, isAsync2, allowDirectSuper) {
        var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
        this.initFunction(node);
        if (this.options.ecmaVersion >= 6) {
          node.generator = isGenerator;
        }
        if (this.options.ecmaVersion >= 8) {
          node.async = !!isAsync2;
        }
        this.yieldPos = 0;
        this.awaitPos = 0;
        this.awaitIdentPos = 0;
        this.enterScope(functionFlags3(isAsync2, node.generator) | SCOPE_SUPER3 | (allowDirectSuper ? SCOPE_DIRECT_SUPER3 : 0));
        this.expect(types$13.parenL);
        node.params = this.parseBindingList(types$13.parenR, false, this.options.ecmaVersion >= 8);
        this.checkYieldAwaitInDefaultParams();
        this.parseFunctionBody(node, false, true, false);
        this.yieldPos = oldYieldPos;
        this.awaitPos = oldAwaitPos;
        this.awaitIdentPos = oldAwaitIdentPos;
        return this.finishNode(node, "FunctionExpression");
      };
      pp$53.parseArrowExpression = function(node, params, isAsync2, forInit) {
        var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
        this.enterScope(functionFlags3(isAsync2, false) | SCOPE_ARROW3);
        this.initFunction(node);
        if (this.options.ecmaVersion >= 8) {
          node.async = !!isAsync2;
        }
        this.yieldPos = 0;
        this.awaitPos = 0;
        this.awaitIdentPos = 0;
        node.params = this.toAssignableList(params, true);
        this.parseFunctionBody(node, true, false, forInit);
        this.yieldPos = oldYieldPos;
        this.awaitPos = oldAwaitPos;
        this.awaitIdentPos = oldAwaitIdentPos;
        return this.finishNode(node, "ArrowFunctionExpression");
      };
      pp$53.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) {
        var isExpression = isArrowFunction && this.type !== types$13.braceL;
        var oldStrict = this.strict, useStrict = false;
        if (isExpression) {
          node.body = this.parseMaybeAssign(forInit);
          node.expression = true;
          this.checkParams(node, false);
        } else {
          var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
          if (!oldStrict || nonSimple) {
            useStrict = this.strictDirective(this.end);
            if (useStrict && nonSimple) {
              this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list");
            }
          }
          var oldLabels = this.labels;
          this.labels = [];
          if (useStrict) {
            this.strict = true;
          }
          this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));
          if (this.strict && node.id) {
            this.checkLValSimple(node.id, BIND_OUTSIDE3);
          }
          node.body = this.parseBlock(false, void 0, useStrict && !oldStrict);
          node.expression = false;
          this.adaptDirectivePrologue(node.body.body);
          this.labels = oldLabels;
        }
        this.exitScope();
      };
      pp$53.isSimpleParamList = function(params) {
        for (var i7 = 0, list2 = params; i7 < list2.length; i7 += 1) {
          var param = list2[i7];
          if (param.type !== "Identifier") {
            return false;
          }
        }
        return true;
      };
      pp$53.checkParams = function(node, allowDuplicates) {
        var nameHash = /* @__PURE__ */ Object.create(null);
        for (var i7 = 0, list2 = node.params; i7 < list2.length; i7 += 1) {
          var param = list2[i7];
          this.checkLValInnerPattern(param, BIND_VAR3, allowDuplicates ? null : nameHash);
        }
      };
      pp$53.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
        var elts = [], first = true;
        while (!this.eat(close)) {
          if (!first) {
            this.expect(types$13.comma);
            if (allowTrailingComma && this.afterTrailingComma(close)) {
              break;
            }
          } else {
            first = false;
          }
          var elt = void 0;
          if (allowEmpty && this.type === types$13.comma) {
            elt = null;
          } else if (this.type === types$13.ellipsis) {
            elt = this.parseSpread(refDestructuringErrors);
            if (refDestructuringErrors && this.type === types$13.comma && refDestructuringErrors.trailingComma < 0) {
              refDestructuringErrors.trailingComma = this.start;
            }
          } else {
            elt = this.parseMaybeAssign(false, refDestructuringErrors);
          }
          elts.push(elt);
        }
        return elts;
      };
      pp$53.checkUnreserved = function(ref4) {
        var start = ref4.start;
        var end = ref4.end;
        var name2 = ref4.name;
        if (this.inGenerator && name2 === "yield") {
          this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator");
        }
        if (this.inAsync && name2 === "await") {
          this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function");
        }
        if (!(this.currentThisScope().flags & SCOPE_VAR3) && name2 === "arguments") {
          this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer");
        }
        if (this.inClassStaticBlock && (name2 === "arguments" || name2 === "await")) {
          this.raise(start, "Cannot use " + name2 + " in class static initialization block");
        }
        if (this.keywords.test(name2)) {
          this.raise(start, "Unexpected keyword '" + name2 + "'");
        }
        if (this.options.ecmaVersion < 6 && this.input.slice(start, end).indexOf("\\") !== -1) {
          return;
        }
        var re3 = this.strict ? this.reservedWordsStrict : this.reservedWords;
        if (re3.test(name2)) {
          if (!this.inAsync && name2 === "await") {
            this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function");
          }
          this.raiseRecoverable(start, "The keyword '" + name2 + "' is reserved");
        }
      };
      pp$53.parseIdent = function(liberal) {
        var node = this.parseIdentNode();
        this.next(!!liberal);
        this.finishNode(node, "Identifier");
        if (!liberal) {
          this.checkUnreserved(node);
          if (node.name === "await" && !this.awaitIdentPos) {
            this.awaitIdentPos = node.start;
          }
        }
        return node;
      };
      pp$53.parseIdentNode = function() {
        var node = this.startNode();
        if (this.type === types$13.name) {
          node.name = this.value;
        } else if (this.type.keyword) {
          node.name = this.type.keyword;
          if ((node.name === "class" || node.name === "function") && (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
            this.context.pop();
          }
          this.type = types$13.name;
        } else {
          this.unexpected();
        }
        return node;
      };
      pp$53.parsePrivateIdent = function() {
        var node = this.startNode();
        if (this.type === types$13.privateId) {
          node.name = this.value;
        } else {
          this.unexpected();
        }
        this.next();
        this.finishNode(node, "PrivateIdentifier");
        if (this.options.checkPrivateFields) {
          if (this.privateNameStack.length === 0) {
            this.raise(node.start, "Private field '#" + node.name + "' must be declared in an enclosing class");
          } else {
            this.privateNameStack[this.privateNameStack.length - 1].used.push(node);
          }
        }
        return node;
      };
      pp$53.parseYield = function(forInit) {
        if (!this.yieldPos) {
          this.yieldPos = this.start;
        }
        var node = this.startNode();
        this.next();
        if (this.type === types$13.semi || this.canInsertSemicolon() || this.type !== types$13.star && !this.type.startsExpr) {
          node.delegate = false;
          node.argument = null;
        } else {
          node.delegate = this.eat(types$13.star);
          node.argument = this.parseMaybeAssign(forInit);
        }
        return this.finishNode(node, "YieldExpression");
      };
      pp$53.parseAwait = function(forInit) {
        if (!this.awaitPos) {
          this.awaitPos = this.start;
        }
        var node = this.startNode();
        this.next();
        node.argument = this.parseMaybeUnary(null, true, false, forInit);
        return this.finishNode(node, "AwaitExpression");
      };
      var pp$43 = Parser6.prototype;
      pp$43.raise = function(pos, message) {
        var loc = getLineInfo3(this.input, pos);
        message += " (" + loc.line + ":" + loc.column + ")";
        if (this.sourceFile) {
          message += " in " + this.sourceFile;
        }
        var err2 = new SyntaxError(message);
        err2.pos = pos;
        err2.loc = loc;
        err2.raisedAt = this.pos;
        throw err2;
      };
      pp$43.raiseRecoverable = pp$43.raise;
      pp$43.curPosition = function() {
        if (this.options.locations) {
          return new Position4(this.curLine, this.pos - this.lineStart);
        }
      };
      var pp$33 = Parser6.prototype;
      var Scope4 = function Scope5(flags) {
        this.flags = flags;
        this.var = [];
        this.lexical = [];
        this.functions = [];
      };
      pp$33.enterScope = function(flags) {
        this.scopeStack.push(new Scope4(flags));
      };
      pp$33.exitScope = function() {
        this.scopeStack.pop();
      };
      pp$33.treatFunctionsAsVarInScope = function(scope) {
        return scope.flags & SCOPE_FUNCTION4 || !this.inModule && scope.flags & SCOPE_TOP3;
      };
      pp$33.declareName = function(name2, bindingType, pos) {
        var redeclared = false;
        if (bindingType === BIND_LEXICAL3) {
          var scope = this.currentScope();
          redeclared = scope.lexical.indexOf(name2) > -1 || scope.functions.indexOf(name2) > -1 || scope.var.indexOf(name2) > -1;
          scope.lexical.push(name2);
          if (this.inModule && scope.flags & SCOPE_TOP3) {
            delete this.undefinedExports[name2];
          }
        } else if (bindingType === BIND_SIMPLE_CATCH3) {
          var scope$1 = this.currentScope();
          scope$1.lexical.push(name2);
        } else if (bindingType === BIND_FUNCTION3) {
          var scope$2 = this.currentScope();
          if (this.treatFunctionsAsVar) {
            redeclared = scope$2.lexical.indexOf(name2) > -1;
          } else {
            redeclared = scope$2.lexical.indexOf(name2) > -1 || scope$2.var.indexOf(name2) > -1;
          }
          scope$2.functions.push(name2);
        } else {
          for (var i7 = this.scopeStack.length - 1; i7 >= 0; --i7) {
            var scope$3 = this.scopeStack[i7];
            if (scope$3.lexical.indexOf(name2) > -1 && !(scope$3.flags & SCOPE_SIMPLE_CATCH3 && scope$3.lexical[0] === name2) || !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name2) > -1) {
              redeclared = true;
              break;
            }
            scope$3.var.push(name2);
            if (this.inModule && scope$3.flags & SCOPE_TOP3) {
              delete this.undefinedExports[name2];
            }
            if (scope$3.flags & SCOPE_VAR3) {
              break;
            }
          }
        }
        if (redeclared) {
          this.raiseRecoverable(pos, "Identifier '" + name2 + "' has already been declared");
        }
      };
      pp$33.checkLocalExport = function(id) {
        if (this.scopeStack[0].lexical.indexOf(id.name) === -1 && this.scopeStack[0].var.indexOf(id.name) === -1) {
          this.undefinedExports[id.name] = id;
        }
      };
      pp$33.currentScope = function() {
        return this.scopeStack[this.scopeStack.length - 1];
      };
      pp$33.currentVarScope = function() {
        for (var i7 = this.scopeStack.length - 1; ; i7--) {
          var scope = this.scopeStack[i7];
          if (scope.flags & (SCOPE_VAR3 | SCOPE_CLASS_FIELD_INIT | SCOPE_CLASS_STATIC_BLOCK)) {
            return scope;
          }
        }
      };
      pp$33.currentThisScope = function() {
        for (var i7 = this.scopeStack.length - 1; ; i7--) {
          var scope = this.scopeStack[i7];
          if (scope.flags & (SCOPE_VAR3 | SCOPE_CLASS_FIELD_INIT | SCOPE_CLASS_STATIC_BLOCK) && !(scope.flags & SCOPE_ARROW3)) {
            return scope;
          }
        }
      };
      var Node7 = function Node8(parser, pos, loc) {
        this.type = "";
        this.start = pos;
        this.end = 0;
        if (parser.options.locations) {
          this.loc = new SourceLocation4(parser, loc);
        }
        if (parser.options.directSourceFile) {
          this.sourceFile = parser.options.directSourceFile;
        }
        if (parser.options.ranges) {
          this.range = [pos, 0];
        }
      };
      var pp$23 = Parser6.prototype;
      pp$23.startNode = function() {
        return new Node7(this, this.start, this.startLoc);
      };
      pp$23.startNodeAt = function(pos, loc) {
        return new Node7(this, pos, loc);
      };
      function finishNodeAt3(node, type4, pos, loc) {
        node.type = type4;
        node.end = pos;
        if (this.options.locations) {
          node.loc.end = loc;
        }
        if (this.options.ranges) {
          node.range[1] = pos;
        }
        return node;
      }
      pp$23.finishNode = function(node, type4) {
        return finishNodeAt3.call(this, node, type4, this.lastTokEnd, this.lastTokEndLoc);
      };
      pp$23.finishNodeAt = function(node, type4, pos, loc) {
        return finishNodeAt3.call(this, node, type4, pos, loc);
      };
      pp$23.copyNode = function(node) {
        var newNode = new Node7(this, node.start, this.startLoc);
        for (var prop in node) {
          newNode[prop] = node[prop];
        }
        return newNode;
      };
      var scriptValuesAddedInUnicode = "Berf Beria_Erfe Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sidetic Sidt Sunu Sunuwar Tai_Yo Tayo Todhri Todr Tolong_Siki Tols Tulu_Tigalari Tutg Unknown Zzzz";
      var ecma9BinaryProperties3 = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";
      var ecma10BinaryProperties3 = ecma9BinaryProperties3 + " Extended_Pictographic";
      var ecma11BinaryProperties3 = ecma10BinaryProperties3;
      var ecma12BinaryProperties2 = ecma11BinaryProperties3 + " EBase EComp EMod EPres ExtPict";
      var ecma13BinaryProperties = ecma12BinaryProperties2;
      var ecma14BinaryProperties = ecma13BinaryProperties;
      var unicodeBinaryProperties3 = {
        9: ecma9BinaryProperties3,
        10: ecma10BinaryProperties3,
        11: ecma11BinaryProperties3,
        12: ecma12BinaryProperties2,
        13: ecma13BinaryProperties,
        14: ecma14BinaryProperties
      };
      var ecma14BinaryPropertiesOfStrings = "Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji";
      var unicodeBinaryPropertiesOfStrings = {
        9: "",
        10: "",
        11: "",
        12: "",
        13: "",
        14: ecma14BinaryPropertiesOfStrings
      };
      var unicodeGeneralCategoryValues3 = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu";
      var ecma9ScriptValues3 = "Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb";
      var ecma10ScriptValues3 = ecma9ScriptValues3 + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
      var ecma11ScriptValues3 = ecma10ScriptValues3 + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
      var ecma12ScriptValues2 = ecma11ScriptValues3 + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";
      var ecma13ScriptValues = ecma12ScriptValues2 + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith";
      var ecma14ScriptValues = ecma13ScriptValues + " " + scriptValuesAddedInUnicode;
      var unicodeScriptValues3 = {
        9: ecma9ScriptValues3,
        10: ecma10ScriptValues3,
        11: ecma11ScriptValues3,
        12: ecma12ScriptValues2,
        13: ecma13ScriptValues,
        14: ecma14ScriptValues
      };
      var data3 = {};
      function buildUnicodeData3(ecmaVersion2) {
        var d4 = data3[ecmaVersion2] = {
          binary: wordsRegexp3(unicodeBinaryProperties3[ecmaVersion2] + " " + unicodeGeneralCategoryValues3),
          binaryOfStrings: wordsRegexp3(unicodeBinaryPropertiesOfStrings[ecmaVersion2]),
          nonBinary: {
            General_Category: wordsRegexp3(unicodeGeneralCategoryValues3),
            Script: wordsRegexp3(unicodeScriptValues3[ecmaVersion2])
          }
        };
        d4.nonBinary.Script_Extensions = d4.nonBinary.Script;
        d4.nonBinary.gc = d4.nonBinary.General_Category;
        d4.nonBinary.sc = d4.nonBinary.Script;
        d4.nonBinary.scx = d4.nonBinary.Script_Extensions;
      }
      for (var i6 = 0, list = [9, 10, 11, 12, 13, 14]; i6 < list.length; i6 += 1) {
        var ecmaVersion = list[i6];
        buildUnicodeData3(ecmaVersion);
      }
      var pp$13 = Parser6.prototype;
      var BranchID = function BranchID2(parent, base3) {
        this.parent = parent;
        this.base = base3 || this;
      };
      BranchID.prototype.separatedFrom = function separatedFrom(alt) {
        for (var self2 = this; self2; self2 = self2.parent) {
          for (var other = alt; other; other = other.parent) {
            if (self2.base === other.base && self2 !== other) {
              return true;
            }
          }
        }
        return false;
      };
      BranchID.prototype.sibling = function sibling() {
        return new BranchID(this.parent, this.base);
      };
      var RegExpValidationState4 = function RegExpValidationState5(parser) {
        this.parser = parser;
        this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "") + (parser.options.ecmaVersion >= 15 ? "v" : "");
        this.unicodeProperties = data3[parser.options.ecmaVersion >= 14 ? 14 : parser.options.ecmaVersion];
        this.source = "";
        this.flags = "";
        this.start = 0;
        this.switchU = false;
        this.switchV = false;
        this.switchN = false;
        this.pos = 0;
        this.lastIntValue = 0;
        this.lastStringValue = "";
        this.lastAssertionIsQuantifiable = false;
        this.numCapturingParens = 0;
        this.maxBackReference = 0;
        this.groupNames = /* @__PURE__ */ Object.create(null);
        this.backReferenceNames = [];
        this.branchID = null;
      };
      RegExpValidationState4.prototype.reset = function reset4(start, pattern, flags) {
        var unicodeSets = flags.indexOf("v") !== -1;
        var unicode = flags.indexOf("u") !== -1;
        this.start = start | 0;
        this.source = pattern + "";
        this.flags = flags;
        if (unicodeSets && this.parser.options.ecmaVersion >= 15) {
          this.switchU = true;
          this.switchV = true;
          this.switchN = true;
        } else {
          this.switchU = unicode && this.parser.options.ecmaVersion >= 6;
          this.switchV = false;
          this.switchN = unicode && this.parser.options.ecmaVersion >= 9;
        }
      };
      RegExpValidationState4.prototype.raise = function raise3(message) {
        this.parser.raiseRecoverable(this.start, "Invalid regular expression: /" + this.source + "/: " + message);
      };
      RegExpValidationState4.prototype.at = function at3(i7, forceU) {
        if (forceU === void 0) forceU = false;
        var s5 = this.source;
        var l6 = s5.length;
        if (i7 >= l6) {
          return -1;
        }
        var c6 = s5.charCodeAt(i7);
        if (!(forceU || this.switchU) || c6 <= 55295 || c6 >= 57344 || i7 + 1 >= l6) {
          return c6;
        }
        var next = s5.charCodeAt(i7 + 1);
        return next >= 56320 && next <= 57343 ? (c6 << 10) + next - 56613888 : c6;
      };
      RegExpValidationState4.prototype.nextIndex = function nextIndex3(i7, forceU) {
        if (forceU === void 0) forceU = false;
        var s5 = this.source;
        var l6 = s5.length;
        if (i7 >= l6) {
          return l6;
        }
        var c6 = s5.charCodeAt(i7), next;
        if (!(forceU || this.switchU) || c6 <= 55295 || c6 >= 57344 || i7 + 1 >= l6 || (next = s5.charCodeAt(i7 + 1)) < 56320 || next > 57343) {
          return i7 + 1;
        }
        return i7 + 2;
      };
      RegExpValidationState4.prototype.current = function current3(forceU) {
        if (forceU === void 0) forceU = false;
        return this.at(this.pos, forceU);
      };
      RegExpValidationState4.prototype.lookahead = function lookahead3(forceU) {
        if (forceU === void 0) forceU = false;
        return this.at(this.nextIndex(this.pos, forceU), forceU);
      };
      RegExpValidationState4.prototype.advance = function advance3(forceU) {
        if (forceU === void 0) forceU = false;
        this.pos = this.nextIndex(this.pos, forceU);
      };
      RegExpValidationState4.prototype.eat = function eat3(ch, forceU) {
        if (forceU === void 0) forceU = false;
        if (this.current(forceU) === ch) {
          this.advance(forceU);
          return true;
        }
        return false;
      };
      RegExpValidationState4.prototype.eatChars = function eatChars(chs, forceU) {
        if (forceU === void 0) forceU = false;
        var pos = this.pos;
        for (var i7 = 0, list2 = chs; i7 < list2.length; i7 += 1) {
          var ch = list2[i7];
          var current3 = this.at(pos, forceU);
          if (current3 === -1 || current3 !== ch) {
            return false;
          }
          pos = this.nextIndex(pos, forceU);
        }
        this.pos = pos;
        return true;
      };
      pp$13.validateRegExpFlags = function(state2) {
        var validFlags = state2.validFlags;
        var flags = state2.flags;
        var u5 = false;
        var v4 = false;
        for (var i7 = 0; i7 < flags.length; i7++) {
          var flag = flags.charAt(i7);
          if (validFlags.indexOf(flag) === -1) {
            this.raise(state2.start, "Invalid regular expression flag");
          }
          if (flags.indexOf(flag, i7 + 1) > -1) {
            this.raise(state2.start, "Duplicate regular expression flag");
          }
          if (flag === "u") {
            u5 = true;
          }
          if (flag === "v") {
            v4 = true;
          }
        }
        if (this.options.ecmaVersion >= 15 && u5 && v4) {
          this.raise(state2.start, "Invalid regular expression flag");
        }
      };
      function hasProp(obj) {
        for (var _3 in obj) {
          return true;
        }
        return false;
      }
      pp$13.validateRegExpPattern = function(state2) {
        this.regexp_pattern(state2);
        if (!state2.switchN && this.options.ecmaVersion >= 9 && hasProp(state2.groupNames)) {
          state2.switchN = true;
          this.regexp_pattern(state2);
        }
      };
      pp$13.regexp_pattern = function(state2) {
        state2.pos = 0;
        state2.lastIntValue = 0;
        state2.lastStringValue = "";
        state2.lastAssertionIsQuantifiable = false;
        state2.numCapturingParens = 0;
        state2.maxBackReference = 0;
        state2.groupNames = /* @__PURE__ */ Object.create(null);
        state2.backReferenceNames.length = 0;
        state2.branchID = null;
        this.regexp_disjunction(state2);
        if (state2.pos !== state2.source.length) {
          if (state2.eat(
            41
            /* ) */
          )) {
            state2.raise("Unmatched ')'");
          }
          if (state2.eat(
            93
            /* ] */
          ) || state2.eat(
            125
            /* } */
          )) {
            state2.raise("Lone quantifier brackets");
          }
        }
        if (state2.maxBackReference > state2.numCapturingParens) {
          state2.raise("Invalid escape");
        }
        for (var i7 = 0, list2 = state2.backReferenceNames; i7 < list2.length; i7 += 1) {
          var name2 = list2[i7];
          if (!state2.groupNames[name2]) {
            state2.raise("Invalid named capture referenced");
          }
        }
      };
      pp$13.regexp_disjunction = function(state2) {
        var trackDisjunction = this.options.ecmaVersion >= 16;
        if (trackDisjunction) {
          state2.branchID = new BranchID(state2.branchID, null);
        }
        this.regexp_alternative(state2);
        while (state2.eat(
          124
          /* | */
        )) {
          if (trackDisjunction) {
            state2.branchID = state2.branchID.sibling();
          }
          this.regexp_alternative(state2);
        }
        if (trackDisjunction) {
          state2.branchID = state2.branchID.parent;
        }
        if (this.regexp_eatQuantifier(state2, true)) {
          state2.raise("Nothing to repeat");
        }
        if (state2.eat(
          123
          /* { */
        )) {
          state2.raise("Lone quantifier brackets");
        }
      };
      pp$13.regexp_alternative = function(state2) {
        while (state2.pos < state2.source.length && this.regexp_eatTerm(state2)) {
        }
      };
      pp$13.regexp_eatTerm = function(state2) {
        if (this.regexp_eatAssertion(state2)) {
          if (state2.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state2)) {
            if (state2.switchU) {
              state2.raise("Invalid quantifier");
            }
          }
          return true;
        }
        if (state2.switchU ? this.regexp_eatAtom(state2) : this.regexp_eatExtendedAtom(state2)) {
          this.regexp_eatQuantifier(state2);
          return true;
        }
        return false;
      };
      pp$13.regexp_eatAssertion = function(state2) {
        var start = state2.pos;
        state2.lastAssertionIsQuantifiable = false;
        if (state2.eat(
          94
          /* ^ */
        ) || state2.eat(
          36
          /* $ */
        )) {
          return true;
        }
        if (state2.eat(
          92
          /* \ */
        )) {
          if (state2.eat(
            66
            /* B */
          ) || state2.eat(
            98
            /* b */
          )) {
            return true;
          }
          state2.pos = start;
        }
        if (state2.eat(
          40
          /* ( */
        ) && state2.eat(
          63
          /* ? */
        )) {
          var lookbehind = false;
          if (this.options.ecmaVersion >= 9) {
            lookbehind = state2.eat(
              60
              /* < */
            );
          }
          if (state2.eat(
            61
            /* = */
          ) || state2.eat(
            33
            /* ! */
          )) {
            this.regexp_disjunction(state2);
            if (!state2.eat(
              41
              /* ) */
            )) {
              state2.raise("Unterminated group");
            }
            state2.lastAssertionIsQuantifiable = !lookbehind;
            return true;
          }
        }
        state2.pos = start;
        return false;
      };
      pp$13.regexp_eatQuantifier = function(state2, noError) {
        if (noError === void 0) noError = false;
        if (this.regexp_eatQuantifierPrefix(state2, noError)) {
          state2.eat(
            63
            /* ? */
          );
          return true;
        }
        return false;
      };
      pp$13.regexp_eatQuantifierPrefix = function(state2, noError) {
        return state2.eat(
          42
          /* * */
        ) || state2.eat(
          43
          /* + */
        ) || state2.eat(
          63
          /* ? */
        ) || this.regexp_eatBracedQuantifier(state2, noError);
      };
      pp$13.regexp_eatBracedQuantifier = function(state2, noError) {
        var start = state2.pos;
        if (state2.eat(
          123
          /* { */
        )) {
          var min2 = 0, max = -1;
          if (this.regexp_eatDecimalDigits(state2)) {
            min2 = state2.lastIntValue;
            if (state2.eat(
              44
              /* , */
            ) && this.regexp_eatDecimalDigits(state2)) {
              max = state2.lastIntValue;
            }
            if (state2.eat(
              125
              /* } */
            )) {
              if (max !== -1 && max < min2 && !noError) {
                state2.raise("numbers out of order in {} quantifier");
              }
              return true;
            }
          }
          if (state2.switchU && !noError) {
            state2.raise("Incomplete quantifier");
          }
          state2.pos = start;
        }
        return false;
      };
      pp$13.regexp_eatAtom = function(state2) {
        return this.regexp_eatPatternCharacters(state2) || state2.eat(
          46
          /* . */
        ) || this.regexp_eatReverseSolidusAtomEscape(state2) || this.regexp_eatCharacterClass(state2) || this.regexp_eatUncapturingGroup(state2) || this.regexp_eatCapturingGroup(state2);
      };
      pp$13.regexp_eatReverseSolidusAtomEscape = function(state2) {
        var start = state2.pos;
        if (state2.eat(
          92
          /* \ */
        )) {
          if (this.regexp_eatAtomEscape(state2)) {
            return true;
          }
          state2.pos = start;
        }
        return false;
      };
      pp$13.regexp_eatUncapturingGroup = function(state2) {
        var start = state2.pos;
        if (state2.eat(
          40
          /* ( */
        )) {
          if (state2.eat(
            63
            /* ? */
          )) {
            if (this.options.ecmaVersion >= 16) {
              var addModifiers = this.regexp_eatModifiers(state2);
              var hasHyphen = state2.eat(
                45
                /* - */
              );
              if (addModifiers || hasHyphen) {
                for (var i7 = 0; i7 < addModifiers.length; i7++) {
                  var modifier = addModifiers.charAt(i7);
                  if (addModifiers.indexOf(modifier, i7 + 1) > -1) {
                    state2.raise("Duplicate regular expression modifiers");
                  }
                }
                if (hasHyphen) {
                  var removeModifiers = this.regexp_eatModifiers(state2);
                  if (!addModifiers && !removeModifiers && state2.current() === 58) {
                    state2.raise("Invalid regular expression modifiers");
                  }
                  for (var i$13 = 0; i$13 < removeModifiers.length; i$13++) {
                    var modifier$1 = removeModifiers.charAt(i$13);
                    if (removeModifiers.indexOf(modifier$1, i$13 + 1) > -1 || addModifiers.indexOf(modifier$1) > -1) {
                      state2.raise("Duplicate regular expression modifiers");
                    }
                  }
                }
              }
            }
            if (state2.eat(
              58
              /* : */
            )) {
              this.regexp_disjunction(state2);
              if (state2.eat(
                41
                /* ) */
              )) {
                return true;
              }
              state2.raise("Unterminated group");
            }
          }
          state2.pos = start;
        }
        return false;
      };
      pp$13.regexp_eatCapturingGroup = function(state2) {
        if (state2.eat(
          40
          /* ( */
        )) {
          if (this.options.ecmaVersion >= 9) {
            this.regexp_groupSpecifier(state2);
          } else if (state2.current() === 63) {
            state2.raise("Invalid group");
          }
          this.regexp_disjunction(state2);
          if (state2.eat(
            41
            /* ) */
          )) {
            state2.numCapturingParens += 1;
            return true;
          }
          state2.raise("Unterminated group");
        }
        return false;
      };
      pp$13.regexp_eatModifiers = function(state2) {
        var modifiers = "";
        var ch = 0;
        while ((ch = state2.current()) !== -1 && isRegularExpressionModifier(ch)) {
          modifiers += codePointToString3(ch);
          state2.advance();
        }
        return modifiers;
      };
      function isRegularExpressionModifier(ch) {
        return ch === 105 || ch === 109 || ch === 115;
      }
      pp$13.regexp_eatExtendedAtom = function(state2) {
        return state2.eat(
          46
          /* . */
        ) || this.regexp_eatReverseSolidusAtomEscape(state2) || this.regexp_eatCharacterClass(state2) || this.regexp_eatUncapturingGroup(state2) || this.regexp_eatCapturingGroup(state2) || this.regexp_eatInvalidBracedQuantifier(state2) || this.regexp_eatExtendedPatternCharacter(state2);
      };
      pp$13.regexp_eatInvalidBracedQuantifier = function(state2) {
        if (this.regexp_eatBracedQuantifier(state2, true)) {
          state2.raise("Nothing to repeat");
        }
        return false;
      };
      pp$13.regexp_eatSyntaxCharacter = function(state2) {
        var ch = state2.current();
        if (isSyntaxCharacter3(ch)) {
          state2.lastIntValue = ch;
          state2.advance();
          return true;
        }
        return false;
      };
      function isSyntaxCharacter3(ch) {
        return ch === 36 || ch >= 40 && ch <= 43 || ch === 46 || ch === 63 || ch >= 91 && ch <= 94 || ch >= 123 && ch <= 125;
      }
      pp$13.regexp_eatPatternCharacters = function(state2) {
        var start = state2.pos;
        var ch = 0;
        while ((ch = state2.current()) !== -1 && !isSyntaxCharacter3(ch)) {
          state2.advance();
        }
        return state2.pos !== start;
      };
      pp$13.regexp_eatExtendedPatternCharacter = function(state2) {
        var ch = state2.current();
        if (ch !== -1 && ch !== 36 && !(ch >= 40 && ch <= 43) && ch !== 46 && ch !== 63 && ch !== 91 && ch !== 94 && ch !== 124) {
          state2.advance();
          return true;
        }
        return false;
      };
      pp$13.regexp_groupSpecifier = function(state2) {
        if (state2.eat(
          63
          /* ? */
        )) {
          if (!this.regexp_eatGroupName(state2)) {
            state2.raise("Invalid group");
          }
          var trackDisjunction = this.options.ecmaVersion >= 16;
          var known = state2.groupNames[state2.lastStringValue];
          if (known) {
            if (trackDisjunction) {
              for (var i7 = 0, list2 = known; i7 < list2.length; i7 += 1) {
                var altID = list2[i7];
                if (!altID.separatedFrom(state2.branchID)) {
                  state2.raise("Duplicate capture group name");
                }
              }
            } else {
              state2.raise("Duplicate capture group name");
            }
          }
          if (trackDisjunction) {
            (known || (state2.groupNames[state2.lastStringValue] = [])).push(state2.branchID);
          } else {
            state2.groupNames[state2.lastStringValue] = true;
          }
        }
      };
      pp$13.regexp_eatGroupName = function(state2) {
        state2.lastStringValue = "";
        if (state2.eat(
          60
          /* < */
        )) {
          if (this.regexp_eatRegExpIdentifierName(state2) && state2.eat(
            62
            /* > */
          )) {
            return true;
          }
          state2.raise("Invalid capture group name");
        }
        return false;
      };
      pp$13.regexp_eatRegExpIdentifierName = function(state2) {
        state2.lastStringValue = "";
        if (this.regexp_eatRegExpIdentifierStart(state2)) {
          state2.lastStringValue += codePointToString3(state2.lastIntValue);
          while (this.regexp_eatRegExpIdentifierPart(state2)) {
            state2.lastStringValue += codePointToString3(state2.lastIntValue);
          }
          return true;
        }
        return false;
      };
      pp$13.regexp_eatRegExpIdentifierStart = function(state2) {
        var start = state2.pos;
        var forceU = this.options.ecmaVersion >= 11;
        var ch = state2.current(forceU);
        state2.advance(forceU);
        if (ch === 92 && this.regexp_eatRegExpUnicodeEscapeSequence(state2, forceU)) {
          ch = state2.lastIntValue;
        }
        if (isRegExpIdentifierStart3(ch)) {
          state2.lastIntValue = ch;
          return true;
        }
        state2.pos = start;
        return false;
      };
      function isRegExpIdentifierStart3(ch) {
        return isIdentifierStart3(ch, true) || ch === 36 || ch === 95;
      }
      pp$13.regexp_eatRegExpIdentifierPart = function(state2) {
        var start = state2.pos;
        var forceU = this.options.ecmaVersion >= 11;
        var ch = state2.current(forceU);
        state2.advance(forceU);
        if (ch === 92 && this.regexp_eatRegExpUnicodeEscapeSequence(state2, forceU)) {
          ch = state2.lastIntValue;
        }
        if (isRegExpIdentifierPart3(ch)) {
          state2.lastIntValue = ch;
          return true;
        }
        state2.pos = start;
        return false;
      };
      function isRegExpIdentifierPart3(ch) {
        return isIdentifierChar3(ch, true) || ch === 36 || ch === 95 || ch === 8204 || ch === 8205;
      }
      pp$13.regexp_eatAtomEscape = function(state2) {
        if (this.regexp_eatBackReference(state2) || this.regexp_eatCharacterClassEscape(state2) || this.regexp_eatCharacterEscape(state2) || state2.switchN && this.regexp_eatKGroupName(state2)) {
          return true;
        }
        if (state2.switchU) {
          if (state2.current() === 99) {
            state2.raise("Invalid unicode escape");
          }
          state2.raise("Invalid escape");
        }
        return false;
      };
      pp$13.regexp_eatBackReference = function(state2) {
        var start = state2.pos;
        if (this.regexp_eatDecimalEscape(state2)) {
          var n5 = state2.lastIntValue;
          if (state2.switchU) {
            if (n5 > state2.maxBackReference) {
              state2.maxBackReference = n5;
            }
            return true;
          }
          if (n5 <= state2.numCapturingParens) {
            return true;
          }
          state2.pos = start;
        }
        return false;
      };
      pp$13.regexp_eatKGroupName = function(state2) {
        if (state2.eat(
          107
          /* k */
        )) {
          if (this.regexp_eatGroupName(state2)) {
            state2.backReferenceNames.push(state2.lastStringValue);
            return true;
          }
          state2.raise("Invalid named reference");
        }
        return false;
      };
      pp$13.regexp_eatCharacterEscape = function(state2) {
        return this.regexp_eatControlEscape(state2) || this.regexp_eatCControlLetter(state2) || this.regexp_eatZero(state2) || this.regexp_eatHexEscapeSequence(state2) || this.regexp_eatRegExpUnicodeEscapeSequence(state2, false) || !state2.switchU && this.regexp_eatLegacyOctalEscapeSequence(state2) || this.regexp_eatIdentityEscape(state2);
      };
      pp$13.regexp_eatCControlLetter = function(state2) {
        var start = state2.pos;
        if (state2.eat(
          99
          /* c */
        )) {
          if (this.regexp_eatControlLetter(state2)) {
            return true;
          }
          state2.pos = start;
        }
        return false;
      };
      pp$13.regexp_eatZero = function(state2) {
        if (state2.current() === 48 && !isDecimalDigit3(state2.lookahead())) {
          state2.lastIntValue = 0;
          state2.advance();
          return true;
        }
        return false;
      };
      pp$13.regexp_eatControlEscape = function(state2) {
        var ch = state2.current();
        if (ch === 116) {
          state2.lastIntValue = 9;
          state2.advance();
          return true;
        }
        if (ch === 110) {
          state2.lastIntValue = 10;
          state2.advance();
          return true;
        }
        if (ch === 118) {
          state2.lastIntValue = 11;
          state2.advance();
          return true;
        }
        if (ch === 102) {
          state2.lastIntValue = 12;
          state2.advance();
          return true;
        }
        if (ch === 114) {
          state2.lastIntValue = 13;
          state2.advance();
          return true;
        }
        return false;
      };
      pp$13.regexp_eatControlLetter = function(state2) {
        var ch = state2.current();
        if (isControlLetter3(ch)) {
          state2.lastIntValue = ch % 32;
          state2.advance();
          return true;
        }
        return false;
      };
      function isControlLetter3(ch) {
        return ch >= 65 && ch <= 90 || ch >= 97 && ch <= 122;
      }
      pp$13.regexp_eatRegExpUnicodeEscapeSequence = function(state2, forceU) {
        if (forceU === void 0) forceU = false;
        var start = state2.pos;
        var switchU = forceU || state2.switchU;
        if (state2.eat(
          117
          /* u */
        )) {
          if (this.regexp_eatFixedHexDigits(state2, 4)) {
            var lead = state2.lastIntValue;
            if (switchU && lead >= 55296 && lead <= 56319) {
              var leadSurrogateEnd = state2.pos;
              if (state2.eat(
                92
                /* \ */
              ) && state2.eat(
                117
                /* u */
              ) && this.regexp_eatFixedHexDigits(state2, 4)) {
                var trail = state2.lastIntValue;
                if (trail >= 56320 && trail <= 57343) {
                  state2.lastIntValue = (lead - 55296) * 1024 + (trail - 56320) + 65536;
                  return true;
                }
              }
              state2.pos = leadSurrogateEnd;
              state2.lastIntValue = lead;
            }
            return true;
          }
          if (switchU && state2.eat(
            123
            /* { */
          ) && this.regexp_eatHexDigits(state2) && state2.eat(
            125
            /* } */
          ) && isValidUnicode3(state2.lastIntValue)) {
            return true;
          }
          if (switchU) {
            state2.raise("Invalid unicode escape");
          }
          state2.pos = start;
        }
        return false;
      };
      function isValidUnicode3(ch) {
        return ch >= 0 && ch <= 1114111;
      }
      pp$13.regexp_eatIdentityEscape = function(state2) {
        if (state2.switchU) {
          if (this.regexp_eatSyntaxCharacter(state2)) {
            return true;
          }
          if (state2.eat(
            47
            /* / */
          )) {
            state2.lastIntValue = 47;
            return true;
          }
          return false;
        }
        var ch = state2.current();
        if (ch !== 99 && (!state2.switchN || ch !== 107)) {
          state2.lastIntValue = ch;
          state2.advance();
          return true;
        }
        return false;
      };
      pp$13.regexp_eatDecimalEscape = function(state2) {
        state2.lastIntValue = 0;
        var ch = state2.current();
        if (ch >= 49 && ch <= 57) {
          do {
            state2.lastIntValue = 10 * state2.lastIntValue + (ch - 48);
            state2.advance();
          } while ((ch = state2.current()) >= 48 && ch <= 57);
          return true;
        }
        return false;
      };
      var CharSetNone = 0;
      var CharSetOk = 1;
      var CharSetString = 2;
      pp$13.regexp_eatCharacterClassEscape = function(state2) {
        var ch = state2.current();
        if (isCharacterClassEscape3(ch)) {
          state2.lastIntValue = -1;
          state2.advance();
          return CharSetOk;
        }
        var negate = false;
        if (state2.switchU && this.options.ecmaVersion >= 9 && ((negate = ch === 80) || ch === 112)) {
          state2.lastIntValue = -1;
          state2.advance();
          var result2;
          if (state2.eat(
            123
            /* { */
          ) && (result2 = this.regexp_eatUnicodePropertyValueExpression(state2)) && state2.eat(
            125
            /* } */
          )) {
            if (negate && result2 === CharSetString) {
              state2.raise("Invalid property name");
            }
            return result2;
          }
          state2.raise("Invalid property name");
        }
        return CharSetNone;
      };
      function isCharacterClassEscape3(ch) {
        return ch === 100 || ch === 68 || ch === 115 || ch === 83 || ch === 119 || ch === 87;
      }
      pp$13.regexp_eatUnicodePropertyValueExpression = function(state2) {
        var start = state2.pos;
        if (this.regexp_eatUnicodePropertyName(state2) && state2.eat(
          61
          /* = */
        )) {
          var name2 = state2.lastStringValue;
          if (this.regexp_eatUnicodePropertyValue(state2)) {
            var value = state2.lastStringValue;
            this.regexp_validateUnicodePropertyNameAndValue(state2, name2, value);
            return CharSetOk;
          }
        }
        state2.pos = start;
        if (this.regexp_eatLoneUnicodePropertyNameOrValue(state2)) {
          var nameOrValue = state2.lastStringValue;
          return this.regexp_validateUnicodePropertyNameOrValue(state2, nameOrValue);
        }
        return CharSetNone;
      };
      pp$13.regexp_validateUnicodePropertyNameAndValue = function(state2, name2, value) {
        if (!hasOwn2(state2.unicodeProperties.nonBinary, name2)) {
          state2.raise("Invalid property name");
        }
        if (!state2.unicodeProperties.nonBinary[name2].test(value)) {
          state2.raise("Invalid property value");
        }
      };
      pp$13.regexp_validateUnicodePropertyNameOrValue = function(state2, nameOrValue) {
        if (state2.unicodeProperties.binary.test(nameOrValue)) {
          return CharSetOk;
        }
        if (state2.switchV && state2.unicodeProperties.binaryOfStrings.test(nameOrValue)) {
          return CharSetString;
        }
        state2.raise("Invalid property name");
      };
      pp$13.regexp_eatUnicodePropertyName = function(state2) {
        var ch = 0;
        state2.lastStringValue = "";
        while (isUnicodePropertyNameCharacter3(ch = state2.current())) {
          state2.lastStringValue += codePointToString3(ch);
          state2.advance();
        }
        return state2.lastStringValue !== "";
      };
      function isUnicodePropertyNameCharacter3(ch) {
        return isControlLetter3(ch) || ch === 95;
      }
      pp$13.regexp_eatUnicodePropertyValue = function(state2) {
        var ch = 0;
        state2.lastStringValue = "";
        while (isUnicodePropertyValueCharacter3(ch = state2.current())) {
          state2.lastStringValue += codePointToString3(ch);
          state2.advance();
        }
        return state2.lastStringValue !== "";
      };
      function isUnicodePropertyValueCharacter3(ch) {
        return isUnicodePropertyNameCharacter3(ch) || isDecimalDigit3(ch);
      }
      pp$13.regexp_eatLoneUnicodePropertyNameOrValue = function(state2) {
        return this.regexp_eatUnicodePropertyValue(state2);
      };
      pp$13.regexp_eatCharacterClass = function(state2) {
        if (state2.eat(
          91
          /* [ */
        )) {
          var negate = state2.eat(
            94
            /* ^ */
          );
          var result2 = this.regexp_classContents(state2);
          if (!state2.eat(
            93
            /* ] */
          )) {
            state2.raise("Unterminated character class");
          }
          if (negate && result2 === CharSetString) {
            state2.raise("Negated character class may contain strings");
          }
          return true;
        }
        return false;
      };
      pp$13.regexp_classContents = function(state2) {
        if (state2.current() === 93) {
          return CharSetOk;
        }
        if (state2.switchV) {
          return this.regexp_classSetExpression(state2);
        }
        this.regexp_nonEmptyClassRanges(state2);
        return CharSetOk;
      };
      pp$13.regexp_nonEmptyClassRanges = function(state2) {
        while (this.regexp_eatClassAtom(state2)) {
          var left = state2.lastIntValue;
          if (state2.eat(
            45
            /* - */
          ) && this.regexp_eatClassAtom(state2)) {
            var right = state2.lastIntValue;
            if (state2.switchU && (left === -1 || right === -1)) {
              state2.raise("Invalid character class");
            }
            if (left !== -1 && right !== -1 && left > right) {
              state2.raise("Range out of order in character class");
            }
          }
        }
      };
      pp$13.regexp_eatClassAtom = function(state2) {
        var start = state2.pos;
        if (state2.eat(
          92
          /* \ */
        )) {
          if (this.regexp_eatClassEscape(state2)) {
            return true;
          }
          if (state2.switchU) {
            var ch$1 = state2.current();
            if (ch$1 === 99 || isOctalDigit3(ch$1)) {
              state2.raise("Invalid class escape");
            }
            state2.raise("Invalid escape");
          }
          state2.pos = start;
        }
        var ch = state2.current();
        if (ch !== 93) {
          state2.lastIntValue = ch;
          state2.advance();
          return true;
        }
        return false;
      };
      pp$13.regexp_eatClassEscape = function(state2) {
        var start = state2.pos;
        if (state2.eat(
          98
          /* b */
        )) {
          state2.lastIntValue = 8;
          return true;
        }
        if (state2.switchU && state2.eat(
          45
          /* - */
        )) {
          state2.lastIntValue = 45;
          return true;
        }
        if (!state2.switchU && state2.eat(
          99
          /* c */
        )) {
          if (this.regexp_eatClassControlLetter(state2)) {
            return true;
          }
          state2.pos = start;
        }
        return this.regexp_eatCharacterClassEscape(state2) || this.regexp_eatCharacterEscape(state2);
      };
      pp$13.regexp_classSetExpression = function(state2) {
        var result2 = CharSetOk, subResult;
        if (this.regexp_eatClassSetRange(state2)) ;
        else if (subResult = this.regexp_eatClassSetOperand(state2)) {
          if (subResult === CharSetString) {
            result2 = CharSetString;
          }
          var start = state2.pos;
          while (state2.eatChars(
            [38, 38]
            /* && */
          )) {
            if (state2.current() !== 38 && (subResult = this.regexp_eatClassSetOperand(state2))) {
              if (subResult !== CharSetString) {
                result2 = CharSetOk;
              }
              continue;
            }
            state2.raise("Invalid character in character class");
          }
          if (start !== state2.pos) {
            return result2;
          }
          while (state2.eatChars(
            [45, 45]
            /* -- */
          )) {
            if (this.regexp_eatClassSetOperand(state2)) {
              continue;
            }
            state2.raise("Invalid character in character class");
          }
          if (start !== state2.pos) {
            return result2;
          }
        } else {
          state2.raise("Invalid character in character class");
        }
        for (; ; ) {
          if (this.regexp_eatClassSetRange(state2)) {
            continue;
          }
          subResult = this.regexp_eatClassSetOperand(state2);
          if (!subResult) {
            return result2;
          }
          if (subResult === CharSetString) {
            result2 = CharSetString;
          }
        }
      };
      pp$13.regexp_eatClassSetRange = function(state2) {
        var start = state2.pos;
        if (this.regexp_eatClassSetCharacter(state2)) {
          var left = state2.lastIntValue;
          if (state2.eat(
            45
            /* - */
          ) && this.regexp_eatClassSetCharacter(state2)) {
            var right = state2.lastIntValue;
            if (left !== -1 && right !== -1 && left > right) {
              state2.raise("Range out of order in character class");
            }
            return true;
          }
          state2.pos = start;
        }
        return false;
      };
      pp$13.regexp_eatClassSetOperand = function(state2) {
        if (this.regexp_eatClassSetCharacter(state2)) {
          return CharSetOk;
        }
        return this.regexp_eatClassStringDisjunction(state2) || this.regexp_eatNestedClass(state2);
      };
      pp$13.regexp_eatNestedClass = function(state2) {
        var start = state2.pos;
        if (state2.eat(
          91
          /* [ */
        )) {
          var negate = state2.eat(
            94
            /* ^ */
          );
          var result2 = this.regexp_classContents(state2);
          if (state2.eat(
            93
            /* ] */
          )) {
            if (negate && result2 === CharSetString) {
              state2.raise("Negated character class may contain strings");
            }
            return result2;
          }
          state2.pos = start;
        }
        if (state2.eat(
          92
          /* \ */
        )) {
          var result$1 = this.regexp_eatCharacterClassEscape(state2);
          if (result$1) {
            return result$1;
          }
          state2.pos = start;
        }
        return null;
      };
      pp$13.regexp_eatClassStringDisjunction = function(state2) {
        var start = state2.pos;
        if (state2.eatChars(
          [92, 113]
          /* \q */
        )) {
          if (state2.eat(
            123
            /* { */
          )) {
            var result2 = this.regexp_classStringDisjunctionContents(state2);
            if (state2.eat(
              125
              /* } */
            )) {
              return result2;
            }
          } else {
            state2.raise("Invalid escape");
          }
          state2.pos = start;
        }
        return null;
      };
      pp$13.regexp_classStringDisjunctionContents = function(state2) {
        var result2 = this.regexp_classString(state2);
        while (state2.eat(
          124
          /* | */
        )) {
          if (this.regexp_classString(state2) === CharSetString) {
            result2 = CharSetString;
          }
        }
        return result2;
      };
      pp$13.regexp_classString = function(state2) {
        var count = 0;
        while (this.regexp_eatClassSetCharacter(state2)) {
          count++;
        }
        return count === 1 ? CharSetOk : CharSetString;
      };
      pp$13.regexp_eatClassSetCharacter = function(state2) {
        var start = state2.pos;
        if (state2.eat(
          92
          /* \ */
        )) {
          if (this.regexp_eatCharacterEscape(state2) || this.regexp_eatClassSetReservedPunctuator(state2)) {
            return true;
          }
          if (state2.eat(
            98
            /* b */
          )) {
            state2.lastIntValue = 8;
            return true;
          }
          state2.pos = start;
          return false;
        }
        var ch = state2.current();
        if (ch < 0 || ch === state2.lookahead() && isClassSetReservedDoublePunctuatorCharacter(ch)) {
          return false;
        }
        if (isClassSetSyntaxCharacter(ch)) {
          return false;
        }
        state2.advance();
        state2.lastIntValue = ch;
        return true;
      };
      function isClassSetReservedDoublePunctuatorCharacter(ch) {
        return ch === 33 || ch >= 35 && ch <= 38 || ch >= 42 && ch <= 44 || ch === 46 || ch >= 58 && ch <= 64 || ch === 94 || ch === 96 || ch === 126;
      }
      function isClassSetSyntaxCharacter(ch) {
        return ch === 40 || ch === 41 || ch === 45 || ch === 47 || ch >= 91 && ch <= 93 || ch >= 123 && ch <= 125;
      }
      pp$13.regexp_eatClassSetReservedPunctuator = function(state2) {
        var ch = state2.current();
        if (isClassSetReservedPunctuator(ch)) {
          state2.lastIntValue = ch;
          state2.advance();
          return true;
        }
        return false;
      };
      function isClassSetReservedPunctuator(ch) {
        return ch === 33 || ch === 35 || ch === 37 || ch === 38 || ch === 44 || ch === 45 || ch >= 58 && ch <= 62 || ch === 64 || ch === 96 || ch === 126;
      }
      pp$13.regexp_eatClassControlLetter = function(state2) {
        var ch = state2.current();
        if (isDecimalDigit3(ch) || ch === 95) {
          state2.lastIntValue = ch % 32;
          state2.advance();
          return true;
        }
        return false;
      };
      pp$13.regexp_eatHexEscapeSequence = function(state2) {
        var start = state2.pos;
        if (state2.eat(
          120
          /* x */
        )) {
          if (this.regexp_eatFixedHexDigits(state2, 2)) {
            return true;
          }
          if (state2.switchU) {
            state2.raise("Invalid escape");
          }
          state2.pos = start;
        }
        return false;
      };
      pp$13.regexp_eatDecimalDigits = function(state2) {
        var start = state2.pos;
        var ch = 0;
        state2.lastIntValue = 0;
        while (isDecimalDigit3(ch = state2.current())) {
          state2.lastIntValue = 10 * state2.lastIntValue + (ch - 48);
          state2.advance();
        }
        return state2.pos !== start;
      };
      function isDecimalDigit3(ch) {
        return ch >= 48 && ch <= 57;
      }
      pp$13.regexp_eatHexDigits = function(state2) {
        var start = state2.pos;
        var ch = 0;
        state2.lastIntValue = 0;
        while (isHexDigit3(ch = state2.current())) {
          state2.lastIntValue = 16 * state2.lastIntValue + hexToInt3(ch);
          state2.advance();
        }
        return state2.pos !== start;
      };
      function isHexDigit3(ch) {
        return ch >= 48 && ch <= 57 || ch >= 65 && ch <= 70 || ch >= 97 && ch <= 102;
      }
      function hexToInt3(ch) {
        if (ch >= 65 && ch <= 70) {
          return 10 + (ch - 65);
        }
        if (ch >= 97 && ch <= 102) {
          return 10 + (ch - 97);
        }
        return ch - 48;
      }
      pp$13.regexp_eatLegacyOctalEscapeSequence = function(state2) {
        if (this.regexp_eatOctalDigit(state2)) {
          var n1 = state2.lastIntValue;
          if (this.regexp_eatOctalDigit(state2)) {
            var n22 = state2.lastIntValue;
            if (n1 <= 3 && this.regexp_eatOctalDigit(state2)) {
              state2.lastIntValue = n1 * 64 + n22 * 8 + state2.lastIntValue;
            } else {
              state2.lastIntValue = n1 * 8 + n22;
            }
          } else {
            state2.lastIntValue = n1;
          }
          return true;
        }
        return false;
      };
      pp$13.regexp_eatOctalDigit = function(state2) {
        var ch = state2.current();
        if (isOctalDigit3(ch)) {
          state2.lastIntValue = ch - 48;
          state2.advance();
          return true;
        }
        state2.lastIntValue = 0;
        return false;
      };
      function isOctalDigit3(ch) {
        return ch >= 48 && ch <= 55;
      }
      pp$13.regexp_eatFixedHexDigits = function(state2, length) {
        var start = state2.pos;
        state2.lastIntValue = 0;
        for (var i7 = 0; i7 < length; ++i7) {
          var ch = state2.current();
          if (!isHexDigit3(ch)) {
            state2.pos = start;
            return false;
          }
          state2.lastIntValue = 16 * state2.lastIntValue + hexToInt3(ch);
          state2.advance();
        }
        return true;
      };
      var Token5 = function Token6(p5) {
        this.type = p5.type;
        this.value = p5.value;
        this.start = p5.start;
        this.end = p5.end;
        if (p5.options.locations) {
          this.loc = new SourceLocation4(p5, p5.startLoc, p5.endLoc);
        }
        if (p5.options.ranges) {
          this.range = [p5.start, p5.end];
        }
      };
      var pp3 = Parser6.prototype;
      pp3.next = function(ignoreEscapeSequenceInKeyword) {
        if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc) {
          this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword);
        }
        if (this.options.onToken) {
          this.options.onToken(new Token5(this));
        }
        this.lastTokEnd = this.end;
        this.lastTokStart = this.start;
        this.lastTokEndLoc = this.endLoc;
        this.lastTokStartLoc = this.startLoc;
        this.nextToken();
      };
      pp3.getToken = function() {
        this.next();
        return new Token5(this);
      };
      if (typeof Symbol !== "undefined") {
        pp3[Symbol.iterator] = function() {
          var this$1$1 = this;
          return {
            next: function() {
              var token = this$1$1.getToken();
              return {
                done: token.type === types$13.eof,
                value: token
              };
            }
          };
        };
      }
      pp3.nextToken = function() {
        var curContext = this.curContext();
        if (!curContext || !curContext.preserveSpace) {
          this.skipSpace();
        }
        this.start = this.pos;
        if (this.options.locations) {
          this.startLoc = this.curPosition();
        }
        if (this.pos >= this.input.length) {
          return this.finishToken(types$13.eof);
        }
        if (curContext.override) {
          return curContext.override(this);
        } else {
          this.readToken(this.fullCharCodeAtPos());
        }
      };
      pp3.readToken = function(code5) {
        if (isIdentifierStart3(code5, this.options.ecmaVersion >= 6) || code5 === 92) {
          return this.readWord();
        }
        return this.getTokenFromCode(code5);
      };
      pp3.fullCharCodeAt = function(pos) {
        var code5 = this.input.charCodeAt(pos);
        if (code5 <= 55295 || code5 >= 56320) {
          return code5;
        }
        var next = this.input.charCodeAt(pos + 1);
        return next <= 56319 || next >= 57344 ? code5 : (code5 << 10) + next - 56613888;
      };
      pp3.fullCharCodeAtPos = function() {
        return this.fullCharCodeAt(this.pos);
      };
      pp3.skipBlockComment = function() {
        var startLoc = this.options.onComment && this.curPosition();
        var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
        if (end === -1) {
          this.raise(this.pos - 2, "Unterminated comment");
        }
        this.pos = end + 2;
        if (this.options.locations) {
          for (var nextBreak = void 0, pos = start; (nextBreak = nextLineBreak(this.input, pos, this.pos)) > -1; ) {
            ++this.curLine;
            pos = this.lineStart = nextBreak;
          }
        }
        if (this.options.onComment) {
          this.options.onComment(
            true,
            this.input.slice(start + 2, end),
            start,
            this.pos,
            startLoc,
            this.curPosition()
          );
        }
      };
      pp3.skipLineComment = function(startSkip) {
        var start = this.pos;
        var startLoc = this.options.onComment && this.curPosition();
        var ch = this.input.charCodeAt(this.pos += startSkip);
        while (this.pos < this.input.length && !isNewLine3(ch)) {
          ch = this.input.charCodeAt(++this.pos);
        }
        if (this.options.onComment) {
          this.options.onComment(
            false,
            this.input.slice(start + startSkip, this.pos),
            start,
            this.pos,
            startLoc,
            this.curPosition()
          );
        }
      };
      pp3.skipSpace = function() {
        loop: while (this.pos < this.input.length) {
          var ch = this.input.charCodeAt(this.pos);
          switch (ch) {
            case 32:
            case 160:
              ++this.pos;
              break;
            case 13:
              if (this.input.charCodeAt(this.pos + 1) === 10) {
                ++this.pos;
              }
            case 10:
            case 8232:
            case 8233:
              ++this.pos;
              if (this.options.locations) {
                ++this.curLine;
                this.lineStart = this.pos;
              }
              break;
            case 47:
              switch (this.input.charCodeAt(this.pos + 1)) {
                case 42:
                  this.skipBlockComment();
                  break;
                case 47:
                  this.skipLineComment(2);
                  break;
                default:
                  break loop;
              }
              break;
            default:
              if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace3.test(String.fromCharCode(ch))) {
                ++this.pos;
              } else {
                break loop;
              }
          }
        }
      };
      pp3.finishToken = function(type4, val) {
        this.end = this.pos;
        if (this.options.locations) {
          this.endLoc = this.curPosition();
        }
        var prevType = this.type;
        this.type = type4;
        this.value = val;
        this.updateContext(prevType);
      };
      pp3.readToken_dot = function() {
        var next = this.input.charCodeAt(this.pos + 1);
        if (next >= 48 && next <= 57) {
          return this.readNumber(true);
        }
        var next2 = this.input.charCodeAt(this.pos + 2);
        if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) {
          this.pos += 3;
          return this.finishToken(types$13.ellipsis);
        } else {
          ++this.pos;
          return this.finishToken(types$13.dot);
        }
      };
      pp3.readToken_slash = function() {
        var next = this.input.charCodeAt(this.pos + 1);
        if (this.exprAllowed) {
          ++this.pos;
          return this.readRegexp();
        }
        if (next === 61) {
          return this.finishOp(types$13.assign, 2);
        }
        return this.finishOp(types$13.slash, 1);
      };
      pp3.readToken_mult_modulo_exp = function(code5) {
        var next = this.input.charCodeAt(this.pos + 1);
        var size = 1;
        var tokentype = code5 === 42 ? types$13.star : types$13.modulo;
        if (this.options.ecmaVersion >= 7 && code5 === 42 && next === 42) {
          ++size;
          tokentype = types$13.starstar;
          next = this.input.charCodeAt(this.pos + 2);
        }
        if (next === 61) {
          return this.finishOp(types$13.assign, size + 1);
        }
        return this.finishOp(tokentype, size);
      };
      pp3.readToken_pipe_amp = function(code5) {
        var next = this.input.charCodeAt(this.pos + 1);
        if (next === code5) {
          if (this.options.ecmaVersion >= 12) {
            var next2 = this.input.charCodeAt(this.pos + 2);
            if (next2 === 61) {
              return this.finishOp(types$13.assign, 3);
            }
          }
          return this.finishOp(code5 === 124 ? types$13.logicalOR : types$13.logicalAND, 2);
        }
        if (next === 61) {
          return this.finishOp(types$13.assign, 2);
        }
        return this.finishOp(code5 === 124 ? types$13.bitwiseOR : types$13.bitwiseAND, 1);
      };
      pp3.readToken_caret = function() {
        var next = this.input.charCodeAt(this.pos + 1);
        if (next === 61) {
          return this.finishOp(types$13.assign, 2);
        }
        return this.finishOp(types$13.bitwiseXOR, 1);
      };
      pp3.readToken_plus_min = function(code5) {
        var next = this.input.charCodeAt(this.pos + 1);
        if (next === code5) {
          if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 && (this.lastTokEnd === 0 || lineBreak3.test(this.input.slice(this.lastTokEnd, this.pos)))) {
            this.skipLineComment(3);
            this.skipSpace();
            return this.nextToken();
          }
          return this.finishOp(types$13.incDec, 2);
        }
        if (next === 61) {
          return this.finishOp(types$13.assign, 2);
        }
        return this.finishOp(types$13.plusMin, 1);
      };
      pp3.readToken_lt_gt = function(code5) {
        var next = this.input.charCodeAt(this.pos + 1);
        var size = 1;
        if (next === code5) {
          size = code5 === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
          if (this.input.charCodeAt(this.pos + size) === 61) {
            return this.finishOp(types$13.assign, size + 1);
          }
          return this.finishOp(types$13.bitShift, size);
        }
        if (next === 33 && code5 === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && this.input.charCodeAt(this.pos + 3) === 45) {
          this.skipLineComment(4);
          this.skipSpace();
          return this.nextToken();
        }
        if (next === 61) {
          size = 2;
        }
        return this.finishOp(types$13.relational, size);
      };
      pp3.readToken_eq_excl = function(code5) {
        var next = this.input.charCodeAt(this.pos + 1);
        if (next === 61) {
          return this.finishOp(types$13.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2);
        }
        if (code5 === 61 && next === 62 && this.options.ecmaVersion >= 6) {
          this.pos += 2;
          return this.finishToken(types$13.arrow);
        }
        return this.finishOp(code5 === 61 ? types$13.eq : types$13.prefix, 1);
      };
      pp3.readToken_question = function() {
        var ecmaVersion2 = this.options.ecmaVersion;
        if (ecmaVersion2 >= 11) {
          var next = this.input.charCodeAt(this.pos + 1);
          if (next === 46) {
            var next2 = this.input.charCodeAt(this.pos + 2);
            if (next2 < 48 || next2 > 57) {
              return this.finishOp(types$13.questionDot, 2);
            }
          }
          if (next === 63) {
            if (ecmaVersion2 >= 12) {
              var next2$1 = this.input.charCodeAt(this.pos + 2);
              if (next2$1 === 61) {
                return this.finishOp(types$13.assign, 3);
              }
            }
            return this.finishOp(types$13.coalesce, 2);
          }
        }
        return this.finishOp(types$13.question, 1);
      };
      pp3.readToken_numberSign = function() {
        var ecmaVersion2 = this.options.ecmaVersion;
        var code5 = 35;
        if (ecmaVersion2 >= 13) {
          ++this.pos;
          code5 = this.fullCharCodeAtPos();
          if (isIdentifierStart3(code5, true) || code5 === 92) {
            return this.finishToken(types$13.privateId, this.readWord1());
          }
        }
        this.raise(this.pos, "Unexpected character '" + codePointToString3(code5) + "'");
      };
      pp3.getTokenFromCode = function(code5) {
        switch (code5) {
          // The interpretation of a dot depends on whether it is followed
          // by a digit or another two dots.
          case 46:
            return this.readToken_dot();
          // Punctuation tokens.
          case 40:
            ++this.pos;
            return this.finishToken(types$13.parenL);
          case 41:
            ++this.pos;
            return this.finishToken(types$13.parenR);
          case 59:
            ++this.pos;
            return this.finishToken(types$13.semi);
          case 44:
            ++this.pos;
            return this.finishToken(types$13.comma);
          case 91:
            ++this.pos;
            return this.finishToken(types$13.bracketL);
          case 93:
            ++this.pos;
            return this.finishToken(types$13.bracketR);
          case 123:
            ++this.pos;
            return this.finishToken(types$13.braceL);
          case 125:
            ++this.pos;
            return this.finishToken(types$13.braceR);
          case 58:
            ++this.pos;
            return this.finishToken(types$13.colon);
          case 96:
            if (this.options.ecmaVersion < 6) {
              break;
            }
            ++this.pos;
            return this.finishToken(types$13.backQuote);
          case 48:
            var next = this.input.charCodeAt(this.pos + 1);
            if (next === 120 || next === 88) {
              return this.readRadixNumber(16);
            }
            if (this.options.ecmaVersion >= 6) {
              if (next === 111 || next === 79) {
                return this.readRadixNumber(8);
              }
              if (next === 98 || next === 66) {
                return this.readRadixNumber(2);
              }
            }
          // Anything else beginning with a digit is an integer, octal
          // number, or float.
          case 49:
          case 50:
          case 51:
          case 52:
          case 53:
          case 54:
          case 55:
          case 56:
          case 57:
            return this.readNumber(false);
          // Quotes produce strings.
          case 34:
          case 39:
            return this.readString(code5);
          // Operators are parsed inline in tiny state machines. '=' (61) is
          // often referred to. `finishOp` simply skips the amount of
          // characters it is given as second argument, and returns a token
          // of the type given by its first argument.
          case 47:
            return this.readToken_slash();
          case 37:
          case 42:
            return this.readToken_mult_modulo_exp(code5);
          case 124:
          case 38:
            return this.readToken_pipe_amp(code5);
          case 94:
            return this.readToken_caret();
          case 43:
          case 45:
            return this.readToken_plus_min(code5);
          case 60:
          case 62:
            return this.readToken_lt_gt(code5);
          case 61:
          case 33:
            return this.readToken_eq_excl(code5);
          case 63:
            return this.readToken_question();
          case 126:
            return this.finishOp(types$13.prefix, 1);
          case 35:
            return this.readToken_numberSign();
        }
        this.raise(this.pos, "Unexpected character '" + codePointToString3(code5) + "'");
      };
      pp3.finishOp = function(type4, size) {
        var str3 = this.input.slice(this.pos, this.pos + size);
        this.pos += size;
        return this.finishToken(type4, str3);
      };
      pp3.readRegexp = function() {
        var escaped, inClass, start = this.pos;
        for (; ; ) {
          if (this.pos >= this.input.length) {
            this.raise(start, "Unterminated regular expression");
          }
          var ch = this.input.charAt(this.pos);
          if (lineBreak3.test(ch)) {
            this.raise(start, "Unterminated regular expression");
          }
          if (!escaped) {
            if (ch === "[") {
              inClass = true;
            } else if (ch === "]" && inClass) {
              inClass = false;
            } else if (ch === "/" && !inClass) {
              break;
            }
            escaped = ch === "\\";
          } else {
            escaped = false;
          }
          ++this.pos;
        }
        var pattern = this.input.slice(start, this.pos);
        ++this.pos;
        var flagsStart = this.pos;
        var flags = this.readWord1();
        if (this.containsEsc) {
          this.unexpected(flagsStart);
        }
        var state2 = this.regexpState || (this.regexpState = new RegExpValidationState4(this));
        state2.reset(start, pattern, flags);
        this.validateRegExpFlags(state2);
        this.validateRegExpPattern(state2);
        var value = null;
        try {
          value = new RegExp(pattern, flags);
        } catch (e5) {
        }
        return this.finishToken(types$13.regexp, { pattern, flags, value });
      };
      pp3.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {
        var allowSeparators = this.options.ecmaVersion >= 12 && len === void 0;
        var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;
        var start = this.pos, total = 0, lastCode = 0;
        for (var i7 = 0, e5 = len == null ? Infinity : len; i7 < e5; ++i7, ++this.pos) {
          var code5 = this.input.charCodeAt(this.pos), val = void 0;
          if (allowSeparators && code5 === 95) {
            if (isLegacyOctalNumericLiteral) {
              this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals");
            }
            if (lastCode === 95) {
              this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore");
            }
            if (i7 === 0) {
              this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits");
            }
            lastCode = code5;
            continue;
          }
          if (code5 >= 97) {
            val = code5 - 97 + 10;
          } else if (code5 >= 65) {
            val = code5 - 65 + 10;
          } else if (code5 >= 48 && code5 <= 57) {
            val = code5 - 48;
          } else {
            val = Infinity;
          }
          if (val >= radix) {
            break;
          }
          lastCode = code5;
          total = total * radix + val;
        }
        if (allowSeparators && lastCode === 95) {
          this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits");
        }
        if (this.pos === start || len != null && this.pos - start !== len) {
          return null;
        }
        return total;
      };
      function stringToNumber3(str3, isLegacyOctalNumericLiteral) {
        if (isLegacyOctalNumericLiteral) {
          return parseInt(str3, 8);
        }
        return parseFloat(str3.replace(/_/g, ""));
      }
      function stringToBigInt3(str3) {
        if (typeof BigInt !== "function") {
          return null;
        }
        return BigInt(str3.replace(/_/g, ""));
      }
      pp3.readRadixNumber = function(radix) {
        var start = this.pos;
        this.pos += 2;
        var val = this.readInt(radix);
        if (val == null) {
          this.raise(this.start + 2, "Expected number in radix " + radix);
        }
        if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
          val = stringToBigInt3(this.input.slice(start, this.pos));
          ++this.pos;
        } else if (isIdentifierStart3(this.fullCharCodeAtPos())) {
          this.raise(this.pos, "Identifier directly after number");
        }
        return this.finishToken(types$13.num, val);
      };
      pp3.readNumber = function(startsWithDot) {
        var start = this.pos;
        if (!startsWithDot && this.readInt(10, void 0, true) === null) {
          this.raise(start, "Invalid number");
        }
        var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
        if (octal && this.strict) {
          this.raise(start, "Invalid number");
        }
        var next = this.input.charCodeAt(this.pos);
        if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
          var val$1 = stringToBigInt3(this.input.slice(start, this.pos));
          ++this.pos;
          if (isIdentifierStart3(this.fullCharCodeAtPos())) {
            this.raise(this.pos, "Identifier directly after number");
          }
          return this.finishToken(types$13.num, val$1);
        }
        if (octal && /[89]/.test(this.input.slice(start, this.pos))) {
          octal = false;
        }
        if (next === 46 && !octal) {
          ++this.pos;
          this.readInt(10);
          next = this.input.charCodeAt(this.pos);
        }
        if ((next === 69 || next === 101) && !octal) {
          next = this.input.charCodeAt(++this.pos);
          if (next === 43 || next === 45) {
            ++this.pos;
          }
          if (this.readInt(10) === null) {
            this.raise(start, "Invalid number");
          }
        }
        if (isIdentifierStart3(this.fullCharCodeAtPos())) {
          this.raise(this.pos, "Identifier directly after number");
        }
        var val = stringToNumber3(this.input.slice(start, this.pos), octal);
        return this.finishToken(types$13.num, val);
      };
      pp3.readCodePoint = function() {
        var ch = this.input.charCodeAt(this.pos), code5;
        if (ch === 123) {
          if (this.options.ecmaVersion < 6) {
            this.unexpected();
          }
          var codePos = ++this.pos;
          code5 = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
          ++this.pos;
          if (code5 > 1114111) {
            this.invalidStringToken(codePos, "Code point out of bounds");
          }
        } else {
          code5 = this.readHexChar(4);
        }
        return code5;
      };
      pp3.readString = function(quote) {
        var out = "", chunkStart = ++this.pos;
        for (; ; ) {
          if (this.pos >= this.input.length) {
            this.raise(this.start, "Unterminated string constant");
          }
          var ch = this.input.charCodeAt(this.pos);
          if (ch === quote) {
            break;
          }
          if (ch === 92) {
            out += this.input.slice(chunkStart, this.pos);
            out += this.readEscapedChar(false);
            chunkStart = this.pos;
          } else if (ch === 8232 || ch === 8233) {
            if (this.options.ecmaVersion < 10) {
              this.raise(this.start, "Unterminated string constant");
            }
            ++this.pos;
            if (this.options.locations) {
              this.curLine++;
              this.lineStart = this.pos;
            }
          } else {
            if (isNewLine3(ch)) {
              this.raise(this.start, "Unterminated string constant");
            }
            ++this.pos;
          }
        }
        out += this.input.slice(chunkStart, this.pos++);
        return this.finishToken(types$13.string, out);
      };
      var INVALID_TEMPLATE_ESCAPE_ERROR3 = {};
      pp3.tryReadTemplateToken = function() {
        this.inTemplateElement = true;
        try {
          this.readTmplToken();
        } catch (err2) {
          if (err2 === INVALID_TEMPLATE_ESCAPE_ERROR3) {
            this.readInvalidTemplateToken();
          } else {
            throw err2;
          }
        }
        this.inTemplateElement = false;
      };
      pp3.invalidStringToken = function(position, message) {
        if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
          throw INVALID_TEMPLATE_ESCAPE_ERROR3;
        } else {
          this.raise(position, message);
        }
      };
      pp3.readTmplToken = function() {
        var out = "", chunkStart = this.pos;
        for (; ; ) {
          if (this.pos >= this.input.length) {
            this.raise(this.start, "Unterminated template");
          }
          var ch = this.input.charCodeAt(this.pos);
          if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) {
            if (this.pos === this.start && (this.type === types$13.template || this.type === types$13.invalidTemplate)) {
              if (ch === 36) {
                this.pos += 2;
                return this.finishToken(types$13.dollarBraceL);
              } else {
                ++this.pos;
                return this.finishToken(types$13.backQuote);
              }
            }
            out += this.input.slice(chunkStart, this.pos);
            return this.finishToken(types$13.template, out);
          }
          if (ch === 92) {
            out += this.input.slice(chunkStart, this.pos);
            out += this.readEscapedChar(true);
            chunkStart = this.pos;
          } else if (isNewLine3(ch)) {
            out += this.input.slice(chunkStart, this.pos);
            ++this.pos;
            switch (ch) {
              case 13:
                if (this.input.charCodeAt(this.pos) === 10) {
                  ++this.pos;
                }
              case 10:
                out += "\n";
                break;
              default:
                out += String.fromCharCode(ch);
                break;
            }
            if (this.options.locations) {
              ++this.curLine;
              this.lineStart = this.pos;
            }
            chunkStart = this.pos;
          } else {
            ++this.pos;
          }
        }
      };
      pp3.readInvalidTemplateToken = function() {
        for (; this.pos < this.input.length; this.pos++) {
          switch (this.input[this.pos]) {
            case "\\":
              ++this.pos;
              break;
            case "$":
              if (this.input[this.pos + 1] !== "{") {
                break;
              }
            // fall through
            case "`":
              return this.finishToken(types$13.invalidTemplate, this.input.slice(this.start, this.pos));
            case "\r":
              if (this.input[this.pos + 1] === "\n") {
                ++this.pos;
              }
            // fall through
            case "\n":
            case "\u2028":
            case "\u2029":
              ++this.curLine;
              this.lineStart = this.pos + 1;
              break;
          }
        }
        this.raise(this.start, "Unterminated template");
      };
      pp3.readEscapedChar = function(inTemplate) {
        var ch = this.input.charCodeAt(++this.pos);
        ++this.pos;
        switch (ch) {
          case 110:
            return "\n";
          // 'n' -> '\n'
          case 114:
            return "\r";
          // 'r' -> '\r'
          case 120:
            return String.fromCharCode(this.readHexChar(2));
          // 'x'
          case 117:
            return codePointToString3(this.readCodePoint());
          // 'u'
          case 116:
            return "	";
          // 't' -> '\t'
          case 98:
            return "\b";
          // 'b' -> '\b'
          case 118:
            return "\v";
          // 'v' -> '\u000b'
          case 102:
            return "\f";
          // 'f' -> '\f'
          case 13:
            if (this.input.charCodeAt(this.pos) === 10) {
              ++this.pos;
            }
          // '\r\n'
          case 10:
            if (this.options.locations) {
              this.lineStart = this.pos;
              ++this.curLine;
            }
            return "";
          case 56:
          case 57:
            if (this.strict) {
              this.invalidStringToken(
                this.pos - 1,
                "Invalid escape sequence"
              );
            }
            if (inTemplate) {
              var codePos = this.pos - 1;
              this.invalidStringToken(
                codePos,
                "Invalid escape sequence in template string"
              );
            }
          default:
            if (ch >= 48 && ch <= 55) {
              var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
              var octal = parseInt(octalStr, 8);
              if (octal > 255) {
                octalStr = octalStr.slice(0, -1);
                octal = parseInt(octalStr, 8);
              }
              this.pos += octalStr.length - 1;
              ch = this.input.charCodeAt(this.pos);
              if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {
                this.invalidStringToken(
                  this.pos - 1 - octalStr.length,
                  inTemplate ? "Octal literal in template string" : "Octal literal in strict mode"
                );
              }
              return String.fromCharCode(octal);
            }
            if (isNewLine3(ch)) {
              if (this.options.locations) {
                this.lineStart = this.pos;
                ++this.curLine;
              }
              return "";
            }
            return String.fromCharCode(ch);
        }
      };
      pp3.readHexChar = function(len) {
        var codePos = this.pos;
        var n5 = this.readInt(16, len);
        if (n5 === null) {
          this.invalidStringToken(codePos, "Bad character escape sequence");
        }
        return n5;
      };
      pp3.readWord1 = function() {
        this.containsEsc = false;
        var word = "", first = true, chunkStart = this.pos;
        var astral = this.options.ecmaVersion >= 6;
        while (this.pos < this.input.length) {
          var ch = this.fullCharCodeAtPos();
          if (isIdentifierChar3(ch, astral)) {
            this.pos += ch <= 65535 ? 1 : 2;
          } else if (ch === 92) {
            this.containsEsc = true;
            word += this.input.slice(chunkStart, this.pos);
            var escStart = this.pos;
            if (this.input.charCodeAt(++this.pos) !== 117) {
              this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX");
            }
            ++this.pos;
            var esc = this.readCodePoint();
            if (!(first ? isIdentifierStart3 : isIdentifierChar3)(esc, astral)) {
              this.invalidStringToken(escStart, "Invalid Unicode escape");
            }
            word += codePointToString3(esc);
            chunkStart = this.pos;
          } else {
            break;
          }
          first = false;
        }
        return word + this.input.slice(chunkStart, this.pos);
      };
      pp3.readWord = function() {
        var word = this.readWord1();
        var type4 = types$13.name;
        if (this.keywords.test(word)) {
          type4 = keywords3[word];
        }
        return this.finishToken(type4, word);
      };
      var version4 = "8.16.0";
      Parser6.acorn = {
        Parser: Parser6,
        version: version4,
        defaultOptions: defaultOptions3,
        Position: Position4,
        SourceLocation: SourceLocation4,
        getLineInfo: getLineInfo3,
        Node: Node7,
        TokenType: TokenType4,
        tokTypes: types$13,
        keywordTypes: keywords3,
        TokContext: TokContext4,
        tokContexts: types8,
        isIdentifierChar: isIdentifierChar3,
        isIdentifierStart: isIdentifierStart3,
        Token: Token5,
        isNewLine: isNewLine3,
        lineBreak: lineBreak3,
        lineBreakG: lineBreakG3,
        nonASCIIwhitespace: nonASCIIwhitespace3
      };
      function parse24(input, options) {
        return Parser6.parse(input, options);
      }
      function parseExpressionAt3(input, pos, options) {
        return Parser6.parseExpressionAt(input, pos, options);
      }
      function tokenizer3(input, options) {
        return Parser6.tokenizer(input, options);
      }
      exports24.Node = Node7;
      exports24.Parser = Parser6;
      exports24.Position = Position4;
      exports24.SourceLocation = SourceLocation4;
      exports24.TokContext = TokContext4;
      exports24.Token = Token5;
      exports24.TokenType = TokenType4;
      exports24.defaultOptions = defaultOptions3;
      exports24.getLineInfo = getLineInfo3;
      exports24.isIdentifierChar = isIdentifierChar3;
      exports24.isIdentifierStart = isIdentifierStart3;
      exports24.isNewLine = isNewLine3;
      exports24.keywordTypes = keywords3;
      exports24.lineBreak = lineBreak3;
      exports24.lineBreakG = lineBreakG3;
      exports24.nonASCIIwhitespace = nonASCIIwhitespace3;
      exports24.parse = parse24;
      exports24.parseExpressionAt = parseExpressionAt3;
      exports24.tokContexts = types8;
      exports24.tokTypes = types$13;
      exports24.tokenizer = tokenizer3;
      exports24.version = version4;
    }));
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/acorn-private-class-elements@1.0.0_acorn@8.16.0/node_modules/acorn-private-class-elements/index.js
var require_acorn_private_class_elements = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/acorn-private-class-elements@1.0.0_acorn@8.16.0/node_modules/acorn-private-class-elements/index.js"(exports23, module2) {
    "use strict";
    var getPrototype = Object.getPrototypeOf || ((o5) => o5.__proto__);
    var getAcorn = (Parser6) => {
      if (Parser6.acorn) return Parser6.acorn;
      const acorn = require_acorn();
      if (acorn.version.indexOf("6.") != 0 && acorn.version.indexOf("6.0.") == 0 && acorn.version.indexOf("7.") != 0) {
        throw new Error(`acorn-private-class-elements requires acorn@^6.1.0 or acorn@7.0.0, not ${acorn.version}`);
      }
      for (let cur = Parser6; cur && cur !== acorn.Parser; cur = getPrototype(cur)) {
        if (cur !== acorn.Parser) {
          throw new Error("acorn-private-class-elements does not support mixing different acorn copies");
        }
      }
      return acorn;
    };
    module2.exports = function(Parser6) {
      if (Parser6.prototype.parsePrivateName) {
        return Parser6;
      }
      const acorn = getAcorn(Parser6);
      Parser6 = class extends Parser6 {
        _branch() {
          this.__branch = this.__branch || new Parser6({ ecmaVersion: this.options.ecmaVersion }, this.input);
          this.__branch.end = this.end;
          this.__branch.pos = this.pos;
          this.__branch.type = this.type;
          this.__branch.value = this.value;
          this.__branch.containsEsc = this.containsEsc;
          return this.__branch;
        }
        parsePrivateClassElementName(element) {
          element.computed = false;
          element.key = this.parsePrivateName();
          if (element.key.name == "constructor") this.raise(element.key.start, "Classes may not have a private element named constructor");
          const accept = { get: "set", set: "get" }[element.kind];
          const privateBoundNames = this._privateBoundNames;
          if (Object.prototype.hasOwnProperty.call(privateBoundNames, element.key.name) && privateBoundNames[element.key.name] !== accept) {
            this.raise(element.start, "Duplicate private element");
          }
          privateBoundNames[element.key.name] = element.kind || true;
          delete this._unresolvedPrivateNames[element.key.name];
          return element.key;
        }
        parsePrivateName() {
          const node = this.startNode();
          node.name = this.value;
          this.next();
          this.finishNode(node, "PrivateIdentifier");
          if (this.options.allowReserved == "never") this.checkUnreserved(node);
          return node;
        }
        // Parse # token
        getTokenFromCode(code5) {
          if (code5 === 35) {
            ++this.pos;
            const word = this.readWord1();
            return this.finishToken(this.privateIdentifierToken, word);
          }
          return super.getTokenFromCode(code5);
        }
        // Manage stacks and check for undeclared private names
        parseClass(node, isStatement) {
          const oldOuterPrivateBoundNames = this._outerPrivateBoundNames;
          this._outerPrivateBoundNames = this._privateBoundNames;
          this._privateBoundNames = Object.create(this._privateBoundNames || null);
          const oldOuterUnresolvedPrivateNames = this._outerUnresolvedPrivateNames;
          this._outerUnresolvedPrivateNames = this._unresolvedPrivateNames;
          this._unresolvedPrivateNames = /* @__PURE__ */ Object.create(null);
          const _return = super.parseClass(node, isStatement);
          const unresolvedPrivateNames = this._unresolvedPrivateNames;
          this._privateBoundNames = this._outerPrivateBoundNames;
          this._outerPrivateBoundNames = oldOuterPrivateBoundNames;
          this._unresolvedPrivateNames = this._outerUnresolvedPrivateNames;
          this._outerUnresolvedPrivateNames = oldOuterUnresolvedPrivateNames;
          if (!this._unresolvedPrivateNames) {
            const names = Object.keys(unresolvedPrivateNames);
            if (names.length) {
              names.sort((n1, n22) => unresolvedPrivateNames[n1] - unresolvedPrivateNames[n22]);
              this.raise(unresolvedPrivateNames[names[0]], "Usage of undeclared private name");
            }
          } else Object.assign(this._unresolvedPrivateNames, unresolvedPrivateNames);
          return _return;
        }
        // Class heritage is evaluated with outer private environment
        parseClassSuper(node) {
          const privateBoundNames = this._privateBoundNames;
          this._privateBoundNames = this._outerPrivateBoundNames;
          const unresolvedPrivateNames = this._unresolvedPrivateNames;
          this._unresolvedPrivateNames = this._outerUnresolvedPrivateNames;
          const _return = super.parseClassSuper(node);
          this._privateBoundNames = privateBoundNames;
          this._unresolvedPrivateNames = unresolvedPrivateNames;
          return _return;
        }
        // Parse private element access
        parseSubscript(base3, startPos, startLoc, _noCalls, _maybeAsyncArrow, _optionalChained) {
          const optionalSupported = this.options.ecmaVersion >= 11 && acorn.tokTypes.questionDot;
          const branch = this._branch();
          if (!((branch.eat(acorn.tokTypes.dot) || optionalSupported && branch.eat(acorn.tokTypes.questionDot)) && branch.type == this.privateIdentifierToken)) {
            return super.parseSubscript.apply(this, arguments);
          }
          let optional = false;
          if (!this.eat(acorn.tokTypes.dot)) {
            this.expect(acorn.tokTypes.questionDot);
            optional = true;
          }
          let node = this.startNodeAt(startPos, startLoc);
          node.object = base3;
          node.computed = false;
          if (optionalSupported) {
            node.optional = optional;
          }
          if (this.type == this.privateIdentifierToken) {
            if (base3.type == "Super") {
              this.raise(this.start, "Cannot access private element on super");
            }
            node.property = this.parsePrivateName();
            if (!this._privateBoundNames || !this._privateBoundNames[node.property.name]) {
              if (!this._unresolvedPrivateNames) {
                this.raise(node.property.start, "Usage of undeclared private name");
              }
              this._unresolvedPrivateNames[node.property.name] = node.property.start;
            }
          } else {
            node.property = this.parseIdent(true);
          }
          return this.finishNode(node, "MemberExpression");
        }
        // Prohibit delete of private class elements
        parseMaybeUnary(refDestructuringErrors, sawUnary) {
          const _return = super.parseMaybeUnary(refDestructuringErrors, sawUnary);
          if (_return.operator == "delete") {
            if (_return.argument.type == "MemberExpression" && _return.argument.property.type == "PrivateIdentifier") {
              this.raise(_return.start, "Private elements may not be deleted");
            }
          }
          return _return;
        }
      };
      Parser6.prototype.privateIdentifierToken = new acorn.TokenType("privateIdentifier");
      return Parser6;
    };
  }
});

// ../../../../.cache/deno/deno_esbuild/registry.npmjs.org/acorn-class-fields@1.0.0_acorn@8.16.0/node_modules/acorn-class-fields/index.js
var require_acorn_class_fields = __commonJS({
  "../../../../.cache/deno/deno_esbuild/registry.npmjs.org/acorn-class-fields@1.0.0_acorn@8.16.0/node_modules/acorn-class-fields/index.js"(exports23, module2) {
    "use strict";
    var privateClassElements = require_acorn_private_class_elements();
    module2.exports = function(Parser6) {
      const acorn = Parser6.acorn || require_acorn();
      const tt = acorn.tokTypes;
      Parser6 = privateClassElements(Parser6);
      return class extends Parser6 {
        _maybeParseFieldValue(field) {
          if (this.eat(tt.eq)) {
            const oldInFieldValue = this._inFieldValue;
            this._inFieldValue = true;
            if (this.type === tt.name && this.value === "await" && (this.inAsync || this.options.allowAwaitOutsideFunction)) {
              field.value = this.parseAwait();
            } else field.value = this.parseExpression();
            this._inFieldValue = oldInFieldValue;
          } else field.value = null;
        }
        // Parse fields
        parseClassElement(_constructorAllowsSuper) {
          if (this.options.ecmaVersion >= 8 && (this.type == tt.name || this.type.keyword || this.type == this.privateIdentifierToken || this.type == tt.bracketL || this.type == tt.string || this.type == tt.num)) {
            const branch = this._branch();
            if (branch.type == tt.bracketL) {
              let count = 0;
              do {
                if (branch.eat(tt.bracketL)) ++count;
                else if (branch.eat(tt.bracketR)) --count;
                else branch.next();
              } while (count > 0);
            } else branch.next(true);
            let isField = branch.type == tt.eq || branch.type == tt.semi;
            if (!isField && branch.canInsertSemicolon()) {
              isField = branch.type != tt.parenL;
            }
            if (isField) {
              const node = this.startNode();
              if (this.type == this.privateIdentifierToken) {
                this.parsePrivateClassElementName(node);
              } else {
                this.parsePropertyName(node);
              }
              if (node.key.type === "Identifier" && node.key.name === "constructor" || node.key.type === "Literal" && node.key.value === "constructor") {
                this.raise(node.key.start, "Classes may not have a field called constructor");
              }
              this.enterScope(64 | 2 | 1);
              this._maybeParseFieldValue(node);
              this.exitScope();
              this.finishNode(node, "PropertyDefinition");
              this.semicolon();
              return node;
            }
          }
          return super.parseClassElement.apply(this, arguments);
        }
        // Prohibit arguments in class field initializers
        parseIdent(liberal, isBinding) {
          const ident = super.parseIdent(liberal, isBinding);
          if (this._inFieldValue && ident.name == "arguments") this.raise(ident.start, "A class field initializer may not contain arguments");
          return ident;
        }
      };
    };
  }
});

// quarto.ts
init_original_real_path();

// core/deno/monkey-patch.ts
init_log();
init_path2();

// https://jsr.io/@std/io/0.224.0/_constants.ts
var DEFAULT_CHUNK_SIZE = 16640;
var DEFAULT_BUFFER_SIZE = 32 * 1024;

// https://jsr.io/@std/io/0.224.0/copy.ts
async function copy2(src2, dst, options) {
  let n5 = 0;
  const bufSize = options?.bufSize ?? DEFAULT_BUFFER_SIZE;
  const b3 = new Uint8Array(bufSize);
  let gotEOF = false;
  while (gotEOF === false) {
    const result2 = await src2.read(b3);
    if (result2 === null) {
      gotEOF = true;
    } else {
      let nwritten = 0;
      while (nwritten < result2) {
        nwritten += await dst.write(b3.subarray(nwritten, result2));
      }
      n5 += nwritten;
    }
  }
  return n5;
}

// core/deno/monkey-patch.ts
init_write_all();
Deno.realPathSync = normalizePath;
Deno.copy = copy2;
Deno.writeAll = writeAll;
var maxAttempts = 5;
function withAttempts(callable) {
  for (let i6 = 0; i6 < maxAttempts; i6++) {
    try {
      return callable();
    } catch (err2) {
      if (!(err2 instanceof Error)) {
        throw err2;
      }
      if (err2.message) {
        debug("Error attempting to create temp file: " + err2.message);
        if (i6 === maxAttempts - 1) {
          throw err2;
        } else {
          debug(`Retrying... ${i6 + 1} of ${maxAttempts - 1}`);
        }
      }
    }
  }
  throw new Error("Shouldn't get here");
}
function withAttemptsAsync(callable) {
  const inner = (attempt) => {
    return callable().catch((err2) => {
      if (!(err2 instanceof Error)) {
        throw err2;
      }
      if (err2.message) {
        debug("Error attempting to create temp file: " + err2.message);
      }
      if (attempt === maxAttempts - 1) {
        throw err2;
      } else {
        debug(`Retrying... ${attempt + 1} of ${maxAttempts - 1}`);
        return inner(attempt + 1);
      }
    });
  };
  return inner(0);
}
var oldMakeTempFile = Deno.makeTempFile;
var oldMakeTempFileSync = Deno.makeTempFileSync;
var oldMakeTempDir = Deno.makeTempDir;
var oldMakeTempDirSync = Deno.makeTempDirSync;
function makeTempFileSync(options) {
  return withAttempts(() => oldMakeTempFileSync(options));
}
function makeTempFile(options) {
  return withAttemptsAsync(() => oldMakeTempFile(options));
}
function makeTempDirSync(options) {
  return withAttempts(() => oldMakeTempDirSync(options));
}
function makeTempDir(options) {
  return withAttemptsAsync(() => oldMakeTempDir(options));
}
Deno.makeTempFile = makeTempFile;
Deno.makeTempFileSync = makeTempFileSync;
Deno.makeTempDir = makeTempDir;
Deno.makeTempDirSync = makeTempDirSync;
var oldReadTextFile = Deno.readTextFile;
var oldReadTextFileSync = Deno.readTextFileSync;
Deno.readTextFile = async (path3, options) => {
  try {
    const result2 = await oldReadTextFile(path3, options);
    return result2;
  } catch (err2) {
    if (!(err2 instanceof Error)) {
      throw err2;
    }
    if (err2.message) {
      err2.message = err2.message + "\nPath: " + path3;
    }
    throw err2;
  }
};
Deno.readTextFileSync = (path3) => {
  try {
    const result2 = oldReadTextFileSync(path3);
    return result2;
  } catch (err2) {
    if (!(err2 instanceof Error)) {
      throw err2;
    }
    if (err2.message) {
      err2.message = err2.message + "\nPath: " + path3;
    }
    throw err2;
  }
};

// https://deno.land/x/cliffy@v1.0.0-rc.3/_utils/distance.ts
function distance(a5, b3) {
  if (a5.length == 0) {
    return b3.length;
  }
  if (b3.length == 0) {
    return a5.length;
  }
  const matrix = [];
  for (let i6 = 0; i6 <= b3.length; i6++) {
    matrix[i6] = [i6];
  }
  for (let j3 = 0; j3 <= a5.length; j3++) {
    matrix[0][j3] = j3;
  }
  for (let i6 = 1; i6 <= b3.length; i6++) {
    for (let j3 = 1; j3 <= a5.length; j3++) {
      if (b3.charAt(i6 - 1) == a5.charAt(j3 - 1)) {
        matrix[i6][j3] = matrix[i6 - 1][j3 - 1];
      } else {
        matrix[i6][j3] = Math.min(
          matrix[i6 - 1][j3 - 1] + 1,
          Math.min(matrix[i6][j3 - 1] + 1, matrix[i6 - 1][j3] + 1)
        );
      }
    }
  }
  return matrix[b3.length][a5.length];
}

// https://deno.land/x/cliffy@v1.0.0-rc.3/flags/_utils.ts
function paramCaseToCamelCase(str3) {
  return str3.replace(
    /-([a-z])/g,
    (g3) => g3[1].toUpperCase()
  );
}
function underscoreToCamelCase(str3) {
  return str3.replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase().replace(
    /_([a-z])/g,
    (g3) => g3[1].toUpperCase()
  );
}
function getOption(flags, name2) {
  while (name2[0] === "-") {
    name2 = name2.slice(1);
  }
  for (const flag of flags) {
    if (isOption(flag, name2)) {
      return flag;
    }
  }
  return;
}
function didYouMeanOption(option, options) {
  const optionNames = options.map((option2) => [option2.name, ...option2.aliases ?? []]).flat().map((option2) => getFlag(option2));
  return didYouMean(" Did you mean option", getFlag(option), optionNames);
}
function didYouMeanType(type4, types8) {
  return didYouMean(" Did you mean type", type4, types8);
}
function didYouMean(message, type4, types8) {
  const match = closest(type4, types8);
  return match ? `${message} "${match}"?` : "";
}
function getFlag(name2) {
  if (name2.startsWith("-")) {
    return name2;
  }
  if (name2.length > 1) {
    return `--${name2}`;
  }
  return `-${name2}`;
}
function isOption(option, name2) {
  return option.name === name2 || option.aliases && option.aliases.indexOf(name2) !== -1;
}
function matchWildCardOptions(name2, flags) {
  for (const option of flags) {
    if (option.name.indexOf("*") === -1) {
      continue;
    }
    let matched = matchWildCardOption(name2, option);
    if (matched) {
      matched = { ...matched, name: name2 };
      flags.push(matched);
      return matched;
    }
  }
}
function matchWildCardOption(name2, option) {
  const parts = option.name.split(".");
  const parts2 = name2.split(".");
  if (parts.length !== parts2.length) {
    return false;
  }
  const count = Math.max(parts.length, parts2.length);
  for (let i6 = 0; i6 < count; i6++) {
    if (parts[i6] !== parts2[i6] && parts[i6] !== "*") {
      return false;
    }
  }
  return option;
}
function closest(str3, arr) {
  let minDistance = Infinity;
  let minIndex = 0;
  for (let i6 = 0; i6 < arr.length; i6++) {
    const dist = distance(str3, arr[i6]);
    if (dist < minDistance) {
      minDistance = dist;
      minIndex = i6;
    }
  }
  return arr[minIndex];
}
function getDefaultValue(option) {
  return typeof option.default === "function" ? option.default() : option.default;
}

// https://deno.land/x/cliffy@v1.0.0-rc.3/flags/_errors.ts
var FlagsError = class _FlagsError extends Error {
  constructor(message) {
    super(message);
    Object.setPrototypeOf(this, _FlagsError.prototype);
  }
};
var UnknownRequiredOptionError = class _UnknownRequiredOptionError extends FlagsError {
  constructor(option, options) {
    super(
      `Unknown required option "${getFlag(option)}".${didYouMeanOption(option, options)}`
    );
    Object.setPrototypeOf(this, _UnknownRequiredOptionError.prototype);
  }
};
var UnknownConflictingOptionError = class _UnknownConflictingOptionError extends FlagsError {
  constructor(option, options) {
    super(
      `Unknown conflicting option "${getFlag(option)}".${didYouMeanOption(option, options)}`
    );
    Object.setPrototypeOf(this, _UnknownConflictingOptionError.prototype);
  }
};
var UnknownTypeError = class _UnknownTypeError extends FlagsError {
  constructor(type4, types8) {
    super(`Unknown type "${type4}".${didYouMeanType(type4, types8)}`);
    Object.setPrototypeOf(this, _UnknownTypeError.prototype);
  }
};
var ValidationError = class _ValidationError extends FlagsError {
  constructor(message) {
    super(message);
    Object.setPrototypeOf(this, _ValidationError.prototype);
  }
};
var DuplicateOptionError = class _DuplicateOptionError extends ValidationError {
  constructor(name2) {
    super(
      `Option "${getFlag(name2).replace(/^--no-/, "--")}" can only occur once, but was found several times.`
    );
    Object.setPrototypeOf(this, _DuplicateOptionError.prototype);
  }
};
var InvalidOptionError = class _InvalidOptionError extends ValidationError {
  constructor(option, options) {
    super(
      `Invalid option "${getFlag(option)}".${didYouMeanOption(option, options)}`
    );
    Object.setPrototypeOf(this, _InvalidOptionError.prototype);
  }
};
var UnknownOptionError = class _UnknownOptionError extends ValidationError {
  constructor(option, options) {
    super(
      `Unknown option "${getFlag(option)}".${didYouMeanOption(option, options)}`
    );
    Object.setPrototypeOf(this, _UnknownOptionError.prototype);
  }
};
var MissingOptionValueError = class _MissingOptionValueError extends ValidationError {
  constructor(option) {
    super(`Missing value for option "${getFlag(option)}".`);
    Object.setPrototypeOf(this, _MissingOptionValueError.prototype);
  }
};
var InvalidOptionValueError = class _InvalidOptionValueError extends ValidationError {
  constructor(option, expected, value) {
    super(
      `Option "${getFlag(option)}" must be of type "${expected}", but got "${value}".`
    );
    Object.setPrototypeOf(this, _InvalidOptionValueError.prototype);
  }
};
var UnexpectedOptionValueError = class extends ValidationError {
  constructor(option, value) {
    super(
      `Option "${getFlag(option)}" doesn't take a value, but got "${value}".`
    );
    Object.setPrototypeOf(this, InvalidOptionValueError.prototype);
  }
};
var OptionNotCombinableError = class _OptionNotCombinableError extends ValidationError {
  constructor(option) {
    super(`Option "${getFlag(option)}" cannot be combined with other options.`);
    Object.setPrototypeOf(this, _OptionNotCombinableError.prototype);
  }
};
var ConflictingOptionError = class _ConflictingOptionError extends ValidationError {
  constructor(option, conflictingOption) {
    super(
      `Option "${getFlag(option)}" conflicts with option "${getFlag(conflictingOption)}".`
    );
    Object.setPrototypeOf(this, _ConflictingOptionError.prototype);
  }
};
var DependingOptionError = class _DependingOptionError extends ValidationError {
  constructor(option, dependingOption) {
    super(
      `Option "${getFlag(option)}" depends on option "${getFlag(dependingOption)}".`
    );
    Object.setPrototypeOf(this, _DependingOptionError.prototype);
  }
};
var MissingRequiredOptionError = class _MissingRequiredOptionError extends ValidationError {
  constructor(option) {
    super(`Missing required option "${getFlag(option)}".`);
    Object.setPrototypeOf(this, _MissingRequiredOptionError.prototype);
  }
};
var UnexpectedRequiredArgumentError = class _UnexpectedRequiredArgumentError extends ValidationError {
  constructor(arg) {
    super(
      `An required argument cannot follow an optional argument, but "${arg}"  is defined as required.`
    );
    Object.setPrototypeOf(
      this,
      _UnexpectedRequiredArgumentError.prototype
    );
  }
};
var UnexpectedArgumentAfterVariadicArgumentError = class _UnexpectedArgumentAfterVariadicArgumentError extends ValidationError {
  constructor(arg) {
    super(`An argument cannot follow an variadic argument, but got "${arg}".`);
    Object.setPrototypeOf(
      this,
      _UnexpectedArgumentAfterVariadicArgumentError.prototype
    );
  }
};
var InvalidTypeError = class extends ValidationError {
  constructor({ label, name: name2, value, type: type4 }, expected) {
    super(
      `${label} "${name2}" must be of type "${type4}", but got "${value}".` + (expected ? ` Expected values: ${expected.map((value2) => `"${value2}"`).join(", ")}` : "")
    );
    Object.setPrototypeOf(this, MissingOptionValueError.prototype);
  }
};

// https://deno.land/x/cliffy@v1.0.0-rc.3/flags/types/boolean.ts
var boolean = (type4) => {
  if (~["1", "true"].indexOf(type4.value)) {
    return true;
  }
  if (~["0", "false"].indexOf(type4.value)) {
    return false;
  }
  throw new InvalidTypeError(type4, ["true", "false", "1", "0"]);
};

// https://deno.land/x/cliffy@v1.0.0-rc.3/flags/types/number.ts
var number = (type4) => {
  const value = Number(type4.value);
  if (Number.isFinite(value)) {
    return value;
  }
  throw new InvalidTypeError(type4);
};

// https://deno.land/x/cliffy@v1.0.0-rc.3/flags/types/string.ts
var string = ({ value }) => {
  return value;
};

// https://deno.land/x/cliffy@v1.0.0-rc.3/flags/_validate_flags.ts
function validateFlags(ctx, opts, options = /* @__PURE__ */ new Map()) {
  if (!opts.flags) {
    return;
  }
  setDefaultValues(ctx, opts);
  const optionNames = Object.keys(ctx.flags);
  if (!optionNames.length && opts.allowEmpty) {
    return;
  }
  if (ctx.standalone) {
    validateStandaloneOption(
      ctx,
      options,
      optionNames
    );
    return;
  }
  for (const [name2, option] of options) {
    validateUnknownOption(option, opts);
    validateConflictingOptions(ctx, option);
    validateDependingOptions(ctx, option);
    validateRequiredValues(ctx, option, name2);
  }
  validateRequiredOptions(ctx, options, opts);
}
function validateUnknownOption(option, opts) {
  if (!getOption(opts.flags ?? [], option.name)) {
    throw new UnknownOptionError(option.name, opts.flags ?? []);
  }
}
function setDefaultValues(ctx, opts) {
  if (!opts.flags?.length) {
    return;
  }
  for (const option of opts.flags) {
    let name2;
    let defaultValue = void 0;
    if (option.name.startsWith("no-")) {
      const propName = option.name.replace(/^no-/, "");
      if (typeof ctx.flags[propName] !== "undefined") {
        continue;
      }
      const positiveOption = getOption(opts.flags, propName);
      if (positiveOption) {
        continue;
      }
      name2 = paramCaseToCamelCase(propName);
      defaultValue = true;
    }
    if (!name2) {
      name2 = paramCaseToCamelCase(option.name);
    }
    const hasDefaultValue = (!opts.ignoreDefaults || typeof opts.ignoreDefaults[name2] === "undefined") && typeof ctx.flags[name2] === "undefined" && (typeof option.default !== "undefined" || typeof defaultValue !== "undefined");
    if (hasDefaultValue) {
      ctx.flags[name2] = getDefaultValue(option) ?? defaultValue;
      ctx.defaults[option.name] = true;
      if (typeof option.value === "function") {
        ctx.flags[name2] = option.value(ctx.flags[name2]);
      }
    }
  }
}
function validateStandaloneOption(ctx, options, optionNames) {
  if (!ctx.standalone || optionNames.length === 1) {
    return;
  }
  for (const [_3, opt] of options) {
    if (!ctx.defaults[opt.name] && opt !== ctx.standalone) {
      throw new OptionNotCombinableError(ctx.standalone.name);
    }
  }
}
function validateConflictingOptions(ctx, option) {
  if (!option.conflicts?.length) {
    return;
  }
  for (const flag of option.conflicts) {
    if (isset(flag, ctx.flags)) {
      throw new ConflictingOptionError(option.name, flag);
    }
  }
}
function validateDependingOptions(ctx, option) {
  if (!option.depends) {
    return;
  }
  for (const flag of option.depends) {
    if (!isset(flag, ctx.flags) && !ctx.defaults[option.name]) {
      throw new DependingOptionError(option.name, flag);
    }
  }
}
function validateRequiredValues(ctx, option, name2) {
  if (!option.args) {
    return;
  }
  const isArray6 = option.args.length > 1;
  for (let i6 = 0; i6 < option.args.length; i6++) {
    const arg = option.args[i6];
    if (arg.optional) {
      continue;
    }
    const hasValue = isArray6 ? typeof ctx.flags[name2][i6] !== "undefined" : typeof ctx.flags[name2] !== "undefined";
    if (!hasValue) {
      throw new MissingOptionValueError(option.name);
    }
  }
}
function validateRequiredOptions(ctx, options, opts) {
  if (!opts.flags?.length) {
    return;
  }
  const optionsValues = [...options.values()];
  for (const option of opts.flags) {
    if (!option.required || paramCaseToCamelCase(option.name) in ctx.flags) {
      continue;
    }
    const conflicts = option.conflicts ?? [];
    const hasConflict = conflicts.find((flag) => !!ctx.flags[flag]);
    const hasConflicts = hasConflict || optionsValues.find(
      (opt) => opt.conflicts?.find((flag) => flag === option.name)
    );
    if (hasConflicts) {
      continue;
    }
    throw new MissingRequiredOptionError(option.name);
  }
}
function isset(flagName, flags) {
  const name2 = paramCaseToCamelCase(flagName);
  return typeof flags[name2] !== "undefined";
}

// https://deno.land/x/cliffy@v1.0.0-rc.3/flags/types/integer.ts
var integer = (type4) => {
  const value = Number(type4.value);
  if (Number.isInteger(value)) {
    return value;
  }
  throw new InvalidTypeError(type4);
};

// https://deno.land/x/cliffy@v1.0.0-rc.3/flags/flags.ts
var DefaultTypes = {
  string,
  number,
  integer,
  boolean
};
function parseFlags(argsOrCtx, opts = {}) {
  let args;
  let ctx;
  if (Array.isArray(argsOrCtx)) {
    ctx = {};
    args = argsOrCtx;
  } else {
    ctx = argsOrCtx;
    args = argsOrCtx.unknown;
    argsOrCtx.unknown = [];
  }
  args = args.slice();
  ctx.flags ??= {};
  ctx.literal ??= [];
  ctx.unknown ??= [];
  ctx.stopEarly = false;
  ctx.stopOnUnknown = false;
  ctx.defaults ??= {};
  opts.dotted ??= true;
  validateOptions(opts);
  const options = parseArgs(ctx, args, opts);
  validateFlags(ctx, opts, options);
  if (opts.dotted) {
    parseDottedOptions(ctx);
  }
  return ctx;
}
function validateOptions(opts) {
  opts.flags?.forEach((opt) => {
    opt.depends?.forEach((flag) => {
      if (!opts.flags || !getOption(opts.flags, flag)) {
        throw new UnknownRequiredOptionError(flag, opts.flags ?? []);
      }
    });
    opt.conflicts?.forEach((flag) => {
      if (!opts.flags || !getOption(opts.flags, flag)) {
        throw new UnknownConflictingOptionError(flag, opts.flags ?? []);
      }
    });
  });
}
function parseArgs(ctx, args, opts) {
  const optionsMap = /* @__PURE__ */ new Map();
  let inLiteral = false;
  for (let argsIndex = 0; argsIndex < args.length; argsIndex++) {
    let parseNext = function(option2) {
      if (negate) {
        setFlagValue(false);
        return;
      } else if (!option2.args?.length) {
        setFlagValue(void 0);
        return;
      }
      const arg = option2.args[optionArgsIndex];
      if (!arg) {
        const flag = next();
        throw new UnknownOptionError(flag, opts.flags ?? []);
      }
      if (!arg.type) {
        arg.type = "boolean" /* BOOLEAN */;
      }
      if (!option2.args?.length && arg.type === "boolean" /* BOOLEAN */ && arg.optional === void 0) {
        arg.optional = true;
      }
      if (arg.optional) {
        inOptionalArg = true;
      } else if (inOptionalArg) {
        throw new UnexpectedRequiredArgumentError(option2.name);
      }
      let result2;
      let increase = false;
      if (arg.list && hasNext(arg)) {
        const parsed = next().split(arg.separator || ",").map((nextValue) => {
          const value = parseValue(option2, arg, nextValue);
          if (typeof value === "undefined") {
            throw new InvalidOptionValueError(
              option2.name,
              arg.type ?? "?",
              nextValue
            );
          }
          return value;
        });
        if (parsed?.length) {
          result2 = parsed;
        }
      } else {
        if (hasNext(arg)) {
          result2 = parseValue(option2, arg, next());
        } else if (arg.optional && arg.type === "boolean" /* BOOLEAN */) {
          result2 = true;
        }
      }
      if (increase && typeof currentValue === "undefined") {
        argsIndex++;
        if (!arg.variadic) {
          optionArgsIndex++;
        } else if (option2.args[optionArgsIndex + 1]) {
          throw new UnexpectedArgumentAfterVariadicArgumentError(next());
        }
      }
      if (typeof result2 !== "undefined" && (option2.args.length > 1 || arg.variadic)) {
        if (!ctx.flags[propName]) {
          setFlagValue([]);
        }
        ctx.flags[propName].push(result2);
        if (hasNext(arg)) {
          parseNext(option2);
        }
      } else {
        setFlagValue(result2);
      }
      function hasNext(arg2) {
        if (!option2.args?.length) {
          return false;
        }
        const nextValue = currentValue ?? args[argsIndex + 1];
        if (!nextValue) {
          return false;
        }
        if (option2.args.length > 1 && optionArgsIndex >= option2.args.length) {
          return false;
        }
        if (!arg2.optional) {
          return true;
        }
        if (option2.equalsSign && arg2.optional && !arg2.variadic && typeof currentValue === "undefined") {
          return false;
        }
        if (arg2.optional || arg2.variadic) {
          return nextValue[0] !== "-" || typeof currentValue !== "undefined" || arg2.type === "number" /* NUMBER */ && !isNaN(Number(nextValue));
        }
        return false;
      }
      function parseValue(option3, arg2, value) {
        const result3 = opts.parse ? opts.parse({
          label: "Option",
          type: arg2.type || "string" /* STRING */,
          name: `--${option3.name}`,
          value
        }) : parseDefaultType(option3, arg2, value);
        if (typeof result3 !== "undefined") {
          increase = true;
        }
        return result3;
      }
    }, setFlagValue = function(value) {
      ctx.flags[propName] = value;
      if (ctx.defaults[propName]) {
        delete ctx.defaults[propName];
      }
    };
    let option;
    let current3 = args[argsIndex];
    let currentValue;
    let negate = false;
    if (inLiteral) {
      ctx.literal.push(current3);
      continue;
    } else if (current3 === "--") {
      inLiteral = true;
      continue;
    } else if (ctx.stopEarly || ctx.stopOnUnknown) {
      ctx.unknown.push(current3);
      continue;
    }
    const isFlag = current3.length > 1 && current3[0] === "-";
    if (!isFlag) {
      if (opts.stopEarly) {
        ctx.stopEarly = true;
      }
      ctx.unknown.push(current3);
      continue;
    }
    const isShort = current3[1] !== "-";
    const isLong = isShort ? false : current3.length > 3 && current3[2] !== "-";
    if (!isShort && !isLong) {
      throw new InvalidOptionError(current3, opts.flags ?? []);
    }
    if (isShort && current3.length > 2 && current3[2] !== ".") {
      args.splice(argsIndex, 1, ...splitFlags(current3));
      current3 = args[argsIndex];
    } else if (isLong && current3.startsWith("--no-")) {
      negate = true;
    }
    const equalSignIndex = current3.indexOf("=");
    if (equalSignIndex !== -1) {
      currentValue = current3.slice(equalSignIndex + 1) || void 0;
      current3 = current3.slice(0, equalSignIndex);
    }
    if (opts.flags) {
      option = getOption(opts.flags, current3);
      if (!option) {
        const name2 = current3.replace(/^-+/, "");
        option = matchWildCardOptions(name2, opts.flags);
        if (!option) {
          if (opts.stopOnUnknown) {
            ctx.stopOnUnknown = true;
            ctx.unknown.push(args[argsIndex]);
            continue;
          }
          throw new UnknownOptionError(current3, opts.flags);
        }
      }
    } else {
      option = {
        name: current3.replace(/^-+/, ""),
        optionalValue: true,
        type: "string" /* STRING */
      };
    }
    if (option.standalone) {
      ctx.standalone = option;
    }
    const positiveName = negate ? option.name.replace(/^no-?/, "") : option.name;
    const propName = paramCaseToCamelCase(positiveName);
    if (typeof ctx.flags[propName] !== "undefined") {
      if (!opts.flags?.length) {
        option.collect = true;
      } else if (!option.collect && !ctx.defaults[option.name]) {
        throw new DuplicateOptionError(current3);
      }
    }
    if (option.type && !option.args?.length) {
      option.args = [{
        type: option.type,
        optional: option.optionalValue,
        variadic: option.variadic,
        list: option.list,
        separator: option.separator
      }];
    }
    if (opts.flags?.length && !option.args?.length && typeof currentValue !== "undefined") {
      throw new UnexpectedOptionValueError(option.name, currentValue);
    }
    let optionArgsIndex = 0;
    let inOptionalArg = false;
    const next = () => currentValue ?? args[argsIndex + 1];
    const previous = ctx.flags[propName];
    parseNext(option);
    if (typeof ctx.flags[propName] === "undefined") {
      if (option.args?.length && !option.args?.[optionArgsIndex].optional) {
        throw new MissingOptionValueError(option.name);
      } else if (typeof option.default !== "undefined" && (option.type || option.value || option.args?.length)) {
        ctx.flags[propName] = getDefaultValue(option);
      } else {
        setFlagValue(true);
      }
    }
    if (option.value) {
      const value = option.value(ctx.flags[propName], previous);
      setFlagValue(value);
    } else if (option.collect) {
      const value = typeof previous !== "undefined" ? Array.isArray(previous) ? previous : [previous] : [];
      value.push(ctx.flags[propName]);
      setFlagValue(value);
    }
    optionsMap.set(propName, option);
    opts.option?.(option, ctx.flags[propName]);
  }
  return optionsMap;
}
function parseDottedOptions(ctx) {
  ctx.flags = Object.keys(ctx.flags).reduce(
    (result2, key) => {
      if (~key.indexOf(".")) {
        key.split(".").reduce(
          (result3, subKey, index2, parts) => {
            if (index2 === parts.length - 1) {
              result3[subKey] = ctx.flags[key];
            } else {
              result3[subKey] = result3[subKey] ?? {};
            }
            return result3[subKey];
          },
          result2
        );
      } else {
        result2[key] = ctx.flags[key];
      }
      return result2;
    },
    {}
  );
}
function splitFlags(flag) {
  flag = flag.slice(1);
  const normalized = [];
  const index2 = flag.indexOf("=");
  const flags = (index2 !== -1 ? flag.slice(0, index2) : flag).split("");
  if (isNaN(Number(flag[flag.length - 1]))) {
    flags.forEach((val) => normalized.push(`-${val}`));
  } else {
    normalized.push(`-${flags.shift()}`);
    if (flags.length) {
      normalized.push(flags.join(""));
    }
  }
  if (index2 !== -1) {
    normalized[normalized.length - 1] += flag.slice(index2);
  }
  return normalized;
}
function parseDefaultType(option, arg, value) {
  const type4 = arg.type || "string" /* STRING */;
  const parseType = DefaultTypes[type4];
  if (!parseType) {
    throw new UnknownTypeError(type4, Object.keys(DefaultTypes));
  }
  return parseType({
    label: "Option",
    type: type4,
    name: `--${option.name}`,
    value
  });
}

// https://deno.land/x/cliffy@v1.0.0-rc.3/command/_utils.ts
function didYouMeanCommand(command, commands2, excludes = []) {
  const commandNames = commands2.map((command2) => command2.getName()).filter((command2) => !excludes.includes(command2));
  return didYouMean(" Did you mean command", command, commandNames);
}
var ARGUMENT_REGEX = /^[<\[].+[\]>]$/;
var ARGUMENT_DETAILS_REGEX = /[<\[:>\]]/;
function splitArguments(args) {
  const parts = args.trim().split(/[, =] */g);
  const typeParts = [];
  while (parts[parts.length - 1] && ARGUMENT_REGEX.test(parts[parts.length - 1])) {
    typeParts.unshift(parts.pop());
  }
  const typeDefinition = typeParts.join(" ");
  return { flags: parts, typeDefinition, equalsSign: args.includes("=") };
}
function parseArgumentsDefinition(argsDefinition, validate2 = true, all2) {
  const argumentDetails = [];
  let hasOptional = false;
  let hasVariadic = false;
  const parts = argsDefinition.split(/ +/);
  for (const arg of parts) {
    if (validate2 && hasVariadic) {
      throw new UnexpectedArgumentAfterVariadicArgumentError(arg);
    }
    const parts2 = arg.split(ARGUMENT_DETAILS_REGEX);
    if (!parts2[1]) {
      if (all2) {
        argumentDetails.push(parts2[0]);
      }
      continue;
    }
    const type4 = parts2[2] || "string" /* STRING */;
    const details = {
      optional: arg[0] === "[",
      name: parts2[1],
      action: parts2[3] || type4,
      variadic: false,
      list: type4 ? arg.indexOf(type4 + "[]") !== -1 : false,
      type: type4
    };
    if (validate2 && !details.optional && hasOptional) {
      throw new UnexpectedRequiredArgumentError(details.name);
    }
    if (arg[0] === "[") {
      hasOptional = true;
    }
    if (details.name.length > 3) {
      const istVariadicLeft = details.name.slice(0, 3) === "...";
      const istVariadicRight = details.name.slice(-3) === "...";
      hasVariadic = details.variadic = istVariadicLeft || istVariadicRight;
      if (istVariadicLeft) {
        details.name = details.name.slice(3);
      } else if (istVariadicRight) {
        details.name = details.name.slice(0, -3);
      }
    }
    argumentDetails.push(details);
  }
  return argumentDetails;
}
function dedent(str3) {
  const lines2 = str3.split(/\r?\n|\r/g);
  let text = "";
  let indent = 0;
  for (const line of lines2) {
    if (text || line.trim()) {
      if (!text) {
        text = line.trimStart();
        indent = line.length - text.length;
      } else {
        text += line.slice(indent);
      }
      text += "\n";
    }
  }
  return text.trimEnd();
}
function getDescription(description, short) {
  return short ? description.trim().split("\n", 1)[0].trim() : dedent(description);
}

// https://deno.land/std@0.196.0/fmt/colors.ts
var colors_exports = {};
__export(colors_exports, {
  bgBlack: () => bgBlack,
  bgBlue: () => bgBlue,
  bgBrightBlack: () => bgBrightBlack,
  bgBrightBlue: () => bgBrightBlue,
  bgBrightCyan: () => bgBrightCyan,
  bgBrightGreen: () => bgBrightGreen,
  bgBrightMagenta: () => bgBrightMagenta,
  bgBrightRed: () => bgBrightRed,
  bgBrightWhite: () => bgBrightWhite,
  bgBrightYellow: () => bgBrightYellow,
  bgCyan: () => bgCyan,
  bgGreen: () => bgGreen,
  bgMagenta: () => bgMagenta,
  bgRed: () => bgRed,
  bgRgb24: () => bgRgb24,
  bgRgb8: () => bgRgb8,
  bgWhite: () => bgWhite,
  bgYellow: () => bgYellow,
  black: () => black,
  blue: () => blue2,
  bold: () => bold2,
  brightBlack: () => brightBlack,
  brightBlue: () => brightBlue,
  brightCyan: () => brightCyan,
  brightGreen: () => brightGreen,
  brightMagenta: () => brightMagenta,
  brightRed: () => brightRed,
  brightWhite: () => brightWhite,
  brightYellow: () => brightYellow,
  cyan: () => cyan,
  dim: () => dim,
  getColorEnabled: () => getColorEnabled,
  gray: () => gray,
  green: () => green,
  hidden: () => hidden,
  inverse: () => inverse,
  italic: () => italic,
  magenta: () => magenta,
  red: () => red2,
  reset: () => reset,
  rgb24: () => rgb24,
  rgb8: () => rgb8,
  setColorEnabled: () => setColorEnabled,
  strikethrough: () => strikethrough,
  stripColor: () => stripColor,
  underline: () => underline,
  white: () => white,
  yellow: () => yellow2
});
var { Deno: Deno3 } = globalThis;
var noColor2 = typeof Deno3?.noColor === "boolean" ? Deno3.noColor : false;
var enabled2 = !noColor2;
function setColorEnabled(value) {
  if (Deno3?.noColor) {
    return;
  }
  enabled2 = value;
}
function getColorEnabled() {
  return enabled2;
}
function code2(open, close) {
  return {
    open: `\x1B[${open.join(";")}m`,
    close: `\x1B[${close}m`,
    regexp: new RegExp(`\\x1b\\[${close}m`, "g")
  };
}
function run2(str3, code5) {
  return enabled2 ? `${code5.open}${str3.replace(code5.regexp, code5.open)}${code5.close}` : str3;
}
function reset(str3) {
  return run2(str3, code2([0], 0));
}
function bold2(str3) {
  return run2(str3, code2([1], 22));
}
function dim(str3) {
  return run2(str3, code2([2], 22));
}
function italic(str3) {
  return run2(str3, code2([3], 23));
}
function underline(str3) {
  return run2(str3, code2([4], 24));
}
function inverse(str3) {
  return run2(str3, code2([7], 27));
}
function hidden(str3) {
  return run2(str3, code2([8], 28));
}
function strikethrough(str3) {
  return run2(str3, code2([9], 29));
}
function black(str3) {
  return run2(str3, code2([30], 39));
}
function red2(str3) {
  return run2(str3, code2([31], 39));
}
function green(str3) {
  return run2(str3, code2([32], 39));
}
function yellow2(str3) {
  return run2(str3, code2([33], 39));
}
function blue2(str3) {
  return run2(str3, code2([34], 39));
}
function magenta(str3) {
  return run2(str3, code2([35], 39));
}
function cyan(str3) {
  return run2(str3, code2([36], 39));
}
function white(str3) {
  return run2(str3, code2([37], 39));
}
function gray(str3) {
  return brightBlack(str3);
}
function brightBlack(str3) {
  return run2(str3, code2([90], 39));
}
function brightRed(str3) {
  return run2(str3, code2([91], 39));
}
function brightGreen(str3) {
  return run2(str3, code2([92], 39));
}
function brightYellow(str3) {
  return run2(str3, code2([93], 39));
}
function brightBlue(str3) {
  return run2(str3, code2([94], 39));
}
function brightMagenta(str3) {
  return run2(str3, code2([95], 39));
}
function brightCyan(str3) {
  return run2(str3, code2([96], 39));
}
function brightWhite(str3) {
  return run2(str3, code2([97], 39));
}
function bgBlack(str3) {
  return run2(str3, code2([40], 49));
}
function bgRed(str3) {
  return run2(str3, code2([41], 49));
}
function bgGreen(str3) {
  return run2(str3, code2([42], 49));
}
function bgYellow(str3) {
  return run2(str3, code2([43], 49));
}
function bgBlue(str3) {
  return run2(str3, code2([44], 49));
}
function bgMagenta(str3) {
  return run2(str3, code2([45], 49));
}
function bgCyan(str3) {
  return run2(str3, code2([46], 49));
}
function bgWhite(str3) {
  return run2(str3, code2([47], 49));
}
function bgBrightBlack(str3) {
  return run2(str3, code2([100], 49));
}
function bgBrightRed(str3) {
  return run2(str3, code2([101], 49));
}
function bgBrightGreen(str3) {
  return run2(str3, code2([102], 49));
}
function bgBrightYellow(str3) {
  return run2(str3, code2([103], 49));
}
function bgBrightBlue(str3) {
  return run2(str3, code2([104], 49));
}
function bgBrightMagenta(str3) {
  return run2(str3, code2([105], 49));
}
function bgBrightCyan(str3) {
  return run2(str3, code2([106], 49));
}
function bgBrightWhite(str3) {
  return run2(str3, code2([107], 49));
}
function clampAndTruncate(n5, max = 255, min2 = 0) {
  return Math.trunc(Math.max(Math.min(n5, max), min2));
}
function rgb8(str3, color) {
  return run2(str3, code2([38, 5, clampAndTruncate(color)], 39));
}
function bgRgb8(str3, color) {
  return run2(str3, code2([48, 5, clampAndTruncate(color)], 49));
}
function rgb24(str3, color) {
  if (typeof color === "number") {
    return run2(
      str3,
      code2(
        [38, 2, color >> 16 & 255, color >> 8 & 255, color & 255],
        39
      )
    );
  }
  return run2(
    str3,
    code2(
      [
        38,
        2,
        clampAndTruncate(color.r),
        clampAndTruncate(color.g),
        clampAndTruncate(color.b)
      ],
      39
    )
  );
}
function bgRgb24(str3, color) {
  if (typeof color === "number") {
    return run2(
      str3,
      code2(
        [48, 2, color >> 16 & 255, color >> 8 & 255, color & 255],
        49
      )
    );
  }
  return run2(
    str3,
    code2(
      [
        48,
        2,
        clampAndTruncate(color.r),
        clampAndTruncate(color.g),
        clampAndTruncate(color.b)
      ],
      49
    )
  );
}
var ANSI_PATTERN2 = new RegExp(
  [
    "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
    "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"
  ].join("|"),
  "g"
);
function stripColor(string2) {
  return string2.replace(ANSI_PATTERN2, "");
}

// https://deno.land/x/cliffy@v1.0.0-rc.3/command/_errors.ts
var CommandError = class _CommandError extends Error {
  constructor(message) {
    super(message);
    Object.setPrototypeOf(this, _CommandError.prototype);
  }
};
var ValidationError2 = class _ValidationError extends CommandError {
  exitCode;
  cmd;
  constructor(message, { exitCode } = {}) {
    super(message);
    Object.setPrototypeOf(this, _ValidationError.prototype);
    this.exitCode = exitCode ?? 2;
  }
};
var DuplicateOptionNameError = class _DuplicateOptionNameError extends CommandError {
  constructor(optionName, commandName) {
    super(
      `An option with name '${bold2(getFlag(optionName))}' is already registered on command '${bold2(commandName)}'. If it is intended to override the option, set the '${bold2("override")}' option of the '${bold2("option")}' method to true.`
    );
    Object.setPrototypeOf(this, _DuplicateOptionNameError.prototype);
  }
};
var MissingCommandNameCompletionsError = class _MissingCommandNameCompletionsError extends CommandError {
  constructor(shell) {
    super(
      `Failed to generate shell completions. Missing main command name. Use '${bold2('cmd.name("<comand-name>")')}' to set the name of the main command or use the '${bold2("--name")}' option from the '${bold2("completions")}' command to set the cli name: '${bold2(`<command> completions ${shell} --name <cli-name>`)}'.`
    );
    Object.setPrototypeOf(
      this,
      _MissingCommandNameCompletionsError.prototype
    );
  }
};
var MissingCommandNameError = class _MissingCommandNameError extends CommandError {
  constructor() {
    super("Missing command name.");
    Object.setPrototypeOf(this, _MissingCommandNameError.prototype);
  }
};
var DuplicateCommandNameError = class _DuplicateCommandNameError extends CommandError {
  constructor(name2) {
    super(`Duplicate command name "${name2}".`);
    Object.setPrototypeOf(this, _DuplicateCommandNameError.prototype);
  }
};
var DuplicateCommandAliasError = class _DuplicateCommandAliasError extends CommandError {
  constructor(alias) {
    super(`Duplicate command alias "${alias}".`);
    Object.setPrototypeOf(this, _DuplicateCommandAliasError.prototype);
  }
};
var CommandNotFoundError = class _CommandNotFoundError extends CommandError {
  constructor(name2, commands2, excluded) {
    super(
      `Unknown command "${name2}".${didYouMeanCommand(name2, commands2, excluded)}`
    );
    Object.setPrototypeOf(this, _CommandNotFoundError.prototype);
  }
};
var DuplicateTypeError = class _DuplicateTypeError extends CommandError {
  constructor(name2) {
    super(`Type with name "${name2}" already exists.`);
    Object.setPrototypeOf(this, _DuplicateTypeError.prototype);
  }
};
var DuplicateCompletionError = class _DuplicateCompletionError extends CommandError {
  constructor(name2) {
    super(`Completion with name "${name2}" already exists.`);
    Object.setPrototypeOf(this, _DuplicateCompletionError.prototype);
  }
};
var DuplicateExampleError = class _DuplicateExampleError extends CommandError {
  constructor(name2) {
    super(`Example with name "${name2}" already exists.`);
    Object.setPrototypeOf(this, _DuplicateExampleError.prototype);
  }
};
var DuplicateEnvVarError = class _DuplicateEnvVarError extends CommandError {
  constructor(name2) {
    super(`Environment variable with name "${name2}" already exists.`);
    Object.setPrototypeOf(this, _DuplicateEnvVarError.prototype);
  }
};
var MissingRequiredEnvVarError = class _MissingRequiredEnvVarError extends ValidationError2 {
  constructor(envVar) {
    super(`Missing required environment variable "${envVar.names[0]}".`);
    Object.setPrototypeOf(this, _MissingRequiredEnvVarError.prototype);
  }
};
var TooManyEnvVarValuesError = class _TooManyEnvVarValuesError extends CommandError {
  constructor(name2) {
    super(
      `An environment variable can only have one value, but "${name2}" has more than one.`
    );
    Object.setPrototypeOf(this, _TooManyEnvVarValuesError.prototype);
  }
};
var UnexpectedOptionalEnvVarValueError = class _UnexpectedOptionalEnvVarValueError extends CommandError {
  constructor(name2) {
    super(
      `An environment variable cannot have an optional value, but "${name2}" is defined as optional.`
    );
    Object.setPrototypeOf(this, _UnexpectedOptionalEnvVarValueError.prototype);
  }
};
var UnexpectedVariadicEnvVarValueError = class _UnexpectedVariadicEnvVarValueError extends CommandError {
  constructor(name2) {
    super(
      `An environment variable cannot have an variadic value, but "${name2}" is defined as variadic.`
    );
    Object.setPrototypeOf(this, _UnexpectedVariadicEnvVarValueError.prototype);
  }
};
var DefaultCommandNotFoundError = class _DefaultCommandNotFoundError extends CommandError {
  constructor(name2, commands2) {
    super(
      `Default command "${name2}" not found.${didYouMeanCommand(name2, commands2)}`
    );
    Object.setPrototypeOf(this, _DefaultCommandNotFoundError.prototype);
  }
};
var CommandExecutableNotFoundError = class _CommandExecutableNotFoundError extends CommandError {
  constructor(name2) {
    super(
      `Command executable not found: ${name2}`
    );
    Object.setPrototypeOf(this, _CommandExecutableNotFoundError.prototype);
  }
};
var UnknownCompletionCommandError = class _UnknownCompletionCommandError extends CommandError {
  constructor(name2, commands2) {
    super(
      `Auto-completion failed. Unknown command "${name2}".${didYouMeanCommand(name2, commands2)}`
    );
    Object.setPrototypeOf(this, _UnknownCompletionCommandError.prototype);
  }
};
var UnknownCommandError = class _UnknownCommandError extends ValidationError2 {
  constructor(name2, commands2, excluded) {
    super(
      `Unknown command "${name2}".${didYouMeanCommand(name2, commands2, excluded)}`
    );
    Object.setPrototypeOf(this, _UnknownCommandError.prototype);
  }
};
var NoArgumentsAllowedError = class _NoArgumentsAllowedError extends ValidationError2 {
  constructor(name2) {
    super(`No arguments allowed for command "${name2}".`);
    Object.setPrototypeOf(this, _NoArgumentsAllowedError.prototype);
  }
};
var MissingArgumentsError = class _MissingArgumentsError extends ValidationError2 {
  constructor(names) {
    super(`Missing argument(s): ${names.join(", ")}`);
    Object.setPrototypeOf(this, _MissingArgumentsError.prototype);
  }
};
var MissingArgumentError = class _MissingArgumentError extends ValidationError2 {
  constructor(name2) {
    super(`Missing argument: ${name2}`);
    Object.setPrototypeOf(this, _MissingArgumentError.prototype);
  }
};
var TooManyArgumentsError = class _TooManyArgumentsError extends ValidationError2 {
  constructor(args) {
    super(`Too many arguments: ${args.join(" ")}`);
    Object.setPrototypeOf(this, _TooManyArgumentsError.prototype);
  }
};

// https://deno.land/x/cliffy@v1.0.0-rc.3/command/type.ts
var Type = class {
};

// https://deno.land/x/cliffy@v1.0.0-rc.3/command/types/boolean.ts
var BooleanType = class extends Type {
  /** Parse boolean type. */
  parse(type4) {
    return boolean(type4);
  }
  /** Complete boolean type. */
  complete() {
    return ["true", "false"];
  }
};

// https://deno.land/x/cliffy@v1.0.0-rc.3/command/types/string.ts
var StringType = class extends Type {
  /** Complete string type. */
  parse(type4) {
    return string(type4);
  }
};

// https://deno.land/x/cliffy@v1.0.0-rc.3/command/types/file.ts
var FileType = class extends StringType {
  constructor() {
    super();
  }
  // getOptions(): FileTypeOptions {
  //   return this.opts;
  // }
};

// https://deno.land/x/cliffy@v1.0.0-rc.3/command/types/integer.ts
var IntegerType = class extends Type {
  /** Parse integer type. */
  parse(type4) {
    return integer(type4);
  }
};

// https://deno.land/x/cliffy@v1.0.0-rc.3/command/types/number.ts
var NumberType = class extends Type {
  /** Parse number type. */
  parse(type4) {
    return number(type4);
  }
};

// https://deno.land/x/cliffy@v1.0.0-rc.3/table/border.ts
var border = {
  top: "\u2500",
  topMid: "\u252C",
  topLeft: "\u250C",
  topRight: "\u2510",
  bottom: "\u2500",
  bottomMid: "\u2534",
  bottomLeft: "\u2514",
  bottomRight: "\u2518",
  left: "\u2502",
  leftMid: "\u251C",
  mid: "\u2500",
  midMid: "\u253C",
  right: "\u2502",
  rightMid: "\u2524",
  middle: "\u2502"
};

// https://deno.land/x/cliffy@v1.0.0-rc.3/table/cell.ts
var Cell = class _Cell {
  /**
   * Cell constructor.
   *
   * @param value Cell value.
   */
  constructor(value) {
    this.value = value;
  }
  options = {};
  /** Get cell length. */
  get length() {
    return this.toString().length;
  }
  /**
   * Create a new cell. If value is a cell, the value and all options of the cell
   * will be copied to the new cell.
   *
   * @param value Cell or cell value.
   */
  static from(value) {
    let cell;
    if (value instanceof _Cell) {
      cell = new this(value.getValue());
      cell.options = { ...value.options };
    } else {
      cell = new this(value);
    }
    return cell;
  }
  /** Get cell string value. */
  toString() {
    return this.value.toString();
  }
  /** Get cell value. */
  getValue() {
    return this.value;
  }
  /**
   * Set cell value.
   *
   * @param value Cell or cell value.
   */
  setValue(value) {
    this.value = value;
    return this;
  }
  /**
   * Clone cell with all options.
   *
   * @param value Cell or cell value.
   */
  clone(value) {
    return _Cell.from(value ?? this);
  }
  /**
   * Setter:
   */
  /**
   * Enable/disable cell border.
   *
   * @param enable    Enable/disable cell border.
   * @param override  Override existing value.
   */
  border(enable = true, override = true) {
    if (override || typeof this.options.border === "undefined") {
      this.options.border = enable;
    }
    return this;
  }
  /**
   * Set col span.
   *
   * ```ts
   * import { Cell, Table } from "./mod.ts";
   *
   * new Table()
   *   .body([
   *     [
   *       new Cell("Row 1 & 2 Column 1").rowSpan(2),
   *       "Row 1 Column 2",
   *       "Row 1 Column 3",
   *     ],
   *     [new Cell("Row 2 Column 2 & 3").colSpan(2)],
   *   ])
   *   .border()
   *   .render();
   * ```
   *
   * @param span      Number of cols to span.
   * @param override  Override existing value.
   */
  colSpan(span, override = true) {
    if (override || typeof this.options.colSpan === "undefined") {
      this.options.colSpan = span;
    }
    return this;
  }
  /**
   * Set row span.
   *
   * ```ts
   * import { Cell, Table } from "./mod.ts";
   *
   * new Table()
   *   .body([
   *     [
   *       new Cell("Row 1 & 2 Column 1").rowSpan(2),
   *       "Row 1 Column 2",
   *       "Row 1 Column 3",
   *     ],
   *     [new Cell("Row 2 Column 2 & 3").colSpan(2)],
   *   ])
   *   .border()
   *   .render();
   * ```
   *
   * @param span      Number of rows to span.
   * @param override  Override existing value.
   */
  rowSpan(span, override = true) {
    if (override || typeof this.options.rowSpan === "undefined") {
      this.options.rowSpan = span;
    }
    return this;
  }
  /**
   * Align cell content.
   *
   * @param direction Align direction.
   * @param override  Override existing value.
   */
  align(direction, override = true) {
    if (override || typeof this.options.align === "undefined") {
      this.options.align = direction;
    }
    return this;
  }
  /**
   * Getter:
   */
  /** Check if cell has border. */
  getBorder() {
    return this.options.border === true;
  }
  /** Get col span. */
  getColSpan() {
    return typeof this.options.colSpan === "number" && this.options.colSpan > 0 ? this.options.colSpan : 1;
  }
  /** Get row span. */
  getRowSpan() {
    return typeof this.options.rowSpan === "number" && this.options.rowSpan > 0 ? this.options.rowSpan : 1;
  }
  /** Get row span. */
  getAlign() {
    return this.options.align ?? "left";
  }
};

// https://deno.land/x/cliffy@v1.0.0-rc.3/table/column.ts
var Column = class _Column {
  /**
   * Create a new cell from column options or an existing column.
   * @param options
   */
  static from(options) {
    const opts = options instanceof _Column ? options.opts : options;
    return new _Column().options(opts);
  }
  opts = {};
  /** Set column options. */
  options(options) {
    Object.assign(this.opts, options);
    return this;
  }
  /** Set min column width. */
  minWidth(width) {
    this.opts.minWidth = width;
    return this;
  }
  /** Set max column width. */
  maxWidth(width) {
    this.opts.maxWidth = width;
    return this;
  }
  /** Set column border. */
  border(border2 = true) {
    this.opts.border = border2;
    return this;
  }
  /** Set column padding. */
  padding(padding3) {
    this.opts.padding = padding3;
    return this;
  }
  /** Set column alignment. */
  align(direction) {
    this.opts.align = direction;
    return this;
  }
  /** Get min column width. */
  getMinWidth() {
    return this.opts.minWidth;
  }
  /** Get max column width. */
  getMaxWidth() {
    return this.opts.maxWidth;
  }
  /** Get column border. */
  getBorder() {
    return this.opts.border;
  }
  /** Get column padding. */
  getPadding() {
    return this.opts.padding;
  }
  /** Get column alignment. */
  getAlign() {
    return this.opts.align;
  }
};

// https://deno.land/std@0.224.0/cli/_data.json
var data_default = {
  UNICODE_VERSION: "15.0.0",
  tables: [
    {
      d: "AAECAwQFBgcICQoLDA0OAw8DDwkQCRESERIA",
      r: "AQEBAgEBAQEBAQEBAQEBBwEHAVABBwcBBwF4"
    },
    {
      d: "AAECAwQFBgcGCAYJCgsMDQ4PEAYREhMUBhUWFxgZGhscHR4fICEiIyIkJSYnKCkqJSssLS4vMDEyMzQ1Njc4OToGOzwKBj0GPj9AQUIGQwZEBkVGR0hJSktMTQZOBgoGT1BRUlNUVVZXWFkGWgZbBlxdXl1fYGFiY2RlZmdoBmlqBmsGAQZsBm1uO29wcXI7czt0dXZ3OwY7eHkGent8Bn0Gfn+AgYKDhIWGBoc7iAZdO4kGiosGAXGMBo0GjgaPBpAGkQaSBpMGlJUGlpcGmJmam5ydnp+gLgahLKIGo6SlpganqKmqqwasBq0Grq8GsLGyswa0BrUGtre4Brm6uwZHvAa9vga/wME7wjvDxAbFO8bHO8gGyQbKywbMzQbOBs/Q0QbSBr8GvgbT1AbUBtUG1gbXBtjZ2tsG3N0G3t/g4eLjO+Tl5ufoO+k76gbrBuztOwbu7/AGO+XxCgYKCwZd8g==",
      r: "AQEBAQEBAQEBAQEBAQEBAQEBAQMBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQECBQEOAQEBAQEBAQEBAwEBAQEBAQEBAQIBAwEIAQEBAQEBAQEBAQEBAQIBAQEBAQEBAQEBAQEBAQEBDQEBBQEBAQEBAgEBAwEBAQEBAQEBAQEBbQHaAQEFAQEBBAECAQEBAQEBAQEBAwGuASFkCAELAQEBAQEBAQEHAQMBAQEaAQIBCAEFAQEBAQEBAQEBAQEBAQEBAQEBAQECAQEBAQIBAQEBAQEBAwEDAQEBAQEBAQUBAQEBAQEBBAEBAVIBAdkBARABAQFfARMBAYoBBAEBBQEmAUkBAQcBAQIBHgEBARUBAQEBAQUBAQcBDwEBARoBAgEBAQEBAQECAQEBAQEBAQEBAQEBAQEBAQMBBAEBAgEBAQEUfwEBAQIDAXj/AQ=="
    },
    {
      d: "AFUVAF3Xd3X/93//VXVVV9VX9V91f1/31X93XVXdVdVV9dVV/VVX1X9X/131VfXVVXV3V1VdVV1V1/1dV1X/3VUAVf3/3/9fVf3/3/9fVV1V/11VFQBQVQEAEEEQVQBQVQBAVFUVAFVUVQUAEAAUBFBVFVFVAEBVBQBUVRUAVVFVBRAAAVBVAVVQVQBVBQBAVUVUAQBUUQEAVQVVUVVUAVRVUVUFVUVBVVRBFRRQUVVQUVUBEFRRVQVVBQBRVRQBVFVRVUFVBVVFVVRVUVVUVQRUBQRQVUFVBVVFVVBVBVVQVRVUAVRVUVUFVVFVRVUFRFVRAEBVFQBAVVEAVFUAQFVQVRFRVQEAQAAEVQEAAQBUVUVVAQQAQVVQBVRVAVRVRUFVUVVRVaoAVQFVBVRVBVUFVQVVEABQVUUBAFVRVRUAVUFVUVVAFVRVRVUBVRUUVUUAQEQBAFQVABRVAEBVAFUEQFRFVRUAVVBVBVAQUFVFUBFQVQAFVUAABABUUVVUUFUVANd/X3//BUD3XdV1VQAEAFVXVdX9V1VXVQBUVdVdVdV1VX111VXVV9V//1X/X1VdVf9fVV9VdVdV1VX31dfVXXX9193/d1X/VV9VV3VVX//1VfVVXVVdVdVVdVWlVWlVqVaWVf/f/1X/Vf/1X1Xf/19V9VVf9df1X1X1X1XVVWlVfV31VVpVd1V3VapV33/fVZVVlVX1WVWlVelV+v/v//7/31Xv/6/77/tVWaVVVlVdVWaVmlX1/1WpVVZVlVWVVlVW+V9VFVBVAKqaqlWqWlWqVaoKoKpqqapqgapVqaqpqmqqVapqqv+qVqpqVRVAAFBVBVVQVUUVVUFVVFVQVQBQVRVVBQBQVRUAUFWqVkBVFQVQVVFVAUBBVRVVVFVUVQQUVAVRVVBVRVVRVFFVqlVFVQCqWlUAqmqqaqpVqlZVqmpVAV1VUVVUVQVAVQFBVQBVQBVVQVUAVRVUVQFVBQBUVQVQVVFVAEBVFFRVFVBVFUBBUUVVUVVAVRUAAQBUVRVVUFUFAEBVARRVFVAEVUVVFQBAVVRVBQBUAFRVAAVEVUVVFQBEFQRVBVBVEFRVUFUVAEARVFUVUQAQVQEFEABVFQBBVRVEFVUABVVUVQEAQFUVABRAVRVVAUABVQUAQFBVAEAAEFUFAAUABEFVAUBFEAAQVVARVRVUVVBVBUBVRFVUFQBQVQBUVQBAVRVVFUBVqlRVWlWqVapaVapWVaqpqmmqalVlVWpZVapVqlVBAFUAUABAVRVQVRUAQAEAVQVQVQVUVQBAFQBUVVFVVFUVAAEAVQBAABQAEARAVUVVAFUAQFUAQFVWVZVV/39V/1//X1X/76uq6v9XVWpVqlWqVlVaVapaVapWVamqmqqmqlWqapWqVapWqmqmqpaqWlWVaqpVZVVpVVZVlapVqlpVVmqpVapVlVZVqlZVqlVWVapqqpqqVapWqlZVqpqqWlWlqlWqVlWqVlVRVQD/Xw==",
      r: "CBcBCAEBAQEBAQEBAQECAQEBAQEBAQEBAQEBAQMBAQECAQEBAQEBAQEBAQEBBAEBGAEDAQwBAwEIAQEBAQEBAQgcCAEDAQEBAQEDAQEBDQEDEAELAQEBEQEKAQEBDgEBAgIBAQoBBQQBCAEBAQEBAQEHAQEHBgEWAQIBDQECAgEFAQECAgEKAQ0BAQIKAQ0BDQEBAQEBAQEBAgEHAQ4BAQEBAQQBBgEBDgEBAQEBAQcBAQIBAQEBBAEFAQEBDgEBAQEBAQECAQcBDwECAQwCDQEBAQEBAQECAQgBAQEEAQcBDQEBAQEBAQQBBwERAQEBARYBAQECAQEBGAECAQIBARIBBgEBDQECAQEBAQECAQgBAQEZAQEBAgYBAQEDAQECAQEBAQMBCBgIBwEMAQEGAQcBBwEQAQEBAQEBAgIBCgEBDQEIAQ0BAQEBAQEBBgEBDgEBAQEBAQEBAgEMBwEMAQwBAQEBCQECAwEHAQEBAQ0BAQEBDgIBBgEDAQEBAQEBAQMBAQEBAgEBAQEBAQEBCAEBAgEBAQEBAQkBCAgBAwECAQEBAgEBAQkBAQEBAwECAQMBAQIBBwEFAQEDAQYBAQEBAgEBAQEBAQEBAQECAgEDAQECBAIDAgIBBQEEAQEBAwEPAQEBCyIBCAEJAwQBAQIBAQEBAgECAQEBAQMBAQEBAwEBAQEBAQEBAQgBAQMDAgEBAwEEAQIBAQEBBAEBAQEBAQECAQEBAQEBAQEBAQEHAQQBAwEBAQcBAgUBBgECAQYBAQwBAQEUAQELCAYBFgMFAQYDAQoBAQMBARQBAQkBAQoBBgEVAwsBCgIPAQ0BGQEBAgEHARQBAwIBBgEBAQUBBgQBAgEJAQEBBQECAQMHAQELAQECCQEQAQECAgECAQsBDAEBAQEBCgEBAQsBAQEECQ4BCAQCAQEECAEEAQEFCAEPAQEEAQEPAQgBFAEBAQEBAQEKAQEJAQ8BEAEBEwEBAQIBCwEBDgENAwEKAQEBAQELAQEBAQECAQwBCAEBAQEBDgEDAQwBAQECAQEXAQEBAQEHAgEBBQEIAQEBAQEQAgEBBQEUAQEBAQEbAQEBAQEGARQBAQEBARkBAQEBCQEBAQEQAQIBDwEBARQBAQEBBwEBAQkBAQEBAQECAQEBCwECAQEVAQEBAQQBBQEBAQEOAQEBAQEBEgEBFgEBAgEMAQEBAQ8BAQMBFgEBDgEBBQEPAQETAQECAQMOAgUBCgIBGQEBAQEIAQMBBwEBAwECEwgBAQcLAQUBFwEBAQEDAQEBBwEBBAEBDg0BAQwBAQEDAQQBAQEDBAEBBAEBAQEBEAEPAQgBAQsBAQ4BEQEMAgEBBwEOAQEHAQEBAQQBBAEDCwECAQEBAwEBBggBAgEBAREBBQMKAQEBAwQCEQEBHgEPAQIBAQYEAQYBAwEUAQUMAQEBAQEBAQECAQEBAgEIAwEBBgsBAgEODAMBAgEBCwEBAQEBAwECAQECAQEBBwgPAQ=="
    }
  ]
};

// https://deno.land/std@0.224.0/cli/_run_length.ts
function runLengthDecode({ d: d4, r: r5 }) {
  const data3 = atob(d4);
  const runLengths = atob(r5);
  let out = "";
  for (const [i6, ch] of [...runLengths].entries()) {
    out += data3[i6].repeat(ch.codePointAt(0));
  }
  return Uint8Array.from([...out].map((x3) => x3.codePointAt(0)));
}

// https://deno.land/std@0.224.0/cli/unicode_width.ts
var tables = null;
function lookupWidth(cp) {
  if (!tables) tables = data_default.tables.map(runLengthDecode);
  const t1Offset = tables[0][cp >> 13 & 255];
  const t2Offset = tables[1][128 * t1Offset + (cp >> 6 & 127)];
  const packedWidths = tables[2][16 * t2Offset + (cp >> 2 & 15)];
  const width = packedWidths >> 2 * (cp & 3) & 3;
  return width === 3 ? 1 : width;
}
var cache = /* @__PURE__ */ new Map();
function charWidth(ch) {
  if (cache.has(ch)) return cache.get(ch);
  const cp = ch.codePointAt(0);
  let v4 = null;
  if (cp < 127) {
    v4 = cp >= 32 ? 1 : cp === 0 ? 0 : null;
  } else if (cp >= 160) {
    v4 = lookupWidth(cp);
  } else {
    v4 = null;
  }
  cache.set(ch, v4);
  return v4;
}
function unicodeWidth(str3) {
  return [...str3].map((ch) => charWidth(ch) ?? 0).reduce((a5, b3) => a5 + b3, 0);
}

// https://deno.land/std@0.224.0/console/unicode_width.ts
function unicodeWidth2(str3) {
  return unicodeWidth(str3);
}

// https://deno.land/x/cliffy@v1.0.0-rc.3/table/_utils.ts
function longest(index2, rows, maxWidth) {
  const cellLengths = rows.map((row) => {
    const cell = row[index2];
    const cellValue = cell instanceof Cell && cell.getColSpan() > 1 ? "" : cell?.toString() || "";
    return cellValue.split("\n").map((line) => {
      const str3 = typeof maxWidth === "undefined" ? line : consumeWords(maxWidth, line);
      return strLength(str3) || 0;
    });
  }).flat();
  return Math.max(...cellLengths);
}
var strLength = (str3) => {
  return unicodeWidth2(stripColor(str3));
};

// https://deno.land/x/cliffy@v1.0.0-rc.3/table/consume_words.ts
function consumeWords(length, content) {
  let consumed = "";
  const words = content.split("\n")[0]?.split(/ /g);
  for (let i6 = 0; i6 < words.length; i6++) {
    const word = words[i6];
    if (consumed) {
      const nextLength = strLength(word);
      const consumedLength = strLength(consumed);
      if (consumedLength + nextLength >= length) {
        break;
      }
    }
    consumed += (i6 > 0 ? " " : "") + word;
  }
  return consumed;
}

// https://deno.land/x/cliffy@v1.0.0-rc.3/table/row.ts
var Row = class _Row extends Array {
  options = {};
  /**
   * Create a new row. If cells is a row, all cells and options of the row will
   * be copied to the new row.
   *
   * @param cells Cells or row.
   */
  static from(cells) {
    const row = new this(...cells);
    if (cells instanceof _Row) {
      row.options = { ...cells.options };
    }
    return row;
  }
  /** Clone row recursively with all options. */
  clone() {
    const row = new _Row(
      ...this.map((cell) => cell instanceof Cell ? cell.clone() : cell)
    );
    row.options = { ...this.options };
    return row;
  }
  /**
   * Setter:
   */
  /**
   * Enable/disable cell border.
   *
   * @param enable    Enable/disable cell border.
   * @param override  Override existing value.
   */
  border(enable = true, override = true) {
    if (override || typeof this.options.border === "undefined") {
      this.options.border = enable;
    }
    return this;
  }
  /**
   * Align row content.
   *
   * @param direction Align direction.
   * @param override  Override existing value.
   */
  align(direction, override = true) {
    if (override || typeof this.options.align === "undefined") {
      this.options.align = direction;
    }
    return this;
  }
  /**
   * Getter:
   */
  /** Check if row has border. */
  getBorder() {
    return this.options.border === true;
  }
  /** Check if row or any child cell has border. */
  hasBorder() {
    return this.getBorder() || this.some((cell) => cell instanceof Cell && cell.getBorder());
  }
  /** Get row alignment. */
  getAlign() {
    return this.options.align ?? "left";
  }
};

// https://deno.land/x/cliffy@v1.0.0-rc.3/table/_layout.ts
var TableLayout = class {
  /**
   * Table layout constructor.
   * @param table   Table instance.
   * @param options Render options.
   */
  constructor(table, options) {
    this.table = table;
    this.options = options;
  }
  /** Generate table string. */
  toString() {
    const opts = this.createLayout();
    return opts.rows.length ? this.renderRows(opts) : "";
  }
  /**
   * Generates table layout including row and col span, converts all none
   * Cell/Row values to Cells and Rows and returns the layout rendering
   * settings.
   */
  createLayout() {
    Object.keys(this.options.chars).forEach((key) => {
      if (typeof this.options.chars[key] !== "string") {
        this.options.chars[key] = "";
      }
    });
    const hasBodyBorder = this.table.getBorder() || this.table.hasBodyBorder();
    const hasHeaderBorder = this.table.hasHeaderBorder();
    const hasBorder = hasHeaderBorder || hasBodyBorder;
    const rows = this.#getRows();
    const columns = Math.max(...rows.map((row) => row.length));
    for (let rowIndex = 0; rowIndex < rows.length; rowIndex++) {
      const row = rows[rowIndex];
      const length = row.length;
      if (length < columns) {
        const diff3 = columns - length;
        for (let i6 = 0; i6 < diff3; i6++) {
          row.push(this.createCell(null, row, rowIndex, length + i6));
        }
      }
    }
    const padding3 = [];
    const width = [];
    for (let colIndex = 0; colIndex < columns; colIndex++) {
      const column = this.options.columns.at(colIndex);
      const minColWidth = column?.getMinWidth() ?? (Array.isArray(this.options.minColWidth) ? this.options.minColWidth[colIndex] : this.options.minColWidth);
      const maxColWidth = column?.getMaxWidth() ?? (Array.isArray(this.options.maxColWidth) ? this.options.maxColWidth[colIndex] : this.options.maxColWidth);
      const colWidth = longest(colIndex, rows, maxColWidth);
      width[colIndex] = Math.min(maxColWidth, Math.max(minColWidth, colWidth));
      padding3[colIndex] = column?.getPadding() ?? (Array.isArray(this.options.padding) ? this.options.padding[colIndex] : this.options.padding);
    }
    return {
      padding: padding3,
      width,
      rows,
      columns,
      hasBorder,
      hasBodyBorder,
      hasHeaderBorder
    };
  }
  #getRows() {
    const header = this.table.getHeader();
    const rows = header ? [header, ...this.table] : this.table.slice();
    const hasSpan = rows.some(
      (row) => row.some(
        (cell) => cell instanceof Cell && (cell.getColSpan() > 1 || cell.getRowSpan() > 1)
      )
    );
    if (hasSpan) {
      return this.spanRows(rows);
    }
    return rows.map((row, rowIndex) => {
      const newRow = this.createRow(row);
      for (let colIndex = 0; colIndex < row.length; colIndex++) {
        newRow[colIndex] = this.createCell(
          row[colIndex],
          newRow,
          rowIndex,
          colIndex
        );
      }
      return newRow;
    });
  }
  /**
   * Fills rows and cols by specified row/col span with a reference of the
   * original cell.
   */
  spanRows(rows) {
    const rowSpan = [];
    let colSpan = 1;
    let rowIndex = -1;
    while (true) {
      rowIndex++;
      if (rowIndex === rows.length && rowSpan.every((span) => span === 1)) {
        break;
      }
      const row = rows[rowIndex] = this.createRow(rows[rowIndex] || []);
      let colIndex = -1;
      while (true) {
        colIndex++;
        if (colIndex === row.length && colIndex === rowSpan.length && colSpan === 1) {
          break;
        }
        if (colSpan > 1) {
          colSpan--;
          rowSpan[colIndex] = rowSpan[colIndex - 1];
          row.splice(
            colIndex,
            this.getDeleteCount(rows, rowIndex, colIndex),
            row[colIndex - 1]
          );
          continue;
        }
        if (rowSpan[colIndex] > 1) {
          rowSpan[colIndex]--;
          rows[rowIndex].splice(
            colIndex,
            this.getDeleteCount(rows, rowIndex, colIndex),
            rows[rowIndex - 1][colIndex]
          );
          continue;
        }
        const cell = row[colIndex] = this.createCell(
          row[colIndex] || null,
          row,
          rowIndex,
          colIndex
        );
        colSpan = cell.getColSpan();
        rowSpan[colIndex] = cell.getRowSpan();
      }
    }
    return rows;
  }
  getDeleteCount(rows, rowIndex, colIndex) {
    return colIndex <= rows[rowIndex].length - 1 && typeof rows[rowIndex][colIndex] === "undefined" ? 1 : 0;
  }
  /**
   * Create a new row from existing row or cell array.
   * @param row Original row.
   */
  createRow(row) {
    return Row.from(row).border(this.table.getBorder(), false).align(this.table.getAlign(), false);
  }
  /**
   * Create a new cell from existing cell or cell value.
   *
   * @param cell      Original cell.
   * @param row       Parent row.
   * @param rowIndex  The row index of the cell.
   * @param colIndex  The column index of the cell.
   */
  createCell(cell, row, rowIndex, colIndex) {
    const column = this.options.columns.at(colIndex);
    const isHeaderRow = this.isHeaderRow(rowIndex);
    return Cell.from(cell ?? "").border(
      (isHeaderRow ? null : column?.getBorder()) ?? row.getBorder(),
      false
    ).align(
      (isHeaderRow ? null : column?.getAlign()) ?? row.getAlign(),
      false
    );
  }
  isHeaderRow(rowIndex) {
    return rowIndex === 0 && this.table.getHeader() !== void 0;
  }
  /**
   * Render table layout.
   * @param opts Render options.
   */
  renderRows(opts) {
    let result2 = "";
    const rowSpan = new Array(opts.columns).fill(1);
    for (let rowIndex = 0; rowIndex < opts.rows.length; rowIndex++) {
      result2 += this.renderRow(rowSpan, rowIndex, opts);
    }
    return result2.slice(0, -1);
  }
  /**
   * Render row.
   * @param rowSpan     Current row span.
   * @param rowIndex    Current row index.
   * @param opts        Render options.
   * @param isMultiline Is multiline row.
   */
  renderRow(rowSpan, rowIndex, opts, isMultiline) {
    const row = opts.rows[rowIndex];
    const prevRow = opts.rows[rowIndex - 1];
    const nextRow = opts.rows[rowIndex + 1];
    let result2 = "";
    let colSpan = 1;
    if (!isMultiline && rowIndex === 0 && row.hasBorder()) {
      result2 += this.renderBorderRow(void 0, row, rowSpan, opts);
    }
    let isMultilineRow = false;
    result2 += " ".repeat(this.options.indent || 0);
    for (let colIndex = 0; colIndex < opts.columns; colIndex++) {
      if (colSpan > 1) {
        colSpan--;
        rowSpan[colIndex] = rowSpan[colIndex - 1];
        continue;
      }
      result2 += this.renderCell(colIndex, row, opts);
      if (rowSpan[colIndex] > 1) {
        if (!isMultiline) {
          rowSpan[colIndex]--;
        }
      } else if (!prevRow || prevRow[colIndex] !== row[colIndex]) {
        rowSpan[colIndex] = row[colIndex].getRowSpan();
      }
      colSpan = row[colIndex].getColSpan();
      if (rowSpan[colIndex] === 1 && row[colIndex].length) {
        isMultilineRow = true;
      }
    }
    if (opts.columns > 0) {
      if (row[opts.columns - 1].getBorder()) {
        result2 += this.options.chars.right;
      } else if (opts.hasBorder) {
        result2 += " ";
      }
    }
    result2 += "\n";
    if (isMultilineRow) {
      return result2 + this.renderRow(rowSpan, rowIndex, opts, isMultilineRow);
    }
    if (opts.rows.length > 1 && (rowIndex === 0 && opts.hasHeaderBorder || rowIndex < opts.rows.length - 1 && opts.hasBodyBorder)) {
      result2 += this.renderBorderRow(row, nextRow, rowSpan, opts);
    }
    if (rowIndex === opts.rows.length - 1 && row.hasBorder()) {
      result2 += this.renderBorderRow(row, void 0, rowSpan, opts);
    }
    return result2;
  }
  /**
   * Render cell.
   * @param colIndex  Current col index.
   * @param row       Current row.
   * @param opts      Render options.
   * @param noBorder  Disable border.
   */
  renderCell(colIndex, row, opts, noBorder) {
    let result2 = "";
    const prevCell = row[colIndex - 1];
    const cell = row[colIndex];
    if (!noBorder) {
      if (colIndex === 0) {
        if (cell.getBorder()) {
          result2 += this.options.chars.left;
        } else if (opts.hasBorder) {
          result2 += " ";
        }
      } else {
        if (cell.getBorder() || prevCell?.getBorder()) {
          result2 += this.options.chars.middle;
        } else if (opts.hasBorder) {
          result2 += " ";
        }
      }
    }
    let maxLength = opts.width[colIndex];
    const colSpan = cell.getColSpan();
    if (colSpan > 1) {
      for (let o5 = 1; o5 < colSpan; o5++) {
        maxLength += opts.width[colIndex + o5] + opts.padding[colIndex + o5];
        if (opts.hasBorder) {
          maxLength += opts.padding[colIndex + o5] + 1;
        }
      }
    }
    const { current: current3, next } = this.renderCellValue(cell, maxLength);
    row[colIndex].setValue(next.getValue());
    if (opts.hasBorder) {
      result2 += " ".repeat(opts.padding[colIndex]);
    }
    result2 += current3;
    if (opts.hasBorder || colIndex < opts.columns - 1) {
      result2 += " ".repeat(opts.padding[colIndex]);
    }
    return result2;
  }
  /**
   * Render specified length of cell. Returns the rendered value and a new cell
   * with the rest value.
   * @param cell      Cell to render.
   * @param maxLength Max length of content to render.
   */
  renderCellValue(cell, maxLength) {
    const length = Math.min(
      maxLength,
      strLength(cell.toString())
    );
    let words = consumeWords(length, cell.toString());
    const breakWord = strLength(words) > length;
    if (breakWord) {
      words = words.slice(0, length);
    }
    const next = cell.toString().slice(words.length + (breakWord ? 0 : 1));
    const fillLength = maxLength - strLength(words);
    const align = cell.getAlign();
    let current3;
    if (fillLength === 0) {
      current3 = words;
    } else if (align === "left") {
      current3 = words + " ".repeat(fillLength);
    } else if (align === "center") {
      current3 = " ".repeat(Math.floor(fillLength / 2)) + words + " ".repeat(Math.ceil(fillLength / 2));
    } else if (align === "right") {
      current3 = " ".repeat(fillLength) + words;
    } else {
      throw new Error("Unknown direction: " + align);
    }
    return {
      current: current3,
      next: cell.clone(next)
    };
  }
  /**
   * Render border row.
   * @param prevRow Previous row.
   * @param nextRow Next row.
   * @param rowSpan Current row span.
   * @param opts    Render options.
   */
  renderBorderRow(prevRow, nextRow, rowSpan, opts) {
    let result2 = "";
    let colSpan = 1;
    for (let colIndex = 0; colIndex < opts.columns; colIndex++) {
      if (rowSpan[colIndex] > 1) {
        if (!nextRow) {
          throw new Error("invalid layout");
        }
        if (colSpan > 1) {
          colSpan--;
          continue;
        }
      }
      result2 += this.renderBorderCell(
        colIndex,
        prevRow,
        nextRow,
        rowSpan,
        opts
      );
      colSpan = nextRow?.[colIndex].getColSpan() ?? 1;
    }
    return result2.length ? " ".repeat(this.options.indent) + result2 + "\n" : "";
  }
  /**
   * Render border cell.
   * @param colIndex  Current index.
   * @param prevRow   Previous row.
   * @param nextRow   Next row.
   * @param rowSpan   Current row span.
   * @param opts      Render options.
   */
  renderBorderCell(colIndex, prevRow, nextRow, rowSpan, opts) {
    const a1 = prevRow?.[colIndex - 1];
    const a22 = nextRow?.[colIndex - 1];
    const b1 = prevRow?.[colIndex];
    const b22 = nextRow?.[colIndex];
    const a1Border = !!a1?.getBorder();
    const a2Border = !!a22?.getBorder();
    const b1Border = !!b1?.getBorder();
    const b2Border = !!b22?.getBorder();
    const hasColSpan = (cell) => (cell?.getColSpan() ?? 1) > 1;
    const hasRowSpan = (cell) => (cell?.getRowSpan() ?? 1) > 1;
    let result2 = "";
    if (colIndex === 0) {
      if (rowSpan[colIndex] > 1) {
        if (b1Border) {
          result2 += this.options.chars.left;
        } else {
          result2 += " ";
        }
      } else if (b1Border && b2Border) {
        result2 += this.options.chars.leftMid;
      } else if (b1Border) {
        result2 += this.options.chars.bottomLeft;
      } else if (b2Border) {
        result2 += this.options.chars.topLeft;
      } else {
        result2 += " ";
      }
    } else if (colIndex < opts.columns) {
      if (a1Border && b2Border || b1Border && a2Border) {
        const a1ColSpan = hasColSpan(a1);
        const a2ColSpan = hasColSpan(a22);
        const b1ColSpan = hasColSpan(b1);
        const b2ColSpan = hasColSpan(b22);
        const a1RowSpan = hasRowSpan(a1);
        const a2RowSpan = hasRowSpan(a22);
        const b1RowSpan = hasRowSpan(b1);
        const b2RowSpan = hasRowSpan(b22);
        const hasAllBorder = a1Border && b2Border && b1Border && a2Border;
        const hasAllRowSpan = a1RowSpan && b1RowSpan && a2RowSpan && b2RowSpan;
        const hasAllColSpan = a1ColSpan && b1ColSpan && a2ColSpan && b2ColSpan;
        if (hasAllRowSpan && hasAllBorder) {
          result2 += this.options.chars.middle;
        } else if (hasAllColSpan && hasAllBorder && a1 === b1 && a22 === b22) {
          result2 += this.options.chars.mid;
        } else if (a1ColSpan && b1ColSpan && a1 === b1) {
          result2 += this.options.chars.topMid;
        } else if (a2ColSpan && b2ColSpan && a22 === b22) {
          result2 += this.options.chars.bottomMid;
        } else if (a1RowSpan && a2RowSpan && a1 === a22) {
          result2 += this.options.chars.leftMid;
        } else if (b1RowSpan && b2RowSpan && b1 === b22) {
          result2 += this.options.chars.rightMid;
        } else {
          result2 += this.options.chars.midMid;
        }
      } else if (a1Border && b1Border) {
        if (hasColSpan(a1) && hasColSpan(b1) && a1 === b1) {
          result2 += this.options.chars.bottom;
        } else {
          result2 += this.options.chars.bottomMid;
        }
      } else if (b1Border && b2Border) {
        if (rowSpan[colIndex] > 1) {
          result2 += this.options.chars.left;
        } else {
          result2 += this.options.chars.leftMid;
        }
      } else if (b2Border && a2Border) {
        if (hasColSpan(a22) && hasColSpan(b22) && a22 === b22) {
          result2 += this.options.chars.top;
        } else {
          result2 += this.options.chars.topMid;
        }
      } else if (a1Border && a2Border) {
        if (hasRowSpan(a1) && a1 === a22) {
          result2 += this.options.chars.right;
        } else {
          result2 += this.options.chars.rightMid;
        }
      } else if (a1Border) {
        result2 += this.options.chars.bottomRight;
      } else if (b1Border) {
        result2 += this.options.chars.bottomLeft;
      } else if (a2Border) {
        result2 += this.options.chars.topRight;
      } else if (b2Border) {
        result2 += this.options.chars.topLeft;
      } else {
        result2 += " ";
      }
    }
    const length = opts.padding[colIndex] + opts.width[colIndex] + opts.padding[colIndex];
    if (rowSpan[colIndex] > 1 && nextRow) {
      result2 += this.renderCell(
        colIndex,
        nextRow,
        opts,
        true
      );
      if (nextRow[colIndex] === nextRow[nextRow.length - 1]) {
        if (b1Border) {
          result2 += this.options.chars.right;
        } else {
          result2 += " ";
        }
        return result2;
      }
    } else if (b1Border && b2Border) {
      result2 += this.options.chars.mid.repeat(length);
    } else if (b1Border) {
      result2 += this.options.chars.bottom.repeat(length);
    } else if (b2Border) {
      result2 += this.options.chars.top.repeat(length);
    } else {
      result2 += " ".repeat(length);
    }
    if (colIndex === opts.columns - 1) {
      if (b1Border && b2Border) {
        result2 += this.options.chars.rightMid;
      } else if (b1Border) {
        result2 += this.options.chars.bottomRight;
      } else if (b2Border) {
        result2 += this.options.chars.topRight;
      } else {
        result2 += " ";
      }
    }
    return result2;
  }
};

// https://deno.land/x/cliffy@v1.0.0-rc.3/table/table.ts
var Table = class _Table extends Array {
  static _chars = { ...border };
  options = {
    indent: 0,
    border: false,
    maxColWidth: Infinity,
    minColWidth: 0,
    padding: 1,
    chars: { ..._Table._chars },
    columns: []
  };
  headerRow;
  /**
   * Create a new table. If rows is a table, all rows and options of the table
   * will be copied to the new table.
   *
   * @param rows An array of rows or a table instance.
   */
  static from(rows) {
    const table = new this(...rows);
    if (rows instanceof _Table) {
      table.options = { ...rows.options };
      table.headerRow = rows.headerRow ? Row.from(rows.headerRow) : void 0;
    }
    return table;
  }
  /**
   * Create a new table from an array of json objects. An object represents a
   * row and each property a column.
   *
   * @param rows Array of objects.
   */
  static fromJson(rows) {
    return new this().fromJson(rows);
  }
  /**
   * Set global default border characters.
   *
   * @param chars Border options.
   */
  static chars(chars) {
    Object.assign(this._chars, chars);
    return this;
  }
  /**
   * Write table or rows to stdout.
   *
   * @param rows Table or rows.
   */
  static render(rows) {
    _Table.from(rows).render();
  }
  /**
   * Read data from an array of json objects. An object represents a
   * row and each property a column.
   *
   * @param rows Array of objects.
   */
  fromJson(rows) {
    this.header(Object.keys(rows[0]));
    this.body(rows.map((row) => Object.values(row)));
    return this;
  }
  /**
   * Set column options.
   *
   * @param columns An array of columns or column options.
   */
  columns(columns) {
    this.options.columns = columns.map(
      (column) => column instanceof Column ? column : Column.from(column)
    );
    return this;
  }
  /**
   * Set column options by index.
   *
   @param index   The column index.
   @param column  Column or column options.
   */
  column(index2, column) {
    if (column instanceof Column) {
      this.options.columns[index2] = column;
    } else if (this.options.columns[index2]) {
      this.options.columns[index2].options(column);
    } else {
      this.options.columns[index2] = Column.from(column);
    }
    return this;
  }
  /**
   * Set table header.
   *
   * @param header Header row or cells.
   */
  header(header) {
    this.headerRow = header instanceof Row ? header : Row.from(header);
    return this;
  }
  /**
   * Set table body.
   *
   * @param rows Array of rows.
   */
  body(rows) {
    this.length = 0;
    this.push(...rows);
    return this;
  }
  /** Clone table recursively with header and options. */
  clone() {
    const table = new _Table(
      ...this.map(
        (row) => row instanceof Row ? row.clone() : Row.from(row).clone()
      )
    );
    table.options = { ...this.options };
    table.headerRow = this.headerRow?.clone();
    return table;
  }
  /** Generate table string. */
  toString() {
    return new TableLayout(this, this.options).toString();
  }
  /** Write table to stdout. */
  render() {
    console.log(this.toString());
    return this;
  }
  /**
   * Set max column width.
   *
   * @param width     Max column width.
   * @param override  Override existing value.
   */
  maxColWidth(width, override = true) {
    if (override || typeof this.options.maxColWidth === "undefined") {
      this.options.maxColWidth = width;
    }
    return this;
  }
  /**
   * Set min column width.
   *
   * @param width     Min column width.
   * @param override  Override existing value.
   */
  minColWidth(width, override = true) {
    if (override || typeof this.options.minColWidth === "undefined") {
      this.options.minColWidth = width;
    }
    return this;
  }
  /**
   * Set table indentation.
   *
   * @param width     Indent width.
   * @param override  Override existing value.
   */
  indent(width, override = true) {
    if (override || typeof this.options.indent === "undefined") {
      this.options.indent = width;
    }
    return this;
  }
  /**
   * Set cell padding.
   *
   * @param padding   Cell padding.
   * @param override  Override existing value.
   */
  padding(padding3, override = true) {
    if (override || typeof this.options.padding === "undefined") {
      this.options.padding = padding3;
    }
    return this;
  }
  /**
   * Enable/disable cell border.
   *
   * @param enable    Enable/disable cell border.
   * @param override  Override existing value.
   */
  border(enable = true, override = true) {
    if (override || typeof this.options.border === "undefined") {
      this.options.border = enable;
    }
    return this;
  }
  /**
   * Align table content.
   *
   * @param direction Align direction.
   * @param override  Override existing value.
   */
  align(direction, override = true) {
    if (override || typeof this.options.align === "undefined") {
      this.options.align = direction;
    }
    return this;
  }
  /**
   * Set border characters.
   *
   * @param chars Border options.
   */
  chars(chars) {
    Object.assign(this.options.chars, chars);
    return this;
  }
  /** Get table header. */
  getHeader() {
    return this.headerRow;
  }
  /** Get table body. */
  getBody() {
    return [...this];
  }
  /** Get max column width. */
  getMaxColWidth() {
    return this.options.maxColWidth;
  }
  /** Get min column width. */
  getMinColWidth() {
    return this.options.minColWidth;
  }
  /** Get table indentation. */
  getIndent() {
    return this.options.indent;
  }
  /** Get cell padding. */
  getPadding() {
    return this.options.padding;
  }
  /** Check if table has border. */
  getBorder() {
    return this.options.border === true;
  }
  /** Check if header row has border. */
  hasHeaderBorder() {
    const hasBorder = this.headerRow?.hasBorder();
    return hasBorder === true || this.getBorder() && hasBorder !== false;
  }
  /** Check if table bordy has border. */
  hasBodyBorder() {
    return this.getBorder() || this.options.columns.some((column) => column.getBorder()) || this.some(
      (row) => row instanceof Row ? row.hasBorder() : row.some((cell) => cell instanceof Cell ? cell.getBorder() : false)
    );
  }
  /** Check if table header or body has border. */
  hasBorder() {
    return this.hasHeaderBorder() || this.hasBodyBorder();
  }
  /** Get table alignment. */
  getAlign() {
    return this.options.align ?? "left";
  }
  /** Get columns. */
  getColumns() {
    return this.options.columns;
  }
  /** Get column by column index. */
  getColumn(index2) {
    return this.options.columns[index2] ??= new Column();
  }
};

// https://deno.land/x/cliffy@v1.0.0-rc.3/command/help/_help_generator.ts
var HelpGenerator = class _HelpGenerator {
  constructor(cmd, options = {}) {
    this.cmd = cmd;
    this.options = {
      types: false,
      hints: true,
      colors: true,
      long: false,
      ...options
    };
  }
  indent = 2;
  options;
  /** Generate help text for given command. */
  static generate(cmd, options) {
    return new _HelpGenerator(cmd, options).generate();
  }
  generate() {
    const areColorsEnabled = getColorEnabled();
    setColorEnabled(this.options.colors);
    const result2 = this.generateHeader() + this.generateMeta() + this.generateDescription() + this.generateOptions() + this.generateCommands() + this.generateEnvironmentVariables() + this.generateExamples();
    setColorEnabled(areColorsEnabled);
    return result2;
  }
  generateHeader() {
    const usage = this.cmd.getUsage();
    const rows = [
      [
        bold2("Usage:"),
        brightMagenta(
          this.cmd.getPath() + (usage ? " " + highlightArguments(usage, this.options.types) : "")
        )
      ]
    ];
    const version4 = this.cmd.getVersion();
    if (version4) {
      rows.push([bold2("Version:"), yellow2(`${this.cmd.getVersion()}`)]);
    }
    return "\n" + Table.from(rows).padding(1).toString() + "\n";
  }
  generateMeta() {
    const meta = Object.entries(this.cmd.getMeta());
    if (!meta.length) {
      return "";
    }
    const rows = [];
    for (const [name2, value] of meta) {
      rows.push([bold2(`${name2}: `) + value]);
    }
    return "\n" + Table.from(rows).padding(1).toString() + "\n";
  }
  generateDescription() {
    if (!this.cmd.getDescription()) {
      return "";
    }
    return this.label("Description") + Table.from([
      [dedent(this.cmd.getDescription())]
    ]).indent(this.indent).maxColWidth(140).padding(1).toString() + "\n";
  }
  generateOptions() {
    const options = this.cmd.getOptions(false);
    if (!options.length) {
      return "";
    }
    let groups = [];
    const hasGroups = options.some((option) => option.groupName);
    if (hasGroups) {
      for (const option of options) {
        let group = groups.find((group2) => group2.name === option.groupName);
        if (!group) {
          group = {
            name: option.groupName,
            options: []
          };
          groups.push(group);
        }
        group.options.push(option);
      }
    } else {
      groups = [{
        name: "Options",
        options
      }];
    }
    let result2 = "";
    for (const group of groups) {
      result2 += this.generateOptionGroup(group);
    }
    return result2;
  }
  generateOptionGroup(group) {
    if (!group.options.length) {
      return "";
    }
    const hasTypeDefinitions = !!group.options.find(
      (option) => !!option.typeDefinition
    );
    if (hasTypeDefinitions) {
      return this.label(group.name ?? "Options") + Table.from([
        ...group.options.map((option) => [
          option.flags.map((flag) => brightBlue(flag)).join(", "),
          highlightArguments(
            option.typeDefinition || "",
            this.options.types
          ),
          red2(bold2("-")),
          getDescription(option.description, !this.options.long),
          this.generateHints(option)
        ])
      ]).padding([2, 2, 1, 2]).indent(this.indent).maxColWidth([60, 60, 1, 80, 60]).toString() + "\n";
    }
    return this.label(group.name ?? "Options") + Table.from([
      ...group.options.map((option) => [
        option.flags.map((flag) => brightBlue(flag)).join(", "),
        red2(bold2("-")),
        getDescription(option.description, !this.options.long),
        this.generateHints(option)
      ])
    ]).indent(this.indent).maxColWidth([60, 1, 80, 60]).padding([2, 1, 2]).toString() + "\n";
  }
  generateCommands() {
    const commands2 = this.cmd.getCommands(false);
    if (!commands2.length) {
      return "";
    }
    const hasTypeDefinitions = !!commands2.find(
      (command) => !!command.getArgsDefinition()
    );
    if (hasTypeDefinitions) {
      return this.label("Commands") + Table.from([
        ...commands2.map((command) => [
          [command.getName(), ...command.getAliases()].map(
            (name2) => brightBlue(name2)
          ).join(", "),
          highlightArguments(
            command.getArgsDefinition() || "",
            this.options.types
          ),
          red2(bold2("-")),
          command.getShortDescription()
        ])
      ]).indent(this.indent).maxColWidth([60, 60, 1, 80]).padding([2, 2, 1, 2]).toString() + "\n";
    }
    return this.label("Commands") + Table.from([
      ...commands2.map((command) => [
        [command.getName(), ...command.getAliases()].map(
          (name2) => brightBlue(name2)
        ).join(", "),
        red2(bold2("-")),
        command.getShortDescription()
      ])
    ]).maxColWidth([60, 1, 80]).padding([2, 1, 2]).indent(this.indent).toString() + "\n";
  }
  generateEnvironmentVariables() {
    const envVars = this.cmd.getEnvVars(false);
    if (!envVars.length) {
      return "";
    }
    return this.label("Environment variables") + Table.from([
      ...envVars.map((envVar) => [
        envVar.names.map((name2) => brightBlue(name2)).join(", "),
        highlightArgumentDetails(
          envVar.details,
          this.options.types
        ),
        red2(bold2("-")),
        this.options.long ? dedent(envVar.description) : envVar.description.trim().split("\n", 1)[0],
        envVar.required ? `(${yellow2(`required`)})` : ""
      ])
    ]).padding([2, 2, 1, 2]).indent(this.indent).maxColWidth([60, 60, 1, 80, 10]).toString() + "\n";
  }
  generateExamples() {
    const examples = this.cmd.getExamples();
    if (!examples.length) {
      return "";
    }
    return this.label("Examples") + Table.from(examples.map((example) => [
      dim(bold2(`${capitalize(example.name)}:`)),
      dedent(example.description)
    ])).padding(1).indent(this.indent).maxColWidth(150).toString() + "\n";
  }
  generateHints(option) {
    if (!this.options.hints) {
      return "";
    }
    const hints = [];
    option.required && hints.push(yellow2(`required`));
    if (typeof option.default !== "undefined") {
      const defaultValue = getDefaultValue(option);
      if (typeof defaultValue !== "undefined") {
        hints.push(
          bold2(`Default: `) + inspect(defaultValue, this.options.colors)
        );
      }
    }
    option.depends?.length && hints.push(
      yellow2(bold2(`Depends: `)) + italic(option.depends.map(getFlag).join(", "))
    );
    option.conflicts?.length && hints.push(
      red2(bold2(`Conflicts: `)) + italic(option.conflicts.map(getFlag).join(", "))
    );
    const type4 = this.cmd.getType(option.args[0]?.type)?.handler;
    if (type4 instanceof Type) {
      const possibleValues = type4.values?.(this.cmd, this.cmd.getParent());
      if (possibleValues?.length) {
        hints.push(
          bold2(`Values: `) + possibleValues.map(
            (value) => inspect(value, this.options.colors)
          ).join(", ")
        );
      }
    }
    if (hints.length) {
      return `(${hints.join(", ")})`;
    }
    return "";
  }
  label(label) {
    return "\n" + bold2(`${label}:`) + "\n\n";
  }
};
function capitalize(string2) {
  return string2?.charAt(0).toUpperCase() + string2.slice(1);
}
function inspect(value, colors2) {
  return Deno.inspect(
    value,
    // deno < 1.4.3 doesn't support the colors property.
    { depth: 1, colors: colors2, trailingComma: false }
  );
}
function highlightArguments(argsDefinition, types8 = true) {
  if (!argsDefinition) {
    return "";
  }
  return parseArgumentsDefinition(argsDefinition, false, true).map(
    (arg) => typeof arg === "string" ? arg : highlightArgumentDetails(arg, types8)
  ).join(" ");
}
function highlightArgumentDetails(arg, types8 = true) {
  let str3 = "";
  str3 += yellow2(arg.optional ? "[" : "<");
  let name2 = "";
  name2 += arg.name;
  if (arg.variadic) {
    name2 += "...";
  }
  name2 = brightMagenta(name2);
  str3 += name2;
  if (types8) {
    str3 += yellow2(":");
    str3 += red2(arg.type);
    if (arg.list) {
      str3 += green("[]");
    }
  }
  str3 += yellow2(arg.optional ? "]" : ">");
  return str3;
}

// https://deno.land/x/cliffy@v1.0.0-rc.3/command/upgrade/_check_version.ts
async function checkVersion(cmd) {
  const mainCommand = cmd.getMainCommand();
  const upgradeCommand = mainCommand.getCommand("upgrade");
  if (!isUpgradeCommand(upgradeCommand)) {
    return;
  }
  const latestVersion = await upgradeCommand.getLatestVersion();
  const currentVersion = mainCommand.getVersion();
  if (currentVersion === latestVersion) {
    return;
  }
  const versionHelpText = `(New version available: ${latestVersion}. Run '${mainCommand.getName()} upgrade' to upgrade to the latest version!)`;
  mainCommand.version(`${currentVersion}  ${bold2(yellow2(versionHelpText))}`);
}
function isUpgradeCommand(command) {
  return command instanceof Command && "getLatestVersion" in command;
}

// https://deno.land/x/cliffy@v1.0.0-rc.3/command/command.ts
var Command = class _Command {
  types = /* @__PURE__ */ new Map();
  rawArgs = [];
  literalArgs = [];
  _name = "COMMAND";
  _parent;
  _globalParent;
  ver;
  desc = "";
  _usage;
  actionHandler;
  globalActionHandler;
  options = [];
  commands = /* @__PURE__ */ new Map();
  examples = [];
  envVars = [];
  aliases = [];
  completions = /* @__PURE__ */ new Map();
  cmd = this;
  argsDefinition;
  isExecutable = false;
  throwOnError = false;
  _allowEmpty = false;
  _stopEarly = false;
  defaultCommand;
  _useRawArgs = false;
  args = [];
  isHidden = false;
  isGlobal = false;
  hasDefaults = false;
  _versionOptions;
  _helpOptions;
  _versionOption;
  _helpOption;
  _help;
  _shouldExit;
  _meta = {};
  _groupName = null;
  _noGlobals = false;
  errorHandler;
  versionOption(flags, desc, opts) {
    this._versionOptions = flags === false ? flags : {
      flags,
      desc,
      opts: typeof opts === "function" ? { action: opts } : opts
    };
    return this;
  }
  helpOption(flags, desc, opts) {
    this._helpOptions = flags === false ? flags : {
      flags,
      desc,
      opts: typeof opts === "function" ? { action: opts } : opts
    };
    return this;
  }
  /**
   * Add new sub-command.
   * @param nameAndArguments  Command definition. E.g: `my-command <input-file:string> <output-file:string>`
   * @param cmdOrDescription  The description of the new child command.
   * @param override          Override existing child command.
   */
  command(nameAndArguments, cmdOrDescription, override) {
    this.reset();
    const result2 = splitArguments(nameAndArguments);
    const name2 = result2.flags.shift();
    const aliases = result2.flags;
    if (!name2) {
      throw new MissingCommandNameError();
    }
    if (this.getBaseCommand(name2, true)) {
      if (!override) {
        throw new DuplicateCommandNameError(name2);
      }
      this.removeCommand(name2);
    }
    let description;
    let cmd;
    if (typeof cmdOrDescription === "string") {
      description = cmdOrDescription;
    }
    if (cmdOrDescription instanceof _Command) {
      cmd = cmdOrDescription.reset();
    } else {
      cmd = new _Command();
    }
    cmd._name = name2;
    cmd._parent = this;
    if (description) {
      cmd.description(description);
    }
    if (result2.typeDefinition) {
      cmd.arguments(result2.typeDefinition);
    }
    aliases.forEach((alias) => cmd.alias(alias));
    this.commands.set(name2, cmd);
    this.select(name2);
    return this;
  }
  /**
   * Add new command alias.
   *
   * @param alias Tha name of the alias.
   */
  alias(alias) {
    if (this.cmd._name === alias || this.cmd.aliases.includes(alias)) {
      throw new DuplicateCommandAliasError(alias);
    }
    this.cmd.aliases.push(alias);
    return this;
  }
  /** Reset internal command reference to main command. */
  reset() {
    this._groupName = null;
    this.cmd = this;
    return this;
  }
  /**
   * Set internal command pointer to child command with given name.
   * @param name The name of the command to select.
   */
  select(name2) {
    const cmd = this.getBaseCommand(name2, true);
    if (!cmd) {
      throw new CommandNotFoundError(name2, this.getBaseCommands(true));
    }
    this.cmd = cmd;
    return this;
  }
  /*****************************************************************************
   **** SUB HANDLER ************************************************************
   *****************************************************************************/
  /** Set command name. Used in auto generated help and shell completions */
  name(name2) {
    this.cmd._name = name2;
    return this;
  }
  /**
   * Set command version.
   *
   * @param version Semantic version string string or method that returns the version string.
   */
  version(version4) {
    if (typeof version4 === "string") {
      this.cmd.ver = () => version4;
    } else if (typeof version4 === "function") {
      this.cmd.ver = version4;
    }
    return this;
  }
  /**
   * Add meta data. Will be displayed in the auto generated help and in the
   * output of the long version.
   *
   * @param name  The name/label of the metadata.
   * @param value The value of the metadata.
   */
  meta(name2, value) {
    this.cmd._meta[name2] = value;
    return this;
  }
  getMeta(name2) {
    return typeof name2 === "undefined" ? this._meta : this._meta[name2];
  }
  /**
   * Set command help.
   *
   * @param help Help string, method, or config for generator that returns the help string.
   */
  help(help) {
    if (typeof help === "string") {
      this.cmd._help = () => help;
    } else if (typeof help === "function") {
      this.cmd._help = help;
    } else {
      this.cmd._help = (cmd, options) => HelpGenerator.generate(cmd, { ...help, ...options });
    }
    return this;
  }
  /**
   * Set the long command description.
   *
   * @param description The command description.
   */
  description(description) {
    this.cmd.desc = description;
    return this;
  }
  /**
   * Set the command usage. Defaults to arguments.
   *
   * @param usage The command usage.
   */
  usage(usage) {
    this.cmd._usage = usage;
    return this;
  }
  /** Hide command from help, completions, etc. */
  hidden() {
    this.cmd.isHidden = true;
    return this;
  }
  /** Make command globally available. */
  global() {
    this.cmd.isGlobal = true;
    return this;
  }
  /** Make command executable. */
  executable() {
    this.cmd.isExecutable = true;
    return this;
  }
  /**
   * Set command arguments:
   *
   *   <requiredArg:string> [optionalArg: number] [...restArgs:string]
   */
  arguments(args) {
    this.cmd.argsDefinition = args;
    return this;
  }
  /**
   * Set command callback method.
   *
   * @param fn Command action handler.
   */
  action(fn) {
    this.cmd.actionHandler = fn;
    return this;
  }
  /**
   * Set command callback method.
   *
   * @param fn Command action handler.
   */
  globalAction(fn) {
    this.cmd.globalActionHandler = fn;
    return this;
  }
  /**
   * Don't throw an error if the command was called without arguments.
   *
   * @param allowEmpty Enable/disable allow empty.
   */
  allowEmpty(allowEmpty) {
    this.cmd._allowEmpty = allowEmpty !== false;
    return this;
  }
  /**
   * Enable stop early. If enabled, all arguments starting from the first non
   * option argument will be passed as arguments with type string to the command
   * action handler.
   *
   * For example:
   *     `command --debug-level warning server --port 80`
   *
   * Will result in:
   *     - options: `{ debugLevel: 'warning' }`
   *     - args: `['server', '--port', '80']`
   *
   * @param stopEarly Enable/disable stop early.
   */
  stopEarly(stopEarly = true) {
    this.cmd._stopEarly = stopEarly;
    return this;
  }
  /**
   * Disable parsing arguments. If enabled the raw arguments will be passed to
   * the action handler. This has no effect for parent or child commands. Only
   * for the command on which this method was called.
   *
   * @param useRawArgs Enable/disable raw arguments.
   */
  useRawArgs(useRawArgs = true) {
    this.cmd._useRawArgs = useRawArgs;
    return this;
  }
  /**
   * Set default command. The default command is executed when the program
   * was called without any argument and if no action handler is registered.
   *
   * @param name Name of the default command.
   */
  default(name2) {
    this.cmd.defaultCommand = name2;
    return this;
  }
  globalType(name2, handler, options) {
    return this.type(name2, handler, { ...options, global: true });
  }
  /**
   * Register custom type.
   *
   * @param name    The name of the type.
   * @param handler The callback method to parse the type.
   * @param options Type options.
   */
  type(name2, handler, options) {
    if (this.cmd.types.get(name2) && !options?.override) {
      throw new DuplicateTypeError(name2);
    }
    this.cmd.types.set(name2, {
      ...options,
      name: name2,
      handler
    });
    if (handler instanceof Type && (typeof handler.complete !== "undefined" || typeof handler.values !== "undefined")) {
      const completeHandler = (cmd, parent) => handler.complete?.(cmd, parent) || [];
      this.complete(name2, completeHandler, options);
    }
    return this;
  }
  /**
   * Register global complete handler.
   *
   * @param name      The name of the completion.
   * @param complete  The callback method to complete the type.
   * @param options   Complete options.
   */
  globalComplete(name2, complete, options) {
    return this.complete(name2, complete, { ...options, global: true });
  }
  complete(name2, complete, options) {
    if (this.cmd.completions.has(name2) && !options?.override) {
      throw new DuplicateCompletionError(name2);
    }
    this.cmd.completions.set(name2, {
      name: name2,
      complete,
      ...options
    });
    return this;
  }
  /**
   * Throw validation errors instead of calling `Deno.exit()` to handle
   * validation errors manually.
   *
   * A validation error is thrown when the command is wrongly used by the user.
   * For example: If the user passes some invalid options or arguments to the
   * command.
   *
   * This has no effect for parent commands. Only for the command on which this
   * method was called and all child commands.
   *
   * **Example:**
   *
   * ```ts
   * import { Command, ValidationError } from "./mod.ts";
   *
   * const cmd = new Command();
   * // ...
   *
   * try {
   *   cmd.parse();
   * } catch(error) {
   *   if (error instanceof ValidationError) {
   *     cmd.showHelp();
   *     Deno.exit(1);
   *   }
   *   throw error;
   * }
   * ```
   *
   * @see ValidationError
   */
  throwErrors() {
    this.cmd.throwOnError = true;
    return this;
  }
  /**
   * Set custom error handler.
   *
   * @param handler Error handler callback function.
   */
  error(handler) {
    this.cmd.errorHandler = handler;
    return this;
  }
  /** Get error handler callback function. */
  getErrorHandler() {
    return this.errorHandler ?? this._parent?.errorHandler;
  }
  /**
   * Same as `.throwErrors()` but also prevents calling `Deno.exit` after
   * printing help or version with the --help and --version option.
   */
  noExit() {
    this.cmd._shouldExit = false;
    this.throwErrors();
    return this;
  }
  /**
   * Disable inheriting global commands, options and environment variables from
   * parent commands.
   */
  noGlobals() {
    this.cmd._noGlobals = true;
    return this;
  }
  /** Check whether the command should throw errors or exit. */
  shouldThrowErrors() {
    return this.throwOnError || !!this._parent?.shouldThrowErrors();
  }
  /** Check whether the command should exit after printing help or version. */
  shouldExit() {
    return this._shouldExit ?? this._parent?.shouldExit() ?? true;
  }
  /**
   * Enable grouping of options and set the name of the group.
   * All option which are added after calling the `.group()` method will be
   * grouped in the help output. If the `.group()` method can be use multiple
   * times to create more groups.
   *
   * @param name The name of the option group.
   */
  group(name2) {
    this.cmd._groupName = name2;
    return this;
  }
  /**
   * Register a global option.
   *
   * @param flags Flags string e.g: -h, --help, --manual <requiredArg:string> [optionalArg:number] [...restArgs:string]
   * @param desc Flag description.
   * @param opts Flag options or custom handler for processing flag value.
   */
  globalOption(flags, desc, opts) {
    if (typeof opts === "function") {
      return this.option(
        flags,
        desc,
        { value: opts, global: true }
      );
    }
    return this.option(
      flags,
      desc,
      { ...opts, global: true }
    );
  }
  option(flags, desc, opts) {
    if (typeof opts === "function") {
      opts = { value: opts };
    }
    const result2 = splitArguments(flags);
    const args = result2.typeDefinition ? parseArgumentsDefinition(result2.typeDefinition) : [];
    const option = {
      ...opts,
      name: "",
      description: desc,
      args,
      flags: result2.flags,
      equalsSign: result2.equalsSign,
      typeDefinition: result2.typeDefinition,
      groupName: this._groupName ?? void 0
    };
    if (option.separator) {
      for (const arg of args) {
        if (arg.list) {
          arg.separator = option.separator;
        }
      }
    }
    for (const part of option.flags) {
      const arg = part.trim();
      const isLong = /^--/.test(arg);
      const name2 = isLong ? arg.slice(2) : arg.slice(1);
      if (this.cmd.getBaseOption(name2, true)) {
        if (opts?.override) {
          this.removeOption(name2);
        } else {
          throw new DuplicateOptionNameError(name2, this.getPath());
        }
      }
      if (!option.name && isLong) {
        option.name = name2;
      } else if (!option.aliases) {
        option.aliases = [name2];
      } else {
        option.aliases.push(name2);
      }
    }
    if (option.prepend) {
      this.cmd.options.unshift(option);
    } else {
      this.cmd.options.push(option);
    }
    return this;
  }
  /**
   * Register command example.
   *
   * @param name          Name of the example.
   * @param description   The content of the example.
   */
  example(name2, description) {
    if (this.cmd.hasExample(name2)) {
      throw new DuplicateExampleError(name2);
    }
    this.cmd.examples.push({ name: name2, description });
    return this;
  }
  /**
   * @param flags Flags string e.g: -h, --help, --manual <requiredArg:string> [optionalArg:number] [...restArgs:string]
   * @param desc Flag description.
   * @param opts Flag options or custom handler for processing flag value.
   */
  /**
   * Register a global environment variable.
   *
   * @param name        Name of the environment variable.
   * @param description The description of the environment variable.
   * @param options     Environment variable options.
   */
  globalEnv(name2, description, options) {
    return this.env(
      name2,
      description,
      { ...options, global: true }
    );
  }
  env(name2, description, options) {
    const result2 = splitArguments(name2);
    if (!result2.typeDefinition) {
      result2.typeDefinition = "<value:boolean>";
    }
    if (result2.flags.some((envName) => this.cmd.getBaseEnvVar(envName, true))) {
      throw new DuplicateEnvVarError(name2);
    }
    const details = parseArgumentsDefinition(
      result2.typeDefinition
    );
    if (details.length > 1) {
      throw new TooManyEnvVarValuesError(name2);
    } else if (details.length && details[0].optional) {
      throw new UnexpectedOptionalEnvVarValueError(name2);
    } else if (details.length && details[0].variadic) {
      throw new UnexpectedVariadicEnvVarValueError(name2);
    }
    this.cmd.envVars.push({
      name: result2.flags[0],
      names: result2.flags,
      description,
      type: details[0].type,
      details: details.shift(),
      ...options
    });
    return this;
  }
  /*****************************************************************************
   **** MAIN HANDLER ***********************************************************
   *****************************************************************************/
  /**
   * Parse command line arguments and execute matched command.
   *
   * @param args Command line args to parse. Ex: `cmd.parse( Deno.args )`
   */
  parse(args = Deno.args) {
    const ctx = {
      unknown: args.slice(),
      flags: {},
      env: {},
      literal: [],
      stopEarly: false,
      stopOnUnknown: false,
      defaults: {},
      actions: []
    };
    return this.parseCommand(ctx);
  }
  async parseCommand(ctx) {
    try {
      this.reset();
      this.registerDefaults();
      this.rawArgs = ctx.unknown.slice();
      if (this.isExecutable) {
        await this.executeExecutable(ctx.unknown);
        return { options: {}, args: [], cmd: this, literal: [] };
      } else if (this._useRawArgs) {
        await this.parseEnvVars(ctx, this.envVars);
        return await this.execute(ctx.env, ctx.unknown);
      }
      let preParseGlobals = false;
      let subCommand;
      if (ctx.unknown.length > 0) {
        subCommand = this.getSubCommand(ctx);
        if (!subCommand) {
          const optionName = ctx.unknown[0].replace(/^-+/, "");
          const option = this.getOption(optionName, true);
          if (option?.global) {
            preParseGlobals = true;
            await this.parseGlobalOptionsAndEnvVars(ctx);
          }
        }
      }
      if (subCommand || ctx.unknown.length > 0) {
        subCommand ??= this.getSubCommand(ctx);
        if (subCommand) {
          subCommand._globalParent = this;
          return subCommand.parseCommand(ctx);
        }
      }
      await this.parseOptionsAndEnvVars(ctx, preParseGlobals);
      const options = { ...ctx.env, ...ctx.flags };
      const args = this.parseArguments(ctx, options);
      this.literalArgs = ctx.literal;
      if (ctx.actions.length) {
        await Promise.all(
          ctx.actions.map((action) => action.call(this, options, ...args))
        );
      }
      if (ctx.standalone) {
        return {
          options,
          args,
          cmd: this,
          literal: this.literalArgs
        };
      }
      return await this.execute(options, args);
    } catch (error2) {
      this.handleError(error2);
    }
  }
  getSubCommand(ctx) {
    const subCommand = this.getCommand(ctx.unknown[0], true);
    if (subCommand) {
      ctx.unknown.shift();
    }
    return subCommand;
  }
  async parseGlobalOptionsAndEnvVars(ctx) {
    const isHelpOption = this.getHelpOption()?.flags.includes(ctx.unknown[0]);
    const envVars = [
      ...this.envVars.filter((envVar) => envVar.global),
      ...this.getGlobalEnvVars(true)
    ];
    await this.parseEnvVars(ctx, envVars, !isHelpOption);
    const options = [
      ...this.options.filter((option) => option.global),
      ...this.getGlobalOptions(true)
    ];
    this.parseOptions(ctx, options, {
      stopEarly: true,
      stopOnUnknown: true,
      dotted: false
    });
  }
  async parseOptionsAndEnvVars(ctx, preParseGlobals) {
    const helpOption = this.getHelpOption();
    const isVersionOption = this._versionOption?.flags.includes(ctx.unknown[0]);
    const isHelpOption = helpOption && ctx.flags?.[helpOption.name] === true;
    const envVars = preParseGlobals ? this.envVars.filter((envVar) => !envVar.global) : this.getEnvVars(true);
    await this.parseEnvVars(
      ctx,
      envVars,
      !isHelpOption && !isVersionOption
    );
    const options = this.getOptions(true);
    this.parseOptions(ctx, options);
  }
  /** Register default options like `--version` and `--help`. */
  registerDefaults() {
    if (this.hasDefaults || this.getParent()) {
      return this;
    }
    this.hasDefaults = true;
    this.reset();
    !this.types.has("string") && this.type("string", new StringType(), { global: true });
    !this.types.has("number") && this.type("number", new NumberType(), { global: true });
    !this.types.has("integer") && this.type("integer", new IntegerType(), { global: true });
    !this.types.has("boolean") && this.type("boolean", new BooleanType(), { global: true });
    !this.types.has("file") && this.type("file", new FileType(), { global: true });
    if (!this._help) {
      this.help({});
    }
    if (this._versionOptions !== false && (this._versionOptions || this.ver)) {
      this.option(
        this._versionOptions?.flags || "-V, --version",
        this._versionOptions?.desc || "Show the version number for this program.",
        {
          standalone: true,
          prepend: true,
          action: async function() {
            const long = this.getRawArgs().includes(
              `--${this._versionOption?.name}`
            );
            if (long) {
              await checkVersion(this);
              this.showLongVersion();
            } else {
              this.showVersion();
            }
            this.exit();
          },
          ...this._versionOptions?.opts ?? {}
        }
      );
      this._versionOption = this.options[0];
    }
    if (this._helpOptions !== false) {
      this.option(
        this._helpOptions?.flags || "-h, --help",
        this._helpOptions?.desc || "Show this help.",
        {
          standalone: true,
          global: true,
          prepend: true,
          action: async function() {
            const long = this.getRawArgs().includes(
              `--${this.getHelpOption()?.name}`
            );
            await checkVersion(this);
            this.showHelp({ long });
            this.exit();
          },
          ...this._helpOptions?.opts ?? {}
        }
      );
      this._helpOption = this.options[0];
    }
    return this;
  }
  /**
   * Execute command.
   * @param options A map of options.
   * @param args Command arguments.
   */
  async execute(options, args) {
    if (this.defaultCommand) {
      const cmd = this.getCommand(this.defaultCommand, true);
      if (!cmd) {
        throw new DefaultCommandNotFoundError(
          this.defaultCommand,
          this.getCommands()
        );
      }
      cmd._globalParent = this;
      return cmd.execute(options, args);
    }
    await this.executeGlobalAction(options, args);
    if (this.actionHandler) {
      await this.actionHandler(options, ...args);
    }
    return {
      options,
      args,
      cmd: this,
      literal: this.literalArgs
    };
  }
  async executeGlobalAction(options, args) {
    if (!this._noGlobals) {
      await this._parent?.executeGlobalAction(options, args);
    }
    await this.globalActionHandler?.(options, ...args);
  }
  /**
   * Execute external sub-command.
   * @param args Raw command line arguments.
   */
  async executeExecutable(args) {
    const command = this.getPath().replace(/\s+/g, "-");
    await Deno.permissions.request({ name: "run", command });
    try {
      const cmd = new Deno.Command(command, {
        args
      });
      const output = await cmd.output();
      if (!output.success) {
        Deno.exit(output.code);
      }
    } catch (error2) {
      if (error2 instanceof Deno.errors.NotFound) {
        throw new CommandExecutableNotFoundError(command);
      }
      throw error2;
    }
  }
  /** Parse raw command line arguments. */
  parseOptions(ctx, options, {
    stopEarly = this._stopEarly,
    stopOnUnknown = false,
    dotted = true
  } = {}) {
    parseFlags(ctx, {
      stopEarly,
      stopOnUnknown,
      dotted,
      allowEmpty: this._allowEmpty,
      flags: options,
      ignoreDefaults: ctx.env,
      parse: (type4) => this.parseType(type4),
      option: (option) => {
        if (option.action) {
          ctx.actions.push(option.action);
        }
      }
    });
  }
  /** Parse argument type. */
  parseType(type4) {
    const typeSettings = this.getType(type4.type);
    if (!typeSettings) {
      throw new UnknownTypeError(
        type4.type,
        this.getTypes().map((type5) => type5.name)
      );
    }
    return typeSettings.handler instanceof Type ? typeSettings.handler.parse(type4) : typeSettings.handler(type4);
  }
  /**
   * Read and validate environment variables.
   * @param ctx Parse context.
   * @param envVars env vars defined by the command.
   * @param validate when true, throws an error if a required env var is missing.
   */
  async parseEnvVars(ctx, envVars, validate2 = true) {
    for (const envVar of envVars) {
      const env2 = await this.findEnvVar(envVar.names);
      if (env2) {
        const parseType = (value) => {
          return this.parseType({
            label: "Environment variable",
            type: envVar.type,
            name: env2.name,
            value
          });
        };
        const propertyName = underscoreToCamelCase(
          envVar.prefix ? envVar.names[0].replace(new RegExp(`^${envVar.prefix}`), "") : envVar.names[0]
        );
        if (envVar.details.list) {
          ctx.env[propertyName] = env2.value.split(envVar.details.separator ?? ",").map(parseType);
        } else {
          ctx.env[propertyName] = parseType(env2.value);
        }
        if (envVar.value && typeof ctx.env[propertyName] !== "undefined") {
          ctx.env[propertyName] = envVar.value(ctx.env[propertyName]);
        }
      } else if (envVar.required && validate2) {
        throw new MissingRequiredEnvVarError(envVar);
      }
    }
  }
  async findEnvVar(names) {
    for (const name2 of names) {
      const status = await Deno.permissions.query({
        name: "env",
        variable: name2
      });
      if (status.state === "granted") {
        const value = Deno.env.get(name2);
        if (value) {
          return { name: name2, value };
        }
      }
    }
    return void 0;
  }
  /**
   * Parse command-line arguments.
   * @param ctx     Parse context.
   * @param options Parsed command line options.
   */
  parseArguments(ctx, options) {
    const params = [];
    const args = ctx.unknown.slice();
    if (!this.hasArguments()) {
      if (args.length) {
        if (this.hasCommands(true)) {
          if (this.hasCommand(args[0], true)) {
            throw new TooManyArgumentsError(args);
          } else {
            throw new UnknownCommandError(args[0], this.getCommands());
          }
        } else {
          throw new NoArgumentsAllowedError(this.getPath());
        }
      }
    } else {
      if (!args.length) {
        const required = this.getArguments().filter((expectedArg) => !expectedArg.optional).map((expectedArg) => expectedArg.name);
        if (required.length) {
          const optionNames = Object.keys(options);
          const hasStandaloneOption = !!optionNames.find(
            (name2) => this.getOption(name2, true)?.standalone
          );
          if (!hasStandaloneOption) {
            throw new MissingArgumentsError(required);
          }
        }
      } else {
        for (const expectedArg of this.getArguments()) {
          if (!args.length) {
            if (expectedArg.optional) {
              break;
            }
            throw new MissingArgumentError(expectedArg.name);
          }
          let arg;
          const parseArgValue = (value) => {
            return expectedArg.list ? value.split(",").map((value2) => parseArgType(value2)) : parseArgType(value);
          };
          const parseArgType = (value) => {
            return this.parseType({
              label: "Argument",
              type: expectedArg.type,
              name: expectedArg.name,
              value
            });
          };
          if (expectedArg.variadic) {
            arg = args.splice(0, args.length).map(
              (value) => parseArgValue(value)
            );
          } else {
            arg = parseArgValue(args.shift());
          }
          if (expectedArg.variadic && Array.isArray(arg)) {
            params.push(...arg);
          } else if (typeof arg !== "undefined") {
            params.push(arg);
          }
        }
        if (args.length) {
          throw new TooManyArgumentsError(args);
        }
      }
    }
    return params;
  }
  handleError(error2) {
    this.throw(
      error2 instanceof ValidationError ? new ValidationError2(error2.message) : error2 instanceof Error ? error2 : new Error(`[non-error-thrown] ${error2}`)
    );
  }
  /**
   * Handle error. If `throwErrors` is enabled the error will be thrown,
   * otherwise a formatted error message will be printed and `Deno.exit(1)`
   * will be called. This will also trigger registered error handlers.
   *
   * @param error The error to handle.
   */
  throw(error2) {
    if (error2 instanceof ValidationError2) {
      error2.cmd = this;
    }
    this.getErrorHandler()?.(error2, this);
    if (this.shouldThrowErrors() || !(error2 instanceof ValidationError2)) {
      throw error2;
    }
    this.showHelp();
    console.error(red2(`  ${bold2("error")}: ${error2.message}
`));
    Deno.exit(error2 instanceof ValidationError2 ? error2.exitCode : 1);
  }
  /*****************************************************************************
   **** GETTER *****************************************************************
   *****************************************************************************/
  /** Get command name. */
  getName() {
    return this._name;
  }
  /** Get parent command. */
  getParent() {
    return this._parent;
  }
  /**
   * Get parent command from global executed command.
   * Be sure, to call this method only inside an action handler. Unless this or any child command was executed,
   * this method returns always undefined.
   */
  getGlobalParent() {
    return this._globalParent;
  }
  /** Get main command. */
  getMainCommand() {
    return this._parent?.getMainCommand() ?? this;
  }
  /** Get command name aliases. */
  getAliases() {
    return this.aliases;
  }
  /**
   * Get full command path.
   *
   * @param name Override the main command name.
   */
  getPath(name2) {
    return this._parent ? this._parent.getPath(name2) + " " + this._name : name2 || this._name;
  }
  /** Get arguments definition. E.g: <input-file:string> <output-file:string> */
  getArgsDefinition() {
    return this.argsDefinition;
  }
  /**
   * Get argument by name.
   *
   * @param name Name of the argument.
   */
  getArgument(name2) {
    return this.getArguments().find((arg) => arg.name === name2);
  }
  /** Get arguments. */
  getArguments() {
    if (!this.args.length && this.argsDefinition) {
      this.args = parseArgumentsDefinition(this.argsDefinition);
    }
    return this.args;
  }
  /** Check if command has arguments. */
  hasArguments() {
    return !!this.argsDefinition;
  }
  /** Get command version. */
  getVersion() {
    return this.getVersionHandler()?.call(this, this);
  }
  /** Get help handler method. */
  getVersionHandler() {
    return this.ver ?? this._parent?.getVersionHandler();
  }
  /** Get command description. */
  getDescription() {
    return typeof this.desc === "function" ? this.desc = this.desc() : this.desc;
  }
  /** Get auto generated command usage. */
  getUsage() {
    return this._usage ?? [this.getArgsDefinition(), this.getRequiredOptionsDefinition()].join(" ").trim();
  }
  getRequiredOptionsDefinition() {
    return this.getOptions().filter((option) => option.required).map(
      (option) => [findFlag(option.flags), option.typeDefinition].filter((v4) => v4).join(" ").trim()
    ).join(" ");
  }
  /** Get short command description. This is the first line of the description. */
  getShortDescription() {
    return getDescription(this.getDescription(), true);
  }
  /** Get original command-line arguments. */
  getRawArgs() {
    return this.rawArgs;
  }
  /** Get all arguments defined after the double dash. */
  getLiteralArgs() {
    return this.literalArgs;
  }
  /** Output generated help without exiting. */
  showVersion() {
    console.log(this.getVersion());
  }
  /** Returns command name, version and meta data. */
  getLongVersion() {
    return `${bold2(this.getMainCommand().getName())} ${brightBlue(this.getVersion() ?? "")}` + Object.entries(this.getMeta()).map(
      ([k3, v4]) => `
${bold2(k3)} ${brightBlue(v4)}`
    ).join("");
  }
  /** Outputs command name, version and meta data. */
  showLongVersion() {
    console.log(this.getLongVersion());
  }
  /** Output generated help without exiting. */
  showHelp(options) {
    console.log(this.getHelp(options));
  }
  /** Get generated help. */
  getHelp(options) {
    this.registerDefaults();
    return this.getHelpHandler().call(this, this, options ?? {});
  }
  /** Get help handler method. */
  getHelpHandler() {
    return this._help ?? this._parent?.getHelpHandler();
  }
  exit(code5 = 0) {
    if (this.shouldExit()) {
      Deno.exit(code5);
    }
  }
  /*****************************************************************************
   **** Options GETTER *********************************************************
   *****************************************************************************/
  /**
   * Checks whether the command has options or not.
   *
   * @param hidden Include hidden options.
   */
  hasOptions(hidden2) {
    return this.getOptions(hidden2).length > 0;
  }
  /**
   * Get options.
   *
   * @param hidden Include hidden options.
   */
  getOptions(hidden2) {
    return this.getGlobalOptions(hidden2).concat(this.getBaseOptions(hidden2));
  }
  /**
   * Get base options.
   *
   * @param hidden Include hidden options.
   */
  getBaseOptions(hidden2) {
    if (!this.options.length) {
      return [];
    }
    return hidden2 ? this.options.slice(0) : this.options.filter((opt) => !opt.hidden);
  }
  /**
   * Get global options.
   *
   * @param hidden Include hidden options.
   */
  getGlobalOptions(hidden2) {
    const helpOption = this.getHelpOption();
    const getGlobals = (cmd, noGlobals, options = [], names = []) => {
      if (cmd.options.length) {
        for (const option of cmd.options) {
          if (option.global && !this.options.find((opt) => opt.name === option.name) && names.indexOf(option.name) === -1 && (hidden2 || !option.hidden)) {
            if (noGlobals && option !== helpOption) {
              continue;
            }
            names.push(option.name);
            options.push(option);
          }
        }
      }
      return cmd._parent ? getGlobals(
        cmd._parent,
        noGlobals || cmd._noGlobals,
        options,
        names
      ) : options;
    };
    return this._parent ? getGlobals(this._parent, this._noGlobals) : [];
  }
  /**
   * Checks whether the command has an option with given name or not.
   *
   * @param name Name of the option. Must be in param-case.
   * @param hidden Include hidden options.
   */
  hasOption(name2, hidden2) {
    return !!this.getOption(name2, hidden2);
  }
  /**
   * Get option by name.
   *
   * @param name Name of the option. Must be in param-case.
   * @param hidden Include hidden options.
   */
  getOption(name2, hidden2) {
    return this.getBaseOption(name2, hidden2) ?? this.getGlobalOption(name2, hidden2);
  }
  /**
   * Get base option by name.
   *
   * @param name Name of the option. Must be in param-case.
   * @param hidden Include hidden options.
   */
  getBaseOption(name2, hidden2) {
    const option = this.options.find(
      (option2) => option2.name === name2 || option2.aliases?.includes(name2)
    );
    return option && (hidden2 || !option.hidden) ? option : void 0;
  }
  /**
   * Get global option from parent commands by name.
   *
   * @param name Name of the option. Must be in param-case.
   * @param hidden Include hidden options.
   */
  getGlobalOption(name2, hidden2) {
    const helpOption = this.getHelpOption();
    const getGlobalOption = (parent, noGlobals) => {
      const option = parent.getBaseOption(
        name2,
        hidden2
      );
      if (!option?.global) {
        return parent._parent && getGlobalOption(
          parent._parent,
          noGlobals || parent._noGlobals
        );
      }
      if (noGlobals && option !== helpOption) {
        return;
      }
      return option;
    };
    return this._parent && getGlobalOption(
      this._parent,
      this._noGlobals
    );
  }
  /**
   * Remove option by name.
   *
   * @param name Name of the option. Must be in param-case.
   */
  removeOption(name2) {
    const index2 = this.options.findIndex((option) => option.name === name2);
    if (index2 === -1) {
      return;
    }
    return this.options.splice(index2, 1)[0];
  }
  /**
   * Checks whether the command has sub-commands or not.
   *
   * @param hidden Include hidden commands.
   */
  hasCommands(hidden2) {
    return this.getCommands(hidden2).length > 0;
  }
  /**
   * Get commands.
   *
   * @param hidden Include hidden commands.
   */
  getCommands(hidden2) {
    return this.getGlobalCommands(hidden2).concat(this.getBaseCommands(hidden2));
  }
  /**
   * Get base commands.
   *
   * @param hidden Include hidden commands.
   */
  getBaseCommands(hidden2) {
    const commands2 = Array.from(this.commands.values());
    return hidden2 ? commands2 : commands2.filter((cmd) => !cmd.isHidden);
  }
  /**
   * Get global commands.
   *
   * @param hidden Include hidden commands.
   */
  getGlobalCommands(hidden2) {
    const getCommands = (command, noGlobals, commands2 = [], names = []) => {
      if (command.commands.size) {
        for (const [_3, cmd] of command.commands) {
          if (cmd.isGlobal && this !== cmd && !this.commands.has(cmd._name) && names.indexOf(cmd._name) === -1 && (hidden2 || !cmd.isHidden)) {
            if (noGlobals && cmd?.getName() !== "help") {
              continue;
            }
            names.push(cmd._name);
            commands2.push(cmd);
          }
        }
      }
      return command._parent ? getCommands(
        command._parent,
        noGlobals || command._noGlobals,
        commands2,
        names
      ) : commands2;
    };
    return this._parent ? getCommands(this._parent, this._noGlobals) : [];
  }
  /**
   * Checks whether a child command exists by given name or alias.
   *
   * @param name Name or alias of the command.
   * @param hidden Include hidden commands.
   */
  hasCommand(name2, hidden2) {
    return !!this.getCommand(name2, hidden2);
  }
  /**
   * Get command by name or alias.
   *
   * @param name Name or alias of the command.
   * @param hidden Include hidden commands.
   */
  getCommand(name2, hidden2) {
    return this.getBaseCommand(name2, hidden2) ?? this.getGlobalCommand(name2, hidden2);
  }
  /**
   * Get base command by name or alias.
   *
   * @param name Name or alias of the command.
   * @param hidden Include hidden commands.
   */
  getBaseCommand(name2, hidden2) {
    for (const cmd of this.commands.values()) {
      if (cmd._name === name2 || cmd.aliases.includes(name2)) {
        return cmd && (hidden2 || !cmd.isHidden) ? cmd : void 0;
      }
    }
  }
  /**
   * Get global command by name or alias.
   *
   * @param name Name or alias of the command.
   * @param hidden Include hidden commands.
   */
  getGlobalCommand(name2, hidden2) {
    const getGlobalCommand = (parent, noGlobals) => {
      const cmd = parent.getBaseCommand(name2, hidden2);
      if (!cmd?.isGlobal) {
        return parent._parent && getGlobalCommand(parent._parent, noGlobals || parent._noGlobals);
      }
      if (noGlobals && cmd.getName() !== "help") {
        return;
      }
      return cmd;
    };
    return this._parent && getGlobalCommand(this._parent, this._noGlobals);
  }
  /**
   * Remove sub-command by name or alias.
   *
   * @param name Name or alias of the command.
   */
  removeCommand(name2) {
    const command = this.getBaseCommand(name2, true);
    if (command) {
      this.commands.delete(command._name);
    }
    return command;
  }
  /** Get types. */
  getTypes() {
    return this.getGlobalTypes().concat(this.getBaseTypes());
  }
  /** Get base types. */
  getBaseTypes() {
    return Array.from(this.types.values());
  }
  /** Get global types. */
  getGlobalTypes() {
    const getTypes = (cmd, types8 = [], names = []) => {
      if (cmd) {
        if (cmd.types.size) {
          cmd.types.forEach((type4) => {
            if (type4.global && !this.types.has(type4.name) && names.indexOf(type4.name) === -1) {
              names.push(type4.name);
              types8.push(type4);
            }
          });
        }
        return getTypes(cmd._parent, types8, names);
      }
      return types8;
    };
    return getTypes(this._parent);
  }
  /**
   * Get type by name.
   *
   * @param name Name of the type.
   */
  getType(name2) {
    return this.getBaseType(name2) ?? this.getGlobalType(name2);
  }
  /**
   * Get base type by name.
   *
   * @param name Name of the type.
   */
  getBaseType(name2) {
    return this.types.get(name2);
  }
  /**
   * Get global type by name.
   *
   * @param name Name of the type.
   */
  getGlobalType(name2) {
    if (!this._parent) {
      return;
    }
    const cmd = this._parent.getBaseType(name2);
    if (!cmd?.global) {
      return this._parent.getGlobalType(name2);
    }
    return cmd;
  }
  /** Get completions. */
  getCompletions() {
    return this.getGlobalCompletions().concat(this.getBaseCompletions());
  }
  /** Get base completions. */
  getBaseCompletions() {
    return Array.from(this.completions.values());
  }
  /** Get global completions. */
  getGlobalCompletions() {
    const getCompletions = (cmd, completions = [], names = []) => {
      if (cmd) {
        if (cmd.completions.size) {
          cmd.completions.forEach((completion) => {
            if (completion.global && !this.completions.has(completion.name) && names.indexOf(completion.name) === -1) {
              names.push(completion.name);
              completions.push(completion);
            }
          });
        }
        return getCompletions(cmd._parent, completions, names);
      }
      return completions;
    };
    return getCompletions(this._parent);
  }
  /**
   * Get completion by name.
   *
   * @param name Name of the completion.
   */
  getCompletion(name2) {
    return this.getBaseCompletion(name2) ?? this.getGlobalCompletion(name2);
  }
  /**
   * Get base completion by name.
   *
   * @param name Name of the completion.
   */
  getBaseCompletion(name2) {
    return this.completions.get(name2);
  }
  /**
   * Get global completions by name.
   *
   * @param name Name of the completion.
   */
  getGlobalCompletion(name2) {
    if (!this._parent) {
      return;
    }
    const completion = this._parent.getBaseCompletion(
      name2
    );
    if (!completion?.global) {
      return this._parent.getGlobalCompletion(name2);
    }
    return completion;
  }
  /**
   * Checks whether the command has environment variables or not.
   *
   * @param hidden Include hidden environment variable.
   */
  hasEnvVars(hidden2) {
    return this.getEnvVars(hidden2).length > 0;
  }
  /**
   * Get environment variables.
   *
   * @param hidden Include hidden environment variable.
   */
  getEnvVars(hidden2) {
    return this.getGlobalEnvVars(hidden2).concat(this.getBaseEnvVars(hidden2));
  }
  /**
   * Get base environment variables.
   *
   * @param hidden Include hidden environment variable.
   */
  getBaseEnvVars(hidden2) {
    if (!this.envVars.length) {
      return [];
    }
    return hidden2 ? this.envVars.slice(0) : this.envVars.filter((env2) => !env2.hidden);
  }
  /**
   * Get global environment variables.
   *
   * @param hidden Include hidden environment variable.
   */
  getGlobalEnvVars(hidden2) {
    if (this._noGlobals) {
      return [];
    }
    const getEnvVars = (cmd, envVars = [], names = []) => {
      if (cmd) {
        if (cmd.envVars.length) {
          cmd.envVars.forEach((envVar) => {
            if (envVar.global && !this.envVars.find((env2) => env2.names[0] === envVar.names[0]) && names.indexOf(envVar.names[0]) === -1 && (hidden2 || !envVar.hidden)) {
              names.push(envVar.names[0]);
              envVars.push(envVar);
            }
          });
        }
        return getEnvVars(cmd._parent, envVars, names);
      }
      return envVars;
    };
    return getEnvVars(this._parent);
  }
  /**
   * Checks whether the command has an environment variable with given name or not.
   *
   * @param name Name of the environment variable.
   * @param hidden Include hidden environment variable.
   */
  hasEnvVar(name2, hidden2) {
    return !!this.getEnvVar(name2, hidden2);
  }
  /**
   * Get environment variable by name.
   *
   * @param name Name of the environment variable.
   * @param hidden Include hidden environment variable.
   */
  getEnvVar(name2, hidden2) {
    return this.getBaseEnvVar(name2, hidden2) ?? this.getGlobalEnvVar(name2, hidden2);
  }
  /**
   * Get base environment variable by name.
   *
   * @param name Name of the environment variable.
   * @param hidden Include hidden environment variable.
   */
  getBaseEnvVar(name2, hidden2) {
    const envVar = this.envVars.find(
      (env2) => env2.names.indexOf(name2) !== -1
    );
    return envVar && (hidden2 || !envVar.hidden) ? envVar : void 0;
  }
  /**
   * Get global environment variable by name.
   *
   * @param name Name of the environment variable.
   * @param hidden Include hidden environment variable.
   */
  getGlobalEnvVar(name2, hidden2) {
    if (!this._parent || this._noGlobals) {
      return;
    }
    const envVar = this._parent.getBaseEnvVar(
      name2,
      hidden2
    );
    if (!envVar?.global) {
      return this._parent.getGlobalEnvVar(name2, hidden2);
    }
    return envVar;
  }
  /** Checks whether the command has examples or not. */
  hasExamples() {
    return this.examples.length > 0;
  }
  /** Get all examples. */
  getExamples() {
    return this.examples;
  }
  /** Checks whether the command has an example with given name or not. */
  hasExample(name2) {
    return !!this.getExample(name2);
  }
  /** Get example with given name. */
  getExample(name2) {
    return this.examples.find((example) => example.name === name2);
  }
  getHelpOption() {
    return this._helpOption ?? this._parent?.getHelpOption();
  }
};
function findFlag(flags) {
  for (const flag of flags) {
    if (flag.startsWith("--")) {
      return flag;
    }
  }
  return flags[0];
}

// https://deno.land/x/cliffy@v1.0.0-rc.3/command/types/command.ts
var CommandType = class extends StringType {
  /** Complete sub-command names of global parent command. */
  complete(_cmd, parent) {
    return parent?.getCommands(false).map((cmd) => cmd.getName()) || [];
  }
};

// https://deno.land/x/cliffy@v1.0.0-rc.3/command/help/help_command.ts
var HelpCommand = class extends Command {
  constructor(cmd) {
    super();
    return this.type("command", new CommandType()).arguments("[command:command]").description("Show this help or the help of a sub-command.").noGlobals().action(async (_3, name2) => {
      if (!cmd) {
        cmd = name2 ? this.getGlobalParent()?.getBaseCommand(name2) : this.getGlobalParent();
      }
      if (!cmd) {
        const cmds = this.getGlobalParent()?.getCommands();
        throw new UnknownCommandError(name2 ?? "", cmds ?? [], [
          this.getName(),
          ...this.getAliases()
        ]);
      }
      await checkVersion(cmd);
      cmd.showHelp();
      if (this.shouldExit()) {
        Deno.exit(0);
      }
    });
  }
};

// https://deno.land/x/cliffy@v1.0.0-rc.3/command/completions/_bash_completions_generator.ts
var BashCompletionsGenerator = class _BashCompletionsGenerator {
  constructor(name2, cmd) {
    this.name = name2;
    this.cmd = cmd;
  }
  /** Generates bash completions script for given command. */
  static generate(name2, cmd) {
    if (!name2 || name2 === "COMMAND") {
      throw new MissingCommandNameCompletionsError("bash");
    }
    return new _BashCompletionsGenerator(name2, cmd).generate();
  }
  /** Generates bash completions code. */
  generate() {
    const path3 = this.cmd.getPath(this.name);
    const version4 = this.cmd.getVersion() ? ` v${this.cmd.getVersion()}` : "";
    return `#!/usr/bin/env bash
# bash completion support for ${path3}${version4}

_${replaceSpecialChars(path3)}() {
  local word cur prev listFiles
  local -a opts
  COMPREPLY=()
  cur="\${COMP_WORDS[COMP_CWORD]}"
  prev="\${COMP_WORDS[COMP_CWORD-1]}"
  cmd="_"
  opts=()
  listFiles=0

  _${replaceSpecialChars(this.name)}_complete() {
    local action="$1"; shift
    mapfile -t values < <( ${this.name} completions complete "\${action}" "\${@}" )
    for i in "\${values[@]}"; do
      opts+=("$i")
    done
  }

  _${replaceSpecialChars(this.name)}_expand() {
    [ "$cur" != "\${cur%\\\\}" ] && cur="$cur\\\\"
  
    # expand ~username type directory specifications
    if [[ "$cur" == \\~*/* ]]; then
      # shellcheck disable=SC2086
      eval cur=$cur
      
    elif [[ "$cur" == \\~* ]]; then
      cur=\${cur#\\~}
      # shellcheck disable=SC2086,SC2207
      COMPREPLY=( $( compgen -P '~' -u $cur ) )
      return \${#COMPREPLY[@]}
    fi
  }

  # shellcheck disable=SC2120
  _${replaceSpecialChars(this.name)}_file_dir() {
    listFiles=1
    local IFS=$'\\t\\n' xspec #glob
    _${replaceSpecialChars(this.name)}_expand || return 0
  
    if [ "\${1:-}" = -d ]; then
      # shellcheck disable=SC2206,SC2207,SC2086
      COMPREPLY=( \${COMPREPLY[@]:-} $( compgen -d -- $cur ) )
      #eval "$glob"    # restore glob setting.
      return 0
    fi
  
    xspec=\${1:+"!*.$1"}	# set only if glob passed in as $1
    # shellcheck disable=SC2206,SC2207
    COMPREPLY=( \${COMPREPLY[@]:-} $( compgen -f -X "$xspec" -- "$cur" )           $( compgen -d -- "$cur" ) )
  }

  ${this.generateCompletions(this.name, this.cmd).trim()}

  for word in "\${COMP_WORDS[@]}"; do
    case "\${word}" in
      -*) ;;
      *)
        cmd_tmp="\${cmd}_\${word//[^[:alnum:]]/_}"
        if type "\${cmd_tmp}" &>/dev/null; then
          cmd="\${cmd_tmp}"
        fi
    esac
  done

  \${cmd}

  if [[ listFiles -eq 1 ]]; then
    return 0
  fi

  if [[ \${#opts[@]} -eq 0 ]]; then
    # shellcheck disable=SC2207
    COMPREPLY=($(compgen -f "\${cur}"))
    return 0
  fi

  local values
  values="$( printf "\\n%s" "\${opts[@]}" )"
  local IFS=$'\\n'
  # shellcheck disable=SC2207
  local result=($(compgen -W "\${values[@]}" -- "\${cur}"))
  if [[ \${#result[@]} -eq 0 ]]; then
    # shellcheck disable=SC2207
    COMPREPLY=($(compgen -f "\${cur}"))
  else
    # shellcheck disable=SC2207
    COMPREPLY=($(printf '%q\\n' "\${result[@]}"))
  fi

  return 0
}

complete -F _${replaceSpecialChars(path3)} -o bashdefault -o default ${path3}`;
  }
  /** Generates bash completions method for given command and child commands. */
  generateCompletions(name2, command, path3 = "", index2 = 1) {
    path3 = (path3 ? path3 + " " : "") + name2;
    const commandCompletions = this.generateCommandCompletions(
      command,
      path3,
      index2
    );
    const childCommandCompletions = command.getCommands(false).filter((subCommand) => subCommand !== command).map(
      (subCommand) => this.generateCompletions(
        subCommand.getName(),
        subCommand,
        path3,
        index2 + 1
      )
    ).join("");
    return `${commandCompletions}

${childCommandCompletions}`;
  }
  generateCommandCompletions(command, path3, index2) {
    const flags = this.getFlags(command);
    const childCommandNames = command.getCommands(false).map((childCommand) => childCommand.getName());
    const completionsPath = ~path3.indexOf(" ") ? " " + path3.split(" ").slice(1).join(" ") : "";
    const optionArguments = this.generateOptionArguments(
      command,
      completionsPath
    );
    const completionsCmd = this.generateCommandCompletionsCommand(
      command,
      completionsPath
    );
    return `  __${replaceSpecialChars(path3)}() {
    opts=(${[...flags, ...childCommandNames].join(" ")})
    ${completionsCmd}
    if [[ \${cur} == -* || \${COMP_CWORD} -eq ${index2} ]] ; then
      return 0
    fi
    ${optionArguments}
  }`;
  }
  getFlags(command) {
    return command.getOptions(false).map((option) => option.flags).flat();
  }
  generateOptionArguments(command, completionsPath) {
    let opts = "";
    const options = command.getOptions(false);
    if (options.length) {
      opts += 'case "${prev}" in';
      for (const option of options) {
        const flags = option.flags.map((flag) => flag.trim()).join("|");
        const completionsCmd = this.generateOptionCompletionsCommand(
          command,
          option.args,
          completionsPath,
          { standalone: option.standalone }
        );
        opts += `
      ${flags}) ${completionsCmd} ;;`;
      }
      opts += "\n    esac";
    }
    return opts;
  }
  generateCommandCompletionsCommand(command, path3) {
    const args = command.getArguments();
    if (args.length) {
      const type4 = command.getType(args[0].type);
      if (type4 && type4.handler instanceof FileType) {
        return `_${replaceSpecialChars(this.name)}_file_dir`;
      }
      return `_${replaceSpecialChars(this.name)}_complete ${args[0].action}${path3}`;
    }
    return "";
  }
  generateOptionCompletionsCommand(command, args, path3, opts) {
    if (args.length) {
      const type4 = command.getType(args[0].type);
      if (type4 && type4.handler instanceof FileType) {
        return `opts=(); _${replaceSpecialChars(this.name)}_file_dir`;
      }
      return `opts=(); _${replaceSpecialChars(this.name)}_complete ${args[0].action}${path3}`;
    }
    if (opts?.standalone) {
      return "opts=()";
    }
    return "";
  }
};
function replaceSpecialChars(str3) {
  return str3.replace(/[^a-zA-Z0-9]/g, "_");
}

// https://deno.land/x/cliffy@v1.0.0-rc.3/command/completions/bash.ts
var BashCompletionsCommand = class extends Command {
  #cmd;
  constructor(cmd) {
    super();
    this.#cmd = cmd;
    return this.description(() => {
      const baseCmd = this.#cmd || this.getMainCommand();
      return `Generate shell completions for bash.

To enable bash completions for this program add following line to your ${dim(italic("~/.bashrc"))}:

    ${dim(italic(`source <(${baseCmd.getPath()} completions bash)`))}`;
    }).noGlobals().option("-n, --name <command-name>", "The name of the main command.").action(({ name: name2 = this.getMainCommand().getName() }) => {
      const baseCmd = this.#cmd || this.getMainCommand();
      console.log(BashCompletionsGenerator.generate(name2, baseCmd));
    });
  }
};

// https://deno.land/x/cliffy@v1.0.0-rc.3/command/completions/_fish_completions_generator.ts
var FishCompletionsGenerator = class _FishCompletionsGenerator {
  constructor(name2, cmd) {
    this.name = name2;
    this.cmd = cmd;
  }
  /** Generates fish completions script for given command. */
  static generate(name2, cmd) {
    if (!name2 || name2 === "COMMAND") {
      throw new MissingCommandNameCompletionsError("fish");
    }
    return new _FishCompletionsGenerator(name2, cmd).generate();
  }
  /** Generates fish completions script. */
  generate() {
    const path3 = this.cmd.getPath(this.name);
    const version4 = this.cmd.getVersion() ? ` v${this.cmd.getVersion()}` : "";
    return `#!/usr/bin/env fish
# fish completion support for ${path3}${version4}

function __fish_${replaceSpecialChars2(this.name)}_using_command
  set -l cmds ${getCommandFnNames(this.name, this.cmd).join(" ")}
  set -l words (commandline -opc)
  set -l cmd "_"
  for word in $words
    switch $word
      case '-*'
        continue
      case '*'
        set word (string replace -r -a '\\W' '_' $word)
        set -l cmd_tmp $cmd"_$word"
        if contains $cmd_tmp $cmds
          set cmd $cmd_tmp
        end
    end
  end
  if test "$cmd" = "$argv[1]"
    return 0
  end
  return 1
end

${this.generateCompletions(this.name, this.cmd).trim()}`;
  }
  generateCompletions(name2, command) {
    const parent = command.getParent();
    let result2 = ``;
    if (parent) {
      result2 += "\n" + this.complete(parent, {
        description: command.getShortDescription(),
        arguments: name2
      });
    }
    const commandArgs = command.getArguments();
    if (commandArgs.length) {
      result2 += "\n" + this.complete(command, {
        arguments: commandArgs.length ? this.getCompletionCommand(command, commandArgs[0]) : void 0
      });
    }
    for (const option of command.getOptions(false)) {
      result2 += "\n" + this.completeOption(command, option);
    }
    for (const subCommand of command.getCommands(false)) {
      result2 += this.generateCompletions(subCommand.getName(), subCommand);
    }
    return result2;
  }
  completeOption(command, option) {
    const shortOption = option.flags.find((flag) => flag.length === 2)?.replace(/^(-)+/, "");
    const longOption = option.flags.find((flag) => flag.length > 2)?.replace(/^(-)+/, "");
    return this.complete(command, {
      description: getDescription(option.description),
      shortOption,
      longOption,
      // required: option.requiredValue,
      required: true,
      standalone: option.standalone,
      arguments: option.args.length ? this.getCompletionCommand(command, option.args[0]) : void 0
    });
  }
  complete(command, options) {
    const cmd = ["complete"];
    cmd.push("-c", this.name);
    cmd.push(
      "-n",
      `'__fish_${replaceSpecialChars2(this.name)}_using_command __${replaceSpecialChars2(command.getPath(this.name))}'`
    );
    options.shortOption && cmd.push("-s", options.shortOption);
    options.longOption && cmd.push("-l", options.longOption);
    options.standalone && cmd.push("-x");
    cmd.push("-k");
    cmd.push("-f");
    if (options.arguments) {
      options.required && cmd.push("-r");
      cmd.push("-a", options.arguments);
    }
    if (options.description) {
      const description = getDescription(options.description, true).replace(/'/g, "\\'");
      cmd.push("-d", `'${description}'`);
    }
    return cmd.join(" ");
  }
  getCompletionCommand(cmd, arg) {
    const type4 = cmd.getType(arg.type);
    if (type4 && type4.handler instanceof FileType) {
      return `'(__fish_complete_path)'`;
    }
    return `'(${this.name} completions complete ${arg.action + " " + getCompletionsPath(cmd)})'`;
  }
};
function getCommandFnNames(name2, cmd, cmds = []) {
  cmds.push(`__${replaceSpecialChars2(cmd.getPath(name2))}`);
  cmd.getCommands(false).forEach((command) => {
    getCommandFnNames(name2, command, cmds);
  });
  return cmds;
}
function getCompletionsPath(command) {
  return command.getPath().split(" ").slice(1).join(" ");
}
function replaceSpecialChars2(str3) {
  return str3.replace(/[^a-zA-Z0-9]/g, "_");
}

// https://deno.land/x/cliffy@v1.0.0-rc.3/command/completions/fish.ts
var FishCompletionsCommand = class extends Command {
  #cmd;
  constructor(cmd) {
    super();
    this.#cmd = cmd;
    return this.description(() => {
      const baseCmd = this.#cmd || this.getMainCommand();
      return `Generate shell completions for fish.

To enable fish completions for this program add following line to your ${dim(italic("~/.config/fish/config.fish"))}:

    ${dim(italic(`source (${baseCmd.getPath()} completions fish | psub)`))}`;
    }).noGlobals().option("-n, --name <command-name>", "The name of the main command.").action(({ name: name2 = this.getMainCommand().getName() }) => {
      const baseCmd = this.#cmd || this.getMainCommand();
      console.log(FishCompletionsGenerator.generate(name2, baseCmd));
    });
  }
};

// https://deno.land/x/cliffy@v1.0.0-rc.3/command/completions/_zsh_completions_generator.ts
var ZshCompletionsGenerator = class _ZshCompletionsGenerator {
  constructor(name2, cmd) {
    this.name = name2;
    this.cmd = cmd;
  }
  actions = /* @__PURE__ */ new Map();
  /** Generates zsh completions script for given command. */
  static generate(name2, cmd) {
    if (!name2 || name2 === "COMMAND") {
      throw new MissingCommandNameCompletionsError("zsh");
    }
    return new _ZshCompletionsGenerator(name2, cmd).generate();
  }
  /** Generates zsh completions code. */
  generate() {
    const path3 = this.cmd.getPath(this.name);
    const version4 = this.cmd.getVersion() ? ` v${this.cmd.getVersion()}` : "";
    return `#!/usr/bin/env zsh
# zsh completion support for ${path3}${version4}

autoload -U is-at-least

# shellcheck disable=SC2154
(( $+functions[__${replaceSpecialChars3(this.name)}_complete] )) ||
function __${replaceSpecialChars3(this.name)}_complete {
  local name="$1"; shift
  local action="$1"; shift
  integer ret=1
  local -a values
  local expl lines
  _tags "$name"
  while _tags; do
    if _requested "$name"; then
      # shellcheck disable=SC2034
      lines="$(${this.name} completions complete "\${action}" "\${@}")"
      values=("\${(ps:\\n:)lines}")
      if (( \${#values[@]} )); then
        while _next_label "$name" expl "$action"; do
          compadd -S '' "\${expl[@]}" "\${values[@]}"
        done
      fi
    fi
  done
}

${this.generateCompletions(this.name, this.cmd).trim()}

# _${replaceSpecialChars3(path3)} "\${@}"

compdef _${replaceSpecialChars3(path3)} ${path3}`;
  }
  /** Generates zsh completions method for given command and child commands. */
  generateCompletions(name2, command, path3 = "") {
    if (!command.hasCommands(false) && !command.hasOptions(false) && !command.hasArguments()) {
      return "";
    }
    path3 = (path3 ? path3 + " " : "") + name2;
    return `# shellcheck disable=SC2154
(( $+functions[_${replaceSpecialChars3(path3)}] )) ||
function _${replaceSpecialChars3(path3)}() {` + (!command.getParent() ? `
  local state` : "") + this.generateCommandCompletions(command, path3) + this.generateSubCommandCompletions(command, path3) + this.generateArgumentCompletions(command, path3) + this.generateActions(command) + `
}

` + command.getCommands(false).filter((subCommand) => subCommand !== command).map(
      (subCommand) => this.generateCompletions(subCommand.getName(), subCommand, path3)
    ).join("");
  }
  generateCommandCompletions(command, path3) {
    const commands2 = command.getCommands(false);
    let completions = commands2.map(
      (subCommand) => `'${subCommand.getName()}:${subCommand.getShortDescription().replace(/'/g, `'"'"'`)}'`
    ).join("\n      ");
    if (completions) {
      completions = `
    local -a commands
    # shellcheck disable=SC2034
    commands=(
      ${completions}
    )
    _describe 'command' commands`;
    }
    if (command.hasArguments()) {
      const completionsPath = path3.split(" ").slice(1).join(" ");
      const arg = command.getArguments()[0];
      const action = this.addAction(arg, completionsPath);
      if (action && command.getCompletion(arg.action)) {
        completions += `
    __${replaceSpecialChars3(this.name)}_complete ${action.arg.name} ${action.arg.action} ${action.cmd}`;
      }
    }
    if (completions) {
      completions = `

  function _commands() {${completions}
  }`;
    }
    return completions;
  }
  generateSubCommandCompletions(command, path3) {
    if (command.hasCommands(false)) {
      const actions = command.getCommands(false).map(
        (command2) => `${command2.getName()}) _${replaceSpecialChars3(path3 + " " + command2.getName())} ;;`
      ).join("\n      ");
      return `

  function _command_args() {
    case "\${words[1]}" in
      ${actions}
    esac
  }`;
    }
    return "";
  }
  generateArgumentCompletions(command, path3) {
    this.actions.clear();
    const options = this.generateOptions(command, path3);
    let argIndex = 0;
    let argsCommand = "\n\n  _arguments -w -s -S -C";
    if (command.hasOptions()) {
      argsCommand += ` \\
    ${options.join(" \\\n    ")}`;
    }
    if (command.hasCommands(false) || command.getArguments().filter((arg) => command.getCompletion(arg.action)).length) {
      argsCommand += ` \\
    '${++argIndex}:command:_commands'`;
    }
    if (command.hasArguments() || command.hasCommands(false)) {
      const args = [];
      for (const arg of command.getArguments().slice(1)) {
        const type4 = command.getType(arg.type);
        if (type4 && type4.handler instanceof FileType) {
          const fileCompletions = this.getFileCompletions(type4);
          if (arg.variadic) {
            argIndex++;
            for (let i6 = 0; i6 < 5; i6++) {
              args.push(
                `${argIndex + i6}${arg.optional ? "::" : ":"}${arg.name}:${fileCompletions}`
              );
            }
          } else {
            args.push(
              `${++argIndex}${arg.optional ? "::" : ":"}${arg.name}:${fileCompletions}`
            );
          }
        } else {
          const completionsPath = path3.split(" ").slice(1).join(" ");
          const action = this.addAction(arg, completionsPath);
          args.push(
            `${++argIndex}${arg.optional ? "::" : ":"}${arg.name}:->${action.name}`
          );
        }
      }
      argsCommand += args.map((arg) => `\\
    '${arg}'`).join("");
      if (command.hasCommands(false)) {
        argsCommand += ` \\
    '*::sub command:->command_args'`;
      }
    }
    return argsCommand;
  }
  generateOptions(command, path3) {
    const options = [];
    const cmdArgs = path3.split(" ");
    const _baseName = cmdArgs.shift();
    const completionsPath = cmdArgs.join(" ");
    const excludedFlags = command.getOptions(false).map((option) => option.standalone ? option.flags : false).flat().filter((flag) => typeof flag === "string");
    for (const option of command.getOptions(false)) {
      options.push(
        this.generateOption(command, option, completionsPath, excludedFlags)
      );
    }
    return options;
  }
  generateOption(command, option, completionsPath, excludedOptions) {
    let args = "";
    for (const arg of option.args) {
      const type4 = command.getType(arg.type);
      const optionalValue = arg.optional ? "::" : ":";
      if (type4 && type4.handler instanceof FileType) {
        const fileCompletions = this.getFileCompletions(type4);
        args += `${optionalValue}${arg.name}:${fileCompletions}`;
      } else {
        const action = this.addAction(arg, completionsPath);
        args += `${optionalValue}${arg.name}:->${action.name}`;
      }
    }
    const description = getDescription(option.description, true).replace(/\[/g, "\\[").replace(/]/g, "\\]").replace(/"/g, '\\"').replace(/'/g, `'"'"'`);
    const collect = option.collect ? "*" : "";
    const equalsSign = option.equalsSign ? "=" : "";
    const flags = option.flags.map((flag) => `${flag}${equalsSign}`);
    let result2 = "";
    if (option.standalone) {
      result2 += "'(- *)'";
    } else {
      const excludedFlags = [...excludedOptions];
      if (option.conflicts?.length) {
        excludedFlags.push(
          ...option.conflicts.map((opt) => "--" + opt.replace(/^--/, ""))
        );
      }
      if (!option.collect) {
        excludedFlags.push(...option.flags);
      }
      if (excludedFlags.length) {
        result2 += `'(${excludedFlags.join(" ")})'`;
      }
    }
    if (collect || flags.length > 1) {
      result2 += `{${collect}${flags.join(",")}}`;
    } else {
      result2 += `${flags.join(",")}`;
    }
    return `${result2}'[${description}]${args}'`;
  }
  getFileCompletions(type4) {
    if (!(type4.handler instanceof FileType)) {
      return "";
    }
    return "_files";
  }
  addAction(arg, cmd) {
    const action = `${arg.name}-${arg.action}`;
    if (!this.actions.has(action)) {
      this.actions.set(action, {
        arg,
        label: `${arg.name}: ${arg.action}`,
        name: action,
        cmd
      });
    }
    return this.actions.get(action);
  }
  generateActions(command) {
    let actions = [];
    if (this.actions.size) {
      actions = Array.from(this.actions).map(
        ([name2, action]) => `${name2}) __${replaceSpecialChars3(this.name)}_complete ${action.arg.name} ${action.arg.action} ${action.cmd} ;;`
      );
    }
    if (command.hasCommands(false)) {
      actions.unshift(`command_args) _command_args ;;`);
    }
    if (actions.length) {
      return `

  case "$state" in
    ${actions.join("\n    ")}
  esac`;
    }
    return "";
  }
};
function replaceSpecialChars3(str3) {
  return str3.replace(/[^a-zA-Z0-9]/g, "_");
}

// https://deno.land/x/cliffy@v1.0.0-rc.3/command/completions/zsh.ts
var ZshCompletionsCommand = class extends Command {
  #cmd;
  constructor(cmd) {
    super();
    this.#cmd = cmd;
    return this.description(() => {
      const baseCmd = this.#cmd || this.getMainCommand();
      return `Generate shell completions for zsh.

To enable zsh completions for this program add following line to your ${dim(italic("~/.zshrc"))}:

    ${dim(italic(`source <(${baseCmd.getPath()} completions zsh)`))}`;
    }).noGlobals().option(
      "-n, --name <command-name>",
      "The name of the main command.",
      { default: () => this.getMainCommand().getName() }
    ).action(({ name: name2 }) => {
      const baseCmd = this.#cmd || this.getMainCommand();
      console.log(ZshCompletionsGenerator.generate(name2, baseCmd));
    });
  }
};

// https://deno.land/x/cliffy@v1.0.0-rc.3/command/completions/complete.ts
var CompleteCommand = class extends Command {
  constructor(cmd) {
    super();
    return this.description(
      "Get completions for given action from given command."
    ).noGlobals().arguments("<action:string> [command...:string]").action(async (_3, action, ...commandNames) => {
      let parent;
      const completeCommand = commandNames?.reduce((cmd2, name2) => {
        parent = cmd2;
        const childCmd = cmd2.getCommand(name2, false);
        if (!childCmd) {
          throw new UnknownCompletionCommandError(name2, cmd2.getCommands());
        }
        return childCmd;
      }, cmd || this.getMainCommand()) ?? (cmd || this.getMainCommand());
      const completion = completeCommand.getCompletion(action);
      const result2 = await completion?.complete(completeCommand, parent) ?? [];
      if (result2?.length) {
        Deno.stdout.writeSync(new TextEncoder().encode(result2.join("\n")));
      }
    }).reset();
  }
};

// https://deno.land/x/cliffy@v1.0.0-rc.3/command/completions/completions_command.ts
var CompletionsCommand = class extends Command {
  #cmd;
  constructor(cmd) {
    super();
    this.#cmd = cmd;
    return this.description(() => {
      const baseCmd = this.#cmd || this.getMainCommand();
      return `Generate shell completions.

To enable shell completions for this program add the following line to your ${dim(italic("~/.bashrc"))} or similar:

    ${dim(italic(`source <(${baseCmd.getPath()} completions [shell])`))}

    For more information run ${dim(italic(`${baseCmd.getPath()} completions [shell] --help`))}
`;
    }).noGlobals().action(() => this.showHelp()).command("bash", new BashCompletionsCommand(this.#cmd)).command("fish", new FishCompletionsCommand(this.#cmd)).command("zsh", new ZshCompletionsCommand(this.#cmd)).command("complete", new CompleteCommand(this.#cmd)).hidden().reset();
  }
};

// command/render/cmd.ts
init_path();
init_fs();
init_log();
init_flags2();

// command/render/render.ts
init_fs();
init_path();
init_deno_dom();
init_config2();
init_resources2();
init_render();
init_path2();
await init_engine();
await init_engine_project_context();

// command/render/pandoc.ts
init_path();
init_log();
init_fs();
init_yaml();
init_copy5();
init_base64();
init_lodash();
init_process();
init_path2();
init_config2();
init_url();
init_types5();
init_format5();
init_metadata();
init_resources2();
init_pandoc_id();
init_yaml();
await init_project_shared();

// project/project-crossrefs.ts
init_fs();
init_path();
init_constants6();
init_path2();
init_uuid();
init_project_scratch();
var kCrossrefIndexFile = "crossref-index-file";
var kCrossrefInputType = "crossref-input-type";
var kCrossrefResolveRefs = "crossref-resolve-refs";
var kCrossrefIndexDir = "xref";
function crossrefIndexForOutputFile(projectDir, input, output) {
  if (isAbsolute4(input)) {
    input = relative4(projectDir, input);
  }
  input = pathWithForwardSlashes(input);
  const crossrefDir = projectScratchPath(projectDir, kCrossrefIndexDir);
  ensureDirSync(crossrefDir);
  const mainIndexFile = join4(crossrefDir, "INDEX");
  const mainIndex = existsSync2(mainIndexFile) ? JSON.parse(Deno.readTextFileSync(mainIndexFile)) : {};
  const outputBaseFile = basename4(output);
  if (mainIndex[input]?.[outputBaseFile] === void 0) {
    if (mainIndex[input] === void 0) {
      mainIndex[input] = {};
    }
    mainIndex[input][outputBaseFile] = shortUuid();
    Deno.writeTextFileSync(
      mainIndexFile,
      JSON.stringify(mainIndex, void 0, 2)
    );
  }
  return join4(crossrefDir, mainIndex[input]?.[outputBaseFile]);
}
function deleteCrossrefMetadata(metadata) {
  const crossref = metadata[kCrossref];
  if (crossref) {
    delete crossref[kCrossrefChaptersAppendix];
    delete crossref[kCrossrefChaptersAlpha];
    delete crossref[kCrossrefChapterId];
    if (Object.keys(crossref).length === 0) {
      delete metadata[kCrossref];
    }
  }
}

// command/render/pandoc.ts
init_project_scratch();
init_flags2();

// command/render/defaults.ts
init_path();
init_yaml();
init_format5();
init_constants6();
init_template();

// command/render/filters.ts
init_fs();
init_constants6();
init_types5();
init_types4();
init_pdf();
init_resources2();

// command/render/crossref.ts
init_constants6();
init_render_paths();
init_book_shared();
await init_project_shared();
function crossrefFilterActive(options) {
  return options.format.metadata.crossref !== false;
}
function crossrefFilterParams(options, defaults) {
  const flags = options.flags;
  const metadata = options.format.metadata;
  const kCrossrefFilterParams = [kListings, kNumberSections, kNumberOffset];
  const params = {};
  kCrossrefFilterParams.forEach((option) => {
    let value = crossrefOption(option, flags, defaults);
    if (value) {
      if (option === kNumberOffset) {
        if (typeof value === "number") {
          value = [value];
        }
        if (!Array.isArray(value) || value.some((num) => !Number.isInteger(num))) {
          throw new Error(
            "Invalid value for number-offset (should be an array of numbers)"
          );
        }
        if (defaults?.[kNumberSections] === void 0) {
          params[kNumberSections] = true;
        }
      }
      params[option] = value;
    }
  });
  params[kNumberDepth] = metadata?.[kNumberDepth];
  if (!options.project?.isSingleFile) {
    if (!projectIsBook(options.project) || isMultiFileBookFormat(options.format)) {
      params[kCrossrefIndexFile] = pandocMetadataPath(
        crossrefIndexForOutputFile(
          options.project.dir,
          options.source,
          options.output
        )
      );
    }
  } else {
    const crossrefIndex = Deno.env.get("QUARTO_CROSSREF_INDEX_PATH");
    if (crossrefIndex) {
      params[kCrossrefIndexFile] = pandocMetadataPath(crossrefIndex);
    }
  }
  const crossrefInputType = Deno.env.get("QUARTO_CROSSREF_INPUT_TYPE");
  if (crossrefInputType) {
    params[kCrossrefInputType] = crossrefInputType;
  }
  return params;
}
function crossrefOption(name2, flags, defaults) {
  if (flags && Object.keys(flags).includes(name2)) {
    return flags[name2];
  } else if (Object.keys(defaults || {}).includes(name2)) {
    return defaults[name2];
  } else {
    return void 0;
  }
}

// command/render/layout.ts
init_constants6();

// quarto-core/text-highlighting.ts
init_path();

// command/render/constants.ts
var kMarkdownBlockSeparator = "\n\n<!-- -->\n\n";
var kDefaultHighlightStyle = "arrow";
var kHtmlEmptyPostProcessResult = {
  resources: [],
  supporting: []
};
var kQuartoRenderCommand = "90B3C9E8-0DBC-4BC0-B164-AA2D5C031B28";

// quarto-core/text-highlighting.ts
init_constants6();
init_fs();
init_resources2();
init_path2();
init_log2();
var kDarkSuffix2 = "dark";
var kLightSuffix2 = "light";
function getHighlightTheme(pandoc2) {
  return pandoc2[kSyntaxHighlighting] || pandoc2[kHighlightStyle] || kDefaultHighlightStyle;
}
function textHighlightThemePath2(inputDir, theme, style) {
  let resolvedTheme;
  if (typeof theme === "object") {
    if (style && theme[style]) {
      resolvedTheme = theme[style];
    } else {
      resolvedTheme = theme[Object.keys(theme)[0]];
    }
  } else {
    resolvedTheme = theme;
  }
  const names = [
    `${resolvedTheme}-${style === "dark" ? kDarkSuffix2 : kLightSuffix2}`,
    resolvedTheme
  ];
  const themePath = names.map((name2) => {
    return resourcePath(join4("pandoc", "highlight-styles", `${name2}.theme`));
  }).find((path3) => existsSync2(path3));
  if (themePath) {
    return themePath;
  } else {
    const userThemePath = join4(inputDir, resolvedTheme);
    if (existsSync2(userThemePath)) {
      return normalizePath(userThemePath);
    }
  }
  return void 0;
}
function readHighlightingTheme(inputDir, pandoc2, style) {
  const theme = getHighlightTheme(pandoc2);
  const themeRaw = readTheme(inputDir, theme, style);
  if (themeRaw) {
    return {
      json: JSON.parse(themeRaw),
      isAdaptive: isAdaptiveTheme(theme)
    };
  }
  return void 0;
}
function hasAdaptiveTheme(pandoc2) {
  return isAdaptiveTheme(getHighlightTheme(pandoc2));
}
function hasTextHighlighting(pandoc2) {
  return getHighlightTheme(pandoc2) !== "none";
}
function isAdaptiveTheme(theme) {
  if (typeof theme === "string") {
    return [
      "a11y",
      "arrow",
      "atom-one",
      "ayu",
      "breeze",
      "github",
      "gruvbox",
      "monochrome"
    ].includes(
      theme
    );
  } else {
    const keys = Object.keys(theme);
    return keys.includes("dark") && keys.includes("light");
  }
}
function readTheme(inputDir, theme, style) {
  const themeFile = textHighlightThemePath2(
    inputDir,
    theme,
    style === "default" ? void 0 : style
  );
  if (!themeFile) {
    return void 0;
  }
  if (!existsSync2(themeFile)) {
    warnOnce(`The text highlighting theme ${themeFile} does not exist.`);
    return void 0;
  }
  if (Deno.statSync(themeFile).isDirectory) {
    throw new Error(
      `The text highlighting theme ${themeFile} is a directory. Please provide a valid theme name or path to a .theme file.`
    );
  }
  return Deno.readTextFileSync(themeFile);
}
var kAbbrevs = {
  "Keyword": "kw",
  "DataType": "dt",
  "DecVal": "dv",
  "BaseN": "bn",
  "Float": "fl",
  "Char": "ch",
  "String": "st",
  "Comment": "co",
  "Other": "ot",
  "Alert": "al",
  "Function": "fu",
  "RegionMarker": "re",
  "Error": "er",
  "Constant": "cn",
  "SpecialChar": "sc",
  "VerbatimString": "vs",
  "SpecialString": "ss",
  "Import": "im",
  "Documentation": "do",
  "Annotation": "an",
  "CommentVar": "cv",
  "Variable": "va",
  "ControlFlow": "cf",
  "Operator": "op",
  "BuiltIn": "bu",
  "Extension": "ex",
  "Preprocessor": "pp",
  "Attribute": "at",
  "Information": "in",
  "Warning": "wa",
  "Normal": ""
};

// command/render/layout.ts
var kAdaptiveTextHighlighting = "adaptive-text-highlighting";
var kTextHighlighting = "text-highlighting";
function layoutFilterParams(format14, defaults) {
  const params = {};
  const pageWidth = format14.render[kPageWidth];
  if (pageWidth) {
    params[kPageWidth] = pageWidth;
  }
  if (defaults) {
    if (hasAdaptiveTheme(defaults)) {
      params[kAdaptiveTextHighlighting] = true;
    }
    if (hasTextHighlighting(defaults)) {
      params[kTextHighlighting] = true;
    }
  }
  return params;
}
function overflowXPostprocessor(doc) {
  const outputs = doc.querySelectorAll(".cell-output-display");
  for (let i6 = 0; i6 < outputs.length; i6++) {
    const output = outputs[i6];
    const noOverflowX = (
      // select inputs end up having their drop down truncated
      !!output.querySelector("select") || // shiny can inject select boxes (for example) which will be truncated
      // see https://github.com/quarto-dev/quarto-cli/issues/8091
      !!output.querySelector(".shiny-html-output") || // the rgl htmlwidget barely overflows the container and gets scrollbars
      // see https://github.com/quarto-dev/quarto-cli/issues/1800
      !!output.querySelector(".rglWebGL")
    );
    if (noOverflowX) {
      output.classList.add("no-overflow-x");
    }
  }
  return Promise.resolve(kHtmlEmptyPostProcessResult);
}

// command/render/filters.ts
init_render_paths();
init_flags2();
init_config2();
init_project_types();
init_windows();
init_format_html_info();
init_profile();
await init_extension();
init_quarto();

// command/render/normalize.ts
init_resources2();
var kMetaNormalizationActive = "metadata-normalization";
function metadataNormalizationFilterActive(options) {
  return options.format.metadata[kMetaNormalizationActive] !== false;
}

// command/render/filters.ts
init_format_html_shared();
await init_project_shared();
init_path();

// project/project-cites.ts
init_fs();
init_path();
await init_project_shared();
init_project_scratch();
var kCitesIndexFile = "cites-index-file";
var kCiteIndexDir = "cites";
function citeIndexFilterParams(options, _defaults) {
  if (options.project && projectIsBook(options.project)) {
    return {
      [kCitesIndexFile]: citeIndexFile(options.project.dir)
    };
  } else {
    return {};
  }
}
function citeIndex(projectDir) {
  const mainIndexFile = citeIndexFile(projectDir);
  const mainIndex = existsSync2(mainIndexFile) ? JSON.parse(Deno.readTextFileSync(mainIndexFile)) : {};
  return mainIndex;
}
function citeIndexFile(projectDir) {
  const citesDir = projectScratchPath(projectDir, kCiteIndexDir);
  ensureDirSync(citesDir);
  return join4(citesDir, "index.json");
}

// command/render/filters.ts
init_log();
init_format_jats_types();
init_uuid();
init_render();
init_exec();
init_constants6();
init_platform();

// tools/impl/tinytex-info.ts
init_path2();
init_path();
init_env();
init_platform();
function hasTinyTex() {
  const binDir3 = tinyTexBinDir();
  if (!binDir3) {
    return false;
  }
  const tlmgrBinary = os === "windows" ? "tlmgr.bat" : "tlmgr";
  const tlmgrPath = join4(binDir3, tlmgrBinary);
  return safeExistsSync(tlmgrPath);
}
function tinyTexInstallDir() {
  switch (os) {
    case "windows": {
      let appDir = getenv("APPDATA", void 0);
      if (!appDir || !appDir.match(/^[!-~]+$/)) {
        appDir = getenv("ProgramData", void 0);
      }
      return expandPath(join4(appDir, "TinyTeX"));
    }
    case "linux":
      return expandPath("~/.TinyTeX");
    case "darwin":
      return expandPath("~/Library/TinyTeX");
    default:
      return void 0;
  }
}
function tinyTexBinDir() {
  const basePath = tinyTexInstallDir();
  if (basePath) {
    switch (os) {
      case "windows": {
        const winPath = join4(basePath, "bin\\win32\\");
        if (safeExistsSync(winPath)) return winPath;
        return join4(basePath, "bin\\windows\\");
      }
      case "linux": {
        const linuxPath = join4(basePath, `bin/${Deno.build.arch}-linux`);
        if (safeExistsSync(linuxPath)) return linuxPath;
        return void 0;
      }
      case "darwin": {
        const darwinPath = join4(basePath, "bin/universal-darwin");
        if (safeExistsSync(darwinPath)) return darwinPath;
        return void 0;
      }
      default:
        return void 0;
    }
  } else {
    return void 0;
  }
}

// core/typst.ts
init_log();
init_path();
init_fs();
init_colors2();
init_mod6();
init_process();
init_resources2();
init_resources2();
function typstBinaryPath() {
  return Deno.env.get("QUARTO_TYPST") || architectureToolsPath("typst");
}
function fontPathsArgs(fontPaths) {
  const fontPathsQuarto = ["--font-path", resourcePath("formats/typst/fonts")];
  const fontPathsEnv = Deno.env.get("TYPST_FONT_PATHS");
  let fontExtrasArgs = [];
  if (fontPaths && fontPaths.length > 0) {
    fontExtrasArgs = fontPaths.map((p5) => ["--font-path", p5]).flat();
  } else if (fontPathsEnv) {
    return fontExtrasArgs = ["--font-path", fontPathsEnv];
  }
  return fontPathsQuarto.concat(fontExtrasArgs);
}
async function typstCompile(input, output, options = {}) {
  const quiet = options.quiet ?? false;
  const fontPaths = options.fontPaths;
  if (!quiet) {
    typstProgress(input, output);
  }
  const cmd = [
    typstBinaryPath(),
    "compile"
  ];
  if (options.rootDir) {
    cmd.push("--root", options.rootDir);
  }
  if (options.packagePath) {
    const localDir = join4(options.packagePath, "local");
    if (existsSync2(localDir)) {
      cmd.push("--package-path", options.packagePath);
    }
    const previewDir = join4(options.packagePath, "preview");
    if (existsSync2(previewDir)) {
      cmd.push("--package-cache-path", options.packagePath);
    }
  }
  if (options.pdfStandard && options.pdfStandard.length > 0) {
    cmd.push("--pdf-standard", options.pdfStandard.join(","));
  }
  cmd.push(
    input,
    ...fontPathsArgs(fontPaths),
    output
  );
  const result2 = await execProcess({ cmd: cmd[0], args: cmd.slice(1) });
  if (!quiet && result2.success) {
    typstProgressDone();
  }
  return result2;
}
async function typstVersion() {
  const cmd = [typstBinaryPath(), "--version"];
  try {
    const result2 = await execProcess({
      cmd: cmd[0],
      args: cmd.slice(1),
      stdout: "piped",
      stderr: "piped"
    });
    if (result2.success && result2.stdout) {
      const match = result2.stdout.trim().match(/^typst (\d+\.\d+\.\d+)/);
      if (match) {
        return match[1];
      } else {
        return void 0;
      }
    } else {
      return void 0;
    }
  } catch {
    return void 0;
  }
}
async function validateRequiredTypstVersion() {
  if (Deno.env.get("QUARTO_TYPST")) {
    const version4 = await typstVersion();
    if (version4) {
      const required = ">=0.8";
      if (!satisfies(version4, required)) {
        error(
          "An updated version of the Typst CLI is required for rendering typst documents.\n"
        );
        info(blue3(
          `You are running version ${version4} and version ${required} is required.
`
        ));
        info(blue3(
          `Updating Typst: ${underline2("https://github.com/typst/typst#installation")}
`
        ));
        throw new Error();
      }
    } else {
      error(
        "You need to install the Typst CLI in order to render typst documents.\n"
      );
      info(blue3(
        `Installing Typst: ${underline2("https://github.com/typst/typst#installation")}
`
      ));
      throw new Error();
    }
  }
}
function typstProgress(input, output) {
  info(
    `[typst]: Compiling ${basename4(input)} to ${basename4(output)}...`,
    { newline: false }
  );
}
function typstProgressDone() {
  info("DONE\n");
}

// command/render/filters.ts
var kQuartoParams = "quarto-params";
var kProjectOffset = "project-offset";
var kFilterProjectOutputDir = "project-output-dir";
var kMediabagDir = "mediabag-dir";
var kResultsFile = "results-file";
var kHasBootstrap = "has-bootstrap";
var kActiveFilters = "active-filters";
var kQuartoVersion2 = "quarto-version";
var kQuartoCliPath = "quarto-cli-path";
var kQuartoSource = "quarto-source";
var kHasResourcePath = "has-resource-path";
var kQuartoCustomFormat = "quarto-custom-format";
var kIsShinyPython = "is-shiny-python";
var kShinyPythonExec = "shiny-python-exec";
var kExecutionEngine = "execution-engine";
async function filterParamsJson(args, options, defaults, filterParams, resultsFile, dependenciesFile) {
  const includes = options.format.render[kMergeIncludes] !== false ? extractIncludeParams(
    args,
    options.format.metadata,
    defaults || {}
  ) : {};
  const filterSpec = extractFilterSpecParams(
    options.format.metadata
  );
  const quartoColumnParams = extractColumnParams(
    args,
    options.format.metadata,
    defaults
  );
  const customFormatParams = extractCustomFormatParams(
    options.format.metadata
  );
  const isShinyPython = isServerShinyPython(
    options.format,
    options.executionEngine
  );
  const typstFilterParams = extractTypstFilterParams(
    options.format
  );
  const params = {
    ...includes,
    ...initFilterParams(dependenciesFile),
    ...ipynbFilterParams(options),
    ...await projectFilterParams(options),
    ...quartoColumnParams,
    ...await quartoFilterParams(options, defaults),
    ...crossrefFilterParams(options, defaults),
    ...citeIndexFilterParams(options, defaults),
    ...layoutFilterParams(options.format, defaults),
    ...languageFilterParams(options.format),
    ...jatsFilterParams(options),
    ...notebookContextFilterParams(options),
    ...filterParams,
    ...customFormatParams,
    ...typstFilterParams,
    [kResultsFile]: pandocMetadataPath(resultsFile),
    [kQuartoFilters]: filterSpec,
    [kActiveFilters]: {
      normalization: metadataNormalizationFilterActive(options),
      crossref: crossrefFilterActive(options),
      jats_subarticle: options.format.metadata[kJatsSubarticle]
    },
    [kFormatIdentifier]: options.format.identifier,
    [kIsShinyPython]: isShinyPython,
    [kShinyPythonExec]: isShinyPython ? await pythonExec() : void 0,
    [kExecutionEngine]: options.executionEngine,
    [kBrand]: options.format.render[kBrand],
    "quarto-environment": await quartoEnvironmentParams(options)
  };
  return params;
}
async function quartoEnvironmentParams(_options) {
  return {
    "paths": {
      "Rscript": await rBinaryPath("Rscript"),
      "TinyTexBinDir": tinyTexBinDir(),
      // will be undefined if no tinytex found and quarto will look in PATH
      "Typst": typstBinaryPath()
    }
  };
}
function removeFilterParams(metadata) {
  delete metadata[kQuartoParams];
}
function quartoMainFilter() {
  return resourcePath("filters/main.lua");
}
function extractCustomFormatParams(metadata) {
  const customFormatParams = metadata[kQuartoCustomFormat];
  if (customFormatParams) {
    delete metadata[kQuartoCustomFormat];
    return {
      [kQuartoCustomFormat]: customFormatParams
    };
  } else {
    return {};
  }
}
function extractFilterSpecParams(metadata) {
  const filterSpec = metadata[kQuartoFilters];
  delete metadata[kQuartoFilters];
  return filterSpec;
}
function extractIncludeParams(args, metadata, defaults) {
  const includes = mergeConfigs(
    extractSmartIncludeText(metadata),
    extractSmartIncludeText(defaults || {}),
    extractSmartIncludeText(defaults.variables || {}),
    extractIncludeVariables(metadata),
    extractIncludeVariables(defaults.variables || {})
  );
  if (defaults.variables && Object.keys(defaults.variables).length === 0) {
    delete defaults.variables;
  }
  const inHeaderFiles = [];
  const beforeBodyFiles = [];
  const afterBodyFiles = [];
  const smartMetadataFiles = extractSmartIncludeFile(metadata);
  const smartDefaultsFiles = extractSmartIncludeFile(
    defaults || {}
  );
  const smartDefaultsVariablesFiles = extractSmartIncludeFile(
    defaults.variables || {}
  );
  inHeaderFiles.push(...defaults[kIncludeInHeader] || []);
  beforeBodyFiles.push(...defaults[kIncludeBeforeBody] || []);
  afterBodyFiles.push(...defaults[kIncludeAfterBody] || []);
  inHeaderFiles.push(...smartMetadataFiles[kIncludeInHeader]);
  beforeBodyFiles.push(...smartMetadataFiles[kIncludeBeforeBody]);
  afterBodyFiles.push(...smartMetadataFiles[kIncludeAfterBody]);
  inHeaderFiles.push(...smartDefaultsFiles[kIncludeInHeader]);
  beforeBodyFiles.push(...smartDefaultsFiles[kIncludeBeforeBody]);
  afterBodyFiles.push(...smartDefaultsFiles[kIncludeAfterBody]);
  inHeaderFiles.push(...smartDefaultsVariablesFiles[kIncludeInHeader]);
  beforeBodyFiles.push(...smartDefaultsVariablesFiles[kIncludeBeforeBody]);
  afterBodyFiles.push(...smartDefaultsVariablesFiles[kIncludeAfterBody]);
  delete defaults[kIncludeInHeader];
  delete defaults[kIncludeAfterBody];
  delete defaults[kIncludeBeforeBody];
  for (const arg in args) {
    switch (arg) {
      case kIncludeInHeader:
        inHeaderFiles.push(arg);
        break;
      case kIncludeBeforeBody:
        beforeBodyFiles.push(arg);
        break;
      case kIncludeAfterBody:
        afterBodyFiles.push(arg);
        break;
    }
  }
  const removeArgs = /* @__PURE__ */ new Map();
  removeArgs.set(kIncludeInHeader, true);
  removeArgs.set(kIncludeBeforeBody, true);
  removeArgs.set(kIncludeAfterBody, true);
  removePandocArgsInPlace(args, removeArgs);
  const result2 = {
    ...includes,
    [kIncludeInHeader]: inHeaderFiles.map(pandocMetadataPath),
    [kIncludeBeforeBody]: beforeBodyFiles.map(pandocMetadataPath),
    [kIncludeAfterBody]: afterBodyFiles.map(pandocMetadataPath)
  };
  return result2;
}
function extractSmartIncludeText(obj) {
  return extractSmartIncludeInternal(obj, "text");
}
function extractSmartIncludeFile(obj) {
  const inner = extractSmartIncludeInternal(obj, "file");
  return {
    [kIncludeInHeader]: inner[kHeaderIncludes],
    [kIncludeBeforeBody]: inner[kIncludeBefore],
    [kIncludeAfterBody]: inner[kIncludeAfter]
  };
}
function extractSmartIncludeInternal(obj, key) {
  const isContent = (v4) => {
    if (typeof v4 !== "object") {
      return false;
    }
    return typeof v4[key] === "string";
  };
  const extractVariable = (name2) => {
    const value = obj[name2];
    if (value === void 0) {
      return [];
    }
    if (Array.isArray(value)) {
      const contents = value.filter(isContent);
      const nonContents = value.filter((v4) => !isContent(v4));
      obj[name2] = nonContents;
      return contents.map((v4) => v4[key]);
    } else if (isContent(value)) {
      delete obj[name2];
      return [value[key]];
    } else {
      return [];
    }
  };
  return {
    [kHeaderIncludes]: extractVariable(kIncludeInHeader),
    [kIncludeBefore]: extractVariable(kIncludeBeforeBody),
    [kIncludeAfter]: extractVariable(kIncludeAfterBody)
  };
}
function extractIncludeVariables(obj) {
  const extractVariable = (name2) => {
    const value = obj[name2];
    delete obj[name2];
    if (!value) {
      return [];
    } else if (Array.isArray(value)) {
      return value;
    } else {
      return [value];
    }
  };
  return {
    [kHeaderIncludes]: extractVariable(kHeaderIncludes),
    [kIncludeBefore]: extractVariable(kIncludeBefore),
    [kIncludeAfter]: extractVariable(kIncludeAfter)
  };
}
function extractColumnParams(args, metadata, defaults) {
  const quartoColumnParams = {};
  if (defaults?.[kReferenceLocation] === "margin" || referenceLocationArg(args) === "margin") {
    quartoColumnParams[kReferenceLocation] = "margin";
    const removeArgs = /* @__PURE__ */ new Map();
    removeArgs.set(`--${kReferenceLocation}`, true);
    removePandocArgsInPlace(args, removeArgs);
    if (defaults) {
      delete defaults[kReferenceLocation];
    }
  }
  if (metadata[kCitationLocation]) {
    quartoColumnParams[kCitationLocation] = metadata[kCitationLocation];
  }
  return quartoColumnParams;
}
function removePandocArgsInPlace(args, removeArgs) {
  const cleanedArgs = removePandocArgs(args, removeArgs);
  if (cleanedArgs.length !== args.length) {
    args.splice(0, args.length);
    args.push(...cleanedArgs);
  }
}
function referenceLocationArg(args) {
  const argIndex = args.findIndex((arg) => {
    return arg === `--${kReferenceLocation}`;
  });
  if (argIndex > -1 && args.length > argIndex + 1) {
    const referenceLocation = args[argIndex + 1];
    return referenceLocation;
  } else {
    return void 0;
  }
}
function languageFilterParams(format14) {
  const language = format14.language;
  const params = {
    [kCodeSummary]: format14.metadata[kCodeSummary] || language[kCodeSummary],
    [kTocTitleDocument]: language[kTocTitleDocument]
  };
  [
    "fig",
    "tbl",
    "lst",
    "thm",
    "lem",
    "cor",
    "prp",
    "cnj",
    "def",
    "exm",
    "exr"
  ].forEach((type4) => {
    params[`crossref-${type4}-prefix`] = language[`crossref-${type4}-title`];
  });
  Object.keys(language).forEach((key) => {
    if (key.startsWith("callout-") || key.startsWith("crossref-") || key.startsWith("environment-")) {
      params[key] = language[key];
    }
  });
  return params;
}
async function projectFilterParams(options) {
  const projType = projectType(
    options.project?.config?.project?.[kProjectType]
  );
  const params = (projType.filterParams ? await projType.filterParams(options) : void 0) || {};
  const additionalParams = {};
  if (options.project) {
    const absProjectOutputDir = projectOutputDir(options.project);
    const outputDir = relative4(options.project.dir, absProjectOutputDir);
    if (outputDir) {
      additionalParams[kFilterProjectOutputDir] = outputDir;
    }
  }
  if (options.offset) {
    additionalParams[kProjectOffset] = options.offset;
  }
  return {
    ...additionalParams,
    ...params
  };
}
function ipynbFilterParams(options) {
  const params = {
    [kIPynbTitleBlockTemplate]: options.format.metadata[kIPynbTitleBlockTemplate]
  };
  if (options.format.render[kIpynbProduceSourceNotebook]) {
    params[kEnableCrossRef] = false;
    params[kIpynbProduceSourceNotebook] = true;
  }
  return params;
}
function jatsFilterParams(options) {
  if (options.format.metadata[kJatsSubarticle]) {
    return {
      [kJatsSubarticleId]: options.format.metadata[kJatsSubarticleId] || shortUuid()
    };
  } else {
    return {};
  }
}
function notebookContextFilterParams(options) {
  const nbContext = options.services.notebook;
  const notebooks = nbContext.all(options.project);
  if (notebooks.length > 0) {
    return {
      "notebook-context": notebooks
    };
  }
}
async function quartoFilterParams(options, defaults) {
  const format14 = options.format;
  const params = {
    [kOutputDivs]: format14.render[kOutputDivs]
  };
  params[kMediabagDir] = options.mediabagDir;
  const figAlign = format14.render[kFigAlign];
  if (figAlign) {
    params[kFigAlign] = figAlign;
  }
  const figPos = format14.render[kFigPos];
  if (figPos) {
    params[kFigPos] = figPos;
  }
  const figEnv = format14.render[kFigEnv];
  if (figEnv) {
    params[kFigEnv] = figEnv;
  }
  const foldCode = format14.render[kCodeFold];
  if (foldCode) {
    params[kCodeFold] = foldCode;
  }
  const htmlTableProcessing = format14.render[kHtmlTableProcessing];
  if (htmlTableProcessing) {
    params[kHtmlTableProcessing] = htmlTableProcessing;
  }
  const useRsvgConvert = format14.render[kUseRsvgConvert];
  if (useRsvgConvert !== void 0) {
    params[kUseRsvgConvert] = useRsvgConvert;
  }
  const tblColwidths = format14.render[kTblColwidths];
  if (tblColwidths !== void 0) {
    params[kTblColwidths] = tblColwidths;
  }
  const shortcodes = format14.render[kShortcodes];
  if (shortcodes !== void 0) {
    params[kShortcodes] = shortcodes;
  }
  const extShortcodes = await extensionShortcodes(options);
  if (extShortcodes) {
    params[kShortcodes] = params[kShortcodes] || [];
    params[kShortcodes].push(...extShortcodes);
  }
  params[kHtmlMathMethod] = defaults?.[kHtmlMathMethod];
  const figResponsive = format14.metadata[kFigResponsive] === true;
  if (figResponsive) {
    params[kFigResponsive] = figResponsive;
  }
  const outputLocation = format14.metadata[kOutputLocation];
  if (outputLocation) {
    params[kOutputLocation] = outputLocation;
  }
  const lineNumbers = format14.render[kCodeLineNumbers];
  if (lineNumbers) {
    params[kCodeLineNumbers] = lineNumbers;
  }
  const keepHidden = format14.render[kKeepHidden];
  if (keepHidden) {
    params[kKeepHidden] = kKeepHidden;
  }
  const removeHidden = format14.metadata[kRemoveHidden];
  if (removeHidden) {
    params[kRemoveHidden] = removeHidden;
  }
  const clearHiddenClasses = format14.metadata[kClearHiddenClasses];
  if (clearHiddenClasses) {
    params[kClearHiddenClasses] = clearHiddenClasses;
  }
  const unrollMarkdownCells = format14.metadata[kUnrollMarkdownCells];
  if (unrollMarkdownCells) {
    params[kUnrollMarkdownCells] = unrollMarkdownCells;
  }
  const clearCellOptions = format14.render[kClearCellOptions];
  if (clearCellOptions) {
    params[kClearCellOptions] = clearCellOptions;
  }
  params[kCiteMethod] = citeMethod(options);
  params[kPdfEngine] = pdfEngine2(options);
  params[kHasBootstrap] = formatHasBootstrap(options.format);
  const hasResourcePath = options.format.pandoc[kResourcePath] !== void 0 || options.args.includes("--resource-path");
  params[kHasResourcePath] = hasResourcePath;
  if (options.project.isSingleFile) {
    params[kQuartoSource] = basename4(options.source);
  } else {
    params[kQuartoSource] = options.source;
  }
  params[kQuartoProfile.toLowerCase()] = activeProfiles();
  params[kQuartoVersion2] = quartoConfig.version();
  params[kQuartoCliPath] = quartoConfig.cliPath();
  params[kCodeAnnotations] = format14.metadata[kCodeAnnotations];
  return params;
}
async function extensionShortcodes(options) {
  const extensionShortcodes2 = [];
  if (options.services.extension) {
    const allExtensions = await options.services.extension?.extensions(
      options.source,
      options.project?.config,
      options.project?.dir
    );
    const shortCodeExtensions = filterBuiltInExtensions(
      allExtensions.filter((ext) => {
        return !!ext.contributes.shortcodes;
      })
    );
    shortCodeExtensions.forEach((extension) => {
      const shortcodes = extension.contributes.shortcodes || [];
      extensionShortcodes2.push(...shortcodes);
    });
  }
  return extensionShortcodes2;
}
function initFilterParams(dependenciesFile) {
  const params = {};
  if (isWindows4) {
    const value = readCodePage();
    if (value) {
      debug("Windows: Using code page " + value);
      Deno.env.set("QUARTO_WIN_CODEPAGE", value);
    }
  }
  Deno.env.set("QUARTO_FILTER_DEPENDENCY_FILE", dependenciesFile);
  return params;
}
var kQuartoFilterMarker = "quarto";
var kQuartoCiteProcMarker = "citeproc";
async function resolveFilters(filters, options, pandoc2) {
  const quartoFilters = [];
  quartoFilters.push(quartoMainFilter());
  filters = await resolveFilterExtension(options, filters);
  let quartoLoc = filters.findIndex((filter3) => filter3 === kQuartoFilterMarker);
  if (quartoLoc === -1) {
    quartoLoc = Infinity;
  }
  const entryPoints = filters.filter((f5) => f5 !== "quarto").map((filter3, i6) => {
    if (isFilterEntryPoint(filter3)) {
      return filter3;
    }
    const at3 = quartoLoc > i6 ? kQuartoPre : kQuartoPost;
    const result2 = typeof filter3 === "string" ? {
      "at": at3,
      "type": filter3.endsWith(".lua") ? "lua" : "json",
      "path": filter3
    } : {
      "at": at3,
      ...filter3
    };
    return result2;
  });
  filters = filters.filter((filter3) => filter3 !== kQuartoCiteProcMarker);
  const citeproc = citeMethod(options) === kQuartoCiteProcMarker;
  if (citeproc) {
    if (pandoc2.citeproc === true) {
      delete pandoc2.citeproc;
    }
    quartoFilters.push(kQuartoCiteProcMarker);
  }
  if ([
    quartoFilters
  ].some((x3) => x3.length)) {
    return {
      quartoFilters,
      beforeQuartoFilters: [],
      afterQuartoFilters: [],
      entryPoints
    };
  } else {
    return void 0;
  }
}
function citeMethod(options) {
  const pandoc2 = options.format.pandoc;
  const metadata = options.format.metadata;
  const engine = bibEngine(options.format.pandoc, options.flags);
  if (pandoc2.citeproc) {
    if (engine) {
      throw new Error(
        `The bibliography engine '${engine}' was set when 'citeproc' was also explicitly requested.`
      );
    }
    return "citeproc";
  }
  if (!metadata[kBibliography] && !metadata[kReferences]) {
    return null;
  }
  if (engine) {
    return engine;
  }
  if (pandoc2.citeproc !== false) {
    return "citeproc";
  } else {
    return null;
  }
}
function pdfEngine2(options) {
  const pdfEngine3 = options.flags?.pdfEngine || options.format.pandoc?.[kPdfEngine] || "pdflatex";
  return pdfEngine3;
}
async function resolveFilterExtension(options, filters) {
  const results = [];
  const getFilter = async (filter3) => {
    if (filter3 === kQuartoFilterMarker || filter3 === kQuartoCiteProcMarker) {
      return filter3;
    }
    let pathToResolve = null;
    if (typeof filter3 === "string") {
      pathToResolve = filter3;
    } else if (typeof filter3 === "object" && filter3.path) {
      pathToResolve = filter3.path;
    }
    if (pathToResolve) {
      if (existsSync2(pathToResolve) && !Deno.statSync(pathToResolve).isDirectory) {
        return filter3;
      }
      const extensions2 = await options.services.extension?.find(
        pathToResolve,
        options.source,
        "filters",
        options.project?.config,
        options.project?.dir
      ) || [];
      const filteredExtensions = filterExtensions(
        extensions2 || [],
        pathToResolve,
        "filter"
      );
      if (filteredExtensions.length > 0) {
        const extensionFilters = extensions2[0].contributes.filters;
        if (extensionFilters) {
          if (typeof filter3 === "string") {
            return extensionFilters;
          } else if (isFilterEntryPoint(filter3)) {
            return extensionFilters.map((extFilter) => {
              if (typeof extFilter === "string") {
                return {
                  type: extFilter.endsWith(".lua") ? "lua" : "json",
                  path: extFilter,
                  at: filter3.at
                };
              } else {
                return {
                  ...extFilter,
                  at: filter3.at
                };
              }
            });
          } else {
            return extensionFilters;
          }
        } else {
          return filter3;
        }
      } else if (extensions2.length > 0) {
        return [];
      } else {
        return filter3;
      }
    } else {
      return filter3;
    }
  };
  for (const filter3 of filters) {
    const r5 = await getFilter(filter3);
    results.push(r5);
  }
  return results.flat();
}
var extractTypstFilterParams = (format14) => {
  return {
    [kTocIndent]: format14.metadata[kTocIndent],
    [kLogo]: format14.metadata[kLogo],
    [kCssPropertyProcessing]: format14.metadata[kCssPropertyProcessing],
    [kBrandMode]: format14.metadata[kBrandMode],
    [kHtmlPreTagProcessing]: format14.metadata[kHtmlPreTagProcessing]
  };
};

// command/render/defaults.ts
async function generateDefaults(options) {
  let allDefaults;
  if (options.format.pandoc) {
    allDefaults = {
      ...options.format.pandoc || {},
      variables: {
        ...options.format.pandoc?.variables || {}
      }
    };
    const resolvedFilters = await resolveFilters(
      [
        ...allDefaults[kFilters] || []
      ],
      options,
      allDefaults
    );
    if (resolvedFilters) {
      allDefaults[kFilters] = resolvedFilters.quartoFilters;
      options.format.metadata[kQuartoFilters] = resolvedFilters;
    }
    if (isLatexOutput(options.format.pandoc)) {
      if (options.format.metadata[kNumberDepth] !== void 0) {
        allDefaults.variables = allDefaults.variables || {};
        allDefaults.variables["secnumdepth"] = options.format.metadata[kNumberDepth];
      }
    }
    return allDefaults;
  } else {
    return void 0;
  }
}
async function writeDefaultsFile(defaults, temp) {
  const defaultsStr = "---\n" + stringify(defaults, {
    indent: 2,
    lineWidth: -1,
    sortKeys: false,
    skipInvalid: true
  });
  const defaultsFile = temp.createFile(
    { prefix: "quarto-defaults", suffix: ".yml" }
  );
  await Deno.writeTextFile(defaultsFile, defaultsStr);
  return defaultsFile;
}
function pandocDefaultsMessage(pandoc2, sysFilters, debug4) {
  const kDebugOnly = [
    kIncludeInHeader,
    kIncludeBeforeBody,
    kIncludeAfterBody
  ];
  const kOrder2 = [
    kTo,
    kFrom,
    kOutputFile,
    kTemplate,
    kStandalone,
    kEmbedResources,
    kSelfContained
  ];
  const defaults = {};
  kOrder2.forEach((key) => {
    if (Object.keys(pandoc2).includes(key)) {
      defaults[key] = pandoc2[key];
    }
  });
  Object.keys(pandoc2).forEach((key) => {
    if (!kOrder2.includes(key) && (debug4 || !kDebugOnly.includes(key))) {
      defaults[key] = pandoc2[key];
    }
  });
  const filtersContains = (filters, filter3) => {
    return filters.find((sysFilter) => {
      const sysPath = typeof sysFilter === "string" ? sysFilter : sysFilter.path;
      const filterPath = typeof filter3 === "string" ? filter3 : filter3.path;
      return sysPath === filterPath;
    });
  };
  if (defaults.filters?.length) {
    defaults.filters = defaults.filters.filter((filter3) => {
      return filter3 !== quartoMainFilter() && filtersContains(sysFilters, filter3);
    });
    if (defaults.filters?.length === 0) {
      delete defaults.filters;
    }
  }
  if (defaults.template && extname4(defaults.template) === kPatchedTemplateExt) {
    delete defaults.template;
  }
  if (defaults.writer) {
    if (defaults.writer.match(/(?:^|[\\/])_extensions[\\/]/) || defaults.writer.match(/(?:^|[\\/])extensions[\\/]quarto[\\/]/)) {
      delete defaults.writer;
    }
  }
  return stringify(defaults);
}

// command/render/pandoc.ts
init_constants6();
init_html();

// command/render/codetools.ts
init_constants6();
init_format5();

// execute/engine-info.ts
function executionEngineCanKeepSource(engine, target) {
  return !engine.canKeepSource || engine.canKeepSource(target);
}

// command/render/codetools.ts
init_format_html_info();
init_timing();
var kHideAllCodeLinkId = "quarto-hide-all-code";
var kShowAllCodeLinkId = "quarto-show-all-code";
var kViewSourceLinkId = "quarto-view-source";
var kEmbeddedSourceClass = "quarto-embedded-source-code";
var kEmbeddedSourceModalId = kEmbeddedSourceClass + "-modal";
var kEmbeddedSourceModalLabelId = kEmbeddedSourceClass + "-modal-label";
var kKeepSourceSentinel = "quarto-executable-code-5450563D";
var kCodeToolsSourceButtonId = "quarto-code-tools-source";
var kCodeToolsMenuButtonId = "quarto-code-tools-menu";
var kDataQuartoSourceUrl = "data-quarto-source-url";
function formatHasCodeTools(format14) {
  const codeTools = format14.render?.[kCodeTools];
  return !!codeTools && isHtmlOutput(format14.pandoc, true) && formatHasBootstrap(format14);
}
function resolveKeepSource(format14, engine, target) {
  const codeTools = format14.render?.[kCodeTools];
  if (codeTools === true || typeof codeTools === "object" && (codeTools?.source === void 0 || codeTools?.source === true)) {
    format14.render[kKeepSource] = true;
  }
  format14.render[kKeepSource] = format14.render[kKeepSource] && isHtmlOutput(format14.pandoc, true) && formatHasBootstrap(format14) && executionEngineCanKeepSource(engine, target);
}
function keepSourceBlock(format14, source2) {
  if (format14.render[kKeepSource]) {
    let code5 = Deno.readTextFileSync(source2).trimLeft();
    if (!code5.endsWith("\n")) {
      code5 = code5 + "\n";
    }
    code5 = code5.replaceAll(
      /\n```{(\w+)}\s*\n/g,
      "\n" + kKeepSourceSentinel + "\n\n```$1\n"
    );
    const kKeepSourceBackticks = "```````````````````";
    return `${kMarkdownBlockSeparator}::: {.${kEmbeddedSourceClass}}
${kKeepSourceBackticks}{.markdown shortcodes="false"}
${code5}${kKeepSourceBackticks}
:::
`;
  } else {
    return "";
  }
}
function codeToolsPostprocessor(format14) {
  return (doc) => {
    return withTiming("codeToolsPostprocessor", () => {
      if (format14.render[kKeepSource]) {
        const lines2 = doc.querySelectorAll(
          `.${kEmbeddedSourceClass} > div.sourceCode > pre > code > span`
        );
        if (lines2.length > 0) {
          const newLines = [];
          for (let i6 = 0; i6 < lines2.length; i6++) {
            const line = lines2[i6];
            if (line.innerText === kKeepSourceSentinel) {
              i6 += 2;
              const codeBlockLine = lines2[i6];
              const anchor = codeBlockLine.querySelector("a");
              const text = codeBlockLine.innerText;
              codeBlockLine.textContent = "";
              codeBlockLine.appendChild(anchor);
              const newSpan = doc.createElement("span");
              newSpan.classList.add("in");
              newSpan.innerText = text.replace(
                /```(\w+)/,
                "```{$1}"
              );
              codeBlockLine.appendChild(newSpan);
              newLines.push(codeBlockLine);
            } else {
              newLines.push(line);
            }
          }
          if (newLines.length !== lines2.length) {
            const parent = lines2[0].parentElement;
            parent.innerHTML = "";
            newLines.forEach((line) => {
              parent.appendChild(line);
              parent.appendChild(doc.createTextNode("\n"));
            });
          }
        }
      }
      if (formatHasCodeTools(format14)) {
        const codeTools = resolveCodeTools(format14, doc);
        if (codeTools.source || codeTools.toggle) {
          const title3 = doc.querySelector("#title-block-header h1");
          const header = title3 !== null ? title3.parentElement : doc.querySelector("main.content");
          if (header) {
            const titleDiv = doc.createElement("div");
            titleDiv.classList.add("quarto-title-block");
            const layoutDiv = doc.createElement("div");
            titleDiv.appendChild(layoutDiv);
            if (title3) {
              header?.replaceChild(titleDiv, title3);
              layoutDiv.appendChild(title3);
            } else {
              const h1El = doc.createElement("h1");
              layoutDiv.appendChild(h1El);
              layoutDiv.classList.add("quarto-title-tools-only");
            }
            const button = doc.createElement("button");
            button.setAttribute("type", "button");
            button.classList.add("btn");
            button.classList.add("code-tools-button");
            const icon = doc.createElement("i");
            icon.classList.add("bi");
            button.appendChild(icon);
            if (codeTools.caption !== "none") {
              button.appendChild(doc.createTextNode(" " + codeTools.caption));
            }
            layoutDiv.appendChild(button);
            if (title3) {
              header.appendChild(titleDiv);
            } else {
              header.prepend(titleDiv);
            }
            if (codeTools.toggle) {
              button.setAttribute("id", kCodeToolsMenuButtonId);
              button.classList.add("dropdown-toggle");
              button.setAttribute("data-bs-toggle", "dropdown");
              button.setAttribute("aria-expanded", "false");
              const ul = doc.createElement("ul");
              ul.classList.add("dropdown-menu");
              ul.classList.add("dropdown-menu-end");
              ul.setAttribute("aria-labelelledby", kCodeToolsMenuButtonId);
              const addListItem = (id, text) => {
                const a5 = doc.createElement("a");
                a5.setAttribute("id", id);
                a5.classList.add("dropdown-item");
                a5.setAttribute("href", "javascript:void(0)");
                a5.setAttribute("role", "button");
                a5.appendChild(doc.createTextNode(text));
                const li = doc.createElement("li");
                li.appendChild(a5);
                ul.appendChild(li);
                return li;
              };
              const addDivider = () => {
                const hr = doc.createElement("hr");
                hr.classList.add("dropdown-divider");
                const li = doc.createElement("li");
                li.appendChild(hr);
                ul.appendChild(li);
              };
              addListItem(
                kShowAllCodeLinkId,
                format14.language[kCodeToolsShowAllCode]
              );
              addListItem(
                kHideAllCodeLinkId,
                format14.language[kCodeToolsHideAllCode]
              );
              if (codeTools.source) {
                addDivider();
                const vsLi = addListItem(
                  kViewSourceLinkId,
                  format14.language[kCodeToolsViewSource]
                );
                if (typeof codeTools.source === "string") {
                  vsLi.firstChild.setAttribute(
                    kDataQuartoSourceUrl,
                    codeTools.source
                  );
                }
              }
              layoutDiv.appendChild(ul);
            } else {
              button.setAttribute("id", kCodeToolsSourceButtonId);
              if (typeof codeTools.source === "string") {
                button.setAttribute(kDataQuartoSourceUrl, codeTools.source);
              }
            }
          }
          if (codeTools.source) {
            const embeddedCode = doc.querySelector(`.${kEmbeddedSourceClass}`);
            if (embeddedCode) {
              const modalDiv = doc.createElement("div");
              modalDiv.classList.add("modal");
              modalDiv.classList.add("fade");
              modalDiv.setAttribute("id", kEmbeddedSourceModalId);
              modalDiv.setAttribute("tabindex", "-1");
              modalDiv.setAttribute(
                "aria-labelledby",
                kEmbeddedSourceModalLabelId
              );
              modalDiv.setAttribute("aria-hidden", "true");
              const modalDialogDiv = doc.createElement("div");
              modalDialogDiv.classList.add("modal-dialog");
              modalDialogDiv.classList.add("modal-dialog-scrollable");
              const modalContentDiv = doc.createElement("div");
              modalContentDiv.classList.add("modal-content");
              const modalDialogHeader = doc.createElement("div");
              modalDialogHeader.classList.add("modal-header");
              const h5 = doc.createElement("h5");
              h5.classList.add("modal-title");
              h5.setAttribute("id", kEmbeddedSourceModalLabelId);
              h5.appendChild(
                doc.createTextNode(format14.language[kCodeToolsSourceCode])
              );
              modalDialogHeader.appendChild(h5);
              const button = doc.createElement("button");
              button.classList.add("btn-close");
              button.setAttribute("data-bs-dismiss", "modal");
              modalDialogHeader.appendChild(button);
              modalContentDiv.appendChild(modalDialogHeader);
              const modalBody = doc.createElement("div");
              modalBody.classList.add("modal-body");
              modalContentDiv.appendChild(modalBody);
              modalDialogDiv.appendChild(modalContentDiv);
              modalDiv.appendChild(modalDialogDiv);
              const mainEl = doc.querySelector("main.content");
              if (mainEl) {
                const mainParentEl = mainEl.parentElement;
                mainParentEl?.insertBefore(modalDiv, mainParentEl.lastChild);
              } else {
                embeddedCode.parentElement?.insertBefore(
                  modalDiv,
                  embeddedCode
                );
              }
              modalBody.appendChild(embeddedCode);
              embeddedCode.classList.remove(kEmbeddedSourceClass);
            }
          }
          for (const el of Array.from(
            doc.querySelectorAll(
              "details div pre.hidden"
            )
          )) {
            const det = el.parentElement.parentElement;
            det.classList.add("hidden");
          }
        }
      }
      return Promise.resolve(kHtmlEmptyPostProcessResult);
    });
  };
}
function resolveCodeTools(format14, doc) {
  const kCodeCaption = format14.language[kCodeToolsMenuCaption];
  const codeTools = format14?.render[kCodeTools];
  const codeToolsResolved = {
    source: typeof codeTools === "boolean" ? codeTools : codeTools?.source !== void 0 ? codeTools?.source : true,
    toggle: typeof codeTools === "boolean" ? codeTools : codeTools?.toggle !== void 0 ? !!codeTools?.toggle : true,
    caption: typeof codeTools === "boolean" ? kCodeCaption : codeTools?.caption || kCodeCaption
  };
  if (codeToolsResolved.source === true) {
    codeToolsResolved.source = !!format14.render[kKeepSource];
  }
  if (codeToolsResolved.toggle) {
    const codeDetails = doc.querySelector(".cell > details > .sourceCode");
    const codeHidden = doc.querySelector(
      ".cell .sourceCode.hidden:not(div pre.js)"
    );
    codeToolsResolved.toggle = !!codeDetails || !!codeHidden;
  }
  return codeToolsResolved;
}

// command/render/pandoc.ts
init_render_paths();

// command/render/resources.ts
init_path();
init_path2();
init_lodash();
await init_engine();
init_project_scratch();

// execute/ojs/extract-resources.ts
init_colors2();
init_path();
init_base64();

// https://deno.land/x/media_types@v2.10.1/db.ts
var db = JSON.parse(`{
  "application/1d-interleaved-parityfec": {
    "source": "iana"
  },
  "application/3gpdash-qoe-report+xml": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true
  },
  "application/3gpp-ims+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/3gpphal+json": {
    "source": "iana",
    "compressible": true
  },
  "application/3gpphalforms+json": {
    "source": "iana",
    "compressible": true
  },
  "application/a2l": {
    "source": "iana"
  },
  "application/activemessage": {
    "source": "iana"
  },
  "application/activity+json": {
    "source": "iana",
    "compressible": true
  },
  "application/alto-costmap+json": {
    "source": "iana",
    "compressible": true
  },
  "application/alto-costmapfilter+json": {
    "source": "iana",
    "compressible": true
  },
  "application/alto-directory+json": {
    "source": "iana",
    "compressible": true
  },
  "application/alto-endpointcost+json": {
    "source": "iana",
    "compressible": true
  },
  "application/alto-endpointcostparams+json": {
    "source": "iana",
    "compressible": true
  },
  "application/alto-endpointprop+json": {
    "source": "iana",
    "compressible": true
  },
  "application/alto-endpointpropparams+json": {
    "source": "iana",
    "compressible": true
  },
  "application/alto-error+json": {
    "source": "iana",
    "compressible": true
  },
  "application/alto-networkmap+json": {
    "source": "iana",
    "compressible": true
  },
  "application/alto-networkmapfilter+json": {
    "source": "iana",
    "compressible": true
  },
  "application/alto-updatestreamcontrol+json": {
    "source": "iana",
    "compressible": true
  },
  "application/alto-updatestreamparams+json": {
    "source": "iana",
    "compressible": true
  },
  "application/aml": {
    "source": "iana"
  },
  "application/andrew-inset": {
    "source": "iana",
    "extensions": ["ez"]
  },
  "application/applefile": {
    "source": "iana"
  },
  "application/applixware": {
    "source": "apache",
    "extensions": ["aw"]
  },
  "application/atf": {
    "source": "iana"
  },
  "application/atfx": {
    "source": "iana"
  },
  "application/atom+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["atom"]
  },
  "application/atomcat+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["atomcat"]
  },
  "application/atomdeleted+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["atomdeleted"]
  },
  "application/atomicmail": {
    "source": "iana"
  },
  "application/atomsvc+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["atomsvc"]
  },
  "application/atsc-dwd+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["dwd"]
  },
  "application/atsc-dynamic-event-message": {
    "source": "iana"
  },
  "application/atsc-held+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["held"]
  },
  "application/atsc-rdt+json": {
    "source": "iana",
    "compressible": true
  },
  "application/atsc-rsat+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["rsat"]
  },
  "application/atxml": {
    "source": "iana"
  },
  "application/auth-policy+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/bacnet-xdd+zip": {
    "source": "iana",
    "compressible": false
  },
  "application/batch-smtp": {
    "source": "iana"
  },
  "application/bdoc": {
    "compressible": false,
    "extensions": ["bdoc"]
  },
  "application/beep+xml": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true
  },
  "application/calendar+json": {
    "source": "iana",
    "compressible": true
  },
  "application/calendar+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["xcs"]
  },
  "application/call-completion": {
    "source": "iana"
  },
  "application/cals-1840": {
    "source": "iana"
  },
  "application/captive+json": {
    "source": "iana",
    "compressible": true
  },
  "application/cbor": {
    "source": "iana"
  },
  "application/cbor-seq": {
    "source": "iana"
  },
  "application/cccex": {
    "source": "iana"
  },
  "application/ccmp+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/ccxml+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["ccxml"]
  },
  "application/cdfx+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["cdfx"]
  },
  "application/cdmi-capability": {
    "source": "iana",
    "extensions": ["cdmia"]
  },
  "application/cdmi-container": {
    "source": "iana",
    "extensions": ["cdmic"]
  },
  "application/cdmi-domain": {
    "source": "iana",
    "extensions": ["cdmid"]
  },
  "application/cdmi-object": {
    "source": "iana",
    "extensions": ["cdmio"]
  },
  "application/cdmi-queue": {
    "source": "iana",
    "extensions": ["cdmiq"]
  },
  "application/cdni": {
    "source": "iana"
  },
  "application/cea": {
    "source": "iana"
  },
  "application/cea-2018+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/cellml+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/cfw": {
    "source": "iana"
  },
  "application/clr": {
    "source": "iana"
  },
  "application/clue+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/clue_info+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/cms": {
    "source": "iana"
  },
  "application/cnrp+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/coap-group+json": {
    "source": "iana",
    "compressible": true
  },
  "application/coap-payload": {
    "source": "iana"
  },
  "application/commonground": {
    "source": "iana"
  },
  "application/conference-info+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/cose": {
    "source": "iana"
  },
  "application/cose-key": {
    "source": "iana"
  },
  "application/cose-key-set": {
    "source": "iana"
  },
  "application/cpl+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/csrattrs": {
    "source": "iana"
  },
  "application/csta+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/cstadata+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/csvm+json": {
    "source": "iana",
    "compressible": true
  },
  "application/cu-seeme": {
    "source": "apache",
    "extensions": ["cu"]
  },
  "application/cwt": {
    "source": "iana"
  },
  "application/cybercash": {
    "source": "iana"
  },
  "application/dart": {
    "compressible": true
  },
  "application/dash+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["mpd"]
  },
  "application/dashdelta": {
    "source": "iana"
  },
  "application/davmount+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["davmount"]
  },
  "application/dca-rft": {
    "source": "iana"
  },
  "application/dcd": {
    "source": "iana"
  },
  "application/dec-dx": {
    "source": "iana"
  },
  "application/dialog-info+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/dicom": {
    "source": "iana"
  },
  "application/dicom+json": {
    "source": "iana",
    "compressible": true
  },
  "application/dicom+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/dii": {
    "source": "iana"
  },
  "application/dit": {
    "source": "iana"
  },
  "application/dns": {
    "source": "iana"
  },
  "application/dns+json": {
    "source": "iana",
    "compressible": true
  },
  "application/dns-message": {
    "source": "iana"
  },
  "application/docbook+xml": {
    "source": "apache",
    "compressible": true,
    "extensions": ["dbk"]
  },
  "application/dots+cbor": {
    "source": "iana"
  },
  "application/dskpp+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/dssc+der": {
    "source": "iana",
    "extensions": ["dssc"]
  },
  "application/dssc+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["xdssc"]
  },
  "application/dvcs": {
    "source": "iana"
  },
  "application/ecmascript": {
    "source": "iana",
    "compressible": true,
    "extensions": ["es","ecma"]
  },
  "application/edi-consent": {
    "source": "iana"
  },
  "application/edi-x12": {
    "source": "iana",
    "compressible": false
  },
  "application/edifact": {
    "source": "iana",
    "compressible": false
  },
  "application/efi": {
    "source": "iana"
  },
  "application/elm+json": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true
  },
  "application/elm+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/emergencycalldata.cap+xml": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true
  },
  "application/emergencycalldata.comment+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/emergencycalldata.control+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/emergencycalldata.deviceinfo+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/emergencycalldata.ecall.msd": {
    "source": "iana"
  },
  "application/emergencycalldata.providerinfo+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/emergencycalldata.serviceinfo+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/emergencycalldata.subscriberinfo+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/emergencycalldata.veds+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/emma+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["emma"]
  },
  "application/emotionml+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["emotionml"]
  },
  "application/encaprtp": {
    "source": "iana"
  },
  "application/epp+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/epub+zip": {
    "source": "iana",
    "compressible": false,
    "extensions": ["epub"]
  },
  "application/eshop": {
    "source": "iana"
  },
  "application/exi": {
    "source": "iana",
    "extensions": ["exi"]
  },
  "application/expect-ct-report+json": {
    "source": "iana",
    "compressible": true
  },
  "application/fastinfoset": {
    "source": "iana"
  },
  "application/fastsoap": {
    "source": "iana"
  },
  "application/fdt+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["fdt"]
  },
  "application/fhir+json": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true
  },
  "application/fhir+xml": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true
  },
  "application/fido.trusted-apps+json": {
    "compressible": true
  },
  "application/fits": {
    "source": "iana"
  },
  "application/flexfec": {
    "source": "iana"
  },
  "application/font-sfnt": {
    "source": "iana"
  },
  "application/font-tdpfr": {
    "source": "iana",
    "extensions": ["pfr"]
  },
  "application/font-woff": {
    "source": "iana",
    "compressible": false
  },
  "application/framework-attributes+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/geo+json": {
    "source": "iana",
    "compressible": true,
    "extensions": ["geojson"]
  },
  "application/geo+json-seq": {
    "source": "iana"
  },
  "application/geopackage+sqlite3": {
    "source": "iana"
  },
  "application/geoxacml+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/gltf-buffer": {
    "source": "iana"
  },
  "application/gml+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["gml"]
  },
  "application/gpx+xml": {
    "source": "apache",
    "compressible": true,
    "extensions": ["gpx"]
  },
  "application/gxf": {
    "source": "apache",
    "extensions": ["gxf"]
  },
  "application/gzip": {
    "source": "iana",
    "compressible": false,
    "extensions": ["gz"]
  },
  "application/h224": {
    "source": "iana"
  },
  "application/held+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/hjson": {
    "extensions": ["hjson"]
  },
  "application/http": {
    "source": "iana"
  },
  "application/hyperstudio": {
    "source": "iana",
    "extensions": ["stk"]
  },
  "application/ibe-key-request+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/ibe-pkg-reply+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/ibe-pp-data": {
    "source": "iana"
  },
  "application/iges": {
    "source": "iana"
  },
  "application/im-iscomposing+xml": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true
  },
  "application/index": {
    "source": "iana"
  },
  "application/index.cmd": {
    "source": "iana"
  },
  "application/index.obj": {
    "source": "iana"
  },
  "application/index.response": {
    "source": "iana"
  },
  "application/index.vnd": {
    "source": "iana"
  },
  "application/inkml+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["ink","inkml"]
  },
  "application/iotp": {
    "source": "iana"
  },
  "application/ipfix": {
    "source": "iana",
    "extensions": ["ipfix"]
  },
  "application/ipp": {
    "source": "iana"
  },
  "application/isup": {
    "source": "iana"
  },
  "application/its+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["its"]
  },
  "application/java-archive": {
    "source": "apache",
    "compressible": false,
    "extensions": ["jar","war","ear"]
  },
  "application/java-serialized-object": {
    "source": "apache",
    "compressible": false,
    "extensions": ["ser"]
  },
  "application/java-vm": {
    "source": "apache",
    "compressible": false,
    "extensions": ["class"]
  },
  "application/javascript": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true,
    "extensions": ["js","mjs"]
  },
  "application/jf2feed+json": {
    "source": "iana",
    "compressible": true
  },
  "application/jose": {
    "source": "iana"
  },
  "application/jose+json": {
    "source": "iana",
    "compressible": true
  },
  "application/jrd+json": {
    "source": "iana",
    "compressible": true
  },
  "application/jscalendar+json": {
    "source": "iana",
    "compressible": true
  },
  "application/json": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true,
    "extensions": ["json","map"]
  },
  "application/json-patch+json": {
    "source": "iana",
    "compressible": true
  },
  "application/json-seq": {
    "source": "iana"
  },
  "application/json5": {
    "extensions": ["json5"]
  },
  "application/jsonml+json": {
    "source": "apache",
    "compressible": true,
    "extensions": ["jsonml"]
  },
  "application/jwk+json": {
    "source": "iana",
    "compressible": true
  },
  "application/jwk-set+json": {
    "source": "iana",
    "compressible": true
  },
  "application/jwt": {
    "source": "iana"
  },
  "application/kpml-request+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/kpml-response+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/ld+json": {
    "source": "iana",
    "compressible": true,
    "extensions": ["jsonld"]
  },
  "application/lgr+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["lgr"]
  },
  "application/link-format": {
    "source": "iana"
  },
  "application/load-control+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/lost+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["lostxml"]
  },
  "application/lostsync+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/lpf+zip": {
    "source": "iana",
    "compressible": false
  },
  "application/lxf": {
    "source": "iana"
  },
  "application/mac-binhex40": {
    "source": "iana",
    "extensions": ["hqx"]
  },
  "application/mac-compactpro": {
    "source": "apache",
    "extensions": ["cpt"]
  },
  "application/macwriteii": {
    "source": "iana"
  },
  "application/mads+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["mads"]
  },
  "application/manifest+json": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true,
    "extensions": ["webmanifest"]
  },
  "application/marc": {
    "source": "iana",
    "extensions": ["mrc"]
  },
  "application/marcxml+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["mrcx"]
  },
  "application/mathematica": {
    "source": "iana",
    "extensions": ["ma","nb","mb"]
  },
  "application/mathml+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["mathml"]
  },
  "application/mathml-content+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/mathml-presentation+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/mbms-associated-procedure-description+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/mbms-deregister+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/mbms-envelope+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/mbms-msk+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/mbms-msk-response+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/mbms-protection-description+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/mbms-reception-report+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/mbms-register+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/mbms-register-response+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/mbms-schedule+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/mbms-user-service-description+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/mbox": {
    "source": "iana",
    "extensions": ["mbox"]
  },
  "application/media-policy-dataset+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/media_control+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/mediaservercontrol+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["mscml"]
  },
  "application/merge-patch+json": {
    "source": "iana",
    "compressible": true
  },
  "application/metalink+xml": {
    "source": "apache",
    "compressible": true,
    "extensions": ["metalink"]
  },
  "application/metalink4+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["meta4"]
  },
  "application/mets+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["mets"]
  },
  "application/mf4": {
    "source": "iana"
  },
  "application/mikey": {
    "source": "iana"
  },
  "application/mipc": {
    "source": "iana"
  },
  "application/missing-blocks+cbor-seq": {
    "source": "iana"
  },
  "application/mmt-aei+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["maei"]
  },
  "application/mmt-usd+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["musd"]
  },
  "application/mods+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["mods"]
  },
  "application/moss-keys": {
    "source": "iana"
  },
  "application/moss-signature": {
    "source": "iana"
  },
  "application/mosskey-data": {
    "source": "iana"
  },
  "application/mosskey-request": {
    "source": "iana"
  },
  "application/mp21": {
    "source": "iana",
    "extensions": ["m21","mp21"]
  },
  "application/mp4": {
    "source": "iana",
    "extensions": ["mp4s","m4p"]
  },
  "application/mpeg4-generic": {
    "source": "iana"
  },
  "application/mpeg4-iod": {
    "source": "iana"
  },
  "application/mpeg4-iod-xmt": {
    "source": "iana"
  },
  "application/mrb-consumer+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/mrb-publish+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/msc-ivr+xml": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true
  },
  "application/msc-mixer+xml": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true
  },
  "application/msword": {
    "source": "iana",
    "compressible": false,
    "extensions": ["doc","dot"]
  },
  "application/mud+json": {
    "source": "iana",
    "compressible": true
  },
  "application/multipart-core": {
    "source": "iana"
  },
  "application/mxf": {
    "source": "iana",
    "extensions": ["mxf"]
  },
  "application/n-quads": {
    "source": "iana",
    "extensions": ["nq"]
  },
  "application/n-triples": {
    "source": "iana",
    "extensions": ["nt"]
  },
  "application/nasdata": {
    "source": "iana"
  },
  "application/news-checkgroups": {
    "source": "iana",
    "charset": "US-ASCII"
  },
  "application/news-groupinfo": {
    "source": "iana",
    "charset": "US-ASCII"
  },
  "application/news-transmission": {
    "source": "iana"
  },
  "application/nlsml+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/node": {
    "source": "iana",
    "extensions": ["cjs"]
  },
  "application/nss": {
    "source": "iana"
  },
  "application/oauth-authz-req+jwt": {
    "source": "iana"
  },
  "application/ocsp-request": {
    "source": "iana"
  },
  "application/ocsp-response": {
    "source": "iana"
  },
  "application/octet-stream": {
    "source": "iana",
    "compressible": false,
    "extensions": ["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"]
  },
  "application/oda": {
    "source": "iana",
    "extensions": ["oda"]
  },
  "application/odm+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/odx": {
    "source": "iana"
  },
  "application/oebps-package+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["opf"]
  },
  "application/ogg": {
    "source": "iana",
    "compressible": false,
    "extensions": ["ogx"]
  },
  "application/omdoc+xml": {
    "source": "apache",
    "compressible": true,
    "extensions": ["omdoc"]
  },
  "application/onenote": {
    "source": "apache",
    "extensions": ["onetoc","onetoc2","onetmp","onepkg"]
  },
  "application/opc-nodeset+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/oscore": {
    "source": "iana"
  },
  "application/oxps": {
    "source": "iana",
    "extensions": ["oxps"]
  },
  "application/p21+zip": {
    "source": "iana",
    "compressible": false
  },
  "application/p2p-overlay+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["relo"]
  },
  "application/parityfec": {
    "source": "iana"
  },
  "application/passport": {
    "source": "iana"
  },
  "application/patch-ops-error+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["xer"]
  },
  "application/pdf": {
    "source": "iana",
    "compressible": false,
    "extensions": ["pdf"]
  },
  "application/pdx": {
    "source": "iana"
  },
  "application/pem-certificate-chain": {
    "source": "iana"
  },
  "application/pgp-encrypted": {
    "source": "iana",
    "compressible": false,
    "extensions": ["pgp"]
  },
  "application/pgp-keys": {
    "source": "iana"
  },
  "application/pgp-signature": {
    "source": "iana",
    "extensions": ["asc","sig"]
  },
  "application/pics-rules": {
    "source": "apache",
    "extensions": ["prf"]
  },
  "application/pidf+xml": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true
  },
  "application/pidf-diff+xml": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true
  },
  "application/pkcs10": {
    "source": "iana",
    "extensions": ["p10"]
  },
  "application/pkcs12": {
    "source": "iana"
  },
  "application/pkcs7-mime": {
    "source": "iana",
    "extensions": ["p7m","p7c"]
  },
  "application/pkcs7-signature": {
    "source": "iana",
    "extensions": ["p7s"]
  },
  "application/pkcs8": {
    "source": "iana",
    "extensions": ["p8"]
  },
  "application/pkcs8-encrypted": {
    "source": "iana"
  },
  "application/pkix-attr-cert": {
    "source": "iana",
    "extensions": ["ac"]
  },
  "application/pkix-cert": {
    "source": "iana",
    "extensions": ["cer"]
  },
  "application/pkix-crl": {
    "source": "iana",
    "extensions": ["crl"]
  },
  "application/pkix-pkipath": {
    "source": "iana",
    "extensions": ["pkipath"]
  },
  "application/pkixcmp": {
    "source": "iana",
    "extensions": ["pki"]
  },
  "application/pls+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["pls"]
  },
  "application/poc-settings+xml": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true
  },
  "application/postscript": {
    "source": "iana",
    "compressible": true,
    "extensions": ["ai","eps","ps"]
  },
  "application/ppsp-tracker+json": {
    "source": "iana",
    "compressible": true
  },
  "application/problem+json": {
    "source": "iana",
    "compressible": true
  },
  "application/problem+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/provenance+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["provx"]
  },
  "application/prs.alvestrand.titrax-sheet": {
    "source": "iana"
  },
  "application/prs.cww": {
    "source": "iana",
    "extensions": ["cww"]
  },
  "application/prs.cyn": {
    "source": "iana",
    "charset": "7-BIT"
  },
  "application/prs.hpub+zip": {
    "source": "iana",
    "compressible": false
  },
  "application/prs.nprend": {
    "source": "iana"
  },
  "application/prs.plucker": {
    "source": "iana"
  },
  "application/prs.rdf-xml-crypt": {
    "source": "iana"
  },
  "application/prs.xsf+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/pskc+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["pskcxml"]
  },
  "application/pvd+json": {
    "source": "iana",
    "compressible": true
  },
  "application/qsig": {
    "source": "iana"
  },
  "application/raml+yaml": {
    "compressible": true,
    "extensions": ["raml"]
  },
  "application/raptorfec": {
    "source": "iana"
  },
  "application/rdap+json": {
    "source": "iana",
    "compressible": true
  },
  "application/rdf+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["rdf","owl"]
  },
  "application/reginfo+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["rif"]
  },
  "application/relax-ng-compact-syntax": {
    "source": "iana",
    "extensions": ["rnc"]
  },
  "application/remote-printing": {
    "source": "iana"
  },
  "application/reputon+json": {
    "source": "iana",
    "compressible": true
  },
  "application/resource-lists+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["rl"]
  },
  "application/resource-lists-diff+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["rld"]
  },
  "application/rfc+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/riscos": {
    "source": "iana"
  },
  "application/rlmi+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/rls-services+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["rs"]
  },
  "application/route-apd+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["rapd"]
  },
  "application/route-s-tsid+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["sls"]
  },
  "application/route-usd+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["rusd"]
  },
  "application/rpki-ghostbusters": {
    "source": "iana",
    "extensions": ["gbr"]
  },
  "application/rpki-manifest": {
    "source": "iana",
    "extensions": ["mft"]
  },
  "application/rpki-publication": {
    "source": "iana"
  },
  "application/rpki-roa": {
    "source": "iana",
    "extensions": ["roa"]
  },
  "application/rpki-updown": {
    "source": "iana"
  },
  "application/rsd+xml": {
    "source": "apache",
    "compressible": true,
    "extensions": ["rsd"]
  },
  "application/rss+xml": {
    "source": "apache",
    "compressible": true,
    "extensions": ["rss"]
  },
  "application/rtf": {
    "source": "iana",
    "compressible": true,
    "extensions": ["rtf"]
  },
  "application/rtploopback": {
    "source": "iana"
  },
  "application/rtx": {
    "source": "iana"
  },
  "application/samlassertion+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/samlmetadata+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/sarif+json": {
    "source": "iana",
    "compressible": true
  },
  "application/sarif-external-properties+json": {
    "source": "iana",
    "compressible": true
  },
  "application/sbe": {
    "source": "iana"
  },
  "application/sbml+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["sbml"]
  },
  "application/scaip+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/scim+json": {
    "source": "iana",
    "compressible": true
  },
  "application/scvp-cv-request": {
    "source": "iana",
    "extensions": ["scq"]
  },
  "application/scvp-cv-response": {
    "source": "iana",
    "extensions": ["scs"]
  },
  "application/scvp-vp-request": {
    "source": "iana",
    "extensions": ["spq"]
  },
  "application/scvp-vp-response": {
    "source": "iana",
    "extensions": ["spp"]
  },
  "application/sdp": {
    "source": "iana",
    "extensions": ["sdp"]
  },
  "application/secevent+jwt": {
    "source": "iana"
  },
  "application/senml+cbor": {
    "source": "iana"
  },
  "application/senml+json": {
    "source": "iana",
    "compressible": true
  },
  "application/senml+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["senmlx"]
  },
  "application/senml-etch+cbor": {
    "source": "iana"
  },
  "application/senml-etch+json": {
    "source": "iana",
    "compressible": true
  },
  "application/senml-exi": {
    "source": "iana"
  },
  "application/sensml+cbor": {
    "source": "iana"
  },
  "application/sensml+json": {
    "source": "iana",
    "compressible": true
  },
  "application/sensml+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["sensmlx"]
  },
  "application/sensml-exi": {
    "source": "iana"
  },
  "application/sep+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/sep-exi": {
    "source": "iana"
  },
  "application/session-info": {
    "source": "iana"
  },
  "application/set-payment": {
    "source": "iana"
  },
  "application/set-payment-initiation": {
    "source": "iana",
    "extensions": ["setpay"]
  },
  "application/set-registration": {
    "source": "iana"
  },
  "application/set-registration-initiation": {
    "source": "iana",
    "extensions": ["setreg"]
  },
  "application/sgml": {
    "source": "iana"
  },
  "application/sgml-open-catalog": {
    "source": "iana"
  },
  "application/shf+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["shf"]
  },
  "application/sieve": {
    "source": "iana",
    "extensions": ["siv","sieve"]
  },
  "application/simple-filter+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/simple-message-summary": {
    "source": "iana"
  },
  "application/simplesymbolcontainer": {
    "source": "iana"
  },
  "application/sipc": {
    "source": "iana"
  },
  "application/slate": {
    "source": "iana"
  },
  "application/smil": {
    "source": "iana"
  },
  "application/smil+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["smi","smil"]
  },
  "application/smpte336m": {
    "source": "iana"
  },
  "application/soap+fastinfoset": {
    "source": "iana"
  },
  "application/soap+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/sparql-query": {
    "source": "iana",
    "extensions": ["rq"]
  },
  "application/sparql-results+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["srx"]
  },
  "application/spirits-event+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/sql": {
    "source": "iana"
  },
  "application/srgs": {
    "source": "iana",
    "extensions": ["gram"]
  },
  "application/srgs+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["grxml"]
  },
  "application/sru+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["sru"]
  },
  "application/ssdl+xml": {
    "source": "apache",
    "compressible": true,
    "extensions": ["ssdl"]
  },
  "application/ssml+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["ssml"]
  },
  "application/stix+json": {
    "source": "iana",
    "compressible": true
  },
  "application/swid+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["swidtag"]
  },
  "application/tamp-apex-update": {
    "source": "iana"
  },
  "application/tamp-apex-update-confirm": {
    "source": "iana"
  },
  "application/tamp-community-update": {
    "source": "iana"
  },
  "application/tamp-community-update-confirm": {
    "source": "iana"
  },
  "application/tamp-error": {
    "source": "iana"
  },
  "application/tamp-sequence-adjust": {
    "source": "iana"
  },
  "application/tamp-sequence-adjust-confirm": {
    "source": "iana"
  },
  "application/tamp-status-query": {
    "source": "iana"
  },
  "application/tamp-status-response": {
    "source": "iana"
  },
  "application/tamp-update": {
    "source": "iana"
  },
  "application/tamp-update-confirm": {
    "source": "iana"
  },
  "application/tar": {
    "compressible": true
  },
  "application/taxii+json": {
    "source": "iana",
    "compressible": true
  },
  "application/td+json": {
    "source": "iana",
    "compressible": true
  },
  "application/tei+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["tei","teicorpus"]
  },
  "application/tetra_isi": {
    "source": "iana"
  },
  "application/thraud+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["tfi"]
  },
  "application/timestamp-query": {
    "source": "iana"
  },
  "application/timestamp-reply": {
    "source": "iana"
  },
  "application/timestamped-data": {
    "source": "iana",
    "extensions": ["tsd"]
  },
  "application/tlsrpt+gzip": {
    "source": "iana"
  },
  "application/tlsrpt+json": {
    "source": "iana",
    "compressible": true
  },
  "application/tnauthlist": {
    "source": "iana"
  },
  "application/toml": {
    "compressible": true,
    "extensions": ["toml"]
  },
  "application/trickle-ice-sdpfrag": {
    "source": "iana"
  },
  "application/trig": {
    "source": "iana",
    "extensions": ["trig"]
  },
  "application/ttml+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["ttml"]
  },
  "application/tve-trigger": {
    "source": "iana"
  },
  "application/tzif": {
    "source": "iana"
  },
  "application/tzif-leap": {
    "source": "iana"
  },
  "application/ubjson": {
    "compressible": false,
    "extensions": ["ubj"]
  },
  "application/ulpfec": {
    "source": "iana"
  },
  "application/urc-grpsheet+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/urc-ressheet+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["rsheet"]
  },
  "application/urc-targetdesc+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["td"]
  },
  "application/urc-uisocketdesc+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vcard+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vcard+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vemmi": {
    "source": "iana"
  },
  "application/vividence.scriptfile": {
    "source": "apache"
  },
  "application/vnd.1000minds.decision-model+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["1km"]
  },
  "application/vnd.3gpp-prose+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp-prose-pc3ch+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp-v2x-local-service-information": {
    "source": "iana"
  },
  "application/vnd.3gpp.5gnas": {
    "source": "iana"
  },
  "application/vnd.3gpp.access-transfer-events+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.bsf+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.gmop+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.gtpc": {
    "source": "iana"
  },
  "application/vnd.3gpp.interworking-data": {
    "source": "iana"
  },
  "application/vnd.3gpp.lpp": {
    "source": "iana"
  },
  "application/vnd.3gpp.mc-signalling-ear": {
    "source": "iana"
  },
  "application/vnd.3gpp.mcdata-affiliation-command+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcdata-info+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcdata-payload": {
    "source": "iana"
  },
  "application/vnd.3gpp.mcdata-service-config+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcdata-signalling": {
    "source": "iana"
  },
  "application/vnd.3gpp.mcdata-ue-config+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcdata-user-profile+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcptt-affiliation-command+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcptt-floor-request+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcptt-info+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcptt-location-info+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcptt-mbms-usage-info+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcptt-service-config+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcptt-signed+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcptt-ue-config+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcptt-ue-init-config+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcptt-user-profile+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcvideo-affiliation-command+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcvideo-affiliation-info+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcvideo-info+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcvideo-location-info+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcvideo-mbms-usage-info+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcvideo-service-config+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcvideo-transmission-request+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcvideo-ue-config+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcvideo-user-profile+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mid-call+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.ngap": {
    "source": "iana"
  },
  "application/vnd.3gpp.pfcp": {
    "source": "iana"
  },
  "application/vnd.3gpp.pic-bw-large": {
    "source": "iana",
    "extensions": ["plb"]
  },
  "application/vnd.3gpp.pic-bw-small": {
    "source": "iana",
    "extensions": ["psb"]
  },
  "application/vnd.3gpp.pic-bw-var": {
    "source": "iana",
    "extensions": ["pvb"]
  },
  "application/vnd.3gpp.s1ap": {
    "source": "iana"
  },
  "application/vnd.3gpp.sms": {
    "source": "iana"
  },
  "application/vnd.3gpp.sms+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.srvcc-ext+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.srvcc-info+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.state-and-event-info+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.ussd+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp2.bcmcsinfo+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp2.sms": {
    "source": "iana"
  },
  "application/vnd.3gpp2.tcap": {
    "source": "iana",
    "extensions": ["tcap"]
  },
  "application/vnd.3lightssoftware.imagescal": {
    "source": "iana"
  },
  "application/vnd.3m.post-it-notes": {
    "source": "iana",
    "extensions": ["pwn"]
  },
  "application/vnd.accpac.simply.aso": {
    "source": "iana",
    "extensions": ["aso"]
  },
  "application/vnd.accpac.simply.imp": {
    "source": "iana",
    "extensions": ["imp"]
  },
  "application/vnd.acucobol": {
    "source": "iana",
    "extensions": ["acu"]
  },
  "application/vnd.acucorp": {
    "source": "iana",
    "extensions": ["atc","acutc"]
  },
  "application/vnd.adobe.air-application-installer-package+zip": {
    "source": "apache",
    "compressible": false,
    "extensions": ["air"]
  },
  "application/vnd.adobe.flash.movie": {
    "source": "iana"
  },
  "application/vnd.adobe.formscentral.fcdt": {
    "source": "iana",
    "extensions": ["fcdt"]
  },
  "application/vnd.adobe.fxp": {
    "source": "iana",
    "extensions": ["fxp","fxpl"]
  },
  "application/vnd.adobe.partial-upload": {
    "source": "iana"
  },
  "application/vnd.adobe.xdp+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["xdp"]
  },
  "application/vnd.adobe.xfdf": {
    "source": "iana",
    "extensions": ["xfdf"]
  },
  "application/vnd.aether.imp": {
    "source": "iana"
  },
  "application/vnd.afpc.afplinedata": {
    "source": "iana"
  },
  "application/vnd.afpc.afplinedata-pagedef": {
    "source": "iana"
  },
  "application/vnd.afpc.cmoca-cmresource": {
    "source": "iana"
  },
  "application/vnd.afpc.foca-charset": {
    "source": "iana"
  },
  "application/vnd.afpc.foca-codedfont": {
    "source": "iana"
  },
  "application/vnd.afpc.foca-codepage": {
    "source": "iana"
  },
  "application/vnd.afpc.modca": {
    "source": "iana"
  },
  "application/vnd.afpc.modca-cmtable": {
    "source": "iana"
  },
  "application/vnd.afpc.modca-formdef": {
    "source": "iana"
  },
  "application/vnd.afpc.modca-mediummap": {
    "source": "iana"
  },
  "application/vnd.afpc.modca-objectcontainer": {
    "source": "iana"
  },
  "application/vnd.afpc.modca-overlay": {
    "source": "iana"
  },
  "application/vnd.afpc.modca-pagesegment": {
    "source": "iana"
  },
  "application/vnd.ah-barcode": {
    "source": "iana"
  },
  "application/vnd.ahead.space": {
    "source": "iana",
    "extensions": ["ahead"]
  },
  "application/vnd.airzip.filesecure.azf": {
    "source": "iana",
    "extensions": ["azf"]
  },
  "application/vnd.airzip.filesecure.azs": {
    "source": "iana",
    "extensions": ["azs"]
  },
  "application/vnd.amadeus+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.amazon.ebook": {
    "source": "apache",
    "extensions": ["azw"]
  },
  "application/vnd.amazon.mobi8-ebook": {
    "source": "iana"
  },
  "application/vnd.americandynamics.acc": {
    "source": "iana",
    "extensions": ["acc"]
  },
  "application/vnd.amiga.ami": {
    "source": "iana",
    "extensions": ["ami"]
  },
  "application/vnd.amundsen.maze+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.android.ota": {
    "source": "iana"
  },
  "application/vnd.android.package-archive": {
    "source": "apache",
    "compressible": false,
    "extensions": ["apk"]
  },
  "application/vnd.anki": {
    "source": "iana"
  },
  "application/vnd.anser-web-certificate-issue-initiation": {
    "source": "iana",
    "extensions": ["cii"]
  },
  "application/vnd.anser-web-funds-transfer-initiation": {
    "source": "apache",
    "extensions": ["fti"]
  },
  "application/vnd.antix.game-component": {
    "source": "iana",
    "extensions": ["atx"]
  },
  "application/vnd.apache.arrow.file": {
    "source": "iana"
  },
  "application/vnd.apache.arrow.stream": {
    "source": "iana"
  },
  "application/vnd.apache.thrift.binary": {
    "source": "iana"
  },
  "application/vnd.apache.thrift.compact": {
    "source": "iana"
  },
  "application/vnd.apache.thrift.json": {
    "source": "iana"
  },
  "application/vnd.api+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.aplextor.warrp+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.apothekende.reservation+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.apple.installer+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["mpkg"]
  },
  "application/vnd.apple.keynote": {
    "source": "iana",
    "extensions": ["key"]
  },
  "application/vnd.apple.mpegurl": {
    "source": "iana",
    "extensions": ["m3u8"]
  },
  "application/vnd.apple.numbers": {
    "source": "iana",
    "extensions": ["numbers"]
  },
  "application/vnd.apple.pages": {
    "source": "iana",
    "extensions": ["pages"]
  },
  "application/vnd.apple.pkpass": {
    "compressible": false,
    "extensions": ["pkpass"]
  },
  "application/vnd.arastra.swi": {
    "source": "iana"
  },
  "application/vnd.aristanetworks.swi": {
    "source": "iana",
    "extensions": ["swi"]
  },
  "application/vnd.artisan+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.artsquare": {
    "source": "iana"
  },
  "application/vnd.astraea-software.iota": {
    "source": "iana",
    "extensions": ["iota"]
  },
  "application/vnd.audiograph": {
    "source": "iana",
    "extensions": ["aep"]
  },
  "application/vnd.autopackage": {
    "source": "iana"
  },
  "application/vnd.avalon+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.avistar+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.balsamiq.bmml+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["bmml"]
  },
  "application/vnd.balsamiq.bmpr": {
    "source": "iana"
  },
  "application/vnd.banana-accounting": {
    "source": "iana"
  },
  "application/vnd.bbf.usp.error": {
    "source": "iana"
  },
  "application/vnd.bbf.usp.msg": {
    "source": "iana"
  },
  "application/vnd.bbf.usp.msg+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.bekitzur-stech+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.bint.med-content": {
    "source": "iana"
  },
  "application/vnd.biopax.rdf+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.blink-idb-value-wrapper": {
    "source": "iana"
  },
  "application/vnd.blueice.multipass": {
    "source": "iana",
    "extensions": ["mpm"]
  },
  "application/vnd.bluetooth.ep.oob": {
    "source": "iana"
  },
  "application/vnd.bluetooth.le.oob": {
    "source": "iana"
  },
  "application/vnd.bmi": {
    "source": "iana",
    "extensions": ["bmi"]
  },
  "application/vnd.bpf": {
    "source": "iana"
  },
  "application/vnd.bpf3": {
    "source": "iana"
  },
  "application/vnd.businessobjects": {
    "source": "iana",
    "extensions": ["rep"]
  },
  "application/vnd.byu.uapi+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.cab-jscript": {
    "source": "iana"
  },
  "application/vnd.canon-cpdl": {
    "source": "iana"
  },
  "application/vnd.canon-lips": {
    "source": "iana"
  },
  "application/vnd.capasystems-pg+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.cendio.thinlinc.clientconf": {
    "source": "iana"
  },
  "application/vnd.century-systems.tcp_stream": {
    "source": "iana"
  },
  "application/vnd.chemdraw+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["cdxml"]
  },
  "application/vnd.chess-pgn": {
    "source": "iana"
  },
  "application/vnd.chipnuts.karaoke-mmd": {
    "source": "iana",
    "extensions": ["mmd"]
  },
  "application/vnd.ciedi": {
    "source": "iana"
  },
  "application/vnd.cinderella": {
    "source": "iana",
    "extensions": ["cdy"]
  },
  "application/vnd.cirpack.isdn-ext": {
    "source": "iana"
  },
  "application/vnd.citationstyles.style+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["csl"]
  },
  "application/vnd.claymore": {
    "source": "iana",
    "extensions": ["cla"]
  },
  "application/vnd.cloanto.rp9": {
    "source": "iana",
    "extensions": ["rp9"]
  },
  "application/vnd.clonk.c4group": {
    "source": "iana",
    "extensions": ["c4g","c4d","c4f","c4p","c4u"]
  },
  "application/vnd.cluetrust.cartomobile-config": {
    "source": "iana",
    "extensions": ["c11amc"]
  },
  "application/vnd.cluetrust.cartomobile-config-pkg": {
    "source": "iana",
    "extensions": ["c11amz"]
  },
  "application/vnd.coffeescript": {
    "source": "iana"
  },
  "application/vnd.collabio.xodocuments.document": {
    "source": "iana"
  },
  "application/vnd.collabio.xodocuments.document-template": {
    "source": "iana"
  },
  "application/vnd.collabio.xodocuments.presentation": {
    "source": "iana"
  },
  "application/vnd.collabio.xodocuments.presentation-template": {
    "source": "iana"
  },
  "application/vnd.collabio.xodocuments.spreadsheet": {
    "source": "iana"
  },
  "application/vnd.collabio.xodocuments.spreadsheet-template": {
    "source": "iana"
  },
  "application/vnd.collection+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.collection.doc+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.collection.next+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.comicbook+zip": {
    "source": "iana",
    "compressible": false
  },
  "application/vnd.comicbook-rar": {
    "source": "iana"
  },
  "application/vnd.commerce-battelle": {
    "source": "iana"
  },
  "application/vnd.commonspace": {
    "source": "iana",
    "extensions": ["csp"]
  },
  "application/vnd.contact.cmsg": {
    "source": "iana",
    "extensions": ["cdbcmsg"]
  },
  "application/vnd.coreos.ignition+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.cosmocaller": {
    "source": "iana",
    "extensions": ["cmc"]
  },
  "application/vnd.crick.clicker": {
    "source": "iana",
    "extensions": ["clkx"]
  },
  "application/vnd.crick.clicker.keyboard": {
    "source": "iana",
    "extensions": ["clkk"]
  },
  "application/vnd.crick.clicker.palette": {
    "source": "iana",
    "extensions": ["clkp"]
  },
  "application/vnd.crick.clicker.template": {
    "source": "iana",
    "extensions": ["clkt"]
  },
  "application/vnd.crick.clicker.wordbank": {
    "source": "iana",
    "extensions": ["clkw"]
  },
  "application/vnd.criticaltools.wbs+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["wbs"]
  },
  "application/vnd.cryptii.pipe+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.crypto-shade-file": {
    "source": "iana"
  },
  "application/vnd.cryptomator.encrypted": {
    "source": "iana"
  },
  "application/vnd.cryptomator.vault": {
    "source": "iana"
  },
  "application/vnd.ctc-posml": {
    "source": "iana",
    "extensions": ["pml"]
  },
  "application/vnd.ctct.ws+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.cups-pdf": {
    "source": "iana"
  },
  "application/vnd.cups-postscript": {
    "source": "iana"
  },
  "application/vnd.cups-ppd": {
    "source": "iana",
    "extensions": ["ppd"]
  },
  "application/vnd.cups-raster": {
    "source": "iana"
  },
  "application/vnd.cups-raw": {
    "source": "iana"
  },
  "application/vnd.curl": {
    "source": "iana"
  },
  "application/vnd.curl.car": {
    "source": "apache",
    "extensions": ["car"]
  },
  "application/vnd.curl.pcurl": {
    "source": "apache",
    "extensions": ["pcurl"]
  },
  "application/vnd.cyan.dean.root+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.cybank": {
    "source": "iana"
  },
  "application/vnd.cyclonedx+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.cyclonedx+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.d2l.coursepackage1p0+zip": {
    "source": "iana",
    "compressible": false
  },
  "application/vnd.d3m-dataset": {
    "source": "iana"
  },
  "application/vnd.d3m-problem": {
    "source": "iana"
  },
  "application/vnd.dart": {
    "source": "iana",
    "compressible": true,
    "extensions": ["dart"]
  },
  "application/vnd.data-vision.rdz": {
    "source": "iana",
    "extensions": ["rdz"]
  },
  "application/vnd.datapackage+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.dataresource+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.dbf": {
    "source": "iana",
    "extensions": ["dbf"]
  },
  "application/vnd.debian.binary-package": {
    "source": "iana"
  },
  "application/vnd.dece.data": {
    "source": "iana",
    "extensions": ["uvf","uvvf","uvd","uvvd"]
  },
  "application/vnd.dece.ttml+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["uvt","uvvt"]
  },
  "application/vnd.dece.unspecified": {
    "source": "iana",
    "extensions": ["uvx","uvvx"]
  },
  "application/vnd.dece.zip": {
    "source": "iana",
    "extensions": ["uvz","uvvz"]
  },
  "application/vnd.denovo.fcselayout-link": {
    "source": "iana",
    "extensions": ["fe_launch"]
  },
  "application/vnd.desmume.movie": {
    "source": "iana"
  },
  "application/vnd.dir-bi.plate-dl-nosuffix": {
    "source": "iana"
  },
  "application/vnd.dm.delegation+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.dna": {
    "source": "iana",
    "extensions": ["dna"]
  },
  "application/vnd.document+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.dolby.mlp": {
    "source": "apache",
    "extensions": ["mlp"]
  },
  "application/vnd.dolby.mobile.1": {
    "source": "iana"
  },
  "application/vnd.dolby.mobile.2": {
    "source": "iana"
  },
  "application/vnd.doremir.scorecloud-binary-document": {
    "source": "iana"
  },
  "application/vnd.dpgraph": {
    "source": "iana",
    "extensions": ["dpg"]
  },
  "application/vnd.dreamfactory": {
    "source": "iana",
    "extensions": ["dfac"]
  },
  "application/vnd.drive+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.ds-keypoint": {
    "source": "apache",
    "extensions": ["kpxx"]
  },
  "application/vnd.dtg.local": {
    "source": "iana"
  },
  "application/vnd.dtg.local.flash": {
    "source": "iana"
  },
  "application/vnd.dtg.local.html": {
    "source": "iana"
  },
  "application/vnd.dvb.ait": {
    "source": "iana",
    "extensions": ["ait"]
  },
  "application/vnd.dvb.dvbisl+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.dvb.dvbj": {
    "source": "iana"
  },
  "application/vnd.dvb.esgcontainer": {
    "source": "iana"
  },
  "application/vnd.dvb.ipdcdftnotifaccess": {
    "source": "iana"
  },
  "application/vnd.dvb.ipdcesgaccess": {
    "source": "iana"
  },
  "application/vnd.dvb.ipdcesgaccess2": {
    "source": "iana"
  },
  "application/vnd.dvb.ipdcesgpdd": {
    "source": "iana"
  },
  "application/vnd.dvb.ipdcroaming": {
    "source": "iana"
  },
  "application/vnd.dvb.iptv.alfec-base": {
    "source": "iana"
  },
  "application/vnd.dvb.iptv.alfec-enhancement": {
    "source": "iana"
  },
  "application/vnd.dvb.notif-aggregate-root+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.dvb.notif-container+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.dvb.notif-generic+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.dvb.notif-ia-msglist+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.dvb.notif-ia-registration-request+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.dvb.notif-ia-registration-response+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.dvb.notif-init+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.dvb.pfr": {
    "source": "iana"
  },
  "application/vnd.dvb.service": {
    "source": "iana",
    "extensions": ["svc"]
  },
  "application/vnd.dxr": {
    "source": "iana"
  },
  "application/vnd.dynageo": {
    "source": "iana",
    "extensions": ["geo"]
  },
  "application/vnd.dzr": {
    "source": "iana"
  },
  "application/vnd.easykaraoke.cdgdownload": {
    "source": "iana"
  },
  "application/vnd.ecdis-update": {
    "source": "iana"
  },
  "application/vnd.ecip.rlp": {
    "source": "iana"
  },
  "application/vnd.ecowin.chart": {
    "source": "iana",
    "extensions": ["mag"]
  },
  "application/vnd.ecowin.filerequest": {
    "source": "iana"
  },
  "application/vnd.ecowin.fileupdate": {
    "source": "iana"
  },
  "application/vnd.ecowin.series": {
    "source": "iana"
  },
  "application/vnd.ecowin.seriesrequest": {
    "source": "iana"
  },
  "application/vnd.ecowin.seriesupdate": {
    "source": "iana"
  },
  "application/vnd.efi.img": {
    "source": "iana"
  },
  "application/vnd.efi.iso": {
    "source": "iana"
  },
  "application/vnd.emclient.accessrequest+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.enliven": {
    "source": "iana",
    "extensions": ["nml"]
  },
  "application/vnd.enphase.envoy": {
    "source": "iana"
  },
  "application/vnd.eprints.data+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.epson.esf": {
    "source": "iana",
    "extensions": ["esf"]
  },
  "application/vnd.epson.msf": {
    "source": "iana",
    "extensions": ["msf"]
  },
  "application/vnd.epson.quickanime": {
    "source": "iana",
    "extensions": ["qam"]
  },
  "application/vnd.epson.salt": {
    "source": "iana",
    "extensions": ["slt"]
  },
  "application/vnd.epson.ssf": {
    "source": "iana",
    "extensions": ["ssf"]
  },
  "application/vnd.ericsson.quickcall": {
    "source": "iana"
  },
  "application/vnd.espass-espass+zip": {
    "source": "iana",
    "compressible": false
  },
  "application/vnd.eszigno3+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["es3","et3"]
  },
  "application/vnd.etsi.aoc+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.etsi.asic-e+zip": {
    "source": "iana",
    "compressible": false
  },
  "application/vnd.etsi.asic-s+zip": {
    "source": "iana",
    "compressible": false
  },
  "application/vnd.etsi.cug+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.etsi.iptvcommand+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.etsi.iptvdiscovery+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.etsi.iptvprofile+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.etsi.iptvsad-bc+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.etsi.iptvsad-cod+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.etsi.iptvsad-npvr+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.etsi.iptvservice+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.etsi.iptvsync+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.etsi.iptvueprofile+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.etsi.mcid+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.etsi.mheg5": {
    "source": "iana"
  },
  "application/vnd.etsi.overload-control-policy-dataset+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.etsi.pstn+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.etsi.sci+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.etsi.simservs+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.etsi.timestamp-token": {
    "source": "iana"
  },
  "application/vnd.etsi.tsl+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.etsi.tsl.der": {
    "source": "iana"
  },
  "application/vnd.eudora.data": {
    "source": "iana"
  },
  "application/vnd.evolv.ecig.profile": {
    "source": "iana"
  },
  "application/vnd.evolv.ecig.settings": {
    "source": "iana"
  },
  "application/vnd.evolv.ecig.theme": {
    "source": "iana"
  },
  "application/vnd.exstream-empower+zip": {
    "source": "iana",
    "compressible": false
  },
  "application/vnd.exstream-package": {
    "source": "iana"
  },
  "application/vnd.ezpix-album": {
    "source": "iana",
    "extensions": ["ez2"]
  },
  "application/vnd.ezpix-package": {
    "source": "iana",
    "extensions": ["ez3"]
  },
  "application/vnd.f-secure.mobile": {
    "source": "iana"
  },
  "application/vnd.fastcopy-disk-image": {
    "source": "iana"
  },
  "application/vnd.fdf": {
    "source": "iana",
    "extensions": ["fdf"]
  },
  "application/vnd.fdsn.mseed": {
    "source": "iana",
    "extensions": ["mseed"]
  },
  "application/vnd.fdsn.seed": {
    "source": "iana",
    "extensions": ["seed","dataless"]
  },
  "application/vnd.ffsns": {
    "source": "iana"
  },
  "application/vnd.ficlab.flb+zip": {
    "source": "iana",
    "compressible": false
  },
  "application/vnd.filmit.zfc": {
    "source": "iana"
  },
  "application/vnd.fints": {
    "source": "iana"
  },
  "application/vnd.firemonkeys.cloudcell": {
    "source": "iana"
  },
  "application/vnd.flographit": {
    "source": "iana",
    "extensions": ["gph"]
  },
  "application/vnd.fluxtime.clip": {
    "source": "iana",
    "extensions": ["ftc"]
  },
  "application/vnd.font-fontforge-sfd": {
    "source": "iana"
  },
  "application/vnd.framemaker": {
    "source": "iana",
    "extensions": ["fm","frame","maker","book"]
  },
  "application/vnd.frogans.fnc": {
    "source": "iana",
    "extensions": ["fnc"]
  },
  "application/vnd.frogans.ltf": {
    "source": "iana",
    "extensions": ["ltf"]
  },
  "application/vnd.fsc.weblaunch": {
    "source": "iana",
    "extensions": ["fsc"]
  },
  "application/vnd.fujifilm.fb.docuworks": {
    "source": "iana"
  },
  "application/vnd.fujifilm.fb.docuworks.binder": {
    "source": "iana"
  },
  "application/vnd.fujifilm.fb.docuworks.container": {
    "source": "iana"
  },
  "application/vnd.fujifilm.fb.jfi+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.fujitsu.oasys": {
    "source": "iana",
    "extensions": ["oas"]
  },
  "application/vnd.fujitsu.oasys2": {
    "source": "iana",
    "extensions": ["oa2"]
  },
  "application/vnd.fujitsu.oasys3": {
    "source": "iana",
    "extensions": ["oa3"]
  },
  "application/vnd.fujitsu.oasysgp": {
    "source": "iana",
    "extensions": ["fg5"]
  },
  "application/vnd.fujitsu.oasysprs": {
    "source": "iana",
    "extensions": ["bh2"]
  },
  "application/vnd.fujixerox.art-ex": {
    "source": "iana"
  },
  "application/vnd.fujixerox.art4": {
    "source": "iana"
  },
  "application/vnd.fujixerox.ddd": {
    "source": "iana",
    "extensions": ["ddd"]
  },
  "application/vnd.fujixerox.docuworks": {
    "source": "iana",
    "extensions": ["xdw"]
  },
  "application/vnd.fujixerox.docuworks.binder": {
    "source": "iana",
    "extensions": ["xbd"]
  },
  "application/vnd.fujixerox.docuworks.container": {
    "source": "iana"
  },
  "application/vnd.fujixerox.hbpl": {
    "source": "iana"
  },
  "application/vnd.fut-misnet": {
    "source": "iana"
  },
  "application/vnd.futoin+cbor": {
    "source": "iana"
  },
  "application/vnd.futoin+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.fuzzysheet": {
    "source": "iana",
    "extensions": ["fzs"]
  },
  "application/vnd.genomatix.tuxedo": {
    "source": "iana",
    "extensions": ["txd"]
  },
  "application/vnd.gentics.grd+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.geo+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.geocube+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.geogebra.file": {
    "source": "iana",
    "extensions": ["ggb"]
  },
  "application/vnd.geogebra.slides": {
    "source": "iana"
  },
  "application/vnd.geogebra.tool": {
    "source": "iana",
    "extensions": ["ggt"]
  },
  "application/vnd.geometry-explorer": {
    "source": "iana",
    "extensions": ["gex","gre"]
  },
  "application/vnd.geonext": {
    "source": "iana",
    "extensions": ["gxt"]
  },
  "application/vnd.geoplan": {
    "source": "iana",
    "extensions": ["g2w"]
  },
  "application/vnd.geospace": {
    "source": "iana",
    "extensions": ["g3w"]
  },
  "application/vnd.gerber": {
    "source": "iana"
  },
  "application/vnd.globalplatform.card-content-mgt": {
    "source": "iana"
  },
  "application/vnd.globalplatform.card-content-mgt-response": {
    "source": "iana"
  },
  "application/vnd.gmx": {
    "source": "iana",
    "extensions": ["gmx"]
  },
  "application/vnd.google-apps.document": {
    "compressible": false,
    "extensions": ["gdoc"]
  },
  "application/vnd.google-apps.presentation": {
    "compressible": false,
    "extensions": ["gslides"]
  },
  "application/vnd.google-apps.spreadsheet": {
    "compressible": false,
    "extensions": ["gsheet"]
  },
  "application/vnd.google-earth.kml+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["kml"]
  },
  "application/vnd.google-earth.kmz": {
    "source": "iana",
    "compressible": false,
    "extensions": ["kmz"]
  },
  "application/vnd.gov.sk.e-form+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.gov.sk.e-form+zip": {
    "source": "iana",
    "compressible": false
  },
  "application/vnd.gov.sk.xmldatacontainer+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.grafeq": {
    "source": "iana",
    "extensions": ["gqf","gqs"]
  },
  "application/vnd.gridmp": {
    "source": "iana"
  },
  "application/vnd.groove-account": {
    "source": "iana",
    "extensions": ["gac"]
  },
  "application/vnd.groove-help": {
    "source": "iana",
    "extensions": ["ghf"]
  },
  "application/vnd.groove-identity-message": {
    "source": "iana",
    "extensions": ["gim"]
  },
  "application/vnd.groove-injector": {
    "source": "iana",
    "extensions": ["grv"]
  },
  "application/vnd.groove-tool-message": {
    "source": "iana",
    "extensions": ["gtm"]
  },
  "application/vnd.groove-tool-template": {
    "source": "iana",
    "extensions": ["tpl"]
  },
  "application/vnd.groove-vcard": {
    "source": "iana",
    "extensions": ["vcg"]
  },
  "application/vnd.hal+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.hal+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["hal"]
  },
  "application/vnd.handheld-entertainment+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["zmm"]
  },
  "application/vnd.hbci": {
    "source": "iana",
    "extensions": ["hbci"]
  },
  "application/vnd.hc+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.hcl-bireports": {
    "source": "iana"
  },
  "application/vnd.hdt": {
    "source": "iana"
  },
  "application/vnd.heroku+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.hhe.lesson-player": {
    "source": "iana",
    "extensions": ["les"]
  },
  "application/vnd.hp-hpgl": {
    "source": "iana",
    "extensions": ["hpgl"]
  },
  "application/vnd.hp-hpid": {
    "source": "iana",
    "extensions": ["hpid"]
  },
  "application/vnd.hp-hps": {
    "source": "iana",
    "extensions": ["hps"]
  },
  "application/vnd.hp-jlyt": {
    "source": "iana",
    "extensions": ["jlt"]
  },
  "application/vnd.hp-pcl": {
    "source": "iana",
    "extensions": ["pcl"]
  },
  "application/vnd.hp-pclxl": {
    "source": "iana",
    "extensions": ["pclxl"]
  },
  "application/vnd.httphone": {
    "source": "iana"
  },
  "application/vnd.hydrostatix.sof-data": {
    "source": "iana",
    "extensions": ["sfd-hdstx"]
  },
  "application/vnd.hyper+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.hyper-item+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.hyperdrive+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.hzn-3d-crossword": {
    "source": "iana"
  },
  "application/vnd.ibm.afplinedata": {
    "source": "iana"
  },
  "application/vnd.ibm.electronic-media": {
    "source": "iana"
  },
  "application/vnd.ibm.minipay": {
    "source": "iana",
    "extensions": ["mpy"]
  },
  "application/vnd.ibm.modcap": {
    "source": "iana",
    "extensions": ["afp","listafp","list3820"]
  },
  "application/vnd.ibm.rights-management": {
    "source": "iana",
    "extensions": ["irm"]
  },
  "application/vnd.ibm.secure-container": {
    "source": "iana",
    "extensions": ["sc"]
  },
  "application/vnd.iccprofile": {
    "source": "iana",
    "extensions": ["icc","icm"]
  },
  "application/vnd.ieee.1905": {
    "source": "iana"
  },
  "application/vnd.igloader": {
    "source": "iana",
    "extensions": ["igl"]
  },
  "application/vnd.imagemeter.folder+zip": {
    "source": "iana",
    "compressible": false
  },
  "application/vnd.imagemeter.image+zip": {
    "source": "iana",
    "compressible": false
  },
  "application/vnd.immervision-ivp": {
    "source": "iana",
    "extensions": ["ivp"]
  },
  "application/vnd.immervision-ivu": {
    "source": "iana",
    "extensions": ["ivu"]
  },
  "application/vnd.ims.imsccv1p1": {
    "source": "iana"
  },
  "application/vnd.ims.imsccv1p2": {
    "source": "iana"
  },
  "application/vnd.ims.imsccv1p3": {
    "source": "iana"
  },
  "application/vnd.ims.lis.v2.result+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.ims.lti.v2.toolconsumerprofile+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.ims.lti.v2.toolproxy+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.ims.lti.v2.toolproxy.id+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.ims.lti.v2.toolsettings+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.ims.lti.v2.toolsettings.simple+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.informedcontrol.rms+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.informix-visionary": {
    "source": "iana"
  },
  "application/vnd.infotech.project": {
    "source": "iana"
  },
  "application/vnd.infotech.project+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.innopath.wamp.notification": {
    "source": "iana"
  },
  "application/vnd.insors.igm": {
    "source": "iana",
    "extensions": ["igm"]
  },
  "application/vnd.intercon.formnet": {
    "source": "iana",
    "extensions": ["xpw","xpx"]
  },
  "application/vnd.intergeo": {
    "source": "iana",
    "extensions": ["i2g"]
  },
  "application/vnd.intertrust.digibox": {
    "source": "iana"
  },
  "application/vnd.intertrust.nncp": {
    "source": "iana"
  },
  "application/vnd.intu.qbo": {
    "source": "iana",
    "extensions": ["qbo"]
  },
  "application/vnd.intu.qfx": {
    "source": "iana",
    "extensions": ["qfx"]
  },
  "application/vnd.iptc.g2.catalogitem+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.iptc.g2.conceptitem+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.iptc.g2.knowledgeitem+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.iptc.g2.newsitem+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.iptc.g2.newsmessage+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.iptc.g2.packageitem+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.iptc.g2.planningitem+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.ipunplugged.rcprofile": {
    "source": "iana",
    "extensions": ["rcprofile"]
  },
  "application/vnd.irepository.package+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["irp"]
  },
  "application/vnd.is-xpr": {
    "source": "iana",
    "extensions": ["xpr"]
  },
  "application/vnd.isac.fcs": {
    "source": "iana",
    "extensions": ["fcs"]
  },
  "application/vnd.iso11783-10+zip": {
    "source": "iana",
    "compressible": false
  },
  "application/vnd.jam": {
    "source": "iana",
    "extensions": ["jam"]
  },
  "application/vnd.japannet-directory-service": {
    "source": "iana"
  },
  "application/vnd.japannet-jpnstore-wakeup": {
    "source": "iana"
  },
  "application/vnd.japannet-payment-wakeup": {
    "source": "iana"
  },
  "application/vnd.japannet-registration": {
    "source": "iana"
  },
  "application/vnd.japannet-registration-wakeup": {
    "source": "iana"
  },
  "application/vnd.japannet-setstore-wakeup": {
    "source": "iana"
  },
  "application/vnd.japannet-verification": {
    "source": "iana"
  },
  "application/vnd.japannet-verification-wakeup": {
    "source": "iana"
  },
  "application/vnd.jcp.javame.midlet-rms": {
    "source": "iana",
    "extensions": ["rms"]
  },
  "application/vnd.jisp": {
    "source": "iana",
    "extensions": ["jisp"]
  },
  "application/vnd.joost.joda-archive": {
    "source": "iana",
    "extensions": ["joda"]
  },
  "application/vnd.jsk.isdn-ngn": {
    "source": "iana"
  },
  "application/vnd.kahootz": {
    "source": "iana",
    "extensions": ["ktz","ktr"]
  },
  "application/vnd.kde.karbon": {
    "source": "iana",
    "extensions": ["karbon"]
  },
  "application/vnd.kde.kchart": {
    "source": "iana",
    "extensions": ["chrt"]
  },
  "application/vnd.kde.kformula": {
    "source": "iana",
    "extensions": ["kfo"]
  },
  "application/vnd.kde.kivio": {
    "source": "iana",
    "extensions": ["flw"]
  },
  "application/vnd.kde.kontour": {
    "source": "iana",
    "extensions": ["kon"]
  },
  "application/vnd.kde.kpresenter": {
    "source": "iana",
    "extensions": ["kpr","kpt"]
  },
  "application/vnd.kde.kspread": {
    "source": "iana",
    "extensions": ["ksp"]
  },
  "application/vnd.kde.kword": {
    "source": "iana",
    "extensions": ["kwd","kwt"]
  },
  "application/vnd.kenameaapp": {
    "source": "iana",
    "extensions": ["htke"]
  },
  "application/vnd.kidspiration": {
    "source": "iana",
    "extensions": ["kia"]
  },
  "application/vnd.kinar": {
    "source": "iana",
    "extensions": ["kne","knp"]
  },
  "application/vnd.koan": {
    "source": "iana",
    "extensions": ["skp","skd","skt","skm"]
  },
  "application/vnd.kodak-descriptor": {
    "source": "iana",
    "extensions": ["sse"]
  },
  "application/vnd.las": {
    "source": "iana"
  },
  "application/vnd.las.las+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.las.las+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["lasxml"]
  },
  "application/vnd.laszip": {
    "source": "iana"
  },
  "application/vnd.leap+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.liberty-request+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.llamagraphics.life-balance.desktop": {
    "source": "iana",
    "extensions": ["lbd"]
  },
  "application/vnd.llamagraphics.life-balance.exchange+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["lbe"]
  },
  "application/vnd.logipipe.circuit+zip": {
    "source": "iana",
    "compressible": false
  },
  "application/vnd.loom": {
    "source": "iana"
  },
  "application/vnd.lotus-1-2-3": {
    "source": "iana",
    "extensions": ["123"]
  },
  "application/vnd.lotus-approach": {
    "source": "iana",
    "extensions": ["apr"]
  },
  "application/vnd.lotus-freelance": {
    "source": "iana",
    "extensions": ["pre"]
  },
  "application/vnd.lotus-notes": {
    "source": "iana",
    "extensions": ["nsf"]
  },
  "application/vnd.lotus-organizer": {
    "source": "iana",
    "extensions": ["org"]
  },
  "application/vnd.lotus-screencam": {
    "source": "iana",
    "extensions": ["scm"]
  },
  "application/vnd.lotus-wordpro": {
    "source": "iana",
    "extensions": ["lwp"]
  },
  "application/vnd.macports.portpkg": {
    "source": "iana",
    "extensions": ["portpkg"]
  },
  "application/vnd.mapbox-vector-tile": {
    "source": "iana",
    "extensions": ["mvt"]
  },
  "application/vnd.marlin.drm.actiontoken+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.marlin.drm.conftoken+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.marlin.drm.license+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.marlin.drm.mdcf": {
    "source": "iana"
  },
  "application/vnd.mason+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.maxmind.maxmind-db": {
    "source": "iana"
  },
  "application/vnd.mcd": {
    "source": "iana",
    "extensions": ["mcd"]
  },
  "application/vnd.medcalcdata": {
    "source": "iana",
    "extensions": ["mc1"]
  },
  "application/vnd.mediastation.cdkey": {
    "source": "iana",
    "extensions": ["cdkey"]
  },
  "application/vnd.meridian-slingshot": {
    "source": "iana"
  },
  "application/vnd.mfer": {
    "source": "iana",
    "extensions": ["mwf"]
  },
  "application/vnd.mfmp": {
    "source": "iana",
    "extensions": ["mfm"]
  },
  "application/vnd.micro+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.micrografx.flo": {
    "source": "iana",
    "extensions": ["flo"]
  },
  "application/vnd.micrografx.igx": {
    "source": "iana",
    "extensions": ["igx"]
  },
  "application/vnd.microsoft.portable-executable": {
    "source": "iana"
  },
  "application/vnd.microsoft.windows.thumbnail-cache": {
    "source": "iana"
  },
  "application/vnd.miele+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.mif": {
    "source": "iana",
    "extensions": ["mif"]
  },
  "application/vnd.minisoft-hp3000-save": {
    "source": "iana"
  },
  "application/vnd.mitsubishi.misty-guard.trustweb": {
    "source": "iana"
  },
  "application/vnd.mobius.daf": {
    "source": "iana",
    "extensions": ["daf"]
  },
  "application/vnd.mobius.dis": {
    "source": "iana",
    "extensions": ["dis"]
  },
  "application/vnd.mobius.mbk": {
    "source": "iana",
    "extensions": ["mbk"]
  },
  "application/vnd.mobius.mqy": {
    "source": "iana",
    "extensions": ["mqy"]
  },
  "application/vnd.mobius.msl": {
    "source": "iana",
    "extensions": ["msl"]
  },
  "application/vnd.mobius.plc": {
    "source": "iana",
    "extensions": ["plc"]
  },
  "application/vnd.mobius.txf": {
    "source": "iana",
    "extensions": ["txf"]
  },
  "application/vnd.mophun.application": {
    "source": "iana",
    "extensions": ["mpn"]
  },
  "application/vnd.mophun.certificate": {
    "source": "iana",
    "extensions": ["mpc"]
  },
  "application/vnd.motorola.flexsuite": {
    "source": "iana"
  },
  "application/vnd.motorola.flexsuite.adsi": {
    "source": "iana"
  },
  "application/vnd.motorola.flexsuite.fis": {
    "source": "iana"
  },
  "application/vnd.motorola.flexsuite.gotap": {
    "source": "iana"
  },
  "application/vnd.motorola.flexsuite.kmr": {
    "source": "iana"
  },
  "application/vnd.motorola.flexsuite.ttc": {
    "source": "iana"
  },
  "application/vnd.motorola.flexsuite.wem": {
    "source": "iana"
  },
  "application/vnd.motorola.iprm": {
    "source": "iana"
  },
  "application/vnd.mozilla.xul+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["xul"]
  },
  "application/vnd.ms-3mfdocument": {
    "source": "iana"
  },
  "application/vnd.ms-artgalry": {
    "source": "iana",
    "extensions": ["cil"]
  },
  "application/vnd.ms-asf": {
    "source": "iana"
  },
  "application/vnd.ms-cab-compressed": {
    "source": "iana",
    "extensions": ["cab"]
  },
  "application/vnd.ms-color.iccprofile": {
    "source": "apache"
  },
  "application/vnd.ms-excel": {
    "source": "iana",
    "compressible": false,
    "extensions": ["xls","xlm","xla","xlc","xlt","xlw"]
  },
  "application/vnd.ms-excel.addin.macroenabled.12": {
    "source": "iana",
    "extensions": ["xlam"]
  },
  "application/vnd.ms-excel.sheet.binary.macroenabled.12": {
    "source": "iana",
    "extensions": ["xlsb"]
  },
  "application/vnd.ms-excel.sheet.macroenabled.12": {
    "source": "iana",
    "extensions": ["xlsm"]
  },
  "application/vnd.ms-excel.template.macroenabled.12": {
    "source": "iana",
    "extensions": ["xltm"]
  },
  "application/vnd.ms-fontobject": {
    "source": "iana",
    "compressible": true,
    "extensions": ["eot"]
  },
  "application/vnd.ms-htmlhelp": {
    "source": "iana",
    "extensions": ["chm"]
  },
  "application/vnd.ms-ims": {
    "source": "iana",
    "extensions": ["ims"]
  },
  "application/vnd.ms-lrm": {
    "source": "iana",
    "extensions": ["lrm"]
  },
  "application/vnd.ms-office.activex+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.ms-officetheme": {
    "source": "iana",
    "extensions": ["thmx"]
  },
  "application/vnd.ms-opentype": {
    "source": "apache",
    "compressible": true
  },
  "application/vnd.ms-outlook": {
    "compressible": false,
    "extensions": ["msg"]
  },
  "application/vnd.ms-package.obfuscated-opentype": {
    "source": "apache"
  },
  "application/vnd.ms-pki.seccat": {
    "source": "apache",
    "extensions": ["cat"]
  },
  "application/vnd.ms-pki.stl": {
    "source": "apache",
    "extensions": ["stl"]
  },
  "application/vnd.ms-playready.initiator+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.ms-powerpoint": {
    "source": "iana",
    "compressible": false,
    "extensions": ["ppt","pps","pot"]
  },
  "application/vnd.ms-powerpoint.addin.macroenabled.12": {
    "source": "iana",
    "extensions": ["ppam"]
  },
  "application/vnd.ms-powerpoint.presentation.macroenabled.12": {
    "source": "iana",
    "extensions": ["pptm"]
  },
  "application/vnd.ms-powerpoint.slide.macroenabled.12": {
    "source": "iana",
    "extensions": ["sldm"]
  },
  "application/vnd.ms-powerpoint.slideshow.macroenabled.12": {
    "source": "iana",
    "extensions": ["ppsm"]
  },
  "application/vnd.ms-powerpoint.template.macroenabled.12": {
    "source": "iana",
    "extensions": ["potm"]
  },
  "application/vnd.ms-printdevicecapabilities+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.ms-printing.printticket+xml": {
    "source": "apache",
    "compressible": true
  },
  "application/vnd.ms-printschematicket+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.ms-project": {
    "source": "iana",
    "extensions": ["mpp","mpt"]
  },
  "application/vnd.ms-tnef": {
    "source": "iana"
  },
  "application/vnd.ms-windows.devicepairing": {
    "source": "iana"
  },
  "application/vnd.ms-windows.nwprinting.oob": {
    "source": "iana"
  },
  "application/vnd.ms-windows.printerpairing": {
    "source": "iana"
  },
  "application/vnd.ms-windows.wsd.oob": {
    "source": "iana"
  },
  "application/vnd.ms-wmdrm.lic-chlg-req": {
    "source": "iana"
  },
  "application/vnd.ms-wmdrm.lic-resp": {
    "source": "iana"
  },
  "application/vnd.ms-wmdrm.meter-chlg-req": {
    "source": "iana"
  },
  "application/vnd.ms-wmdrm.meter-resp": {
    "source": "iana"
  },
  "application/vnd.ms-word.document.macroenabled.12": {
    "source": "iana",
    "extensions": ["docm"]
  },
  "application/vnd.ms-word.template.macroenabled.12": {
    "source": "iana",
    "extensions": ["dotm"]
  },
  "application/vnd.ms-works": {
    "source": "iana",
    "extensions": ["wps","wks","wcm","wdb"]
  },
  "application/vnd.ms-wpl": {
    "source": "iana",
    "extensions": ["wpl"]
  },
  "application/vnd.ms-xpsdocument": {
    "source": "iana",
    "compressible": false,
    "extensions": ["xps"]
  },
  "application/vnd.msa-disk-image": {
    "source": "iana"
  },
  "application/vnd.mseq": {
    "source": "iana",
    "extensions": ["mseq"]
  },
  "application/vnd.msign": {
    "source": "iana"
  },
  "application/vnd.multiad.creator": {
    "source": "iana"
  },
  "application/vnd.multiad.creator.cif": {
    "source": "iana"
  },
  "application/vnd.music-niff": {
    "source": "iana"
  },
  "application/vnd.musician": {
    "source": "iana",
    "extensions": ["mus"]
  },
  "application/vnd.muvee.style": {
    "source": "iana",
    "extensions": ["msty"]
  },
  "application/vnd.mynfc": {
    "source": "iana",
    "extensions": ["taglet"]
  },
  "application/vnd.ncd.control": {
    "source": "iana"
  },
  "application/vnd.ncd.reference": {
    "source": "iana"
  },
  "application/vnd.nearst.inv+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.nebumind.line": {
    "source": "iana"
  },
  "application/vnd.nervana": {
    "source": "iana"
  },
  "application/vnd.netfpx": {
    "source": "iana"
  },
  "application/vnd.neurolanguage.nlu": {
    "source": "iana",
    "extensions": ["nlu"]
  },
  "application/vnd.nimn": {
    "source": "iana"
  },
  "application/vnd.nintendo.nitro.rom": {
    "source": "iana"
  },
  "application/vnd.nintendo.snes.rom": {
    "source": "iana"
  },
  "application/vnd.nitf": {
    "source": "iana",
    "extensions": ["ntf","nitf"]
  },
  "application/vnd.noblenet-directory": {
    "source": "iana",
    "extensions": ["nnd"]
  },
  "application/vnd.noblenet-sealer": {
    "source": "iana",
    "extensions": ["nns"]
  },
  "application/vnd.noblenet-web": {
    "source": "iana",
    "extensions": ["nnw"]
  },
  "application/vnd.nokia.catalogs": {
    "source": "iana"
  },
  "application/vnd.nokia.conml+wbxml": {
    "source": "iana"
  },
  "application/vnd.nokia.conml+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.nokia.iptv.config+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.nokia.isds-radio-presets": {
    "source": "iana"
  },
  "application/vnd.nokia.landmark+wbxml": {
    "source": "iana"
  },
  "application/vnd.nokia.landmark+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.nokia.landmarkcollection+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.nokia.n-gage.ac+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["ac"]
  },
  "application/vnd.nokia.n-gage.data": {
    "source": "iana",
    "extensions": ["ngdat"]
  },
  "application/vnd.nokia.n-gage.symbian.install": {
    "source": "iana",
    "extensions": ["n-gage"]
  },
  "application/vnd.nokia.ncd": {
    "source": "iana"
  },
  "application/vnd.nokia.pcd+wbxml": {
    "source": "iana"
  },
  "application/vnd.nokia.pcd+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.nokia.radio-preset": {
    "source": "iana",
    "extensions": ["rpst"]
  },
  "application/vnd.nokia.radio-presets": {
    "source": "iana",
    "extensions": ["rpss"]
  },
  "application/vnd.novadigm.edm": {
    "source": "iana",
    "extensions": ["edm"]
  },
  "application/vnd.novadigm.edx": {
    "source": "iana",
    "extensions": ["edx"]
  },
  "application/vnd.novadigm.ext": {
    "source": "iana",
    "extensions": ["ext"]
  },
  "application/vnd.ntt-local.content-share": {
    "source": "iana"
  },
  "application/vnd.ntt-local.file-transfer": {
    "source": "iana"
  },
  "application/vnd.ntt-local.ogw_remote-access": {
    "source": "iana"
  },
  "application/vnd.ntt-local.sip-ta_remote": {
    "source": "iana"
  },
  "application/vnd.ntt-local.sip-ta_tcp_stream": {
    "source": "iana"
  },
  "application/vnd.oasis.opendocument.chart": {
    "source": "iana",
    "extensions": ["odc"]
  },
  "application/vnd.oasis.opendocument.chart-template": {
    "source": "iana",
    "extensions": ["otc"]
  },
  "application/vnd.oasis.opendocument.database": {
    "source": "iana",
    "extensions": ["odb"]
  },
  "application/vnd.oasis.opendocument.formula": {
    "source": "iana",
    "extensions": ["odf"]
  },
  "application/vnd.oasis.opendocument.formula-template": {
    "source": "iana",
    "extensions": ["odft"]
  },
  "application/vnd.oasis.opendocument.graphics": {
    "source": "iana",
    "compressible": false,
    "extensions": ["odg"]
  },
  "application/vnd.oasis.opendocument.graphics-template": {
    "source": "iana",
    "extensions": ["otg"]
  },
  "application/vnd.oasis.opendocument.image": {
    "source": "iana",
    "extensions": ["odi"]
  },
  "application/vnd.oasis.opendocument.image-template": {
    "source": "iana",
    "extensions": ["oti"]
  },
  "application/vnd.oasis.opendocument.presentation": {
    "source": "iana",
    "compressible": false,
    "extensions": ["odp"]
  },
  "application/vnd.oasis.opendocument.presentation-template": {
    "source": "iana",
    "extensions": ["otp"]
  },
  "application/vnd.oasis.opendocument.spreadsheet": {
    "source": "iana",
    "compressible": false,
    "extensions": ["ods"]
  },
  "application/vnd.oasis.opendocument.spreadsheet-template": {
    "source": "iana",
    "extensions": ["ots"]
  },
  "application/vnd.oasis.opendocument.text": {
    "source": "iana",
    "compressible": false,
    "extensions": ["odt"]
  },
  "application/vnd.oasis.opendocument.text-master": {
    "source": "iana",
    "extensions": ["odm"]
  },
  "application/vnd.oasis.opendocument.text-template": {
    "source": "iana",
    "extensions": ["ott"]
  },
  "application/vnd.oasis.opendocument.text-web": {
    "source": "iana",
    "extensions": ["oth"]
  },
  "application/vnd.obn": {
    "source": "iana"
  },
  "application/vnd.ocf+cbor": {
    "source": "iana"
  },
  "application/vnd.oci.image.manifest.v1+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oftn.l10n+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oipf.contentaccessdownload+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oipf.contentaccessstreaming+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oipf.cspg-hexbinary": {
    "source": "iana"
  },
  "application/vnd.oipf.dae.svg+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oipf.dae.xhtml+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oipf.mippvcontrolmessage+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oipf.pae.gem": {
    "source": "iana"
  },
  "application/vnd.oipf.spdiscovery+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oipf.spdlist+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oipf.ueprofile+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oipf.userprofile+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.olpc-sugar": {
    "source": "iana",
    "extensions": ["xo"]
  },
  "application/vnd.oma-scws-config": {
    "source": "iana"
  },
  "application/vnd.oma-scws-http-request": {
    "source": "iana"
  },
  "application/vnd.oma-scws-http-response": {
    "source": "iana"
  },
  "application/vnd.oma.bcast.associated-procedure-parameter+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oma.bcast.drm-trigger+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oma.bcast.imd+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oma.bcast.ltkm": {
    "source": "iana"
  },
  "application/vnd.oma.bcast.notification+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oma.bcast.provisioningtrigger": {
    "source": "iana"
  },
  "application/vnd.oma.bcast.sgboot": {
    "source": "iana"
  },
  "application/vnd.oma.bcast.sgdd+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oma.bcast.sgdu": {
    "source": "iana"
  },
  "application/vnd.oma.bcast.simple-symbol-container": {
    "source": "iana"
  },
  "application/vnd.oma.bcast.smartcard-trigger+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oma.bcast.sprov+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oma.bcast.stkm": {
    "source": "iana"
  },
  "application/vnd.oma.cab-address-book+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oma.cab-feature-handler+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oma.cab-pcc+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oma.cab-subs-invite+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oma.cab-user-prefs+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oma.dcd": {
    "source": "iana"
  },
  "application/vnd.oma.dcdc": {
    "source": "iana"
  },
  "application/vnd.oma.dd2+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["dd2"]
  },
  "application/vnd.oma.drm.risd+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oma.group-usage-list+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oma.lwm2m+cbor": {
    "source": "iana"
  },
  "application/vnd.oma.lwm2m+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oma.lwm2m+tlv": {
    "source": "iana"
  },
  "application/vnd.oma.pal+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oma.poc.detailed-progress-report+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oma.poc.final-report+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oma.poc.groups+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oma.poc.invocation-descriptor+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oma.poc.optimized-progress-report+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oma.push": {
    "source": "iana"
  },
  "application/vnd.oma.scidm.messages+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oma.xcap-directory+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.omads-email+xml": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true
  },
  "application/vnd.omads-file+xml": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true
  },
  "application/vnd.omads-folder+xml": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true
  },
  "application/vnd.omaloc-supl-init": {
    "source": "iana"
  },
  "application/vnd.onepager": {
    "source": "iana"
  },
  "application/vnd.onepagertamp": {
    "source": "iana"
  },
  "application/vnd.onepagertamx": {
    "source": "iana"
  },
  "application/vnd.onepagertat": {
    "source": "iana"
  },
  "application/vnd.onepagertatp": {
    "source": "iana"
  },
  "application/vnd.onepagertatx": {
    "source": "iana"
  },
  "application/vnd.openblox.game+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["obgx"]
  },
  "application/vnd.openblox.game-binary": {
    "source": "iana"
  },
  "application/vnd.openeye.oeb": {
    "source": "iana"
  },
  "application/vnd.openofficeorg.extension": {
    "source": "apache",
    "extensions": ["oxt"]
  },
  "application/vnd.openstreetmap.data+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["osm"]
  },
  "application/vnd.opentimestamps.ots": {
    "source": "iana"
  },
  "application/vnd.openxmlformats-officedocument.custom-properties+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.drawing+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.extended-properties+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.presentationml.presentation": {
    "source": "iana",
    "compressible": false,
    "extensions": ["pptx"]
  },
  "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.presentationml.slide": {
    "source": "iana",
    "extensions": ["sldx"]
  },
  "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.presentationml.slideshow": {
    "source": "iana",
    "extensions": ["ppsx"]
  },
  "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.presentationml.template": {
    "source": "iana",
    "extensions": ["potx"]
  },
  "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": {
    "source": "iana",
    "compressible": false,
    "extensions": ["xlsx"]
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.template": {
    "source": "iana",
    "extensions": ["xltx"]
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.theme+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.themeoverride+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.vmldrawing": {
    "source": "iana"
  },
  "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.wordprocessingml.document": {
    "source": "iana",
    "compressible": false,
    "extensions": ["docx"]
  },
  "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.wordprocessingml.template": {
    "source": "iana",
    "extensions": ["dotx"]
  },
  "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-package.core-properties+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-package.relationships+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oracle.resource+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.orange.indata": {
    "source": "iana"
  },
  "application/vnd.osa.netdeploy": {
    "source": "iana"
  },
  "application/vnd.osgeo.mapguide.package": {
    "source": "iana",
    "extensions": ["mgp"]
  },
  "application/vnd.osgi.bundle": {
    "source": "iana"
  },
  "application/vnd.osgi.dp": {
    "source": "iana",
    "extensions": ["dp"]
  },
  "application/vnd.osgi.subsystem": {
    "source": "iana",
    "extensions": ["esa"]
  },
  "application/vnd.otps.ct-kip+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oxli.countgraph": {
    "source": "iana"
  },
  "application/vnd.pagerduty+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.palm": {
    "source": "iana",
    "extensions": ["pdb","pqa","oprc"]
  },
  "application/vnd.panoply": {
    "source": "iana"
  },
  "application/vnd.paos.xml": {
    "source": "iana"
  },
  "application/vnd.patentdive": {
    "source": "iana"
  },
  "application/vnd.patientecommsdoc": {
    "source": "iana"
  },
  "application/vnd.pawaafile": {
    "source": "iana",
    "extensions": ["paw"]
  },
  "application/vnd.pcos": {
    "source": "iana"
  },
  "application/vnd.pg.format": {
    "source": "iana",
    "extensions": ["str"]
  },
  "application/vnd.pg.osasli": {
    "source": "iana",
    "extensions": ["ei6"]
  },
  "application/vnd.piaccess.application-licence": {
    "source": "iana"
  },
  "application/vnd.picsel": {
    "source": "iana",
    "extensions": ["efif"]
  },
  "application/vnd.pmi.widget": {
    "source": "iana",
    "extensions": ["wg"]
  },
  "application/vnd.poc.group-advertisement+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.pocketlearn": {
    "source": "iana",
    "extensions": ["plf"]
  },
  "application/vnd.powerbuilder6": {
    "source": "iana",
    "extensions": ["pbd"]
  },
  "application/vnd.powerbuilder6-s": {
    "source": "iana"
  },
  "application/vnd.powerbuilder7": {
    "source": "iana"
  },
  "application/vnd.powerbuilder7-s": {
    "source": "iana"
  },
  "application/vnd.powerbuilder75": {
    "source": "iana"
  },
  "application/vnd.powerbuilder75-s": {
    "source": "iana"
  },
  "application/vnd.preminet": {
    "source": "iana"
  },
  "application/vnd.previewsystems.box": {
    "source": "iana",
    "extensions": ["box"]
  },
  "application/vnd.proteus.magazine": {
    "source": "iana",
    "extensions": ["mgz"]
  },
  "application/vnd.psfs": {
    "source": "iana"
  },
  "application/vnd.publishare-delta-tree": {
    "source": "iana",
    "extensions": ["qps"]
  },
  "application/vnd.pvi.ptid1": {
    "source": "iana",
    "extensions": ["ptid"]
  },
  "application/vnd.pwg-multiplexed": {
    "source": "iana"
  },
  "application/vnd.pwg-xhtml-print+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.qualcomm.brew-app-res": {
    "source": "iana"
  },
  "application/vnd.quarantainenet": {
    "source": "iana"
  },
  "application/vnd.quark.quarkxpress": {
    "source": "iana",
    "extensions": ["qxd","qxt","qwd","qwt","qxl","qxb"]
  },
  "application/vnd.quobject-quoxdocument": {
    "source": "iana"
  },
  "application/vnd.radisys.moml+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.radisys.msml+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.radisys.msml-audit+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.radisys.msml-audit-conf+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.radisys.msml-audit-conn+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.radisys.msml-audit-dialog+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.radisys.msml-audit-stream+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.radisys.msml-conf+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.radisys.msml-dialog+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.radisys.msml-dialog-base+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.radisys.msml-dialog-fax-detect+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.radisys.msml-dialog-group+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.radisys.msml-dialog-speech+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.radisys.msml-dialog-transform+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.rainstor.data": {
    "source": "iana"
  },
  "application/vnd.rapid": {
    "source": "iana"
  },
  "application/vnd.rar": {
    "source": "iana",
    "extensions": ["rar"]
  },
  "application/vnd.realvnc.bed": {
    "source": "iana",
    "extensions": ["bed"]
  },
  "application/vnd.recordare.musicxml": {
    "source": "iana",
    "extensions": ["mxl"]
  },
  "application/vnd.recordare.musicxml+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["musicxml"]
  },
  "application/vnd.renlearn.rlprint": {
    "source": "iana"
  },
  "application/vnd.resilient.logic": {
    "source": "iana"
  },
  "application/vnd.restful+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.rig.cryptonote": {
    "source": "iana",
    "extensions": ["cryptonote"]
  },
  "application/vnd.rim.cod": {
    "source": "apache",
    "extensions": ["cod"]
  },
  "application/vnd.rn-realmedia": {
    "source": "apache",
    "extensions": ["rm"]
  },
  "application/vnd.rn-realmedia-vbr": {
    "source": "apache",
    "extensions": ["rmvb"]
  },
  "application/vnd.route66.link66+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["link66"]
  },
  "application/vnd.rs-274x": {
    "source": "iana"
  },
  "application/vnd.ruckus.download": {
    "source": "iana"
  },
  "application/vnd.s3sms": {
    "source": "iana"
  },
  "application/vnd.sailingtracker.track": {
    "source": "iana",
    "extensions": ["st"]
  },
  "application/vnd.sar": {
    "source": "iana"
  },
  "application/vnd.sbm.cid": {
    "source": "iana"
  },
  "application/vnd.sbm.mid2": {
    "source": "iana"
  },
  "application/vnd.scribus": {
    "source": "iana"
  },
  "application/vnd.sealed.3df": {
    "source": "iana"
  },
  "application/vnd.sealed.csf": {
    "source": "iana"
  },
  "application/vnd.sealed.doc": {
    "source": "iana"
  },
  "application/vnd.sealed.eml": {
    "source": "iana"
  },
  "application/vnd.sealed.mht": {
    "source": "iana"
  },
  "application/vnd.sealed.net": {
    "source": "iana"
  },
  "application/vnd.sealed.ppt": {
    "source": "iana"
  },
  "application/vnd.sealed.tiff": {
    "source": "iana"
  },
  "application/vnd.sealed.xls": {
    "source": "iana"
  },
  "application/vnd.sealedmedia.softseal.html": {
    "source": "iana"
  },
  "application/vnd.sealedmedia.softseal.pdf": {
    "source": "iana"
  },
  "application/vnd.seemail": {
    "source": "iana",
    "extensions": ["see"]
  },
  "application/vnd.seis+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.sema": {
    "source": "iana",
    "extensions": ["sema"]
  },
  "application/vnd.semd": {
    "source": "iana",
    "extensions": ["semd"]
  },
  "application/vnd.semf": {
    "source": "iana",
    "extensions": ["semf"]
  },
  "application/vnd.shade-save-file": {
    "source": "iana"
  },
  "application/vnd.shana.informed.formdata": {
    "source": "iana",
    "extensions": ["ifm"]
  },
  "application/vnd.shana.informed.formtemplate": {
    "source": "iana",
    "extensions": ["itp"]
  },
  "application/vnd.shana.informed.interchange": {
    "source": "iana",
    "extensions": ["iif"]
  },
  "application/vnd.shana.informed.package": {
    "source": "iana",
    "extensions": ["ipk"]
  },
  "application/vnd.shootproof+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.shopkick+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.shp": {
    "source": "iana"
  },
  "application/vnd.shx": {
    "source": "iana"
  },
  "application/vnd.sigrok.session": {
    "source": "iana"
  },
  "application/vnd.simtech-mindmapper": {
    "source": "iana",
    "extensions": ["twd","twds"]
  },
  "application/vnd.siren+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.smaf": {
    "source": "iana",
    "extensions": ["mmf"]
  },
  "application/vnd.smart.notebook": {
    "source": "iana"
  },
  "application/vnd.smart.teacher": {
    "source": "iana",
    "extensions": ["teacher"]
  },
  "application/vnd.snesdev-page-table": {
    "source": "iana"
  },
  "application/vnd.software602.filler.form+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["fo"]
  },
  "application/vnd.software602.filler.form-xml-zip": {
    "source": "iana"
  },
  "application/vnd.solent.sdkm+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["sdkm","sdkd"]
  },
  "application/vnd.spotfire.dxp": {
    "source": "iana",
    "extensions": ["dxp"]
  },
  "application/vnd.spotfire.sfs": {
    "source": "iana",
    "extensions": ["sfs"]
  },
  "application/vnd.sqlite3": {
    "source": "iana"
  },
  "application/vnd.sss-cod": {
    "source": "iana"
  },
  "application/vnd.sss-dtf": {
    "source": "iana"
  },
  "application/vnd.sss-ntf": {
    "source": "iana"
  },
  "application/vnd.stardivision.calc": {
    "source": "apache",
    "extensions": ["sdc"]
  },
  "application/vnd.stardivision.draw": {
    "source": "apache",
    "extensions": ["sda"]
  },
  "application/vnd.stardivision.impress": {
    "source": "apache",
    "extensions": ["sdd"]
  },
  "application/vnd.stardivision.math": {
    "source": "apache",
    "extensions": ["smf"]
  },
  "application/vnd.stardivision.writer": {
    "source": "apache",
    "extensions": ["sdw","vor"]
  },
  "application/vnd.stardivision.writer-global": {
    "source": "apache",
    "extensions": ["sgl"]
  },
  "application/vnd.stepmania.package": {
    "source": "iana",
    "extensions": ["smzip"]
  },
  "application/vnd.stepmania.stepchart": {
    "source": "iana",
    "extensions": ["sm"]
  },
  "application/vnd.street-stream": {
    "source": "iana"
  },
  "application/vnd.sun.wadl+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["wadl"]
  },
  "application/vnd.sun.xml.calc": {
    "source": "apache",
    "extensions": ["sxc"]
  },
  "application/vnd.sun.xml.calc.template": {
    "source": "apache",
    "extensions": ["stc"]
  },
  "application/vnd.sun.xml.draw": {
    "source": "apache",
    "extensions": ["sxd"]
  },
  "application/vnd.sun.xml.draw.template": {
    "source": "apache",
    "extensions": ["std"]
  },
  "application/vnd.sun.xml.impress": {
    "source": "apache",
    "extensions": ["sxi"]
  },
  "application/vnd.sun.xml.impress.template": {
    "source": "apache",
    "extensions": ["sti"]
  },
  "application/vnd.sun.xml.math": {
    "source": "apache",
    "extensions": ["sxm"]
  },
  "application/vnd.sun.xml.writer": {
    "source": "apache",
    "extensions": ["sxw"]
  },
  "application/vnd.sun.xml.writer.global": {
    "source": "apache",
    "extensions": ["sxg"]
  },
  "application/vnd.sun.xml.writer.template": {
    "source": "apache",
    "extensions": ["stw"]
  },
  "application/vnd.sus-calendar": {
    "source": "iana",
    "extensions": ["sus","susp"]
  },
  "application/vnd.svd": {
    "source": "iana",
    "extensions": ["svd"]
  },
  "application/vnd.swiftview-ics": {
    "source": "iana"
  },
  "application/vnd.sycle+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.symbian.install": {
    "source": "apache",
    "extensions": ["sis","sisx"]
  },
  "application/vnd.syncml+xml": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true,
    "extensions": ["xsm"]
  },
  "application/vnd.syncml.dm+wbxml": {
    "source": "iana",
    "charset": "UTF-8",
    "extensions": ["bdm"]
  },
  "application/vnd.syncml.dm+xml": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true,
    "extensions": ["xdm"]
  },
  "application/vnd.syncml.dm.notification": {
    "source": "iana"
  },
  "application/vnd.syncml.dmddf+wbxml": {
    "source": "iana"
  },
  "application/vnd.syncml.dmddf+xml": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true,
    "extensions": ["ddf"]
  },
  "application/vnd.syncml.dmtnds+wbxml": {
    "source": "iana"
  },
  "application/vnd.syncml.dmtnds+xml": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true
  },
  "application/vnd.syncml.ds.notification": {
    "source": "iana"
  },
  "application/vnd.tableschema+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.tao.intent-module-archive": {
    "source": "iana",
    "extensions": ["tao"]
  },
  "application/vnd.tcpdump.pcap": {
    "source": "iana",
    "extensions": ["pcap","cap","dmp"]
  },
  "application/vnd.think-cell.ppttc+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.tmd.mediaflex.api+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.tml": {
    "source": "iana"
  },
  "application/vnd.tmobile-livetv": {
    "source": "iana",
    "extensions": ["tmo"]
  },
  "application/vnd.tri.onesource": {
    "source": "iana"
  },
  "application/vnd.trid.tpt": {
    "source": "iana",
    "extensions": ["tpt"]
  },
  "application/vnd.triscape.mxs": {
    "source": "iana",
    "extensions": ["mxs"]
  },
  "application/vnd.trueapp": {
    "source": "iana",
    "extensions": ["tra"]
  },
  "application/vnd.truedoc": {
    "source": "iana"
  },
  "application/vnd.ubisoft.webplayer": {
    "source": "iana"
  },
  "application/vnd.ufdl": {
    "source": "iana",
    "extensions": ["ufd","ufdl"]
  },
  "application/vnd.uiq.theme": {
    "source": "iana",
    "extensions": ["utz"]
  },
  "application/vnd.umajin": {
    "source": "iana",
    "extensions": ["umj"]
  },
  "application/vnd.unity": {
    "source": "iana",
    "extensions": ["unityweb"]
  },
  "application/vnd.uoml+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["uoml"]
  },
  "application/vnd.uplanet.alert": {
    "source": "iana"
  },
  "application/vnd.uplanet.alert-wbxml": {
    "source": "iana"
  },
  "application/vnd.uplanet.bearer-choice": {
    "source": "iana"
  },
  "application/vnd.uplanet.bearer-choice-wbxml": {
    "source": "iana"
  },
  "application/vnd.uplanet.cacheop": {
    "source": "iana"
  },
  "application/vnd.uplanet.cacheop-wbxml": {
    "source": "iana"
  },
  "application/vnd.uplanet.channel": {
    "source": "iana"
  },
  "application/vnd.uplanet.channel-wbxml": {
    "source": "iana"
  },
  "application/vnd.uplanet.list": {
    "source": "iana"
  },
  "application/vnd.uplanet.list-wbxml": {
    "source": "iana"
  },
  "application/vnd.uplanet.listcmd": {
    "source": "iana"
  },
  "application/vnd.uplanet.listcmd-wbxml": {
    "source": "iana"
  },
  "application/vnd.uplanet.signal": {
    "source": "iana"
  },
  "application/vnd.uri-map": {
    "source": "iana"
  },
  "application/vnd.valve.source.material": {
    "source": "iana"
  },
  "application/vnd.vcx": {
    "source": "iana",
    "extensions": ["vcx"]
  },
  "application/vnd.vd-study": {
    "source": "iana"
  },
  "application/vnd.vectorworks": {
    "source": "iana"
  },
  "application/vnd.vel+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.verimatrix.vcas": {
    "source": "iana"
  },
  "application/vnd.veritone.aion+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.veryant.thin": {
    "source": "iana"
  },
  "application/vnd.ves.encrypted": {
    "source": "iana"
  },
  "application/vnd.vidsoft.vidconference": {
    "source": "iana"
  },
  "application/vnd.visio": {
    "source": "iana",
    "extensions": ["vsd","vst","vss","vsw"]
  },
  "application/vnd.visionary": {
    "source": "iana",
    "extensions": ["vis"]
  },
  "application/vnd.vividence.scriptfile": {
    "source": "iana"
  },
  "application/vnd.vsf": {
    "source": "iana",
    "extensions": ["vsf"]
  },
  "application/vnd.wap.sic": {
    "source": "iana"
  },
  "application/vnd.wap.slc": {
    "source": "iana"
  },
  "application/vnd.wap.wbxml": {
    "source": "iana",
    "charset": "UTF-8",
    "extensions": ["wbxml"]
  },
  "application/vnd.wap.wmlc": {
    "source": "iana",
    "extensions": ["wmlc"]
  },
  "application/vnd.wap.wmlscriptc": {
    "source": "iana",
    "extensions": ["wmlsc"]
  },
  "application/vnd.webturbo": {
    "source": "iana",
    "extensions": ["wtb"]
  },
  "application/vnd.wfa.dpp": {
    "source": "iana"
  },
  "application/vnd.wfa.p2p": {
    "source": "iana"
  },
  "application/vnd.wfa.wsc": {
    "source": "iana"
  },
  "application/vnd.windows.devicepairing": {
    "source": "iana"
  },
  "application/vnd.wmc": {
    "source": "iana"
  },
  "application/vnd.wmf.bootstrap": {
    "source": "iana"
  },
  "application/vnd.wolfram.mathematica": {
    "source": "iana"
  },
  "application/vnd.wolfram.mathematica.package": {
    "source": "iana"
  },
  "application/vnd.wolfram.player": {
    "source": "iana",
    "extensions": ["nbp"]
  },
  "application/vnd.wordperfect": {
    "source": "iana",
    "extensions": ["wpd"]
  },
  "application/vnd.wqd": {
    "source": "iana",
    "extensions": ["wqd"]
  },
  "application/vnd.wrq-hp3000-labelled": {
    "source": "iana"
  },
  "application/vnd.wt.stf": {
    "source": "iana",
    "extensions": ["stf"]
  },
  "application/vnd.wv.csp+wbxml": {
    "source": "iana"
  },
  "application/vnd.wv.csp+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.wv.ssp+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.xacml+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.xara": {
    "source": "iana",
    "extensions": ["xar"]
  },
  "application/vnd.xfdl": {
    "source": "iana",
    "extensions": ["xfdl"]
  },
  "application/vnd.xfdl.webform": {
    "source": "iana"
  },
  "application/vnd.xmi+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.xmpie.cpkg": {
    "source": "iana"
  },
  "application/vnd.xmpie.dpkg": {
    "source": "iana"
  },
  "application/vnd.xmpie.plan": {
    "source": "iana"
  },
  "application/vnd.xmpie.ppkg": {
    "source": "iana"
  },
  "application/vnd.xmpie.xlim": {
    "source": "iana"
  },
  "application/vnd.yamaha.hv-dic": {
    "source": "iana",
    "extensions": ["hvd"]
  },
  "application/vnd.yamaha.hv-script": {
    "source": "iana",
    "extensions": ["hvs"]
  },
  "application/vnd.yamaha.hv-voice": {
    "source": "iana",
    "extensions": ["hvp"]
  },
  "application/vnd.yamaha.openscoreformat": {
    "source": "iana",
    "extensions": ["osf"]
  },
  "application/vnd.yamaha.openscoreformat.osfpvg+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["osfpvg"]
  },
  "application/vnd.yamaha.remote-setup": {
    "source": "iana"
  },
  "application/vnd.yamaha.smaf-audio": {
    "source": "iana",
    "extensions": ["saf"]
  },
  "application/vnd.yamaha.smaf-phrase": {
    "source": "iana",
    "extensions": ["spf"]
  },
  "application/vnd.yamaha.through-ngn": {
    "source": "iana"
  },
  "application/vnd.yamaha.tunnel-udpencap": {
    "source": "iana"
  },
  "application/vnd.yaoweme": {
    "source": "iana"
  },
  "application/vnd.yellowriver-custom-menu": {
    "source": "iana",
    "extensions": ["cmp"]
  },
  "application/vnd.youtube.yt": {
    "source": "iana"
  },
  "application/vnd.zul": {
    "source": "iana",
    "extensions": ["zir","zirz"]
  },
  "application/vnd.zzazz.deck+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["zaz"]
  },
  "application/voicexml+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["vxml"]
  },
  "application/voucher-cms+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vq-rtcpxr": {
    "source": "iana"
  },
  "application/wasm": {
    "source": "iana",
    "compressible": true,
    "extensions": ["wasm"]
  },
  "application/watcherinfo+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/webpush-options+json": {
    "source": "iana",
    "compressible": true
  },
  "application/whoispp-query": {
    "source": "iana"
  },
  "application/whoispp-response": {
    "source": "iana"
  },
  "application/widget": {
    "source": "iana",
    "extensions": ["wgt"]
  },
  "application/winhlp": {
    "source": "apache",
    "extensions": ["hlp"]
  },
  "application/wita": {
    "source": "iana"
  },
  "application/wordperfect5.1": {
    "source": "iana"
  },
  "application/wsdl+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["wsdl"]
  },
  "application/wspolicy+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["wspolicy"]
  },
  "application/x-7z-compressed": {
    "source": "apache",
    "compressible": false,
    "extensions": ["7z"]
  },
  "application/x-abiword": {
    "source": "apache",
    "extensions": ["abw"]
  },
  "application/x-ace-compressed": {
    "source": "apache",
    "extensions": ["ace"]
  },
  "application/x-amf": {
    "source": "apache"
  },
  "application/x-apple-diskimage": {
    "source": "apache",
    "extensions": ["dmg"]
  },
  "application/x-arj": {
    "compressible": false,
    "extensions": ["arj"]
  },
  "application/x-authorware-bin": {
    "source": "apache",
    "extensions": ["aab","x32","u32","vox"]
  },
  "application/x-authorware-map": {
    "source": "apache",
    "extensions": ["aam"]
  },
  "application/x-authorware-seg": {
    "source": "apache",
    "extensions": ["aas"]
  },
  "application/x-bcpio": {
    "source": "apache",
    "extensions": ["bcpio"]
  },
  "application/x-bdoc": {
    "compressible": false,
    "extensions": ["bdoc"]
  },
  "application/x-bittorrent": {
    "source": "apache",
    "extensions": ["torrent"]
  },
  "application/x-blorb": {
    "source": "apache",
    "extensions": ["blb","blorb"]
  },
  "application/x-bzip": {
    "source": "apache",
    "compressible": false,
    "extensions": ["bz"]
  },
  "application/x-bzip2": {
    "source": "apache",
    "compressible": false,
    "extensions": ["bz2","boz"]
  },
  "application/x-cbr": {
    "source": "apache",
    "extensions": ["cbr","cba","cbt","cbz","cb7"]
  },
  "application/x-cdlink": {
    "source": "apache",
    "extensions": ["vcd"]
  },
  "application/x-cfs-compressed": {
    "source": "apache",
    "extensions": ["cfs"]
  },
  "application/x-chat": {
    "source": "apache",
    "extensions": ["chat"]
  },
  "application/x-chess-pgn": {
    "source": "apache",
    "extensions": ["pgn"]
  },
  "application/x-chrome-extension": {
    "extensions": ["crx"]
  },
  "application/x-cocoa": {
    "source": "nginx",
    "extensions": ["cco"]
  },
  "application/x-compress": {
    "source": "apache"
  },
  "application/x-conference": {
    "source": "apache",
    "extensions": ["nsc"]
  },
  "application/x-cpio": {
    "source": "apache",
    "extensions": ["cpio"]
  },
  "application/x-csh": {
    "source": "apache",
    "extensions": ["csh"]
  },
  "application/x-deb": {
    "compressible": false
  },
  "application/x-debian-package": {
    "source": "apache",
    "extensions": ["deb","udeb"]
  },
  "application/x-dgc-compressed": {
    "source": "apache",
    "extensions": ["dgc"]
  },
  "application/x-director": {
    "source": "apache",
    "extensions": ["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"]
  },
  "application/x-doom": {
    "source": "apache",
    "extensions": ["wad"]
  },
  "application/x-dtbncx+xml": {
    "source": "apache",
    "compressible": true,
    "extensions": ["ncx"]
  },
  "application/x-dtbook+xml": {
    "source": "apache",
    "compressible": true,
    "extensions": ["dtb"]
  },
  "application/x-dtbresource+xml": {
    "source": "apache",
    "compressible": true,
    "extensions": ["res"]
  },
  "application/x-dvi": {
    "source": "apache",
    "compressible": false,
    "extensions": ["dvi"]
  },
  "application/x-envoy": {
    "source": "apache",
    "extensions": ["evy"]
  },
  "application/x-eva": {
    "source": "apache",
    "extensions": ["eva"]
  },
  "application/x-font-bdf": {
    "source": "apache",
    "extensions": ["bdf"]
  },
  "application/x-font-dos": {
    "source": "apache"
  },
  "application/x-font-framemaker": {
    "source": "apache"
  },
  "application/x-font-ghostscript": {
    "source": "apache",
    "extensions": ["gsf"]
  },
  "application/x-font-libgrx": {
    "source": "apache"
  },
  "application/x-font-linux-psf": {
    "source": "apache",
    "extensions": ["psf"]
  },
  "application/x-font-pcf": {
    "source": "apache",
    "extensions": ["pcf"]
  },
  "application/x-font-snf": {
    "source": "apache",
    "extensions": ["snf"]
  },
  "application/x-font-speedo": {
    "source": "apache"
  },
  "application/x-font-sunos-news": {
    "source": "apache"
  },
  "application/x-font-type1": {
    "source": "apache",
    "extensions": ["pfa","pfb","pfm","afm"]
  },
  "application/x-font-vfont": {
    "source": "apache"
  },
  "application/x-freearc": {
    "source": "apache",
    "extensions": ["arc"]
  },
  "application/x-futuresplash": {
    "source": "apache",
    "extensions": ["spl"]
  },
  "application/x-gca-compressed": {
    "source": "apache",
    "extensions": ["gca"]
  },
  "application/x-glulx": {
    "source": "apache",
    "extensions": ["ulx"]
  },
  "application/x-gnumeric": {
    "source": "apache",
    "extensions": ["gnumeric"]
  },
  "application/x-gramps-xml": {
    "source": "apache",
    "extensions": ["gramps"]
  },
  "application/x-gtar": {
    "source": "apache",
    "extensions": ["gtar"]
  },
  "application/x-gzip": {
    "source": "apache"
  },
  "application/x-hdf": {
    "source": "apache",
    "extensions": ["hdf"]
  },
  "application/x-httpd-php": {
    "compressible": true,
    "extensions": ["php"]
  },
  "application/x-install-instructions": {
    "source": "apache",
    "extensions": ["install"]
  },
  "application/x-iso9660-image": {
    "source": "apache",
    "extensions": ["iso"]
  },
  "application/x-java-archive-diff": {
    "source": "nginx",
    "extensions": ["jardiff"]
  },
  "application/x-java-jnlp-file": {
    "source": "apache",
    "compressible": false,
    "extensions": ["jnlp"]
  },
  "application/x-javascript": {
    "compressible": true
  },
  "application/x-keepass2": {
    "extensions": ["kdbx"]
  },
  "application/x-latex": {
    "source": "apache",
    "compressible": false,
    "extensions": ["latex"]
  },
  "application/x-lua-bytecode": {
    "extensions": ["luac"]
  },
  "application/x-lzh-compressed": {
    "source": "apache",
    "extensions": ["lzh","lha"]
  },
  "application/x-makeself": {
    "source": "nginx",
    "extensions": ["run"]
  },
  "application/x-mie": {
    "source": "apache",
    "extensions": ["mie"]
  },
  "application/x-mobipocket-ebook": {
    "source": "apache",
    "extensions": ["prc","mobi"]
  },
  "application/x-mpegurl": {
    "compressible": false
  },
  "application/x-ms-application": {
    "source": "apache",
    "extensions": ["application"]
  },
  "application/x-ms-shortcut": {
    "source": "apache",
    "extensions": ["lnk"]
  },
  "application/x-ms-wmd": {
    "source": "apache",
    "extensions": ["wmd"]
  },
  "application/x-ms-wmz": {
    "source": "apache",
    "extensions": ["wmz"]
  },
  "application/x-ms-xbap": {
    "source": "apache",
    "extensions": ["xbap"]
  },
  "application/x-msaccess": {
    "source": "apache",
    "extensions": ["mdb"]
  },
  "application/x-msbinder": {
    "source": "apache",
    "extensions": ["obd"]
  },
  "application/x-mscardfile": {
    "source": "apache",
    "extensions": ["crd"]
  },
  "application/x-msclip": {
    "source": "apache",
    "extensions": ["clp"]
  },
  "application/x-msdos-program": {
    "extensions": ["exe"]
  },
  "application/x-msdownload": {
    "source": "apache",
    "extensions": ["exe","dll","com","bat","msi"]
  },
  "application/x-msmediaview": {
    "source": "apache",
    "extensions": ["mvb","m13","m14"]
  },
  "application/x-msmetafile": {
    "source": "apache",
    "extensions": ["wmf","wmz","emf","emz"]
  },
  "application/x-msmoney": {
    "source": "apache",
    "extensions": ["mny"]
  },
  "application/x-mspublisher": {
    "source": "apache",
    "extensions": ["pub"]
  },
  "application/x-msschedule": {
    "source": "apache",
    "extensions": ["scd"]
  },
  "application/x-msterminal": {
    "source": "apache",
    "extensions": ["trm"]
  },
  "application/x-mswrite": {
    "source": "apache",
    "extensions": ["wri"]
  },
  "application/x-netcdf": {
    "source": "apache",
    "extensions": ["nc","cdf"]
  },
  "application/x-ns-proxy-autoconfig": {
    "compressible": true,
    "extensions": ["pac"]
  },
  "application/x-nzb": {
    "source": "apache",
    "extensions": ["nzb"]
  },
  "application/x-perl": {
    "source": "nginx",
    "extensions": ["pl","pm"]
  },
  "application/x-pilot": {
    "source": "nginx",
    "extensions": ["prc","pdb"]
  },
  "application/x-pkcs12": {
    "source": "apache",
    "compressible": false,
    "extensions": ["p12","pfx"]
  },
  "application/x-pkcs7-certificates": {
    "source": "apache",
    "extensions": ["p7b","spc"]
  },
  "application/x-pkcs7-certreqresp": {
    "source": "apache",
    "extensions": ["p7r"]
  },
  "application/x-pki-message": {
    "source": "iana"
  },
  "application/x-rar-compressed": {
    "source": "apache",
    "compressible": false,
    "extensions": ["rar"]
  },
  "application/x-redhat-package-manager": {
    "source": "nginx",
    "extensions": ["rpm"]
  },
  "application/x-research-info-systems": {
    "source": "apache",
    "extensions": ["ris"]
  },
  "application/x-sea": {
    "source": "nginx",
    "extensions": ["sea"]
  },
  "application/x-sh": {
    "source": "apache",
    "compressible": true,
    "extensions": ["sh"]
  },
  "application/x-shar": {
    "source": "apache",
    "extensions": ["shar"]
  },
  "application/x-shockwave-flash": {
    "source": "apache",
    "compressible": false,
    "extensions": ["swf"]
  },
  "application/x-silverlight-app": {
    "source": "apache",
    "extensions": ["xap"]
  },
  "application/x-sql": {
    "source": "apache",
    "extensions": ["sql"]
  },
  "application/x-stuffit": {
    "source": "apache",
    "compressible": false,
    "extensions": ["sit"]
  },
  "application/x-stuffitx": {
    "source": "apache",
    "extensions": ["sitx"]
  },
  "application/x-subrip": {
    "source": "apache",
    "extensions": ["srt"]
  },
  "application/x-sv4cpio": {
    "source": "apache",
    "extensions": ["sv4cpio"]
  },
  "application/x-sv4crc": {
    "source": "apache",
    "extensions": ["sv4crc"]
  },
  "application/x-t3vm-image": {
    "source": "apache",
    "extensions": ["t3"]
  },
  "application/x-tads": {
    "source": "apache",
    "extensions": ["gam"]
  },
  "application/x-tar": {
    "source": "apache",
    "compressible": true,
    "extensions": ["tar"]
  },
  "application/x-tcl": {
    "source": "apache",
    "extensions": ["tcl","tk"]
  },
  "application/x-tex": {
    "source": "apache",
    "extensions": ["tex"]
  },
  "application/x-tex-tfm": {
    "source": "apache",
    "extensions": ["tfm"]
  },
  "application/x-texinfo": {
    "source": "apache",
    "extensions": ["texinfo","texi"]
  },
  "application/x-tgif": {
    "source": "apache",
    "extensions": ["obj"]
  },
  "application/x-ustar": {
    "source": "apache",
    "extensions": ["ustar"]
  },
  "application/x-virtualbox-hdd": {
    "compressible": true,
    "extensions": ["hdd"]
  },
  "application/x-virtualbox-ova": {
    "compressible": true,
    "extensions": ["ova"]
  },
  "application/x-virtualbox-ovf": {
    "compressible": true,
    "extensions": ["ovf"]
  },
  "application/x-virtualbox-vbox": {
    "compressible": true,
    "extensions": ["vbox"]
  },
  "application/x-virtualbox-vbox-extpack": {
    "compressible": false,
    "extensions": ["vbox-extpack"]
  },
  "application/x-virtualbox-vdi": {
    "compressible": true,
    "extensions": ["vdi"]
  },
  "application/x-virtualbox-vhd": {
    "compressible": true,
    "extensions": ["vhd"]
  },
  "application/x-virtualbox-vmdk": {
    "compressible": true,
    "extensions": ["vmdk"]
  },
  "application/x-wais-source": {
    "source": "apache",
    "extensions": ["src"]
  },
  "application/x-web-app-manifest+json": {
    "compressible": true,
    "extensions": ["webapp"]
  },
  "application/x-www-form-urlencoded": {
    "source": "iana",
    "compressible": true
  },
  "application/x-x509-ca-cert": {
    "source": "iana",
    "extensions": ["der","crt","pem"]
  },
  "application/x-x509-ca-ra-cert": {
    "source": "iana"
  },
  "application/x-x509-next-ca-cert": {
    "source": "iana"
  },
  "application/x-xfig": {
    "source": "apache",
    "extensions": ["fig"]
  },
  "application/x-xliff+xml": {
    "source": "apache",
    "compressible": true,
    "extensions": ["xlf"]
  },
  "application/x-xpinstall": {
    "source": "apache",
    "compressible": false,
    "extensions": ["xpi"]
  },
  "application/x-xz": {
    "source": "apache",
    "extensions": ["xz"]
  },
  "application/x-zmachine": {
    "source": "apache",
    "extensions": ["z1","z2","z3","z4","z5","z6","z7","z8"]
  },
  "application/x400-bp": {
    "source": "iana"
  },
  "application/xacml+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/xaml+xml": {
    "source": "apache",
    "compressible": true,
    "extensions": ["xaml"]
  },
  "application/xcap-att+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["xav"]
  },
  "application/xcap-caps+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["xca"]
  },
  "application/xcap-diff+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["xdf"]
  },
  "application/xcap-el+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["xel"]
  },
  "application/xcap-error+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/xcap-ns+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["xns"]
  },
  "application/xcon-conference-info+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/xcon-conference-info-diff+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/xenc+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["xenc"]
  },
  "application/xhtml+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["xhtml","xht"]
  },
  "application/xhtml-voice+xml": {
    "source": "apache",
    "compressible": true
  },
  "application/xliff+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["xlf"]
  },
  "application/xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["xml","xsl","xsd","rng"]
  },
  "application/xml-dtd": {
    "source": "iana",
    "compressible": true,
    "extensions": ["dtd"]
  },
  "application/xml-external-parsed-entity": {
    "source": "iana"
  },
  "application/xml-patch+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/xmpp+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/xop+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["xop"]
  },
  "application/xproc+xml": {
    "source": "apache",
    "compressible": true,
    "extensions": ["xpl"]
  },
  "application/xslt+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["xsl","xslt"]
  },
  "application/xspf+xml": {
    "source": "apache",
    "compressible": true,
    "extensions": ["xspf"]
  },
  "application/xv+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["mxml","xhvml","xvml","xvm"]
  },
  "application/yang": {
    "source": "iana",
    "extensions": ["yang"]
  },
  "application/yang-data+json": {
    "source": "iana",
    "compressible": true
  },
  "application/yang-data+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/yang-patch+json": {
    "source": "iana",
    "compressible": true
  },
  "application/yang-patch+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/yin+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["yin"]
  },
  "application/zip": {
    "source": "iana",
    "compressible": false,
    "extensions": ["zip"]
  },
  "application/zlib": {
    "source": "iana"
  },
  "application/zstd": {
    "source": "iana"
  },
  "audio/1d-interleaved-parityfec": {
    "source": "iana"
  },
  "audio/32kadpcm": {
    "source": "iana"
  },
  "audio/3gpp": {
    "source": "iana",
    "compressible": false,
    "extensions": ["3gpp"]
  },
  "audio/3gpp2": {
    "source": "iana"
  },
  "audio/aac": {
    "source": "iana"
  },
  "audio/ac3": {
    "source": "iana"
  },
  "audio/adpcm": {
    "source": "apache",
    "extensions": ["adp"]
  },
  "audio/amr": {
    "source": "iana",
    "extensions": ["amr"]
  },
  "audio/amr-wb": {
    "source": "iana"
  },
  "audio/amr-wb+": {
    "source": "iana"
  },
  "audio/aptx": {
    "source": "iana"
  },
  "audio/asc": {
    "source": "iana"
  },
  "audio/atrac-advanced-lossless": {
    "source": "iana"
  },
  "audio/atrac-x": {
    "source": "iana"
  },
  "audio/atrac3": {
    "source": "iana"
  },
  "audio/basic": {
    "source": "iana",
    "compressible": false,
    "extensions": ["au","snd"]
  },
  "audio/bv16": {
    "source": "iana"
  },
  "audio/bv32": {
    "source": "iana"
  },
  "audio/clearmode": {
    "source": "iana"
  },
  "audio/cn": {
    "source": "iana"
  },
  "audio/dat12": {
    "source": "iana"
  },
  "audio/dls": {
    "source": "iana"
  },
  "audio/dsr-es201108": {
    "source": "iana"
  },
  "audio/dsr-es202050": {
    "source": "iana"
  },
  "audio/dsr-es202211": {
    "source": "iana"
  },
  "audio/dsr-es202212": {
    "source": "iana"
  },
  "audio/dv": {
    "source": "iana"
  },
  "audio/dvi4": {
    "source": "iana"
  },
  "audio/eac3": {
    "source": "iana"
  },
  "audio/encaprtp": {
    "source": "iana"
  },
  "audio/evrc": {
    "source": "iana"
  },
  "audio/evrc-qcp": {
    "source": "iana"
  },
  "audio/evrc0": {
    "source": "iana"
  },
  "audio/evrc1": {
    "source": "iana"
  },
  "audio/evrcb": {
    "source": "iana"
  },
  "audio/evrcb0": {
    "source": "iana"
  },
  "audio/evrcb1": {
    "source": "iana"
  },
  "audio/evrcnw": {
    "source": "iana"
  },
  "audio/evrcnw0": {
    "source": "iana"
  },
  "audio/evrcnw1": {
    "source": "iana"
  },
  "audio/evrcwb": {
    "source": "iana"
  },
  "audio/evrcwb0": {
    "source": "iana"
  },
  "audio/evrcwb1": {
    "source": "iana"
  },
  "audio/evs": {
    "source": "iana"
  },
  "audio/flexfec": {
    "source": "iana"
  },
  "audio/fwdred": {
    "source": "iana"
  },
  "audio/g711-0": {
    "source": "iana"
  },
  "audio/g719": {
    "source": "iana"
  },
  "audio/g722": {
    "source": "iana"
  },
  "audio/g7221": {
    "source": "iana"
  },
  "audio/g723": {
    "source": "iana"
  },
  "audio/g726-16": {
    "source": "iana"
  },
  "audio/g726-24": {
    "source": "iana"
  },
  "audio/g726-32": {
    "source": "iana"
  },
  "audio/g726-40": {
    "source": "iana"
  },
  "audio/g728": {
    "source": "iana"
  },
  "audio/g729": {
    "source": "iana"
  },
  "audio/g7291": {
    "source": "iana"
  },
  "audio/g729d": {
    "source": "iana"
  },
  "audio/g729e": {
    "source": "iana"
  },
  "audio/gsm": {
    "source": "iana"
  },
  "audio/gsm-efr": {
    "source": "iana"
  },
  "audio/gsm-hr-08": {
    "source": "iana"
  },
  "audio/ilbc": {
    "source": "iana"
  },
  "audio/ip-mr_v2.5": {
    "source": "iana"
  },
  "audio/isac": {
    "source": "apache"
  },
  "audio/l16": {
    "source": "iana"
  },
  "audio/l20": {
    "source": "iana"
  },
  "audio/l24": {
    "source": "iana",
    "compressible": false
  },
  "audio/l8": {
    "source": "iana"
  },
  "audio/lpc": {
    "source": "iana"
  },
  "audio/melp": {
    "source": "iana"
  },
  "audio/melp1200": {
    "source": "iana"
  },
  "audio/melp2400": {
    "source": "iana"
  },
  "audio/melp600": {
    "source": "iana"
  },
  "audio/mhas": {
    "source": "iana"
  },
  "audio/midi": {
    "source": "apache",
    "extensions": ["mid","midi","kar","rmi"]
  },
  "audio/mobile-xmf": {
    "source": "iana",
    "extensions": ["mxmf"]
  },
  "audio/mp3": {
    "compressible": false,
    "extensions": ["mp3"]
  },
  "audio/mp4": {
    "source": "iana",
    "compressible": false,
    "extensions": ["m4a","mp4a"]
  },
  "audio/mp4a-latm": {
    "source": "iana"
  },
  "audio/mpa": {
    "source": "iana"
  },
  "audio/mpa-robust": {
    "source": "iana"
  },
  "audio/mpeg": {
    "source": "iana",
    "compressible": false,
    "extensions": ["mpga","mp2","mp2a","mp3","m2a","m3a"]
  },
  "audio/mpeg4-generic": {
    "source": "iana"
  },
  "audio/musepack": {
    "source": "apache"
  },
  "audio/ogg": {
    "source": "iana",
    "compressible": false,
    "extensions": ["oga","ogg","spx","opus"]
  },
  "audio/opus": {
    "source": "iana"
  },
  "audio/parityfec": {
    "source": "iana"
  },
  "audio/pcma": {
    "source": "iana"
  },
  "audio/pcma-wb": {
    "source": "iana"
  },
  "audio/pcmu": {
    "source": "iana"
  },
  "audio/pcmu-wb": {
    "source": "iana"
  },
  "audio/prs.sid": {
    "source": "iana"
  },
  "audio/qcelp": {
    "source": "iana"
  },
  "audio/raptorfec": {
    "source": "iana"
  },
  "audio/red": {
    "source": "iana"
  },
  "audio/rtp-enc-aescm128": {
    "source": "iana"
  },
  "audio/rtp-midi": {
    "source": "iana"
  },
  "audio/rtploopback": {
    "source": "iana"
  },
  "audio/rtx": {
    "source": "iana"
  },
  "audio/s3m": {
    "source": "apache",
    "extensions": ["s3m"]
  },
  "audio/scip": {
    "source": "iana"
  },
  "audio/silk": {
    "source": "apache",
    "extensions": ["sil"]
  },
  "audio/smv": {
    "source": "iana"
  },
  "audio/smv-qcp": {
    "source": "iana"
  },
  "audio/smv0": {
    "source": "iana"
  },
  "audio/sofa": {
    "source": "iana"
  },
  "audio/sp-midi": {
    "source": "iana"
  },
  "audio/speex": {
    "source": "iana"
  },
  "audio/t140c": {
    "source": "iana"
  },
  "audio/t38": {
    "source": "iana"
  },
  "audio/telephone-event": {
    "source": "iana"
  },
  "audio/tetra_acelp": {
    "source": "iana"
  },
  "audio/tetra_acelp_bb": {
    "source": "iana"
  },
  "audio/tone": {
    "source": "iana"
  },
  "audio/tsvcis": {
    "source": "iana"
  },
  "audio/uemclip": {
    "source": "iana"
  },
  "audio/ulpfec": {
    "source": "iana"
  },
  "audio/usac": {
    "source": "iana"
  },
  "audio/vdvi": {
    "source": "iana"
  },
  "audio/vmr-wb": {
    "source": "iana"
  },
  "audio/vnd.3gpp.iufp": {
    "source": "iana"
  },
  "audio/vnd.4sb": {
    "source": "iana"
  },
  "audio/vnd.audiokoz": {
    "source": "iana"
  },
  "audio/vnd.celp": {
    "source": "iana"
  },
  "audio/vnd.cisco.nse": {
    "source": "iana"
  },
  "audio/vnd.cmles.radio-events": {
    "source": "iana"
  },
  "audio/vnd.cns.anp1": {
    "source": "iana"
  },
  "audio/vnd.cns.inf1": {
    "source": "iana"
  },
  "audio/vnd.dece.audio": {
    "source": "iana",
    "extensions": ["uva","uvva"]
  },
  "audio/vnd.digital-winds": {
    "source": "iana",
    "extensions": ["eol"]
  },
  "audio/vnd.dlna.adts": {
    "source": "iana"
  },
  "audio/vnd.dolby.heaac.1": {
    "source": "iana"
  },
  "audio/vnd.dolby.heaac.2": {
    "source": "iana"
  },
  "audio/vnd.dolby.mlp": {
    "source": "iana"
  },
  "audio/vnd.dolby.mps": {
    "source": "iana"
  },
  "audio/vnd.dolby.pl2": {
    "source": "iana"
  },
  "audio/vnd.dolby.pl2x": {
    "source": "iana"
  },
  "audio/vnd.dolby.pl2z": {
    "source": "iana"
  },
  "audio/vnd.dolby.pulse.1": {
    "source": "iana"
  },
  "audio/vnd.dra": {
    "source": "iana",
    "extensions": ["dra"]
  },
  "audio/vnd.dts": {
    "source": "iana",
    "extensions": ["dts"]
  },
  "audio/vnd.dts.hd": {
    "source": "iana",
    "extensions": ["dtshd"]
  },
  "audio/vnd.dts.uhd": {
    "source": "iana"
  },
  "audio/vnd.dvb.file": {
    "source": "iana"
  },
  "audio/vnd.everad.plj": {
    "source": "iana"
  },
  "audio/vnd.hns.audio": {
    "source": "iana"
  },
  "audio/vnd.lucent.voice": {
    "source": "iana",
    "extensions": ["lvp"]
  },
  "audio/vnd.ms-playready.media.pya": {
    "source": "iana",
    "extensions": ["pya"]
  },
  "audio/vnd.nokia.mobile-xmf": {
    "source": "iana"
  },
  "audio/vnd.nortel.vbk": {
    "source": "iana"
  },
  "audio/vnd.nuera.ecelp4800": {
    "source": "iana",
    "extensions": ["ecelp4800"]
  },
  "audio/vnd.nuera.ecelp7470": {
    "source": "iana",
    "extensions": ["ecelp7470"]
  },
  "audio/vnd.nuera.ecelp9600": {
    "source": "iana",
    "extensions": ["ecelp9600"]
  },
  "audio/vnd.octel.sbc": {
    "source": "iana"
  },
  "audio/vnd.presonus.multitrack": {
    "source": "iana"
  },
  "audio/vnd.qcelp": {
    "source": "iana"
  },
  "audio/vnd.rhetorex.32kadpcm": {
    "source": "iana"
  },
  "audio/vnd.rip": {
    "source": "iana",
    "extensions": ["rip"]
  },
  "audio/vnd.rn-realaudio": {
    "compressible": false
  },
  "audio/vnd.sealedmedia.softseal.mpeg": {
    "source": "iana"
  },
  "audio/vnd.vmx.cvsd": {
    "source": "iana"
  },
  "audio/vnd.wave": {
    "compressible": false
  },
  "audio/vorbis": {
    "source": "iana",
    "compressible": false
  },
  "audio/vorbis-config": {
    "source": "iana"
  },
  "audio/wav": {
    "compressible": false,
    "extensions": ["wav"]
  },
  "audio/wave": {
    "compressible": false,
    "extensions": ["wav"]
  },
  "audio/webm": {
    "source": "apache",
    "compressible": false,
    "extensions": ["weba"]
  },
  "audio/x-aac": {
    "source": "apache",
    "compressible": false,
    "extensions": ["aac"]
  },
  "audio/x-aiff": {
    "source": "apache",
    "extensions": ["aif","aiff","aifc"]
  },
  "audio/x-caf": {
    "source": "apache",
    "compressible": false,
    "extensions": ["caf"]
  },
  "audio/x-flac": {
    "source": "apache",
    "extensions": ["flac"]
  },
  "audio/x-m4a": {
    "source": "nginx",
    "extensions": ["m4a"]
  },
  "audio/x-matroska": {
    "source": "apache",
    "extensions": ["mka"]
  },
  "audio/x-mpegurl": {
    "source": "apache",
    "extensions": ["m3u"]
  },
  "audio/x-ms-wax": {
    "source": "apache",
    "extensions": ["wax"]
  },
  "audio/x-ms-wma": {
    "source": "apache",
    "extensions": ["wma"]
  },
  "audio/x-pn-realaudio": {
    "source": "apache",
    "extensions": ["ram","ra"]
  },
  "audio/x-pn-realaudio-plugin": {
    "source": "apache",
    "extensions": ["rmp"]
  },
  "audio/x-realaudio": {
    "source": "nginx",
    "extensions": ["ra"]
  },
  "audio/x-tta": {
    "source": "apache"
  },
  "audio/x-wav": {
    "source": "apache",
    "extensions": ["wav"]
  },
  "audio/xm": {
    "source": "apache",
    "extensions": ["xm"]
  },
  "chemical/x-cdx": {
    "source": "apache",
    "extensions": ["cdx"]
  },
  "chemical/x-cif": {
    "source": "apache",
    "extensions": ["cif"]
  },
  "chemical/x-cmdf": {
    "source": "apache",
    "extensions": ["cmdf"]
  },
  "chemical/x-cml": {
    "source": "apache",
    "extensions": ["cml"]
  },
  "chemical/x-csml": {
    "source": "apache",
    "extensions": ["csml"]
  },
  "chemical/x-pdb": {
    "source": "apache"
  },
  "chemical/x-xyz": {
    "source": "apache",
    "extensions": ["xyz"]
  },
  "font/collection": {
    "source": "iana",
    "extensions": ["ttc"]
  },
  "font/otf": {
    "source": "iana",
    "compressible": true,
    "extensions": ["otf"]
  },
  "font/sfnt": {
    "source": "iana"
  },
  "font/ttf": {
    "source": "iana",
    "compressible": true,
    "extensions": ["ttf"]
  },
  "font/woff": {
    "source": "iana",
    "extensions": ["woff"]
  },
  "font/woff2": {
    "source": "iana",
    "extensions": ["woff2"]
  },
  "image/aces": {
    "source": "iana",
    "extensions": ["exr"]
  },
  "image/apng": {
    "compressible": false,
    "extensions": ["apng"]
  },
  "image/avci": {
    "source": "iana"
  },
  "image/avcs": {
    "source": "iana"
  },
  "image/avif": {
    "source": "iana",
    "compressible": false,
    "extensions": ["avif"]
  },
  "image/bmp": {
    "source": "iana",
    "compressible": true,
    "extensions": ["bmp"]
  },
  "image/cgm": {
    "source": "iana",
    "extensions": ["cgm"]
  },
  "image/dicom-rle": {
    "source": "iana",
    "extensions": ["drle"]
  },
  "image/emf": {
    "source": "iana",
    "extensions": ["emf"]
  },
  "image/fits": {
    "source": "iana",
    "extensions": ["fits"]
  },
  "image/g3fax": {
    "source": "iana",
    "extensions": ["g3"]
  },
  "image/gif": {
    "source": "iana",
    "compressible": false,
    "extensions": ["gif"]
  },
  "image/heic": {
    "source": "iana",
    "extensions": ["heic"]
  },
  "image/heic-sequence": {
    "source": "iana",
    "extensions": ["heics"]
  },
  "image/heif": {
    "source": "iana",
    "extensions": ["heif"]
  },
  "image/heif-sequence": {
    "source": "iana",
    "extensions": ["heifs"]
  },
  "image/hej2k": {
    "source": "iana",
    "extensions": ["hej2"]
  },
  "image/hsj2": {
    "source": "iana",
    "extensions": ["hsj2"]
  },
  "image/ief": {
    "source": "iana",
    "extensions": ["ief"]
  },
  "image/jls": {
    "source": "iana",
    "extensions": ["jls"]
  },
  "image/jp2": {
    "source": "iana",
    "compressible": false,
    "extensions": ["jp2","jpg2"]
  },
  "image/jpeg": {
    "source": "iana",
    "compressible": false,
    "extensions": ["jpeg","jpg","jpe"]
  },
  "image/jph": {
    "source": "iana",
    "extensions": ["jph"]
  },
  "image/jphc": {
    "source": "iana",
    "extensions": ["jhc"]
  },
  "image/jpm": {
    "source": "iana",
    "compressible": false,
    "extensions": ["jpm"]
  },
  "image/jpx": {
    "source": "iana",
    "compressible": false,
    "extensions": ["jpx","jpf"]
  },
  "image/jxr": {
    "source": "iana",
    "extensions": ["jxr"]
  },
  "image/jxra": {
    "source": "iana",
    "extensions": ["jxra"]
  },
  "image/jxrs": {
    "source": "iana",
    "extensions": ["jxrs"]
  },
  "image/jxs": {
    "source": "iana",
    "extensions": ["jxs"]
  },
  "image/jxsc": {
    "source": "iana",
    "extensions": ["jxsc"]
  },
  "image/jxsi": {
    "source": "iana",
    "extensions": ["jxsi"]
  },
  "image/jxss": {
    "source": "iana",
    "extensions": ["jxss"]
  },
  "image/ktx": {
    "source": "iana",
    "extensions": ["ktx"]
  },
  "image/ktx2": {
    "source": "iana",
    "extensions": ["ktx2"]
  },
  "image/naplps": {
    "source": "iana"
  },
  "image/pjpeg": {
    "compressible": false
  },
  "image/png": {
    "source": "iana",
    "compressible": false,
    "extensions": ["png"]
  },
  "image/prs.btif": {
    "source": "iana",
    "extensions": ["btif"]
  },
  "image/prs.pti": {
    "source": "iana",
    "extensions": ["pti"]
  },
  "image/pwg-raster": {
    "source": "iana"
  },
  "image/sgi": {
    "source": "apache",
    "extensions": ["sgi"]
  },
  "image/svg+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["svg","svgz"]
  },
  "image/t38": {
    "source": "iana",
    "extensions": ["t38"]
  },
  "image/tiff": {
    "source": "iana",
    "compressible": false,
    "extensions": ["tif","tiff"]
  },
  "image/tiff-fx": {
    "source": "iana",
    "extensions": ["tfx"]
  },
  "image/vnd.adobe.photoshop": {
    "source": "iana",
    "compressible": true,
    "extensions": ["psd"]
  },
  "image/vnd.airzip.accelerator.azv": {
    "source": "iana",
    "extensions": ["azv"]
  },
  "image/vnd.cns.inf2": {
    "source": "iana"
  },
  "image/vnd.dece.graphic": {
    "source": "iana",
    "extensions": ["uvi","uvvi","uvg","uvvg"]
  },
  "image/vnd.djvu": {
    "source": "iana",
    "extensions": ["djvu","djv"]
  },
  "image/vnd.dvb.subtitle": {
    "source": "iana",
    "extensions": ["sub"]
  },
  "image/vnd.dwg": {
    "source": "iana",
    "extensions": ["dwg"]
  },
  "image/vnd.dxf": {
    "source": "iana",
    "extensions": ["dxf"]
  },
  "image/vnd.fastbidsheet": {
    "source": "iana",
    "extensions": ["fbs"]
  },
  "image/vnd.fpx": {
    "source": "iana",
    "extensions": ["fpx"]
  },
  "image/vnd.fst": {
    "source": "iana",
    "extensions": ["fst"]
  },
  "image/vnd.fujixerox.edmics-mmr": {
    "source": "iana",
    "extensions": ["mmr"]
  },
  "image/vnd.fujixerox.edmics-rlc": {
    "source": "iana",
    "extensions": ["rlc"]
  },
  "image/vnd.globalgraphics.pgb": {
    "source": "iana"
  },
  "image/vnd.microsoft.icon": {
    "source": "iana",
    "extensions": ["ico"]
  },
  "image/vnd.mix": {
    "source": "iana"
  },
  "image/vnd.mozilla.apng": {
    "source": "iana"
  },
  "image/vnd.ms-dds": {
    "extensions": ["dds"]
  },
  "image/vnd.ms-modi": {
    "source": "iana",
    "extensions": ["mdi"]
  },
  "image/vnd.ms-photo": {
    "source": "apache",
    "extensions": ["wdp"]
  },
  "image/vnd.net-fpx": {
    "source": "iana",
    "extensions": ["npx"]
  },
  "image/vnd.pco.b16": {
    "source": "iana",
    "extensions": ["b16"]
  },
  "image/vnd.radiance": {
    "source": "iana"
  },
  "image/vnd.sealed.png": {
    "source": "iana"
  },
  "image/vnd.sealedmedia.softseal.gif": {
    "source": "iana"
  },
  "image/vnd.sealedmedia.softseal.jpg": {
    "source": "iana"
  },
  "image/vnd.svf": {
    "source": "iana"
  },
  "image/vnd.tencent.tap": {
    "source": "iana",
    "extensions": ["tap"]
  },
  "image/vnd.valve.source.texture": {
    "source": "iana",
    "extensions": ["vtf"]
  },
  "image/vnd.wap.wbmp": {
    "source": "iana",
    "extensions": ["wbmp"]
  },
  "image/vnd.xiff": {
    "source": "iana",
    "extensions": ["xif"]
  },
  "image/vnd.zbrush.pcx": {
    "source": "iana",
    "extensions": ["pcx"]
  },
  "image/webp": {
    "source": "apache",
    "extensions": ["webp"]
  },
  "image/wmf": {
    "source": "iana",
    "extensions": ["wmf"]
  },
  "image/x-3ds": {
    "source": "apache",
    "extensions": ["3ds"]
  },
  "image/x-cmu-raster": {
    "source": "apache",
    "extensions": ["ras"]
  },
  "image/x-cmx": {
    "source": "apache",
    "extensions": ["cmx"]
  },
  "image/x-freehand": {
    "source": "apache",
    "extensions": ["fh","fhc","fh4","fh5","fh7"]
  },
  "image/x-icon": {
    "source": "apache",
    "compressible": true,
    "extensions": ["ico"]
  },
  "image/x-jng": {
    "source": "nginx",
    "extensions": ["jng"]
  },
  "image/x-mrsid-image": {
    "source": "apache",
    "extensions": ["sid"]
  },
  "image/x-ms-bmp": {
    "source": "nginx",
    "compressible": true,
    "extensions": ["bmp"]
  },
  "image/x-pcx": {
    "source": "apache",
    "extensions": ["pcx"]
  },
  "image/x-pict": {
    "source": "apache",
    "extensions": ["pic","pct"]
  },
  "image/x-portable-anymap": {
    "source": "apache",
    "extensions": ["pnm"]
  },
  "image/x-portable-bitmap": {
    "source": "apache",
    "extensions": ["pbm"]
  },
  "image/x-portable-graymap": {
    "source": "apache",
    "extensions": ["pgm"]
  },
  "image/x-portable-pixmap": {
    "source": "apache",
    "extensions": ["ppm"]
  },
  "image/x-rgb": {
    "source": "apache",
    "extensions": ["rgb"]
  },
  "image/x-tga": {
    "source": "apache",
    "extensions": ["tga"]
  },
  "image/x-xbitmap": {
    "source": "apache",
    "extensions": ["xbm"]
  },
  "image/x-xcf": {
    "compressible": false
  },
  "image/x-xpixmap": {
    "source": "apache",
    "extensions": ["xpm"]
  },
  "image/x-xwindowdump": {
    "source": "apache",
    "extensions": ["xwd"]
  },
  "message/cpim": {
    "source": "iana"
  },
  "message/delivery-status": {
    "source": "iana"
  },
  "message/disposition-notification": {
    "source": "iana",
    "extensions": [
      "disposition-notification"
    ]
  },
  "message/external-body": {
    "source": "iana"
  },
  "message/feedback-report": {
    "source": "iana"
  },
  "message/global": {
    "source": "iana",
    "extensions": ["u8msg"]
  },
  "message/global-delivery-status": {
    "source": "iana",
    "extensions": ["u8dsn"]
  },
  "message/global-disposition-notification": {
    "source": "iana",
    "extensions": ["u8mdn"]
  },
  "message/global-headers": {
    "source": "iana",
    "extensions": ["u8hdr"]
  },
  "message/http": {
    "source": "iana",
    "compressible": false
  },
  "message/imdn+xml": {
    "source": "iana",
    "compressible": true
  },
  "message/news": {
    "source": "iana"
  },
  "message/partial": {
    "source": "iana",
    "compressible": false
  },
  "message/rfc822": {
    "source": "iana",
    "compressible": true,
    "extensions": ["eml","mime"]
  },
  "message/s-http": {
    "source": "iana"
  },
  "message/sip": {
    "source": "iana"
  },
  "message/sipfrag": {
    "source": "iana"
  },
  "message/tracking-status": {
    "source": "iana"
  },
  "message/vnd.si.simp": {
    "source": "iana"
  },
  "message/vnd.wfa.wsc": {
    "source": "iana",
    "extensions": ["wsc"]
  },
  "model/3mf": {
    "source": "iana",
    "extensions": ["3mf"]
  },
  "model/e57": {
    "source": "iana"
  },
  "model/gltf+json": {
    "source": "iana",
    "compressible": true,
    "extensions": ["gltf"]
  },
  "model/gltf-binary": {
    "source": "iana",
    "compressible": true,
    "extensions": ["glb"]
  },
  "model/iges": {
    "source": "iana",
    "compressible": false,
    "extensions": ["igs","iges"]
  },
  "model/mesh": {
    "source": "iana",
    "compressible": false,
    "extensions": ["msh","mesh","silo"]
  },
  "model/mtl": {
    "source": "iana",
    "extensions": ["mtl"]
  },
  "model/obj": {
    "source": "iana",
    "extensions": ["obj"]
  },
  "model/step+zip": {
    "source": "iana",
    "compressible": false,
    "extensions": ["stpz"]
  },
  "model/step-xml+zip": {
    "source": "iana",
    "compressible": false,
    "extensions": ["stpxz"]
  },
  "model/stl": {
    "source": "iana",
    "extensions": ["stl"]
  },
  "model/vnd.collada+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["dae"]
  },
  "model/vnd.dwf": {
    "source": "iana",
    "extensions": ["dwf"]
  },
  "model/vnd.flatland.3dml": {
    "source": "iana"
  },
  "model/vnd.gdl": {
    "source": "iana",
    "extensions": ["gdl"]
  },
  "model/vnd.gs-gdl": {
    "source": "apache"
  },
  "model/vnd.gs.gdl": {
    "source": "iana"
  },
  "model/vnd.gtw": {
    "source": "iana",
    "extensions": ["gtw"]
  },
  "model/vnd.moml+xml": {
    "source": "iana",
    "compressible": true
  },
  "model/vnd.mts": {
    "source": "iana",
    "extensions": ["mts"]
  },
  "model/vnd.opengex": {
    "source": "iana",
    "extensions": ["ogex"]
  },
  "model/vnd.parasolid.transmit.binary": {
    "source": "iana",
    "extensions": ["x_b"]
  },
  "model/vnd.parasolid.transmit.text": {
    "source": "iana",
    "extensions": ["x_t"]
  },
  "model/vnd.pytha.pyox": {
    "source": "iana"
  },
  "model/vnd.rosette.annotated-data-model": {
    "source": "iana"
  },
  "model/vnd.sap.vds": {
    "source": "iana",
    "extensions": ["vds"]
  },
  "model/vnd.usdz+zip": {
    "source": "iana",
    "compressible": false,
    "extensions": ["usdz"]
  },
  "model/vnd.valve.source.compiled-map": {
    "source": "iana",
    "extensions": ["bsp"]
  },
  "model/vnd.vtu": {
    "source": "iana",
    "extensions": ["vtu"]
  },
  "model/vrml": {
    "source": "iana",
    "compressible": false,
    "extensions": ["wrl","vrml"]
  },
  "model/x3d+binary": {
    "source": "apache",
    "compressible": false,
    "extensions": ["x3db","x3dbz"]
  },
  "model/x3d+fastinfoset": {
    "source": "iana",
    "extensions": ["x3db"]
  },
  "model/x3d+vrml": {
    "source": "apache",
    "compressible": false,
    "extensions": ["x3dv","x3dvz"]
  },
  "model/x3d+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["x3d","x3dz"]
  },
  "model/x3d-vrml": {
    "source": "iana",
    "extensions": ["x3dv"]
  },
  "multipart/alternative": {
    "source": "iana",
    "compressible": false
  },
  "multipart/appledouble": {
    "source": "iana"
  },
  "multipart/byteranges": {
    "source": "iana"
  },
  "multipart/digest": {
    "source": "iana"
  },
  "multipart/encrypted": {
    "source": "iana",
    "compressible": false
  },
  "multipart/form-data": {
    "source": "iana",
    "compressible": false
  },
  "multipart/header-set": {
    "source": "iana"
  },
  "multipart/mixed": {
    "source": "iana"
  },
  "multipart/multilingual": {
    "source": "iana"
  },
  "multipart/parallel": {
    "source": "iana"
  },
  "multipart/related": {
    "source": "iana",
    "compressible": false
  },
  "multipart/report": {
    "source": "iana"
  },
  "multipart/signed": {
    "source": "iana",
    "compressible": false
  },
  "multipart/vnd.bint.med-plus": {
    "source": "iana"
  },
  "multipart/voice-message": {
    "source": "iana"
  },
  "multipart/x-mixed-replace": {
    "source": "iana"
  },
  "text/1d-interleaved-parityfec": {
    "source": "iana"
  },
  "text/cache-manifest": {
    "source": "iana",
    "compressible": true,
    "extensions": ["appcache","manifest"]
  },
  "text/calendar": {
    "source": "iana",
    "extensions": ["ics","ifb"]
  },
  "text/calender": {
    "compressible": true
  },
  "text/cmd": {
    "compressible": true
  },
  "text/coffeescript": {
    "extensions": ["coffee","litcoffee"]
  },
  "text/cql": {
    "source": "iana"
  },
  "text/cql-expression": {
    "source": "iana"
  },
  "text/cql-identifier": {
    "source": "iana"
  },
  "text/css": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true,
    "extensions": ["css"]
  },
  "text/csv": {
    "source": "iana",
    "compressible": true,
    "extensions": ["csv"]
  },
  "text/csv-schema": {
    "source": "iana"
  },
  "text/directory": {
    "source": "iana"
  },
  "text/dns": {
    "source": "iana"
  },
  "text/ecmascript": {
    "source": "iana"
  },
  "text/encaprtp": {
    "source": "iana"
  },
  "text/enriched": {
    "source": "iana"
  },
  "text/fhirpath": {
    "source": "iana"
  },
  "text/flexfec": {
    "source": "iana"
  },
  "text/fwdred": {
    "source": "iana"
  },
  "text/gff3": {
    "source": "iana"
  },
  "text/grammar-ref-list": {
    "source": "iana"
  },
  "text/html": {
    "source": "iana",
    "compressible": true,
    "extensions": ["html","htm","shtml"]
  },
  "text/jade": {
    "extensions": ["jade"]
  },
  "text/javascript": {
    "source": "iana",
    "compressible": true
  },
  "text/jcr-cnd": {
    "source": "iana"
  },
  "text/jsx": {
    "compressible": true,
    "extensions": ["jsx"]
  },
  "text/less": {
    "compressible": true,
    "extensions": ["less"]
  },
  "text/markdown": {
    "source": "iana",
    "compressible": true,
    "extensions": ["markdown","md"]
  },
  "text/mathml": {
    "source": "nginx",
    "extensions": ["mml"]
  },
  "text/mdx": {
    "compressible": true,
    "extensions": ["mdx"]
  },
  "text/mizar": {
    "source": "iana"
  },
  "text/n3": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true,
    "extensions": ["n3"]
  },
  "text/parameters": {
    "source": "iana",
    "charset": "UTF-8"
  },
  "text/parityfec": {
    "source": "iana"
  },
  "text/plain": {
    "source": "iana",
    "compressible": true,
    "extensions": ["txt","text","conf","def","list","log","in","ini"]
  },
  "text/provenance-notation": {
    "source": "iana",
    "charset": "UTF-8"
  },
  "text/prs.fallenstein.rst": {
    "source": "iana"
  },
  "text/prs.lines.tag": {
    "source": "iana",
    "extensions": ["dsc"]
  },
  "text/prs.prop.logic": {
    "source": "iana"
  },
  "text/raptorfec": {
    "source": "iana"
  },
  "text/red": {
    "source": "iana"
  },
  "text/rfc822-headers": {
    "source": "iana"
  },
  "text/richtext": {
    "source": "iana",
    "compressible": true,
    "extensions": ["rtx"]
  },
  "text/rtf": {
    "source": "iana",
    "compressible": true,
    "extensions": ["rtf"]
  },
  "text/rtp-enc-aescm128": {
    "source": "iana"
  },
  "text/rtploopback": {
    "source": "iana"
  },
  "text/rtx": {
    "source": "iana"
  },
  "text/sgml": {
    "source": "iana",
    "extensions": ["sgml","sgm"]
  },
  "text/shaclc": {
    "source": "iana"
  },
  "text/shex": {
    "source": "iana",
    "extensions": ["shex"]
  },
  "text/slim": {
    "extensions": ["slim","slm"]
  },
  "text/spdx": {
    "source": "iana",
    "extensions": ["spdx"]
  },
  "text/strings": {
    "source": "iana"
  },
  "text/stylus": {
    "extensions": ["stylus","styl"]
  },
  "text/t140": {
    "source": "iana"
  },
  "text/tab-separated-values": {
    "source": "iana",
    "compressible": true,
    "extensions": ["tsv"]
  },
  "text/troff": {
    "source": "iana",
    "extensions": ["t","tr","roff","man","me","ms"]
  },
  "text/turtle": {
    "source": "iana",
    "charset": "UTF-8",
    "extensions": ["ttl"]
  },
  "text/ulpfec": {
    "source": "iana"
  },
  "text/uri-list": {
    "source": "iana",
    "compressible": true,
    "extensions": ["uri","uris","urls"]
  },
  "text/vcard": {
    "source": "iana",
    "compressible": true,
    "extensions": ["vcard"]
  },
  "text/vnd.a": {
    "source": "iana"
  },
  "text/vnd.abc": {
    "source": "iana"
  },
  "text/vnd.ascii-art": {
    "source": "iana"
  },
  "text/vnd.curl": {
    "source": "iana",
    "extensions": ["curl"]
  },
  "text/vnd.curl.dcurl": {
    "source": "apache",
    "extensions": ["dcurl"]
  },
  "text/vnd.curl.mcurl": {
    "source": "apache",
    "extensions": ["mcurl"]
  },
  "text/vnd.curl.scurl": {
    "source": "apache",
    "extensions": ["scurl"]
  },
  "text/vnd.debian.copyright": {
    "source": "iana",
    "charset": "UTF-8"
  },
  "text/vnd.dmclientscript": {
    "source": "iana"
  },
  "text/vnd.dvb.subtitle": {
    "source": "iana",
    "extensions": ["sub"]
  },
  "text/vnd.esmertec.theme-descriptor": {
    "source": "iana",
    "charset": "UTF-8"
  },
  "text/vnd.ficlab.flt": {
    "source": "iana"
  },
  "text/vnd.fly": {
    "source": "iana",
    "extensions": ["fly"]
  },
  "text/vnd.fmi.flexstor": {
    "source": "iana",
    "extensions": ["flx"]
  },
  "text/vnd.gml": {
    "source": "iana"
  },
  "text/vnd.graphviz": {
    "source": "iana",
    "extensions": ["gv"]
  },
  "text/vnd.hans": {
    "source": "iana"
  },
  "text/vnd.hgl": {
    "source": "iana"
  },
  "text/vnd.in3d.3dml": {
    "source": "iana",
    "extensions": ["3dml"]
  },
  "text/vnd.in3d.spot": {
    "source": "iana",
    "extensions": ["spot"]
  },
  "text/vnd.iptc.newsml": {
    "source": "iana"
  },
  "text/vnd.iptc.nitf": {
    "source": "iana"
  },
  "text/vnd.latex-z": {
    "source": "iana"
  },
  "text/vnd.motorola.reflex": {
    "source": "iana"
  },
  "text/vnd.ms-mediapackage": {
    "source": "iana"
  },
  "text/vnd.net2phone.commcenter.command": {
    "source": "iana"
  },
  "text/vnd.radisys.msml-basic-layout": {
    "source": "iana"
  },
  "text/vnd.senx.warpscript": {
    "source": "iana"
  },
  "text/vnd.si.uricatalogue": {
    "source": "iana"
  },
  "text/vnd.sosi": {
    "source": "iana"
  },
  "text/vnd.sun.j2me.app-descriptor": {
    "source": "iana",
    "charset": "UTF-8",
    "extensions": ["jad"]
  },
  "text/vnd.trolltech.linguist": {
    "source": "iana",
    "charset": "UTF-8"
  },
  "text/vnd.wap.si": {
    "source": "iana"
  },
  "text/vnd.wap.sl": {
    "source": "iana"
  },
  "text/vnd.wap.wml": {
    "source": "iana",
    "extensions": ["wml"]
  },
  "text/vnd.wap.wmlscript": {
    "source": "iana",
    "extensions": ["wmls"]
  },
  "text/vtt": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true,
    "extensions": ["vtt"]
  },
  "text/x-asm": {
    "source": "apache",
    "extensions": ["s","asm"]
  },
  "text/x-c": {
    "source": "apache",
    "extensions": ["c","cc","cxx","cpp","h","hh","dic"]
  },
  "text/x-component": {
    "source": "nginx",
    "extensions": ["htc"]
  },
  "text/x-fortran": {
    "source": "apache",
    "extensions": ["f","for","f77","f90"]
  },
  "text/x-gwt-rpc": {
    "compressible": true
  },
  "text/x-handlebars-template": {
    "extensions": ["hbs"]
  },
  "text/x-java-source": {
    "source": "apache",
    "extensions": ["java"]
  },
  "text/x-jquery-tmpl": {
    "compressible": true
  },
  "text/x-lua": {
    "extensions": ["lua"]
  },
  "text/x-markdown": {
    "compressible": true,
    "extensions": ["mkd"]
  },
  "text/x-nfo": {
    "source": "apache",
    "extensions": ["nfo"]
  },
  "text/x-opml": {
    "source": "apache",
    "extensions": ["opml"]
  },
  "text/x-org": {
    "compressible": true,
    "extensions": ["org"]
  },
  "text/x-pascal": {
    "source": "apache",
    "extensions": ["p","pas"]
  },
  "text/x-processing": {
    "compressible": true,
    "extensions": ["pde"]
  },
  "text/x-sass": {
    "extensions": ["sass"]
  },
  "text/x-scss": {
    "extensions": ["scss"]
  },
  "text/x-setext": {
    "source": "apache",
    "extensions": ["etx"]
  },
  "text/x-sfv": {
    "source": "apache",
    "extensions": ["sfv"]
  },
  "text/x-suse-ymp": {
    "compressible": true,
    "extensions": ["ymp"]
  },
  "text/x-uuencode": {
    "source": "apache",
    "extensions": ["uu"]
  },
  "text/x-vcalendar": {
    "source": "apache",
    "extensions": ["vcs"]
  },
  "text/x-vcard": {
    "source": "apache",
    "extensions": ["vcf"]
  },
  "text/xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["xml"]
  },
  "text/xml-external-parsed-entity": {
    "source": "iana"
  },
  "text/yaml": {
    "compressible": true,
    "extensions": ["yaml","yml"]
  },
  "video/1d-interleaved-parityfec": {
    "source": "iana"
  },
  "video/3gpp": {
    "source": "iana",
    "extensions": ["3gp","3gpp"]
  },
  "video/3gpp-tt": {
    "source": "iana"
  },
  "video/3gpp2": {
    "source": "iana",
    "extensions": ["3g2"]
  },
  "video/av1": {
    "source": "iana"
  },
  "video/bmpeg": {
    "source": "iana"
  },
  "video/bt656": {
    "source": "iana"
  },
  "video/celb": {
    "source": "iana"
  },
  "video/dv": {
    "source": "iana"
  },
  "video/encaprtp": {
    "source": "iana"
  },
  "video/ffv1": {
    "source": "iana"
  },
  "video/flexfec": {
    "source": "iana"
  },
  "video/h261": {
    "source": "iana",
    "extensions": ["h261"]
  },
  "video/h263": {
    "source": "iana",
    "extensions": ["h263"]
  },
  "video/h263-1998": {
    "source": "iana"
  },
  "video/h263-2000": {
    "source": "iana"
  },
  "video/h264": {
    "source": "iana",
    "extensions": ["h264"]
  },
  "video/h264-rcdo": {
    "source": "iana"
  },
  "video/h264-svc": {
    "source": "iana"
  },
  "video/h265": {
    "source": "iana"
  },
  "video/iso.segment": {
    "source": "iana",
    "extensions": ["m4s"]
  },
  "video/jpeg": {
    "source": "iana",
    "extensions": ["jpgv"]
  },
  "video/jpeg2000": {
    "source": "iana"
  },
  "video/jpm": {
    "source": "apache",
    "extensions": ["jpm","jpgm"]
  },
  "video/mj2": {
    "source": "iana",
    "extensions": ["mj2","mjp2"]
  },
  "video/mp1s": {
    "source": "iana"
  },
  "video/mp2p": {
    "source": "iana"
  },
  "video/mp2t": {
    "source": "iana",
    "extensions": ["ts"]
  },
  "video/mp4": {
    "source": "iana",
    "compressible": false,
    "extensions": ["mp4","mp4v","mpg4"]
  },
  "video/mp4v-es": {
    "source": "iana"
  },
  "video/mpeg": {
    "source": "iana",
    "compressible": false,
    "extensions": ["mpeg","mpg","mpe","m1v","m2v"]
  },
  "video/mpeg4-generic": {
    "source": "iana"
  },
  "video/mpv": {
    "source": "iana"
  },
  "video/nv": {
    "source": "iana"
  },
  "video/ogg": {
    "source": "iana",
    "compressible": false,
    "extensions": ["ogv"]
  },
  "video/parityfec": {
    "source": "iana"
  },
  "video/pointer": {
    "source": "iana"
  },
  "video/quicktime": {
    "source": "iana",
    "compressible": false,
    "extensions": ["qt","mov"]
  },
  "video/raptorfec": {
    "source": "iana"
  },
  "video/raw": {
    "source": "iana"
  },
  "video/rtp-enc-aescm128": {
    "source": "iana"
  },
  "video/rtploopback": {
    "source": "iana"
  },
  "video/rtx": {
    "source": "iana"
  },
  "video/scip": {
    "source": "iana"
  },
  "video/smpte291": {
    "source": "iana"
  },
  "video/smpte292m": {
    "source": "iana"
  },
  "video/ulpfec": {
    "source": "iana"
  },
  "video/vc1": {
    "source": "iana"
  },
  "video/vc2": {
    "source": "iana"
  },
  "video/vnd.cctv": {
    "source": "iana"
  },
  "video/vnd.dece.hd": {
    "source": "iana",
    "extensions": ["uvh","uvvh"]
  },
  "video/vnd.dece.mobile": {
    "source": "iana",
    "extensions": ["uvm","uvvm"]
  },
  "video/vnd.dece.mp4": {
    "source": "iana"
  },
  "video/vnd.dece.pd": {
    "source": "iana",
    "extensions": ["uvp","uvvp"]
  },
  "video/vnd.dece.sd": {
    "source": "iana",
    "extensions": ["uvs","uvvs"]
  },
  "video/vnd.dece.video": {
    "source": "iana",
    "extensions": ["uvv","uvvv"]
  },
  "video/vnd.directv.mpeg": {
    "source": "iana"
  },
  "video/vnd.directv.mpeg-tts": {
    "source": "iana"
  },
  "video/vnd.dlna.mpeg-tts": {
    "source": "iana"
  },
  "video/vnd.dvb.file": {
    "source": "iana",
    "extensions": ["dvb"]
  },
  "video/vnd.fvt": {
    "source": "iana",
    "extensions": ["fvt"]
  },
  "video/vnd.hns.video": {
    "source": "iana"
  },
  "video/vnd.iptvforum.1dparityfec-1010": {
    "source": "iana"
  },
  "video/vnd.iptvforum.1dparityfec-2005": {
    "source": "iana"
  },
  "video/vnd.iptvforum.2dparityfec-1010": {
    "source": "iana"
  },
  "video/vnd.iptvforum.2dparityfec-2005": {
    "source": "iana"
  },
  "video/vnd.iptvforum.ttsavc": {
    "source": "iana"
  },
  "video/vnd.iptvforum.ttsmpeg2": {
    "source": "iana"
  },
  "video/vnd.motorola.video": {
    "source": "iana"
  },
  "video/vnd.motorola.videop": {
    "source": "iana"
  },
  "video/vnd.mpegurl": {
    "source": "iana",
    "extensions": ["mxu","m4u"]
  },
  "video/vnd.ms-playready.media.pyv": {
    "source": "iana",
    "extensions": ["pyv"]
  },
  "video/vnd.nokia.interleaved-multimedia": {
    "source": "iana"
  },
  "video/vnd.nokia.mp4vr": {
    "source": "iana"
  },
  "video/vnd.nokia.videovoip": {
    "source": "iana"
  },
  "video/vnd.objectvideo": {
    "source": "iana"
  },
  "video/vnd.radgamettools.bink": {
    "source": "iana"
  },
  "video/vnd.radgamettools.smacker": {
    "source": "iana"
  },
  "video/vnd.sealed.mpeg1": {
    "source": "iana"
  },
  "video/vnd.sealed.mpeg4": {
    "source": "iana"
  },
  "video/vnd.sealed.swf": {
    "source": "iana"
  },
  "video/vnd.sealedmedia.softseal.mov": {
    "source": "iana"
  },
  "video/vnd.uvvu.mp4": {
    "source": "iana",
    "extensions": ["uvu","uvvu"]
  },
  "video/vnd.vivo": {
    "source": "iana",
    "extensions": ["viv"]
  },
  "video/vnd.youtube.yt": {
    "source": "iana"
  },
  "video/vp8": {
    "source": "iana"
  },
  "video/vp9": {
    "source": "iana"
  },
  "video/webm": {
    "source": "apache",
    "compressible": false,
    "extensions": ["webm"]
  },
  "video/x-f4v": {
    "source": "apache",
    "extensions": ["f4v"]
  },
  "video/x-fli": {
    "source": "apache",
    "extensions": ["fli"]
  },
  "video/x-flv": {
    "source": "apache",
    "compressible": false,
    "extensions": ["flv"]
  },
  "video/x-m4v": {
    "source": "apache",
    "extensions": ["m4v"]
  },
  "video/x-matroska": {
    "source": "apache",
    "compressible": false,
    "extensions": ["mkv","mk3d","mks"]
  },
  "video/x-mng": {
    "source": "apache",
    "extensions": ["mng"]
  },
  "video/x-ms-asf": {
    "source": "apache",
    "extensions": ["asf","asx"]
  },
  "video/x-ms-vob": {
    "source": "apache",
    "extensions": ["vob"]
  },
  "video/x-ms-wm": {
    "source": "apache",
    "extensions": ["wm"]
  },
  "video/x-ms-wmv": {
    "source": "apache",
    "compressible": false,
    "extensions": ["wmv"]
  },
  "video/x-ms-wmx": {
    "source": "apache",
    "extensions": ["wmx"]
  },
  "video/x-ms-wvx": {
    "source": "apache",
    "extensions": ["wvx"]
  },
  "video/x-msvideo": {
    "source": "apache",
    "extensions": ["avi"]
  },
  "video/x-sgi-movie": {
    "source": "apache",
    "extensions": ["movie"]
  },
  "video/x-smv": {
    "source": "apache",
    "extensions": ["smv"]
  },
  "x-conference/x-cooltalk": {
    "source": "apache",
    "extensions": ["ice"]
  },
  "x-shader/x-fragment": {
    "compressible": true
  },
  "x-shader/x-vertex": {
    "compressible": true
  }
}`);

// https://deno.land/std@0.217.0/path/windows/mod.ts
init_basename11();

// https://deno.land/std@0.217.0/path/_common/dirname.ts
init_assert_path3();

// https://deno.land/std@0.217.0/path/windows/dirname.ts
init_constants9();
init_strip_trailing_separators3();
init_util7();

// https://deno.land/std@0.217.0/path/windows/extname.ts
init_constants9();
init_assert_path3();
init_util7();
function extname6(path3) {
  assertPath3(path3);
  let start = 0;
  let startDot = -1;
  let startPart = 0;
  let end = -1;
  let matchedSlash = true;
  let preDotState = 0;
  if (path3.length >= 2 && path3.charCodeAt(1) === CHAR_COLON5 && isWindowsDeviceRoot3(path3.charCodeAt(0))) {
    start = startPart = 2;
  }
  for (let i6 = path3.length - 1; i6 >= start; --i6) {
    const code5 = path3.charCodeAt(i6);
    if (isPathSeparator3(code5)) {
      if (!matchedSlash) {
        startPart = i6 + 1;
        break;
      }
      continue;
    }
    if (end === -1) {
      matchedSlash = false;
      end = i6 + 1;
    }
    if (code5 === CHAR_DOT3) {
      if (startDot === -1) startDot = i6;
      else if (preDotState !== 1) preDotState = 1;
    } else if (startDot !== -1) {
      preDotState = -1;
    }
  }
  if (startDot === -1 || end === -1 || // We saw a non-dot character immediately before the dot
  preDotState === 0 || // The (right-most) trimmed path component is exactly '..'
  preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
    return "";
  }
  return path3.slice(startDot, end);
}

// https://deno.land/std@0.217.0/path/windows/mod.ts
init_from_file_url11();

// https://deno.land/std@0.217.0/path/windows/is_absolute.ts
init_constants9();
init_assert_path3();
init_util7();

// https://deno.land/std@0.217.0/path/windows/mod.ts
init_join8();
init_normalize11();

// https://deno.land/std@0.217.0/path/windows/parse.ts
init_constants9();
init_assert_path3();
init_util7();

// https://deno.land/std@0.217.0/path/windows/relative.ts
init_constants9();
init_resolve9();

// https://deno.land/std@0.217.0/path/_common/relative.ts
init_assert_path3();

// https://deno.land/std@0.217.0/path/windows/mod.ts
init_resolve9();

// https://deno.land/std@0.217.0/path/windows/to_namespaced_path.ts
init_constants9();
init_util7();
init_resolve9();

// https://deno.land/std@0.217.0/path/windows/join_globs.ts
init_join8();

// https://deno.land/std@0.217.0/path/windows/normalize_glob.ts
init_normalize11();

// https://deno.land/std@0.217.0/path/posix/mod.ts
init_basename10();

// https://deno.land/std@0.217.0/path/posix/dirname.ts
init_strip_trailing_separators3();
init_util6();

// https://deno.land/std@0.217.0/path/posix/extname.ts
init_constants9();
init_assert_path3();
init_util6();
function extname7(path3) {
  assertPath3(path3);
  let startDot = -1;
  let startPart = 0;
  let end = -1;
  let matchedSlash = true;
  let preDotState = 0;
  for (let i6 = path3.length - 1; i6 >= 0; --i6) {
    const code5 = path3.charCodeAt(i6);
    if (isPosixPathSeparator5(code5)) {
      if (!matchedSlash) {
        startPart = i6 + 1;
        break;
      }
      continue;
    }
    if (end === -1) {
      matchedSlash = false;
      end = i6 + 1;
    }
    if (code5 === CHAR_DOT3) {
      if (startDot === -1) startDot = i6;
      else if (preDotState !== 1) preDotState = 1;
    } else if (startDot !== -1) {
      preDotState = -1;
    }
  }
  if (startDot === -1 || end === -1 || // We saw a non-dot character immediately before the dot
  preDotState === 0 || // The (right-most) trimmed path component is exactly '..'
  preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
    return "";
  }
  return path3.slice(startDot, end);
}

// https://deno.land/std@0.217.0/path/posix/mod.ts
init_from_file_url10();

// https://deno.land/std@0.217.0/path/posix/is_absolute.ts
init_assert_path3();
init_util6();

// https://deno.land/std@0.217.0/path/posix/mod.ts
init_join7();
init_normalize10();

// https://deno.land/std@0.217.0/path/posix/parse.ts
init_constants9();
init_strip_trailing_separators3();
init_assert_path3();
init_util6();

// https://deno.land/std@0.217.0/path/posix/relative.ts
init_util6();
init_resolve8();

// https://deno.land/std@0.217.0/path/posix/mod.ts
init_resolve8();

// https://deno.land/std@0.217.0/path/posix/join_globs.ts
init_join7();

// https://deno.land/std@0.217.0/path/posix/normalize_glob.ts
init_normalize10();

// https://deno.land/std@0.217.0/path/mod.ts
init_basename12();
init_constants10();

// https://deno.land/std@0.217.0/path/dirname.ts
init_os3();

// https://deno.land/std@0.217.0/path/extname.ts
init_os3();
function extname8(path3) {
  return isWindows6 ? extname6(path3) : extname7(path3);
}

// https://deno.land/std@0.217.0/path/format.ts
init_os3();

// https://deno.land/std@0.217.0/path/mod.ts
init_from_file_url12();

// https://deno.land/std@0.217.0/path/is_absolute.ts
init_os3();

// https://deno.land/std@0.217.0/path/mod.ts
init_join9();
init_normalize12();

// https://deno.land/std@0.217.0/path/parse.ts
init_os3();

// https://deno.land/std@0.217.0/path/relative.ts
init_os3();

// https://deno.land/std@0.217.0/path/mod.ts
init_resolve10();

// https://deno.land/std@0.217.0/path/to_file_url.ts
init_os3();

// https://deno.land/std@0.217.0/path/to_namespaced_path.ts
init_os3();

// https://deno.land/std@0.217.0/path/common.ts
init_constants10();

// https://deno.land/std@0.217.0/path/glob_to_regexp.ts
init_os3();

// https://deno.land/std@0.217.0/path/join_globs.ts
init_os3();

// https://deno.land/std@0.217.0/path/normalize_glob.ts
init_os3();

// https://deno.land/x/media_types@v2.10.1/mod.ts
var extensions = /* @__PURE__ */ new Map();
var types4 = /* @__PURE__ */ new Map();
function populateMaps(extensions2, types8) {
  const preference = ["nginx", "apache", void 0, "iana"];
  for (const type4 of Object.keys(db)) {
    const mime = db[type4];
    const exts = mime.extensions;
    if (!exts || !exts.length) {
      continue;
    }
    extensions2.set(type4, exts);
    for (const ext of exts) {
      const current3 = types8.get(ext);
      if (current3) {
        const from = preference.indexOf(db[current3].source);
        const to = preference.indexOf(mime.source);
        if (current3 !== "application/octet-stream" && (from > to || from === to && current3.substr(0, 12) === "application/")) {
          continue;
        }
      }
      types8.set(ext, type4);
    }
  }
}
populateMaps(extensions, types4);
function lookup2(path3) {
  const extension = extname8("x." + path3).toLowerCase().substr(1);
  return types4.get(extension);
}

// https://cdn.skypack.dev/-/acorn@v7.4.1-aIeX4aKa0RO2JeS9dtPa/dist=es2019,mode=imports/optimized/acorn.js
var reservedWords = {
  3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",
  5: "class enum extends super const export import",
  6: "enum",
  strict: "implements interface let package private protected public static yield",
  strictBind: "eval arguments"
};
var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";
var keywords = {
  5: ecma5AndLessKeywords,
  "5module": ecma5AndLessKeywords + " export import",
  6: ecma5AndLessKeywords + " const class extends export import super"
};
var keywordRelationalOperator = /^in(stanceof)?$/;
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\u08A0-\u08B4\u08B6-\u08C7\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\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\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-\u170C\u170E-\u1711\u1720-\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-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\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-\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-\u312F\u3131-\u318E\u31A0-\u31BF\u31F0-\u31FF\u3400-\u4DBF\u4E00-\u9FFC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7BF\uA7C2-\uA7CA\uA7F5-\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 = "\u200C\u200D\xB7\u0300-\u036F\u0387\u0483-\u0487\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u0669\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07C0-\u07C9\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\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\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\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-\u0ECD\u0ED0-\u0ED9\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1040-\u1049\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F-\u109D\u135D-\u135F\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u18A9\u1920-\u192B\u1930-\u193B\u1946-\u194F\u19D0-\u19DA\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AB0-\u1ABD\u1ABF\u1AC0\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-\u1DF9\u1DFB-\u1DFF\u203F\u2040\u2054\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA620-\uA629\uA66F\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\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";
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, 157, 310, 10, 21, 11, 7, 153, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 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, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 107, 20, 28, 22, 13, 52, 76, 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, 85, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 230, 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, 35, 56, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 190, 0, 80, 921, 103, 110, 18, 195, 2749, 1070, 4050, 582, 8634, 568, 8, 30, 114, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8952, 286, 50, 2, 18, 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, 2357, 44, 11, 6, 17, 0, 370, 43, 1301, 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, 42717, 35, 4148, 12, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938];
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, 370, 1, 154, 10, 176, 2, 54, 14, 32, 9, 16, 3, 46, 10, 54, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 161, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 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, 406, 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, 330, 3, 19306, 9, 135, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 5319, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 262, 6, 10, 9, 419, 13, 1495, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
function isInAstralSet(code5, set3) {
  var pos = 65536;
  for (var i6 = 0; i6 < set3.length; i6 += 2) {
    pos += set3[i6];
    if (pos > code5) {
      return false;
    }
    pos += set3[i6 + 1];
    if (pos >= code5) {
      return true;
    }
  }
}
function isIdentifierStart(code5, astral) {
  if (code5 < 65) {
    return code5 === 36;
  }
  if (code5 < 91) {
    return true;
  }
  if (code5 < 97) {
    return code5 === 95;
  }
  if (code5 < 123) {
    return true;
  }
  if (code5 <= 65535) {
    return code5 >= 170 && nonASCIIidentifierStart.test(String.fromCharCode(code5));
  }
  if (astral === false) {
    return false;
  }
  return isInAstralSet(code5, astralIdentifierStartCodes);
}
function isIdentifierChar(code5, astral) {
  if (code5 < 48) {
    return code5 === 36;
  }
  if (code5 < 58) {
    return true;
  }
  if (code5 < 65) {
    return false;
  }
  if (code5 < 91) {
    return true;
  }
  if (code5 < 97) {
    return code5 === 95;
  }
  if (code5 < 123) {
    return true;
  }
  if (code5 <= 65535) {
    return code5 >= 170 && nonASCIIidentifier.test(String.fromCharCode(code5));
  }
  if (astral === false) {
    return false;
  }
  return isInAstralSet(code5, astralIdentifierStartCodes) || isInAstralSet(code5, astralIdentifierCodes);
}
var TokenType = function TokenType2(label, conf) {
  if (conf === void 0)
    conf = {};
  this.label = label;
  this.keyword = conf.keyword;
  this.beforeExpr = !!conf.beforeExpr;
  this.startsExpr = !!conf.startsExpr;
  this.isLoop = !!conf.isLoop;
  this.isAssign = !!conf.isAssign;
  this.prefix = !!conf.prefix;
  this.postfix = !!conf.postfix;
  this.binop = conf.binop || null;
  this.updateContext = null;
};
function binop(name2, prec) {
  return new TokenType(name2, { beforeExpr: true, binop: prec });
}
var beforeExpr = { beforeExpr: true };
var startsExpr = { startsExpr: true };
var keywords$1 = {};
function kw(name2, options) {
  if (options === void 0)
    options = {};
  options.keyword = name2;
  return keywords$1[name2] = new TokenType(name2, options);
}
var types5 = {
  num: new TokenType("num", startsExpr),
  regexp: new TokenType("regexp", startsExpr),
  string: new TokenType("string", startsExpr),
  name: new TokenType("name", startsExpr),
  eof: new TokenType("eof"),
  bracketL: new TokenType("[", { beforeExpr: true, startsExpr: true }),
  bracketR: new TokenType("]"),
  braceL: new TokenType("{", { beforeExpr: true, startsExpr: true }),
  braceR: new TokenType("}"),
  parenL: new TokenType("(", { beforeExpr: true, startsExpr: true }),
  parenR: new TokenType(")"),
  comma: new TokenType(",", beforeExpr),
  semi: new TokenType(";", beforeExpr),
  colon: new TokenType(":", beforeExpr),
  dot: new TokenType("."),
  question: new TokenType("?", beforeExpr),
  questionDot: new TokenType("?."),
  arrow: new TokenType("=>", beforeExpr),
  template: new TokenType("template"),
  invalidTemplate: new TokenType("invalidTemplate"),
  ellipsis: new TokenType("...", beforeExpr),
  backQuote: new TokenType("`", startsExpr),
  dollarBraceL: new TokenType("${", { beforeExpr: true, startsExpr: true }),
  eq: new TokenType("=", { beforeExpr: true, isAssign: true }),
  assign: new TokenType("_=", { beforeExpr: true, isAssign: true }),
  incDec: new TokenType("++/--", { prefix: true, postfix: true, startsExpr: true }),
  prefix: new TokenType("!/~", { beforeExpr: true, prefix: true, startsExpr: true }),
  logicalOR: binop("||", 1),
  logicalAND: binop("&&", 2),
  bitwiseOR: binop("|", 3),
  bitwiseXOR: binop("^", 4),
  bitwiseAND: binop("&", 5),
  equality: binop("==/!=/===/!==", 6),
  relational: binop("</>/<=/>=", 7),
  bitShift: binop("<</>>/>>>", 8),
  plusMin: new TokenType("+/-", { beforeExpr: true, binop: 9, prefix: true, startsExpr: true }),
  modulo: binop("%", 10),
  star: binop("*", 10),
  slash: binop("/", 10),
  starstar: new TokenType("**", { beforeExpr: true }),
  coalesce: binop("??", 1),
  _break: kw("break"),
  _case: kw("case", beforeExpr),
  _catch: kw("catch"),
  _continue: kw("continue"),
  _debugger: kw("debugger"),
  _default: kw("default", beforeExpr),
  _do: kw("do", { isLoop: true, beforeExpr: true }),
  _else: kw("else", beforeExpr),
  _finally: kw("finally"),
  _for: kw("for", { isLoop: true }),
  _function: kw("function", startsExpr),
  _if: kw("if"),
  _return: kw("return", beforeExpr),
  _switch: kw("switch"),
  _throw: kw("throw", beforeExpr),
  _try: kw("try"),
  _var: kw("var"),
  _const: kw("const"),
  _while: kw("while", { isLoop: true }),
  _with: kw("with"),
  _new: kw("new", { beforeExpr: true, startsExpr: true }),
  _this: kw("this", startsExpr),
  _super: kw("super", startsExpr),
  _class: kw("class", startsExpr),
  _extends: kw("extends", beforeExpr),
  _export: kw("export"),
  _import: kw("import", startsExpr),
  _null: kw("null", startsExpr),
  _true: kw("true", startsExpr),
  _false: kw("false", startsExpr),
  _in: kw("in", { beforeExpr: true, binop: 7 }),
  _instanceof: kw("instanceof", { beforeExpr: true, binop: 7 }),
  _typeof: kw("typeof", { beforeExpr: true, prefix: true, startsExpr: true }),
  _void: kw("void", { beforeExpr: true, prefix: true, startsExpr: true }),
  _delete: kw("delete", { beforeExpr: true, prefix: true, startsExpr: true })
};
var lineBreak = /\r\n?|\n|\u2028|\u2029/;
var lineBreakG = new RegExp(lineBreak.source, "g");
function isNewLine(code5, ecma2019String) {
  return code5 === 10 || code5 === 13 || !ecma2019String && (code5 === 8232 || code5 === 8233);
}
var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
var ref = Object.prototype;
var hasOwnProperty = ref.hasOwnProperty;
var toString6 = ref.toString;
function has(obj, propName) {
  return hasOwnProperty.call(obj, propName);
}
var isArray4 = Array.isArray || function(obj) {
  return toString6.call(obj) === "[object Array]";
};
function wordsRegexp(words) {
  return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$");
}
var Position = function Position2(line, col) {
  this.line = line;
  this.column = col;
};
Position.prototype.offset = function offset(n5) {
  return new Position(this.line, this.column + n5);
};
var SourceLocation = function SourceLocation2(p5, start, end) {
  this.start = start;
  this.end = end;
  if (p5.sourceFile !== null) {
    this.source = p5.sourceFile;
  }
};
function getLineInfo(input, offset22) {
  for (var line = 1, cur = 0; ; ) {
    lineBreakG.lastIndex = cur;
    var match = lineBreakG.exec(input);
    if (match && match.index < offset22) {
      ++line;
      cur = match.index + match[0].length;
    } else {
      return new Position(line, offset22 - cur);
    }
  }
}
var defaultOptions = {
  ecmaVersion: 10,
  sourceType: "script",
  onInsertedSemicolon: null,
  onTrailingComma: null,
  allowReserved: null,
  allowReturnOutsideFunction: false,
  allowImportExportEverywhere: false,
  allowAwaitOutsideFunction: false,
  allowHashBang: false,
  locations: false,
  onToken: null,
  onComment: null,
  ranges: false,
  program: null,
  sourceFile: null,
  directSourceFile: null,
  preserveParens: false
};
function getOptions(opts) {
  var options = {};
  for (var opt in defaultOptions) {
    options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt];
  }
  if (options.ecmaVersion >= 2015) {
    options.ecmaVersion -= 2009;
  }
  if (options.allowReserved == null) {
    options.allowReserved = options.ecmaVersion < 5;
  }
  if (isArray4(options.onToken)) {
    var tokens2 = options.onToken;
    options.onToken = function(token) {
      return tokens2.push(token);
    };
  }
  if (isArray4(options.onComment)) {
    options.onComment = pushComment(options, options.onComment);
  }
  return options;
}
function pushComment(options, array) {
  return function(block, text, start, end, startLoc, endLoc) {
    var comment = {
      type: block ? "Block" : "Line",
      value: text,
      start,
      end
    };
    if (options.locations) {
      comment.loc = new SourceLocation(this, startLoc, endLoc);
    }
    if (options.ranges) {
      comment.range = [start, end];
    }
    array.push(comment);
  };
}
var SCOPE_TOP = 1;
var SCOPE_FUNCTION = 2;
var SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION;
var SCOPE_ASYNC = 4;
var SCOPE_GENERATOR = 8;
var SCOPE_ARROW = 16;
var SCOPE_SIMPLE_CATCH = 32;
var SCOPE_SUPER = 64;
var SCOPE_DIRECT_SUPER = 128;
function functionFlags(async, generator) {
  return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0);
}
var BIND_NONE = 0;
var BIND_VAR = 1;
var BIND_LEXICAL = 2;
var BIND_FUNCTION = 3;
var BIND_SIMPLE_CATCH = 4;
var BIND_OUTSIDE = 5;
var Parser2 = function Parser22(options, input, startPos) {
  this.options = options = getOptions(options);
  this.sourceFile = options.sourceFile;
  this.keywords = wordsRegexp(keywords[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
  var reserved = "";
  if (options.allowReserved !== true) {
    for (var v4 = options.ecmaVersion; ; v4--) {
      if (reserved = reservedWords[v4]) {
        break;
      }
    }
    if (options.sourceType === "module") {
      reserved += " await";
    }
  }
  this.reservedWords = wordsRegexp(reserved);
  var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict;
  this.reservedWordsStrict = wordsRegexp(reservedStrict);
  this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind);
  this.input = String(input);
  this.containsEsc = false;
  if (startPos) {
    this.pos = startPos;
    this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
    this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
  } else {
    this.pos = this.lineStart = 0;
    this.curLine = 1;
  }
  this.type = types5.eof;
  this.value = null;
  this.start = this.end = this.pos;
  this.startLoc = this.endLoc = this.curPosition();
  this.lastTokEndLoc = this.lastTokStartLoc = null;
  this.lastTokStart = this.lastTokEnd = this.pos;
  this.context = this.initialContext();
  this.exprAllowed = true;
  this.inModule = options.sourceType === "module";
  this.strict = this.inModule || this.strictDirective(this.pos);
  this.potentialArrowAt = -1;
  this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
  this.labels = [];
  this.undefinedExports = {};
  if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!") {
    this.skipLineComment(2);
  }
  this.scopeStack = [];
  this.enterScope(SCOPE_TOP);
  this.regexpState = null;
};
var prototypeAccessors = { inFunction: { configurable: true }, inGenerator: { configurable: true }, inAsync: { configurable: true }, allowSuper: { configurable: true }, allowDirectSuper: { configurable: true }, treatFunctionsAsVar: { configurable: true } };
Parser2.prototype.parse = function parse13() {
  var node = this.options.program || this.startNode();
  this.nextToken();
  return this.parseTopLevel(node);
};
prototypeAccessors.inFunction.get = function() {
  return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0;
};
prototypeAccessors.inGenerator.get = function() {
  return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0;
};
prototypeAccessors.inAsync.get = function() {
  return (this.currentVarScope().flags & SCOPE_ASYNC) > 0;
};
prototypeAccessors.allowSuper.get = function() {
  return (this.currentThisScope().flags & SCOPE_SUPER) > 0;
};
prototypeAccessors.allowDirectSuper.get = function() {
  return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0;
};
prototypeAccessors.treatFunctionsAsVar.get = function() {
  return this.treatFunctionsAsVarInScope(this.currentScope());
};
Parser2.prototype.inNonArrowFunction = function inNonArrowFunction() {
  return (this.currentThisScope().flags & SCOPE_FUNCTION) > 0;
};
Parser2.extend = function extend4() {
  var plugins = [], len = arguments.length;
  while (len--)
    plugins[len] = arguments[len];
  var cls = this;
  for (var i6 = 0; i6 < plugins.length; i6++) {
    cls = plugins[i6](cls);
  }
  return cls;
};
Parser2.parse = function parse22(input, options) {
  return new this(options, input).parse();
};
Parser2.parseExpressionAt = function parseExpressionAt(input, pos, options) {
  var parser = new this(options, input, pos);
  parser.nextToken();
  return parser.parseExpression();
};
Parser2.tokenizer = function tokenizer(input, options) {
  return new this(options, input);
};
Object.defineProperties(Parser2.prototype, prototypeAccessors);
var pp = Parser2.prototype;
var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/;
pp.strictDirective = function(start) {
  for (; ; ) {
    skipWhiteSpace.lastIndex = start;
    start += skipWhiteSpace.exec(this.input)[0].length;
    var match = literal.exec(this.input.slice(start));
    if (!match) {
      return false;
    }
    if ((match[1] || match[2]) === "use strict") {
      skipWhiteSpace.lastIndex = start + match[0].length;
      var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;
      var next = this.input.charAt(end);
      return next === ";" || next === "}" || lineBreak.test(spaceAfter[0]) && !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "=");
    }
    start += match[0].length;
    skipWhiteSpace.lastIndex = start;
    start += skipWhiteSpace.exec(this.input)[0].length;
    if (this.input[start] === ";") {
      start++;
    }
  }
};
pp.eat = function(type4) {
  if (this.type === type4) {
    this.next();
    return true;
  } else {
    return false;
  }
};
pp.isContextual = function(name2) {
  return this.type === types5.name && this.value === name2 && !this.containsEsc;
};
pp.eatContextual = function(name2) {
  if (!this.isContextual(name2)) {
    return false;
  }
  this.next();
  return true;
};
pp.expectContextual = function(name2) {
  if (!this.eatContextual(name2)) {
    this.unexpected();
  }
};
pp.canInsertSemicolon = function() {
  return this.type === types5.eof || this.type === types5.braceR || lineBreak.test(this.input.slice(this.lastTokEnd, this.start));
};
pp.insertSemicolon = function() {
  if (this.canInsertSemicolon()) {
    if (this.options.onInsertedSemicolon) {
      this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc);
    }
    return true;
  }
};
pp.semicolon = function() {
  if (!this.eat(types5.semi) && !this.insertSemicolon()) {
    this.unexpected();
  }
};
pp.afterTrailingComma = function(tokType, notNext) {
  if (this.type === tokType) {
    if (this.options.onTrailingComma) {
      this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc);
    }
    if (!notNext) {
      this.next();
    }
    return true;
  }
};
pp.expect = function(type4) {
  this.eat(type4) || this.unexpected();
};
pp.unexpected = function(pos) {
  this.raise(pos != null ? pos : this.start, "Unexpected token");
};
function DestructuringErrors() {
  this.shorthandAssign = this.trailingComma = this.parenthesizedAssign = this.parenthesizedBind = this.doubleProto = -1;
}
pp.checkPatternErrors = function(refDestructuringErrors, isAssign) {
  if (!refDestructuringErrors) {
    return;
  }
  if (refDestructuringErrors.trailingComma > -1) {
    this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element");
  }
  var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
  if (parens > -1) {
    this.raiseRecoverable(parens, "Parenthesized pattern");
  }
};
pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
  if (!refDestructuringErrors) {
    return false;
  }
  var shorthandAssign = refDestructuringErrors.shorthandAssign;
  var doubleProto = refDestructuringErrors.doubleProto;
  if (!andThrow) {
    return shorthandAssign >= 0 || doubleProto >= 0;
  }
  if (shorthandAssign >= 0) {
    this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns");
  }
  if (doubleProto >= 0) {
    this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property");
  }
};
pp.checkYieldAwaitInDefaultParams = function() {
  if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos)) {
    this.raise(this.yieldPos, "Yield expression cannot be a default value");
  }
  if (this.awaitPos) {
    this.raise(this.awaitPos, "Await expression cannot be a default value");
  }
};
pp.isSimpleAssignTarget = function(expr) {
  if (expr.type === "ParenthesizedExpression") {
    return this.isSimpleAssignTarget(expr.expression);
  }
  return expr.type === "Identifier" || expr.type === "MemberExpression";
};
var pp$1 = Parser2.prototype;
pp$1.parseTopLevel = function(node) {
  var exports23 = {};
  if (!node.body) {
    node.body = [];
  }
  while (this.type !== types5.eof) {
    var stmt = this.parseStatement(null, true, exports23);
    node.body.push(stmt);
  }
  if (this.inModule) {
    for (var i6 = 0, list = Object.keys(this.undefinedExports); i6 < list.length; i6 += 1) {
      var name2 = list[i6];
      this.raiseRecoverable(this.undefinedExports[name2].start, "Export '" + name2 + "' is not defined");
    }
  }
  this.adaptDirectivePrologue(node.body);
  this.next();
  node.sourceType = this.options.sourceType;
  return this.finishNode(node, "Program");
};
var loopLabel = { kind: "loop" };
var switchLabel = { kind: "switch" };
pp$1.isLet = function(context) {
  if (this.options.ecmaVersion < 6 || !this.isContextual("let")) {
    return false;
  }
  skipWhiteSpace.lastIndex = this.pos;
  var skip = skipWhiteSpace.exec(this.input);
  var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  if (nextCh === 91) {
    return true;
  }
  if (context) {
    return false;
  }
  if (nextCh === 123) {
    return true;
  }
  if (isIdentifierStart(nextCh, true)) {
    var pos = next + 1;
    while (isIdentifierChar(this.input.charCodeAt(pos), true)) {
      ++pos;
    }
    var ident = this.input.slice(next, pos);
    if (!keywordRelationalOperator.test(ident)) {
      return true;
    }
  }
  return false;
};
pp$1.isAsyncFunction = function() {
  if (this.options.ecmaVersion < 8 || !this.isContextual("async")) {
    return false;
  }
  skipWhiteSpace.lastIndex = this.pos;
  var skip = skipWhiteSpace.exec(this.input);
  var next = this.pos + skip[0].length;
  return !lineBreak.test(this.input.slice(this.pos, next)) && this.input.slice(next, next + 8) === "function" && (next + 8 === this.input.length || !isIdentifierChar(this.input.charAt(next + 8)));
};
pp$1.parseStatement = function(context, topLevel, exports23) {
  var starttype = this.type, node = this.startNode(), kind;
  if (this.isLet(context)) {
    starttype = types5._var;
    kind = "let";
  }
  switch (starttype) {
    case types5._break:
    case types5._continue:
      return this.parseBreakContinueStatement(node, starttype.keyword);
    case types5._debugger:
      return this.parseDebuggerStatement(node);
    case types5._do:
      return this.parseDoStatement(node);
    case types5._for:
      return this.parseForStatement(node);
    case types5._function:
      if (context && (this.strict || context !== "if" && context !== "label") && this.options.ecmaVersion >= 6) {
        this.unexpected();
      }
      return this.parseFunctionStatement(node, false, !context);
    case types5._class:
      if (context) {
        this.unexpected();
      }
      return this.parseClass(node, true);
    case types5._if:
      return this.parseIfStatement(node);
    case types5._return:
      return this.parseReturnStatement(node);
    case types5._switch:
      return this.parseSwitchStatement(node);
    case types5._throw:
      return this.parseThrowStatement(node);
    case types5._try:
      return this.parseTryStatement(node);
    case types5._const:
    case types5._var:
      kind = kind || this.value;
      if (context && kind !== "var") {
        this.unexpected();
      }
      return this.parseVarStatement(node, kind);
    case types5._while:
      return this.parseWhileStatement(node);
    case types5._with:
      return this.parseWithStatement(node);
    case types5.braceL:
      return this.parseBlock(true, node);
    case types5.semi:
      return this.parseEmptyStatement(node);
    case types5._export:
    case types5._import:
      if (this.options.ecmaVersion > 10 && starttype === types5._import) {
        skipWhiteSpace.lastIndex = this.pos;
        var skip = skipWhiteSpace.exec(this.input);
        var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
        if (nextCh === 40 || nextCh === 46) {
          return this.parseExpressionStatement(node, this.parseExpression());
        }
      }
      if (!this.options.allowImportExportEverywhere) {
        if (!topLevel) {
          this.raise(this.start, "'import' and 'export' may only appear at the top level");
        }
        if (!this.inModule) {
          this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'");
        }
      }
      return starttype === types5._import ? this.parseImport(node) : this.parseExport(node, exports23);
    default:
      if (this.isAsyncFunction()) {
        if (context) {
          this.unexpected();
        }
        this.next();
        return this.parseFunctionStatement(node, true, !context);
      }
      var maybeName = this.value, expr = this.parseExpression();
      if (starttype === types5.name && expr.type === "Identifier" && this.eat(types5.colon)) {
        return this.parseLabeledStatement(node, maybeName, expr, context);
      } else {
        return this.parseExpressionStatement(node, expr);
      }
  }
};
pp$1.parseBreakContinueStatement = function(node, keyword) {
  var isBreak = keyword === "break";
  this.next();
  if (this.eat(types5.semi) || this.insertSemicolon()) {
    node.label = null;
  } else if (this.type !== types5.name) {
    this.unexpected();
  } else {
    node.label = this.parseIdent();
    this.semicolon();
  }
  var i6 = 0;
  for (; i6 < this.labels.length; ++i6) {
    var lab = this.labels[i6];
    if (node.label == null || lab.name === node.label.name) {
      if (lab.kind != null && (isBreak || lab.kind === "loop")) {
        break;
      }
      if (node.label && isBreak) {
        break;
      }
    }
  }
  if (i6 === this.labels.length) {
    this.raise(node.start, "Unsyntactic " + keyword);
  }
  return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
};
pp$1.parseDebuggerStatement = function(node) {
  this.next();
  this.semicolon();
  return this.finishNode(node, "DebuggerStatement");
};
pp$1.parseDoStatement = function(node) {
  this.next();
  this.labels.push(loopLabel);
  node.body = this.parseStatement("do");
  this.labels.pop();
  this.expect(types5._while);
  node.test = this.parseParenExpression();
  if (this.options.ecmaVersion >= 6) {
    this.eat(types5.semi);
  } else {
    this.semicolon();
  }
  return this.finishNode(node, "DoWhileStatement");
};
pp$1.parseForStatement = function(node) {
  this.next();
  var awaitAt = this.options.ecmaVersion >= 9 && (this.inAsync || !this.inFunction && this.options.allowAwaitOutsideFunction) && this.eatContextual("await") ? this.lastTokStart : -1;
  this.labels.push(loopLabel);
  this.enterScope(0);
  this.expect(types5.parenL);
  if (this.type === types5.semi) {
    if (awaitAt > -1) {
      this.unexpected(awaitAt);
    }
    return this.parseFor(node, null);
  }
  var isLet = this.isLet();
  if (this.type === types5._var || this.type === types5._const || isLet) {
    var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
    this.next();
    this.parseVar(init$1, true, kind);
    this.finishNode(init$1, "VariableDeclaration");
    if ((this.type === types5._in || this.options.ecmaVersion >= 6 && this.isContextual("of")) && init$1.declarations.length === 1) {
      if (this.options.ecmaVersion >= 9) {
        if (this.type === types5._in) {
          if (awaitAt > -1) {
            this.unexpected(awaitAt);
          }
        } else {
          node.await = awaitAt > -1;
        }
      }
      return this.parseForIn(node, init$1);
    }
    if (awaitAt > -1) {
      this.unexpected(awaitAt);
    }
    return this.parseFor(node, init$1);
  }
  var refDestructuringErrors = new DestructuringErrors();
  var init5 = this.parseExpression(true, refDestructuringErrors);
  if (this.type === types5._in || this.options.ecmaVersion >= 6 && this.isContextual("of")) {
    if (this.options.ecmaVersion >= 9) {
      if (this.type === types5._in) {
        if (awaitAt > -1) {
          this.unexpected(awaitAt);
        }
      } else {
        node.await = awaitAt > -1;
      }
    }
    this.toAssignable(init5, false, refDestructuringErrors);
    this.checkLVal(init5);
    return this.parseForIn(node, init5);
  } else {
    this.checkExpressionErrors(refDestructuringErrors, true);
  }
  if (awaitAt > -1) {
    this.unexpected(awaitAt);
  }
  return this.parseFor(node, init5);
};
pp$1.parseFunctionStatement = function(node, isAsync2, declarationPosition) {
  this.next();
  return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync2);
};
pp$1.parseIfStatement = function(node) {
  this.next();
  node.test = this.parseParenExpression();
  node.consequent = this.parseStatement("if");
  node.alternate = this.eat(types5._else) ? this.parseStatement("if") : null;
  return this.finishNode(node, "IfStatement");
};
pp$1.parseReturnStatement = function(node) {
  if (!this.inFunction && !this.options.allowReturnOutsideFunction) {
    this.raise(this.start, "'return' outside of function");
  }
  this.next();
  if (this.eat(types5.semi) || this.insertSemicolon()) {
    node.argument = null;
  } else {
    node.argument = this.parseExpression();
    this.semicolon();
  }
  return this.finishNode(node, "ReturnStatement");
};
pp$1.parseSwitchStatement = function(node) {
  this.next();
  node.discriminant = this.parseParenExpression();
  node.cases = [];
  this.expect(types5.braceL);
  this.labels.push(switchLabel);
  this.enterScope(0);
  var cur;
  for (var sawDefault = false; this.type !== types5.braceR; ) {
    if (this.type === types5._case || this.type === types5._default) {
      var isCase = this.type === types5._case;
      if (cur) {
        this.finishNode(cur, "SwitchCase");
      }
      node.cases.push(cur = this.startNode());
      cur.consequent = [];
      this.next();
      if (isCase) {
        cur.test = this.parseExpression();
      } else {
        if (sawDefault) {
          this.raiseRecoverable(this.lastTokStart, "Multiple default clauses");
        }
        sawDefault = true;
        cur.test = null;
      }
      this.expect(types5.colon);
    } else {
      if (!cur) {
        this.unexpected();
      }
      cur.consequent.push(this.parseStatement(null));
    }
  }
  this.exitScope();
  if (cur) {
    this.finishNode(cur, "SwitchCase");
  }
  this.next();
  this.labels.pop();
  return this.finishNode(node, "SwitchStatement");
};
pp$1.parseThrowStatement = function(node) {
  this.next();
  if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) {
    this.raise(this.lastTokEnd, "Illegal newline after throw");
  }
  node.argument = this.parseExpression();
  this.semicolon();
  return this.finishNode(node, "ThrowStatement");
};
var empty = [];
pp$1.parseTryStatement = function(node) {
  this.next();
  node.block = this.parseBlock();
  node.handler = null;
  if (this.type === types5._catch) {
    var clause = this.startNode();
    this.next();
    if (this.eat(types5.parenL)) {
      clause.param = this.parseBindingAtom();
      var simple3 = clause.param.type === "Identifier";
      this.enterScope(simple3 ? SCOPE_SIMPLE_CATCH : 0);
      this.checkLVal(clause.param, simple3 ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
      this.expect(types5.parenR);
    } else {
      if (this.options.ecmaVersion < 10) {
        this.unexpected();
      }
      clause.param = null;
      this.enterScope(0);
    }
    clause.body = this.parseBlock(false);
    this.exitScope();
    node.handler = this.finishNode(clause, "CatchClause");
  }
  node.finalizer = this.eat(types5._finally) ? this.parseBlock() : null;
  if (!node.handler && !node.finalizer) {
    this.raise(node.start, "Missing catch or finally clause");
  }
  return this.finishNode(node, "TryStatement");
};
pp$1.parseVarStatement = function(node, kind) {
  this.next();
  this.parseVar(node, false, kind);
  this.semicolon();
  return this.finishNode(node, "VariableDeclaration");
};
pp$1.parseWhileStatement = function(node) {
  this.next();
  node.test = this.parseParenExpression();
  this.labels.push(loopLabel);
  node.body = this.parseStatement("while");
  this.labels.pop();
  return this.finishNode(node, "WhileStatement");
};
pp$1.parseWithStatement = function(node) {
  if (this.strict) {
    this.raise(this.start, "'with' in strict mode");
  }
  this.next();
  node.object = this.parseParenExpression();
  node.body = this.parseStatement("with");
  return this.finishNode(node, "WithStatement");
};
pp$1.parseEmptyStatement = function(node) {
  this.next();
  return this.finishNode(node, "EmptyStatement");
};
pp$1.parseLabeledStatement = function(node, maybeName, expr, context) {
  for (var i$13 = 0, list = this.labels; i$13 < list.length; i$13 += 1) {
    var label = list[i$13];
    if (label.name === maybeName) {
      this.raise(expr.start, "Label '" + maybeName + "' is already declared");
    }
  }
  var kind = this.type.isLoop ? "loop" : this.type === types5._switch ? "switch" : null;
  for (var i6 = this.labels.length - 1; i6 >= 0; i6--) {
    var label$1 = this.labels[i6];
    if (label$1.statementStart === node.start) {
      label$1.statementStart = this.start;
      label$1.kind = kind;
    } else {
      break;
    }
  }
  this.labels.push({ name: maybeName, kind, statementStart: this.start });
  node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
  this.labels.pop();
  node.label = expr;
  return this.finishNode(node, "LabeledStatement");
};
pp$1.parseExpressionStatement = function(node, expr) {
  node.expression = expr;
  this.semicolon();
  return this.finishNode(node, "ExpressionStatement");
};
pp$1.parseBlock = function(createNewLexicalScope, node, exitStrict) {
  if (createNewLexicalScope === void 0)
    createNewLexicalScope = true;
  if (node === void 0)
    node = this.startNode();
  node.body = [];
  this.expect(types5.braceL);
  if (createNewLexicalScope) {
    this.enterScope(0);
  }
  while (this.type !== types5.braceR) {
    var stmt = this.parseStatement(null);
    node.body.push(stmt);
  }
  if (exitStrict) {
    this.strict = false;
  }
  this.next();
  if (createNewLexicalScope) {
    this.exitScope();
  }
  return this.finishNode(node, "BlockStatement");
};
pp$1.parseFor = function(node, init5) {
  node.init = init5;
  this.expect(types5.semi);
  node.test = this.type === types5.semi ? null : this.parseExpression();
  this.expect(types5.semi);
  node.update = this.type === types5.parenR ? null : this.parseExpression();
  this.expect(types5.parenR);
  node.body = this.parseStatement("for");
  this.exitScope();
  this.labels.pop();
  return this.finishNode(node, "ForStatement");
};
pp$1.parseForIn = function(node, init5) {
  var isForIn = this.type === types5._in;
  this.next();
  if (init5.type === "VariableDeclaration" && init5.declarations[0].init != null && (!isForIn || this.options.ecmaVersion < 8 || this.strict || init5.kind !== "var" || init5.declarations[0].id.type !== "Identifier")) {
    this.raise(init5.start, (isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer");
  } else if (init5.type === "AssignmentPattern") {
    this.raise(init5.start, "Invalid left-hand side in for-loop");
  }
  node.left = init5;
  node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
  this.expect(types5.parenR);
  node.body = this.parseStatement("for");
  this.exitScope();
  this.labels.pop();
  return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement");
};
pp$1.parseVar = function(node, isFor, kind) {
  node.declarations = [];
  node.kind = kind;
  for (; ; ) {
    var decl = this.startNode();
    this.parseVarId(decl, kind);
    if (this.eat(types5.eq)) {
      decl.init = this.parseMaybeAssign(isFor);
    } else if (kind === "const" && !(this.type === types5._in || this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
      this.unexpected();
    } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types5._in || this.isContextual("of")))) {
      this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
    } else {
      decl.init = null;
    }
    node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
    if (!this.eat(types5.comma)) {
      break;
    }
  }
  return node;
};
pp$1.parseVarId = function(decl, kind) {
  decl.id = this.parseBindingAtom();
  this.checkLVal(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);
};
var FUNC_STATEMENT = 1;
var FUNC_HANGING_STATEMENT = 2;
var FUNC_NULLABLE_ID = 4;
pp$1.parseFunction = function(node, statement, allowExpressionBody, isAsync2) {
  this.initFunction(node);
  if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync2) {
    if (this.type === types5.star && statement & FUNC_HANGING_STATEMENT) {
      this.unexpected();
    }
    node.generator = this.eat(types5.star);
  }
  if (this.options.ecmaVersion >= 8) {
    node.async = !!isAsync2;
  }
  if (statement & FUNC_STATEMENT) {
    node.id = statement & FUNC_NULLABLE_ID && this.type !== types5.name ? null : this.parseIdent();
    if (node.id && !(statement & FUNC_HANGING_STATEMENT)) {
      this.checkLVal(node.id, this.strict || node.generator || node.async ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION);
    }
  }
  var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  this.yieldPos = 0;
  this.awaitPos = 0;
  this.awaitIdentPos = 0;
  this.enterScope(functionFlags(node.async, node.generator));
  if (!(statement & FUNC_STATEMENT)) {
    node.id = this.type === types5.name ? this.parseIdent() : null;
  }
  this.parseFunctionParams(node);
  this.parseFunctionBody(node, allowExpressionBody, false);
  this.yieldPos = oldYieldPos;
  this.awaitPos = oldAwaitPos;
  this.awaitIdentPos = oldAwaitIdentPos;
  return this.finishNode(node, statement & FUNC_STATEMENT ? "FunctionDeclaration" : "FunctionExpression");
};
pp$1.parseFunctionParams = function(node) {
  this.expect(types5.parenL);
  node.params = this.parseBindingList(types5.parenR, false, this.options.ecmaVersion >= 8);
  this.checkYieldAwaitInDefaultParams();
};
pp$1.parseClass = function(node, isStatement) {
  this.next();
  var oldStrict = this.strict;
  this.strict = true;
  this.parseClassId(node, isStatement);
  this.parseClassSuper(node);
  var classBody = this.startNode();
  var hadConstructor = false;
  classBody.body = [];
  this.expect(types5.braceL);
  while (this.type !== types5.braceR) {
    var element = this.parseClassElement(node.superClass !== null);
    if (element) {
      classBody.body.push(element);
      if (element.type === "MethodDefinition" && element.kind === "constructor") {
        if (hadConstructor) {
          this.raise(element.start, "Duplicate constructor in the same class");
        }
        hadConstructor = true;
      }
    }
  }
  this.strict = oldStrict;
  this.next();
  node.body = this.finishNode(classBody, "ClassBody");
  return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");
};
pp$1.parseClassElement = function(constructorAllowsSuper) {
  var this$1 = this;
  if (this.eat(types5.semi)) {
    return null;
  }
  var method = this.startNode();
  var tryContextual = function(k3, noLineBreak) {
    if (noLineBreak === void 0)
      noLineBreak = false;
    var start = this$1.start, startLoc = this$1.startLoc;
    if (!this$1.eatContextual(k3)) {
      return false;
    }
    if (this$1.type !== types5.parenL && (!noLineBreak || !this$1.canInsertSemicolon())) {
      return true;
    }
    if (method.key) {
      this$1.unexpected();
    }
    method.computed = false;
    method.key = this$1.startNodeAt(start, startLoc);
    method.key.name = k3;
    this$1.finishNode(method.key, "Identifier");
    return false;
  };
  method.kind = "method";
  method.static = tryContextual("static");
  var isGenerator = this.eat(types5.star);
  var isAsync2 = false;
  if (!isGenerator) {
    if (this.options.ecmaVersion >= 8 && tryContextual("async", true)) {
      isAsync2 = true;
      isGenerator = this.options.ecmaVersion >= 9 && this.eat(types5.star);
    } else if (tryContextual("get")) {
      method.kind = "get";
    } else if (tryContextual("set")) {
      method.kind = "set";
    }
  }
  if (!method.key) {
    this.parsePropertyName(method);
  }
  var key = method.key;
  var allowsDirectSuper = false;
  if (!method.computed && !method.static && (key.type === "Identifier" && key.name === "constructor" || key.type === "Literal" && key.value === "constructor")) {
    if (method.kind !== "method") {
      this.raise(key.start, "Constructor can't have get/set modifier");
    }
    if (isGenerator) {
      this.raise(key.start, "Constructor can't be a generator");
    }
    if (isAsync2) {
      this.raise(key.start, "Constructor can't be an async method");
    }
    method.kind = "constructor";
    allowsDirectSuper = constructorAllowsSuper;
  } else if (method.static && key.type === "Identifier" && key.name === "prototype") {
    this.raise(key.start, "Classes may not have a static property named prototype");
  }
  this.parseClassMethod(method, isGenerator, isAsync2, allowsDirectSuper);
  if (method.kind === "get" && method.value.params.length !== 0) {
    this.raiseRecoverable(method.value.start, "getter should have no params");
  }
  if (method.kind === "set" && method.value.params.length !== 1) {
    this.raiseRecoverable(method.value.start, "setter should have exactly one param");
  }
  if (method.kind === "set" && method.value.params[0].type === "RestElement") {
    this.raiseRecoverable(method.value.params[0].start, "Setter cannot use rest params");
  }
  return method;
};
pp$1.parseClassMethod = function(method, isGenerator, isAsync2, allowsDirectSuper) {
  method.value = this.parseMethod(isGenerator, isAsync2, allowsDirectSuper);
  return this.finishNode(method, "MethodDefinition");
};
pp$1.parseClassId = function(node, isStatement) {
  if (this.type === types5.name) {
    node.id = this.parseIdent();
    if (isStatement) {
      this.checkLVal(node.id, BIND_LEXICAL, false);
    }
  } else {
    if (isStatement === true) {
      this.unexpected();
    }
    node.id = null;
  }
};
pp$1.parseClassSuper = function(node) {
  node.superClass = this.eat(types5._extends) ? this.parseExprSubscripts() : null;
};
pp$1.parseExport = function(node, exports23) {
  this.next();
  if (this.eat(types5.star)) {
    if (this.options.ecmaVersion >= 11) {
      if (this.eatContextual("as")) {
        node.exported = this.parseIdent(true);
        this.checkExport(exports23, node.exported.name, this.lastTokStart);
      } else {
        node.exported = null;
      }
    }
    this.expectContextual("from");
    if (this.type !== types5.string) {
      this.unexpected();
    }
    node.source = this.parseExprAtom();
    this.semicolon();
    return this.finishNode(node, "ExportAllDeclaration");
  }
  if (this.eat(types5._default)) {
    this.checkExport(exports23, "default", this.lastTokStart);
    var isAsync2;
    if (this.type === types5._function || (isAsync2 = this.isAsyncFunction())) {
      var fNode = this.startNode();
      this.next();
      if (isAsync2) {
        this.next();
      }
      node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync2);
    } else if (this.type === types5._class) {
      var cNode = this.startNode();
      node.declaration = this.parseClass(cNode, "nullableID");
    } else {
      node.declaration = this.parseMaybeAssign();
      this.semicolon();
    }
    return this.finishNode(node, "ExportDefaultDeclaration");
  }
  if (this.shouldParseExportStatement()) {
    node.declaration = this.parseStatement(null);
    if (node.declaration.type === "VariableDeclaration") {
      this.checkVariableExport(exports23, node.declaration.declarations);
    } else {
      this.checkExport(exports23, node.declaration.id.name, node.declaration.id.start);
    }
    node.specifiers = [];
    node.source = null;
  } else {
    node.declaration = null;
    node.specifiers = this.parseExportSpecifiers(exports23);
    if (this.eatContextual("from")) {
      if (this.type !== types5.string) {
        this.unexpected();
      }
      node.source = this.parseExprAtom();
    } else {
      for (var i6 = 0, list = node.specifiers; i6 < list.length; i6 += 1) {
        var spec = list[i6];
        this.checkUnreserved(spec.local);
        this.checkLocalExport(spec.local);
      }
      node.source = null;
    }
    this.semicolon();
  }
  return this.finishNode(node, "ExportNamedDeclaration");
};
pp$1.checkExport = function(exports23, name2, pos) {
  if (!exports23) {
    return;
  }
  if (has(exports23, name2)) {
    this.raiseRecoverable(pos, "Duplicate export '" + name2 + "'");
  }
  exports23[name2] = true;
};
pp$1.checkPatternExport = function(exports23, pat) {
  var type4 = pat.type;
  if (type4 === "Identifier") {
    this.checkExport(exports23, pat.name, pat.start);
  } else if (type4 === "ObjectPattern") {
    for (var i6 = 0, list = pat.properties; i6 < list.length; i6 += 1) {
      var prop = list[i6];
      this.checkPatternExport(exports23, prop);
    }
  } else if (type4 === "ArrayPattern") {
    for (var i$13 = 0, list$1 = pat.elements; i$13 < list$1.length; i$13 += 1) {
      var elt = list$1[i$13];
      if (elt) {
        this.checkPatternExport(exports23, elt);
      }
    }
  } else if (type4 === "Property") {
    this.checkPatternExport(exports23, pat.value);
  } else if (type4 === "AssignmentPattern") {
    this.checkPatternExport(exports23, pat.left);
  } else if (type4 === "RestElement") {
    this.checkPatternExport(exports23, pat.argument);
  } else if (type4 === "ParenthesizedExpression") {
    this.checkPatternExport(exports23, pat.expression);
  }
};
pp$1.checkVariableExport = function(exports23, decls) {
  if (!exports23) {
    return;
  }
  for (var i6 = 0, list = decls; i6 < list.length; i6 += 1) {
    var decl = list[i6];
    this.checkPatternExport(exports23, decl.id);
  }
};
pp$1.shouldParseExportStatement = function() {
  return this.type.keyword === "var" || this.type.keyword === "const" || this.type.keyword === "class" || this.type.keyword === "function" || this.isLet() || this.isAsyncFunction();
};
pp$1.parseExportSpecifiers = function(exports23) {
  var nodes = [], first = true;
  this.expect(types5.braceL);
  while (!this.eat(types5.braceR)) {
    if (!first) {
      this.expect(types5.comma);
      if (this.afterTrailingComma(types5.braceR)) {
        break;
      }
    } else {
      first = false;
    }
    var node = this.startNode();
    node.local = this.parseIdent(true);
    node.exported = this.eatContextual("as") ? this.parseIdent(true) : node.local;
    this.checkExport(exports23, node.exported.name, node.exported.start);
    nodes.push(this.finishNode(node, "ExportSpecifier"));
  }
  return nodes;
};
pp$1.parseImport = function(node) {
  this.next();
  if (this.type === types5.string) {
    node.specifiers = empty;
    node.source = this.parseExprAtom();
  } else {
    node.specifiers = this.parseImportSpecifiers();
    this.expectContextual("from");
    node.source = this.type === types5.string ? this.parseExprAtom() : this.unexpected();
  }
  this.semicolon();
  return this.finishNode(node, "ImportDeclaration");
};
pp$1.parseImportSpecifiers = function() {
  var nodes = [], first = true;
  if (this.type === types5.name) {
    var node = this.startNode();
    node.local = this.parseIdent();
    this.checkLVal(node.local, BIND_LEXICAL);
    nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));
    if (!this.eat(types5.comma)) {
      return nodes;
    }
  }
  if (this.type === types5.star) {
    var node$1 = this.startNode();
    this.next();
    this.expectContextual("as");
    node$1.local = this.parseIdent();
    this.checkLVal(node$1.local, BIND_LEXICAL);
    nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier"));
    return nodes;
  }
  this.expect(types5.braceL);
  while (!this.eat(types5.braceR)) {
    if (!first) {
      this.expect(types5.comma);
      if (this.afterTrailingComma(types5.braceR)) {
        break;
      }
    } else {
      first = false;
    }
    var node$2 = this.startNode();
    node$2.imported = this.parseIdent(true);
    if (this.eatContextual("as")) {
      node$2.local = this.parseIdent();
    } else {
      this.checkUnreserved(node$2.imported);
      node$2.local = node$2.imported;
    }
    this.checkLVal(node$2.local, BIND_LEXICAL);
    nodes.push(this.finishNode(node$2, "ImportSpecifier"));
  }
  return nodes;
};
pp$1.adaptDirectivePrologue = function(statements) {
  for (var i6 = 0; i6 < statements.length && this.isDirectiveCandidate(statements[i6]); ++i6) {
    statements[i6].directive = statements[i6].expression.raw.slice(1, -1);
  }
};
pp$1.isDirectiveCandidate = function(statement) {
  return statement.type === "ExpressionStatement" && statement.expression.type === "Literal" && typeof statement.expression.value === "string" && (this.input[statement.start] === '"' || this.input[statement.start] === "'");
};
var pp$2 = Parser2.prototype;
pp$2.toAssignable = function(node, isBinding, refDestructuringErrors) {
  if (this.options.ecmaVersion >= 6 && node) {
    switch (node.type) {
      case "Identifier":
        if (this.inAsync && node.name === "await") {
          this.raise(node.start, "Cannot use 'await' as identifier inside an async function");
        }
        break;
      case "ObjectPattern":
      case "ArrayPattern":
      case "RestElement":
        break;
      case "ObjectExpression":
        node.type = "ObjectPattern";
        if (refDestructuringErrors) {
          this.checkPatternErrors(refDestructuringErrors, true);
        }
        for (var i6 = 0, list = node.properties; i6 < list.length; i6 += 1) {
          var prop = list[i6];
          this.toAssignable(prop, isBinding);
          if (prop.type === "RestElement" && (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")) {
            this.raise(prop.argument.start, "Unexpected token");
          }
        }
        break;
      case "Property":
        if (node.kind !== "init") {
          this.raise(node.key.start, "Object pattern can't contain getter or setter");
        }
        this.toAssignable(node.value, isBinding);
        break;
      case "ArrayExpression":
        node.type = "ArrayPattern";
        if (refDestructuringErrors) {
          this.checkPatternErrors(refDestructuringErrors, true);
        }
        this.toAssignableList(node.elements, isBinding);
        break;
      case "SpreadElement":
        node.type = "RestElement";
        this.toAssignable(node.argument, isBinding);
        if (node.argument.type === "AssignmentPattern") {
          this.raise(node.argument.start, "Rest elements cannot have a default value");
        }
        break;
      case "AssignmentExpression":
        if (node.operator !== "=") {
          this.raise(node.left.end, "Only '=' operator can be used for specifying default value.");
        }
        node.type = "AssignmentPattern";
        delete node.operator;
        this.toAssignable(node.left, isBinding);
      case "AssignmentPattern":
        break;
      case "ParenthesizedExpression":
        this.toAssignable(node.expression, isBinding, refDestructuringErrors);
        break;
      case "ChainExpression":
        this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side");
        break;
      case "MemberExpression":
        if (!isBinding) {
          break;
        }
      default:
        this.raise(node.start, "Assigning to rvalue");
    }
  } else if (refDestructuringErrors) {
    this.checkPatternErrors(refDestructuringErrors, true);
  }
  return node;
};
pp$2.toAssignableList = function(exprList, isBinding) {
  var end = exprList.length;
  for (var i6 = 0; i6 < end; i6++) {
    var elt = exprList[i6];
    if (elt) {
      this.toAssignable(elt, isBinding);
    }
  }
  if (end) {
    var last = exprList[end - 1];
    if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier") {
      this.unexpected(last.argument.start);
    }
  }
  return exprList;
};
pp$2.parseSpread = function(refDestructuringErrors) {
  var node = this.startNode();
  this.next();
  node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  return this.finishNode(node, "SpreadElement");
};
pp$2.parseRestBinding = function() {
  var node = this.startNode();
  this.next();
  if (this.options.ecmaVersion === 6 && this.type !== types5.name) {
    this.unexpected();
  }
  node.argument = this.parseBindingAtom();
  return this.finishNode(node, "RestElement");
};
pp$2.parseBindingAtom = function() {
  if (this.options.ecmaVersion >= 6) {
    switch (this.type) {
      case types5.bracketL:
        var node = this.startNode();
        this.next();
        node.elements = this.parseBindingList(types5.bracketR, true, true);
        return this.finishNode(node, "ArrayPattern");
      case types5.braceL:
        return this.parseObj(true);
    }
  }
  return this.parseIdent();
};
pp$2.parseBindingList = function(close, allowEmpty, allowTrailingComma) {
  var elts = [], first = true;
  while (!this.eat(close)) {
    if (first) {
      first = false;
    } else {
      this.expect(types5.comma);
    }
    if (allowEmpty && this.type === types5.comma) {
      elts.push(null);
    } else if (allowTrailingComma && this.afterTrailingComma(close)) {
      break;
    } else if (this.type === types5.ellipsis) {
      var rest = this.parseRestBinding();
      this.parseBindingListItem(rest);
      elts.push(rest);
      if (this.type === types5.comma) {
        this.raise(this.start, "Comma is not permitted after the rest element");
      }
      this.expect(close);
      break;
    } else {
      var elem = this.parseMaybeDefault(this.start, this.startLoc);
      this.parseBindingListItem(elem);
      elts.push(elem);
    }
  }
  return elts;
};
pp$2.parseBindingListItem = function(param) {
  return param;
};
pp$2.parseMaybeDefault = function(startPos, startLoc, left) {
  left = left || this.parseBindingAtom();
  if (this.options.ecmaVersion < 6 || !this.eat(types5.eq)) {
    return left;
  }
  var node = this.startNodeAt(startPos, startLoc);
  node.left = left;
  node.right = this.parseMaybeAssign();
  return this.finishNode(node, "AssignmentPattern");
};
pp$2.checkLVal = function(expr, bindingType, checkClashes) {
  if (bindingType === void 0)
    bindingType = BIND_NONE;
  switch (expr.type) {
    case "Identifier":
      if (bindingType === BIND_LEXICAL && expr.name === "let") {
        this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name");
      }
      if (this.strict && this.reservedWordsStrictBind.test(expr.name)) {
        this.raiseRecoverable(expr.start, (bindingType ? "Binding " : "Assigning to ") + expr.name + " in strict mode");
      }
      if (checkClashes) {
        if (has(checkClashes, expr.name)) {
          this.raiseRecoverable(expr.start, "Argument name clash");
        }
        checkClashes[expr.name] = true;
      }
      if (bindingType !== BIND_NONE && bindingType !== BIND_OUTSIDE) {
        this.declareName(expr.name, bindingType, expr.start);
      }
      break;
    case "ChainExpression":
      this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side");
      break;
    case "MemberExpression":
      if (bindingType) {
        this.raiseRecoverable(expr.start, "Binding member expression");
      }
      break;
    case "ObjectPattern":
      for (var i6 = 0, list = expr.properties; i6 < list.length; i6 += 1) {
        var prop = list[i6];
        this.checkLVal(prop, bindingType, checkClashes);
      }
      break;
    case "Property":
      this.checkLVal(expr.value, bindingType, checkClashes);
      break;
    case "ArrayPattern":
      for (var i$13 = 0, list$1 = expr.elements; i$13 < list$1.length; i$13 += 1) {
        var elem = list$1[i$13];
        if (elem) {
          this.checkLVal(elem, bindingType, checkClashes);
        }
      }
      break;
    case "AssignmentPattern":
      this.checkLVal(expr.left, bindingType, checkClashes);
      break;
    case "RestElement":
      this.checkLVal(expr.argument, bindingType, checkClashes);
      break;
    case "ParenthesizedExpression":
      this.checkLVal(expr.expression, bindingType, checkClashes);
      break;
    default:
      this.raise(expr.start, (bindingType ? "Binding" : "Assigning to") + " rvalue");
  }
};
var pp$3 = Parser2.prototype;
pp$3.checkPropClash = function(prop, propHash, refDestructuringErrors) {
  if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement") {
    return;
  }
  if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) {
    return;
  }
  var key = prop.key;
  var name2;
  switch (key.type) {
    case "Identifier":
      name2 = key.name;
      break;
    case "Literal":
      name2 = String(key.value);
      break;
    default:
      return;
  }
  var kind = prop.kind;
  if (this.options.ecmaVersion >= 6) {
    if (name2 === "__proto__" && kind === "init") {
      if (propHash.proto) {
        if (refDestructuringErrors) {
          if (refDestructuringErrors.doubleProto < 0) {
            refDestructuringErrors.doubleProto = key.start;
          }
        } else {
          this.raiseRecoverable(key.start, "Redefinition of __proto__ property");
        }
      }
      propHash.proto = true;
    }
    return;
  }
  name2 = "$" + name2;
  var other = propHash[name2];
  if (other) {
    var redefinition;
    if (kind === "init") {
      redefinition = this.strict && other.init || other.get || other.set;
    } else {
      redefinition = other.init || other[kind];
    }
    if (redefinition) {
      this.raiseRecoverable(key.start, "Redefinition of property");
    }
  } else {
    other = propHash[name2] = {
      init: false,
      get: false,
      set: false
    };
  }
  other[kind] = true;
};
pp$3.parseExpression = function(noIn, refDestructuringErrors) {
  var startPos = this.start, startLoc = this.startLoc;
  var expr = this.parseMaybeAssign(noIn, refDestructuringErrors);
  if (this.type === types5.comma) {
    var node = this.startNodeAt(startPos, startLoc);
    node.expressions = [expr];
    while (this.eat(types5.comma)) {
      node.expressions.push(this.parseMaybeAssign(noIn, refDestructuringErrors));
    }
    return this.finishNode(node, "SequenceExpression");
  }
  return expr;
};
pp$3.parseMaybeAssign = function(noIn, refDestructuringErrors, afterLeftParse) {
  if (this.isContextual("yield")) {
    if (this.inGenerator) {
      return this.parseYield(noIn);
    } else {
      this.exprAllowed = false;
    }
  }
  var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1;
  if (refDestructuringErrors) {
    oldParenAssign = refDestructuringErrors.parenthesizedAssign;
    oldTrailingComma = refDestructuringErrors.trailingComma;
    refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
  } else {
    refDestructuringErrors = new DestructuringErrors();
    ownDestructuringErrors = true;
  }
  var startPos = this.start, startLoc = this.startLoc;
  if (this.type === types5.parenL || this.type === types5.name) {
    this.potentialArrowAt = this.start;
  }
  var left = this.parseMaybeConditional(noIn, refDestructuringErrors);
  if (afterLeftParse) {
    left = afterLeftParse.call(this, left, startPos, startLoc);
  }
  if (this.type.isAssign) {
    var node = this.startNodeAt(startPos, startLoc);
    node.operator = this.value;
    node.left = this.type === types5.eq ? this.toAssignable(left, false, refDestructuringErrors) : left;
    if (!ownDestructuringErrors) {
      refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;
    }
    if (refDestructuringErrors.shorthandAssign >= node.left.start) {
      refDestructuringErrors.shorthandAssign = -1;
    }
    this.checkLVal(left);
    this.next();
    node.right = this.parseMaybeAssign(noIn);
    return this.finishNode(node, "AssignmentExpression");
  } else {
    if (ownDestructuringErrors) {
      this.checkExpressionErrors(refDestructuringErrors, true);
    }
  }
  if (oldParenAssign > -1) {
    refDestructuringErrors.parenthesizedAssign = oldParenAssign;
  }
  if (oldTrailingComma > -1) {
    refDestructuringErrors.trailingComma = oldTrailingComma;
  }
  return left;
};
pp$3.parseMaybeConditional = function(noIn, refDestructuringErrors) {
  var startPos = this.start, startLoc = this.startLoc;
  var expr = this.parseExprOps(noIn, refDestructuringErrors);
  if (this.checkExpressionErrors(refDestructuringErrors)) {
    return expr;
  }
  if (this.eat(types5.question)) {
    var node = this.startNodeAt(startPos, startLoc);
    node.test = expr;
    node.consequent = this.parseMaybeAssign();
    this.expect(types5.colon);
    node.alternate = this.parseMaybeAssign(noIn);
    return this.finishNode(node, "ConditionalExpression");
  }
  return expr;
};
pp$3.parseExprOps = function(noIn, refDestructuringErrors) {
  var startPos = this.start, startLoc = this.startLoc;
  var expr = this.parseMaybeUnary(refDestructuringErrors, false);
  if (this.checkExpressionErrors(refDestructuringErrors)) {
    return expr;
  }
  return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, noIn);
};
pp$3.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, noIn) {
  var prec = this.type.binop;
  if (prec != null && (!noIn || this.type !== types5._in)) {
    if (prec > minPrec) {
      var logical = this.type === types5.logicalOR || this.type === types5.logicalAND;
      var coalesce = this.type === types5.coalesce;
      if (coalesce) {
        prec = types5.logicalAND.binop;
      }
      var op = this.value;
      this.next();
      var startPos = this.start, startLoc = this.startLoc;
      var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, noIn);
      var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);
      if (logical && this.type === types5.coalesce || coalesce && (this.type === types5.logicalOR || this.type === types5.logicalAND)) {
        this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");
      }
      return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn);
    }
  }
  return left;
};
pp$3.buildBinary = function(startPos, startLoc, left, right, op, logical) {
  var node = this.startNodeAt(startPos, startLoc);
  node.left = left;
  node.operator = op;
  node.right = right;
  return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression");
};
pp$3.parseMaybeUnary = function(refDestructuringErrors, sawUnary) {
  var startPos = this.start, startLoc = this.startLoc, expr;
  if (this.isContextual("await") && (this.inAsync || !this.inFunction && this.options.allowAwaitOutsideFunction)) {
    expr = this.parseAwait();
    sawUnary = true;
  } else if (this.type.prefix) {
    var node = this.startNode(), update = this.type === types5.incDec;
    node.operator = this.value;
    node.prefix = true;
    this.next();
    node.argument = this.parseMaybeUnary(null, true);
    this.checkExpressionErrors(refDestructuringErrors, true);
    if (update) {
      this.checkLVal(node.argument);
    } else if (this.strict && node.operator === "delete" && node.argument.type === "Identifier") {
      this.raiseRecoverable(node.start, "Deleting local variable in strict mode");
    } else {
      sawUnary = true;
    }
    expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
  } else {
    expr = this.parseExprSubscripts(refDestructuringErrors);
    if (this.checkExpressionErrors(refDestructuringErrors)) {
      return expr;
    }
    while (this.type.postfix && !this.canInsertSemicolon()) {
      var node$1 = this.startNodeAt(startPos, startLoc);
      node$1.operator = this.value;
      node$1.prefix = false;
      node$1.argument = expr;
      this.checkLVal(expr);
      this.next();
      expr = this.finishNode(node$1, "UpdateExpression");
    }
  }
  if (!sawUnary && this.eat(types5.starstar)) {
    return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false);
  } else {
    return expr;
  }
};
pp$3.parseExprSubscripts = function(refDestructuringErrors) {
  var startPos = this.start, startLoc = this.startLoc;
  var expr = this.parseExprAtom(refDestructuringErrors);
  if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")") {
    return expr;
  }
  var result2 = this.parseSubscripts(expr, startPos, startLoc);
  if (refDestructuringErrors && result2.type === "MemberExpression") {
    if (refDestructuringErrors.parenthesizedAssign >= result2.start) {
      refDestructuringErrors.parenthesizedAssign = -1;
    }
    if (refDestructuringErrors.parenthesizedBind >= result2.start) {
      refDestructuringErrors.parenthesizedBind = -1;
    }
  }
  return result2;
};
pp$3.parseSubscripts = function(base3, startPos, startLoc, noCalls) {
  var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base3.type === "Identifier" && base3.name === "async" && this.lastTokEnd === base3.end && !this.canInsertSemicolon() && base3.end - base3.start === 5 && this.potentialArrowAt === base3.start;
  var optionalChained = false;
  while (true) {
    var element = this.parseSubscript(base3, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained);
    if (element.optional) {
      optionalChained = true;
    }
    if (element === base3 || element.type === "ArrowFunctionExpression") {
      if (optionalChained) {
        var chainNode = this.startNodeAt(startPos, startLoc);
        chainNode.expression = element;
        element = this.finishNode(chainNode, "ChainExpression");
      }
      return element;
    }
    base3 = element;
  }
};
pp$3.parseSubscript = function(base3, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained) {
  var optionalSupported = this.options.ecmaVersion >= 11;
  var optional = optionalSupported && this.eat(types5.questionDot);
  if (noCalls && optional) {
    this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions");
  }
  var computed = this.eat(types5.bracketL);
  if (computed || optional && this.type !== types5.parenL && this.type !== types5.backQuote || this.eat(types5.dot)) {
    var node = this.startNodeAt(startPos, startLoc);
    node.object = base3;
    node.property = computed ? this.parseExpression() : this.parseIdent(this.options.allowReserved !== "never");
    node.computed = !!computed;
    if (computed) {
      this.expect(types5.bracketR);
    }
    if (optionalSupported) {
      node.optional = optional;
    }
    base3 = this.finishNode(node, "MemberExpression");
  } else if (!noCalls && this.eat(types5.parenL)) {
    var refDestructuringErrors = new DestructuringErrors(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
    this.yieldPos = 0;
    this.awaitPos = 0;
    this.awaitIdentPos = 0;
    var exprList = this.parseExprList(types5.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
    if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types5.arrow)) {
      this.checkPatternErrors(refDestructuringErrors, false);
      this.checkYieldAwaitInDefaultParams();
      if (this.awaitIdentPos > 0) {
        this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function");
      }
      this.yieldPos = oldYieldPos;
      this.awaitPos = oldAwaitPos;
      this.awaitIdentPos = oldAwaitIdentPos;
      return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true);
    }
    this.checkExpressionErrors(refDestructuringErrors, true);
    this.yieldPos = oldYieldPos || this.yieldPos;
    this.awaitPos = oldAwaitPos || this.awaitPos;
    this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
    var node$1 = this.startNodeAt(startPos, startLoc);
    node$1.callee = base3;
    node$1.arguments = exprList;
    if (optionalSupported) {
      node$1.optional = optional;
    }
    base3 = this.finishNode(node$1, "CallExpression");
  } else if (this.type === types5.backQuote) {
    if (optional || optionalChained) {
      this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions");
    }
    var node$2 = this.startNodeAt(startPos, startLoc);
    node$2.tag = base3;
    node$2.quasi = this.parseTemplate({ isTagged: true });
    base3 = this.finishNode(node$2, "TaggedTemplateExpression");
  }
  return base3;
};
pp$3.parseExprAtom = function(refDestructuringErrors) {
  if (this.type === types5.slash) {
    this.readRegexp();
  }
  var node, canBeArrow = this.potentialArrowAt === this.start;
  switch (this.type) {
    case types5._super:
      if (!this.allowSuper) {
        this.raise(this.start, "'super' keyword outside a method");
      }
      node = this.startNode();
      this.next();
      if (this.type === types5.parenL && !this.allowDirectSuper) {
        this.raise(node.start, "super() call outside constructor of a subclass");
      }
      if (this.type !== types5.dot && this.type !== types5.bracketL && this.type !== types5.parenL) {
        this.unexpected();
      }
      return this.finishNode(node, "Super");
    case types5._this:
      node = this.startNode();
      this.next();
      return this.finishNode(node, "ThisExpression");
    case types5.name:
      var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;
      var id = this.parseIdent(false);
      if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types5._function)) {
        return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true);
      }
      if (canBeArrow && !this.canInsertSemicolon()) {
        if (this.eat(types5.arrow)) {
          return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false);
        }
        if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types5.name && !containsEsc) {
          id = this.parseIdent(false);
          if (this.canInsertSemicolon() || !this.eat(types5.arrow)) {
            this.unexpected();
          }
          return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true);
        }
      }
      return id;
    case types5.regexp:
      var value = this.value;
      node = this.parseLiteral(value.value);
      node.regex = { pattern: value.pattern, flags: value.flags };
      return node;
    case types5.num:
    case types5.string:
      return this.parseLiteral(this.value);
    case types5._null:
    case types5._true:
    case types5._false:
      node = this.startNode();
      node.value = this.type === types5._null ? null : this.type === types5._true;
      node.raw = this.type.keyword;
      this.next();
      return this.finishNode(node, "Literal");
    case types5.parenL:
      var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow);
      if (refDestructuringErrors) {
        if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr)) {
          refDestructuringErrors.parenthesizedAssign = start;
        }
        if (refDestructuringErrors.parenthesizedBind < 0) {
          refDestructuringErrors.parenthesizedBind = start;
        }
      }
      return expr;
    case types5.bracketL:
      node = this.startNode();
      this.next();
      node.elements = this.parseExprList(types5.bracketR, true, true, refDestructuringErrors);
      return this.finishNode(node, "ArrayExpression");
    case types5.braceL:
      return this.parseObj(false, refDestructuringErrors);
    case types5._function:
      node = this.startNode();
      this.next();
      return this.parseFunction(node, 0);
    case types5._class:
      return this.parseClass(this.startNode(), false);
    case types5._new:
      return this.parseNew();
    case types5.backQuote:
      return this.parseTemplate();
    case types5._import:
      if (this.options.ecmaVersion >= 11) {
        return this.parseExprImport();
      } else {
        return this.unexpected();
      }
    default:
      this.unexpected();
  }
};
pp$3.parseExprImport = function() {
  var node = this.startNode();
  if (this.containsEsc) {
    this.raiseRecoverable(this.start, "Escape sequence in keyword import");
  }
  var meta = this.parseIdent(true);
  switch (this.type) {
    case types5.parenL:
      return this.parseDynamicImport(node);
    case types5.dot:
      node.meta = meta;
      return this.parseImportMeta(node);
    default:
      this.unexpected();
  }
};
pp$3.parseDynamicImport = function(node) {
  this.next();
  node.source = this.parseMaybeAssign();
  if (!this.eat(types5.parenR)) {
    var errorPos = this.start;
    if (this.eat(types5.comma) && this.eat(types5.parenR)) {
      this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
    } else {
      this.unexpected(errorPos);
    }
  }
  return this.finishNode(node, "ImportExpression");
};
pp$3.parseImportMeta = function(node) {
  this.next();
  var containsEsc = this.containsEsc;
  node.property = this.parseIdent(true);
  if (node.property.name !== "meta") {
    this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'");
  }
  if (containsEsc) {
    this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters");
  }
  if (this.options.sourceType !== "module") {
    this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module");
  }
  return this.finishNode(node, "MetaProperty");
};
pp$3.parseLiteral = function(value) {
  var node = this.startNode();
  node.value = value;
  node.raw = this.input.slice(this.start, this.end);
  if (node.raw.charCodeAt(node.raw.length - 1) === 110) {
    node.bigint = node.raw.slice(0, -1).replace(/_/g, "");
  }
  this.next();
  return this.finishNode(node, "Literal");
};
pp$3.parseParenExpression = function() {
  this.expect(types5.parenL);
  var val = this.parseExpression();
  this.expect(types5.parenR);
  return val;
};
pp$3.parseParenAndDistinguishExpression = function(canBeArrow) {
  var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
  if (this.options.ecmaVersion >= 6) {
    this.next();
    var innerStartPos = this.start, innerStartLoc = this.startLoc;
    var exprList = [], first = true, lastIsComma = false;
    var refDestructuringErrors = new DestructuringErrors(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;
    this.yieldPos = 0;
    this.awaitPos = 0;
    while (this.type !== types5.parenR) {
      first ? first = false : this.expect(types5.comma);
      if (allowTrailingComma && this.afterTrailingComma(types5.parenR, true)) {
        lastIsComma = true;
        break;
      } else if (this.type === types5.ellipsis) {
        spreadStart = this.start;
        exprList.push(this.parseParenItem(this.parseRestBinding()));
        if (this.type === types5.comma) {
          this.raise(this.start, "Comma is not permitted after the rest element");
        }
        break;
      } else {
        exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
      }
    }
    var innerEndPos = this.start, innerEndLoc = this.startLoc;
    this.expect(types5.parenR);
    if (canBeArrow && !this.canInsertSemicolon() && this.eat(types5.arrow)) {
      this.checkPatternErrors(refDestructuringErrors, false);
      this.checkYieldAwaitInDefaultParams();
      this.yieldPos = oldYieldPos;
      this.awaitPos = oldAwaitPos;
      return this.parseParenArrowList(startPos, startLoc, exprList);
    }
    if (!exprList.length || lastIsComma) {
      this.unexpected(this.lastTokStart);
    }
    if (spreadStart) {
      this.unexpected(spreadStart);
    }
    this.checkExpressionErrors(refDestructuringErrors, true);
    this.yieldPos = oldYieldPos || this.yieldPos;
    this.awaitPos = oldAwaitPos || this.awaitPos;
    if (exprList.length > 1) {
      val = this.startNodeAt(innerStartPos, innerStartLoc);
      val.expressions = exprList;
      this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
    } else {
      val = exprList[0];
    }
  } else {
    val = this.parseParenExpression();
  }
  if (this.options.preserveParens) {
    var par = this.startNodeAt(startPos, startLoc);
    par.expression = val;
    return this.finishNode(par, "ParenthesizedExpression");
  } else {
    return val;
  }
};
pp$3.parseParenItem = function(item) {
  return item;
};
pp$3.parseParenArrowList = function(startPos, startLoc, exprList) {
  return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList);
};
var empty$1 = [];
pp$3.parseNew = function() {
  if (this.containsEsc) {
    this.raiseRecoverable(this.start, "Escape sequence in keyword new");
  }
  var node = this.startNode();
  var meta = this.parseIdent(true);
  if (this.options.ecmaVersion >= 6 && this.eat(types5.dot)) {
    node.meta = meta;
    var containsEsc = this.containsEsc;
    node.property = this.parseIdent(true);
    if (node.property.name !== "target") {
      this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'");
    }
    if (containsEsc) {
      this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters");
    }
    if (!this.inNonArrowFunction()) {
      this.raiseRecoverable(node.start, "'new.target' can only be used in functions");
    }
    return this.finishNode(node, "MetaProperty");
  }
  var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types5._import;
  node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
  if (isImport && node.callee.type === "ImportExpression") {
    this.raise(startPos, "Cannot use new with import()");
  }
  if (this.eat(types5.parenL)) {
    node.arguments = this.parseExprList(types5.parenR, this.options.ecmaVersion >= 8, false);
  } else {
    node.arguments = empty$1;
  }
  return this.finishNode(node, "NewExpression");
};
pp$3.parseTemplateElement = function(ref22) {
  var isTagged = ref22.isTagged;
  var elem = this.startNode();
  if (this.type === types5.invalidTemplate) {
    if (!isTagged) {
      this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
    }
    elem.value = {
      raw: this.value,
      cooked: null
    };
  } else {
    elem.value = {
      raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
      cooked: this.value
    };
  }
  this.next();
  elem.tail = this.type === types5.backQuote;
  return this.finishNode(elem, "TemplateElement");
};
pp$3.parseTemplate = function(ref22) {
  if (ref22 === void 0)
    ref22 = {};
  var isTagged = ref22.isTagged;
  if (isTagged === void 0)
    isTagged = false;
  var node = this.startNode();
  this.next();
  node.expressions = [];
  var curElt = this.parseTemplateElement({ isTagged });
  node.quasis = [curElt];
  while (!curElt.tail) {
    if (this.type === types5.eof) {
      this.raise(this.pos, "Unterminated template literal");
    }
    this.expect(types5.dollarBraceL);
    node.expressions.push(this.parseExpression());
    this.expect(types5.braceR);
    node.quasis.push(curElt = this.parseTemplateElement({ isTagged }));
  }
  this.next();
  return this.finishNode(node, "TemplateLiteral");
};
pp$3.isAsyncProp = function(prop) {
  return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" && (this.type === types5.name || this.type === types5.num || this.type === types5.string || this.type === types5.bracketL || this.type.keyword || this.options.ecmaVersion >= 9 && this.type === types5.star) && !lineBreak.test(this.input.slice(this.lastTokEnd, this.start));
};
pp$3.parseObj = function(isPattern, refDestructuringErrors) {
  var node = this.startNode(), first = true, propHash = {};
  node.properties = [];
  this.next();
  while (!this.eat(types5.braceR)) {
    if (!first) {
      this.expect(types5.comma);
      if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types5.braceR)) {
        break;
      }
    } else {
      first = false;
    }
    var prop = this.parseProperty(isPattern, refDestructuringErrors);
    if (!isPattern) {
      this.checkPropClash(prop, propHash, refDestructuringErrors);
    }
    node.properties.push(prop);
  }
  return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression");
};
pp$3.parseProperty = function(isPattern, refDestructuringErrors) {
  var prop = this.startNode(), isGenerator, isAsync2, startPos, startLoc;
  if (this.options.ecmaVersion >= 9 && this.eat(types5.ellipsis)) {
    if (isPattern) {
      prop.argument = this.parseIdent(false);
      if (this.type === types5.comma) {
        this.raise(this.start, "Comma is not permitted after the rest element");
      }
      return this.finishNode(prop, "RestElement");
    }
    if (this.type === types5.parenL && refDestructuringErrors) {
      if (refDestructuringErrors.parenthesizedAssign < 0) {
        refDestructuringErrors.parenthesizedAssign = this.start;
      }
      if (refDestructuringErrors.parenthesizedBind < 0) {
        refDestructuringErrors.parenthesizedBind = this.start;
      }
    }
    prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
    if (this.type === types5.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
      refDestructuringErrors.trailingComma = this.start;
    }
    return this.finishNode(prop, "SpreadElement");
  }
  if (this.options.ecmaVersion >= 6) {
    prop.method = false;
    prop.shorthand = false;
    if (isPattern || refDestructuringErrors) {
      startPos = this.start;
      startLoc = this.startLoc;
    }
    if (!isPattern) {
      isGenerator = this.eat(types5.star);
    }
  }
  var containsEsc = this.containsEsc;
  this.parsePropertyName(prop);
  if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
    isAsync2 = true;
    isGenerator = this.options.ecmaVersion >= 9 && this.eat(types5.star);
    this.parsePropertyName(prop, refDestructuringErrors);
  } else {
    isAsync2 = false;
  }
  this.parsePropertyValue(prop, isPattern, isGenerator, isAsync2, startPos, startLoc, refDestructuringErrors, containsEsc);
  return this.finishNode(prop, "Property");
};
pp$3.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync2, startPos, startLoc, refDestructuringErrors, containsEsc) {
  if ((isGenerator || isAsync2) && this.type === types5.colon) {
    this.unexpected();
  }
  if (this.eat(types5.colon)) {
    prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
    prop.kind = "init";
  } else if (this.options.ecmaVersion >= 6 && this.type === types5.parenL) {
    if (isPattern) {
      this.unexpected();
    }
    prop.kind = "init";
    prop.method = true;
    prop.value = this.parseMethod(isGenerator, isAsync2);
  } else if (!isPattern && !containsEsc && this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && (prop.key.name === "get" || prop.key.name === "set") && (this.type !== types5.comma && this.type !== types5.braceR && this.type !== types5.eq)) {
    if (isGenerator || isAsync2) {
      this.unexpected();
    }
    prop.kind = prop.key.name;
    this.parsePropertyName(prop);
    prop.value = this.parseMethod(false);
    var paramCount = prop.kind === "get" ? 0 : 1;
    if (prop.value.params.length !== paramCount) {
      var start = prop.value.start;
      if (prop.kind === "get") {
        this.raiseRecoverable(start, "getter should have no params");
      } else {
        this.raiseRecoverable(start, "setter should have exactly one param");
      }
    } else {
      if (prop.kind === "set" && prop.value.params[0].type === "RestElement") {
        this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params");
      }
    }
  } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
    if (isGenerator || isAsync2) {
      this.unexpected();
    }
    this.checkUnreserved(prop.key);
    if (prop.key.name === "await" && !this.awaitIdentPos) {
      this.awaitIdentPos = startPos;
    }
    prop.kind = "init";
    if (isPattern) {
      prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key);
    } else if (this.type === types5.eq && refDestructuringErrors) {
      if (refDestructuringErrors.shorthandAssign < 0) {
        refDestructuringErrors.shorthandAssign = this.start;
      }
      prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key);
    } else {
      prop.value = prop.key;
    }
    prop.shorthand = true;
  } else {
    this.unexpected();
  }
};
pp$3.parsePropertyName = function(prop) {
  if (this.options.ecmaVersion >= 6) {
    if (this.eat(types5.bracketL)) {
      prop.computed = true;
      prop.key = this.parseMaybeAssign();
      this.expect(types5.bracketR);
      return prop.key;
    } else {
      prop.computed = false;
    }
  }
  return prop.key = this.type === types5.num || this.type === types5.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never");
};
pp$3.initFunction = function(node) {
  node.id = null;
  if (this.options.ecmaVersion >= 6) {
    node.generator = node.expression = false;
  }
  if (this.options.ecmaVersion >= 8) {
    node.async = false;
  }
};
pp$3.parseMethod = function(isGenerator, isAsync2, allowDirectSuper) {
  var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  this.initFunction(node);
  if (this.options.ecmaVersion >= 6) {
    node.generator = isGenerator;
  }
  if (this.options.ecmaVersion >= 8) {
    node.async = !!isAsync2;
  }
  this.yieldPos = 0;
  this.awaitPos = 0;
  this.awaitIdentPos = 0;
  this.enterScope(functionFlags(isAsync2, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
  this.expect(types5.parenL);
  node.params = this.parseBindingList(types5.parenR, false, this.options.ecmaVersion >= 8);
  this.checkYieldAwaitInDefaultParams();
  this.parseFunctionBody(node, false, true);
  this.yieldPos = oldYieldPos;
  this.awaitPos = oldAwaitPos;
  this.awaitIdentPos = oldAwaitIdentPos;
  return this.finishNode(node, "FunctionExpression");
};
pp$3.parseArrowExpression = function(node, params, isAsync2) {
  var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  this.enterScope(functionFlags(isAsync2, false) | SCOPE_ARROW);
  this.initFunction(node);
  if (this.options.ecmaVersion >= 8) {
    node.async = !!isAsync2;
  }
  this.yieldPos = 0;
  this.awaitPos = 0;
  this.awaitIdentPos = 0;
  node.params = this.toAssignableList(params, true);
  this.parseFunctionBody(node, true, false);
  this.yieldPos = oldYieldPos;
  this.awaitPos = oldAwaitPos;
  this.awaitIdentPos = oldAwaitIdentPos;
  return this.finishNode(node, "ArrowFunctionExpression");
};
pp$3.parseFunctionBody = function(node, isArrowFunction, isMethod) {
  var isExpression = isArrowFunction && this.type !== types5.braceL;
  var oldStrict = this.strict, useStrict = false;
  if (isExpression) {
    node.body = this.parseMaybeAssign();
    node.expression = true;
    this.checkParams(node, false);
  } else {
    var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
    if (!oldStrict || nonSimple) {
      useStrict = this.strictDirective(this.end);
      if (useStrict && nonSimple) {
        this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list");
      }
    }
    var oldLabels = this.labels;
    this.labels = [];
    if (useStrict) {
      this.strict = true;
    }
    this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));
    if (this.strict && node.id) {
      this.checkLVal(node.id, BIND_OUTSIDE);
    }
    node.body = this.parseBlock(false, void 0, useStrict && !oldStrict);
    node.expression = false;
    this.adaptDirectivePrologue(node.body.body);
    this.labels = oldLabels;
  }
  this.exitScope();
};
pp$3.isSimpleParamList = function(params) {
  for (var i6 = 0, list = params; i6 < list.length; i6 += 1) {
    var param = list[i6];
    if (param.type !== "Identifier") {
      return false;
    }
  }
  return true;
};
pp$3.checkParams = function(node, allowDuplicates) {
  var nameHash = {};
  for (var i6 = 0, list = node.params; i6 < list.length; i6 += 1) {
    var param = list[i6];
    this.checkLVal(param, BIND_VAR, allowDuplicates ? null : nameHash);
  }
};
pp$3.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
  var elts = [], first = true;
  while (!this.eat(close)) {
    if (!first) {
      this.expect(types5.comma);
      if (allowTrailingComma && this.afterTrailingComma(close)) {
        break;
      }
    } else {
      first = false;
    }
    var elt = void 0;
    if (allowEmpty && this.type === types5.comma) {
      elt = null;
    } else if (this.type === types5.ellipsis) {
      elt = this.parseSpread(refDestructuringErrors);
      if (refDestructuringErrors && this.type === types5.comma && refDestructuringErrors.trailingComma < 0) {
        refDestructuringErrors.trailingComma = this.start;
      }
    } else {
      elt = this.parseMaybeAssign(false, refDestructuringErrors);
    }
    elts.push(elt);
  }
  return elts;
};
pp$3.checkUnreserved = function(ref22) {
  var start = ref22.start;
  var end = ref22.end;
  var name2 = ref22.name;
  if (this.inGenerator && name2 === "yield") {
    this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator");
  }
  if (this.inAsync && name2 === "await") {
    this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function");
  }
  if (this.keywords.test(name2)) {
    this.raise(start, "Unexpected keyword '" + name2 + "'");
  }
  if (this.options.ecmaVersion < 6 && this.input.slice(start, end).indexOf("\\") !== -1) {
    return;
  }
  var re3 = this.strict ? this.reservedWordsStrict : this.reservedWords;
  if (re3.test(name2)) {
    if (!this.inAsync && name2 === "await") {
      this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function");
    }
    this.raiseRecoverable(start, "The keyword '" + name2 + "' is reserved");
  }
};
pp$3.parseIdent = function(liberal, isBinding) {
  var node = this.startNode();
  if (this.type === types5.name) {
    node.name = this.value;
  } else if (this.type.keyword) {
    node.name = this.type.keyword;
    if ((node.name === "class" || node.name === "function") && (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
      this.context.pop();
    }
  } else {
    this.unexpected();
  }
  this.next(!!liberal);
  this.finishNode(node, "Identifier");
  if (!liberal) {
    this.checkUnreserved(node);
    if (node.name === "await" && !this.awaitIdentPos) {
      this.awaitIdentPos = node.start;
    }
  }
  return node;
};
pp$3.parseYield = function(noIn) {
  if (!this.yieldPos) {
    this.yieldPos = this.start;
  }
  var node = this.startNode();
  this.next();
  if (this.type === types5.semi || this.canInsertSemicolon() || this.type !== types5.star && !this.type.startsExpr) {
    node.delegate = false;
    node.argument = null;
  } else {
    node.delegate = this.eat(types5.star);
    node.argument = this.parseMaybeAssign(noIn);
  }
  return this.finishNode(node, "YieldExpression");
};
pp$3.parseAwait = function() {
  if (!this.awaitPos) {
    this.awaitPos = this.start;
  }
  var node = this.startNode();
  this.next();
  node.argument = this.parseMaybeUnary(null, false);
  return this.finishNode(node, "AwaitExpression");
};
var pp$4 = Parser2.prototype;
pp$4.raise = function(pos, message) {
  var loc = getLineInfo(this.input, pos);
  message += " (" + loc.line + ":" + loc.column + ")";
  var err2 = new SyntaxError(message);
  err2.pos = pos;
  err2.loc = loc;
  err2.raisedAt = this.pos;
  throw err2;
};
pp$4.raiseRecoverable = pp$4.raise;
pp$4.curPosition = function() {
  if (this.options.locations) {
    return new Position(this.curLine, this.pos - this.lineStart);
  }
};
var pp$5 = Parser2.prototype;
var Scope = function Scope2(flags) {
  this.flags = flags;
  this.var = [];
  this.lexical = [];
  this.functions = [];
};
pp$5.enterScope = function(flags) {
  this.scopeStack.push(new Scope(flags));
};
pp$5.exitScope = function() {
  this.scopeStack.pop();
};
pp$5.treatFunctionsAsVarInScope = function(scope) {
  return scope.flags & SCOPE_FUNCTION || !this.inModule && scope.flags & SCOPE_TOP;
};
pp$5.declareName = function(name2, bindingType, pos) {
  var redeclared = false;
  if (bindingType === BIND_LEXICAL) {
    var scope = this.currentScope();
    redeclared = scope.lexical.indexOf(name2) > -1 || scope.functions.indexOf(name2) > -1 || scope.var.indexOf(name2) > -1;
    scope.lexical.push(name2);
    if (this.inModule && scope.flags & SCOPE_TOP) {
      delete this.undefinedExports[name2];
    }
  } else if (bindingType === BIND_SIMPLE_CATCH) {
    var scope$1 = this.currentScope();
    scope$1.lexical.push(name2);
  } else if (bindingType === BIND_FUNCTION) {
    var scope$2 = this.currentScope();
    if (this.treatFunctionsAsVar) {
      redeclared = scope$2.lexical.indexOf(name2) > -1;
    } else {
      redeclared = scope$2.lexical.indexOf(name2) > -1 || scope$2.var.indexOf(name2) > -1;
    }
    scope$2.functions.push(name2);
  } else {
    for (var i6 = this.scopeStack.length - 1; i6 >= 0; --i6) {
      var scope$3 = this.scopeStack[i6];
      if (scope$3.lexical.indexOf(name2) > -1 && !(scope$3.flags & SCOPE_SIMPLE_CATCH && scope$3.lexical[0] === name2) || !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name2) > -1) {
        redeclared = true;
        break;
      }
      scope$3.var.push(name2);
      if (this.inModule && scope$3.flags & SCOPE_TOP) {
        delete this.undefinedExports[name2];
      }
      if (scope$3.flags & SCOPE_VAR) {
        break;
      }
    }
  }
  if (redeclared) {
    this.raiseRecoverable(pos, "Identifier '" + name2 + "' has already been declared");
  }
};
pp$5.checkLocalExport = function(id) {
  if (this.scopeStack[0].lexical.indexOf(id.name) === -1 && this.scopeStack[0].var.indexOf(id.name) === -1) {
    this.undefinedExports[id.name] = id;
  }
};
pp$5.currentScope = function() {
  return this.scopeStack[this.scopeStack.length - 1];
};
pp$5.currentVarScope = function() {
  for (var i6 = this.scopeStack.length - 1; ; i6--) {
    var scope = this.scopeStack[i6];
    if (scope.flags & SCOPE_VAR) {
      return scope;
    }
  }
};
pp$5.currentThisScope = function() {
  for (var i6 = this.scopeStack.length - 1; ; i6--) {
    var scope = this.scopeStack[i6];
    if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) {
      return scope;
    }
  }
};
var Node4 = function Node22(parser, pos, loc) {
  this.type = "";
  this.start = pos;
  this.end = 0;
  if (parser.options.locations) {
    this.loc = new SourceLocation(parser, loc);
  }
  if (parser.options.directSourceFile) {
    this.sourceFile = parser.options.directSourceFile;
  }
  if (parser.options.ranges) {
    this.range = [pos, 0];
  }
};
var pp$6 = Parser2.prototype;
pp$6.startNode = function() {
  return new Node4(this, this.start, this.startLoc);
};
pp$6.startNodeAt = function(pos, loc) {
  return new Node4(this, pos, loc);
};
function finishNodeAt(node, type4, pos, loc) {
  node.type = type4;
  node.end = pos;
  if (this.options.locations) {
    node.loc.end = loc;
  }
  if (this.options.ranges) {
    node.range[1] = pos;
  }
  return node;
}
pp$6.finishNode = function(node, type4) {
  return finishNodeAt.call(this, node, type4, this.lastTokEnd, this.lastTokEndLoc);
};
pp$6.finishNodeAt = function(node, type4, pos, loc) {
  return finishNodeAt.call(this, node, type4, pos, loc);
};
var TokContext = function TokContext2(token, isExpr, preserveSpace, override, generator) {
  this.token = token;
  this.isExpr = !!isExpr;
  this.preserveSpace = !!preserveSpace;
  this.override = override;
  this.generator = !!generator;
};
var types$1 = {
  b_stat: new TokContext("{", false),
  b_expr: new TokContext("{", true),
  b_tmpl: new TokContext("${", false),
  p_stat: new TokContext("(", false),
  p_expr: new TokContext("(", true),
  q_tmpl: new TokContext("`", true, true, function(p5) {
    return p5.tryReadTemplateToken();
  }),
  f_stat: new TokContext("function", false),
  f_expr: new TokContext("function", true),
  f_expr_gen: new TokContext("function", true, false, null, true),
  f_gen: new TokContext("function", false, false, null, true)
};
var pp$7 = Parser2.prototype;
pp$7.initialContext = function() {
  return [types$1.b_stat];
};
pp$7.braceIsBlock = function(prevType) {
  var parent = this.curContext();
  if (parent === types$1.f_expr || parent === types$1.f_stat) {
    return true;
  }
  if (prevType === types5.colon && (parent === types$1.b_stat || parent === types$1.b_expr)) {
    return !parent.isExpr;
  }
  if (prevType === types5._return || prevType === types5.name && this.exprAllowed) {
    return lineBreak.test(this.input.slice(this.lastTokEnd, this.start));
  }
  if (prevType === types5._else || prevType === types5.semi || prevType === types5.eof || prevType === types5.parenR || prevType === types5.arrow) {
    return true;
  }
  if (prevType === types5.braceL) {
    return parent === types$1.b_stat;
  }
  if (prevType === types5._var || prevType === types5._const || prevType === types5.name) {
    return false;
  }
  return !this.exprAllowed;
};
pp$7.inGeneratorContext = function() {
  for (var i6 = this.context.length - 1; i6 >= 1; i6--) {
    var context = this.context[i6];
    if (context.token === "function") {
      return context.generator;
    }
  }
  return false;
};
pp$7.updateContext = function(prevType) {
  var update, type4 = this.type;
  if (type4.keyword && prevType === types5.dot) {
    this.exprAllowed = false;
  } else if (update = type4.updateContext) {
    update.call(this, prevType);
  } else {
    this.exprAllowed = type4.beforeExpr;
  }
};
types5.parenR.updateContext = types5.braceR.updateContext = function() {
  if (this.context.length === 1) {
    this.exprAllowed = true;
    return;
  }
  var out = this.context.pop();
  if (out === types$1.b_stat && this.curContext().token === "function") {
    out = this.context.pop();
  }
  this.exprAllowed = !out.isExpr;
};
types5.braceL.updateContext = function(prevType) {
  this.context.push(this.braceIsBlock(prevType) ? types$1.b_stat : types$1.b_expr);
  this.exprAllowed = true;
};
types5.dollarBraceL.updateContext = function() {
  this.context.push(types$1.b_tmpl);
  this.exprAllowed = true;
};
types5.parenL.updateContext = function(prevType) {
  var statementParens = prevType === types5._if || prevType === types5._for || prevType === types5._with || prevType === types5._while;
  this.context.push(statementParens ? types$1.p_stat : types$1.p_expr);
  this.exprAllowed = true;
};
types5.incDec.updateContext = function() {
};
types5._function.updateContext = types5._class.updateContext = function(prevType) {
  if (prevType.beforeExpr && prevType !== types5.semi && prevType !== types5._else && !(prevType === types5._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) && !((prevType === types5.colon || prevType === types5.braceL) && this.curContext() === types$1.b_stat)) {
    this.context.push(types$1.f_expr);
  } else {
    this.context.push(types$1.f_stat);
  }
  this.exprAllowed = false;
};
types5.backQuote.updateContext = function() {
  if (this.curContext() === types$1.q_tmpl) {
    this.context.pop();
  } else {
    this.context.push(types$1.q_tmpl);
  }
  this.exprAllowed = false;
};
types5.star.updateContext = function(prevType) {
  if (prevType === types5._function) {
    var index2 = this.context.length - 1;
    if (this.context[index2] === types$1.f_expr) {
      this.context[index2] = types$1.f_expr_gen;
    } else {
      this.context[index2] = types$1.f_gen;
    }
  }
  this.exprAllowed = true;
};
types5.name.updateContext = function(prevType) {
  var allowed = false;
  if (this.options.ecmaVersion >= 6 && prevType !== types5.dot) {
    if (this.value === "of" && !this.exprAllowed || this.value === "yield" && this.inGeneratorContext()) {
      allowed = true;
    }
  }
  this.exprAllowed = allowed;
};
var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";
var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic";
var ecma11BinaryProperties = ecma10BinaryProperties;
var unicodeBinaryProperties = {
  9: ecma9BinaryProperties,
  10: ecma10BinaryProperties,
  11: ecma11BinaryProperties
};
var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu";
var ecma9ScriptValues = "Adlam Adlm Ahom Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb";
var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
var unicodeScriptValues = {
  9: ecma9ScriptValues,
  10: ecma10ScriptValues,
  11: ecma11ScriptValues
};
var data = {};
function buildUnicodeData(ecmaVersion) {
  var d4 = data[ecmaVersion] = {
    binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues),
    nonBinary: {
      General_Category: wordsRegexp(unicodeGeneralCategoryValues),
      Script: wordsRegexp(unicodeScriptValues[ecmaVersion])
    }
  };
  d4.nonBinary.Script_Extensions = d4.nonBinary.Script;
  d4.nonBinary.gc = d4.nonBinary.General_Category;
  d4.nonBinary.sc = d4.nonBinary.Script;
  d4.nonBinary.scx = d4.nonBinary.Script_Extensions;
}
buildUnicodeData(9);
buildUnicodeData(10);
buildUnicodeData(11);
var pp$8 = Parser2.prototype;
var RegExpValidationState = function RegExpValidationState2(parser) {
  this.parser = parser;
  this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "");
  this.unicodeProperties = data[parser.options.ecmaVersion >= 11 ? 11 : parser.options.ecmaVersion];
  this.source = "";
  this.flags = "";
  this.start = 0;
  this.switchU = false;
  this.switchN = false;
  this.pos = 0;
  this.lastIntValue = 0;
  this.lastStringValue = "";
  this.lastAssertionIsQuantifiable = false;
  this.numCapturingParens = 0;
  this.maxBackReference = 0;
  this.groupNames = [];
  this.backReferenceNames = [];
};
RegExpValidationState.prototype.reset = function reset2(start, pattern, flags) {
  var unicode = flags.indexOf("u") !== -1;
  this.start = start | 0;
  this.source = pattern + "";
  this.flags = flags;
  this.switchU = unicode && this.parser.options.ecmaVersion >= 6;
  this.switchN = unicode && this.parser.options.ecmaVersion >= 9;
};
RegExpValidationState.prototype.raise = function raise(message) {
  this.parser.raiseRecoverable(this.start, "Invalid regular expression: /" + this.source + "/: " + message);
};
RegExpValidationState.prototype.at = function at(i6, forceU) {
  if (forceU === void 0)
    forceU = false;
  var s5 = this.source;
  var l6 = s5.length;
  if (i6 >= l6) {
    return -1;
  }
  var c6 = s5.charCodeAt(i6);
  if (!(forceU || this.switchU) || c6 <= 55295 || c6 >= 57344 || i6 + 1 >= l6) {
    return c6;
  }
  var next = s5.charCodeAt(i6 + 1);
  return next >= 56320 && next <= 57343 ? (c6 << 10) + next - 56613888 : c6;
};
RegExpValidationState.prototype.nextIndex = function nextIndex(i6, forceU) {
  if (forceU === void 0)
    forceU = false;
  var s5 = this.source;
  var l6 = s5.length;
  if (i6 >= l6) {
    return l6;
  }
  var c6 = s5.charCodeAt(i6), next;
  if (!(forceU || this.switchU) || c6 <= 55295 || c6 >= 57344 || i6 + 1 >= l6 || (next = s5.charCodeAt(i6 + 1)) < 56320 || next > 57343) {
    return i6 + 1;
  }
  return i6 + 2;
};
RegExpValidationState.prototype.current = function current(forceU) {
  if (forceU === void 0)
    forceU = false;
  return this.at(this.pos, forceU);
};
RegExpValidationState.prototype.lookahead = function lookahead(forceU) {
  if (forceU === void 0)
    forceU = false;
  return this.at(this.nextIndex(this.pos, forceU), forceU);
};
RegExpValidationState.prototype.advance = function advance(forceU) {
  if (forceU === void 0)
    forceU = false;
  this.pos = this.nextIndex(this.pos, forceU);
};
RegExpValidationState.prototype.eat = function eat(ch, forceU) {
  if (forceU === void 0)
    forceU = false;
  if (this.current(forceU) === ch) {
    this.advance(forceU);
    return true;
  }
  return false;
};
function codePointToString(ch) {
  if (ch <= 65535) {
    return String.fromCharCode(ch);
  }
  ch -= 65536;
  return String.fromCharCode((ch >> 10) + 55296, (ch & 1023) + 56320);
}
pp$8.validateRegExpFlags = function(state2) {
  var validFlags = state2.validFlags;
  var flags = state2.flags;
  for (var i6 = 0; i6 < flags.length; i6++) {
    var flag = flags.charAt(i6);
    if (validFlags.indexOf(flag) === -1) {
      this.raise(state2.start, "Invalid regular expression flag");
    }
    if (flags.indexOf(flag, i6 + 1) > -1) {
      this.raise(state2.start, "Duplicate regular expression flag");
    }
  }
};
pp$8.validateRegExpPattern = function(state2) {
  this.regexp_pattern(state2);
  if (!state2.switchN && this.options.ecmaVersion >= 9 && state2.groupNames.length > 0) {
    state2.switchN = true;
    this.regexp_pattern(state2);
  }
};
pp$8.regexp_pattern = function(state2) {
  state2.pos = 0;
  state2.lastIntValue = 0;
  state2.lastStringValue = "";
  state2.lastAssertionIsQuantifiable = false;
  state2.numCapturingParens = 0;
  state2.maxBackReference = 0;
  state2.groupNames.length = 0;
  state2.backReferenceNames.length = 0;
  this.regexp_disjunction(state2);
  if (state2.pos !== state2.source.length) {
    if (state2.eat(41)) {
      state2.raise("Unmatched ')'");
    }
    if (state2.eat(93) || state2.eat(125)) {
      state2.raise("Lone quantifier brackets");
    }
  }
  if (state2.maxBackReference > state2.numCapturingParens) {
    state2.raise("Invalid escape");
  }
  for (var i6 = 0, list = state2.backReferenceNames; i6 < list.length; i6 += 1) {
    var name2 = list[i6];
    if (state2.groupNames.indexOf(name2) === -1) {
      state2.raise("Invalid named capture referenced");
    }
  }
};
pp$8.regexp_disjunction = function(state2) {
  this.regexp_alternative(state2);
  while (state2.eat(124)) {
    this.regexp_alternative(state2);
  }
  if (this.regexp_eatQuantifier(state2, true)) {
    state2.raise("Nothing to repeat");
  }
  if (state2.eat(123)) {
    state2.raise("Lone quantifier brackets");
  }
};
pp$8.regexp_alternative = function(state2) {
  while (state2.pos < state2.source.length && this.regexp_eatTerm(state2)) {
  }
};
pp$8.regexp_eatTerm = function(state2) {
  if (this.regexp_eatAssertion(state2)) {
    if (state2.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state2)) {
      if (state2.switchU) {
        state2.raise("Invalid quantifier");
      }
    }
    return true;
  }
  if (state2.switchU ? this.regexp_eatAtom(state2) : this.regexp_eatExtendedAtom(state2)) {
    this.regexp_eatQuantifier(state2);
    return true;
  }
  return false;
};
pp$8.regexp_eatAssertion = function(state2) {
  var start = state2.pos;
  state2.lastAssertionIsQuantifiable = false;
  if (state2.eat(94) || state2.eat(36)) {
    return true;
  }
  if (state2.eat(92)) {
    if (state2.eat(66) || state2.eat(98)) {
      return true;
    }
    state2.pos = start;
  }
  if (state2.eat(40) && state2.eat(63)) {
    var lookbehind = false;
    if (this.options.ecmaVersion >= 9) {
      lookbehind = state2.eat(60);
    }
    if (state2.eat(61) || state2.eat(33)) {
      this.regexp_disjunction(state2);
      if (!state2.eat(41)) {
        state2.raise("Unterminated group");
      }
      state2.lastAssertionIsQuantifiable = !lookbehind;
      return true;
    }
  }
  state2.pos = start;
  return false;
};
pp$8.regexp_eatQuantifier = function(state2, noError) {
  if (noError === void 0)
    noError = false;
  if (this.regexp_eatQuantifierPrefix(state2, noError)) {
    state2.eat(63);
    return true;
  }
  return false;
};
pp$8.regexp_eatQuantifierPrefix = function(state2, noError) {
  return state2.eat(42) || state2.eat(43) || state2.eat(63) || this.regexp_eatBracedQuantifier(state2, noError);
};
pp$8.regexp_eatBracedQuantifier = function(state2, noError) {
  var start = state2.pos;
  if (state2.eat(123)) {
    var min2 = 0, max = -1;
    if (this.regexp_eatDecimalDigits(state2)) {
      min2 = state2.lastIntValue;
      if (state2.eat(44) && this.regexp_eatDecimalDigits(state2)) {
        max = state2.lastIntValue;
      }
      if (state2.eat(125)) {
        if (max !== -1 && max < min2 && !noError) {
          state2.raise("numbers out of order in {} quantifier");
        }
        return true;
      }
    }
    if (state2.switchU && !noError) {
      state2.raise("Incomplete quantifier");
    }
    state2.pos = start;
  }
  return false;
};
pp$8.regexp_eatAtom = function(state2) {
  return this.regexp_eatPatternCharacters(state2) || state2.eat(46) || this.regexp_eatReverseSolidusAtomEscape(state2) || this.regexp_eatCharacterClass(state2) || this.regexp_eatUncapturingGroup(state2) || this.regexp_eatCapturingGroup(state2);
};
pp$8.regexp_eatReverseSolidusAtomEscape = function(state2) {
  var start = state2.pos;
  if (state2.eat(92)) {
    if (this.regexp_eatAtomEscape(state2)) {
      return true;
    }
    state2.pos = start;
  }
  return false;
};
pp$8.regexp_eatUncapturingGroup = function(state2) {
  var start = state2.pos;
  if (state2.eat(40)) {
    if (state2.eat(63) && state2.eat(58)) {
      this.regexp_disjunction(state2);
      if (state2.eat(41)) {
        return true;
      }
      state2.raise("Unterminated group");
    }
    state2.pos = start;
  }
  return false;
};
pp$8.regexp_eatCapturingGroup = function(state2) {
  if (state2.eat(40)) {
    if (this.options.ecmaVersion >= 9) {
      this.regexp_groupSpecifier(state2);
    } else if (state2.current() === 63) {
      state2.raise("Invalid group");
    }
    this.regexp_disjunction(state2);
    if (state2.eat(41)) {
      state2.numCapturingParens += 1;
      return true;
    }
    state2.raise("Unterminated group");
  }
  return false;
};
pp$8.regexp_eatExtendedAtom = function(state2) {
  return state2.eat(46) || this.regexp_eatReverseSolidusAtomEscape(state2) || this.regexp_eatCharacterClass(state2) || this.regexp_eatUncapturingGroup(state2) || this.regexp_eatCapturingGroup(state2) || this.regexp_eatInvalidBracedQuantifier(state2) || this.regexp_eatExtendedPatternCharacter(state2);
};
pp$8.regexp_eatInvalidBracedQuantifier = function(state2) {
  if (this.regexp_eatBracedQuantifier(state2, true)) {
    state2.raise("Nothing to repeat");
  }
  return false;
};
pp$8.regexp_eatSyntaxCharacter = function(state2) {
  var ch = state2.current();
  if (isSyntaxCharacter(ch)) {
    state2.lastIntValue = ch;
    state2.advance();
    return true;
  }
  return false;
};
function isSyntaxCharacter(ch) {
  return ch === 36 || ch >= 40 && ch <= 43 || ch === 46 || ch === 63 || ch >= 91 && ch <= 94 || ch >= 123 && ch <= 125;
}
pp$8.regexp_eatPatternCharacters = function(state2) {
  var start = state2.pos;
  var ch = 0;
  while ((ch = state2.current()) !== -1 && !isSyntaxCharacter(ch)) {
    state2.advance();
  }
  return state2.pos !== start;
};
pp$8.regexp_eatExtendedPatternCharacter = function(state2) {
  var ch = state2.current();
  if (ch !== -1 && ch !== 36 && !(ch >= 40 && ch <= 43) && ch !== 46 && ch !== 63 && ch !== 91 && ch !== 94 && ch !== 124) {
    state2.advance();
    return true;
  }
  return false;
};
pp$8.regexp_groupSpecifier = function(state2) {
  if (state2.eat(63)) {
    if (this.regexp_eatGroupName(state2)) {
      if (state2.groupNames.indexOf(state2.lastStringValue) !== -1) {
        state2.raise("Duplicate capture group name");
      }
      state2.groupNames.push(state2.lastStringValue);
      return;
    }
    state2.raise("Invalid group");
  }
};
pp$8.regexp_eatGroupName = function(state2) {
  state2.lastStringValue = "";
  if (state2.eat(60)) {
    if (this.regexp_eatRegExpIdentifierName(state2) && state2.eat(62)) {
      return true;
    }
    state2.raise("Invalid capture group name");
  }
  return false;
};
pp$8.regexp_eatRegExpIdentifierName = function(state2) {
  state2.lastStringValue = "";
  if (this.regexp_eatRegExpIdentifierStart(state2)) {
    state2.lastStringValue += codePointToString(state2.lastIntValue);
    while (this.regexp_eatRegExpIdentifierPart(state2)) {
      state2.lastStringValue += codePointToString(state2.lastIntValue);
    }
    return true;
  }
  return false;
};
pp$8.regexp_eatRegExpIdentifierStart = function(state2) {
  var start = state2.pos;
  var forceU = this.options.ecmaVersion >= 11;
  var ch = state2.current(forceU);
  state2.advance(forceU);
  if (ch === 92 && this.regexp_eatRegExpUnicodeEscapeSequence(state2, forceU)) {
    ch = state2.lastIntValue;
  }
  if (isRegExpIdentifierStart(ch)) {
    state2.lastIntValue = ch;
    return true;
  }
  state2.pos = start;
  return false;
};
function isRegExpIdentifierStart(ch) {
  return isIdentifierStart(ch, true) || ch === 36 || ch === 95;
}
pp$8.regexp_eatRegExpIdentifierPart = function(state2) {
  var start = state2.pos;
  var forceU = this.options.ecmaVersion >= 11;
  var ch = state2.current(forceU);
  state2.advance(forceU);
  if (ch === 92 && this.regexp_eatRegExpUnicodeEscapeSequence(state2, forceU)) {
    ch = state2.lastIntValue;
  }
  if (isRegExpIdentifierPart(ch)) {
    state2.lastIntValue = ch;
    return true;
  }
  state2.pos = start;
  return false;
};
function isRegExpIdentifierPart(ch) {
  return isIdentifierChar(ch, true) || ch === 36 || ch === 95 || ch === 8204 || ch === 8205;
}
pp$8.regexp_eatAtomEscape = function(state2) {
  if (this.regexp_eatBackReference(state2) || this.regexp_eatCharacterClassEscape(state2) || this.regexp_eatCharacterEscape(state2) || state2.switchN && this.regexp_eatKGroupName(state2)) {
    return true;
  }
  if (state2.switchU) {
    if (state2.current() === 99) {
      state2.raise("Invalid unicode escape");
    }
    state2.raise("Invalid escape");
  }
  return false;
};
pp$8.regexp_eatBackReference = function(state2) {
  var start = state2.pos;
  if (this.regexp_eatDecimalEscape(state2)) {
    var n5 = state2.lastIntValue;
    if (state2.switchU) {
      if (n5 > state2.maxBackReference) {
        state2.maxBackReference = n5;
      }
      return true;
    }
    if (n5 <= state2.numCapturingParens) {
      return true;
    }
    state2.pos = start;
  }
  return false;
};
pp$8.regexp_eatKGroupName = function(state2) {
  if (state2.eat(107)) {
    if (this.regexp_eatGroupName(state2)) {
      state2.backReferenceNames.push(state2.lastStringValue);
      return true;
    }
    state2.raise("Invalid named reference");
  }
  return false;
};
pp$8.regexp_eatCharacterEscape = function(state2) {
  return this.regexp_eatControlEscape(state2) || this.regexp_eatCControlLetter(state2) || this.regexp_eatZero(state2) || this.regexp_eatHexEscapeSequence(state2) || this.regexp_eatRegExpUnicodeEscapeSequence(state2, false) || !state2.switchU && this.regexp_eatLegacyOctalEscapeSequence(state2) || this.regexp_eatIdentityEscape(state2);
};
pp$8.regexp_eatCControlLetter = function(state2) {
  var start = state2.pos;
  if (state2.eat(99)) {
    if (this.regexp_eatControlLetter(state2)) {
      return true;
    }
    state2.pos = start;
  }
  return false;
};
pp$8.regexp_eatZero = function(state2) {
  if (state2.current() === 48 && !isDecimalDigit(state2.lookahead())) {
    state2.lastIntValue = 0;
    state2.advance();
    return true;
  }
  return false;
};
pp$8.regexp_eatControlEscape = function(state2) {
  var ch = state2.current();
  if (ch === 116) {
    state2.lastIntValue = 9;
    state2.advance();
    return true;
  }
  if (ch === 110) {
    state2.lastIntValue = 10;
    state2.advance();
    return true;
  }
  if (ch === 118) {
    state2.lastIntValue = 11;
    state2.advance();
    return true;
  }
  if (ch === 102) {
    state2.lastIntValue = 12;
    state2.advance();
    return true;
  }
  if (ch === 114) {
    state2.lastIntValue = 13;
    state2.advance();
    return true;
  }
  return false;
};
pp$8.regexp_eatControlLetter = function(state2) {
  var ch = state2.current();
  if (isControlLetter(ch)) {
    state2.lastIntValue = ch % 32;
    state2.advance();
    return true;
  }
  return false;
};
function isControlLetter(ch) {
  return ch >= 65 && ch <= 90 || ch >= 97 && ch <= 122;
}
pp$8.regexp_eatRegExpUnicodeEscapeSequence = function(state2, forceU) {
  if (forceU === void 0)
    forceU = false;
  var start = state2.pos;
  var switchU = forceU || state2.switchU;
  if (state2.eat(117)) {
    if (this.regexp_eatFixedHexDigits(state2, 4)) {
      var lead = state2.lastIntValue;
      if (switchU && lead >= 55296 && lead <= 56319) {
        var leadSurrogateEnd = state2.pos;
        if (state2.eat(92) && state2.eat(117) && this.regexp_eatFixedHexDigits(state2, 4)) {
          var trail = state2.lastIntValue;
          if (trail >= 56320 && trail <= 57343) {
            state2.lastIntValue = (lead - 55296) * 1024 + (trail - 56320) + 65536;
            return true;
          }
        }
        state2.pos = leadSurrogateEnd;
        state2.lastIntValue = lead;
      }
      return true;
    }
    if (switchU && state2.eat(123) && this.regexp_eatHexDigits(state2) && state2.eat(125) && isValidUnicode(state2.lastIntValue)) {
      return true;
    }
    if (switchU) {
      state2.raise("Invalid unicode escape");
    }
    state2.pos = start;
  }
  return false;
};
function isValidUnicode(ch) {
  return ch >= 0 && ch <= 1114111;
}
pp$8.regexp_eatIdentityEscape = function(state2) {
  if (state2.switchU) {
    if (this.regexp_eatSyntaxCharacter(state2)) {
      return true;
    }
    if (state2.eat(47)) {
      state2.lastIntValue = 47;
      return true;
    }
    return false;
  }
  var ch = state2.current();
  if (ch !== 99 && (!state2.switchN || ch !== 107)) {
    state2.lastIntValue = ch;
    state2.advance();
    return true;
  }
  return false;
};
pp$8.regexp_eatDecimalEscape = function(state2) {
  state2.lastIntValue = 0;
  var ch = state2.current();
  if (ch >= 49 && ch <= 57) {
    do {
      state2.lastIntValue = 10 * state2.lastIntValue + (ch - 48);
      state2.advance();
    } while ((ch = state2.current()) >= 48 && ch <= 57);
    return true;
  }
  return false;
};
pp$8.regexp_eatCharacterClassEscape = function(state2) {
  var ch = state2.current();
  if (isCharacterClassEscape(ch)) {
    state2.lastIntValue = -1;
    state2.advance();
    return true;
  }
  if (state2.switchU && this.options.ecmaVersion >= 9 && (ch === 80 || ch === 112)) {
    state2.lastIntValue = -1;
    state2.advance();
    if (state2.eat(123) && this.regexp_eatUnicodePropertyValueExpression(state2) && state2.eat(125)) {
      return true;
    }
    state2.raise("Invalid property name");
  }
  return false;
};
function isCharacterClassEscape(ch) {
  return ch === 100 || ch === 68 || ch === 115 || ch === 83 || ch === 119 || ch === 87;
}
pp$8.regexp_eatUnicodePropertyValueExpression = function(state2) {
  var start = state2.pos;
  if (this.regexp_eatUnicodePropertyName(state2) && state2.eat(61)) {
    var name2 = state2.lastStringValue;
    if (this.regexp_eatUnicodePropertyValue(state2)) {
      var value = state2.lastStringValue;
      this.regexp_validateUnicodePropertyNameAndValue(state2, name2, value);
      return true;
    }
  }
  state2.pos = start;
  if (this.regexp_eatLoneUnicodePropertyNameOrValue(state2)) {
    var nameOrValue = state2.lastStringValue;
    this.regexp_validateUnicodePropertyNameOrValue(state2, nameOrValue);
    return true;
  }
  return false;
};
pp$8.regexp_validateUnicodePropertyNameAndValue = function(state2, name2, value) {
  if (!has(state2.unicodeProperties.nonBinary, name2)) {
    state2.raise("Invalid property name");
  }
  if (!state2.unicodeProperties.nonBinary[name2].test(value)) {
    state2.raise("Invalid property value");
  }
};
pp$8.regexp_validateUnicodePropertyNameOrValue = function(state2, nameOrValue) {
  if (!state2.unicodeProperties.binary.test(nameOrValue)) {
    state2.raise("Invalid property name");
  }
};
pp$8.regexp_eatUnicodePropertyName = function(state2) {
  var ch = 0;
  state2.lastStringValue = "";
  while (isUnicodePropertyNameCharacter(ch = state2.current())) {
    state2.lastStringValue += codePointToString(ch);
    state2.advance();
  }
  return state2.lastStringValue !== "";
};
function isUnicodePropertyNameCharacter(ch) {
  return isControlLetter(ch) || ch === 95;
}
pp$8.regexp_eatUnicodePropertyValue = function(state2) {
  var ch = 0;
  state2.lastStringValue = "";
  while (isUnicodePropertyValueCharacter(ch = state2.current())) {
    state2.lastStringValue += codePointToString(ch);
    state2.advance();
  }
  return state2.lastStringValue !== "";
};
function isUnicodePropertyValueCharacter(ch) {
  return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch);
}
pp$8.regexp_eatLoneUnicodePropertyNameOrValue = function(state2) {
  return this.regexp_eatUnicodePropertyValue(state2);
};
pp$8.regexp_eatCharacterClass = function(state2) {
  if (state2.eat(91)) {
    state2.eat(94);
    this.regexp_classRanges(state2);
    if (state2.eat(93)) {
      return true;
    }
    state2.raise("Unterminated character class");
  }
  return false;
};
pp$8.regexp_classRanges = function(state2) {
  while (this.regexp_eatClassAtom(state2)) {
    var left = state2.lastIntValue;
    if (state2.eat(45) && this.regexp_eatClassAtom(state2)) {
      var right = state2.lastIntValue;
      if (state2.switchU && (left === -1 || right === -1)) {
        state2.raise("Invalid character class");
      }
      if (left !== -1 && right !== -1 && left > right) {
        state2.raise("Range out of order in character class");
      }
    }
  }
};
pp$8.regexp_eatClassAtom = function(state2) {
  var start = state2.pos;
  if (state2.eat(92)) {
    if (this.regexp_eatClassEscape(state2)) {
      return true;
    }
    if (state2.switchU) {
      var ch$1 = state2.current();
      if (ch$1 === 99 || isOctalDigit(ch$1)) {
        state2.raise("Invalid class escape");
      }
      state2.raise("Invalid escape");
    }
    state2.pos = start;
  }
  var ch = state2.current();
  if (ch !== 93) {
    state2.lastIntValue = ch;
    state2.advance();
    return true;
  }
  return false;
};
pp$8.regexp_eatClassEscape = function(state2) {
  var start = state2.pos;
  if (state2.eat(98)) {
    state2.lastIntValue = 8;
    return true;
  }
  if (state2.switchU && state2.eat(45)) {
    state2.lastIntValue = 45;
    return true;
  }
  if (!state2.switchU && state2.eat(99)) {
    if (this.regexp_eatClassControlLetter(state2)) {
      return true;
    }
    state2.pos = start;
  }
  return this.regexp_eatCharacterClassEscape(state2) || this.regexp_eatCharacterEscape(state2);
};
pp$8.regexp_eatClassControlLetter = function(state2) {
  var ch = state2.current();
  if (isDecimalDigit(ch) || ch === 95) {
    state2.lastIntValue = ch % 32;
    state2.advance();
    return true;
  }
  return false;
};
pp$8.regexp_eatHexEscapeSequence = function(state2) {
  var start = state2.pos;
  if (state2.eat(120)) {
    if (this.regexp_eatFixedHexDigits(state2, 2)) {
      return true;
    }
    if (state2.switchU) {
      state2.raise("Invalid escape");
    }
    state2.pos = start;
  }
  return false;
};
pp$8.regexp_eatDecimalDigits = function(state2) {
  var start = state2.pos;
  var ch = 0;
  state2.lastIntValue = 0;
  while (isDecimalDigit(ch = state2.current())) {
    state2.lastIntValue = 10 * state2.lastIntValue + (ch - 48);
    state2.advance();
  }
  return state2.pos !== start;
};
function isDecimalDigit(ch) {
  return ch >= 48 && ch <= 57;
}
pp$8.regexp_eatHexDigits = function(state2) {
  var start = state2.pos;
  var ch = 0;
  state2.lastIntValue = 0;
  while (isHexDigit(ch = state2.current())) {
    state2.lastIntValue = 16 * state2.lastIntValue + hexToInt(ch);
    state2.advance();
  }
  return state2.pos !== start;
};
function isHexDigit(ch) {
  return ch >= 48 && ch <= 57 || ch >= 65 && ch <= 70 || ch >= 97 && ch <= 102;
}
function hexToInt(ch) {
  if (ch >= 65 && ch <= 70) {
    return 10 + (ch - 65);
  }
  if (ch >= 97 && ch <= 102) {
    return 10 + (ch - 97);
  }
  return ch - 48;
}
pp$8.regexp_eatLegacyOctalEscapeSequence = function(state2) {
  if (this.regexp_eatOctalDigit(state2)) {
    var n1 = state2.lastIntValue;
    if (this.regexp_eatOctalDigit(state2)) {
      var n22 = state2.lastIntValue;
      if (n1 <= 3 && this.regexp_eatOctalDigit(state2)) {
        state2.lastIntValue = n1 * 64 + n22 * 8 + state2.lastIntValue;
      } else {
        state2.lastIntValue = n1 * 8 + n22;
      }
    } else {
      state2.lastIntValue = n1;
    }
    return true;
  }
  return false;
};
pp$8.regexp_eatOctalDigit = function(state2) {
  var ch = state2.current();
  if (isOctalDigit(ch)) {
    state2.lastIntValue = ch - 48;
    state2.advance();
    return true;
  }
  state2.lastIntValue = 0;
  return false;
};
function isOctalDigit(ch) {
  return ch >= 48 && ch <= 55;
}
pp$8.regexp_eatFixedHexDigits = function(state2, length) {
  var start = state2.pos;
  state2.lastIntValue = 0;
  for (var i6 = 0; i6 < length; ++i6) {
    var ch = state2.current();
    if (!isHexDigit(ch)) {
      state2.pos = start;
      return false;
    }
    state2.lastIntValue = 16 * state2.lastIntValue + hexToInt(ch);
    state2.advance();
  }
  return true;
};
var Token = function Token2(p5) {
  this.type = p5.type;
  this.value = p5.value;
  this.start = p5.start;
  this.end = p5.end;
  if (p5.options.locations) {
    this.loc = new SourceLocation(p5, p5.startLoc, p5.endLoc);
  }
  if (p5.options.ranges) {
    this.range = [p5.start, p5.end];
  }
};
var pp$9 = Parser2.prototype;
pp$9.next = function(ignoreEscapeSequenceInKeyword) {
  if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc) {
    this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword);
  }
  if (this.options.onToken) {
    this.options.onToken(new Token(this));
  }
  this.lastTokEnd = this.end;
  this.lastTokStart = this.start;
  this.lastTokEndLoc = this.endLoc;
  this.lastTokStartLoc = this.startLoc;
  this.nextToken();
};
pp$9.getToken = function() {
  this.next();
  return new Token(this);
};
if (typeof Symbol !== "undefined") {
  pp$9[Symbol.iterator] = function() {
    var this$1 = this;
    return {
      next: function() {
        var token = this$1.getToken();
        return {
          done: token.type === types5.eof,
          value: token
        };
      }
    };
  };
}
pp$9.curContext = function() {
  return this.context[this.context.length - 1];
};
pp$9.nextToken = function() {
  var curContext = this.curContext();
  if (!curContext || !curContext.preserveSpace) {
    this.skipSpace();
  }
  this.start = this.pos;
  if (this.options.locations) {
    this.startLoc = this.curPosition();
  }
  if (this.pos >= this.input.length) {
    return this.finishToken(types5.eof);
  }
  if (curContext.override) {
    return curContext.override(this);
  } else {
    this.readToken(this.fullCharCodeAtPos());
  }
};
pp$9.readToken = function(code5) {
  if (isIdentifierStart(code5, this.options.ecmaVersion >= 6) || code5 === 92) {
    return this.readWord();
  }
  return this.getTokenFromCode(code5);
};
pp$9.fullCharCodeAtPos = function() {
  var code5 = this.input.charCodeAt(this.pos);
  if (code5 <= 55295 || code5 >= 57344) {
    return code5;
  }
  var next = this.input.charCodeAt(this.pos + 1);
  return (code5 << 10) + next - 56613888;
};
pp$9.skipBlockComment = function() {
  var startLoc = this.options.onComment && this.curPosition();
  var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
  if (end === -1) {
    this.raise(this.pos - 2, "Unterminated comment");
  }
  this.pos = end + 2;
  if (this.options.locations) {
    lineBreakG.lastIndex = start;
    var match;
    while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) {
      ++this.curLine;
      this.lineStart = match.index + match[0].length;
    }
  }
  if (this.options.onComment) {
    this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos, startLoc, this.curPosition());
  }
};
pp$9.skipLineComment = function(startSkip) {
  var start = this.pos;
  var startLoc = this.options.onComment && this.curPosition();
  var ch = this.input.charCodeAt(this.pos += startSkip);
  while (this.pos < this.input.length && !isNewLine(ch)) {
    ch = this.input.charCodeAt(++this.pos);
  }
  if (this.options.onComment) {
    this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos, startLoc, this.curPosition());
  }
};
pp$9.skipSpace = function() {
  loop:
    while (this.pos < this.input.length) {
      var ch = this.input.charCodeAt(this.pos);
      switch (ch) {
        case 32:
        case 160:
          ++this.pos;
          break;
        case 13:
          if (this.input.charCodeAt(this.pos + 1) === 10) {
            ++this.pos;
          }
        case 10:
        case 8232:
        case 8233:
          ++this.pos;
          if (this.options.locations) {
            ++this.curLine;
            this.lineStart = this.pos;
          }
          break;
        case 47:
          switch (this.input.charCodeAt(this.pos + 1)) {
            case 42:
              this.skipBlockComment();
              break;
            case 47:
              this.skipLineComment(2);
              break;
            default:
              break loop;
          }
          break;
        default:
          if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
            ++this.pos;
          } else {
            break loop;
          }
      }
    }
};
pp$9.finishToken = function(type4, val) {
  this.end = this.pos;
  if (this.options.locations) {
    this.endLoc = this.curPosition();
  }
  var prevType = this.type;
  this.type = type4;
  this.value = val;
  this.updateContext(prevType);
};
pp$9.readToken_dot = function() {
  var next = this.input.charCodeAt(this.pos + 1);
  if (next >= 48 && next <= 57) {
    return this.readNumber(true);
  }
  var next2 = this.input.charCodeAt(this.pos + 2);
  if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) {
    this.pos += 3;
    return this.finishToken(types5.ellipsis);
  } else {
    ++this.pos;
    return this.finishToken(types5.dot);
  }
};
pp$9.readToken_slash = function() {
  var next = this.input.charCodeAt(this.pos + 1);
  if (this.exprAllowed) {
    ++this.pos;
    return this.readRegexp();
  }
  if (next === 61) {
    return this.finishOp(types5.assign, 2);
  }
  return this.finishOp(types5.slash, 1);
};
pp$9.readToken_mult_modulo_exp = function(code5) {
  var next = this.input.charCodeAt(this.pos + 1);
  var size = 1;
  var tokentype = code5 === 42 ? types5.star : types5.modulo;
  if (this.options.ecmaVersion >= 7 && code5 === 42 && next === 42) {
    ++size;
    tokentype = types5.starstar;
    next = this.input.charCodeAt(this.pos + 2);
  }
  if (next === 61) {
    return this.finishOp(types5.assign, size + 1);
  }
  return this.finishOp(tokentype, size);
};
pp$9.readToken_pipe_amp = function(code5) {
  var next = this.input.charCodeAt(this.pos + 1);
  if (next === code5) {
    if (this.options.ecmaVersion >= 12) {
      var next2 = this.input.charCodeAt(this.pos + 2);
      if (next2 === 61) {
        return this.finishOp(types5.assign, 3);
      }
    }
    return this.finishOp(code5 === 124 ? types5.logicalOR : types5.logicalAND, 2);
  }
  if (next === 61) {
    return this.finishOp(types5.assign, 2);
  }
  return this.finishOp(code5 === 124 ? types5.bitwiseOR : types5.bitwiseAND, 1);
};
pp$9.readToken_caret = function() {
  var next = this.input.charCodeAt(this.pos + 1);
  if (next === 61) {
    return this.finishOp(types5.assign, 2);
  }
  return this.finishOp(types5.bitwiseXOR, 1);
};
pp$9.readToken_plus_min = function(code5) {
  var next = this.input.charCodeAt(this.pos + 1);
  if (next === code5) {
    if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 && (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
      this.skipLineComment(3);
      this.skipSpace();
      return this.nextToken();
    }
    return this.finishOp(types5.incDec, 2);
  }
  if (next === 61) {
    return this.finishOp(types5.assign, 2);
  }
  return this.finishOp(types5.plusMin, 1);
};
pp$9.readToken_lt_gt = function(code5) {
  var next = this.input.charCodeAt(this.pos + 1);
  var size = 1;
  if (next === code5) {
    size = code5 === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
    if (this.input.charCodeAt(this.pos + size) === 61) {
      return this.finishOp(types5.assign, size + 1);
    }
    return this.finishOp(types5.bitShift, size);
  }
  if (next === 33 && code5 === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && this.input.charCodeAt(this.pos + 3) === 45) {
    this.skipLineComment(4);
    this.skipSpace();
    return this.nextToken();
  }
  if (next === 61) {
    size = 2;
  }
  return this.finishOp(types5.relational, size);
};
pp$9.readToken_eq_excl = function(code5) {
  var next = this.input.charCodeAt(this.pos + 1);
  if (next === 61) {
    return this.finishOp(types5.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2);
  }
  if (code5 === 61 && next === 62 && this.options.ecmaVersion >= 6) {
    this.pos += 2;
    return this.finishToken(types5.arrow);
  }
  return this.finishOp(code5 === 61 ? types5.eq : types5.prefix, 1);
};
pp$9.readToken_question = function() {
  var ecmaVersion = this.options.ecmaVersion;
  if (ecmaVersion >= 11) {
    var next = this.input.charCodeAt(this.pos + 1);
    if (next === 46) {
      var next2 = this.input.charCodeAt(this.pos + 2);
      if (next2 < 48 || next2 > 57) {
        return this.finishOp(types5.questionDot, 2);
      }
    }
    if (next === 63) {
      if (ecmaVersion >= 12) {
        var next2$1 = this.input.charCodeAt(this.pos + 2);
        if (next2$1 === 61) {
          return this.finishOp(types5.assign, 3);
        }
      }
      return this.finishOp(types5.coalesce, 2);
    }
  }
  return this.finishOp(types5.question, 1);
};
pp$9.getTokenFromCode = function(code5) {
  switch (code5) {
    case 46:
      return this.readToken_dot();
    case 40:
      ++this.pos;
      return this.finishToken(types5.parenL);
    case 41:
      ++this.pos;
      return this.finishToken(types5.parenR);
    case 59:
      ++this.pos;
      return this.finishToken(types5.semi);
    case 44:
      ++this.pos;
      return this.finishToken(types5.comma);
    case 91:
      ++this.pos;
      return this.finishToken(types5.bracketL);
    case 93:
      ++this.pos;
      return this.finishToken(types5.bracketR);
    case 123:
      ++this.pos;
      return this.finishToken(types5.braceL);
    case 125:
      ++this.pos;
      return this.finishToken(types5.braceR);
    case 58:
      ++this.pos;
      return this.finishToken(types5.colon);
    case 96:
      if (this.options.ecmaVersion < 6) {
        break;
      }
      ++this.pos;
      return this.finishToken(types5.backQuote);
    case 48:
      var next = this.input.charCodeAt(this.pos + 1);
      if (next === 120 || next === 88) {
        return this.readRadixNumber(16);
      }
      if (this.options.ecmaVersion >= 6) {
        if (next === 111 || next === 79) {
          return this.readRadixNumber(8);
        }
        if (next === 98 || next === 66) {
          return this.readRadixNumber(2);
        }
      }
    case 49:
    case 50:
    case 51:
    case 52:
    case 53:
    case 54:
    case 55:
    case 56:
    case 57:
      return this.readNumber(false);
    case 34:
    case 39:
      return this.readString(code5);
    case 47:
      return this.readToken_slash();
    case 37:
    case 42:
      return this.readToken_mult_modulo_exp(code5);
    case 124:
    case 38:
      return this.readToken_pipe_amp(code5);
    case 94:
      return this.readToken_caret();
    case 43:
    case 45:
      return this.readToken_plus_min(code5);
    case 60:
    case 62:
      return this.readToken_lt_gt(code5);
    case 61:
    case 33:
      return this.readToken_eq_excl(code5);
    case 63:
      return this.readToken_question();
    case 126:
      return this.finishOp(types5.prefix, 1);
  }
  this.raise(this.pos, "Unexpected character '" + codePointToString$1(code5) + "'");
};
pp$9.finishOp = function(type4, size) {
  var str3 = this.input.slice(this.pos, this.pos + size);
  this.pos += size;
  return this.finishToken(type4, str3);
};
pp$9.readRegexp = function() {
  var escaped, inClass, start = this.pos;
  for (; ; ) {
    if (this.pos >= this.input.length) {
      this.raise(start, "Unterminated regular expression");
    }
    var ch = this.input.charAt(this.pos);
    if (lineBreak.test(ch)) {
      this.raise(start, "Unterminated regular expression");
    }
    if (!escaped) {
      if (ch === "[") {
        inClass = true;
      } else if (ch === "]" && inClass) {
        inClass = false;
      } else if (ch === "/" && !inClass) {
        break;
      }
      escaped = ch === "\\";
    } else {
      escaped = false;
    }
    ++this.pos;
  }
  var pattern = this.input.slice(start, this.pos);
  ++this.pos;
  var flagsStart = this.pos;
  var flags = this.readWord1();
  if (this.containsEsc) {
    this.unexpected(flagsStart);
  }
  var state2 = this.regexpState || (this.regexpState = new RegExpValidationState(this));
  state2.reset(start, pattern, flags);
  this.validateRegExpFlags(state2);
  this.validateRegExpPattern(state2);
  var value = null;
  try {
    value = new RegExp(pattern, flags);
  } catch (e5) {
  }
  return this.finishToken(types5.regexp, { pattern, flags, value });
};
pp$9.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {
  var allowSeparators = this.options.ecmaVersion >= 12 && len === void 0;
  var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;
  var start = this.pos, total = 0, lastCode = 0;
  for (var i6 = 0, e5 = len == null ? Infinity : len; i6 < e5; ++i6, ++this.pos) {
    var code5 = this.input.charCodeAt(this.pos), val = void 0;
    if (allowSeparators && code5 === 95) {
      if (isLegacyOctalNumericLiteral) {
        this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals");
      }
      if (lastCode === 95) {
        this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore");
      }
      if (i6 === 0) {
        this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits");
      }
      lastCode = code5;
      continue;
    }
    if (code5 >= 97) {
      val = code5 - 97 + 10;
    } else if (code5 >= 65) {
      val = code5 - 65 + 10;
    } else if (code5 >= 48 && code5 <= 57) {
      val = code5 - 48;
    } else {
      val = Infinity;
    }
    if (val >= radix) {
      break;
    }
    lastCode = code5;
    total = total * radix + val;
  }
  if (allowSeparators && lastCode === 95) {
    this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits");
  }
  if (this.pos === start || len != null && this.pos - start !== len) {
    return null;
  }
  return total;
};
function stringToNumber(str3, isLegacyOctalNumericLiteral) {
  if (isLegacyOctalNumericLiteral) {
    return parseInt(str3, 8);
  }
  return parseFloat(str3.replace(/_/g, ""));
}
function stringToBigInt(str3) {
  if (typeof BigInt !== "function") {
    return null;
  }
  return BigInt(str3.replace(/_/g, ""));
}
pp$9.readRadixNumber = function(radix) {
  var start = this.pos;
  this.pos += 2;
  var val = this.readInt(radix);
  if (val == null) {
    this.raise(this.start + 2, "Expected number in radix " + radix);
  }
  if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
    val = stringToBigInt(this.input.slice(start, this.pos));
    ++this.pos;
  } else if (isIdentifierStart(this.fullCharCodeAtPos())) {
    this.raise(this.pos, "Identifier directly after number");
  }
  return this.finishToken(types5.num, val);
};
pp$9.readNumber = function(startsWithDot) {
  var start = this.pos;
  if (!startsWithDot && this.readInt(10, void 0, true) === null) {
    this.raise(start, "Invalid number");
  }
  var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  if (octal && this.strict) {
    this.raise(start, "Invalid number");
  }
  var next = this.input.charCodeAt(this.pos);
  if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
    var val$1 = stringToBigInt(this.input.slice(start, this.pos));
    ++this.pos;
    if (isIdentifierStart(this.fullCharCodeAtPos())) {
      this.raise(this.pos, "Identifier directly after number");
    }
    return this.finishToken(types5.num, val$1);
  }
  if (octal && /[89]/.test(this.input.slice(start, this.pos))) {
    octal = false;
  }
  if (next === 46 && !octal) {
    ++this.pos;
    this.readInt(10);
    next = this.input.charCodeAt(this.pos);
  }
  if ((next === 69 || next === 101) && !octal) {
    next = this.input.charCodeAt(++this.pos);
    if (next === 43 || next === 45) {
      ++this.pos;
    }
    if (this.readInt(10) === null) {
      this.raise(start, "Invalid number");
    }
  }
  if (isIdentifierStart(this.fullCharCodeAtPos())) {
    this.raise(this.pos, "Identifier directly after number");
  }
  var val = stringToNumber(this.input.slice(start, this.pos), octal);
  return this.finishToken(types5.num, val);
};
pp$9.readCodePoint = function() {
  var ch = this.input.charCodeAt(this.pos), code5;
  if (ch === 123) {
    if (this.options.ecmaVersion < 6) {
      this.unexpected();
    }
    var codePos = ++this.pos;
    code5 = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
    ++this.pos;
    if (code5 > 1114111) {
      this.invalidStringToken(codePos, "Code point out of bounds");
    }
  } else {
    code5 = this.readHexChar(4);
  }
  return code5;
};
function codePointToString$1(code5) {
  if (code5 <= 65535) {
    return String.fromCharCode(code5);
  }
  code5 -= 65536;
  return String.fromCharCode((code5 >> 10) + 55296, (code5 & 1023) + 56320);
}
pp$9.readString = function(quote) {
  var out = "", chunkStart = ++this.pos;
  for (; ; ) {
    if (this.pos >= this.input.length) {
      this.raise(this.start, "Unterminated string constant");
    }
    var ch = this.input.charCodeAt(this.pos);
    if (ch === quote) {
      break;
    }
    if (ch === 92) {
      out += this.input.slice(chunkStart, this.pos);
      out += this.readEscapedChar(false);
      chunkStart = this.pos;
    } else {
      if (isNewLine(ch, this.options.ecmaVersion >= 10)) {
        this.raise(this.start, "Unterminated string constant");
      }
      ++this.pos;
    }
  }
  out += this.input.slice(chunkStart, this.pos++);
  return this.finishToken(types5.string, out);
};
var INVALID_TEMPLATE_ESCAPE_ERROR = {};
pp$9.tryReadTemplateToken = function() {
  this.inTemplateElement = true;
  try {
    this.readTmplToken();
  } catch (err2) {
    if (err2 === INVALID_TEMPLATE_ESCAPE_ERROR) {
      this.readInvalidTemplateToken();
    } else {
      throw err2;
    }
  }
  this.inTemplateElement = false;
};
pp$9.invalidStringToken = function(position, message) {
  if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
    throw INVALID_TEMPLATE_ESCAPE_ERROR;
  } else {
    this.raise(position, message);
  }
};
pp$9.readTmplToken = function() {
  var out = "", chunkStart = this.pos;
  for (; ; ) {
    if (this.pos >= this.input.length) {
      this.raise(this.start, "Unterminated template");
    }
    var ch = this.input.charCodeAt(this.pos);
    if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) {
      if (this.pos === this.start && (this.type === types5.template || this.type === types5.invalidTemplate)) {
        if (ch === 36) {
          this.pos += 2;
          return this.finishToken(types5.dollarBraceL);
        } else {
          ++this.pos;
          return this.finishToken(types5.backQuote);
        }
      }
      out += this.input.slice(chunkStart, this.pos);
      return this.finishToken(types5.template, out);
    }
    if (ch === 92) {
      out += this.input.slice(chunkStart, this.pos);
      out += this.readEscapedChar(true);
      chunkStart = this.pos;
    } else if (isNewLine(ch)) {
      out += this.input.slice(chunkStart, this.pos);
      ++this.pos;
      switch (ch) {
        case 13:
          if (this.input.charCodeAt(this.pos) === 10) {
            ++this.pos;
          }
        case 10:
          out += "\n";
          break;
        default:
          out += String.fromCharCode(ch);
          break;
      }
      if (this.options.locations) {
        ++this.curLine;
        this.lineStart = this.pos;
      }
      chunkStart = this.pos;
    } else {
      ++this.pos;
    }
  }
};
pp$9.readInvalidTemplateToken = function() {
  for (; this.pos < this.input.length; this.pos++) {
    switch (this.input[this.pos]) {
      case "\\":
        ++this.pos;
        break;
      case "$":
        if (this.input[this.pos + 1] !== "{") {
          break;
        }
      case "`":
        return this.finishToken(types5.invalidTemplate, this.input.slice(this.start, this.pos));
    }
  }
  this.raise(this.start, "Unterminated template");
};
pp$9.readEscapedChar = function(inTemplate) {
  var ch = this.input.charCodeAt(++this.pos);
  ++this.pos;
  switch (ch) {
    case 110:
      return "\n";
    case 114:
      return "\r";
    case 120:
      return String.fromCharCode(this.readHexChar(2));
    case 117:
      return codePointToString$1(this.readCodePoint());
    case 116:
      return "	";
    case 98:
      return "\b";
    case 118:
      return "\v";
    case 102:
      return "\f";
    case 13:
      if (this.input.charCodeAt(this.pos) === 10) {
        ++this.pos;
      }
    case 10:
      if (this.options.locations) {
        this.lineStart = this.pos;
        ++this.curLine;
      }
      return "";
    case 56:
    case 57:
      if (inTemplate) {
        var codePos = this.pos - 1;
        this.invalidStringToken(codePos, "Invalid escape sequence in template string");
        return null;
      }
    default:
      if (ch >= 48 && ch <= 55) {
        var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
        var octal = parseInt(octalStr, 8);
        if (octal > 255) {
          octalStr = octalStr.slice(0, -1);
          octal = parseInt(octalStr, 8);
        }
        this.pos += octalStr.length - 1;
        ch = this.input.charCodeAt(this.pos);
        if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {
          this.invalidStringToken(this.pos - 1 - octalStr.length, inTemplate ? "Octal literal in template string" : "Octal literal in strict mode");
        }
        return String.fromCharCode(octal);
      }
      if (isNewLine(ch)) {
        return "";
      }
      return String.fromCharCode(ch);
  }
};
pp$9.readHexChar = function(len) {
  var codePos = this.pos;
  var n5 = this.readInt(16, len);
  if (n5 === null) {
    this.invalidStringToken(codePos, "Bad character escape sequence");
  }
  return n5;
};
pp$9.readWord1 = function() {
  this.containsEsc = false;
  var word = "", first = true, chunkStart = this.pos;
  var astral = this.options.ecmaVersion >= 6;
  while (this.pos < this.input.length) {
    var ch = this.fullCharCodeAtPos();
    if (isIdentifierChar(ch, astral)) {
      this.pos += ch <= 65535 ? 1 : 2;
    } else if (ch === 92) {
      this.containsEsc = true;
      word += this.input.slice(chunkStart, this.pos);
      var escStart = this.pos;
      if (this.input.charCodeAt(++this.pos) !== 117) {
        this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX");
      }
      ++this.pos;
      var esc = this.readCodePoint();
      if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral)) {
        this.invalidStringToken(escStart, "Invalid Unicode escape");
      }
      word += codePointToString$1(esc);
      chunkStart = this.pos;
    } else {
      break;
    }
    first = false;
  }
  return word + this.input.slice(chunkStart, this.pos);
};
pp$9.readWord = function() {
  var word = this.readWord1();
  var type4 = types5.name;
  if (this.keywords.test(word)) {
    type4 = keywords$1[word];
  }
  return this.finishToken(type4, word);
};
var version2 = "7.4.1";
Parser2.acorn = {
  Parser: Parser2,
  version: version2,
  defaultOptions,
  Position,
  SourceLocation,
  getLineInfo,
  Node: Node4,
  TokenType,
  tokTypes: types5,
  keywordTypes: keywords$1,
  TokContext,
  tokContexts: types$1,
  isIdentifierChar,
  isIdentifierStart,
  Token,
  isNewLine,
  lineBreak,
  lineBreakG,
  nonASCIIwhitespace
};

// https://cdn.skypack.dev/-/acorn-walk@v7.2.0-HE7wS37ePcNncqJvsD8k/dist=es2019,mode=imports/optimized/acorn-walk.js
function simple(node, visitors, baseVisitor, state2, override) {
  if (!baseVisitor) {
    baseVisitor = base;
  }
  (function c6(node2, st, override2) {
    var type4 = override2 || node2.type, found = visitors[type4];
    baseVisitor[type4](node2, st, c6);
    if (found) {
      found(node2, st);
    }
  })(node, state2, override);
}
function ancestor(node, visitors, baseVisitor, state2, override) {
  var ancestors = [];
  if (!baseVisitor) {
    baseVisitor = base;
  }
  (function c6(node2, st, override2) {
    var type4 = override2 || node2.type, found = visitors[type4];
    var isNew = node2 !== ancestors[ancestors.length - 1];
    if (isNew) {
      ancestors.push(node2);
    }
    baseVisitor[type4](node2, st, c6);
    if (found) {
      found(node2, st || ancestors, ancestors);
    }
    if (isNew) {
      ancestors.pop();
    }
  })(node, state2, override);
}
var create = Object.create || function(proto2) {
  function Ctor() {
  }
  Ctor.prototype = proto2;
  return new Ctor();
};
function make(funcs, baseVisitor) {
  var visitor = create(baseVisitor || base);
  for (var type4 in funcs) {
    visitor[type4] = funcs[type4];
  }
  return visitor;
}
function skipThrough(node, st, c6) {
  c6(node, st);
}
function ignore(_node, _st, _c) {
}
var base = {};
base.Program = base.BlockStatement = function(node, st, c6) {
  for (var i6 = 0, list = node.body; i6 < list.length; i6 += 1) {
    var stmt = list[i6];
    c6(stmt, st, "Statement");
  }
};
base.Statement = skipThrough;
base.EmptyStatement = ignore;
base.ExpressionStatement = base.ParenthesizedExpression = base.ChainExpression = function(node, st, c6) {
  return c6(node.expression, st, "Expression");
};
base.IfStatement = function(node, st, c6) {
  c6(node.test, st, "Expression");
  c6(node.consequent, st, "Statement");
  if (node.alternate) {
    c6(node.alternate, st, "Statement");
  }
};
base.LabeledStatement = function(node, st, c6) {
  return c6(node.body, st, "Statement");
};
base.BreakStatement = base.ContinueStatement = ignore;
base.WithStatement = function(node, st, c6) {
  c6(node.object, st, "Expression");
  c6(node.body, st, "Statement");
};
base.SwitchStatement = function(node, st, c6) {
  c6(node.discriminant, st, "Expression");
  for (var i$13 = 0, list$1 = node.cases; i$13 < list$1.length; i$13 += 1) {
    var cs = list$1[i$13];
    if (cs.test) {
      c6(cs.test, st, "Expression");
    }
    for (var i6 = 0, list = cs.consequent; i6 < list.length; i6 += 1) {
      var cons = list[i6];
      c6(cons, st, "Statement");
    }
  }
};
base.SwitchCase = function(node, st, c6) {
  if (node.test) {
    c6(node.test, st, "Expression");
  }
  for (var i6 = 0, list = node.consequent; i6 < list.length; i6 += 1) {
    var cons = list[i6];
    c6(cons, st, "Statement");
  }
};
base.ReturnStatement = base.YieldExpression = base.AwaitExpression = function(node, st, c6) {
  if (node.argument) {
    c6(node.argument, st, "Expression");
  }
};
base.ThrowStatement = base.SpreadElement = function(node, st, c6) {
  return c6(node.argument, st, "Expression");
};
base.TryStatement = function(node, st, c6) {
  c6(node.block, st, "Statement");
  if (node.handler) {
    c6(node.handler, st);
  }
  if (node.finalizer) {
    c6(node.finalizer, st, "Statement");
  }
};
base.CatchClause = function(node, st, c6) {
  if (node.param) {
    c6(node.param, st, "Pattern");
  }
  c6(node.body, st, "Statement");
};
base.WhileStatement = base.DoWhileStatement = function(node, st, c6) {
  c6(node.test, st, "Expression");
  c6(node.body, st, "Statement");
};
base.ForStatement = function(node, st, c6) {
  if (node.init) {
    c6(node.init, st, "ForInit");
  }
  if (node.test) {
    c6(node.test, st, "Expression");
  }
  if (node.update) {
    c6(node.update, st, "Expression");
  }
  c6(node.body, st, "Statement");
};
base.ForInStatement = base.ForOfStatement = function(node, st, c6) {
  c6(node.left, st, "ForInit");
  c6(node.right, st, "Expression");
  c6(node.body, st, "Statement");
};
base.ForInit = function(node, st, c6) {
  if (node.type === "VariableDeclaration") {
    c6(node, st);
  } else {
    c6(node, st, "Expression");
  }
};
base.DebuggerStatement = ignore;
base.FunctionDeclaration = function(node, st, c6) {
  return c6(node, st, "Function");
};
base.VariableDeclaration = function(node, st, c6) {
  for (var i6 = 0, list = node.declarations; i6 < list.length; i6 += 1) {
    var decl = list[i6];
    c6(decl, st);
  }
};
base.VariableDeclarator = function(node, st, c6) {
  c6(node.id, st, "Pattern");
  if (node.init) {
    c6(node.init, st, "Expression");
  }
};
base.Function = function(node, st, c6) {
  if (node.id) {
    c6(node.id, st, "Pattern");
  }
  for (var i6 = 0, list = node.params; i6 < list.length; i6 += 1) {
    var param = list[i6];
    c6(param, st, "Pattern");
  }
  c6(node.body, st, node.expression ? "Expression" : "Statement");
};
base.Pattern = function(node, st, c6) {
  if (node.type === "Identifier") {
    c6(node, st, "VariablePattern");
  } else if (node.type === "MemberExpression") {
    c6(node, st, "MemberPattern");
  } else {
    c6(node, st);
  }
};
base.VariablePattern = ignore;
base.MemberPattern = skipThrough;
base.RestElement = function(node, st, c6) {
  return c6(node.argument, st, "Pattern");
};
base.ArrayPattern = function(node, st, c6) {
  for (var i6 = 0, list = node.elements; i6 < list.length; i6 += 1) {
    var elt = list[i6];
    if (elt) {
      c6(elt, st, "Pattern");
    }
  }
};
base.ObjectPattern = function(node, st, c6) {
  for (var i6 = 0, list = node.properties; i6 < list.length; i6 += 1) {
    var prop = list[i6];
    if (prop.type === "Property") {
      if (prop.computed) {
        c6(prop.key, st, "Expression");
      }
      c6(prop.value, st, "Pattern");
    } else if (prop.type === "RestElement") {
      c6(prop.argument, st, "Pattern");
    }
  }
};
base.Expression = skipThrough;
base.ThisExpression = base.Super = base.MetaProperty = ignore;
base.ArrayExpression = function(node, st, c6) {
  for (var i6 = 0, list = node.elements; i6 < list.length; i6 += 1) {
    var elt = list[i6];
    if (elt) {
      c6(elt, st, "Expression");
    }
  }
};
base.ObjectExpression = function(node, st, c6) {
  for (var i6 = 0, list = node.properties; i6 < list.length; i6 += 1) {
    var prop = list[i6];
    c6(prop, st);
  }
};
base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration;
base.SequenceExpression = function(node, st, c6) {
  for (var i6 = 0, list = node.expressions; i6 < list.length; i6 += 1) {
    var expr = list[i6];
    c6(expr, st, "Expression");
  }
};
base.TemplateLiteral = function(node, st, c6) {
  for (var i6 = 0, list = node.quasis; i6 < list.length; i6 += 1) {
    var quasi = list[i6];
    c6(quasi, st);
  }
  for (var i$13 = 0, list$1 = node.expressions; i$13 < list$1.length; i$13 += 1) {
    var expr = list$1[i$13];
    c6(expr, st, "Expression");
  }
};
base.TemplateElement = ignore;
base.UnaryExpression = base.UpdateExpression = function(node, st, c6) {
  c6(node.argument, st, "Expression");
};
base.BinaryExpression = base.LogicalExpression = function(node, st, c6) {
  c6(node.left, st, "Expression");
  c6(node.right, st, "Expression");
};
base.AssignmentExpression = base.AssignmentPattern = function(node, st, c6) {
  c6(node.left, st, "Pattern");
  c6(node.right, st, "Expression");
};
base.ConditionalExpression = function(node, st, c6) {
  c6(node.test, st, "Expression");
  c6(node.consequent, st, "Expression");
  c6(node.alternate, st, "Expression");
};
base.NewExpression = base.CallExpression = function(node, st, c6) {
  c6(node.callee, st, "Expression");
  if (node.arguments) {
    for (var i6 = 0, list = node.arguments; i6 < list.length; i6 += 1) {
      var arg = list[i6];
      c6(arg, st, "Expression");
    }
  }
};
base.MemberExpression = function(node, st, c6) {
  c6(node.object, st, "Expression");
  if (node.computed) {
    c6(node.property, st, "Expression");
  }
};
base.ExportNamedDeclaration = base.ExportDefaultDeclaration = function(node, st, c6) {
  if (node.declaration) {
    c6(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression");
  }
  if (node.source) {
    c6(node.source, st, "Expression");
  }
};
base.ExportAllDeclaration = function(node, st, c6) {
  if (node.exported) {
    c6(node.exported, st);
  }
  c6(node.source, st, "Expression");
};
base.ImportDeclaration = function(node, st, c6) {
  for (var i6 = 0, list = node.specifiers; i6 < list.length; i6 += 1) {
    var spec = list[i6];
    c6(spec, st);
  }
  c6(node.source, st, "Expression");
};
base.ImportExpression = function(node, st, c6) {
  c6(node.source, st, "Expression");
};
base.ImportSpecifier = base.ImportDefaultSpecifier = base.ImportNamespaceSpecifier = base.Identifier = base.Literal = ignore;
base.TaggedTemplateExpression = function(node, st, c6) {
  c6(node.tag, st, "Expression");
  c6(node.quasi, st, "Expression");
};
base.ClassDeclaration = base.ClassExpression = function(node, st, c6) {
  return c6(node, st, "Class");
};
base.Class = function(node, st, c6) {
  if (node.id) {
    c6(node.id, st, "Pattern");
  }
  if (node.superClass) {
    c6(node.superClass, st, "Expression");
  }
  c6(node.body, st);
};
base.ClassBody = function(node, st, c6) {
  for (var i6 = 0, list = node.body; i6 < list.length; i6 += 1) {
    var elt = list[i6];
    c6(elt, st);
  }
};
base.MethodDefinition = base.Property = function(node, st, c6) {
  if (node.computed) {
    c6(node.key, st, "Expression");
  }
  c6(node.value, st, "Expression");
};

// https://cdn.skypack.dev/-/@observablehq/parser@v4.5.0-rWZiNfab8flhVomtfVvr/dist=es2019,mode=imports/optimized/@observablehq/parser.js
var defaultGlobals = /* @__PURE__ */ new Set([
  "Array",
  "ArrayBuffer",
  "atob",
  "AudioContext",
  "Blob",
  "Boolean",
  "BigInt",
  "btoa",
  "clearInterval",
  "clearTimeout",
  "console",
  "crypto",
  "CustomEvent",
  "DataView",
  "Date",
  "decodeURI",
  "decodeURIComponent",
  "devicePixelRatio",
  "document",
  "encodeURI",
  "encodeURIComponent",
  "Error",
  "escape",
  "eval",
  "fetch",
  "File",
  "FileList",
  "FileReader",
  "Float32Array",
  "Float64Array",
  "Function",
  "Headers",
  "Image",
  "ImageData",
  "Infinity",
  "Int16Array",
  "Int32Array",
  "Int8Array",
  "Intl",
  "isFinite",
  "isNaN",
  "JSON",
  "Map",
  "Math",
  "NaN",
  "Number",
  "navigator",
  "Object",
  "parseFloat",
  "parseInt",
  "performance",
  "Path2D",
  "Promise",
  "Proxy",
  "RangeError",
  "ReferenceError",
  "Reflect",
  "RegExp",
  "cancelAnimationFrame",
  "requestAnimationFrame",
  "Set",
  "setInterval",
  "setTimeout",
  "String",
  "Symbol",
  "SyntaxError",
  "TextDecoder",
  "TextEncoder",
  "this",
  "TypeError",
  "Uint16Array",
  "Uint32Array",
  "Uint8Array",
  "Uint8ClampedArray",
  "undefined",
  "unescape",
  "URIError",
  "URL",
  "WeakMap",
  "WeakSet",
  "WebSocket",
  "Worker",
  "window"
]);
var walk4 = make({
  Import() {
  },
  ViewExpression(node, st, c6) {
    c6(node.id, st, "Identifier");
  },
  MutableExpression(node, st, c6) {
    c6(node.id, st, "Identifier");
  }
});
function isScope(node) {
  return node.type === "FunctionExpression" || node.type === "FunctionDeclaration" || node.type === "ArrowFunctionExpression" || node.type === "Program";
}
function isBlockScope(node) {
  return node.type === "BlockStatement" || node.type === "ForInStatement" || node.type === "ForOfStatement" || node.type === "ForStatement" || isScope(node);
}
function declaresArguments(node) {
  return node.type === "FunctionExpression" || node.type === "FunctionDeclaration";
}
function findReferences(cell, globals) {
  const ast = { type: "Program", body: [cell.body] };
  const locals = /* @__PURE__ */ new Map();
  const globalSet = new Set(globals);
  const references = [];
  function hasLocal(node, name2) {
    const l6 = locals.get(node);
    return l6 ? l6.has(name2) : false;
  }
  function declareLocal(node, id) {
    const l6 = locals.get(node);
    if (l6)
      l6.add(id.name);
    else
      locals.set(node, /* @__PURE__ */ new Set([id.name]));
  }
  function declareClass(node) {
    if (node.id)
      declareLocal(node, node.id);
  }
  function declareFunction(node) {
    node.params.forEach((param) => declarePattern(param, node));
    if (node.id)
      declareLocal(node, node.id);
  }
  function declareCatchClause(node) {
    if (node.param)
      declarePattern(node.param, node);
  }
  function declarePattern(node, parent) {
    switch (node.type) {
      case "Identifier":
        declareLocal(parent, node);
        break;
      case "ObjectPattern":
        node.properties.forEach((node2) => declarePattern(node2, parent));
        break;
      case "ArrayPattern":
        node.elements.forEach((node2) => node2 && declarePattern(node2, parent));
        break;
      case "Property":
        declarePattern(node.value, parent);
        break;
      case "RestElement":
        declarePattern(node.argument, parent);
        break;
      case "AssignmentPattern":
        declarePattern(node.left, parent);
        break;
      default:
        throw new Error("Unrecognized pattern type: " + node.type);
    }
  }
  function declareModuleSpecifier(node) {
    declareLocal(ast, node.local);
  }
  ancestor(ast, {
    VariableDeclaration: (node, parents) => {
      let parent = null;
      for (let i6 = parents.length - 1; i6 >= 0 && parent === null; --i6) {
        if (node.kind === "var" ? isScope(parents[i6]) : isBlockScope(parents[i6])) {
          parent = parents[i6];
        }
      }
      node.declarations.forEach((declaration) => declarePattern(declaration.id, parent));
    },
    FunctionDeclaration: (node, parents) => {
      let parent = null;
      for (let i6 = parents.length - 2; i6 >= 0 && parent === null; --i6) {
        if (isScope(parents[i6])) {
          parent = parents[i6];
        }
      }
      declareLocal(parent, node.id);
      declareFunction(node);
    },
    Function: declareFunction,
    ClassDeclaration: (node, parents) => {
      let parent = null;
      for (let i6 = parents.length - 2; i6 >= 0 && parent === null; i6--) {
        if (isScope(parents[i6])) {
          parent = parents[i6];
        }
      }
      declareLocal(parent, node.id);
    },
    Class: declareClass,
    CatchClause: declareCatchClause,
    ImportDefaultSpecifier: declareModuleSpecifier,
    ImportSpecifier: declareModuleSpecifier,
    ImportNamespaceSpecifier: declareModuleSpecifier
  }, walk4);
  function identifier(node, parents) {
    let name2 = node.name;
    if (name2 === "undefined")
      return;
    for (let i6 = parents.length - 2; i6 >= 0; --i6) {
      if (name2 === "arguments") {
        if (declaresArguments(parents[i6])) {
          return;
        }
      }
      if (hasLocal(parents[i6], name2)) {
        return;
      }
      if (parents[i6].type === "ViewExpression") {
        node = parents[i6];
        name2 = `viewof ${node.id.name}`;
      }
      if (parents[i6].type === "MutableExpression") {
        node = parents[i6];
        name2 = `mutable ${node.id.name}`;
      }
    }
    if (!globalSet.has(name2)) {
      if (name2 === "arguments") {
        throw Object.assign(new SyntaxError(`arguments is not allowed`), { node });
      }
      references.push(node);
    }
  }
  ancestor(ast, {
    VariablePattern: identifier,
    Identifier: identifier
  }, walk4);
  function checkConst(node, parents) {
    if (!node)
      return;
    switch (node.type) {
      case "Identifier":
      case "VariablePattern": {
        for (const parent of parents) {
          if (hasLocal(parent, node.name)) {
            return;
          }
        }
        if (parents[parents.length - 2].type === "MutableExpression") {
          return;
        }
        throw Object.assign(new SyntaxError(`Assignment to constant variable ${node.name}`), { node });
      }
      case "ArrayPattern": {
        for (const element of node.elements) {
          checkConst(element, parents);
        }
        return;
      }
      case "ObjectPattern": {
        for (const property of node.properties) {
          checkConst(property, parents);
        }
        return;
      }
      case "Property": {
        checkConst(node.value, parents);
        return;
      }
      case "RestElement": {
        checkConst(node.argument, parents);
        return;
      }
    }
  }
  function checkConstArgument(node, parents) {
    checkConst(node.argument, parents);
  }
  function checkConstLeft(node, parents) {
    checkConst(node.left, parents);
  }
  ancestor(ast, {
    AssignmentExpression: checkConstLeft,
    AssignmentPattern: checkConstLeft,
    UpdateExpression: checkConstArgument,
    ForOfStatement: checkConstLeft,
    ForInStatement: checkConstLeft
  }, walk4);
  return references;
}
function findFeatures(cell, featureName) {
  const ast = { type: "Program", body: [cell.body] };
  const features2 = /* @__PURE__ */ new Map();
  const { references } = cell;
  simple(ast, {
    CallExpression: (node) => {
      const { callee, arguments: args } = node;
      if (callee.type !== "Identifier" || callee.name !== featureName || references.indexOf(callee) < 0)
        return;
      if (args.length !== 1 || !(args[0].type === "Literal" && /^['"]/.test(args[0].raw) || args[0].type === "TemplateLiteral" && args[0].expressions.length === 0)) {
        throw Object.assign(new SyntaxError(`${featureName} requires a single literal string argument`), { node });
      }
      const [arg] = args;
      const name2 = arg.type === "Literal" ? arg.value : arg.quasis[0].value.cooked;
      const location = { start: arg.start, end: arg.end };
      if (features2.has(name2))
        features2.get(name2).push(location);
      else
        features2.set(name2, [location]);
    }
  }, walk4);
  return features2;
}
var SCOPE_FUNCTION2 = 2;
var SCOPE_ASYNC2 = 4;
var SCOPE_GENERATOR2 = 8;
var CellParser = class _CellParser extends Parser2 {
  constructor(options, ...args) {
    super(Object.assign({ ecmaVersion: 12 }, options), ...args);
  }
  enterScope(flags) {
    if (flags & SCOPE_FUNCTION2)
      ++this.O_function;
    return super.enterScope(flags);
  }
  exitScope() {
    if (this.currentScope().flags & SCOPE_FUNCTION2)
      --this.O_function;
    return super.exitScope();
  }
  parseForIn(node, init5) {
    if (this.O_function === 1 && node.await)
      this.O_async = true;
    return super.parseForIn(node, init5);
  }
  parseAwait() {
    if (this.O_function === 1)
      this.O_async = true;
    return super.parseAwait();
  }
  parseYield(noIn) {
    if (this.O_function === 1)
      this.O_generator = true;
    return super.parseYield(noIn);
  }
  parseImport(node) {
    this.next();
    node.specifiers = this.parseImportSpecifiers();
    if (this.type === types5._with) {
      this.next();
      node.injections = this.parseImportSpecifiers();
    }
    this.expectContextual("from");
    node.source = this.type === types5.string ? this.parseExprAtom() : this.unexpected();
    return this.finishNode(node, "ImportDeclaration");
  }
  parseImportSpecifiers() {
    const nodes = [];
    const identifiers = /* @__PURE__ */ new Set();
    let first = true;
    this.expect(types5.braceL);
    while (!this.eat(types5.braceR)) {
      if (first) {
        first = false;
      } else {
        this.expect(types5.comma);
        if (this.afterTrailingComma(types5.braceR))
          break;
      }
      const node = this.startNode();
      node.view = this.eatContextual("viewof");
      node.mutable = node.view ? false : this.eatContextual("mutable");
      node.imported = this.parseIdent();
      this.checkUnreserved(node.imported);
      this.checkLocal(node.imported);
      if (this.eatContextual("as")) {
        node.local = this.parseIdent();
        this.checkUnreserved(node.local);
        this.checkLocal(node.local);
      } else {
        node.local = node.imported;
      }
      this.checkLVal(node.local, "let");
      if (identifiers.has(node.local.name)) {
        this.raise(node.local.start, `Identifier '${node.local.name}' has already been declared`);
      }
      identifiers.add(node.local.name);
      nodes.push(this.finishNode(node, "ImportSpecifier"));
    }
    return nodes;
  }
  parseExprAtom(refDestructuringErrors) {
    return this.parseMaybeKeywordExpression("viewof", "ViewExpression") || this.parseMaybeKeywordExpression("mutable", "MutableExpression") || super.parseExprAtom(refDestructuringErrors);
  }
  startCell() {
    this.O_function = 0;
    this.O_async = false;
    this.O_generator = false;
    this.strict = true;
    this.enterScope(SCOPE_FUNCTION2 | SCOPE_ASYNC2 | SCOPE_GENERATOR2);
  }
  finishCell(node, body, id) {
    if (id)
      this.checkLocal(id);
    node.id = id;
    node.body = body;
    node.async = this.O_async;
    node.generator = this.O_generator;
    this.exitScope();
    return this.finishNode(node, "Cell");
  }
  parseCell(node, eof) {
    const lookahead3 = new _CellParser({}, this.input, this.start);
    let token = lookahead3.getToken();
    let body = null;
    let id = null;
    this.startCell();
    if (token.type === types5._import && lookahead3.getToken().type !== types5.parenL) {
      body = this.parseImport(this.startNode());
    } else if (token.type !== types5.eof && token.type !== types5.semi) {
      if (token.type === types5.name) {
        if (token.value === "viewof" || token.value === "mutable") {
          token = lookahead3.getToken();
          if (token.type !== types5.name) {
            lookahead3.unexpected();
          }
        }
        token = lookahead3.getToken();
        if (token.type === types5.eq) {
          id = this.parseMaybeKeywordExpression("viewof", "ViewExpression") || this.parseMaybeKeywordExpression("mutable", "MutableExpression") || this.parseIdent();
          token = lookahead3.getToken();
          this.expect(types5.eq);
        }
      }
      if (token.type === types5.braceL) {
        body = this.parseBlock();
      } else {
        body = this.parseExpression();
        if (id === null && (body.type === "FunctionExpression" || body.type === "ClassExpression")) {
          id = body.id;
        }
      }
    }
    this.semicolon();
    if (eof)
      this.expect(types5.eof);
    return this.finishCell(node, body, id);
  }
  parseTopLevel(node) {
    return this.parseCell(node, true);
  }
  toAssignable(node, isBinding, refDestructuringErrors) {
    return node.type === "MutableExpression" ? node : super.toAssignable(node, isBinding, refDestructuringErrors);
  }
  checkLocal(id) {
    const node = id.id || id;
    if (defaultGlobals.has(node.name) || node.name === "arguments") {
      this.raise(node.start, `Identifier '${node.name}' is reserved`);
    }
  }
  checkUnreserved(node) {
    if (node.name === "viewof" || node.name === "mutable") {
      this.raise(node.start, `Unexpected keyword '${node.name}'`);
    }
    return super.checkUnreserved(node);
  }
  checkLVal(expr, bindingType, checkClashes) {
    return super.checkLVal(expr.type === "MutableExpression" ? expr.id : expr, bindingType, checkClashes);
  }
  unexpected(pos) {
    this.raise(pos != null ? pos : this.start, this.type === types5.eof ? "Unexpected end of input" : "Unexpected token");
  }
  parseMaybeKeywordExpression(keyword, type4) {
    if (this.isContextual(keyword)) {
      const node = this.startNode();
      this.next();
      node.id = this.parseIdent();
      return this.finishNode(node, type4);
    }
  }
};
var o_tmpl = new TokContext("`", true, true, (parser) => readTemplateToken.call(parser));
function readTemplateToken() {
  out:
    for (; this.pos < this.input.length; this.pos++) {
      switch (this.input.charCodeAt(this.pos)) {
        case 92: {
          if (this.pos < this.input.length - 1)
            ++this.pos;
          break;
        }
        case 36: {
          if (this.input.charCodeAt(this.pos + 1) === 123) {
            if (this.pos === this.start && this.type === types5.invalidTemplate) {
              this.pos += 2;
              return this.finishToken(types5.dollarBraceL);
            }
            break out;
          }
          break;
        }
      }
    }
  return this.finishToken(types5.invalidTemplate, this.input.slice(this.start, this.pos));
}
function parseModule(input, { globals } = {}) {
  const program = ModuleParser.parse(input);
  for (const cell of program.cells) {
    parseReferences(cell, input, globals);
    parseFeatures(cell, input);
  }
  return program;
}
var ModuleParser = class extends CellParser {
  parseTopLevel(node) {
    if (!node.cells)
      node.cells = [];
    while (this.type !== types5.eof) {
      const cell = this.parseCell(this.startNode());
      cell.input = this.input;
      node.cells.push(cell);
    }
    this.next();
    return this.finishNode(node, "Program");
  }
};
function parseReferences(cell, input, globals = defaultGlobals) {
  if (!cell.body) {
    cell.references = [];
  } else if (cell.body.type === "ImportDeclaration") {
    cell.references = cell.body.injections ? cell.body.injections.map((i6) => i6.imported) : [];
  } else {
    try {
      cell.references = findReferences(cell, globals);
    } catch (error2) {
      if (error2.node) {
        const loc = getLineInfo(input, error2.node.start);
        error2.message += ` (${loc.line}:${loc.column})`;
        error2.pos = error2.node.start;
        error2.loc = loc;
        delete error2.node;
      }
      throw error2;
    }
  }
  return cell;
}
function parseFeatures(cell, input) {
  if (cell.body && cell.body.type !== "ImportDeclaration") {
    try {
      cell.fileAttachments = findFeatures(cell, "FileAttachment");
      cell.databaseClients = findFeatures(cell, "DatabaseClient");
      cell.secrets = findFeatures(cell, "Secret");
    } catch (error2) {
      if (error2.node) {
        const loc = getLineInfo(input, error2.node.start);
        error2.message += ` (${loc.line}:${loc.column})`;
        error2.pos = error2.node.start;
        error2.loc = loc;
        delete error2.node;
      }
      throw error2;
    }
  } else {
    cell.fileAttachments = /* @__PURE__ */ new Map();
    cell.databaseClients = /* @__PURE__ */ new Map();
    cell.secrets = /* @__PURE__ */ new Map();
  }
  return cell;
}

// https://cdn.skypack.dev/-/acorn@v8.4.0-0ut9V0ADuEAiFqlHW4SG/dist=es2019,mode=imports/optimized/acorn.js
var reservedWords2 = {
  3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",
  5: "class enum extends super const export import",
  6: "enum",
  strict: "implements interface let package private protected public static yield",
  strictBind: "eval arguments"
};
var ecma5AndLessKeywords2 = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";
var keywords2 = {
  5: ecma5AndLessKeywords2,
  "5module": ecma5AndLessKeywords2 + " export import",
  6: ecma5AndLessKeywords2 + " const class extends export import super"
};
var keywordRelationalOperator2 = /^in(stanceof)?$/;
var nonASCIIidentifierStartChars2 = "\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\u08A0-\u08B4\u08B6-\u08C7\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\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\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-\u170C\u170E-\u1711\u1720-\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-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\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-\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-\u312F\u3131-\u318E\u31A0-\u31BF\u31F0-\u31FF\u3400-\u4DBF\u4E00-\u9FFC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7BF\uA7C2-\uA7CA\uA7F5-\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 nonASCIIidentifierChars2 = "\u200C\u200D\xB7\u0300-\u036F\u0387\u0483-\u0487\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u0669\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07C0-\u07C9\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\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\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\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-\u0ECD\u0ED0-\u0ED9\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1040-\u1049\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F-\u109D\u135D-\u135F\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u18A9\u1920-\u192B\u1930-\u193B\u1946-\u194F\u19D0-\u19DA\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AB0-\u1ABD\u1ABF\u1AC0\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-\u1DF9\u1DFB-\u1DFF\u203F\u2040\u2054\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA620-\uA629\uA66F\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\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";
var nonASCIIidentifierStart2 = new RegExp("[" + nonASCIIidentifierStartChars2 + "]");
var nonASCIIidentifier2 = new RegExp("[" + nonASCIIidentifierStartChars2 + nonASCIIidentifierChars2 + "]");
nonASCIIidentifierStartChars2 = nonASCIIidentifierChars2 = null;
var astralIdentifierStartCodes2 = [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, 157, 310, 10, 21, 11, 7, 153, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 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, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 107, 20, 28, 22, 13, 52, 76, 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, 85, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 230, 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, 35, 56, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 190, 0, 80, 921, 103, 110, 18, 195, 2749, 1070, 4050, 582, 8634, 568, 8, 30, 114, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8952, 286, 50, 2, 18, 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, 2357, 44, 11, 6, 17, 0, 370, 43, 1301, 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, 42717, 35, 4148, 12, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938];
var astralIdentifierCodes2 = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 154, 10, 176, 2, 54, 14, 32, 9, 16, 3, 46, 10, 54, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 161, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 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, 406, 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, 330, 3, 19306, 9, 135, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 5319, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 262, 6, 10, 9, 419, 13, 1495, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
function isInAstralSet2(code5, set3) {
  var pos = 65536;
  for (var i6 = 0; i6 < set3.length; i6 += 2) {
    pos += set3[i6];
    if (pos > code5) {
      return false;
    }
    pos += set3[i6 + 1];
    if (pos >= code5) {
      return true;
    }
  }
}
function isIdentifierStart2(code5, astral) {
  if (code5 < 65) {
    return code5 === 36;
  }
  if (code5 < 91) {
    return true;
  }
  if (code5 < 97) {
    return code5 === 95;
  }
  if (code5 < 123) {
    return true;
  }
  if (code5 <= 65535) {
    return code5 >= 170 && nonASCIIidentifierStart2.test(String.fromCharCode(code5));
  }
  if (astral === false) {
    return false;
  }
  return isInAstralSet2(code5, astralIdentifierStartCodes2);
}
function isIdentifierChar2(code5, astral) {
  if (code5 < 48) {
    return code5 === 36;
  }
  if (code5 < 58) {
    return true;
  }
  if (code5 < 65) {
    return false;
  }
  if (code5 < 91) {
    return true;
  }
  if (code5 < 97) {
    return code5 === 95;
  }
  if (code5 < 123) {
    return true;
  }
  if (code5 <= 65535) {
    return code5 >= 170 && nonASCIIidentifier2.test(String.fromCharCode(code5));
  }
  if (astral === false) {
    return false;
  }
  return isInAstralSet2(code5, astralIdentifierStartCodes2) || isInAstralSet2(code5, astralIdentifierCodes2);
}
var TokenType3 = function TokenType22(label, conf) {
  if (conf === void 0)
    conf = {};
  this.label = label;
  this.keyword = conf.keyword;
  this.beforeExpr = !!conf.beforeExpr;
  this.startsExpr = !!conf.startsExpr;
  this.isLoop = !!conf.isLoop;
  this.isAssign = !!conf.isAssign;
  this.prefix = !!conf.prefix;
  this.postfix = !!conf.postfix;
  this.binop = conf.binop || null;
  this.updateContext = null;
};
function binop2(name2, prec) {
  return new TokenType3(name2, { beforeExpr: true, binop: prec });
}
var beforeExpr2 = { beforeExpr: true };
var startsExpr2 = { startsExpr: true };
var keywords$12 = {};
function kw2(name2, options) {
  if (options === void 0)
    options = {};
  options.keyword = name2;
  return keywords$12[name2] = new TokenType3(name2, options);
}
var types6 = {
  num: new TokenType3("num", startsExpr2),
  regexp: new TokenType3("regexp", startsExpr2),
  string: new TokenType3("string", startsExpr2),
  name: new TokenType3("name", startsExpr2),
  privateId: new TokenType3("privateId", startsExpr2),
  eof: new TokenType3("eof"),
  bracketL: new TokenType3("[", { beforeExpr: true, startsExpr: true }),
  bracketR: new TokenType3("]"),
  braceL: new TokenType3("{", { beforeExpr: true, startsExpr: true }),
  braceR: new TokenType3("}"),
  parenL: new TokenType3("(", { beforeExpr: true, startsExpr: true }),
  parenR: new TokenType3(")"),
  comma: new TokenType3(",", beforeExpr2),
  semi: new TokenType3(";", beforeExpr2),
  colon: new TokenType3(":", beforeExpr2),
  dot: new TokenType3("."),
  question: new TokenType3("?", beforeExpr2),
  questionDot: new TokenType3("?."),
  arrow: new TokenType3("=>", beforeExpr2),
  template: new TokenType3("template"),
  invalidTemplate: new TokenType3("invalidTemplate"),
  ellipsis: new TokenType3("...", beforeExpr2),
  backQuote: new TokenType3("`", startsExpr2),
  dollarBraceL: new TokenType3("${", { beforeExpr: true, startsExpr: true }),
  eq: new TokenType3("=", { beforeExpr: true, isAssign: true }),
  assign: new TokenType3("_=", { beforeExpr: true, isAssign: true }),
  incDec: new TokenType3("++/--", { prefix: true, postfix: true, startsExpr: true }),
  prefix: new TokenType3("!/~", { beforeExpr: true, prefix: true, startsExpr: true }),
  logicalOR: binop2("||", 1),
  logicalAND: binop2("&&", 2),
  bitwiseOR: binop2("|", 3),
  bitwiseXOR: binop2("^", 4),
  bitwiseAND: binop2("&", 5),
  equality: binop2("==/!=/===/!==", 6),
  relational: binop2("</>/<=/>=", 7),
  bitShift: binop2("<</>>/>>>", 8),
  plusMin: new TokenType3("+/-", { beforeExpr: true, binop: 9, prefix: true, startsExpr: true }),
  modulo: binop2("%", 10),
  star: binop2("*", 10),
  slash: binop2("/", 10),
  starstar: new TokenType3("**", { beforeExpr: true }),
  coalesce: binop2("??", 1),
  _break: kw2("break"),
  _case: kw2("case", beforeExpr2),
  _catch: kw2("catch"),
  _continue: kw2("continue"),
  _debugger: kw2("debugger"),
  _default: kw2("default", beforeExpr2),
  _do: kw2("do", { isLoop: true, beforeExpr: true }),
  _else: kw2("else", beforeExpr2),
  _finally: kw2("finally"),
  _for: kw2("for", { isLoop: true }),
  _function: kw2("function", startsExpr2),
  _if: kw2("if"),
  _return: kw2("return", beforeExpr2),
  _switch: kw2("switch"),
  _throw: kw2("throw", beforeExpr2),
  _try: kw2("try"),
  _var: kw2("var"),
  _const: kw2("const"),
  _while: kw2("while", { isLoop: true }),
  _with: kw2("with"),
  _new: kw2("new", { beforeExpr: true, startsExpr: true }),
  _this: kw2("this", startsExpr2),
  _super: kw2("super", startsExpr2),
  _class: kw2("class", startsExpr2),
  _extends: kw2("extends", beforeExpr2),
  _export: kw2("export"),
  _import: kw2("import", startsExpr2),
  _null: kw2("null", startsExpr2),
  _true: kw2("true", startsExpr2),
  _false: kw2("false", startsExpr2),
  _in: kw2("in", { beforeExpr: true, binop: 7 }),
  _instanceof: kw2("instanceof", { beforeExpr: true, binop: 7 }),
  _typeof: kw2("typeof", { beforeExpr: true, prefix: true, startsExpr: true }),
  _void: kw2("void", { beforeExpr: true, prefix: true, startsExpr: true }),
  _delete: kw2("delete", { beforeExpr: true, prefix: true, startsExpr: true })
};
var lineBreak2 = /\r\n?|\n|\u2028|\u2029/;
var lineBreakG2 = new RegExp(lineBreak2.source, "g");
function isNewLine2(code5, ecma2019String) {
  return code5 === 10 || code5 === 13 || !ecma2019String && (code5 === 8232 || code5 === 8233);
}
var nonASCIIwhitespace2 = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
var skipWhiteSpace2 = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
var ref2 = Object.prototype;
var hasOwnProperty2 = ref2.hasOwnProperty;
var toString7 = ref2.toString;
function has2(obj, propName) {
  return hasOwnProperty2.call(obj, propName);
}
var isArray5 = Array.isArray || function(obj) {
  return toString7.call(obj) === "[object Array]";
};
function wordsRegexp2(words) {
  return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$");
}
var Position3 = function Position22(line, col) {
  this.line = line;
  this.column = col;
};
Position3.prototype.offset = function offset2(n5) {
  return new Position3(this.line, this.column + n5);
};
var SourceLocation3 = function SourceLocation22(p5, start, end) {
  this.start = start;
  this.end = end;
  if (p5.sourceFile !== null) {
    this.source = p5.sourceFile;
  }
};
function getLineInfo2(input, offset22) {
  for (var line = 1, cur = 0; ; ) {
    lineBreakG2.lastIndex = cur;
    var match = lineBreakG2.exec(input);
    if (match && match.index < offset22) {
      ++line;
      cur = match.index + match[0].length;
    } else {
      return new Position3(line, offset22 - cur);
    }
  }
}
var defaultOptions2 = {
  ecmaVersion: null,
  sourceType: "script",
  onInsertedSemicolon: null,
  onTrailingComma: null,
  allowReserved: null,
  allowReturnOutsideFunction: false,
  allowImportExportEverywhere: false,
  allowAwaitOutsideFunction: null,
  allowSuperOutsideMethod: null,
  allowHashBang: false,
  locations: false,
  onToken: null,
  onComment: null,
  ranges: false,
  program: null,
  sourceFile: null,
  directSourceFile: null,
  preserveParens: false
};
var warnedAboutEcmaVersion = false;
function getOptions2(opts) {
  var options = {};
  for (var opt in defaultOptions2) {
    options[opt] = opts && has2(opts, opt) ? opts[opt] : defaultOptions2[opt];
  }
  if (options.ecmaVersion === "latest") {
    options.ecmaVersion = 1e8;
  } else if (options.ecmaVersion == null) {
    if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) {
      warnedAboutEcmaVersion = true;
      console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.");
    }
    options.ecmaVersion = 11;
  } else if (options.ecmaVersion >= 2015) {
    options.ecmaVersion -= 2009;
  }
  if (options.allowReserved == null) {
    options.allowReserved = options.ecmaVersion < 5;
  }
  if (options.allowAwaitOutsideFunction == null) {
    options.allowAwaitOutsideFunction = options.ecmaVersion >= 13;
  }
  if (isArray5(options.onToken)) {
    var tokens2 = options.onToken;
    options.onToken = function(token) {
      return tokens2.push(token);
    };
  }
  if (isArray5(options.onComment)) {
    options.onComment = pushComment2(options, options.onComment);
  }
  return options;
}
function pushComment2(options, array) {
  return function(block, text, start, end, startLoc, endLoc) {
    var comment = {
      type: block ? "Block" : "Line",
      value: text,
      start,
      end
    };
    if (options.locations) {
      comment.loc = new SourceLocation3(this, startLoc, endLoc);
    }
    if (options.ranges) {
      comment.range = [start, end];
    }
    array.push(comment);
  };
}
var SCOPE_TOP2 = 1;
var SCOPE_FUNCTION3 = 2;
var SCOPE_VAR2 = SCOPE_TOP2 | SCOPE_FUNCTION3;
var SCOPE_ASYNC3 = 4;
var SCOPE_GENERATOR3 = 8;
var SCOPE_ARROW2 = 16;
var SCOPE_SIMPLE_CATCH2 = 32;
var SCOPE_SUPER2 = 64;
var SCOPE_DIRECT_SUPER2 = 128;
function functionFlags2(async, generator) {
  return SCOPE_FUNCTION3 | (async ? SCOPE_ASYNC3 : 0) | (generator ? SCOPE_GENERATOR3 : 0);
}
var BIND_NONE2 = 0;
var BIND_VAR2 = 1;
var BIND_LEXICAL2 = 2;
var BIND_FUNCTION2 = 3;
var BIND_SIMPLE_CATCH2 = 4;
var BIND_OUTSIDE2 = 5;
var Parser3 = function Parser23(options, input, startPos) {
  this.options = options = getOptions2(options);
  this.sourceFile = options.sourceFile;
  this.keywords = wordsRegexp2(keywords2[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
  var reserved = "";
  if (options.allowReserved !== true) {
    reserved = reservedWords2[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3];
    if (options.sourceType === "module") {
      reserved += " await";
    }
  }
  this.reservedWords = wordsRegexp2(reserved);
  var reservedStrict = (reserved ? reserved + " " : "") + reservedWords2.strict;
  this.reservedWordsStrict = wordsRegexp2(reservedStrict);
  this.reservedWordsStrictBind = wordsRegexp2(reservedStrict + " " + reservedWords2.strictBind);
  this.input = String(input);
  this.containsEsc = false;
  if (startPos) {
    this.pos = startPos;
    this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
    this.curLine = this.input.slice(0, this.lineStart).split(lineBreak2).length;
  } else {
    this.pos = this.lineStart = 0;
    this.curLine = 1;
  }
  this.type = types6.eof;
  this.value = null;
  this.start = this.end = this.pos;
  this.startLoc = this.endLoc = this.curPosition();
  this.lastTokEndLoc = this.lastTokStartLoc = null;
  this.lastTokStart = this.lastTokEnd = this.pos;
  this.context = this.initialContext();
  this.exprAllowed = true;
  this.inModule = options.sourceType === "module";
  this.strict = this.inModule || this.strictDirective(this.pos);
  this.potentialArrowAt = -1;
  this.potentialArrowInForAwait = false;
  this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
  this.labels = [];
  this.undefinedExports = /* @__PURE__ */ Object.create(null);
  if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!") {
    this.skipLineComment(2);
  }
  this.scopeStack = [];
  this.enterScope(SCOPE_TOP2);
  this.regexpState = null;
  this.privateNameStack = [];
};
var prototypeAccessors2 = { inFunction: { configurable: true }, inGenerator: { configurable: true }, inAsync: { configurable: true }, allowSuper: { configurable: true }, allowDirectSuper: { configurable: true }, treatFunctionsAsVar: { configurable: true }, inNonArrowFunction: { configurable: true } };
Parser3.prototype.parse = function parse14() {
  var node = this.options.program || this.startNode();
  this.nextToken();
  return this.parseTopLevel(node);
};
prototypeAccessors2.inFunction.get = function() {
  return (this.currentVarScope().flags & SCOPE_FUNCTION3) > 0;
};
prototypeAccessors2.inGenerator.get = function() {
  return (this.currentVarScope().flags & SCOPE_GENERATOR3) > 0 && !this.currentVarScope().inClassFieldInit;
};
prototypeAccessors2.inAsync.get = function() {
  return (this.currentVarScope().flags & SCOPE_ASYNC3) > 0 && !this.currentVarScope().inClassFieldInit;
};
prototypeAccessors2.allowSuper.get = function() {
  var ref22 = this.currentThisScope();
  var flags = ref22.flags;
  var inClassFieldInit = ref22.inClassFieldInit;
  return (flags & SCOPE_SUPER2) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod;
};
prototypeAccessors2.allowDirectSuper.get = function() {
  return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER2) > 0;
};
prototypeAccessors2.treatFunctionsAsVar.get = function() {
  return this.treatFunctionsAsVarInScope(this.currentScope());
};
prototypeAccessors2.inNonArrowFunction.get = function() {
  var ref22 = this.currentThisScope();
  var flags = ref22.flags;
  var inClassFieldInit = ref22.inClassFieldInit;
  return (flags & SCOPE_FUNCTION3) > 0 || inClassFieldInit;
};
Parser3.extend = function extend5() {
  var plugins = [], len = arguments.length;
  while (len--)
    plugins[len] = arguments[len];
  var cls = this;
  for (var i6 = 0; i6 < plugins.length; i6++) {
    cls = plugins[i6](cls);
  }
  return cls;
};
Parser3.parse = function parse23(input, options) {
  return new this(options, input).parse();
};
Parser3.parseExpressionAt = function parseExpressionAt2(input, pos, options) {
  var parser = new this(options, input, pos);
  parser.nextToken();
  return parser.parseExpression();
};
Parser3.tokenizer = function tokenizer2(input, options) {
  return new this(options, input);
};
Object.defineProperties(Parser3.prototype, prototypeAccessors2);
var pp2 = Parser3.prototype;
var literal2 = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/;
pp2.strictDirective = function(start) {
  for (; ; ) {
    skipWhiteSpace2.lastIndex = start;
    start += skipWhiteSpace2.exec(this.input)[0].length;
    var match = literal2.exec(this.input.slice(start));
    if (!match) {
      return false;
    }
    if ((match[1] || match[2]) === "use strict") {
      skipWhiteSpace2.lastIndex = start + match[0].length;
      var spaceAfter = skipWhiteSpace2.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;
      var next = this.input.charAt(end);
      return next === ";" || next === "}" || lineBreak2.test(spaceAfter[0]) && !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "=");
    }
    start += match[0].length;
    skipWhiteSpace2.lastIndex = start;
    start += skipWhiteSpace2.exec(this.input)[0].length;
    if (this.input[start] === ";") {
      start++;
    }
  }
};
pp2.eat = function(type4) {
  if (this.type === type4) {
    this.next();
    return true;
  } else {
    return false;
  }
};
pp2.isContextual = function(name2) {
  return this.type === types6.name && this.value === name2 && !this.containsEsc;
};
pp2.eatContextual = function(name2) {
  if (!this.isContextual(name2)) {
    return false;
  }
  this.next();
  return true;
};
pp2.expectContextual = function(name2) {
  if (!this.eatContextual(name2)) {
    this.unexpected();
  }
};
pp2.canInsertSemicolon = function() {
  return this.type === types6.eof || this.type === types6.braceR || lineBreak2.test(this.input.slice(this.lastTokEnd, this.start));
};
pp2.insertSemicolon = function() {
  if (this.canInsertSemicolon()) {
    if (this.options.onInsertedSemicolon) {
      this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc);
    }
    return true;
  }
};
pp2.semicolon = function() {
  if (!this.eat(types6.semi) && !this.insertSemicolon()) {
    this.unexpected();
  }
};
pp2.afterTrailingComma = function(tokType, notNext) {
  if (this.type === tokType) {
    if (this.options.onTrailingComma) {
      this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc);
    }
    if (!notNext) {
      this.next();
    }
    return true;
  }
};
pp2.expect = function(type4) {
  this.eat(type4) || this.unexpected();
};
pp2.unexpected = function(pos) {
  this.raise(pos != null ? pos : this.start, "Unexpected token");
};
function DestructuringErrors2() {
  this.shorthandAssign = this.trailingComma = this.parenthesizedAssign = this.parenthesizedBind = this.doubleProto = -1;
}
pp2.checkPatternErrors = function(refDestructuringErrors, isAssign) {
  if (!refDestructuringErrors) {
    return;
  }
  if (refDestructuringErrors.trailingComma > -1) {
    this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element");
  }
  var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
  if (parens > -1) {
    this.raiseRecoverable(parens, "Parenthesized pattern");
  }
};
pp2.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
  if (!refDestructuringErrors) {
    return false;
  }
  var shorthandAssign = refDestructuringErrors.shorthandAssign;
  var doubleProto = refDestructuringErrors.doubleProto;
  if (!andThrow) {
    return shorthandAssign >= 0 || doubleProto >= 0;
  }
  if (shorthandAssign >= 0) {
    this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns");
  }
  if (doubleProto >= 0) {
    this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property");
  }
};
pp2.checkYieldAwaitInDefaultParams = function() {
  if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos)) {
    this.raise(this.yieldPos, "Yield expression cannot be a default value");
  }
  if (this.awaitPos) {
    this.raise(this.awaitPos, "Await expression cannot be a default value");
  }
};
pp2.isSimpleAssignTarget = function(expr) {
  if (expr.type === "ParenthesizedExpression") {
    return this.isSimpleAssignTarget(expr.expression);
  }
  return expr.type === "Identifier" || expr.type === "MemberExpression";
};
var pp$12 = Parser3.prototype;
pp$12.parseTopLevel = function(node) {
  var exports23 = /* @__PURE__ */ Object.create(null);
  if (!node.body) {
    node.body = [];
  }
  while (this.type !== types6.eof) {
    var stmt = this.parseStatement(null, true, exports23);
    node.body.push(stmt);
  }
  if (this.inModule) {
    for (var i6 = 0, list = Object.keys(this.undefinedExports); i6 < list.length; i6 += 1) {
      var name2 = list[i6];
      this.raiseRecoverable(this.undefinedExports[name2].start, "Export '" + name2 + "' is not defined");
    }
  }
  this.adaptDirectivePrologue(node.body);
  this.next();
  node.sourceType = this.options.sourceType;
  return this.finishNode(node, "Program");
};
var loopLabel2 = { kind: "loop" };
var switchLabel2 = { kind: "switch" };
pp$12.isLet = function(context) {
  if (this.options.ecmaVersion < 6 || !this.isContextual("let")) {
    return false;
  }
  skipWhiteSpace2.lastIndex = this.pos;
  var skip = skipWhiteSpace2.exec(this.input);
  var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  if (nextCh === 91 || nextCh === 92 || nextCh > 55295 && nextCh < 56320) {
    return true;
  }
  if (context) {
    return false;
  }
  if (nextCh === 123) {
    return true;
  }
  if (isIdentifierStart2(nextCh, true)) {
    var pos = next + 1;
    while (isIdentifierChar2(nextCh = this.input.charCodeAt(pos), true)) {
      ++pos;
    }
    if (nextCh === 92 || nextCh > 55295 && nextCh < 56320) {
      return true;
    }
    var ident = this.input.slice(next, pos);
    if (!keywordRelationalOperator2.test(ident)) {
      return true;
    }
  }
  return false;
};
pp$12.isAsyncFunction = function() {
  if (this.options.ecmaVersion < 8 || !this.isContextual("async")) {
    return false;
  }
  skipWhiteSpace2.lastIndex = this.pos;
  var skip = skipWhiteSpace2.exec(this.input);
  var next = this.pos + skip[0].length, after;
  return !lineBreak2.test(this.input.slice(this.pos, next)) && this.input.slice(next, next + 8) === "function" && (next + 8 === this.input.length || !(isIdentifierChar2(after = this.input.charCodeAt(next + 8)) || after > 55295 && after < 56320));
};
pp$12.parseStatement = function(context, topLevel, exports23) {
  var starttype = this.type, node = this.startNode(), kind;
  if (this.isLet(context)) {
    starttype = types6._var;
    kind = "let";
  }
  switch (starttype) {
    case types6._break:
    case types6._continue:
      return this.parseBreakContinueStatement(node, starttype.keyword);
    case types6._debugger:
      return this.parseDebuggerStatement(node);
    case types6._do:
      return this.parseDoStatement(node);
    case types6._for:
      return this.parseForStatement(node);
    case types6._function:
      if (context && (this.strict || context !== "if" && context !== "label") && this.options.ecmaVersion >= 6) {
        this.unexpected();
      }
      return this.parseFunctionStatement(node, false, !context);
    case types6._class:
      if (context) {
        this.unexpected();
      }
      return this.parseClass(node, true);
    case types6._if:
      return this.parseIfStatement(node);
    case types6._return:
      return this.parseReturnStatement(node);
    case types6._switch:
      return this.parseSwitchStatement(node);
    case types6._throw:
      return this.parseThrowStatement(node);
    case types6._try:
      return this.parseTryStatement(node);
    case types6._const:
    case types6._var:
      kind = kind || this.value;
      if (context && kind !== "var") {
        this.unexpected();
      }
      return this.parseVarStatement(node, kind);
    case types6._while:
      return this.parseWhileStatement(node);
    case types6._with:
      return this.parseWithStatement(node);
    case types6.braceL:
      return this.parseBlock(true, node);
    case types6.semi:
      return this.parseEmptyStatement(node);
    case types6._export:
    case types6._import:
      if (this.options.ecmaVersion > 10 && starttype === types6._import) {
        skipWhiteSpace2.lastIndex = this.pos;
        var skip = skipWhiteSpace2.exec(this.input);
        var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
        if (nextCh === 40 || nextCh === 46) {
          return this.parseExpressionStatement(node, this.parseExpression());
        }
      }
      if (!this.options.allowImportExportEverywhere) {
        if (!topLevel) {
          this.raise(this.start, "'import' and 'export' may only appear at the top level");
        }
        if (!this.inModule) {
          this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'");
        }
      }
      return starttype === types6._import ? this.parseImport(node) : this.parseExport(node, exports23);
    default:
      if (this.isAsyncFunction()) {
        if (context) {
          this.unexpected();
        }
        this.next();
        return this.parseFunctionStatement(node, true, !context);
      }
      var maybeName = this.value, expr = this.parseExpression();
      if (starttype === types6.name && expr.type === "Identifier" && this.eat(types6.colon)) {
        return this.parseLabeledStatement(node, maybeName, expr, context);
      } else {
        return this.parseExpressionStatement(node, expr);
      }
  }
};
pp$12.parseBreakContinueStatement = function(node, keyword) {
  var isBreak = keyword === "break";
  this.next();
  if (this.eat(types6.semi) || this.insertSemicolon()) {
    node.label = null;
  } else if (this.type !== types6.name) {
    this.unexpected();
  } else {
    node.label = this.parseIdent();
    this.semicolon();
  }
  var i6 = 0;
  for (; i6 < this.labels.length; ++i6) {
    var lab = this.labels[i6];
    if (node.label == null || lab.name === node.label.name) {
      if (lab.kind != null && (isBreak || lab.kind === "loop")) {
        break;
      }
      if (node.label && isBreak) {
        break;
      }
    }
  }
  if (i6 === this.labels.length) {
    this.raise(node.start, "Unsyntactic " + keyword);
  }
  return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
};
pp$12.parseDebuggerStatement = function(node) {
  this.next();
  this.semicolon();
  return this.finishNode(node, "DebuggerStatement");
};
pp$12.parseDoStatement = function(node) {
  this.next();
  this.labels.push(loopLabel2);
  node.body = this.parseStatement("do");
  this.labels.pop();
  this.expect(types6._while);
  node.test = this.parseParenExpression();
  if (this.options.ecmaVersion >= 6) {
    this.eat(types6.semi);
  } else {
    this.semicolon();
  }
  return this.finishNode(node, "DoWhileStatement");
};
pp$12.parseForStatement = function(node) {
  this.next();
  var awaitAt = this.options.ecmaVersion >= 9 && (this.inAsync || !this.inFunction && this.options.allowAwaitOutsideFunction) && this.eatContextual("await") ? this.lastTokStart : -1;
  this.labels.push(loopLabel2);
  this.enterScope(0);
  this.expect(types6.parenL);
  if (this.type === types6.semi) {
    if (awaitAt > -1) {
      this.unexpected(awaitAt);
    }
    return this.parseFor(node, null);
  }
  var isLet = this.isLet();
  if (this.type === types6._var || this.type === types6._const || isLet) {
    var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
    this.next();
    this.parseVar(init$1, true, kind);
    this.finishNode(init$1, "VariableDeclaration");
    if ((this.type === types6._in || this.options.ecmaVersion >= 6 && this.isContextual("of")) && init$1.declarations.length === 1) {
      if (this.options.ecmaVersion >= 9) {
        if (this.type === types6._in) {
          if (awaitAt > -1) {
            this.unexpected(awaitAt);
          }
        } else {
          node.await = awaitAt > -1;
        }
      }
      return this.parseForIn(node, init$1);
    }
    if (awaitAt > -1) {
      this.unexpected(awaitAt);
    }
    return this.parseFor(node, init$1);
  }
  var refDestructuringErrors = new DestructuringErrors2();
  var init5 = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors);
  if (this.type === types6._in || this.options.ecmaVersion >= 6 && this.isContextual("of")) {
    if (this.options.ecmaVersion >= 9) {
      if (this.type === types6._in) {
        if (awaitAt > -1) {
          this.unexpected(awaitAt);
        }
      } else {
        node.await = awaitAt > -1;
      }
    }
    this.toAssignable(init5, false, refDestructuringErrors);
    this.checkLValPattern(init5);
    return this.parseForIn(node, init5);
  } else {
    this.checkExpressionErrors(refDestructuringErrors, true);
  }
  if (awaitAt > -1) {
    this.unexpected(awaitAt);
  }
  return this.parseFor(node, init5);
};
pp$12.parseFunctionStatement = function(node, isAsync2, declarationPosition) {
  this.next();
  return this.parseFunction(node, FUNC_STATEMENT2 | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT2), false, isAsync2);
};
pp$12.parseIfStatement = function(node) {
  this.next();
  node.test = this.parseParenExpression();
  node.consequent = this.parseStatement("if");
  node.alternate = this.eat(types6._else) ? this.parseStatement("if") : null;
  return this.finishNode(node, "IfStatement");
};
pp$12.parseReturnStatement = function(node) {
  if (!this.inFunction && !this.options.allowReturnOutsideFunction) {
    this.raise(this.start, "'return' outside of function");
  }
  this.next();
  if (this.eat(types6.semi) || this.insertSemicolon()) {
    node.argument = null;
  } else {
    node.argument = this.parseExpression();
    this.semicolon();
  }
  return this.finishNode(node, "ReturnStatement");
};
pp$12.parseSwitchStatement = function(node) {
  this.next();
  node.discriminant = this.parseParenExpression();
  node.cases = [];
  this.expect(types6.braceL);
  this.labels.push(switchLabel2);
  this.enterScope(0);
  var cur;
  for (var sawDefault = false; this.type !== types6.braceR; ) {
    if (this.type === types6._case || this.type === types6._default) {
      var isCase = this.type === types6._case;
      if (cur) {
        this.finishNode(cur, "SwitchCase");
      }
      node.cases.push(cur = this.startNode());
      cur.consequent = [];
      this.next();
      if (isCase) {
        cur.test = this.parseExpression();
      } else {
        if (sawDefault) {
          this.raiseRecoverable(this.lastTokStart, "Multiple default clauses");
        }
        sawDefault = true;
        cur.test = null;
      }
      this.expect(types6.colon);
    } else {
      if (!cur) {
        this.unexpected();
      }
      cur.consequent.push(this.parseStatement(null));
    }
  }
  this.exitScope();
  if (cur) {
    this.finishNode(cur, "SwitchCase");
  }
  this.next();
  this.labels.pop();
  return this.finishNode(node, "SwitchStatement");
};
pp$12.parseThrowStatement = function(node) {
  this.next();
  if (lineBreak2.test(this.input.slice(this.lastTokEnd, this.start))) {
    this.raise(this.lastTokEnd, "Illegal newline after throw");
  }
  node.argument = this.parseExpression();
  this.semicolon();
  return this.finishNode(node, "ThrowStatement");
};
var empty2 = [];
pp$12.parseTryStatement = function(node) {
  this.next();
  node.block = this.parseBlock();
  node.handler = null;
  if (this.type === types6._catch) {
    var clause = this.startNode();
    this.next();
    if (this.eat(types6.parenL)) {
      clause.param = this.parseBindingAtom();
      var simple3 = clause.param.type === "Identifier";
      this.enterScope(simple3 ? SCOPE_SIMPLE_CATCH2 : 0);
      this.checkLValPattern(clause.param, simple3 ? BIND_SIMPLE_CATCH2 : BIND_LEXICAL2);
      this.expect(types6.parenR);
    } else {
      if (this.options.ecmaVersion < 10) {
        this.unexpected();
      }
      clause.param = null;
      this.enterScope(0);
    }
    clause.body = this.parseBlock(false);
    this.exitScope();
    node.handler = this.finishNode(clause, "CatchClause");
  }
  node.finalizer = this.eat(types6._finally) ? this.parseBlock() : null;
  if (!node.handler && !node.finalizer) {
    this.raise(node.start, "Missing catch or finally clause");
  }
  return this.finishNode(node, "TryStatement");
};
pp$12.parseVarStatement = function(node, kind) {
  this.next();
  this.parseVar(node, false, kind);
  this.semicolon();
  return this.finishNode(node, "VariableDeclaration");
};
pp$12.parseWhileStatement = function(node) {
  this.next();
  node.test = this.parseParenExpression();
  this.labels.push(loopLabel2);
  node.body = this.parseStatement("while");
  this.labels.pop();
  return this.finishNode(node, "WhileStatement");
};
pp$12.parseWithStatement = function(node) {
  if (this.strict) {
    this.raise(this.start, "'with' in strict mode");
  }
  this.next();
  node.object = this.parseParenExpression();
  node.body = this.parseStatement("with");
  return this.finishNode(node, "WithStatement");
};
pp$12.parseEmptyStatement = function(node) {
  this.next();
  return this.finishNode(node, "EmptyStatement");
};
pp$12.parseLabeledStatement = function(node, maybeName, expr, context) {
  for (var i$13 = 0, list = this.labels; i$13 < list.length; i$13 += 1) {
    var label = list[i$13];
    if (label.name === maybeName) {
      this.raise(expr.start, "Label '" + maybeName + "' is already declared");
    }
  }
  var kind = this.type.isLoop ? "loop" : this.type === types6._switch ? "switch" : null;
  for (var i6 = this.labels.length - 1; i6 >= 0; i6--) {
    var label$1 = this.labels[i6];
    if (label$1.statementStart === node.start) {
      label$1.statementStart = this.start;
      label$1.kind = kind;
    } else {
      break;
    }
  }
  this.labels.push({ name: maybeName, kind, statementStart: this.start });
  node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
  this.labels.pop();
  node.label = expr;
  return this.finishNode(node, "LabeledStatement");
};
pp$12.parseExpressionStatement = function(node, expr) {
  node.expression = expr;
  this.semicolon();
  return this.finishNode(node, "ExpressionStatement");
};
pp$12.parseBlock = function(createNewLexicalScope, node, exitStrict) {
  if (createNewLexicalScope === void 0)
    createNewLexicalScope = true;
  if (node === void 0)
    node = this.startNode();
  node.body = [];
  this.expect(types6.braceL);
  if (createNewLexicalScope) {
    this.enterScope(0);
  }
  while (this.type !== types6.braceR) {
    var stmt = this.parseStatement(null);
    node.body.push(stmt);
  }
  if (exitStrict) {
    this.strict = false;
  }
  this.next();
  if (createNewLexicalScope) {
    this.exitScope();
  }
  return this.finishNode(node, "BlockStatement");
};
pp$12.parseFor = function(node, init5) {
  node.init = init5;
  this.expect(types6.semi);
  node.test = this.type === types6.semi ? null : this.parseExpression();
  this.expect(types6.semi);
  node.update = this.type === types6.parenR ? null : this.parseExpression();
  this.expect(types6.parenR);
  node.body = this.parseStatement("for");
  this.exitScope();
  this.labels.pop();
  return this.finishNode(node, "ForStatement");
};
pp$12.parseForIn = function(node, init5) {
  var isForIn = this.type === types6._in;
  this.next();
  if (init5.type === "VariableDeclaration" && init5.declarations[0].init != null && (!isForIn || this.options.ecmaVersion < 8 || this.strict || init5.kind !== "var" || init5.declarations[0].id.type !== "Identifier")) {
    this.raise(init5.start, (isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer");
  }
  node.left = init5;
  node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
  this.expect(types6.parenR);
  node.body = this.parseStatement("for");
  this.exitScope();
  this.labels.pop();
  return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement");
};
pp$12.parseVar = function(node, isFor, kind) {
  node.declarations = [];
  node.kind = kind;
  for (; ; ) {
    var decl = this.startNode();
    this.parseVarId(decl, kind);
    if (this.eat(types6.eq)) {
      decl.init = this.parseMaybeAssign(isFor);
    } else if (kind === "const" && !(this.type === types6._in || this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
      this.unexpected();
    } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types6._in || this.isContextual("of")))) {
      this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
    } else {
      decl.init = null;
    }
    node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
    if (!this.eat(types6.comma)) {
      break;
    }
  }
  return node;
};
pp$12.parseVarId = function(decl, kind) {
  decl.id = this.parseBindingAtom();
  this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR2 : BIND_LEXICAL2, false);
};
var FUNC_STATEMENT2 = 1;
var FUNC_HANGING_STATEMENT2 = 2;
var FUNC_NULLABLE_ID2 = 4;
pp$12.parseFunction = function(node, statement, allowExpressionBody, isAsync2) {
  this.initFunction(node);
  if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync2) {
    if (this.type === types6.star && statement & FUNC_HANGING_STATEMENT2) {
      this.unexpected();
    }
    node.generator = this.eat(types6.star);
  }
  if (this.options.ecmaVersion >= 8) {
    node.async = !!isAsync2;
  }
  if (statement & FUNC_STATEMENT2) {
    node.id = statement & FUNC_NULLABLE_ID2 && this.type !== types6.name ? null : this.parseIdent();
    if (node.id && !(statement & FUNC_HANGING_STATEMENT2)) {
      this.checkLValSimple(node.id, this.strict || node.generator || node.async ? this.treatFunctionsAsVar ? BIND_VAR2 : BIND_LEXICAL2 : BIND_FUNCTION2);
    }
  }
  var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  this.yieldPos = 0;
  this.awaitPos = 0;
  this.awaitIdentPos = 0;
  this.enterScope(functionFlags2(node.async, node.generator));
  if (!(statement & FUNC_STATEMENT2)) {
    node.id = this.type === types6.name ? this.parseIdent() : null;
  }
  this.parseFunctionParams(node);
  this.parseFunctionBody(node, allowExpressionBody, false);
  this.yieldPos = oldYieldPos;
  this.awaitPos = oldAwaitPos;
  this.awaitIdentPos = oldAwaitIdentPos;
  return this.finishNode(node, statement & FUNC_STATEMENT2 ? "FunctionDeclaration" : "FunctionExpression");
};
pp$12.parseFunctionParams = function(node) {
  this.expect(types6.parenL);
  node.params = this.parseBindingList(types6.parenR, false, this.options.ecmaVersion >= 8);
  this.checkYieldAwaitInDefaultParams();
};
pp$12.parseClass = function(node, isStatement) {
  this.next();
  var oldStrict = this.strict;
  this.strict = true;
  this.parseClassId(node, isStatement);
  this.parseClassSuper(node);
  var privateNameMap = this.enterClassBody();
  var classBody = this.startNode();
  var hadConstructor = false;
  classBody.body = [];
  this.expect(types6.braceL);
  while (this.type !== types6.braceR) {
    var element = this.parseClassElement(node.superClass !== null);
    if (element) {
      classBody.body.push(element);
      if (element.type === "MethodDefinition" && element.kind === "constructor") {
        if (hadConstructor) {
          this.raise(element.start, "Duplicate constructor in the same class");
        }
        hadConstructor = true;
      } else if (element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) {
        this.raiseRecoverable(element.key.start, "Identifier '#" + element.key.name + "' has already been declared");
      }
    }
  }
  this.strict = oldStrict;
  this.next();
  node.body = this.finishNode(classBody, "ClassBody");
  this.exitClassBody();
  return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");
};
pp$12.parseClassElement = function(constructorAllowsSuper) {
  if (this.eat(types6.semi)) {
    return null;
  }
  var ecmaVersion = this.options.ecmaVersion;
  var node = this.startNode();
  var keyName = "";
  var isGenerator = false;
  var isAsync2 = false;
  var kind = "method";
  node.static = false;
  if (this.eatContextual("static")) {
    if (this.isClassElementNameStart() || this.type === types6.star) {
      node.static = true;
    } else {
      keyName = "static";
    }
  }
  if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) {
    if ((this.isClassElementNameStart() || this.type === types6.star) && !this.canInsertSemicolon()) {
      isAsync2 = true;
    } else {
      keyName = "async";
    }
  }
  if (!keyName && (ecmaVersion >= 9 || !isAsync2) && this.eat(types6.star)) {
    isGenerator = true;
  }
  if (!keyName && !isAsync2 && !isGenerator) {
    var lastValue = this.value;
    if (this.eatContextual("get") || this.eatContextual("set")) {
      if (this.isClassElementNameStart()) {
        kind = lastValue;
      } else {
        keyName = lastValue;
      }
    }
  }
  if (keyName) {
    node.computed = false;
    node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc);
    node.key.name = keyName;
    this.finishNode(node.key, "Identifier");
  } else {
    this.parseClassElementName(node);
  }
  if (ecmaVersion < 13 || this.type === types6.parenL || kind !== "method" || isGenerator || isAsync2) {
    var isConstructor = !node.static && checkKeyName(node, "constructor");
    var allowsDirectSuper = isConstructor && constructorAllowsSuper;
    if (isConstructor && kind !== "method") {
      this.raise(node.key.start, "Constructor can't have get/set modifier");
    }
    node.kind = isConstructor ? "constructor" : kind;
    this.parseClassMethod(node, isGenerator, isAsync2, allowsDirectSuper);
  } else {
    this.parseClassField(node);
  }
  return node;
};
pp$12.isClassElementNameStart = function() {
  return this.type === types6.name || this.type === types6.privateId || this.type === types6.num || this.type === types6.string || this.type === types6.bracketL || this.type.keyword;
};
pp$12.parseClassElementName = function(element) {
  if (this.type === types6.privateId) {
    if (this.value === "constructor") {
      this.raise(this.start, "Classes can't have an element named '#constructor'");
    }
    element.computed = false;
    element.key = this.parsePrivateIdent();
  } else {
    this.parsePropertyName(element);
  }
};
pp$12.parseClassMethod = function(method, isGenerator, isAsync2, allowsDirectSuper) {
  var key = method.key;
  if (method.kind === "constructor") {
    if (isGenerator) {
      this.raise(key.start, "Constructor can't be a generator");
    }
    if (isAsync2) {
      this.raise(key.start, "Constructor can't be an async method");
    }
  } else if (method.static && checkKeyName(method, "prototype")) {
    this.raise(key.start, "Classes may not have a static property named prototype");
  }
  var value = method.value = this.parseMethod(isGenerator, isAsync2, allowsDirectSuper);
  if (method.kind === "get" && value.params.length !== 0) {
    this.raiseRecoverable(value.start, "getter should have no params");
  }
  if (method.kind === "set" && value.params.length !== 1) {
    this.raiseRecoverable(value.start, "setter should have exactly one param");
  }
  if (method.kind === "set" && value.params[0].type === "RestElement") {
    this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params");
  }
  return this.finishNode(method, "MethodDefinition");
};
pp$12.parseClassField = function(field) {
  if (checkKeyName(field, "constructor")) {
    this.raise(field.key.start, "Classes can't have a field named 'constructor'");
  } else if (field.static && checkKeyName(field, "prototype")) {
    this.raise(field.key.start, "Classes can't have a static field named 'prototype'");
  }
  if (this.eat(types6.eq)) {
    var scope = this.currentThisScope();
    var inClassFieldInit = scope.inClassFieldInit;
    scope.inClassFieldInit = true;
    field.value = this.parseMaybeAssign();
    scope.inClassFieldInit = inClassFieldInit;
  } else {
    field.value = null;
  }
  this.semicolon();
  return this.finishNode(field, "PropertyDefinition");
};
pp$12.parseClassId = function(node, isStatement) {
  if (this.type === types6.name) {
    node.id = this.parseIdent();
    if (isStatement) {
      this.checkLValSimple(node.id, BIND_LEXICAL2, false);
    }
  } else {
    if (isStatement === true) {
      this.unexpected();
    }
    node.id = null;
  }
};
pp$12.parseClassSuper = function(node) {
  node.superClass = this.eat(types6._extends) ? this.parseExprSubscripts() : null;
};
pp$12.enterClassBody = function() {
  var element = { declared: /* @__PURE__ */ Object.create(null), used: [] };
  this.privateNameStack.push(element);
  return element.declared;
};
pp$12.exitClassBody = function() {
  var ref22 = this.privateNameStack.pop();
  var declared = ref22.declared;
  var used = ref22.used;
  var len = this.privateNameStack.length;
  var parent = len === 0 ? null : this.privateNameStack[len - 1];
  for (var i6 = 0; i6 < used.length; ++i6) {
    var id = used[i6];
    if (!has2(declared, id.name)) {
      if (parent) {
        parent.used.push(id);
      } else {
        this.raiseRecoverable(id.start, "Private field '#" + id.name + "' must be declared in an enclosing class");
      }
    }
  }
};
function isPrivateNameConflicted(privateNameMap, element) {
  var name2 = element.key.name;
  var curr = privateNameMap[name2];
  var next = "true";
  if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) {
    next = (element.static ? "s" : "i") + element.kind;
  }
  if (curr === "iget" && next === "iset" || curr === "iset" && next === "iget" || curr === "sget" && next === "sset" || curr === "sset" && next === "sget") {
    privateNameMap[name2] = "true";
    return false;
  } else if (!curr) {
    privateNameMap[name2] = next;
    return false;
  } else {
    return true;
  }
}
function checkKeyName(node, name2) {
  var computed = node.computed;
  var key = node.key;
  return !computed && (key.type === "Identifier" && key.name === name2 || key.type === "Literal" && key.value === name2);
}
pp$12.parseExport = function(node, exports23) {
  this.next();
  if (this.eat(types6.star)) {
    if (this.options.ecmaVersion >= 11) {
      if (this.eatContextual("as")) {
        node.exported = this.parseIdent(true);
        this.checkExport(exports23, node.exported.name, this.lastTokStart);
      } else {
        node.exported = null;
      }
    }
    this.expectContextual("from");
    if (this.type !== types6.string) {
      this.unexpected();
    }
    node.source = this.parseExprAtom();
    this.semicolon();
    return this.finishNode(node, "ExportAllDeclaration");
  }
  if (this.eat(types6._default)) {
    this.checkExport(exports23, "default", this.lastTokStart);
    var isAsync2;
    if (this.type === types6._function || (isAsync2 = this.isAsyncFunction())) {
      var fNode = this.startNode();
      this.next();
      if (isAsync2) {
        this.next();
      }
      node.declaration = this.parseFunction(fNode, FUNC_STATEMENT2 | FUNC_NULLABLE_ID2, false, isAsync2);
    } else if (this.type === types6._class) {
      var cNode = this.startNode();
      node.declaration = this.parseClass(cNode, "nullableID");
    } else {
      node.declaration = this.parseMaybeAssign();
      this.semicolon();
    }
    return this.finishNode(node, "ExportDefaultDeclaration");
  }
  if (this.shouldParseExportStatement()) {
    node.declaration = this.parseStatement(null);
    if (node.declaration.type === "VariableDeclaration") {
      this.checkVariableExport(exports23, node.declaration.declarations);
    } else {
      this.checkExport(exports23, node.declaration.id.name, node.declaration.id.start);
    }
    node.specifiers = [];
    node.source = null;
  } else {
    node.declaration = null;
    node.specifiers = this.parseExportSpecifiers(exports23);
    if (this.eatContextual("from")) {
      if (this.type !== types6.string) {
        this.unexpected();
      }
      node.source = this.parseExprAtom();
    } else {
      for (var i6 = 0, list = node.specifiers; i6 < list.length; i6 += 1) {
        var spec = list[i6];
        this.checkUnreserved(spec.local);
        this.checkLocalExport(spec.local);
      }
      node.source = null;
    }
    this.semicolon();
  }
  return this.finishNode(node, "ExportNamedDeclaration");
};
pp$12.checkExport = function(exports23, name2, pos) {
  if (!exports23) {
    return;
  }
  if (has2(exports23, name2)) {
    this.raiseRecoverable(pos, "Duplicate export '" + name2 + "'");
  }
  exports23[name2] = true;
};
pp$12.checkPatternExport = function(exports23, pat) {
  var type4 = pat.type;
  if (type4 === "Identifier") {
    this.checkExport(exports23, pat.name, pat.start);
  } else if (type4 === "ObjectPattern") {
    for (var i6 = 0, list = pat.properties; i6 < list.length; i6 += 1) {
      var prop = list[i6];
      this.checkPatternExport(exports23, prop);
    }
  } else if (type4 === "ArrayPattern") {
    for (var i$13 = 0, list$1 = pat.elements; i$13 < list$1.length; i$13 += 1) {
      var elt = list$1[i$13];
      if (elt) {
        this.checkPatternExport(exports23, elt);
      }
    }
  } else if (type4 === "Property") {
    this.checkPatternExport(exports23, pat.value);
  } else if (type4 === "AssignmentPattern") {
    this.checkPatternExport(exports23, pat.left);
  } else if (type4 === "RestElement") {
    this.checkPatternExport(exports23, pat.argument);
  } else if (type4 === "ParenthesizedExpression") {
    this.checkPatternExport(exports23, pat.expression);
  }
};
pp$12.checkVariableExport = function(exports23, decls) {
  if (!exports23) {
    return;
  }
  for (var i6 = 0, list = decls; i6 < list.length; i6 += 1) {
    var decl = list[i6];
    this.checkPatternExport(exports23, decl.id);
  }
};
pp$12.shouldParseExportStatement = function() {
  return this.type.keyword === "var" || this.type.keyword === "const" || this.type.keyword === "class" || this.type.keyword === "function" || this.isLet() || this.isAsyncFunction();
};
pp$12.parseExportSpecifiers = function(exports23) {
  var nodes = [], first = true;
  this.expect(types6.braceL);
  while (!this.eat(types6.braceR)) {
    if (!first) {
      this.expect(types6.comma);
      if (this.afterTrailingComma(types6.braceR)) {
        break;
      }
    } else {
      first = false;
    }
    var node = this.startNode();
    node.local = this.parseIdent(true);
    node.exported = this.eatContextual("as") ? this.parseIdent(true) : node.local;
    this.checkExport(exports23, node.exported.name, node.exported.start);
    nodes.push(this.finishNode(node, "ExportSpecifier"));
  }
  return nodes;
};
pp$12.parseImport = function(node) {
  this.next();
  if (this.type === types6.string) {
    node.specifiers = empty2;
    node.source = this.parseExprAtom();
  } else {
    node.specifiers = this.parseImportSpecifiers();
    this.expectContextual("from");
    node.source = this.type === types6.string ? this.parseExprAtom() : this.unexpected();
  }
  this.semicolon();
  return this.finishNode(node, "ImportDeclaration");
};
pp$12.parseImportSpecifiers = function() {
  var nodes = [], first = true;
  if (this.type === types6.name) {
    var node = this.startNode();
    node.local = this.parseIdent();
    this.checkLValSimple(node.local, BIND_LEXICAL2);
    nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));
    if (!this.eat(types6.comma)) {
      return nodes;
    }
  }
  if (this.type === types6.star) {
    var node$1 = this.startNode();
    this.next();
    this.expectContextual("as");
    node$1.local = this.parseIdent();
    this.checkLValSimple(node$1.local, BIND_LEXICAL2);
    nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier"));
    return nodes;
  }
  this.expect(types6.braceL);
  while (!this.eat(types6.braceR)) {
    if (!first) {
      this.expect(types6.comma);
      if (this.afterTrailingComma(types6.braceR)) {
        break;
      }
    } else {
      first = false;
    }
    var node$2 = this.startNode();
    node$2.imported = this.parseIdent(true);
    if (this.eatContextual("as")) {
      node$2.local = this.parseIdent();
    } else {
      this.checkUnreserved(node$2.imported);
      node$2.local = node$2.imported;
    }
    this.checkLValSimple(node$2.local, BIND_LEXICAL2);
    nodes.push(this.finishNode(node$2, "ImportSpecifier"));
  }
  return nodes;
};
pp$12.adaptDirectivePrologue = function(statements) {
  for (var i6 = 0; i6 < statements.length && this.isDirectiveCandidate(statements[i6]); ++i6) {
    statements[i6].directive = statements[i6].expression.raw.slice(1, -1);
  }
};
pp$12.isDirectiveCandidate = function(statement) {
  return statement.type === "ExpressionStatement" && statement.expression.type === "Literal" && typeof statement.expression.value === "string" && (this.input[statement.start] === '"' || this.input[statement.start] === "'");
};
var pp$22 = Parser3.prototype;
pp$22.toAssignable = function(node, isBinding, refDestructuringErrors) {
  if (this.options.ecmaVersion >= 6 && node) {
    switch (node.type) {
      case "Identifier":
        if (this.inAsync && node.name === "await") {
          this.raise(node.start, "Cannot use 'await' as identifier inside an async function");
        }
        break;
      case "ObjectPattern":
      case "ArrayPattern":
      case "AssignmentPattern":
      case "RestElement":
        break;
      case "ObjectExpression":
        node.type = "ObjectPattern";
        if (refDestructuringErrors) {
          this.checkPatternErrors(refDestructuringErrors, true);
        }
        for (var i6 = 0, list = node.properties; i6 < list.length; i6 += 1) {
          var prop = list[i6];
          this.toAssignable(prop, isBinding);
          if (prop.type === "RestElement" && (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")) {
            this.raise(prop.argument.start, "Unexpected token");
          }
        }
        break;
      case "Property":
        if (node.kind !== "init") {
          this.raise(node.key.start, "Object pattern can't contain getter or setter");
        }
        this.toAssignable(node.value, isBinding);
        break;
      case "ArrayExpression":
        node.type = "ArrayPattern";
        if (refDestructuringErrors) {
          this.checkPatternErrors(refDestructuringErrors, true);
        }
        this.toAssignableList(node.elements, isBinding);
        break;
      case "SpreadElement":
        node.type = "RestElement";
        this.toAssignable(node.argument, isBinding);
        if (node.argument.type === "AssignmentPattern") {
          this.raise(node.argument.start, "Rest elements cannot have a default value");
        }
        break;
      case "AssignmentExpression":
        if (node.operator !== "=") {
          this.raise(node.left.end, "Only '=' operator can be used for specifying default value.");
        }
        node.type = "AssignmentPattern";
        delete node.operator;
        this.toAssignable(node.left, isBinding);
        break;
      case "ParenthesizedExpression":
        this.toAssignable(node.expression, isBinding, refDestructuringErrors);
        break;
      case "ChainExpression":
        this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side");
        break;
      case "MemberExpression":
        if (!isBinding) {
          break;
        }
      default:
        this.raise(node.start, "Assigning to rvalue");
    }
  } else if (refDestructuringErrors) {
    this.checkPatternErrors(refDestructuringErrors, true);
  }
  return node;
};
pp$22.toAssignableList = function(exprList, isBinding) {
  var end = exprList.length;
  for (var i6 = 0; i6 < end; i6++) {
    var elt = exprList[i6];
    if (elt) {
      this.toAssignable(elt, isBinding);
    }
  }
  if (end) {
    var last = exprList[end - 1];
    if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier") {
      this.unexpected(last.argument.start);
    }
  }
  return exprList;
};
pp$22.parseSpread = function(refDestructuringErrors) {
  var node = this.startNode();
  this.next();
  node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  return this.finishNode(node, "SpreadElement");
};
pp$22.parseRestBinding = function() {
  var node = this.startNode();
  this.next();
  if (this.options.ecmaVersion === 6 && this.type !== types6.name) {
    this.unexpected();
  }
  node.argument = this.parseBindingAtom();
  return this.finishNode(node, "RestElement");
};
pp$22.parseBindingAtom = function() {
  if (this.options.ecmaVersion >= 6) {
    switch (this.type) {
      case types6.bracketL:
        var node = this.startNode();
        this.next();
        node.elements = this.parseBindingList(types6.bracketR, true, true);
        return this.finishNode(node, "ArrayPattern");
      case types6.braceL:
        return this.parseObj(true);
    }
  }
  return this.parseIdent();
};
pp$22.parseBindingList = function(close, allowEmpty, allowTrailingComma) {
  var elts = [], first = true;
  while (!this.eat(close)) {
    if (first) {
      first = false;
    } else {
      this.expect(types6.comma);
    }
    if (allowEmpty && this.type === types6.comma) {
      elts.push(null);
    } else if (allowTrailingComma && this.afterTrailingComma(close)) {
      break;
    } else if (this.type === types6.ellipsis) {
      var rest = this.parseRestBinding();
      this.parseBindingListItem(rest);
      elts.push(rest);
      if (this.type === types6.comma) {
        this.raise(this.start, "Comma is not permitted after the rest element");
      }
      this.expect(close);
      break;
    } else {
      var elem = this.parseMaybeDefault(this.start, this.startLoc);
      this.parseBindingListItem(elem);
      elts.push(elem);
    }
  }
  return elts;
};
pp$22.parseBindingListItem = function(param) {
  return param;
};
pp$22.parseMaybeDefault = function(startPos, startLoc, left) {
  left = left || this.parseBindingAtom();
  if (this.options.ecmaVersion < 6 || !this.eat(types6.eq)) {
    return left;
  }
  var node = this.startNodeAt(startPos, startLoc);
  node.left = left;
  node.right = this.parseMaybeAssign();
  return this.finishNode(node, "AssignmentPattern");
};
pp$22.checkLValSimple = function(expr, bindingType, checkClashes) {
  if (bindingType === void 0)
    bindingType = BIND_NONE2;
  var isBind = bindingType !== BIND_NONE2;
  switch (expr.type) {
    case "Identifier":
      if (this.strict && this.reservedWordsStrictBind.test(expr.name)) {
        this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode");
      }
      if (isBind) {
        if (bindingType === BIND_LEXICAL2 && expr.name === "let") {
          this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name");
        }
        if (checkClashes) {
          if (has2(checkClashes, expr.name)) {
            this.raiseRecoverable(expr.start, "Argument name clash");
          }
          checkClashes[expr.name] = true;
        }
        if (bindingType !== BIND_OUTSIDE2) {
          this.declareName(expr.name, bindingType, expr.start);
        }
      }
      break;
    case "ChainExpression":
      this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side");
      break;
    case "MemberExpression":
      if (isBind) {
        this.raiseRecoverable(expr.start, "Binding member expression");
      }
      break;
    case "ParenthesizedExpression":
      if (isBind) {
        this.raiseRecoverable(expr.start, "Binding parenthesized expression");
      }
      return this.checkLValSimple(expr.expression, bindingType, checkClashes);
    default:
      this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue");
  }
};
pp$22.checkLValPattern = function(expr, bindingType, checkClashes) {
  if (bindingType === void 0)
    bindingType = BIND_NONE2;
  switch (expr.type) {
    case "ObjectPattern":
      for (var i6 = 0, list = expr.properties; i6 < list.length; i6 += 1) {
        var prop = list[i6];
        this.checkLValInnerPattern(prop, bindingType, checkClashes);
      }
      break;
    case "ArrayPattern":
      for (var i$13 = 0, list$1 = expr.elements; i$13 < list$1.length; i$13 += 1) {
        var elem = list$1[i$13];
        if (elem) {
          this.checkLValInnerPattern(elem, bindingType, checkClashes);
        }
      }
      break;
    default:
      this.checkLValSimple(expr, bindingType, checkClashes);
  }
};
pp$22.checkLValInnerPattern = function(expr, bindingType, checkClashes) {
  if (bindingType === void 0)
    bindingType = BIND_NONE2;
  switch (expr.type) {
    case "Property":
      this.checkLValInnerPattern(expr.value, bindingType, checkClashes);
      break;
    case "AssignmentPattern":
      this.checkLValPattern(expr.left, bindingType, checkClashes);
      break;
    case "RestElement":
      this.checkLValPattern(expr.argument, bindingType, checkClashes);
      break;
    default:
      this.checkLValPattern(expr, bindingType, checkClashes);
  }
};
var pp$32 = Parser3.prototype;
pp$32.checkPropClash = function(prop, propHash, refDestructuringErrors) {
  if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement") {
    return;
  }
  if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) {
    return;
  }
  var key = prop.key;
  var name2;
  switch (key.type) {
    case "Identifier":
      name2 = key.name;
      break;
    case "Literal":
      name2 = String(key.value);
      break;
    default:
      return;
  }
  var kind = prop.kind;
  if (this.options.ecmaVersion >= 6) {
    if (name2 === "__proto__" && kind === "init") {
      if (propHash.proto) {
        if (refDestructuringErrors) {
          if (refDestructuringErrors.doubleProto < 0) {
            refDestructuringErrors.doubleProto = key.start;
          }
        } else {
          this.raiseRecoverable(key.start, "Redefinition of __proto__ property");
        }
      }
      propHash.proto = true;
    }
    return;
  }
  name2 = "$" + name2;
  var other = propHash[name2];
  if (other) {
    var redefinition;
    if (kind === "init") {
      redefinition = this.strict && other.init || other.get || other.set;
    } else {
      redefinition = other.init || other[kind];
    }
    if (redefinition) {
      this.raiseRecoverable(key.start, "Redefinition of property");
    }
  } else {
    other = propHash[name2] = {
      init: false,
      get: false,
      set: false
    };
  }
  other[kind] = true;
};
pp$32.parseExpression = function(forInit, refDestructuringErrors) {
  var startPos = this.start, startLoc = this.startLoc;
  var expr = this.parseMaybeAssign(forInit, refDestructuringErrors);
  if (this.type === types6.comma) {
    var node = this.startNodeAt(startPos, startLoc);
    node.expressions = [expr];
    while (this.eat(types6.comma)) {
      node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors));
    }
    return this.finishNode(node, "SequenceExpression");
  }
  return expr;
};
pp$32.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) {
  if (this.isContextual("yield")) {
    if (this.inGenerator) {
      return this.parseYield(forInit);
    } else {
      this.exprAllowed = false;
    }
  }
  var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1;
  if (refDestructuringErrors) {
    oldParenAssign = refDestructuringErrors.parenthesizedAssign;
    oldTrailingComma = refDestructuringErrors.trailingComma;
    refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
  } else {
    refDestructuringErrors = new DestructuringErrors2();
    ownDestructuringErrors = true;
  }
  var startPos = this.start, startLoc = this.startLoc;
  if (this.type === types6.parenL || this.type === types6.name) {
    this.potentialArrowAt = this.start;
    this.potentialArrowInForAwait = forInit === "await";
  }
  var left = this.parseMaybeConditional(forInit, refDestructuringErrors);
  if (afterLeftParse) {
    left = afterLeftParse.call(this, left, startPos, startLoc);
  }
  if (this.type.isAssign) {
    var node = this.startNodeAt(startPos, startLoc);
    node.operator = this.value;
    if (this.type === types6.eq) {
      left = this.toAssignable(left, false, refDestructuringErrors);
    }
    if (!ownDestructuringErrors) {
      refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;
    }
    if (refDestructuringErrors.shorthandAssign >= left.start) {
      refDestructuringErrors.shorthandAssign = -1;
    }
    if (this.type === types6.eq) {
      this.checkLValPattern(left);
    } else {
      this.checkLValSimple(left);
    }
    node.left = left;
    this.next();
    node.right = this.parseMaybeAssign(forInit);
    return this.finishNode(node, "AssignmentExpression");
  } else {
    if (ownDestructuringErrors) {
      this.checkExpressionErrors(refDestructuringErrors, true);
    }
  }
  if (oldParenAssign > -1) {
    refDestructuringErrors.parenthesizedAssign = oldParenAssign;
  }
  if (oldTrailingComma > -1) {
    refDestructuringErrors.trailingComma = oldTrailingComma;
  }
  return left;
};
pp$32.parseMaybeConditional = function(forInit, refDestructuringErrors) {
  var startPos = this.start, startLoc = this.startLoc;
  var expr = this.parseExprOps(forInit, refDestructuringErrors);
  if (this.checkExpressionErrors(refDestructuringErrors)) {
    return expr;
  }
  if (this.eat(types6.question)) {
    var node = this.startNodeAt(startPos, startLoc);
    node.test = expr;
    node.consequent = this.parseMaybeAssign();
    this.expect(types6.colon);
    node.alternate = this.parseMaybeAssign(forInit);
    return this.finishNode(node, "ConditionalExpression");
  }
  return expr;
};
pp$32.parseExprOps = function(forInit, refDestructuringErrors) {
  var startPos = this.start, startLoc = this.startLoc;
  var expr = this.parseMaybeUnary(refDestructuringErrors, false);
  if (this.checkExpressionErrors(refDestructuringErrors)) {
    return expr;
  }
  return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit);
};
pp$32.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) {
  var prec = this.type.binop;
  if (prec != null && (!forInit || this.type !== types6._in)) {
    if (prec > minPrec) {
      var logical = this.type === types6.logicalOR || this.type === types6.logicalAND;
      var coalesce = this.type === types6.coalesce;
      if (coalesce) {
        prec = types6.logicalAND.binop;
      }
      var op = this.value;
      this.next();
      var startPos = this.start, startLoc = this.startLoc;
      var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, forInit);
      var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);
      if (logical && this.type === types6.coalesce || coalesce && (this.type === types6.logicalOR || this.type === types6.logicalAND)) {
        this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");
      }
      return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit);
    }
  }
  return left;
};
pp$32.buildBinary = function(startPos, startLoc, left, right, op, logical) {
  var node = this.startNodeAt(startPos, startLoc);
  node.left = left;
  node.operator = op;
  node.right = right;
  return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression");
};
pp$32.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec) {
  var startPos = this.start, startLoc = this.startLoc, expr;
  if (this.isContextual("await") && (this.inAsync || !this.inFunction && this.options.allowAwaitOutsideFunction)) {
    expr = this.parseAwait();
    sawUnary = true;
  } else if (this.type.prefix) {
    var node = this.startNode(), update = this.type === types6.incDec;
    node.operator = this.value;
    node.prefix = true;
    this.next();
    node.argument = this.parseMaybeUnary(null, true, update);
    this.checkExpressionErrors(refDestructuringErrors, true);
    if (update) {
      this.checkLValSimple(node.argument);
    } else if (this.strict && node.operator === "delete" && node.argument.type === "Identifier") {
      this.raiseRecoverable(node.start, "Deleting local variable in strict mode");
    } else if (node.operator === "delete" && isPrivateFieldAccess(node.argument)) {
      this.raiseRecoverable(node.start, "Private fields can not be deleted");
    } else {
      sawUnary = true;
    }
    expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
  } else {
    expr = this.parseExprSubscripts(refDestructuringErrors);
    if (this.checkExpressionErrors(refDestructuringErrors)) {
      return expr;
    }
    while (this.type.postfix && !this.canInsertSemicolon()) {
      var node$1 = this.startNodeAt(startPos, startLoc);
      node$1.operator = this.value;
      node$1.prefix = false;
      node$1.argument = expr;
      this.checkLValSimple(expr);
      this.next();
      expr = this.finishNode(node$1, "UpdateExpression");
    }
  }
  if (!incDec && this.eat(types6.starstar)) {
    if (sawUnary) {
      this.unexpected(this.lastTokStart);
    } else {
      return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false);
    }
  } else {
    return expr;
  }
};
function isPrivateFieldAccess(node) {
  return node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" || node.type === "ChainExpression" && isPrivateFieldAccess(node.expression);
}
pp$32.parseExprSubscripts = function(refDestructuringErrors) {
  var startPos = this.start, startLoc = this.startLoc;
  var expr = this.parseExprAtom(refDestructuringErrors);
  if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")") {
    return expr;
  }
  var result2 = this.parseSubscripts(expr, startPos, startLoc);
  if (refDestructuringErrors && result2.type === "MemberExpression") {
    if (refDestructuringErrors.parenthesizedAssign >= result2.start) {
      refDestructuringErrors.parenthesizedAssign = -1;
    }
    if (refDestructuringErrors.parenthesizedBind >= result2.start) {
      refDestructuringErrors.parenthesizedBind = -1;
    }
    if (refDestructuringErrors.trailingComma >= result2.start) {
      refDestructuringErrors.trailingComma = -1;
    }
  }
  return result2;
};
pp$32.parseSubscripts = function(base3, startPos, startLoc, noCalls) {
  var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base3.type === "Identifier" && base3.name === "async" && this.lastTokEnd === base3.end && !this.canInsertSemicolon() && base3.end - base3.start === 5 && this.potentialArrowAt === base3.start;
  var optionalChained = false;
  while (true) {
    var element = this.parseSubscript(base3, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained);
    if (element.optional) {
      optionalChained = true;
    }
    if (element === base3 || element.type === "ArrowFunctionExpression") {
      if (optionalChained) {
        var chainNode = this.startNodeAt(startPos, startLoc);
        chainNode.expression = element;
        element = this.finishNode(chainNode, "ChainExpression");
      }
      return element;
    }
    base3 = element;
  }
};
pp$32.parseSubscript = function(base3, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained) {
  var optionalSupported = this.options.ecmaVersion >= 11;
  var optional = optionalSupported && this.eat(types6.questionDot);
  if (noCalls && optional) {
    this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions");
  }
  var computed = this.eat(types6.bracketL);
  if (computed || optional && this.type !== types6.parenL && this.type !== types6.backQuote || this.eat(types6.dot)) {
    var node = this.startNodeAt(startPos, startLoc);
    node.object = base3;
    if (computed) {
      node.property = this.parseExpression();
      this.expect(types6.bracketR);
    } else if (this.type === types6.privateId && base3.type !== "Super") {
      node.property = this.parsePrivateIdent();
    } else {
      node.property = this.parseIdent(this.options.allowReserved !== "never");
    }
    node.computed = !!computed;
    if (optionalSupported) {
      node.optional = optional;
    }
    base3 = this.finishNode(node, "MemberExpression");
  } else if (!noCalls && this.eat(types6.parenL)) {
    var refDestructuringErrors = new DestructuringErrors2(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
    this.yieldPos = 0;
    this.awaitPos = 0;
    this.awaitIdentPos = 0;
    var exprList = this.parseExprList(types6.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
    if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types6.arrow)) {
      this.checkPatternErrors(refDestructuringErrors, false);
      this.checkYieldAwaitInDefaultParams();
      if (this.awaitIdentPos > 0) {
        this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function");
      }
      this.yieldPos = oldYieldPos;
      this.awaitPos = oldAwaitPos;
      this.awaitIdentPos = oldAwaitIdentPos;
      return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true);
    }
    this.checkExpressionErrors(refDestructuringErrors, true);
    this.yieldPos = oldYieldPos || this.yieldPos;
    this.awaitPos = oldAwaitPos || this.awaitPos;
    this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
    var node$1 = this.startNodeAt(startPos, startLoc);
    node$1.callee = base3;
    node$1.arguments = exprList;
    if (optionalSupported) {
      node$1.optional = optional;
    }
    base3 = this.finishNode(node$1, "CallExpression");
  } else if (this.type === types6.backQuote) {
    if (optional || optionalChained) {
      this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions");
    }
    var node$2 = this.startNodeAt(startPos, startLoc);
    node$2.tag = base3;
    node$2.quasi = this.parseTemplate({ isTagged: true });
    base3 = this.finishNode(node$2, "TaggedTemplateExpression");
  }
  return base3;
};
pp$32.parseExprAtom = function(refDestructuringErrors) {
  if (this.type === types6.slash) {
    this.readRegexp();
  }
  var node, canBeArrow = this.potentialArrowAt === this.start;
  switch (this.type) {
    case types6._super:
      if (!this.allowSuper) {
        this.raise(this.start, "'super' keyword outside a method");
      }
      node = this.startNode();
      this.next();
      if (this.type === types6.parenL && !this.allowDirectSuper) {
        this.raise(node.start, "super() call outside constructor of a subclass");
      }
      if (this.type !== types6.dot && this.type !== types6.bracketL && this.type !== types6.parenL) {
        this.unexpected();
      }
      return this.finishNode(node, "Super");
    case types6._this:
      node = this.startNode();
      this.next();
      return this.finishNode(node, "ThisExpression");
    case types6.name:
      var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;
      var id = this.parseIdent(false);
      if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types6._function)) {
        return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true);
      }
      if (canBeArrow && !this.canInsertSemicolon()) {
        if (this.eat(types6.arrow)) {
          return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false);
        }
        if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types6.name && !containsEsc && (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) {
          id = this.parseIdent(false);
          if (this.canInsertSemicolon() || !this.eat(types6.arrow)) {
            this.unexpected();
          }
          return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true);
        }
      }
      return id;
    case types6.regexp:
      var value = this.value;
      node = this.parseLiteral(value.value);
      node.regex = { pattern: value.pattern, flags: value.flags };
      return node;
    case types6.num:
    case types6.string:
      return this.parseLiteral(this.value);
    case types6._null:
    case types6._true:
    case types6._false:
      node = this.startNode();
      node.value = this.type === types6._null ? null : this.type === types6._true;
      node.raw = this.type.keyword;
      this.next();
      return this.finishNode(node, "Literal");
    case types6.parenL:
      var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow);
      if (refDestructuringErrors) {
        if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr)) {
          refDestructuringErrors.parenthesizedAssign = start;
        }
        if (refDestructuringErrors.parenthesizedBind < 0) {
          refDestructuringErrors.parenthesizedBind = start;
        }
      }
      return expr;
    case types6.bracketL:
      node = this.startNode();
      this.next();
      node.elements = this.parseExprList(types6.bracketR, true, true, refDestructuringErrors);
      return this.finishNode(node, "ArrayExpression");
    case types6.braceL:
      return this.parseObj(false, refDestructuringErrors);
    case types6._function:
      node = this.startNode();
      this.next();
      return this.parseFunction(node, 0);
    case types6._class:
      return this.parseClass(this.startNode(), false);
    case types6._new:
      return this.parseNew();
    case types6.backQuote:
      return this.parseTemplate();
    case types6._import:
      if (this.options.ecmaVersion >= 11) {
        return this.parseExprImport();
      } else {
        return this.unexpected();
      }
    default:
      this.unexpected();
  }
};
pp$32.parseExprImport = function() {
  var node = this.startNode();
  if (this.containsEsc) {
    this.raiseRecoverable(this.start, "Escape sequence in keyword import");
  }
  var meta = this.parseIdent(true);
  switch (this.type) {
    case types6.parenL:
      return this.parseDynamicImport(node);
    case types6.dot:
      node.meta = meta;
      return this.parseImportMeta(node);
    default:
      this.unexpected();
  }
};
pp$32.parseDynamicImport = function(node) {
  this.next();
  node.source = this.parseMaybeAssign();
  if (!this.eat(types6.parenR)) {
    var errorPos = this.start;
    if (this.eat(types6.comma) && this.eat(types6.parenR)) {
      this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
    } else {
      this.unexpected(errorPos);
    }
  }
  return this.finishNode(node, "ImportExpression");
};
pp$32.parseImportMeta = function(node) {
  this.next();
  var containsEsc = this.containsEsc;
  node.property = this.parseIdent(true);
  if (node.property.name !== "meta") {
    this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'");
  }
  if (containsEsc) {
    this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters");
  }
  if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere) {
    this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module");
  }
  return this.finishNode(node, "MetaProperty");
};
pp$32.parseLiteral = function(value) {
  var node = this.startNode();
  node.value = value;
  node.raw = this.input.slice(this.start, this.end);
  if (node.raw.charCodeAt(node.raw.length - 1) === 110) {
    node.bigint = node.raw.slice(0, -1).replace(/_/g, "");
  }
  this.next();
  return this.finishNode(node, "Literal");
};
pp$32.parseParenExpression = function() {
  this.expect(types6.parenL);
  var val = this.parseExpression();
  this.expect(types6.parenR);
  return val;
};
pp$32.parseParenAndDistinguishExpression = function(canBeArrow) {
  var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
  if (this.options.ecmaVersion >= 6) {
    this.next();
    var innerStartPos = this.start, innerStartLoc = this.startLoc;
    var exprList = [], first = true, lastIsComma = false;
    var refDestructuringErrors = new DestructuringErrors2(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;
    this.yieldPos = 0;
    this.awaitPos = 0;
    while (this.type !== types6.parenR) {
      first ? first = false : this.expect(types6.comma);
      if (allowTrailingComma && this.afterTrailingComma(types6.parenR, true)) {
        lastIsComma = true;
        break;
      } else if (this.type === types6.ellipsis) {
        spreadStart = this.start;
        exprList.push(this.parseParenItem(this.parseRestBinding()));
        if (this.type === types6.comma) {
          this.raise(this.start, "Comma is not permitted after the rest element");
        }
        break;
      } else {
        exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
      }
    }
    var innerEndPos = this.start, innerEndLoc = this.startLoc;
    this.expect(types6.parenR);
    if (canBeArrow && !this.canInsertSemicolon() && this.eat(types6.arrow)) {
      this.checkPatternErrors(refDestructuringErrors, false);
      this.checkYieldAwaitInDefaultParams();
      this.yieldPos = oldYieldPos;
      this.awaitPos = oldAwaitPos;
      return this.parseParenArrowList(startPos, startLoc, exprList);
    }
    if (!exprList.length || lastIsComma) {
      this.unexpected(this.lastTokStart);
    }
    if (spreadStart) {
      this.unexpected(spreadStart);
    }
    this.checkExpressionErrors(refDestructuringErrors, true);
    this.yieldPos = oldYieldPos || this.yieldPos;
    this.awaitPos = oldAwaitPos || this.awaitPos;
    if (exprList.length > 1) {
      val = this.startNodeAt(innerStartPos, innerStartLoc);
      val.expressions = exprList;
      this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
    } else {
      val = exprList[0];
    }
  } else {
    val = this.parseParenExpression();
  }
  if (this.options.preserveParens) {
    var par = this.startNodeAt(startPos, startLoc);
    par.expression = val;
    return this.finishNode(par, "ParenthesizedExpression");
  } else {
    return val;
  }
};
pp$32.parseParenItem = function(item) {
  return item;
};
pp$32.parseParenArrowList = function(startPos, startLoc, exprList) {
  return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList);
};
var empty$12 = [];
pp$32.parseNew = function() {
  if (this.containsEsc) {
    this.raiseRecoverable(this.start, "Escape sequence in keyword new");
  }
  var node = this.startNode();
  var meta = this.parseIdent(true);
  if (this.options.ecmaVersion >= 6 && this.eat(types6.dot)) {
    node.meta = meta;
    var containsEsc = this.containsEsc;
    node.property = this.parseIdent(true);
    if (node.property.name !== "target") {
      this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'");
    }
    if (containsEsc) {
      this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters");
    }
    if (!this.inNonArrowFunction) {
      this.raiseRecoverable(node.start, "'new.target' can only be used in functions");
    }
    return this.finishNode(node, "MetaProperty");
  }
  var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types6._import;
  node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
  if (isImport && node.callee.type === "ImportExpression") {
    this.raise(startPos, "Cannot use new with import()");
  }
  if (this.eat(types6.parenL)) {
    node.arguments = this.parseExprList(types6.parenR, this.options.ecmaVersion >= 8, false);
  } else {
    node.arguments = empty$12;
  }
  return this.finishNode(node, "NewExpression");
};
pp$32.parseTemplateElement = function(ref22) {
  var isTagged = ref22.isTagged;
  var elem = this.startNode();
  if (this.type === types6.invalidTemplate) {
    if (!isTagged) {
      this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
    }
    elem.value = {
      raw: this.value,
      cooked: null
    };
  } else {
    elem.value = {
      raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
      cooked: this.value
    };
  }
  this.next();
  elem.tail = this.type === types6.backQuote;
  return this.finishNode(elem, "TemplateElement");
};
pp$32.parseTemplate = function(ref22) {
  if (ref22 === void 0)
    ref22 = {};
  var isTagged = ref22.isTagged;
  if (isTagged === void 0)
    isTagged = false;
  var node = this.startNode();
  this.next();
  node.expressions = [];
  var curElt = this.parseTemplateElement({ isTagged });
  node.quasis = [curElt];
  while (!curElt.tail) {
    if (this.type === types6.eof) {
      this.raise(this.pos, "Unterminated template literal");
    }
    this.expect(types6.dollarBraceL);
    node.expressions.push(this.parseExpression());
    this.expect(types6.braceR);
    node.quasis.push(curElt = this.parseTemplateElement({ isTagged }));
  }
  this.next();
  return this.finishNode(node, "TemplateLiteral");
};
pp$32.isAsyncProp = function(prop) {
  return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" && (this.type === types6.name || this.type === types6.num || this.type === types6.string || this.type === types6.bracketL || this.type.keyword || this.options.ecmaVersion >= 9 && this.type === types6.star) && !lineBreak2.test(this.input.slice(this.lastTokEnd, this.start));
};
pp$32.parseObj = function(isPattern, refDestructuringErrors) {
  var node = this.startNode(), first = true, propHash = {};
  node.properties = [];
  this.next();
  while (!this.eat(types6.braceR)) {
    if (!first) {
      this.expect(types6.comma);
      if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types6.braceR)) {
        break;
      }
    } else {
      first = false;
    }
    var prop = this.parseProperty(isPattern, refDestructuringErrors);
    if (!isPattern) {
      this.checkPropClash(prop, propHash, refDestructuringErrors);
    }
    node.properties.push(prop);
  }
  return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression");
};
pp$32.parseProperty = function(isPattern, refDestructuringErrors) {
  var prop = this.startNode(), isGenerator, isAsync2, startPos, startLoc;
  if (this.options.ecmaVersion >= 9 && this.eat(types6.ellipsis)) {
    if (isPattern) {
      prop.argument = this.parseIdent(false);
      if (this.type === types6.comma) {
        this.raise(this.start, "Comma is not permitted after the rest element");
      }
      return this.finishNode(prop, "RestElement");
    }
    if (this.type === types6.parenL && refDestructuringErrors) {
      if (refDestructuringErrors.parenthesizedAssign < 0) {
        refDestructuringErrors.parenthesizedAssign = this.start;
      }
      if (refDestructuringErrors.parenthesizedBind < 0) {
        refDestructuringErrors.parenthesizedBind = this.start;
      }
    }
    prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
    if (this.type === types6.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
      refDestructuringErrors.trailingComma = this.start;
    }
    return this.finishNode(prop, "SpreadElement");
  }
  if (this.options.ecmaVersion >= 6) {
    prop.method = false;
    prop.shorthand = false;
    if (isPattern || refDestructuringErrors) {
      startPos = this.start;
      startLoc = this.startLoc;
    }
    if (!isPattern) {
      isGenerator = this.eat(types6.star);
    }
  }
  var containsEsc = this.containsEsc;
  this.parsePropertyName(prop);
  if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
    isAsync2 = true;
    isGenerator = this.options.ecmaVersion >= 9 && this.eat(types6.star);
    this.parsePropertyName(prop, refDestructuringErrors);
  } else {
    isAsync2 = false;
  }
  this.parsePropertyValue(prop, isPattern, isGenerator, isAsync2, startPos, startLoc, refDestructuringErrors, containsEsc);
  return this.finishNode(prop, "Property");
};
pp$32.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync2, startPos, startLoc, refDestructuringErrors, containsEsc) {
  if ((isGenerator || isAsync2) && this.type === types6.colon) {
    this.unexpected();
  }
  if (this.eat(types6.colon)) {
    prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
    prop.kind = "init";
  } else if (this.options.ecmaVersion >= 6 && this.type === types6.parenL) {
    if (isPattern) {
      this.unexpected();
    }
    prop.kind = "init";
    prop.method = true;
    prop.value = this.parseMethod(isGenerator, isAsync2);
  } else if (!isPattern && !containsEsc && this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && (prop.key.name === "get" || prop.key.name === "set") && (this.type !== types6.comma && this.type !== types6.braceR && this.type !== types6.eq)) {
    if (isGenerator || isAsync2) {
      this.unexpected();
    }
    prop.kind = prop.key.name;
    this.parsePropertyName(prop);
    prop.value = this.parseMethod(false);
    var paramCount = prop.kind === "get" ? 0 : 1;
    if (prop.value.params.length !== paramCount) {
      var start = prop.value.start;
      if (prop.kind === "get") {
        this.raiseRecoverable(start, "getter should have no params");
      } else {
        this.raiseRecoverable(start, "setter should have exactly one param");
      }
    } else {
      if (prop.kind === "set" && prop.value.params[0].type === "RestElement") {
        this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params");
      }
    }
  } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
    if (isGenerator || isAsync2) {
      this.unexpected();
    }
    this.checkUnreserved(prop.key);
    if (prop.key.name === "await" && !this.awaitIdentPos) {
      this.awaitIdentPos = startPos;
    }
    prop.kind = "init";
    if (isPattern) {
      prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
    } else if (this.type === types6.eq && refDestructuringErrors) {
      if (refDestructuringErrors.shorthandAssign < 0) {
        refDestructuringErrors.shorthandAssign = this.start;
      }
      prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
    } else {
      prop.value = this.copyNode(prop.key);
    }
    prop.shorthand = true;
  } else {
    this.unexpected();
  }
};
pp$32.parsePropertyName = function(prop) {
  if (this.options.ecmaVersion >= 6) {
    if (this.eat(types6.bracketL)) {
      prop.computed = true;
      prop.key = this.parseMaybeAssign();
      this.expect(types6.bracketR);
      return prop.key;
    } else {
      prop.computed = false;
    }
  }
  return prop.key = this.type === types6.num || this.type === types6.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never");
};
pp$32.initFunction = function(node) {
  node.id = null;
  if (this.options.ecmaVersion >= 6) {
    node.generator = node.expression = false;
  }
  if (this.options.ecmaVersion >= 8) {
    node.async = false;
  }
};
pp$32.parseMethod = function(isGenerator, isAsync2, allowDirectSuper) {
  var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  this.initFunction(node);
  if (this.options.ecmaVersion >= 6) {
    node.generator = isGenerator;
  }
  if (this.options.ecmaVersion >= 8) {
    node.async = !!isAsync2;
  }
  this.yieldPos = 0;
  this.awaitPos = 0;
  this.awaitIdentPos = 0;
  this.enterScope(functionFlags2(isAsync2, node.generator) | SCOPE_SUPER2 | (allowDirectSuper ? SCOPE_DIRECT_SUPER2 : 0));
  this.expect(types6.parenL);
  node.params = this.parseBindingList(types6.parenR, false, this.options.ecmaVersion >= 8);
  this.checkYieldAwaitInDefaultParams();
  this.parseFunctionBody(node, false, true);
  this.yieldPos = oldYieldPos;
  this.awaitPos = oldAwaitPos;
  this.awaitIdentPos = oldAwaitIdentPos;
  return this.finishNode(node, "FunctionExpression");
};
pp$32.parseArrowExpression = function(node, params, isAsync2) {
  var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  this.enterScope(functionFlags2(isAsync2, false) | SCOPE_ARROW2);
  this.initFunction(node);
  if (this.options.ecmaVersion >= 8) {
    node.async = !!isAsync2;
  }
  this.yieldPos = 0;
  this.awaitPos = 0;
  this.awaitIdentPos = 0;
  node.params = this.toAssignableList(params, true);
  this.parseFunctionBody(node, true, false);
  this.yieldPos = oldYieldPos;
  this.awaitPos = oldAwaitPos;
  this.awaitIdentPos = oldAwaitIdentPos;
  return this.finishNode(node, "ArrowFunctionExpression");
};
pp$32.parseFunctionBody = function(node, isArrowFunction, isMethod) {
  var isExpression = isArrowFunction && this.type !== types6.braceL;
  var oldStrict = this.strict, useStrict = false;
  if (isExpression) {
    node.body = this.parseMaybeAssign();
    node.expression = true;
    this.checkParams(node, false);
  } else {
    var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
    if (!oldStrict || nonSimple) {
      useStrict = this.strictDirective(this.end);
      if (useStrict && nonSimple) {
        this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list");
      }
    }
    var oldLabels = this.labels;
    this.labels = [];
    if (useStrict) {
      this.strict = true;
    }
    this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));
    if (this.strict && node.id) {
      this.checkLValSimple(node.id, BIND_OUTSIDE2);
    }
    node.body = this.parseBlock(false, void 0, useStrict && !oldStrict);
    node.expression = false;
    this.adaptDirectivePrologue(node.body.body);
    this.labels = oldLabels;
  }
  this.exitScope();
};
pp$32.isSimpleParamList = function(params) {
  for (var i6 = 0, list = params; i6 < list.length; i6 += 1) {
    var param = list[i6];
    if (param.type !== "Identifier") {
      return false;
    }
  }
  return true;
};
pp$32.checkParams = function(node, allowDuplicates) {
  var nameHash = /* @__PURE__ */ Object.create(null);
  for (var i6 = 0, list = node.params; i6 < list.length; i6 += 1) {
    var param = list[i6];
    this.checkLValInnerPattern(param, BIND_VAR2, allowDuplicates ? null : nameHash);
  }
};
pp$32.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
  var elts = [], first = true;
  while (!this.eat(close)) {
    if (!first) {
      this.expect(types6.comma);
      if (allowTrailingComma && this.afterTrailingComma(close)) {
        break;
      }
    } else {
      first = false;
    }
    var elt = void 0;
    if (allowEmpty && this.type === types6.comma) {
      elt = null;
    } else if (this.type === types6.ellipsis) {
      elt = this.parseSpread(refDestructuringErrors);
      if (refDestructuringErrors && this.type === types6.comma && refDestructuringErrors.trailingComma < 0) {
        refDestructuringErrors.trailingComma = this.start;
      }
    } else {
      elt = this.parseMaybeAssign(false, refDestructuringErrors);
    }
    elts.push(elt);
  }
  return elts;
};
pp$32.checkUnreserved = function(ref22) {
  var start = ref22.start;
  var end = ref22.end;
  var name2 = ref22.name;
  if (this.inGenerator && name2 === "yield") {
    this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator");
  }
  if (this.inAsync && name2 === "await") {
    this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function");
  }
  if (this.currentThisScope().inClassFieldInit && name2 === "arguments") {
    this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer");
  }
  if (this.keywords.test(name2)) {
    this.raise(start, "Unexpected keyword '" + name2 + "'");
  }
  if (this.options.ecmaVersion < 6 && this.input.slice(start, end).indexOf("\\") !== -1) {
    return;
  }
  var re3 = this.strict ? this.reservedWordsStrict : this.reservedWords;
  if (re3.test(name2)) {
    if (!this.inAsync && name2 === "await") {
      this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function");
    }
    this.raiseRecoverable(start, "The keyword '" + name2 + "' is reserved");
  }
};
pp$32.parseIdent = function(liberal, isBinding) {
  var node = this.startNode();
  if (this.type === types6.name) {
    node.name = this.value;
  } else if (this.type.keyword) {
    node.name = this.type.keyword;
    if ((node.name === "class" || node.name === "function") && (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
      this.context.pop();
    }
  } else {
    this.unexpected();
  }
  this.next(!!liberal);
  this.finishNode(node, "Identifier");
  if (!liberal) {
    this.checkUnreserved(node);
    if (node.name === "await" && !this.awaitIdentPos) {
      this.awaitIdentPos = node.start;
    }
  }
  return node;
};
pp$32.parsePrivateIdent = function() {
  var node = this.startNode();
  if (this.type === types6.privateId) {
    node.name = this.value;
  } else {
    this.unexpected();
  }
  this.next();
  this.finishNode(node, "PrivateIdentifier");
  if (this.privateNameStack.length === 0) {
    this.raise(node.start, "Private field '#" + node.name + "' must be declared in an enclosing class");
  } else {
    this.privateNameStack[this.privateNameStack.length - 1].used.push(node);
  }
  return node;
};
pp$32.parseYield = function(forInit) {
  if (!this.yieldPos) {
    this.yieldPos = this.start;
  }
  var node = this.startNode();
  this.next();
  if (this.type === types6.semi || this.canInsertSemicolon() || this.type !== types6.star && !this.type.startsExpr) {
    node.delegate = false;
    node.argument = null;
  } else {
    node.delegate = this.eat(types6.star);
    node.argument = this.parseMaybeAssign(forInit);
  }
  return this.finishNode(node, "YieldExpression");
};
pp$32.parseAwait = function() {
  if (!this.awaitPos) {
    this.awaitPos = this.start;
  }
  var node = this.startNode();
  this.next();
  node.argument = this.parseMaybeUnary(null, true);
  return this.finishNode(node, "AwaitExpression");
};
var pp$42 = Parser3.prototype;
pp$42.raise = function(pos, message) {
  var loc = getLineInfo2(this.input, pos);
  message += " (" + loc.line + ":" + loc.column + ")";
  var err2 = new SyntaxError(message);
  err2.pos = pos;
  err2.loc = loc;
  err2.raisedAt = this.pos;
  throw err2;
};
pp$42.raiseRecoverable = pp$42.raise;
pp$42.curPosition = function() {
  if (this.options.locations) {
    return new Position3(this.curLine, this.pos - this.lineStart);
  }
};
var pp$52 = Parser3.prototype;
var Scope3 = function Scope22(flags) {
  this.flags = flags;
  this.var = [];
  this.lexical = [];
  this.functions = [];
  this.inClassFieldInit = false;
};
pp$52.enterScope = function(flags) {
  this.scopeStack.push(new Scope3(flags));
};
pp$52.exitScope = function() {
  this.scopeStack.pop();
};
pp$52.treatFunctionsAsVarInScope = function(scope) {
  return scope.flags & SCOPE_FUNCTION3 || !this.inModule && scope.flags & SCOPE_TOP2;
};
pp$52.declareName = function(name2, bindingType, pos) {
  var redeclared = false;
  if (bindingType === BIND_LEXICAL2) {
    var scope = this.currentScope();
    redeclared = scope.lexical.indexOf(name2) > -1 || scope.functions.indexOf(name2) > -1 || scope.var.indexOf(name2) > -1;
    scope.lexical.push(name2);
    if (this.inModule && scope.flags & SCOPE_TOP2) {
      delete this.undefinedExports[name2];
    }
  } else if (bindingType === BIND_SIMPLE_CATCH2) {
    var scope$1 = this.currentScope();
    scope$1.lexical.push(name2);
  } else if (bindingType === BIND_FUNCTION2) {
    var scope$2 = this.currentScope();
    if (this.treatFunctionsAsVar) {
      redeclared = scope$2.lexical.indexOf(name2) > -1;
    } else {
      redeclared = scope$2.lexical.indexOf(name2) > -1 || scope$2.var.indexOf(name2) > -1;
    }
    scope$2.functions.push(name2);
  } else {
    for (var i6 = this.scopeStack.length - 1; i6 >= 0; --i6) {
      var scope$3 = this.scopeStack[i6];
      if (scope$3.lexical.indexOf(name2) > -1 && !(scope$3.flags & SCOPE_SIMPLE_CATCH2 && scope$3.lexical[0] === name2) || !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name2) > -1) {
        redeclared = true;
        break;
      }
      scope$3.var.push(name2);
      if (this.inModule && scope$3.flags & SCOPE_TOP2) {
        delete this.undefinedExports[name2];
      }
      if (scope$3.flags & SCOPE_VAR2) {
        break;
      }
    }
  }
  if (redeclared) {
    this.raiseRecoverable(pos, "Identifier '" + name2 + "' has already been declared");
  }
};
pp$52.checkLocalExport = function(id) {
  if (this.scopeStack[0].lexical.indexOf(id.name) === -1 && this.scopeStack[0].var.indexOf(id.name) === -1) {
    this.undefinedExports[id.name] = id;
  }
};
pp$52.currentScope = function() {
  return this.scopeStack[this.scopeStack.length - 1];
};
pp$52.currentVarScope = function() {
  for (var i6 = this.scopeStack.length - 1; ; i6--) {
    var scope = this.scopeStack[i6];
    if (scope.flags & SCOPE_VAR2) {
      return scope;
    }
  }
};
pp$52.currentThisScope = function() {
  for (var i6 = this.scopeStack.length - 1; ; i6--) {
    var scope = this.scopeStack[i6];
    if (scope.flags & SCOPE_VAR2 && !(scope.flags & SCOPE_ARROW2)) {
      return scope;
    }
  }
};
var Node5 = function Node23(parser, pos, loc) {
  this.type = "";
  this.start = pos;
  this.end = 0;
  if (parser.options.locations) {
    this.loc = new SourceLocation3(parser, loc);
  }
  if (parser.options.directSourceFile) {
    this.sourceFile = parser.options.directSourceFile;
  }
  if (parser.options.ranges) {
    this.range = [pos, 0];
  }
};
var pp$62 = Parser3.prototype;
pp$62.startNode = function() {
  return new Node5(this, this.start, this.startLoc);
};
pp$62.startNodeAt = function(pos, loc) {
  return new Node5(this, pos, loc);
};
function finishNodeAt2(node, type4, pos, loc) {
  node.type = type4;
  node.end = pos;
  if (this.options.locations) {
    node.loc.end = loc;
  }
  if (this.options.ranges) {
    node.range[1] = pos;
  }
  return node;
}
pp$62.finishNode = function(node, type4) {
  return finishNodeAt2.call(this, node, type4, this.lastTokEnd, this.lastTokEndLoc);
};
pp$62.finishNodeAt = function(node, type4, pos, loc) {
  return finishNodeAt2.call(this, node, type4, pos, loc);
};
pp$62.copyNode = function(node) {
  var newNode = new Node5(this, node.start, this.startLoc);
  for (var prop in node) {
    newNode[prop] = node[prop];
  }
  return newNode;
};
var TokContext3 = function TokContext22(token, isExpr, preserveSpace, override, generator) {
  this.token = token;
  this.isExpr = !!isExpr;
  this.preserveSpace = !!preserveSpace;
  this.override = override;
  this.generator = !!generator;
};
var types$12 = {
  b_stat: new TokContext3("{", false),
  b_expr: new TokContext3("{", true),
  b_tmpl: new TokContext3("${", false),
  p_stat: new TokContext3("(", false),
  p_expr: new TokContext3("(", true),
  q_tmpl: new TokContext3("`", true, true, function(p5) {
    return p5.tryReadTemplateToken();
  }),
  f_stat: new TokContext3("function", false),
  f_expr: new TokContext3("function", true),
  f_expr_gen: new TokContext3("function", true, false, null, true),
  f_gen: new TokContext3("function", false, false, null, true)
};
var pp$72 = Parser3.prototype;
pp$72.initialContext = function() {
  return [types$12.b_stat];
};
pp$72.braceIsBlock = function(prevType) {
  var parent = this.curContext();
  if (parent === types$12.f_expr || parent === types$12.f_stat) {
    return true;
  }
  if (prevType === types6.colon && (parent === types$12.b_stat || parent === types$12.b_expr)) {
    return !parent.isExpr;
  }
  if (prevType === types6._return || prevType === types6.name && this.exprAllowed) {
    return lineBreak2.test(this.input.slice(this.lastTokEnd, this.start));
  }
  if (prevType === types6._else || prevType === types6.semi || prevType === types6.eof || prevType === types6.parenR || prevType === types6.arrow) {
    return true;
  }
  if (prevType === types6.braceL) {
    return parent === types$12.b_stat;
  }
  if (prevType === types6._var || prevType === types6._const || prevType === types6.name) {
    return false;
  }
  return !this.exprAllowed;
};
pp$72.inGeneratorContext = function() {
  for (var i6 = this.context.length - 1; i6 >= 1; i6--) {
    var context = this.context[i6];
    if (context.token === "function") {
      return context.generator;
    }
  }
  return false;
};
pp$72.updateContext = function(prevType) {
  var update, type4 = this.type;
  if (type4.keyword && prevType === types6.dot) {
    this.exprAllowed = false;
  } else if (update = type4.updateContext) {
    update.call(this, prevType);
  } else {
    this.exprAllowed = type4.beforeExpr;
  }
};
types6.parenR.updateContext = types6.braceR.updateContext = function() {
  if (this.context.length === 1) {
    this.exprAllowed = true;
    return;
  }
  var out = this.context.pop();
  if (out === types$12.b_stat && this.curContext().token === "function") {
    out = this.context.pop();
  }
  this.exprAllowed = !out.isExpr;
};
types6.braceL.updateContext = function(prevType) {
  this.context.push(this.braceIsBlock(prevType) ? types$12.b_stat : types$12.b_expr);
  this.exprAllowed = true;
};
types6.dollarBraceL.updateContext = function() {
  this.context.push(types$12.b_tmpl);
  this.exprAllowed = true;
};
types6.parenL.updateContext = function(prevType) {
  var statementParens = prevType === types6._if || prevType === types6._for || prevType === types6._with || prevType === types6._while;
  this.context.push(statementParens ? types$12.p_stat : types$12.p_expr);
  this.exprAllowed = true;
};
types6.incDec.updateContext = function() {
};
types6._function.updateContext = types6._class.updateContext = function(prevType) {
  if (prevType.beforeExpr && prevType !== types6._else && !(prevType === types6.semi && this.curContext() !== types$12.p_stat) && !(prevType === types6._return && lineBreak2.test(this.input.slice(this.lastTokEnd, this.start))) && !((prevType === types6.colon || prevType === types6.braceL) && this.curContext() === types$12.b_stat)) {
    this.context.push(types$12.f_expr);
  } else {
    this.context.push(types$12.f_stat);
  }
  this.exprAllowed = false;
};
types6.backQuote.updateContext = function() {
  if (this.curContext() === types$12.q_tmpl) {
    this.context.pop();
  } else {
    this.context.push(types$12.q_tmpl);
  }
  this.exprAllowed = false;
};
types6.star.updateContext = function(prevType) {
  if (prevType === types6._function) {
    var index2 = this.context.length - 1;
    if (this.context[index2] === types$12.f_expr) {
      this.context[index2] = types$12.f_expr_gen;
    } else {
      this.context[index2] = types$12.f_gen;
    }
  }
  this.exprAllowed = true;
};
types6.name.updateContext = function(prevType) {
  var allowed = false;
  if (this.options.ecmaVersion >= 6 && prevType !== types6.dot) {
    if (this.value === "of" && !this.exprAllowed || this.value === "yield" && this.inGeneratorContext()) {
      allowed = true;
    }
  }
  this.exprAllowed = allowed;
};
var ecma9BinaryProperties2 = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";
var ecma10BinaryProperties2 = ecma9BinaryProperties2 + " Extended_Pictographic";
var ecma11BinaryProperties2 = ecma10BinaryProperties2;
var ecma12BinaryProperties = ecma11BinaryProperties2 + " EBase EComp EMod EPres ExtPict";
var unicodeBinaryProperties2 = {
  9: ecma9BinaryProperties2,
  10: ecma10BinaryProperties2,
  11: ecma11BinaryProperties2,
  12: ecma12BinaryProperties
};
var unicodeGeneralCategoryValues2 = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu";
var ecma9ScriptValues2 = "Adlam Adlm Ahom Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb";
var ecma10ScriptValues2 = ecma9ScriptValues2 + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
var ecma11ScriptValues2 = ecma10ScriptValues2 + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
var ecma12ScriptValues = ecma11ScriptValues2 + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";
var unicodeScriptValues2 = {
  9: ecma9ScriptValues2,
  10: ecma10ScriptValues2,
  11: ecma11ScriptValues2,
  12: ecma12ScriptValues
};
var data2 = {};
function buildUnicodeData2(ecmaVersion) {
  var d4 = data2[ecmaVersion] = {
    binary: wordsRegexp2(unicodeBinaryProperties2[ecmaVersion] + " " + unicodeGeneralCategoryValues2),
    nonBinary: {
      General_Category: wordsRegexp2(unicodeGeneralCategoryValues2),
      Script: wordsRegexp2(unicodeScriptValues2[ecmaVersion])
    }
  };
  d4.nonBinary.Script_Extensions = d4.nonBinary.Script;
  d4.nonBinary.gc = d4.nonBinary.General_Category;
  d4.nonBinary.sc = d4.nonBinary.Script;
  d4.nonBinary.scx = d4.nonBinary.Script_Extensions;
}
buildUnicodeData2(9);
buildUnicodeData2(10);
buildUnicodeData2(11);
buildUnicodeData2(12);
var pp$82 = Parser3.prototype;
var RegExpValidationState3 = function RegExpValidationState22(parser) {
  this.parser = parser;
  this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "");
  this.unicodeProperties = data2[parser.options.ecmaVersion >= 12 ? 12 : parser.options.ecmaVersion];
  this.source = "";
  this.flags = "";
  this.start = 0;
  this.switchU = false;
  this.switchN = false;
  this.pos = 0;
  this.lastIntValue = 0;
  this.lastStringValue = "";
  this.lastAssertionIsQuantifiable = false;
  this.numCapturingParens = 0;
  this.maxBackReference = 0;
  this.groupNames = [];
  this.backReferenceNames = [];
};
RegExpValidationState3.prototype.reset = function reset3(start, pattern, flags) {
  var unicode = flags.indexOf("u") !== -1;
  this.start = start | 0;
  this.source = pattern + "";
  this.flags = flags;
  this.switchU = unicode && this.parser.options.ecmaVersion >= 6;
  this.switchN = unicode && this.parser.options.ecmaVersion >= 9;
};
RegExpValidationState3.prototype.raise = function raise2(message) {
  this.parser.raiseRecoverable(this.start, "Invalid regular expression: /" + this.source + "/: " + message);
};
RegExpValidationState3.prototype.at = function at2(i6, forceU) {
  if (forceU === void 0)
    forceU = false;
  var s5 = this.source;
  var l6 = s5.length;
  if (i6 >= l6) {
    return -1;
  }
  var c6 = s5.charCodeAt(i6);
  if (!(forceU || this.switchU) || c6 <= 55295 || c6 >= 57344 || i6 + 1 >= l6) {
    return c6;
  }
  var next = s5.charCodeAt(i6 + 1);
  return next >= 56320 && next <= 57343 ? (c6 << 10) + next - 56613888 : c6;
};
RegExpValidationState3.prototype.nextIndex = function nextIndex2(i6, forceU) {
  if (forceU === void 0)
    forceU = false;
  var s5 = this.source;
  var l6 = s5.length;
  if (i6 >= l6) {
    return l6;
  }
  var c6 = s5.charCodeAt(i6), next;
  if (!(forceU || this.switchU) || c6 <= 55295 || c6 >= 57344 || i6 + 1 >= l6 || (next = s5.charCodeAt(i6 + 1)) < 56320 || next > 57343) {
    return i6 + 1;
  }
  return i6 + 2;
};
RegExpValidationState3.prototype.current = function current2(forceU) {
  if (forceU === void 0)
    forceU = false;
  return this.at(this.pos, forceU);
};
RegExpValidationState3.prototype.lookahead = function lookahead2(forceU) {
  if (forceU === void 0)
    forceU = false;
  return this.at(this.nextIndex(this.pos, forceU), forceU);
};
RegExpValidationState3.prototype.advance = function advance2(forceU) {
  if (forceU === void 0)
    forceU = false;
  this.pos = this.nextIndex(this.pos, forceU);
};
RegExpValidationState3.prototype.eat = function eat2(ch, forceU) {
  if (forceU === void 0)
    forceU = false;
  if (this.current(forceU) === ch) {
    this.advance(forceU);
    return true;
  }
  return false;
};
function codePointToString2(ch) {
  if (ch <= 65535) {
    return String.fromCharCode(ch);
  }
  ch -= 65536;
  return String.fromCharCode((ch >> 10) + 55296, (ch & 1023) + 56320);
}
pp$82.validateRegExpFlags = function(state2) {
  var validFlags = state2.validFlags;
  var flags = state2.flags;
  for (var i6 = 0; i6 < flags.length; i6++) {
    var flag = flags.charAt(i6);
    if (validFlags.indexOf(flag) === -1) {
      this.raise(state2.start, "Invalid regular expression flag");
    }
    if (flags.indexOf(flag, i6 + 1) > -1) {
      this.raise(state2.start, "Duplicate regular expression flag");
    }
  }
};
pp$82.validateRegExpPattern = function(state2) {
  this.regexp_pattern(state2);
  if (!state2.switchN && this.options.ecmaVersion >= 9 && state2.groupNames.length > 0) {
    state2.switchN = true;
    this.regexp_pattern(state2);
  }
};
pp$82.regexp_pattern = function(state2) {
  state2.pos = 0;
  state2.lastIntValue = 0;
  state2.lastStringValue = "";
  state2.lastAssertionIsQuantifiable = false;
  state2.numCapturingParens = 0;
  state2.maxBackReference = 0;
  state2.groupNames.length = 0;
  state2.backReferenceNames.length = 0;
  this.regexp_disjunction(state2);
  if (state2.pos !== state2.source.length) {
    if (state2.eat(41)) {
      state2.raise("Unmatched ')'");
    }
    if (state2.eat(93) || state2.eat(125)) {
      state2.raise("Lone quantifier brackets");
    }
  }
  if (state2.maxBackReference > state2.numCapturingParens) {
    state2.raise("Invalid escape");
  }
  for (var i6 = 0, list = state2.backReferenceNames; i6 < list.length; i6 += 1) {
    var name2 = list[i6];
    if (state2.groupNames.indexOf(name2) === -1) {
      state2.raise("Invalid named capture referenced");
    }
  }
};
pp$82.regexp_disjunction = function(state2) {
  this.regexp_alternative(state2);
  while (state2.eat(124)) {
    this.regexp_alternative(state2);
  }
  if (this.regexp_eatQuantifier(state2, true)) {
    state2.raise("Nothing to repeat");
  }
  if (state2.eat(123)) {
    state2.raise("Lone quantifier brackets");
  }
};
pp$82.regexp_alternative = function(state2) {
  while (state2.pos < state2.source.length && this.regexp_eatTerm(state2)) {
  }
};
pp$82.regexp_eatTerm = function(state2) {
  if (this.regexp_eatAssertion(state2)) {
    if (state2.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state2)) {
      if (state2.switchU) {
        state2.raise("Invalid quantifier");
      }
    }
    return true;
  }
  if (state2.switchU ? this.regexp_eatAtom(state2) : this.regexp_eatExtendedAtom(state2)) {
    this.regexp_eatQuantifier(state2);
    return true;
  }
  return false;
};
pp$82.regexp_eatAssertion = function(state2) {
  var start = state2.pos;
  state2.lastAssertionIsQuantifiable = false;
  if (state2.eat(94) || state2.eat(36)) {
    return true;
  }
  if (state2.eat(92)) {
    if (state2.eat(66) || state2.eat(98)) {
      return true;
    }
    state2.pos = start;
  }
  if (state2.eat(40) && state2.eat(63)) {
    var lookbehind = false;
    if (this.options.ecmaVersion >= 9) {
      lookbehind = state2.eat(60);
    }
    if (state2.eat(61) || state2.eat(33)) {
      this.regexp_disjunction(state2);
      if (!state2.eat(41)) {
        state2.raise("Unterminated group");
      }
      state2.lastAssertionIsQuantifiable = !lookbehind;
      return true;
    }
  }
  state2.pos = start;
  return false;
};
pp$82.regexp_eatQuantifier = function(state2, noError) {
  if (noError === void 0)
    noError = false;
  if (this.regexp_eatQuantifierPrefix(state2, noError)) {
    state2.eat(63);
    return true;
  }
  return false;
};
pp$82.regexp_eatQuantifierPrefix = function(state2, noError) {
  return state2.eat(42) || state2.eat(43) || state2.eat(63) || this.regexp_eatBracedQuantifier(state2, noError);
};
pp$82.regexp_eatBracedQuantifier = function(state2, noError) {
  var start = state2.pos;
  if (state2.eat(123)) {
    var min2 = 0, max = -1;
    if (this.regexp_eatDecimalDigits(state2)) {
      min2 = state2.lastIntValue;
      if (state2.eat(44) && this.regexp_eatDecimalDigits(state2)) {
        max = state2.lastIntValue;
      }
      if (state2.eat(125)) {
        if (max !== -1 && max < min2 && !noError) {
          state2.raise("numbers out of order in {} quantifier");
        }
        return true;
      }
    }
    if (state2.switchU && !noError) {
      state2.raise("Incomplete quantifier");
    }
    state2.pos = start;
  }
  return false;
};
pp$82.regexp_eatAtom = function(state2) {
  return this.regexp_eatPatternCharacters(state2) || state2.eat(46) || this.regexp_eatReverseSolidusAtomEscape(state2) || this.regexp_eatCharacterClass(state2) || this.regexp_eatUncapturingGroup(state2) || this.regexp_eatCapturingGroup(state2);
};
pp$82.regexp_eatReverseSolidusAtomEscape = function(state2) {
  var start = state2.pos;
  if (state2.eat(92)) {
    if (this.regexp_eatAtomEscape(state2)) {
      return true;
    }
    state2.pos = start;
  }
  return false;
};
pp$82.regexp_eatUncapturingGroup = function(state2) {
  var start = state2.pos;
  if (state2.eat(40)) {
    if (state2.eat(63) && state2.eat(58)) {
      this.regexp_disjunction(state2);
      if (state2.eat(41)) {
        return true;
      }
      state2.raise("Unterminated group");
    }
    state2.pos = start;
  }
  return false;
};
pp$82.regexp_eatCapturingGroup = function(state2) {
  if (state2.eat(40)) {
    if (this.options.ecmaVersion >= 9) {
      this.regexp_groupSpecifier(state2);
    } else if (state2.current() === 63) {
      state2.raise("Invalid group");
    }
    this.regexp_disjunction(state2);
    if (state2.eat(41)) {
      state2.numCapturingParens += 1;
      return true;
    }
    state2.raise("Unterminated group");
  }
  return false;
};
pp$82.regexp_eatExtendedAtom = function(state2) {
  return state2.eat(46) || this.regexp_eatReverseSolidusAtomEscape(state2) || this.regexp_eatCharacterClass(state2) || this.regexp_eatUncapturingGroup(state2) || this.regexp_eatCapturingGroup(state2) || this.regexp_eatInvalidBracedQuantifier(state2) || this.regexp_eatExtendedPatternCharacter(state2);
};
pp$82.regexp_eatInvalidBracedQuantifier = function(state2) {
  if (this.regexp_eatBracedQuantifier(state2, true)) {
    state2.raise("Nothing to repeat");
  }
  return false;
};
pp$82.regexp_eatSyntaxCharacter = function(state2) {
  var ch = state2.current();
  if (isSyntaxCharacter2(ch)) {
    state2.lastIntValue = ch;
    state2.advance();
    return true;
  }
  return false;
};
function isSyntaxCharacter2(ch) {
  return ch === 36 || ch >= 40 && ch <= 43 || ch === 46 || ch === 63 || ch >= 91 && ch <= 94 || ch >= 123 && ch <= 125;
}
pp$82.regexp_eatPatternCharacters = function(state2) {
  var start = state2.pos;
  var ch = 0;
  while ((ch = state2.current()) !== -1 && !isSyntaxCharacter2(ch)) {
    state2.advance();
  }
  return state2.pos !== start;
};
pp$82.regexp_eatExtendedPatternCharacter = function(state2) {
  var ch = state2.current();
  if (ch !== -1 && ch !== 36 && !(ch >= 40 && ch <= 43) && ch !== 46 && ch !== 63 && ch !== 91 && ch !== 94 && ch !== 124) {
    state2.advance();
    return true;
  }
  return false;
};
pp$82.regexp_groupSpecifier = function(state2) {
  if (state2.eat(63)) {
    if (this.regexp_eatGroupName(state2)) {
      if (state2.groupNames.indexOf(state2.lastStringValue) !== -1) {
        state2.raise("Duplicate capture group name");
      }
      state2.groupNames.push(state2.lastStringValue);
      return;
    }
    state2.raise("Invalid group");
  }
};
pp$82.regexp_eatGroupName = function(state2) {
  state2.lastStringValue = "";
  if (state2.eat(60)) {
    if (this.regexp_eatRegExpIdentifierName(state2) && state2.eat(62)) {
      return true;
    }
    state2.raise("Invalid capture group name");
  }
  return false;
};
pp$82.regexp_eatRegExpIdentifierName = function(state2) {
  state2.lastStringValue = "";
  if (this.regexp_eatRegExpIdentifierStart(state2)) {
    state2.lastStringValue += codePointToString2(state2.lastIntValue);
    while (this.regexp_eatRegExpIdentifierPart(state2)) {
      state2.lastStringValue += codePointToString2(state2.lastIntValue);
    }
    return true;
  }
  return false;
};
pp$82.regexp_eatRegExpIdentifierStart = function(state2) {
  var start = state2.pos;
  var forceU = this.options.ecmaVersion >= 11;
  var ch = state2.current(forceU);
  state2.advance(forceU);
  if (ch === 92 && this.regexp_eatRegExpUnicodeEscapeSequence(state2, forceU)) {
    ch = state2.lastIntValue;
  }
  if (isRegExpIdentifierStart2(ch)) {
    state2.lastIntValue = ch;
    return true;
  }
  state2.pos = start;
  return false;
};
function isRegExpIdentifierStart2(ch) {
  return isIdentifierStart2(ch, true) || ch === 36 || ch === 95;
}
pp$82.regexp_eatRegExpIdentifierPart = function(state2) {
  var start = state2.pos;
  var forceU = this.options.ecmaVersion >= 11;
  var ch = state2.current(forceU);
  state2.advance(forceU);
  if (ch === 92 && this.regexp_eatRegExpUnicodeEscapeSequence(state2, forceU)) {
    ch = state2.lastIntValue;
  }
  if (isRegExpIdentifierPart2(ch)) {
    state2.lastIntValue = ch;
    return true;
  }
  state2.pos = start;
  return false;
};
function isRegExpIdentifierPart2(ch) {
  return isIdentifierChar2(ch, true) || ch === 36 || ch === 95 || ch === 8204 || ch === 8205;
}
pp$82.regexp_eatAtomEscape = function(state2) {
  if (this.regexp_eatBackReference(state2) || this.regexp_eatCharacterClassEscape(state2) || this.regexp_eatCharacterEscape(state2) || state2.switchN && this.regexp_eatKGroupName(state2)) {
    return true;
  }
  if (state2.switchU) {
    if (state2.current() === 99) {
      state2.raise("Invalid unicode escape");
    }
    state2.raise("Invalid escape");
  }
  return false;
};
pp$82.regexp_eatBackReference = function(state2) {
  var start = state2.pos;
  if (this.regexp_eatDecimalEscape(state2)) {
    var n5 = state2.lastIntValue;
    if (state2.switchU) {
      if (n5 > state2.maxBackReference) {
        state2.maxBackReference = n5;
      }
      return true;
    }
    if (n5 <= state2.numCapturingParens) {
      return true;
    }
    state2.pos = start;
  }
  return false;
};
pp$82.regexp_eatKGroupName = function(state2) {
  if (state2.eat(107)) {
    if (this.regexp_eatGroupName(state2)) {
      state2.backReferenceNames.push(state2.lastStringValue);
      return true;
    }
    state2.raise("Invalid named reference");
  }
  return false;
};
pp$82.regexp_eatCharacterEscape = function(state2) {
  return this.regexp_eatControlEscape(state2) || this.regexp_eatCControlLetter(state2) || this.regexp_eatZero(state2) || this.regexp_eatHexEscapeSequence(state2) || this.regexp_eatRegExpUnicodeEscapeSequence(state2, false) || !state2.switchU && this.regexp_eatLegacyOctalEscapeSequence(state2) || this.regexp_eatIdentityEscape(state2);
};
pp$82.regexp_eatCControlLetter = function(state2) {
  var start = state2.pos;
  if (state2.eat(99)) {
    if (this.regexp_eatControlLetter(state2)) {
      return true;
    }
    state2.pos = start;
  }
  return false;
};
pp$82.regexp_eatZero = function(state2) {
  if (state2.current() === 48 && !isDecimalDigit2(state2.lookahead())) {
    state2.lastIntValue = 0;
    state2.advance();
    return true;
  }
  return false;
};
pp$82.regexp_eatControlEscape = function(state2) {
  var ch = state2.current();
  if (ch === 116) {
    state2.lastIntValue = 9;
    state2.advance();
    return true;
  }
  if (ch === 110) {
    state2.lastIntValue = 10;
    state2.advance();
    return true;
  }
  if (ch === 118) {
    state2.lastIntValue = 11;
    state2.advance();
    return true;
  }
  if (ch === 102) {
    state2.lastIntValue = 12;
    state2.advance();
    return true;
  }
  if (ch === 114) {
    state2.lastIntValue = 13;
    state2.advance();
    return true;
  }
  return false;
};
pp$82.regexp_eatControlLetter = function(state2) {
  var ch = state2.current();
  if (isControlLetter2(ch)) {
    state2.lastIntValue = ch % 32;
    state2.advance();
    return true;
  }
  return false;
};
function isControlLetter2(ch) {
  return ch >= 65 && ch <= 90 || ch >= 97 && ch <= 122;
}
pp$82.regexp_eatRegExpUnicodeEscapeSequence = function(state2, forceU) {
  if (forceU === void 0)
    forceU = false;
  var start = state2.pos;
  var switchU = forceU || state2.switchU;
  if (state2.eat(117)) {
    if (this.regexp_eatFixedHexDigits(state2, 4)) {
      var lead = state2.lastIntValue;
      if (switchU && lead >= 55296 && lead <= 56319) {
        var leadSurrogateEnd = state2.pos;
        if (state2.eat(92) && state2.eat(117) && this.regexp_eatFixedHexDigits(state2, 4)) {
          var trail = state2.lastIntValue;
          if (trail >= 56320 && trail <= 57343) {
            state2.lastIntValue = (lead - 55296) * 1024 + (trail - 56320) + 65536;
            return true;
          }
        }
        state2.pos = leadSurrogateEnd;
        state2.lastIntValue = lead;
      }
      return true;
    }
    if (switchU && state2.eat(123) && this.regexp_eatHexDigits(state2) && state2.eat(125) && isValidUnicode2(state2.lastIntValue)) {
      return true;
    }
    if (switchU) {
      state2.raise("Invalid unicode escape");
    }
    state2.pos = start;
  }
  return false;
};
function isValidUnicode2(ch) {
  return ch >= 0 && ch <= 1114111;
}
pp$82.regexp_eatIdentityEscape = function(state2) {
  if (state2.switchU) {
    if (this.regexp_eatSyntaxCharacter(state2)) {
      return true;
    }
    if (state2.eat(47)) {
      state2.lastIntValue = 47;
      return true;
    }
    return false;
  }
  var ch = state2.current();
  if (ch !== 99 && (!state2.switchN || ch !== 107)) {
    state2.lastIntValue = ch;
    state2.advance();
    return true;
  }
  return false;
};
pp$82.regexp_eatDecimalEscape = function(state2) {
  state2.lastIntValue = 0;
  var ch = state2.current();
  if (ch >= 49 && ch <= 57) {
    do {
      state2.lastIntValue = 10 * state2.lastIntValue + (ch - 48);
      state2.advance();
    } while ((ch = state2.current()) >= 48 && ch <= 57);
    return true;
  }
  return false;
};
pp$82.regexp_eatCharacterClassEscape = function(state2) {
  var ch = state2.current();
  if (isCharacterClassEscape2(ch)) {
    state2.lastIntValue = -1;
    state2.advance();
    return true;
  }
  if (state2.switchU && this.options.ecmaVersion >= 9 && (ch === 80 || ch === 112)) {
    state2.lastIntValue = -1;
    state2.advance();
    if (state2.eat(123) && this.regexp_eatUnicodePropertyValueExpression(state2) && state2.eat(125)) {
      return true;
    }
    state2.raise("Invalid property name");
  }
  return false;
};
function isCharacterClassEscape2(ch) {
  return ch === 100 || ch === 68 || ch === 115 || ch === 83 || ch === 119 || ch === 87;
}
pp$82.regexp_eatUnicodePropertyValueExpression = function(state2) {
  var start = state2.pos;
  if (this.regexp_eatUnicodePropertyName(state2) && state2.eat(61)) {
    var name2 = state2.lastStringValue;
    if (this.regexp_eatUnicodePropertyValue(state2)) {
      var value = state2.lastStringValue;
      this.regexp_validateUnicodePropertyNameAndValue(state2, name2, value);
      return true;
    }
  }
  state2.pos = start;
  if (this.regexp_eatLoneUnicodePropertyNameOrValue(state2)) {
    var nameOrValue = state2.lastStringValue;
    this.regexp_validateUnicodePropertyNameOrValue(state2, nameOrValue);
    return true;
  }
  return false;
};
pp$82.regexp_validateUnicodePropertyNameAndValue = function(state2, name2, value) {
  if (!has2(state2.unicodeProperties.nonBinary, name2)) {
    state2.raise("Invalid property name");
  }
  if (!state2.unicodeProperties.nonBinary[name2].test(value)) {
    state2.raise("Invalid property value");
  }
};
pp$82.regexp_validateUnicodePropertyNameOrValue = function(state2, nameOrValue) {
  if (!state2.unicodeProperties.binary.test(nameOrValue)) {
    state2.raise("Invalid property name");
  }
};
pp$82.regexp_eatUnicodePropertyName = function(state2) {
  var ch = 0;
  state2.lastStringValue = "";
  while (isUnicodePropertyNameCharacter2(ch = state2.current())) {
    state2.lastStringValue += codePointToString2(ch);
    state2.advance();
  }
  return state2.lastStringValue !== "";
};
function isUnicodePropertyNameCharacter2(ch) {
  return isControlLetter2(ch) || ch === 95;
}
pp$82.regexp_eatUnicodePropertyValue = function(state2) {
  var ch = 0;
  state2.lastStringValue = "";
  while (isUnicodePropertyValueCharacter2(ch = state2.current())) {
    state2.lastStringValue += codePointToString2(ch);
    state2.advance();
  }
  return state2.lastStringValue !== "";
};
function isUnicodePropertyValueCharacter2(ch) {
  return isUnicodePropertyNameCharacter2(ch) || isDecimalDigit2(ch);
}
pp$82.regexp_eatLoneUnicodePropertyNameOrValue = function(state2) {
  return this.regexp_eatUnicodePropertyValue(state2);
};
pp$82.regexp_eatCharacterClass = function(state2) {
  if (state2.eat(91)) {
    state2.eat(94);
    this.regexp_classRanges(state2);
    if (state2.eat(93)) {
      return true;
    }
    state2.raise("Unterminated character class");
  }
  return false;
};
pp$82.regexp_classRanges = function(state2) {
  while (this.regexp_eatClassAtom(state2)) {
    var left = state2.lastIntValue;
    if (state2.eat(45) && this.regexp_eatClassAtom(state2)) {
      var right = state2.lastIntValue;
      if (state2.switchU && (left === -1 || right === -1)) {
        state2.raise("Invalid character class");
      }
      if (left !== -1 && right !== -1 && left > right) {
        state2.raise("Range out of order in character class");
      }
    }
  }
};
pp$82.regexp_eatClassAtom = function(state2) {
  var start = state2.pos;
  if (state2.eat(92)) {
    if (this.regexp_eatClassEscape(state2)) {
      return true;
    }
    if (state2.switchU) {
      var ch$1 = state2.current();
      if (ch$1 === 99 || isOctalDigit2(ch$1)) {
        state2.raise("Invalid class escape");
      }
      state2.raise("Invalid escape");
    }
    state2.pos = start;
  }
  var ch = state2.current();
  if (ch !== 93) {
    state2.lastIntValue = ch;
    state2.advance();
    return true;
  }
  return false;
};
pp$82.regexp_eatClassEscape = function(state2) {
  var start = state2.pos;
  if (state2.eat(98)) {
    state2.lastIntValue = 8;
    return true;
  }
  if (state2.switchU && state2.eat(45)) {
    state2.lastIntValue = 45;
    return true;
  }
  if (!state2.switchU && state2.eat(99)) {
    if (this.regexp_eatClassControlLetter(state2)) {
      return true;
    }
    state2.pos = start;
  }
  return this.regexp_eatCharacterClassEscape(state2) || this.regexp_eatCharacterEscape(state2);
};
pp$82.regexp_eatClassControlLetter = function(state2) {
  var ch = state2.current();
  if (isDecimalDigit2(ch) || ch === 95) {
    state2.lastIntValue = ch % 32;
    state2.advance();
    return true;
  }
  return false;
};
pp$82.regexp_eatHexEscapeSequence = function(state2) {
  var start = state2.pos;
  if (state2.eat(120)) {
    if (this.regexp_eatFixedHexDigits(state2, 2)) {
      return true;
    }
    if (state2.switchU) {
      state2.raise("Invalid escape");
    }
    state2.pos = start;
  }
  return false;
};
pp$82.regexp_eatDecimalDigits = function(state2) {
  var start = state2.pos;
  var ch = 0;
  state2.lastIntValue = 0;
  while (isDecimalDigit2(ch = state2.current())) {
    state2.lastIntValue = 10 * state2.lastIntValue + (ch - 48);
    state2.advance();
  }
  return state2.pos !== start;
};
function isDecimalDigit2(ch) {
  return ch >= 48 && ch <= 57;
}
pp$82.regexp_eatHexDigits = function(state2) {
  var start = state2.pos;
  var ch = 0;
  state2.lastIntValue = 0;
  while (isHexDigit2(ch = state2.current())) {
    state2.lastIntValue = 16 * state2.lastIntValue + hexToInt2(ch);
    state2.advance();
  }
  return state2.pos !== start;
};
function isHexDigit2(ch) {
  return ch >= 48 && ch <= 57 || ch >= 65 && ch <= 70 || ch >= 97 && ch <= 102;
}
function hexToInt2(ch) {
  if (ch >= 65 && ch <= 70) {
    return 10 + (ch - 65);
  }
  if (ch >= 97 && ch <= 102) {
    return 10 + (ch - 97);
  }
  return ch - 48;
}
pp$82.regexp_eatLegacyOctalEscapeSequence = function(state2) {
  if (this.regexp_eatOctalDigit(state2)) {
    var n1 = state2.lastIntValue;
    if (this.regexp_eatOctalDigit(state2)) {
      var n22 = state2.lastIntValue;
      if (n1 <= 3 && this.regexp_eatOctalDigit(state2)) {
        state2.lastIntValue = n1 * 64 + n22 * 8 + state2.lastIntValue;
      } else {
        state2.lastIntValue = n1 * 8 + n22;
      }
    } else {
      state2.lastIntValue = n1;
    }
    return true;
  }
  return false;
};
pp$82.regexp_eatOctalDigit = function(state2) {
  var ch = state2.current();
  if (isOctalDigit2(ch)) {
    state2.lastIntValue = ch - 48;
    state2.advance();
    return true;
  }
  state2.lastIntValue = 0;
  return false;
};
function isOctalDigit2(ch) {
  return ch >= 48 && ch <= 55;
}
pp$82.regexp_eatFixedHexDigits = function(state2, length) {
  var start = state2.pos;
  state2.lastIntValue = 0;
  for (var i6 = 0; i6 < length; ++i6) {
    var ch = state2.current();
    if (!isHexDigit2(ch)) {
      state2.pos = start;
      return false;
    }
    state2.lastIntValue = 16 * state2.lastIntValue + hexToInt2(ch);
    state2.advance();
  }
  return true;
};
var Token3 = function Token22(p5) {
  this.type = p5.type;
  this.value = p5.value;
  this.start = p5.start;
  this.end = p5.end;
  if (p5.options.locations) {
    this.loc = new SourceLocation3(p5, p5.startLoc, p5.endLoc);
  }
  if (p5.options.ranges) {
    this.range = [p5.start, p5.end];
  }
};
var pp$92 = Parser3.prototype;
pp$92.next = function(ignoreEscapeSequenceInKeyword) {
  if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc) {
    this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword);
  }
  if (this.options.onToken) {
    this.options.onToken(new Token3(this));
  }
  this.lastTokEnd = this.end;
  this.lastTokStart = this.start;
  this.lastTokEndLoc = this.endLoc;
  this.lastTokStartLoc = this.startLoc;
  this.nextToken();
};
pp$92.getToken = function() {
  this.next();
  return new Token3(this);
};
if (typeof Symbol !== "undefined") {
  pp$92[Symbol.iterator] = function() {
    var this$1 = this;
    return {
      next: function() {
        var token = this$1.getToken();
        return {
          done: token.type === types6.eof,
          value: token
        };
      }
    };
  };
}
pp$92.curContext = function() {
  return this.context[this.context.length - 1];
};
pp$92.nextToken = function() {
  var curContext = this.curContext();
  if (!curContext || !curContext.preserveSpace) {
    this.skipSpace();
  }
  this.start = this.pos;
  if (this.options.locations) {
    this.startLoc = this.curPosition();
  }
  if (this.pos >= this.input.length) {
    return this.finishToken(types6.eof);
  }
  if (curContext.override) {
    return curContext.override(this);
  } else {
    this.readToken(this.fullCharCodeAtPos());
  }
};
pp$92.readToken = function(code5) {
  if (isIdentifierStart2(code5, this.options.ecmaVersion >= 6) || code5 === 92) {
    return this.readWord();
  }
  return this.getTokenFromCode(code5);
};
pp$92.fullCharCodeAtPos = function() {
  var code5 = this.input.charCodeAt(this.pos);
  if (code5 <= 55295 || code5 >= 56320) {
    return code5;
  }
  var next = this.input.charCodeAt(this.pos + 1);
  return next <= 56319 || next >= 57344 ? code5 : (code5 << 10) + next - 56613888;
};
pp$92.skipBlockComment = function() {
  var startLoc = this.options.onComment && this.curPosition();
  var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
  if (end === -1) {
    this.raise(this.pos - 2, "Unterminated comment");
  }
  this.pos = end + 2;
  if (this.options.locations) {
    lineBreakG2.lastIndex = start;
    var match;
    while ((match = lineBreakG2.exec(this.input)) && match.index < this.pos) {
      ++this.curLine;
      this.lineStart = match.index + match[0].length;
    }
  }
  if (this.options.onComment) {
    this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos, startLoc, this.curPosition());
  }
};
pp$92.skipLineComment = function(startSkip) {
  var start = this.pos;
  var startLoc = this.options.onComment && this.curPosition();
  var ch = this.input.charCodeAt(this.pos += startSkip);
  while (this.pos < this.input.length && !isNewLine2(ch)) {
    ch = this.input.charCodeAt(++this.pos);
  }
  if (this.options.onComment) {
    this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos, startLoc, this.curPosition());
  }
};
pp$92.skipSpace = function() {
  loop:
    while (this.pos < this.input.length) {
      var ch = this.input.charCodeAt(this.pos);
      switch (ch) {
        case 32:
        case 160:
          ++this.pos;
          break;
        case 13:
          if (this.input.charCodeAt(this.pos + 1) === 10) {
            ++this.pos;
          }
        case 10:
        case 8232:
        case 8233:
          ++this.pos;
          if (this.options.locations) {
            ++this.curLine;
            this.lineStart = this.pos;
          }
          break;
        case 47:
          switch (this.input.charCodeAt(this.pos + 1)) {
            case 42:
              this.skipBlockComment();
              break;
            case 47:
              this.skipLineComment(2);
              break;
            default:
              break loop;
          }
          break;
        default:
          if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace2.test(String.fromCharCode(ch))) {
            ++this.pos;
          } else {
            break loop;
          }
      }
    }
};
pp$92.finishToken = function(type4, val) {
  this.end = this.pos;
  if (this.options.locations) {
    this.endLoc = this.curPosition();
  }
  var prevType = this.type;
  this.type = type4;
  this.value = val;
  this.updateContext(prevType);
};
pp$92.readToken_dot = function() {
  var next = this.input.charCodeAt(this.pos + 1);
  if (next >= 48 && next <= 57) {
    return this.readNumber(true);
  }
  var next2 = this.input.charCodeAt(this.pos + 2);
  if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) {
    this.pos += 3;
    return this.finishToken(types6.ellipsis);
  } else {
    ++this.pos;
    return this.finishToken(types6.dot);
  }
};
pp$92.readToken_slash = function() {
  var next = this.input.charCodeAt(this.pos + 1);
  if (this.exprAllowed) {
    ++this.pos;
    return this.readRegexp();
  }
  if (next === 61) {
    return this.finishOp(types6.assign, 2);
  }
  return this.finishOp(types6.slash, 1);
};
pp$92.readToken_mult_modulo_exp = function(code5) {
  var next = this.input.charCodeAt(this.pos + 1);
  var size = 1;
  var tokentype = code5 === 42 ? types6.star : types6.modulo;
  if (this.options.ecmaVersion >= 7 && code5 === 42 && next === 42) {
    ++size;
    tokentype = types6.starstar;
    next = this.input.charCodeAt(this.pos + 2);
  }
  if (next === 61) {
    return this.finishOp(types6.assign, size + 1);
  }
  return this.finishOp(tokentype, size);
};
pp$92.readToken_pipe_amp = function(code5) {
  var next = this.input.charCodeAt(this.pos + 1);
  if (next === code5) {
    if (this.options.ecmaVersion >= 12) {
      var next2 = this.input.charCodeAt(this.pos + 2);
      if (next2 === 61) {
        return this.finishOp(types6.assign, 3);
      }
    }
    return this.finishOp(code5 === 124 ? types6.logicalOR : types6.logicalAND, 2);
  }
  if (next === 61) {
    return this.finishOp(types6.assign, 2);
  }
  return this.finishOp(code5 === 124 ? types6.bitwiseOR : types6.bitwiseAND, 1);
};
pp$92.readToken_caret = function() {
  var next = this.input.charCodeAt(this.pos + 1);
  if (next === 61) {
    return this.finishOp(types6.assign, 2);
  }
  return this.finishOp(types6.bitwiseXOR, 1);
};
pp$92.readToken_plus_min = function(code5) {
  var next = this.input.charCodeAt(this.pos + 1);
  if (next === code5) {
    if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 && (this.lastTokEnd === 0 || lineBreak2.test(this.input.slice(this.lastTokEnd, this.pos)))) {
      this.skipLineComment(3);
      this.skipSpace();
      return this.nextToken();
    }
    return this.finishOp(types6.incDec, 2);
  }
  if (next === 61) {
    return this.finishOp(types6.assign, 2);
  }
  return this.finishOp(types6.plusMin, 1);
};
pp$92.readToken_lt_gt = function(code5) {
  var next = this.input.charCodeAt(this.pos + 1);
  var size = 1;
  if (next === code5) {
    size = code5 === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
    if (this.input.charCodeAt(this.pos + size) === 61) {
      return this.finishOp(types6.assign, size + 1);
    }
    return this.finishOp(types6.bitShift, size);
  }
  if (next === 33 && code5 === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && this.input.charCodeAt(this.pos + 3) === 45) {
    this.skipLineComment(4);
    this.skipSpace();
    return this.nextToken();
  }
  if (next === 61) {
    size = 2;
  }
  return this.finishOp(types6.relational, size);
};
pp$92.readToken_eq_excl = function(code5) {
  var next = this.input.charCodeAt(this.pos + 1);
  if (next === 61) {
    return this.finishOp(types6.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2);
  }
  if (code5 === 61 && next === 62 && this.options.ecmaVersion >= 6) {
    this.pos += 2;
    return this.finishToken(types6.arrow);
  }
  return this.finishOp(code5 === 61 ? types6.eq : types6.prefix, 1);
};
pp$92.readToken_question = function() {
  var ecmaVersion = this.options.ecmaVersion;
  if (ecmaVersion >= 11) {
    var next = this.input.charCodeAt(this.pos + 1);
    if (next === 46) {
      var next2 = this.input.charCodeAt(this.pos + 2);
      if (next2 < 48 || next2 > 57) {
        return this.finishOp(types6.questionDot, 2);
      }
    }
    if (next === 63) {
      if (ecmaVersion >= 12) {
        var next2$1 = this.input.charCodeAt(this.pos + 2);
        if (next2$1 === 61) {
          return this.finishOp(types6.assign, 3);
        }
      }
      return this.finishOp(types6.coalesce, 2);
    }
  }
  return this.finishOp(types6.question, 1);
};
pp$92.readToken_numberSign = function() {
  var ecmaVersion = this.options.ecmaVersion;
  var code5 = 35;
  if (ecmaVersion >= 13) {
    ++this.pos;
    code5 = this.fullCharCodeAtPos();
    if (isIdentifierStart2(code5, true) || code5 === 92) {
      return this.finishToken(types6.privateId, this.readWord1());
    }
  }
  this.raise(this.pos, "Unexpected character '" + codePointToString$12(code5) + "'");
};
pp$92.getTokenFromCode = function(code5) {
  switch (code5) {
    case 46:
      return this.readToken_dot();
    case 40:
      ++this.pos;
      return this.finishToken(types6.parenL);
    case 41:
      ++this.pos;
      return this.finishToken(types6.parenR);
    case 59:
      ++this.pos;
      return this.finishToken(types6.semi);
    case 44:
      ++this.pos;
      return this.finishToken(types6.comma);
    case 91:
      ++this.pos;
      return this.finishToken(types6.bracketL);
    case 93:
      ++this.pos;
      return this.finishToken(types6.bracketR);
    case 123:
      ++this.pos;
      return this.finishToken(types6.braceL);
    case 125:
      ++this.pos;
      return this.finishToken(types6.braceR);
    case 58:
      ++this.pos;
      return this.finishToken(types6.colon);
    case 96:
      if (this.options.ecmaVersion < 6) {
        break;
      }
      ++this.pos;
      return this.finishToken(types6.backQuote);
    case 48:
      var next = this.input.charCodeAt(this.pos + 1);
      if (next === 120 || next === 88) {
        return this.readRadixNumber(16);
      }
      if (this.options.ecmaVersion >= 6) {
        if (next === 111 || next === 79) {
          return this.readRadixNumber(8);
        }
        if (next === 98 || next === 66) {
          return this.readRadixNumber(2);
        }
      }
    case 49:
    case 50:
    case 51:
    case 52:
    case 53:
    case 54:
    case 55:
    case 56:
    case 57:
      return this.readNumber(false);
    case 34:
    case 39:
      return this.readString(code5);
    case 47:
      return this.readToken_slash();
    case 37:
    case 42:
      return this.readToken_mult_modulo_exp(code5);
    case 124:
    case 38:
      return this.readToken_pipe_amp(code5);
    case 94:
      return this.readToken_caret();
    case 43:
    case 45:
      return this.readToken_plus_min(code5);
    case 60:
    case 62:
      return this.readToken_lt_gt(code5);
    case 61:
    case 33:
      return this.readToken_eq_excl(code5);
    case 63:
      return this.readToken_question();
    case 126:
      return this.finishOp(types6.prefix, 1);
    case 35:
      return this.readToken_numberSign();
  }
  this.raise(this.pos, "Unexpected character '" + codePointToString$12(code5) + "'");
};
pp$92.finishOp = function(type4, size) {
  var str3 = this.input.slice(this.pos, this.pos + size);
  this.pos += size;
  return this.finishToken(type4, str3);
};
pp$92.readRegexp = function() {
  var escaped, inClass, start = this.pos;
  for (; ; ) {
    if (this.pos >= this.input.length) {
      this.raise(start, "Unterminated regular expression");
    }
    var ch = this.input.charAt(this.pos);
    if (lineBreak2.test(ch)) {
      this.raise(start, "Unterminated regular expression");
    }
    if (!escaped) {
      if (ch === "[") {
        inClass = true;
      } else if (ch === "]" && inClass) {
        inClass = false;
      } else if (ch === "/" && !inClass) {
        break;
      }
      escaped = ch === "\\";
    } else {
      escaped = false;
    }
    ++this.pos;
  }
  var pattern = this.input.slice(start, this.pos);
  ++this.pos;
  var flagsStart = this.pos;
  var flags = this.readWord1();
  if (this.containsEsc) {
    this.unexpected(flagsStart);
  }
  var state2 = this.regexpState || (this.regexpState = new RegExpValidationState3(this));
  state2.reset(start, pattern, flags);
  this.validateRegExpFlags(state2);
  this.validateRegExpPattern(state2);
  var value = null;
  try {
    value = new RegExp(pattern, flags);
  } catch (e5) {
  }
  return this.finishToken(types6.regexp, { pattern, flags, value });
};
pp$92.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {
  var allowSeparators = this.options.ecmaVersion >= 12 && len === void 0;
  var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;
  var start = this.pos, total = 0, lastCode = 0;
  for (var i6 = 0, e5 = len == null ? Infinity : len; i6 < e5; ++i6, ++this.pos) {
    var code5 = this.input.charCodeAt(this.pos), val = void 0;
    if (allowSeparators && code5 === 95) {
      if (isLegacyOctalNumericLiteral) {
        this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals");
      }
      if (lastCode === 95) {
        this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore");
      }
      if (i6 === 0) {
        this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits");
      }
      lastCode = code5;
      continue;
    }
    if (code5 >= 97) {
      val = code5 - 97 + 10;
    } else if (code5 >= 65) {
      val = code5 - 65 + 10;
    } else if (code5 >= 48 && code5 <= 57) {
      val = code5 - 48;
    } else {
      val = Infinity;
    }
    if (val >= radix) {
      break;
    }
    lastCode = code5;
    total = total * radix + val;
  }
  if (allowSeparators && lastCode === 95) {
    this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits");
  }
  if (this.pos === start || len != null && this.pos - start !== len) {
    return null;
  }
  return total;
};
function stringToNumber2(str3, isLegacyOctalNumericLiteral) {
  if (isLegacyOctalNumericLiteral) {
    return parseInt(str3, 8);
  }
  return parseFloat(str3.replace(/_/g, ""));
}
function stringToBigInt2(str3) {
  if (typeof BigInt !== "function") {
    return null;
  }
  return BigInt(str3.replace(/_/g, ""));
}
pp$92.readRadixNumber = function(radix) {
  var start = this.pos;
  this.pos += 2;
  var val = this.readInt(radix);
  if (val == null) {
    this.raise(this.start + 2, "Expected number in radix " + radix);
  }
  if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
    val = stringToBigInt2(this.input.slice(start, this.pos));
    ++this.pos;
  } else if (isIdentifierStart2(this.fullCharCodeAtPos())) {
    this.raise(this.pos, "Identifier directly after number");
  }
  return this.finishToken(types6.num, val);
};
pp$92.readNumber = function(startsWithDot) {
  var start = this.pos;
  if (!startsWithDot && this.readInt(10, void 0, true) === null) {
    this.raise(start, "Invalid number");
  }
  var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  if (octal && this.strict) {
    this.raise(start, "Invalid number");
  }
  var next = this.input.charCodeAt(this.pos);
  if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
    var val$1 = stringToBigInt2(this.input.slice(start, this.pos));
    ++this.pos;
    if (isIdentifierStart2(this.fullCharCodeAtPos())) {
      this.raise(this.pos, "Identifier directly after number");
    }
    return this.finishToken(types6.num, val$1);
  }
  if (octal && /[89]/.test(this.input.slice(start, this.pos))) {
    octal = false;
  }
  if (next === 46 && !octal) {
    ++this.pos;
    this.readInt(10);
    next = this.input.charCodeAt(this.pos);
  }
  if ((next === 69 || next === 101) && !octal) {
    next = this.input.charCodeAt(++this.pos);
    if (next === 43 || next === 45) {
      ++this.pos;
    }
    if (this.readInt(10) === null) {
      this.raise(start, "Invalid number");
    }
  }
  if (isIdentifierStart2(this.fullCharCodeAtPos())) {
    this.raise(this.pos, "Identifier directly after number");
  }
  var val = stringToNumber2(this.input.slice(start, this.pos), octal);
  return this.finishToken(types6.num, val);
};
pp$92.readCodePoint = function() {
  var ch = this.input.charCodeAt(this.pos), code5;
  if (ch === 123) {
    if (this.options.ecmaVersion < 6) {
      this.unexpected();
    }
    var codePos = ++this.pos;
    code5 = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
    ++this.pos;
    if (code5 > 1114111) {
      this.invalidStringToken(codePos, "Code point out of bounds");
    }
  } else {
    code5 = this.readHexChar(4);
  }
  return code5;
};
function codePointToString$12(code5) {
  if (code5 <= 65535) {
    return String.fromCharCode(code5);
  }
  code5 -= 65536;
  return String.fromCharCode((code5 >> 10) + 55296, (code5 & 1023) + 56320);
}
pp$92.readString = function(quote) {
  var out = "", chunkStart = ++this.pos;
  for (; ; ) {
    if (this.pos >= this.input.length) {
      this.raise(this.start, "Unterminated string constant");
    }
    var ch = this.input.charCodeAt(this.pos);
    if (ch === quote) {
      break;
    }
    if (ch === 92) {
      out += this.input.slice(chunkStart, this.pos);
      out += this.readEscapedChar(false);
      chunkStart = this.pos;
    } else {
      if (isNewLine2(ch, this.options.ecmaVersion >= 10)) {
        this.raise(this.start, "Unterminated string constant");
      }
      ++this.pos;
    }
  }
  out += this.input.slice(chunkStart, this.pos++);
  return this.finishToken(types6.string, out);
};
var INVALID_TEMPLATE_ESCAPE_ERROR2 = {};
pp$92.tryReadTemplateToken = function() {
  this.inTemplateElement = true;
  try {
    this.readTmplToken();
  } catch (err2) {
    if (err2 === INVALID_TEMPLATE_ESCAPE_ERROR2) {
      this.readInvalidTemplateToken();
    } else {
      throw err2;
    }
  }
  this.inTemplateElement = false;
};
pp$92.invalidStringToken = function(position, message) {
  if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
    throw INVALID_TEMPLATE_ESCAPE_ERROR2;
  } else {
    this.raise(position, message);
  }
};
pp$92.readTmplToken = function() {
  var out = "", chunkStart = this.pos;
  for (; ; ) {
    if (this.pos >= this.input.length) {
      this.raise(this.start, "Unterminated template");
    }
    var ch = this.input.charCodeAt(this.pos);
    if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) {
      if (this.pos === this.start && (this.type === types6.template || this.type === types6.invalidTemplate)) {
        if (ch === 36) {
          this.pos += 2;
          return this.finishToken(types6.dollarBraceL);
        } else {
          ++this.pos;
          return this.finishToken(types6.backQuote);
        }
      }
      out += this.input.slice(chunkStart, this.pos);
      return this.finishToken(types6.template, out);
    }
    if (ch === 92) {
      out += this.input.slice(chunkStart, this.pos);
      out += this.readEscapedChar(true);
      chunkStart = this.pos;
    } else if (isNewLine2(ch)) {
      out += this.input.slice(chunkStart, this.pos);
      ++this.pos;
      switch (ch) {
        case 13:
          if (this.input.charCodeAt(this.pos) === 10) {
            ++this.pos;
          }
        case 10:
          out += "\n";
          break;
        default:
          out += String.fromCharCode(ch);
          break;
      }
      if (this.options.locations) {
        ++this.curLine;
        this.lineStart = this.pos;
      }
      chunkStart = this.pos;
    } else {
      ++this.pos;
    }
  }
};
pp$92.readInvalidTemplateToken = function() {
  for (; this.pos < this.input.length; this.pos++) {
    switch (this.input[this.pos]) {
      case "\\":
        ++this.pos;
        break;
      case "$":
        if (this.input[this.pos + 1] !== "{") {
          break;
        }
      case "`":
        return this.finishToken(types6.invalidTemplate, this.input.slice(this.start, this.pos));
    }
  }
  this.raise(this.start, "Unterminated template");
};
pp$92.readEscapedChar = function(inTemplate) {
  var ch = this.input.charCodeAt(++this.pos);
  ++this.pos;
  switch (ch) {
    case 110:
      return "\n";
    case 114:
      return "\r";
    case 120:
      return String.fromCharCode(this.readHexChar(2));
    case 117:
      return codePointToString$12(this.readCodePoint());
    case 116:
      return "	";
    case 98:
      return "\b";
    case 118:
      return "\v";
    case 102:
      return "\f";
    case 13:
      if (this.input.charCodeAt(this.pos) === 10) {
        ++this.pos;
      }
    case 10:
      if (this.options.locations) {
        this.lineStart = this.pos;
        ++this.curLine;
      }
      return "";
    case 56:
    case 57:
      if (this.strict) {
        this.invalidStringToken(this.pos - 1, "Invalid escape sequence");
      }
      if (inTemplate) {
        var codePos = this.pos - 1;
        this.invalidStringToken(codePos, "Invalid escape sequence in template string");
        return null;
      }
    default:
      if (ch >= 48 && ch <= 55) {
        var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
        var octal = parseInt(octalStr, 8);
        if (octal > 255) {
          octalStr = octalStr.slice(0, -1);
          octal = parseInt(octalStr, 8);
        }
        this.pos += octalStr.length - 1;
        ch = this.input.charCodeAt(this.pos);
        if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {
          this.invalidStringToken(this.pos - 1 - octalStr.length, inTemplate ? "Octal literal in template string" : "Octal literal in strict mode");
        }
        return String.fromCharCode(octal);
      }
      if (isNewLine2(ch)) {
        return "";
      }
      return String.fromCharCode(ch);
  }
};
pp$92.readHexChar = function(len) {
  var codePos = this.pos;
  var n5 = this.readInt(16, len);
  if (n5 === null) {
    this.invalidStringToken(codePos, "Bad character escape sequence");
  }
  return n5;
};
pp$92.readWord1 = function() {
  this.containsEsc = false;
  var word = "", first = true, chunkStart = this.pos;
  var astral = this.options.ecmaVersion >= 6;
  while (this.pos < this.input.length) {
    var ch = this.fullCharCodeAtPos();
    if (isIdentifierChar2(ch, astral)) {
      this.pos += ch <= 65535 ? 1 : 2;
    } else if (ch === 92) {
      this.containsEsc = true;
      word += this.input.slice(chunkStart, this.pos);
      var escStart = this.pos;
      if (this.input.charCodeAt(++this.pos) !== 117) {
        this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX");
      }
      ++this.pos;
      var esc = this.readCodePoint();
      if (!(first ? isIdentifierStart2 : isIdentifierChar2)(esc, astral)) {
        this.invalidStringToken(escStart, "Invalid Unicode escape");
      }
      word += codePointToString$12(esc);
      chunkStart = this.pos;
    } else {
      break;
    }
    first = false;
  }
  return word + this.input.slice(chunkStart, this.pos);
};
pp$92.readWord = function() {
  var word = this.readWord1();
  var type4 = types6.name;
  if (this.keywords.test(word)) {
    type4 = keywords$12[word];
  }
  return this.finishToken(type4, word);
};
var version3 = "8.4.0";
Parser3.acorn = {
  Parser: Parser3,
  version: version3,
  defaultOptions: defaultOptions2,
  Position: Position3,
  SourceLocation: SourceLocation3,
  getLineInfo: getLineInfo2,
  Node: Node5,
  TokenType: TokenType3,
  tokTypes: types6,
  keywordTypes: keywords$12,
  TokContext: TokContext3,
  tokContexts: types$12,
  isIdentifierChar: isIdentifierChar2,
  isIdentifierStart: isIdentifierStart2,
  Token: Token3,
  isNewLine: isNewLine2,
  lineBreak: lineBreak2,
  lineBreakG: lineBreakG2,
  nonASCIIwhitespace: nonASCIIwhitespace2
};
function parse32(input, options) {
  return Parser3.parse(input, options);
}

// core/esbuild.ts
init_asserts();
init_process();
init_resources2();
init_temp();

// core/platform.ts
init_platform();
function isWSL() {
  return !!Deno.env.get("WSL_DISTRO_NAME");
}
var _isRStudioOverride;
function isRStudio() {
  if (_isRStudioOverride !== void 0) return _isRStudioOverride;
  return !!Deno.env.get("RSTUDIO");
}
function isPositron() {
  return !!Deno.env.get("POSITRON");
}
function isVSCodeOutputChannel() {
  return !!Deno.env.get("VSCODE_PID");
}
function isVSCodeTerminal() {
  return Deno.env.get("TERM_PROGRAM") === "vscode";
}
function isVSCodeServer() {
  return !!vsCodeServerProxyUri();
}
function isPositWorkbench() {
  return !!Deno.env.get("RS_SERVER_URL") && !!Deno.env.get("RS_SESSION_URL");
}
function isRStudioTerminal() {
  return !!Deno.env.get("RSTUDIO_TERM");
}
function isPositronTerminal() {
  return isPositron();
}
function isServerSession() {
  return isRStudioServer() || isPositWorkbench() || isJupyterServer() || isJupyterHubServer() || isVSCodeServer();
}
function isRStudioServer() {
  return isRStudio() && Deno.env.get("RSTUDIO_PROGRAM_MODE") === "server";
}
function isRStudioPreview() {
  return isRStudio() && !isRStudioTerminal();
}
function isJupyterServer() {
  return !!Deno.env.get("JUPYTER_SERVER_URL");
}
function isJupyterHubServer() {
  return !!jupyterHubUser() && !!jupyterHubServicePrefix();
}
function vsCodeServerProxyUri() {
  return Deno.env.get("VSCODE_PROXY_URI");
}
function jupyterHubHttpReferrer() {
  return Deno.env.get("JUPYTERHUB_HTTP_REFERER");
}
function jupyterHubUser() {
  return Deno.env.get("JUPYTERHUB_USER");
}
function jupyterHubServicePrefix() {
  return Deno.env.get("JUPYTERHUB_SERVICE_PREFIX");
}
function isInteractiveTerminal() {
  return Deno.stderr.isTerminal();
}
function isInteractiveSession() {
  return isRStudio() || isInteractiveTerminal() || isVSCodeOutputChannel();
}
function nullDevice() {
  return isWindows4 ? "NUL" : "/dev/null";
}

// core/esbuild.ts
async function esbuildAnalyze(input, workingDir, tempContext2) {
  let mustCleanup = false;
  if (!tempContext2) {
    tempContext2 = createTempContext();
    mustCleanup = true;
  }
  try {
    const tempName = tempContext2.createFile({ suffix: ".json" });
    await esbuildCommand(
      [
        "--analyze=verbose",
        `--metafile=${tempName}`,
        `--outfile=${nullDevice()}`,
        input
      ],
      "",
      workingDir
    );
    const result2 = JSON.parse(
      Deno.readTextFileSync(tempName)
    );
    assert7(Object.entries(result2.outputs).length === 1);
    result2.outputs = {
      "<output>": Object.values(result2.outputs)[0]
    };
    return result2;
  } finally {
    if (mustCleanup) {
      tempContext2.cleanup();
    }
  }
}
async function esbuildCompile(input, workingDir, args, format14) {
  format14 = format14 ?? "esm";
  const fullArgs = [
    "--bundle",
    `--format=${format14}`,
    ...args || []
  ];
  return await esbuildCommand(fullArgs, input, workingDir);
}
async function esbuildCommand(args, input, workingDir) {
  const cmd = Deno.env.get("QUARTO_ESBUILD") || architectureToolsPath("esbuild");
  const result2 = await execProcess(
    {
      cmd,
      args,
      cwd: workingDir,
      stdout: "piped",
      stderr: "piped"
    },
    input
  );
  if (result2.success) {
    return result2.stdout;
  } else {
    console.error(result2.stderr);
    throw new Error("esbuild command failed");
  }
}

// execute/ojs/extract-resources.ts
init_break_quarto_md();

// https://cdn.skypack.dev/-/acorn-walk@v8.2.0-HeuD5jaELKj6UHxcpfDe/dist=es2019,mode=imports/optimized/acorn-walk.js
function simple2(node, visitors, baseVisitor, state2, override) {
  if (!baseVisitor) {
    baseVisitor = base2;
  }
  (function c6(node2, st, override2) {
    var type4 = override2 || node2.type, found = visitors[type4];
    baseVisitor[type4](node2, st, c6);
    if (found) {
      found(node2, st);
    }
  })(node, state2, override);
}
function make2(funcs, baseVisitor) {
  var visitor = Object.create(baseVisitor || base2);
  for (var type4 in funcs) {
    visitor[type4] = funcs[type4];
  }
  return visitor;
}
function skipThrough2(node, st, c6) {
  c6(node, st);
}
function ignore2(_node, _st, _c) {
}
var base2 = {};
base2.Program = base2.BlockStatement = base2.StaticBlock = function(node, st, c6) {
  for (var i6 = 0, list = node.body; i6 < list.length; i6 += 1) {
    var stmt = list[i6];
    c6(stmt, st, "Statement");
  }
};
base2.Statement = skipThrough2;
base2.EmptyStatement = ignore2;
base2.ExpressionStatement = base2.ParenthesizedExpression = base2.ChainExpression = function(node, st, c6) {
  return c6(node.expression, st, "Expression");
};
base2.IfStatement = function(node, st, c6) {
  c6(node.test, st, "Expression");
  c6(node.consequent, st, "Statement");
  if (node.alternate) {
    c6(node.alternate, st, "Statement");
  }
};
base2.LabeledStatement = function(node, st, c6) {
  return c6(node.body, st, "Statement");
};
base2.BreakStatement = base2.ContinueStatement = ignore2;
base2.WithStatement = function(node, st, c6) {
  c6(node.object, st, "Expression");
  c6(node.body, st, "Statement");
};
base2.SwitchStatement = function(node, st, c6) {
  c6(node.discriminant, st, "Expression");
  for (var i$13 = 0, list$1 = node.cases; i$13 < list$1.length; i$13 += 1) {
    var cs = list$1[i$13];
    if (cs.test) {
      c6(cs.test, st, "Expression");
    }
    for (var i6 = 0, list = cs.consequent; i6 < list.length; i6 += 1) {
      var cons = list[i6];
      c6(cons, st, "Statement");
    }
  }
};
base2.SwitchCase = function(node, st, c6) {
  if (node.test) {
    c6(node.test, st, "Expression");
  }
  for (var i6 = 0, list = node.consequent; i6 < list.length; i6 += 1) {
    var cons = list[i6];
    c6(cons, st, "Statement");
  }
};
base2.ReturnStatement = base2.YieldExpression = base2.AwaitExpression = function(node, st, c6) {
  if (node.argument) {
    c6(node.argument, st, "Expression");
  }
};
base2.ThrowStatement = base2.SpreadElement = function(node, st, c6) {
  return c6(node.argument, st, "Expression");
};
base2.TryStatement = function(node, st, c6) {
  c6(node.block, st, "Statement");
  if (node.handler) {
    c6(node.handler, st);
  }
  if (node.finalizer) {
    c6(node.finalizer, st, "Statement");
  }
};
base2.CatchClause = function(node, st, c6) {
  if (node.param) {
    c6(node.param, st, "Pattern");
  }
  c6(node.body, st, "Statement");
};
base2.WhileStatement = base2.DoWhileStatement = function(node, st, c6) {
  c6(node.test, st, "Expression");
  c6(node.body, st, "Statement");
};
base2.ForStatement = function(node, st, c6) {
  if (node.init) {
    c6(node.init, st, "ForInit");
  }
  if (node.test) {
    c6(node.test, st, "Expression");
  }
  if (node.update) {
    c6(node.update, st, "Expression");
  }
  c6(node.body, st, "Statement");
};
base2.ForInStatement = base2.ForOfStatement = function(node, st, c6) {
  c6(node.left, st, "ForInit");
  c6(node.right, st, "Expression");
  c6(node.body, st, "Statement");
};
base2.ForInit = function(node, st, c6) {
  if (node.type === "VariableDeclaration") {
    c6(node, st);
  } else {
    c6(node, st, "Expression");
  }
};
base2.DebuggerStatement = ignore2;
base2.FunctionDeclaration = function(node, st, c6) {
  return c6(node, st, "Function");
};
base2.VariableDeclaration = function(node, st, c6) {
  for (var i6 = 0, list = node.declarations; i6 < list.length; i6 += 1) {
    var decl = list[i6];
    c6(decl, st);
  }
};
base2.VariableDeclarator = function(node, st, c6) {
  c6(node.id, st, "Pattern");
  if (node.init) {
    c6(node.init, st, "Expression");
  }
};
base2.Function = function(node, st, c6) {
  if (node.id) {
    c6(node.id, st, "Pattern");
  }
  for (var i6 = 0, list = node.params; i6 < list.length; i6 += 1) {
    var param = list[i6];
    c6(param, st, "Pattern");
  }
  c6(node.body, st, node.expression ? "Expression" : "Statement");
};
base2.Pattern = function(node, st, c6) {
  if (node.type === "Identifier") {
    c6(node, st, "VariablePattern");
  } else if (node.type === "MemberExpression") {
    c6(node, st, "MemberPattern");
  } else {
    c6(node, st);
  }
};
base2.VariablePattern = ignore2;
base2.MemberPattern = skipThrough2;
base2.RestElement = function(node, st, c6) {
  return c6(node.argument, st, "Pattern");
};
base2.ArrayPattern = function(node, st, c6) {
  for (var i6 = 0, list = node.elements; i6 < list.length; i6 += 1) {
    var elt = list[i6];
    if (elt) {
      c6(elt, st, "Pattern");
    }
  }
};
base2.ObjectPattern = function(node, st, c6) {
  for (var i6 = 0, list = node.properties; i6 < list.length; i6 += 1) {
    var prop = list[i6];
    if (prop.type === "Property") {
      if (prop.computed) {
        c6(prop.key, st, "Expression");
      }
      c6(prop.value, st, "Pattern");
    } else if (prop.type === "RestElement") {
      c6(prop.argument, st, "Pattern");
    }
  }
};
base2.Expression = skipThrough2;
base2.ThisExpression = base2.Super = base2.MetaProperty = ignore2;
base2.ArrayExpression = function(node, st, c6) {
  for (var i6 = 0, list = node.elements; i6 < list.length; i6 += 1) {
    var elt = list[i6];
    if (elt) {
      c6(elt, st, "Expression");
    }
  }
};
base2.ObjectExpression = function(node, st, c6) {
  for (var i6 = 0, list = node.properties; i6 < list.length; i6 += 1) {
    var prop = list[i6];
    c6(prop, st);
  }
};
base2.FunctionExpression = base2.ArrowFunctionExpression = base2.FunctionDeclaration;
base2.SequenceExpression = function(node, st, c6) {
  for (var i6 = 0, list = node.expressions; i6 < list.length; i6 += 1) {
    var expr = list[i6];
    c6(expr, st, "Expression");
  }
};
base2.TemplateLiteral = function(node, st, c6) {
  for (var i6 = 0, list = node.quasis; i6 < list.length; i6 += 1) {
    var quasi = list[i6];
    c6(quasi, st);
  }
  for (var i$13 = 0, list$1 = node.expressions; i$13 < list$1.length; i$13 += 1) {
    var expr = list$1[i$13];
    c6(expr, st, "Expression");
  }
};
base2.TemplateElement = ignore2;
base2.UnaryExpression = base2.UpdateExpression = function(node, st, c6) {
  c6(node.argument, st, "Expression");
};
base2.BinaryExpression = base2.LogicalExpression = function(node, st, c6) {
  c6(node.left, st, "Expression");
  c6(node.right, st, "Expression");
};
base2.AssignmentExpression = base2.AssignmentPattern = function(node, st, c6) {
  c6(node.left, st, "Pattern");
  c6(node.right, st, "Expression");
};
base2.ConditionalExpression = function(node, st, c6) {
  c6(node.test, st, "Expression");
  c6(node.consequent, st, "Expression");
  c6(node.alternate, st, "Expression");
};
base2.NewExpression = base2.CallExpression = function(node, st, c6) {
  c6(node.callee, st, "Expression");
  if (node.arguments) {
    for (var i6 = 0, list = node.arguments; i6 < list.length; i6 += 1) {
      var arg = list[i6];
      c6(arg, st, "Expression");
    }
  }
};
base2.MemberExpression = function(node, st, c6) {
  c6(node.object, st, "Expression");
  if (node.computed) {
    c6(node.property, st, "Expression");
  }
};
base2.ExportNamedDeclaration = base2.ExportDefaultDeclaration = function(node, st, c6) {
  if (node.declaration) {
    c6(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression");
  }
  if (node.source) {
    c6(node.source, st, "Expression");
  }
};
base2.ExportAllDeclaration = function(node, st, c6) {
  if (node.exported) {
    c6(node.exported, st);
  }
  c6(node.source, st, "Expression");
};
base2.ImportDeclaration = function(node, st, c6) {
  for (var i6 = 0, list = node.specifiers; i6 < list.length; i6 += 1) {
    var spec = list[i6];
    c6(spec, st);
  }
  c6(node.source, st, "Expression");
};
base2.ImportExpression = function(node, st, c6) {
  c6(node.source, st, "Expression");
};
base2.ImportSpecifier = base2.ImportDefaultSpecifier = base2.ImportNamespaceSpecifier = base2.Identifier = base2.PrivateIdentifier = base2.Literal = ignore2;
base2.TaggedTemplateExpression = function(node, st, c6) {
  c6(node.tag, st, "Expression");
  c6(node.quasi, st, "Expression");
};
base2.ClassDeclaration = base2.ClassExpression = function(node, st, c6) {
  return c6(node, st, "Class");
};
base2.Class = function(node, st, c6) {
  if (node.id) {
    c6(node.id, st, "Pattern");
  }
  if (node.superClass) {
    c6(node.superClass, st, "Expression");
  }
  c6(node.body, st);
};
base2.ClassBody = function(node, st, c6) {
  for (var i6 = 0, list = node.body; i6 < list.length; i6 += 1) {
    var elt = list[i6];
    c6(elt, st);
  }
};
base2.MethodDefinition = base2.PropertyDefinition = base2.Property = function(node, st, c6) {
  if (node.computed) {
    c6(node.key, st, "Expression");
  }
  if (node.value) {
    c6(node.value, st, "Expression");
  }
};

// execute/ojs/ojs-tools.ts
init_log();
init_error2();
var walkerBase = make2({
  Import() {
  },
  // deno-lint-ignore no-explicit-any
  ViewExpression(node, st, c6) {
    c6(node.id, st, "Identifier");
  },
  // deno-lint-ignore no-explicit-any
  MutableExpression(node, st, c6) {
    c6(node.id, st, "Identifier");
  },
  // deno-lint-ignore no-explicit-any
  Cell(node, st, c6) {
    c6(node.body, st);
  },
  // deno-lint-ignore no-explicit-any
  Program(node, st, c6) {
    if (node.body) {
      for (let i6 = 0, list = node.body; i6 < list.length; i6 += 1) {
        const stmt = list[i6];
        c6(stmt, st, "Statement");
      }
    } else if (node.cells) {
      for (let i6 = 0, list = node.cells; i6 < list.length; i6 += 1) {
        const stmt = list[i6];
        c6(stmt, st);
      }
    } else {
      error("I don't know how to walk this node", node);
      throw new InternalError(
        `OJS traversal: I don't know how to walk this node: ${node}`
      );
    }
  }
});
function ojsSimpleWalker(parse24, visitor) {
  simple2(parse24, visitor, walkerBase);
}

// execute/ojs/extract-resources.ts
init_mapped_text2();
init_lifetimes();
init_resources2();
init_log();
init_colors3();
init_text();
init_error2();
init_constants6();
init_fs();
function resolveResourceFilename(resource, rootDir) {
  if (resource.pathType == "relative") {
    const result2 = resolve4(
      rootDir,
      dirname4(resource.referent),
      resource.filename
    );
    return result2;
  } else if (resource.pathType === "root-relative") {
    const result2 = resolve4(
      rootDir,
      dirname4(resource.referent),
      `.${resource.filename}`
    );
    return result2;
  } else {
    throw new Error(`Unrecognized pathType ${resource.pathType}`);
  }
}
function uniqueResources(resourceList) {
  const result2 = [];
  const uniqResources = /* @__PURE__ */ new Map();
  for (const resource of resourceList) {
    if (!uniqResources.has(resource.filename)) {
      result2.push(resource);
      uniqResources.set(resource.filename, resource);
    }
  }
  return result2;
}
var resolveES6Path = (path3, originDir, projectRoot) => {
  if (path3.startsWith("/")) {
    if (projectRoot === void 0) {
      return {
        pathType: "root-relative",
        resolvedImportPath: resolve4(originDir, `.${path3}`)
      };
    } else {
      return {
        pathType: "root-relative",
        resolvedImportPath: resolve4(projectRoot, `.${path3}`)
      };
    }
  } else {
    return {
      pathType: "relative",
      resolvedImportPath: resolve4(originDir, path3)
    };
  }
};
var localImports = (parse24) => {
  const result2 = [];
  ojsSimpleWalker(parse24, {
    // deno-lint-ignore no-explicit-any
    ExportNamedDeclaration(node) {
      if (node.source?.value) {
        const source2 = node.source?.value;
        if (source2.startsWith("/") || source2.startsWith(".")) {
          result2.push(source2);
        }
      }
    },
    // deno-lint-ignore no-explicit-any
    ImportDeclaration(node) {
      const source2 = node.source?.value;
      if (source2.startsWith("/") || source2.startsWith(".")) {
        result2.push(source2);
      }
    }
  });
  return result2;
};
async function directDependencies(source2, fileDir, language, projectRoot) {
  let ast;
  if (language === "js") {
    try {
      ast = parse32(source2.value, {
        ecmaVersion: "2020",
        sourceType: "module"
      });
    } catch (e5) {
      if (!(e5 instanceof SyntaxError)) {
        throw e5;
      }
      return [];
    }
  } else if (language === "ojs") {
    try {
      ast = parseModule(source2.value);
    } catch (e5) {
      if (!(e5 instanceof SyntaxError)) throw e5;
      return [];
    }
  } else {
    const ojsCellsSrc = (await breakQuartoMd(source2)).cells.filter(
      (cell) => cell.cell_type !== "markdown" && cell.cell_type !== "raw" && cell.cell_type?.language === "ojs"
    ).flatMap((v4) => v4.source);
    return await directDependencies(
      mappedConcat(ojsCellsSrc),
      fileDir,
      "ojs",
      projectRoot
    );
  }
  return localImports(ast).map((importPath) => {
    const { resolvedImportPath, pathType } = resolveES6Path(
      importPath,
      fileDir,
      projectRoot
    );
    return {
      resolvedImportPath,
      pathType,
      importPath
    };
  });
}
async function extractResolvedResourceFilenamesFromQmd(markdown, mdDir, projectRoot) {
  const pageResources = [];
  for (const cell of (await breakQuartoMd(markdown)).cells) {
    if (cell.cell_type !== "markdown" && cell.cell_type !== "raw" && cell.cell_type?.language === "ojs") {
      pageResources.push(
        ...await extractResourceDescriptionsFromOJSChunk(
          cell.source,
          mdDir,
          projectRoot
        )
      );
    }
  }
  const result2 = /* @__PURE__ */ new Set();
  for (const resource of uniqueResources(pageResources)) {
    result2.add(resolveResourceFilename(resource, Deno.cwd()));
  }
  return Array.from(result2);
}
var literalFileAttachments = (parse24) => {
  const result2 = [];
  ojsSimpleWalker(parse24, {
    // deno-lint-ignore no-explicit-any
    CallExpression(node) {
      if (node.callee?.type !== "Identifier") {
        return;
      }
      if (node.callee?.name !== "FileAttachment") {
        return;
      }
      const args = node.arguments || [];
      if (args.length < 1) {
        return;
      }
      if (args[0]?.type !== "Literal") {
        return;
      }
      result2.push(args[0]?.value);
    }
  });
  return result2;
};
async function resolveImport(file, referent, projectRoot, mdDir, visited) {
  visited = visited ?? /* @__PURE__ */ new Set();
  let source2;
  const createdResources = [];
  if (!file.endsWith(".ts") && !file.endsWith(".tsx")) {
    try {
      source2 = Deno.readTextFileSync(file);
    } catch (_e) {
      error(`OJS dependency ${file} (from ${referent}) not found.`);
      throw new Error();
    }
    return {
      source: source2,
      createdResources
    };
  }
  projectRoot = projectRoot ?? dirname4(referent);
  const deno = Deno.execPath();
  const p5 = new Deno.Command(deno, {
    args: [
      "check",
      file,
      "-c",
      resourcePath("conf/deno-ts-compile.jsonc"),
      `--importmap=${resourcePath("conf/jsx-import-map.json")}`
    ],
    stderr: "piped"
  });
  const output = await p5.output();
  const stderr2 = output.stderr;
  if (!output.success) {
    error("Compilation of typescript dependencies in ojs cell failed.");
    let errStr = new TextDecoder().decode(stderr2);
    const errorLines = lines(stripColor2(errStr));
    const denoBugErrorLines = errorLines.map((l6, i6) => ({ text: l6, line: i6 })).filter(
      (x3) => x3.text.trim().indexOf(
        "TS7026 [ERROR]: JSX element implicitly has type 'any' because no interface 'JSX.IntrinsicElements' exists."
      ) !== -1
    );
    console.log(errorLines);
    const errorCountRe = /^Found (\d+) errors.$/;
    const errorCount = Number(
      (errorLines.filter((x3) => x3.trim().match(errorCountRe))[0] ?? "Found 1 errors.").match(errorCountRe)[1]
    );
    if (denoBugErrorLines.length > 0) {
      const m4 = errorLines[denoBugErrorLines[0].line + 3].trim().match(
        /^.*(file:.+):\d+:\d+$/
      );
      if (m4 === null) {
        console.log(errStr);
        throw new InternalError("Internal error in deno ojs cell compilation.");
      }
      const badFile = fromFileUrl4(m4[1]);
      const badContents = Deno.readTextFileSync(badFile);
      if (!badContents.startsWith("/** @jsxImportSource quarto-tsx */")) {
        console.log(`
File ${red3(badFile)} must start with

${yellow3("/** @jsxImportSource quarto-tsx */")}

We apologize for the inconvenience; this is a temporary workaround for an upstream bug.
`);
      }
      if (denoBugErrorLines.length !== errorCount) {
        console.log(`Other compilation errors follow below.
`);
        let colorErrorLines = lines(errStr);
        for (let i6 = denoBugErrorLines.length - 1; i6 >= 0; i6--) {
          colorErrorLines.splice(denoBugErrorLines[i6].line, 5);
        }
        colorErrorLines = colorErrorLines.map((line) => {
          if (line.match(errorCountRe)) {
            return `Found ${errorCount - denoBugErrorLines.length} errors.`;
          }
          return line;
        });
        errStr = colorErrorLines.slice(1).join("\n");
      }
      throw new Error();
    }
    console.log(errStr);
    throw new Error();
  }
  const localFile = file.replace(/[.]ts$/, ".js").replace(/[.]tsx$/, ".js");
  const fileDir = dirname4(localFile);
  if (!fileDir.startsWith(resolve4(projectRoot))) {
    error(
      `ERROR: File ${file} has typescript import dependency ${localFile},
outside of main folder ${resolve4(projectRoot)}. 
quarto will only generate javascript files in ${resolve4(projectRoot)} or subfolders.`
    );
    throw new Error();
  }
  const jsSource = await esbuildCommand(
    [
      file,
      "--format=esm",
      "--sourcemap=inline",
      "--jsx-factory=window._ojs.jsx.createElement"
    ],
    "",
    fileDir
  );
  if (typeof jsSource === "undefined") {
    throw new InternalError(
      `esbuild compilation of file ${file} failed`
    );
  }
  let fixedSource = jsSource;
  let ast = void 0;
  try {
    ast = parse32(jsSource, {
      ecmaVersion: "latest",
      sourceType: "module"
    });
  } catch (e5) {
    console.error(jsSource);
    console.error("Error parsing compiled typescript file.");
    throw e5;
  }
  const recursionList = [];
  const patchDeclaration = (node) => {
    if (node.source?.value.endsWith(".ts") || node.source?.value.endsWith(".tsx")) {
      recursionList.push(node.source.value);
      const rawReplacement = JSON.stringify(
        node.source.value.replace(/[.]ts$/, ".js").replace(/[.]tsx$/, ".js")
      );
      fixedSource = fixedSource.substring(0, node.source.start) + rawReplacement + fixedSource.slice(node.source.end);
    }
  };
  ojsSimpleWalker(ast, {
    ExportNamedDeclaration: patchDeclaration,
    ImportDeclaration: patchDeclaration
  });
  for (const tsImport of recursionList) {
    if (!visited.has(tsImport)) {
      visited.add(tsImport);
      const { createdResources: recursionCreatedResources } = await resolveImport(
        resolve4(dirname4(file), tsImport),
        file,
        projectRoot,
        mdDir,
        visited
      );
      createdResources.push(...recursionCreatedResources);
    }
  }
  const transformedSource = fixedSource;
  Deno.writeTextFileSync(localFile, transformedSource);
  createdResources.push({
    pathType: "relative",
    resourceType: "import",
    referent,
    filename: resolve4(dirname4(referent), localFile),
    importPath: `./${relative4(resolve4(mdDir), localFile)}`
  });
  source2 = Deno.readTextFileSync(localFile);
  return { source: source2, createdResources };
}
async function extractResourceDescriptionsFromOJSChunk(ojsSource, mdDir, projectRoot) {
  let result2 = [];
  const handled = /* @__PURE__ */ new Set();
  const imports2 = /* @__PURE__ */ new Map();
  const rootReferent = `${mdDir}/<<root>>.qmd`;
  for (const { resolvedImportPath, pathType, importPath } of await directDependencies(
    ojsSource,
    mdDir,
    "ojs",
    projectRoot
  )) {
    if (!imports2.has(resolvedImportPath)) {
      const v4 = {
        filename: resolvedImportPath,
        referent: rootReferent,
        pathType,
        importPath,
        resourceType: "import"
      };
      result2.push(v4);
      imports2.set(resolvedImportPath, v4);
    }
  }
  while (imports2.size > 0) {
    const [thisResolvedImportPath, importResource] = imports2.entries().next().value;
    imports2.delete(thisResolvedImportPath);
    if (handled.has(thisResolvedImportPath)) {
      continue;
    }
    handled.add(thisResolvedImportPath);
    const resolvedImport = await resolveImport(
      thisResolvedImportPath,
      importResource.referent,
      projectRoot,
      mdDir
    );
    if (resolvedImport === void 0) {
      console.error(
        `WARNING: While following dependencies, could not resolve reference:`
      );
      console.error(`  Reference: ${importResource.importPath}`);
      console.error(`  In file: ${importResource.referent}`);
      continue;
    }
    const source2 = resolvedImport.source;
    result2.push(...resolvedImport.createdResources);
    if (projectRoot) {
      getNamedLifetime(kRenderServicesLifetime, true).attach({
        cleanup() {
          for (const res of resolvedImport.createdResources) {
            try {
              safeRemoveSync(res.filename);
            } catch (e5) {
              if (!(e5 instanceof Error)) throw e5;
              if (e5.name !== "NotFound") {
                throw e5;
              }
            }
          }
          return;
        }
      });
    }
    let language;
    if (thisResolvedImportPath.endsWith(".js") || thisResolvedImportPath.endsWith(".ts") || thisResolvedImportPath.endsWith(".tsx")) {
      language = "js";
    } else if (thisResolvedImportPath.endsWith(".ojs")) {
      language = "ojs";
    } else if (thisResolvedImportPath.endsWith(".qmd")) {
      language = "qmd";
    } else {
      throw new Error(
        `Unknown language in file "${thisResolvedImportPath}"`
      );
    }
    for (const { resolvedImportPath, pathType, importPath } of await directDependencies(
      asMappedString(source2),
      dirname4(thisResolvedImportPath),
      language,
      projectRoot
    )) {
      if (!imports2.has(resolvedImportPath)) {
        const v4 = {
          filename: resolvedImportPath,
          referent: thisResolvedImportPath,
          pathType,
          importPath,
          resourceType: "import"
        };
        result2.push(v4);
        imports2.set(resolvedImportPath, v4);
      }
    }
  }
  const fileAttachments = [];
  for (const importFile of result2) {
    if (importFile.filename.endsWith(".ojs")) {
      try {
        const ast = parseModule(Deno.readTextFileSync(importFile.filename));
        for (const attachment of literalFileAttachments(ast)) {
          fileAttachments.push({
            filename: attachment,
            referent: importFile.filename
          });
        }
      } catch (e5) {
        if (!(e5 instanceof SyntaxError)) {
          throw e5;
        }
      }
    }
  }
  try {
    const ast = parseModule(ojsSource.value);
    for (const attachment of literalFileAttachments(ast)) {
      fileAttachments.push({
        filename: attachment,
        referent: rootReferent
      });
    }
  } catch (e5) {
    if (!(e5 instanceof SyntaxError)) {
      throw e5;
    }
  }
  result2 = result2.filter(
    (description) => !description.filename.endsWith(".qmd") && !description.filename.endsWith(".ts") && !description.filename.endsWith(".tsx")
  );
  result2 = result2.map((description) => {
    const { referent, resourceType, importPath, pathType } = description;
    let relName = relative4(mdDir, description.filename);
    if (!relName.startsWith(".")) {
      relName = `./${relName}`;
    }
    return {
      filename: relName,
      referent,
      importPath,
      pathType,
      resourceType
    };
  });
  result2.push(...fileAttachments.map(({ filename, referent }) => {
    let pathType;
    if (filename.startsWith("/")) {
      pathType = "root-relative";
    } else {
      pathType = "relative";
    }
    return {
      referent,
      filename,
      pathType,
      resourceType: "FileAttachment"
    };
  }));
  return result2;
}
async function makeSelfContainedResources(resourceList, wd) {
  const asDataURL = (content, mimeType) => {
    const b64Src = encodeBase64(content);
    return `data:${mimeType};base64,${b64Src}`;
  };
  const uniqResources = uniqueResources(resourceList);
  const jsFiles = uniqResources.filter(
    (r5) => r5.resourceType === "import" && r5.filename.endsWith(".js")
  );
  const ojsFiles = uniqResources.filter(
    (r5) => r5.resourceType === "import" && r5.filename.endsWith("ojs")
  );
  const attachments = uniqResources.filter((r5) => r5.resourceType !== "import");
  const jsModuleResolves = [];
  if (jsFiles.length > 0) {
    const bundleInput = jsFiles.map((r5) => `export * from "${r5.filename}";`).join("\n");
    const es6BundledModule = await esbuildCompile(
      bundleInput,
      wd,
      ["--target=es2018"]
    );
    const jsModule = asDataURL(
      es6BundledModule,
      "application/javascript"
    );
    jsModuleResolves.push(...jsFiles.map((f5) => [f5.importPath, jsModule]));
  }
  const result2 = [
    ...jsModuleResolves,
    ...ojsFiles.map(
      (f5) => [
        // FIXME is this one also wrong?
        f5.importPath,
        asDataURL(
          Deno.readTextFileSync(f5.filename),
          "application/ojs-javascript"
        )
      ]
    ),
    ...attachments.map(
      (f5) => {
        const resolvedFileName = resolveResourceFilename(f5, Deno.cwd());
        const mimeType = lookup2(resolvedFileName) || "application/octet-stream";
        return [
          f5.filename,
          asDataURL(
            Deno.readFileSync(resolvedFileName).buffer,
            mimeType
          )
        ];
      }
    )
  ];
  return result2;
}

// command/render/resources.ts
init_mapped_text2();
function resourcesFromMetadata(resourcesMetadata) {
  const resources = [];
  if (resourcesMetadata) {
    if (Array.isArray(resourcesMetadata)) {
      for (const file of resourcesMetadata) {
        resources.push(String(file));
      }
    } else {
      resources.push(String(resourcesMetadata));
    }
  }
  return resources;
}
async function resolveFileResources(rootDir, fileDir, excludeDirs, markdown, globs, skipOjsDiscovery) {
  const ignore3 = engineIgnoreGlobs().concat(kQuartoScratch + "/").concat(["**/.*", "**/.*/**"]).concat(
    ...excludeDirs
  );
  const resources = resolvePathGlobs(fileDir, globs, ignore3, {
    mode: "always",
    explicitSubfolderSearch: true
  });
  if (markdown.length > 0 && !skipOjsDiscovery) {
    resources.include.push(
      ...await extractResolvedResourceFilenamesFromQmd(
        asMappedString(markdown),
        fileDir,
        rootDir
      )
    );
  }
  return resources;
}
function resourceFilesFromRenderedFile(baseDir, excludeDirs, renderedFile, partitioned) {
  return resourceFilesFromFile(
    baseDir,
    excludeDirs,
    renderedFile.file,
    renderedFile.resourceFiles,
    renderedFile.selfContained,
    renderedFile.supporting,
    partitioned,
    true
  );
}
async function resourceFilesFromFile(baseDir, excludeDirs, file, resources, selfContained, supporting, partitioned, skipOjsDiscovery) {
  const resourceDir = join4(baseDir, dirname4(file));
  const markdown = partitioned ? partitioned.markdown : "";
  const globs = resources.globs;
  const fileResourceFiles = await resolveFileResources(
    baseDir,
    resourceDir,
    excludeDirs,
    markdown,
    globs,
    skipOjsDiscovery
  );
  if (!selfContained) {
    const resultFiles = resources.files.map((file2) => join4(resourceDir, file2)).filter(safeExistsSync).map(normalizePath);
    fileResourceFiles.include.push(...resultFiles);
  }
  const resourceFiles = fileResourceFiles.include.filter(
    (file2) => {
      if (fileResourceFiles.exclude.includes(file2)) {
        return false;
      } else if (supporting && supporting.some((support) => file2.startsWith(join4(baseDir, support)))) {
        return false;
      } else {
        return true;
      }
    }
  );
  return uniq(resourceFiles);
}

// command/render/pandoc-html.ts
init_path();
init_lodash();
init_types5();
init_css();
init_sass();

// format/html/format-html-constants.ts
var kQuartoHtmlDependency = "quarto-html";
var kNotebookViewStyleNotebook = "notebook";

// command/render/pandoc-html.ts
init_format5();

// core/pandoc/css.ts
function generateCssKeyValues(textValues) {
  const lines2 = [];
  Object.keys(textValues).forEach((textAttr) => {
    switch (textAttr) {
      case "text-color":
        lines2.push(
          `color: ${textValues[textAttr]};`
        );
        break;
      case "background-color":
        lines2.push(
          `background-color: ${textValues[textAttr]};`
        );
        break;
      case "bold":
        if (textValues[textAttr]) {
          lines2.push("font-weight: bold;");
        }
        break;
      case "italic":
        if (textValues[textAttr]) {
          lines2.push("font-style: italic;");
        } else {
          lines2.push("font-style: inherit;");
        }
        break;
      case "underline":
        if (textValues[textAttr]) {
          lines2.push("text-decoration: underline;");
        }
        break;
    }
  });
  return lines2;
}
function cssHasDarkModeSentinel(css) {
  return !!css.match(/\/\*! dark \*\//g);
}

// command/render/pandoc-html.ts
init_format_html_shared();
init_types5();
init_hash2();
init_error2();
init_asserts();
init_fs();
init_safe_clone_deep();
async function resolveSassBundles(inputDir, extras, format14, project) {
  extras = safeCloneDeep(extras);
  const mergedBundles = {};
  const group = (bundles, groupedBundles) => {
    bundles.forEach((bundle2) => {
      if (!groupedBundles[bundle2.dependency]) {
        groupedBundles[bundle2.dependency] = [];
      }
      groupedBundles[bundle2.dependency].push(bundle2);
    });
  };
  if (extras?.["html"]?.[kSassBundles]) {
    group(extras["html"][kSassBundles], mergedBundles);
  }
  let hasDarkStyles = false;
  let defaultStyle = void 0;
  for (const dependency of Object.keys(mergedBundles)) {
    const bundlesWithBrand = mergedBundles[dependency];
    const maybeBrandBundle = bundlesWithBrand.find(
      (bundle2) => bundle2.key === "brand"
    );
    assert7(
      !maybeBrandBundle || !maybeBrandBundle.user?.find((v4) => v4 === "brand") && !maybeBrandBundle.dark?.user?.find((v4) => v4 === "brand")
    );
    const foundBrand = { light: false, dark: false };
    const bundles = bundlesWithBrand.filter(
      (bundle2) => bundle2.key !== "brand"
    ).map((bundle2) => {
      const userBrand = bundle2.user?.findIndex((layer) => layer === "brand");
      let cloned = false;
      if (userBrand && userBrand !== -1) {
        bundle2 = safeCloneDeep(bundle2);
        cloned = true;
        bundle2.user.splice(userBrand, 1, ...maybeBrandBundle?.user || []);
        foundBrand.light = true;
      }
      const darkBrand = bundle2.dark?.user?.findIndex(
        (layer) => layer === "brand"
      );
      if (darkBrand && darkBrand !== -1) {
        if (!cloned) {
          bundle2 = safeCloneDeep(bundle2);
        }
        bundle2.dark.user.splice(
          darkBrand,
          1,
          ...maybeBrandBundle?.dark?.user || []
        );
        foundBrand.dark = true;
      }
      return bundle2;
    });
    if (maybeBrandBundle && (!foundBrand.light || !foundBrand.dark)) {
      bundles.unshift({
        dependency,
        key: "brand",
        user: !foundBrand.light && maybeBrandBundle.user || [],
        dark: !foundBrand.dark && maybeBrandBundle.dark?.user && {
          user: maybeBrandBundle.dark.user,
          default: maybeBrandBundle.dark.default
        } || void 0
      });
    }
    const hasDark = bundles.some((bundle2) => bundle2.dark !== void 0);
    defaultStyle = bundles.some(
      (bundle2) => bundle2.dark !== void 0 && bundle2.dark.default
    ) ? "dark" : "light";
    let targets = [{
      name: `${dependency}.min.css`,
      bundles,
      attribs: {
        "append-hash": "true"
      }
    }];
    if (hasDark) {
      targets[0].attribs = {
        ...targets[0].attribs,
        ...attribForThemeStyle("light")
      };
      const darkBundles = bundles.map((bundle2) => {
        bundle2 = safeCloneDeep(bundle2);
        bundle2.user = bundle2.dark?.user || bundle2.user;
        bundle2.quarto = bundle2.dark?.quarto || bundle2.quarto;
        bundle2.framework = bundle2.dark?.framework || bundle2.framework;
        bundle2.key = bundle2.key + "-dark";
        return bundle2;
      });
      const darkTarget = {
        name: `${dependency}-dark.min.css`,
        bundles: darkBundles,
        attribs: {
          "append-hash": "true",
          ...attribForThemeStyle("dark")
        }
      };
      if (defaultStyle === "dark") {
        targets.push(darkTarget);
      } else {
        const lightTargetExtra = {
          ...targets[0],
          attribs: {
            ...targets[0].attribs,
            class: "quarto-color-scheme-extra"
          }
        };
        targets = [
          targets[0],
          darkTarget,
          lightTargetExtra
        ];
      }
      hasDarkStyles = true;
    }
    for (const target of targets) {
      let cssPath;
      cssPath = await compileSass(target.bundles, project);
      cleanSourceMappingUrl(cssPath);
      const cssResult = await processCssIntoExtras(cssPath, extras, project);
      cssPath = cssResult.path;
      if (!cssPath) continue;
      if (Deno.readTextFileSync(cssPath).length === 0) {
        continue;
      }
      for (const bundle2 of target.bundles) {
        if (bundle2.attribs) {
          for (const key of Object.keys(bundle2.attribs)) {
            if (target.attribs[key] === void 0) {
              target.attribs[key] = bundle2.attribs[key];
            }
          }
        }
      }
      target.attribs["data-mode"] = cssResult.dark ? "dark" : "light";
      const css = Deno.readTextFileSync(cssPath);
      const toDependencies = (paths) => {
        return paths.map((path3) => {
          return {
            name: path3,
            path: project ? join4(project.dir, path3) : path3,
            attribs: target.attribs
          };
        });
      };
      const resources = toDependencies(cssResources(css));
      const imports2 = toDependencies(cssImports(css));
      const extraDeps = extras.html?.[kDependencies];
      if (extraDeps) {
        const existingDependency = extraDeps.find(
          (extraDep) => extraDep.name === dependency
        );
        let targetName = target.name;
        if (target.attribs["append-hash"] === "true") {
          const hashFragment = `-${await md5HashBytes(
            Deno.readFileSync(cssPath)
          )}`;
          let extension = "";
          if (target.name.endsWith(".min.css")) {
            extension = ".min.css";
          } else if (target.name.endsWith(".css")) {
            extension = ".css";
          } else {
            throw new InternalError("Unexpected target name: " + target.name);
          }
          targetName = targetName.slice(0, target.name.length - extension.length) + hashFragment + extension;
        } else {
          targetName = target.name;
        }
        if (existingDependency) {
          if (!existingDependency.stylesheets) {
            existingDependency.stylesheets = [];
          }
          existingDependency.stylesheets.push({
            name: targetName,
            path: cssPath,
            attribs: target.attribs
          });
          existingDependency.stylesheets.push(...imports2);
          existingDependency.resources?.push(...resources);
        } else {
          extraDeps.push({
            name: dependency,
            stylesheets: [{
              name: targetName,
              path: cssPath,
              attribs: target.attribs
            }, ...imports2],
            resources
          });
        }
      }
    }
  }
  extras = await resolveQuartoSyntaxHighlighting(
    inputDir,
    extras,
    format14,
    project,
    hasDarkStyles ? "light" : "default",
    defaultStyle
  );
  if (hasDarkStyles) {
    const lightDep = extras.html?.[kDependencies]?.find(
      (extraDep) => extraDep.name === kQuartoHtmlDependency
    );
    const lightEntry = lightDep?.stylesheets && lightDep.stylesheets[lightDep.stylesheets.length - 1];
    extras = await resolveQuartoSyntaxHighlighting(
      inputDir,
      extras,
      format14,
      project,
      "dark",
      defaultStyle
    );
    if (defaultStyle === "light" && lightEntry) {
      const dep2 = extras.html?.[kDependencies]?.find(
        (extraDep) => extraDep.name === kQuartoHtmlDependency
      );
      assert7(dep2?.stylesheets);
      dep2.stylesheets.push({
        ...lightEntry,
        attribs: {
          ...lightEntry.attribs,
          class: "quarto-color-scheme-extra"
        }
      });
    }
  }
  if (isHtmlOutput(format14.pandoc, true)) {
    setTextHighlightStyle("none", extras);
  }
  return extras;
}
async function resolveQuartoSyntaxHighlighting(inputDir, extras, format14, project, style, defaultStyle) {
  const minimal = format14.metadata[kMinimal] === true;
  if (minimal) {
    return extras;
  }
  extras = safeCloneDeep(extras);
  const mediaAttr = attribForThemeStyle(style);
  if (style === "default") {
    if (extras.html?.[kTextHighlightingMode] === "dark") {
      style = "dark";
    }
  }
  mediaAttr.id = "quarto-text-highlighting-styles";
  const cssFileName = `quarto-syntax-highlighting${style === "dark" ? "-dark" : ""}`;
  const themeDescriptor = readHighlightingTheme(inputDir, format14.pandoc, style);
  if (themeDescriptor) {
    const extraVariables = extras.html?.[kQuartoCssVariables] || [];
    for (let i6 = 0; i6 < extraVariables.length; ++i6) {
      let variable = extraVariables[i6].trim();
      if (variable.endsWith("}") && variable.startsWith(":root") && !variable.match(/.*;\s?}$/)) {
        variable = variable.slice(0, -1) + ";}";
        extraVariables[i6] = variable;
      }
    }
    const highlightCss = generateThemeCssVars(themeDescriptor.json);
    if (highlightCss) {
      const rules = [
        highlightCss,
        "",
        "/* other quarto variables */",
        ...extraVariables
      ];
      const textHighlightCssRules = generateThemeCssClasses(
        themeDescriptor.json
      );
      if (textHighlightCssRules) {
        rules.push(...textHighlightCssRules);
      }
      rules.push(".prevent-inlining { content: '</'; }");
      const highlightCssPath = await compileSass(
        [{
          key: cssFileName + ".css",
          quarto: {
            uses: "",
            defaults: "",
            functions: "",
            mixins: "",
            rules: rules.join("\n")
          }
        }],
        project,
        false
      );
      const extraDeps = extras.html?.[kDependencies];
      if (extraDeps) {
        const quartoDependency = extraDeps.find(
          (extraDep) => extraDep.name === kQuartoHtmlDependency
        );
        const existingDependency = quartoDependency;
        if (existingDependency) {
          existingDependency.stylesheets = existingDependency.stylesheets || [];
          const hash = await md5HashBytes(Deno.readFileSync(highlightCssPath));
          existingDependency.stylesheets.push({
            name: cssFileName + `-${hash}.css`,
            path: highlightCssPath,
            attribs: mediaAttr
          });
        }
      }
    }
  }
  return extras;
}
function generateThemeCssVars(themeJson) {
  const textStyles = themeJson["text-styles"];
  if (textStyles) {
    const lines2 = [];
    lines2.push("/* quarto syntax highlight colors */");
    lines2.push(":root {");
    Object.keys(textStyles).forEach((styleName) => {
      const abbr = kAbbrevs[styleName];
      if (abbr) {
        const textValues = textStyles[styleName];
        Object.keys(textValues).forEach((textAttr) => {
          switch (textAttr) {
            case "text-color":
              lines2.push(
                `  --quarto-hl-${abbr}-color: ${textValues[textAttr] || "inherit"};`
              );
              break;
          }
        });
      }
    });
    lines2.push("}");
    return lines2.join("\n");
  }
  return void 0;
}
function generateThemeCssClasses(themeJson) {
  const textStyles = themeJson["text-styles"];
  if (textStyles) {
    const otherLines = [];
    otherLines.push("/* syntax highlight based on Pandoc's rules */");
    const tokenCssByAbbr = {};
    const toCSS = function(abbr, styleName, cssValues) {
      const lines2 = [];
      lines2.push(`/* ${styleName} */`);
      lines2.push(`
code span${abbr !== "" ? `.${abbr}` : ""} {`);
      cssValues.forEach((value) => {
        lines2.push(`  ${value}`);
      });
      lines2.push("}\n");
      tokenCssByAbbr[abbr] = lines2;
    };
    Object.keys(textStyles).forEach((styleName) => {
      const abbr = kAbbrevs[styleName];
      if (abbr !== void 0) {
        const textValues = textStyles[styleName];
        const cssValues = generateCssKeyValues(textValues);
        toCSS(abbr, styleName, cssValues);
        if (abbr == "") {
          [
            "pre > code.sourceCode > span",
            "code.sourceCode > span",
            "div.sourceCode,\ndiv.sourceCode pre.sourceCode"
          ].forEach((selector) => {
            otherLines.push(`
${selector} {`);
            otherLines.push(...cssValues);
            otherLines.push("}\n");
          });
        }
      }
    });
    const sortedTokenCssLines = [];
    Object.keys(tokenCssByAbbr).sort((a5, b3) => {
      if (a5 === "") return -1;
      if (b3 === "") return 1;
      return a5.localeCompare(b3);
    }).forEach((abbr) => {
      sortedTokenCssLines.push(...tokenCssByAbbr[abbr]);
    });
    return otherLines.concat(sortedTokenCssLines);
  }
  return void 0;
}
async function processCssIntoExtras(cssPath, extras, project) {
  const { temp } = project;
  extras.html = extras.html || {};
  const css = Deno.readTextFileSync(cssPath);
  const hasDarkSentinel = cssHasDarkModeSentinel(css);
  if (!extras.html[kTextHighlightingMode] && hasDarkSentinel) {
    setTextHighlightStyle("dark", extras);
  }
  const matches = css.matchAll(kVariablesRegex);
  if (matches) {
    extras.html[kQuartoCssVariables] = extras.html[kQuartoCssVariables] || [];
    let dirty = false;
    for (const match of matches) {
      const variables = match[1];
      extras.html[kQuartoCssVariables]?.push(variables);
      dirty = true;
    }
    extras.html[kQuartoCssVariables] = uniqBy(
      extras.html[kQuartoCssVariables],
      (val) => {
        return val;
      }
    );
    if (dirty) {
      const cleanedCss = css.replaceAll(kVariablesRegex, "");
      let newCssPath;
      if (cleanedCss.trim() === "") {
        newCssPath = void 0;
      } else {
        const hash = await md5HashBytes(new TextEncoder().encode(cleanedCss));
        newCssPath = temp.createFile({ suffix: `-${hash}.css` });
        Deno.writeTextFileSync(newCssPath, cleanedCss, {
          mode: safeModeFromFile(cssPath)
        });
      }
      return {
        dark: hasDarkSentinel,
        path: newCssPath
      };
    }
  }
  return {
    dark: hasDarkSentinel,
    path: cssPath
  };
}
var kVariablesRegex = /\/\*\! quarto-variables-start \*\/([\S\s]*)\/\*\! quarto-variables-end \*\//g;
function attribForThemeStyle(style) {
  const colorModeAttrs = (mode) => {
    const attr = {
      class: `quarto-color-scheme${mode === "dark" ? " quarto-color-alternate" : ""}`
    };
    return attr;
  };
  switch (style) {
    case "dark":
      return colorModeAttrs("dark");
    case "light":
      return colorModeAttrs("light");
    case "default":
    default:
      return {};
  }
}
function setTextHighlightStyle(style, extras) {
  extras.html = extras.html || {};
  extras.html[kTextHighlightingMode] = style;
}

// command/render/pandoc.ts
init_template();
init_pandoc_formats();

// core/author.ts
var kName = "name";
var kGiven = "given";
var kFamily = "family";
var kDropping = "dropping-particle";
var kNonDropping = "non-dropping-particle";
var kAffiliation = "affiliation";
var kAfilliationUrl = "affiliation-url";
var kOrcid = "orcid";
var kUrl = "url";
function cslNameToString(cslName) {
  if (typeof cslName === "string") return cslName;
  if (cslName.literal) return cslName.literal;
  const parts = [];
  if (cslName.given) {
    parts.push(cslName.given);
  }
  if (cslName["dropping-particle"]) {
    parts.push(cslName["dropping-particle"]);
  }
  if (cslName["non-dropping-particle"]) {
    parts.push(cslName["non-dropping-particle"]);
  }
  if (cslName.family) {
    parts.push(cslName.family);
  }
  return parts.join(" ");
}
function parseAuthor(authorRaw, strict) {
  if (!authorRaw) {
    return void 0;
  }
  const parsed = [];
  const authors = Array.isArray(authorRaw) ? authorRaw : [authorRaw];
  let unrecognized = false;
  authors.forEach((author) => {
    if (typeof author === "string") {
      parsed.push({
        name: author
      });
    } else if (typeof author === "object") {
      const name2 = author[kName];
      if (name2) {
        const auth = {
          name: name2
        };
        const affilation = author[kAffiliation];
        if (affilation) {
          auth.affilliation = { name: affilation };
          if (author[kAfilliationUrl]) {
            auth.affilliation.url = author[kAfilliationUrl];
          }
        }
        const orcid = author[kOrcid];
        if (orcid) {
          auth.orcid = orcid;
        }
        const url = author[kUrl];
        if (url) {
          auth.url = url;
        }
        parsed.push(auth);
      } else if (author[kFamily]) {
        const given = author[kGiven];
        const family = author[kFamily];
        const dropping = author[kDropping];
        const nonDropping = author[kNonDropping];
        parsed.push({
          name: {
            [kGiven]: given,
            [kFamily]: family,
            [kDropping]: dropping,
            [kNonDropping]: nonDropping
          }
        });
      } else {
        unrecognized = true;
      }
    }
  });
  if (strict && unrecognized) {
    return void 0;
  } else {
    return parsed;
  }
}

// command/render/pandoc.ts
init_log2();
init_windows();

// https://cdn.skypack.dev/-/moment-guess@v1.2.4-bDXl7KQy0hLGNuGhyGb4/dist=es2019,mode=imports/optimized/moment-guess.js
var Token4 = class {
  constructor(value, type4) {
    this._value = value;
    this._type = type4;
    this._format = "";
  }
  get value() {
    return this._value;
  }
  set value(value) {
    this._value = value;
  }
  get type() {
    return this._type;
  }
  set type(type4) {
    this._type = type4;
  }
  get format() {
    return this._format;
  }
  set format(format14) {
    this._format = format14;
  }
};
var Parser4 = class {
  constructor(name2, pattern) {
    this.name = name2;
    this.pattern = pattern;
  }
  parse(date) {
    const match = this.pattern.exec(date);
    if (!match || !match.groups) {
      return;
    }
    let tokens2 = [];
    for (const [key, val] of Object.entries(match.groups)) {
      if (val) {
        tokens2.push(new Token4(val, /delim\d+/.test(key) ? "delimiter" : key));
      }
    }
    return {
      tokens: tokens2,
      index: match.index,
      parser: this.name
    };
  }
};
var abbreviatedTimezones = "UT|CAT|CET|CVT|EAT|EET|GMT|MUT|RET|SAST|SCT|WAST|WAT|WEST|WET|WST|WT|ADT|AFT|ALMT|AMST|AMT|ANAST|ANAT|AQTT|AST|AZST|AZT|BNT|BST|BTT|CHOST|CHOT|CST|EEST|EET|GET|GST|HKT|HOVST|HOVT|ICT|IDT|IRDT|IRKST|IRKT|IST|JST|KGT|KRAST|KRAT|KST|MAGST|MAGT|MMT|MSK|MVT|NOVST|NOVT|NPT|OMSST|OMST|ORAT|PETST|PETT|PHT|PKT|PYT|QYZT|SAKT|SGT|SRET|TJT|TLT|TMT|TRT|ULAST|ULAT|UZT|VLAST|VLAT|WIB|WIT|YAKST|YAKT|YEKST|YEKT|ART|CAST|CEST|CLST|CLT|DAVT|DDUT|GMT|MAWT|NZDT|NZST|ROTT|SYOT|VOST|ADT|AST|AT|AZOST|AZOT|ACDT|ACST|ACT|ACWST|AEDT|AEST|AET|AWDT|AWST|CXT|LHDT|LHST|NFDT|NFT|AST|AT|CDT|CIDST|CIST|CST|EDT|EST|ET|CST|CT|EST|ET|BST|CEST|CET|EEST|EET|FET|GET|GMT|IST|KUYT|MSD|MSK|SAMT|TRT|WEST|WET|CCT|EAT|IOT|TFT|ADT|AKDT|AKST|AST|AT|CDT|CST|CT|EDT|EGST|EGT|ET|GMT|HDT|HST|MDT|MST|MT|NDT|NST|PDT|PMDT|PMST|PST|PT|WGST|WGT|AoE|BST|CHADT|CHAST|CHUT|CKT|ChST|EASST|EAST|FJST|FJT|GALT|GAMT|GILT|HST|KOST|LINT|MART|MHT|NCT|NRT|NUT|NZDT|NZST|PGT|PHOT|PONT|PST|PWT|SBT|SST|TAHT|TKT|TOST|TOT|TVT|VUT|WAKT|WFT|WST|YAPT|ACT|AMST|AMT|ART|BOT|BRST|BRT|CLST|CLT|COT|ECT|FKST|FKT|FNT|GFT|GST|GYT|PET|PYST|PYT|SRT|UYST|UYT|VET|WARST";
var dayOfMonthAndMonthNameDateFormatParser = new Parser4("DayOfMonthAndMonthNameDateFormatParser", new RegExp(`^(?<dayOfWeek>(?:Sun?|Mon?|Tu(?:es)?|We(?:dnes)?|Th(?:urs)?|Fri?|Sa(?:tur)?)(?:day)?)?(?<delim1>,)?(?<delim2>\\s)?(?<dayOfMonth>(?:3[0-1]|[1-2]\\d|0?[1-9])(?:st|nd|rd|th)?)(?<delim3>\\s)(?<month>Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|June?|July?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)(?<delim4>,)?(?<delim5>\\s)?(?<year>\\d{4}|\\d{2})?(?:(?<delim6>,)?(?<delim7>\\s)(?:(?<twentyFourHour>2[0-3]|0?\\d|1\\d)|(?<twelveHour>0?[1-9]|1[0-2]))(?:(?<delim8>[:.])(?<minute>[0-5]\\d))?(?:(?<delim9>[:.])(?<second>[0-5]\\d))?(?:(?<delim10>.)(?<millisecond>\\d{3}))?(?<delim11>\\s)?(?<meridiem>am|pm|AM|PM)?(?:(?<delim12>\\s)(?<timezone>[+-]\\d{2}(?::?\\d{2})?|Z|${abbreviatedTimezones}))?)?$`));
var iSO8601BasicDateTimeFormatParser = new Parser4("ISO8601BasicDateTimeFormatParser", new RegExp("^(?<year>[+-]\\d{6}|\\d{4})(?:(?<month>\\d{2})(?:(?<dayOfMonth>\\d{2}))?|(?<escapeText>W)(?<isoWeekOfYear>\\d{2})(?:(?<isoDayOfWeek>\\d))?|(?<dayOfYear>\\d{3}))?(?:(?<delim1>T| )(?:(?<twentyFourHour>\\d{2})(?:(?<minute>\\d{2})(?:(?<second>\\d{2})(?:(?<delim2>[.,])(?<millisecond>\\d{1,9}))?)?)?)(?<timezone>[+-]\\d{2}(?::?\\d{2})?|Z)?)?$"));
var iSO8601ExtendedDateTimeFormatParser = new Parser4("ISO8601ExtendedDateTimeFormatParser", new RegExp("^(?<year>[+-]\\d{6}|\\d{4})(?<delim1>\\-)(?:(?<month>\\d{2})(?:(?<delim2>\\-)(?<dayOfMonth>\\d{2}))?|(?<escapeText>W)(?<isoWeekOfYear>\\d{2})(?:(?<delim3>\\-)(?<isoDayOfWeek>\\d))?|(?<dayOfYear>\\d{3}))(?:(?<delim4>T| )(?:(?<twentyFourHour>\\d{2})(?:(?<delim5>:)(?<minute>\\d{2})(?:(?<delim6>:)(?<second>\\d{2})(?:(?<delim7>[.,])(?<millisecond>\\d{1,9}))?)?)?)(?<timezone>[+-]\\d{2}(?::?\\d{2})?|Z)?)?$"));
var monthNameAndDayOfMonthDateFormatParser = new Parser4("MonthNameAndDayOfMonthDateFormatParser", new RegExp(`^(?<dayOfWeek>(?:Sun?|Mon?|Tu(?:es)?|We(?:dnes)?|Th(?:urs)?|Fri?|Sa(?:tur)?)(?:day)?)?(?<delim1>,)?(?<delim2>\\s)?(?<month>Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|June?|July?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)(?<delim3>\\s)(?<dayOfMonth>(?:3[0-1]|[1-2]\\d|0?[1-9])(?:st|nd|rd|th)?)(?<delim4>,)?(?<delim5>\\s)?(?<year>\\d{4}|\\d{2})?(?:(?:(?<delim6>,)?(?<delim7>\\s)(?:(?<twentyFourHour>2[0-3]|0?\\d|1\\d)|(?<twelveHour>0?[1-9]|1[0-2]))(?:(?<delim8>[:.])(?<minute>[0-5]\\d))?(?:(?<delim9>[:.])(?<second>[0-5]\\d))?(?:(?<delim10>.)(?<millisecond>\\d{3}))?(?<delim11>\\s)?(?<meridiem>am|pm|AM|PM)?(?:(?<delim12>\\s)(?<timezone>[+-]\\d{2}(?::?\\d{2})?|Z|${abbreviatedTimezones}))?)?)?$`));
var rFC2822DateTimeFormatParser = new Parser4("RFC2822DateTimeFormatParser", new RegExp("^(?:(?<dayOfWeek>Mon|Tue|Wed|Thu|Fri|Sat|Sun)(?<delim1>,)?(?<delim2>\\s))?(?<dayOfMonth>\\d{1,2})(?<delim3>\\s)(?<month>Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)(?<delim4>\\s)(?<year>\\d{2,4})(?<delim5>\\s)(?<twentyFourHour>\\d{2})(?<delim6>:)(?<minute>\\d{2})(?:(?<delim7>:)(?<second>\\d{2}))?(?<delim8>\\s)(?<timezone>(?:(?:UT|GMT|[ECMP][SD]T)|[Zz]|[+-]\\d{4}))$"));
var slashDelimitedDateTimeFormatParser = new Parser4("SlashDelimitedDateFormatParser", new RegExp(`^(?<year>\\d{4}|\\d{2})(?<delim1>[/.-])(?<month>0?[1-9]|1[0-2])(?:(?<delim2>[/.-])(?<dayOfMonth>0?[1-9]|[1-2]\\d|3[0-1]))?(?:(?:(?<delim3>,)?(?<delim4>\\s)(?:(?<twentyFourHour>2[0-3]|0?\\d|1\\d)|(?<twelveHour>0?[1-9]|1[0-2]))(?:(?<delim5>[:.])(?<minute>[0-5]\\d))?(?:(?<delim6>[:.])(?<second>[0-5]\\d))?(?:(?<delim7>.)(?<millisecond>\\d{3}))?(?<delim8>\\s)?(?<meridiem>am|pm|AM|PM)?(?:(?<delim9>\\s)(?<timezone>[+-]\\d{2}(?::?\\d{2})?|Z|${abbreviatedTimezones}))?)?)?$`));
var twelveHourTimeFormatParser = new Parser4("TwelveHourTimeFormatParser", new RegExp(`^(?<twelveHour>0?[1-9]|1[0-2])(?:(?<delim1>[:.])(?<minute>[0-5]\\d))?(?:(?<delim2>[:.])(?<second>[0-5]\\d))?(?:(?<delim3>.)(?<millisecond>\\d{3}))?(?<delim4>\\s)?(?<meridiem>am|pm|AM|PM)(?:(?<delim5>\\s)(?<timezone>[+-]\\d{2}(?::?\\d{2})?|Z|${abbreviatedTimezones}))?$`));
var twentyFourHourTimeFormatParser = new Parser4("TwentyFourHourTimeFormatParser", new RegExp(`^(?<twentyFourHour>2[0-3]|0?\\d|1\\d)(?<delim1>[:.])(?<minute>[0-5]\\d)(?:(?<delim2>[:.])(?<second>[0-5]\\d))?(?:(?<delim3>.)(?<millisecond>\\d{3}))?(?:(?<delim4>\\s)(?<timezone>[+-]\\d{2}(?::?\\d{2})?|Z|${abbreviatedTimezones}))?$`));
var uKStyleSlashDelimitedDateTimeFormatParser = new Parser4("UKStyleSlashDelimitedDateFormatParser", new RegExp(`^(?<dayOfMonth>0?[1-9]|[1-2]\\d|3[0-1])(?<delim1>[/.-])(?<month>0?[1-9]|1[0-2])(?:(?<delim2>[/.-])(?<year>\\d{4}|\\d{2}))?(?:(?:(?<delim3>,)?(?<delim4>\\s)(?:(?<twentyFourHour>2[0-3]|0?\\d|1\\d)|(?<twelveHour>0?[1-9]|1[0-2]))(?:(?<delim5>[:.])(?<minute>[0-5]\\d))?(?:(?<delim6>[:.])(?<second>[0-5]\\d))?(?:(?<delim7>.)(?<millisecond>\\d{3}))?(?<delim8>\\s)?(?<meridiem>am|pm|AM|PM)?(?:(?<delim9>\\s)(?<timezone>[+-]\\d{2}(?::?\\d{2})?|Z|${abbreviatedTimezones}))?)?)?$`));
var uSStyleSlashDelimitedDateTimeFormatParser = new Parser4("USStyleSlashDelimitedDateFormatParser", new RegExp(`^(?<month>0?[1-9]|1[0-2])(?<delim1>[/.-])(?<dayOfMonth>0?[1-9]|[1-2]\\d|3[0-1])(?:(?<delim2>[/.-])(?<year>\\d{4}|\\d{2}))?(?:(?:(?<delim3>,)?(?<delim4>\\s)(?:(?<twentyFourHour>2[0-3]|0?\\d|1\\d)|(?<twelveHour>0?[1-9]|1[0-2]))(?:(?<delim5>[:.])(?<minute>[0-5]\\d))?(?:(?<delim6>[:.])(?<second>[0-5]\\d))?(?:(?<delim7>.)(?<millisecond>\\d{3}))?(?<delim8>\\s)?(?<meridiem>am|pm|AM|PM)?(?:(?<delim9>\\s)(?<timezone>[+-]\\d{2}(?::?\\d{2})?|Z|${abbreviatedTimezones}))?)?)?$`));
var dashDelimitedWithMonthNameDateTimeFormatParser = new Parser4("DashDelimitedWithMonthNameDateTimeFormatParser", new RegExp(`^(?<dayOfMonth>0?[1-9]|[1-2]\\d|3[0-1])(?<delim1>-)(?<month>Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|June?|July?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)(?<delim2>-)?(?<year>\\d{4}|\\d{2})?(?:(?:(?<delim3>,)?(?<delim4>\\s)(?:(?<twentyFourHour>2[0-3]|0?\\d|1\\d)|(?<twelveHour>0?[1-9]|1[0-2]))(?:(?<delim5>[:.])(?<minute>[0-5]\\d))?(?:(?<delim6>[:.])(?<second>[0-5]\\d))?(?:(?<delim7>.)(?<millisecond>\\d{3}))?(?<delim8>\\s)?(?<meridiem>am|pm|AM|PM)?(?:(?<delim9>\\s)(?<timezone>[+-]\\d{2}(?::?\\d{2})?|Z|${abbreviatedTimezones}))?)?)?$`));
var parsers = [
  iSO8601ExtendedDateTimeFormatParser,
  iSO8601BasicDateTimeFormatParser,
  rFC2822DateTimeFormatParser,
  slashDelimitedDateTimeFormatParser,
  uKStyleSlashDelimitedDateTimeFormatParser,
  uSStyleSlashDelimitedDateTimeFormatParser,
  monthNameAndDayOfMonthDateFormatParser,
  dayOfMonthAndMonthNameDateFormatParser,
  twentyFourHourTimeFormatParser,
  twelveHourTimeFormatParser,
  dashDelimitedWithMonthNameDateTimeFormatParser
];
var StandardFormatParsersRefiner = class {
  constructor(name2) {
    this.name = name2;
  }
  refine(parsedResults) {
    const res = parsedResults.filter((r5) => {
      return r5.parser === "ISO8601ExtendedDateTimeFormatParser" || r5.parser === "ISO8601BasicDateTimeFormatParser" || r5.parser === "RFC2822DateTimeFormatParser";
    });
    if (res.length === 0) {
      return parsedResults;
    }
    return res;
  }
};
var TimeFormatRefiner = class {
  constructor(name2) {
    this.name = name2;
  }
  refine(parsedResults) {
    parsedResults.forEach((r5) => {
      let meridiemExists = false;
      r5.tokens.forEach((t5) => {
        if (t5.type === "meridiem") {
          meridiemExists = true;
        }
      });
      if (meridiemExists) {
        r5.tokens.forEach((t5) => {
          if (t5.type === "twentyFourHour") {
            t5.type = "twelveHour";
          }
        });
      }
    });
    return parsedResults;
  }
};
var timeFormatRefiner = new TimeFormatRefiner("TimeFormatRefiner");
var standardFormatParsersRefiner = new StandardFormatParsersRefiner("StandardFormatParsersRefiner");
var refiners = [
  standardFormatParsersRefiner,
  timeFormatRefiner
];
var YearFormatTokenAssigner = class {
  constructor(name2, type4, format14) {
    this.name = name2;
    this.type = type4;
    this.format = format14;
    this._map = /* @__PURE__ */ new Map();
    if (!format14 || format14 === "default") {
      this._map.set(/\d{2}/, "YY");
      this._map.set(/\d{4}/, "YYYY");
      this._map.set(/[+-]\d{6}/, "YYYYYY");
    } else {
      this._map.set(/\d{2}/, "%y");
      this._map.set(/\d{4}/, "%Y");
      this._map.set(/[+-]\d{6}/, "NA");
    }
  }
  _testTokenType(token) {
    return token.type === this.type;
  }
  assign(token) {
    this._map.forEach((formatToken, pattern) => {
      if (this._testTokenType(token) && pattern.test(token.value)) {
        token.format = formatToken;
      }
    });
  }
};
var MonthFormatTokenAssigner = class {
  constructor(name2, type4, format14) {
    this.name = name2;
    this.type = type4;
    this.format = format14;
    this._map = /* @__PURE__ */ new Map();
    if (!format14 || format14 === "default") {
      this._map.set(/\d{1,2}/, "M");
      this._map.set(/\d{2}/, "MM");
      this._map.set(/\d{1,2}(?:st|nd|rd|th)/, "Mo");
      this._map.set(/^(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)$/, "MMM");
      this._map.set(/^(January|February|March|April|May|June|July|August|September|October|November|December)$/, "MMMM");
    } else {
      this._map.set(/\d{1,2}/, "NA");
      this._map.set(/\d{2}/, "%m");
      this._map.set(/\d{1,2}(?:st|nd|rd|th)/, "NA");
      this._map.set(/^(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)$/, "%b");
      this._map.set(/^(January|February|March|April|May|June|July|August|September|October|November|December)$/, "%B");
    }
  }
  _testTokenType(token) {
    return token.type === this.type;
  }
  assign(token) {
    this._map.forEach((formatToken, pattern) => {
      if (this._testTokenType(token) && pattern.test(token.value)) {
        token.format = formatToken;
      }
    });
  }
};
var DayOfMonthFormatTokenAssigner = class {
  constructor(name2, type4, format14) {
    this.name = name2;
    this.type = type4;
    this.format = format14;
    this._map = /* @__PURE__ */ new Map();
    if (!format14 || format14 === "default") {
      this._map.set(/\d{1,2}/, "D");
      this._map.set(/\d{2}/, "DD");
      this._map.set(/\d{1,2}(?:st|nd|rd|th)/, "Do");
    } else {
      this._map.set(/\d{1,2}/, "%-e");
      this._map.set(/\d{2}/, "%d");
      this._map.set(/\d{1,2}(?:st|nd|rd|th)/, "%o");
    }
  }
  _testTokenType(token) {
    return token.type === this.type;
  }
  assign(token) {
    this._map.forEach((formatToken, pattern) => {
      if (this._testTokenType(token) && pattern.test(token.value)) {
        token.format = formatToken;
      }
    });
  }
};
var DelimiterFormatTokenAssigner = class {
  constructor(name2, type4, format14) {
    this.name = name2;
    this.format = format14;
    this.type = type4;
  }
  assign(token) {
  }
};
var MinuteFormatTokenAssigner = class {
  constructor(name2, type4, format14) {
    this.name = name2;
    this.type = type4;
    this.format = format14;
    this._map = /* @__PURE__ */ new Map();
    if (!format14 || format14 === "default") {
      this._map.set(/\d{1,2}/, "m");
      this._map.set(/\d{2}/, "mm");
    } else {
      this._map.set(/\d{1,2}/, "NA");
      this._map.set(/\d{2}/, "%M");
    }
  }
  _testTokenType(token) {
    return token.type === this.type;
  }
  assign(token) {
    this._map.forEach((formatToken, pattern) => {
      if (this._testTokenType(token) && pattern.test(token.value)) {
        token.format = formatToken;
      }
    });
  }
};
var SecondFormatTokenAssigner = class {
  constructor(name2, type4, format14) {
    this.name = name2;
    this.type = type4;
    this.format = format14;
    this._map = /* @__PURE__ */ new Map();
    if (!format14 || format14 === "default") {
      this._map.set(/\d{1,2}/, "s");
      this._map.set(/\d{2}/, "ss");
    } else {
      this._map.set(/\d{1,2}/, "NA");
      this._map.set(/\d{2}/, "%S");
    }
  }
  _testTokenType(token) {
    return token.type === this.type;
  }
  assign(token) {
    this._map.forEach((formatToken, pattern) => {
      if (this._testTokenType(token) && pattern.test(token.value)) {
        token.format = formatToken;
      }
    });
  }
};
var MillisecondFormatTokenAssigner = class {
  constructor(name2, type4, format14) {
    this.name = name2;
    this.type = type4;
    this.format = format14;
    this._map = /* @__PURE__ */ new Map();
    if (!format14 || format14 === "default") {
      this._map.set(/\d/, "S");
      this._map.set(/\d{2}/, "SS");
      this._map.set(/\d{3}/, "SSS");
    } else {
      this._map.set(/\d/, "NA");
      this._map.set(/\d{2}/, "NA");
      this._map.set(/\d{3}/, "%L");
    }
  }
  _testTokenType(token) {
    return token.type === this.type;
  }
  assign(token) {
    this._map.forEach((formatToken, pattern) => {
      if (this._testTokenType(token) && pattern.test(token.value)) {
        token.format = formatToken;
      }
    });
  }
};
var TimezoneFormatTokenAssigner = class {
  constructor(name2, type4, format14) {
    this.name = name2;
    this.type = type4;
    this.format = format14;
    this._map = /* @__PURE__ */ new Map();
    const abbreviatedTimezoneRegex = new RegExp("UT|CAT|CET|CVT|EAT|EET|GMT|MUT|RET|SAST|SCT|WAST|WAT|WEST|WET|WST|WT|ADT|AFT|ALMT|AMST|AMT|ANAST|ANAT|AQTT|AST|AZST|AZT|BNT|BST|BTT|CHOST|CHOT|CST|EEST|EET|GET|GST|HKT|HOVST|HOVT|ICT|IDT|IRDT|IRKST|IRKT|IST|JST|KGT|KRAST|KRAT|KST|MAGST|MAGT|MMT|MSK|MVT|NOVST|NOVT|NPT|OMSST|OMST|ORAT|PETST|PETT|PHT|PKT|PYT|QYZT|SAKT|SGT|SRET|TJT|TLT|TMT|TRT|ULAST|ULAT|UZT|VLAST|VLAT|WIB|WIT|YAKST|YAKT|YEKST|YEKT|ART|CAST|CEST|CLST|CLT|DAVT|DDUT|GMT|MAWT|NZDT|NZST|ROTT|SYOT|VOST|ADT|AST|AT|AZOST|AZOT|ACDT|ACST|ACT|ACWST|AEDT|AEST|AET|AWDT|AWST|CXT|LHDT|LHST|NFDT|NFT|AST|AT|CDT|CIDST|CIST|CST|EDT|EST|ET|CST|CT|EST|ET|BST|CEST|CET|EEST|EET|FET|GET|GMT|IST|KUYT|MSD|MSK|SAMT|TRT|WEST|WET|CCT|EAT|IOT|TFT|ADT|AKDT|AKST|AST|AT|CDT|CST|CT|EDT|EGST|EGT|ET|GMT|HDT|HST|MDT|MST|MT|NDT|NST|PDT|PMDT|PMST|PST|PT|WGST|WGT|AoE|BST|CHADT|CHAST|CHUT|CKT|ChST|EASST|EAST|FJST|FJT|GALT|GAMT|GILT|HST|KOST|LINT|MART|MHT|NCT|NRT|NUT|NZDT|NZST|PGT|PHOT|PONT|PST|PWT|SBT|SST|TAHT|TKT|TOST|TOT|TVT|VUT|WAKT|WFT|WST|YAPT|ACT|AMST|AMT|ART|BOT|BRST|BRT|CLST|CLT|COT|ECT|FKST|FKT|FNT|GFT|GST|GYT|PET|PYST|PYT|SRT|UYST|UYT|VET|WARST");
    if (!format14 || format14 === "default") {
      this._map.set(/[+-]\d{2}(?::\d{2})?/, "Z");
      this._map.set(/[+-]\d{4}/, "ZZ");
      this._map.set(/Z/, "[Z]");
      this._map.set(/z/, "[z]");
      this._map.set(abbreviatedTimezoneRegex, "z");
    } else {
      this._map.set(/[+-]\d{2}(?::\d{2})?/, "%:z");
      this._map.set(/[+-]\d{4}/, "%z");
      this._map.set(/Z/, "Z");
      this._map.set(/z/, "z");
      this._map.set(abbreviatedTimezoneRegex, "%Z");
    }
  }
  _testTokenType(token) {
    return token.type === this.type;
  }
  assign(token) {
    this._map.forEach((formatToken, pattern) => {
      if (this._testTokenType(token) && pattern.test(token.value)) {
        token.format = formatToken;
      }
    });
  }
};
var DayOfYearFormatTokenAssigner = class {
  constructor(name2, type4, format14) {
    this.name = name2;
    this.type = type4;
    this.format = format14;
    this._map = /* @__PURE__ */ new Map();
    if (!format14 || format14 === "default") {
      this._map.set(/\d{1,3}/, "DDD");
      this._map.set(/\d{3}/, "DDDD");
      this._map.set(/\d{1,3}(?:st|nd|rd|th)/, "DDDo");
    } else {
      this._map.set(/\d{1,3}/, "NA");
      this._map.set(/\d{3}/, "%j");
      this._map.set(/\d{1,3}(?:st|nd|rd|th)/, "NA");
    }
  }
  _testTokenType(token) {
    return token.type === this.type;
  }
  assign(token) {
    this._map.forEach((formatToken, pattern) => {
      if (this._testTokenType(token) && pattern.test(token.value)) {
        token.format = formatToken;
      }
    });
  }
};
var EscapeTextFormatTokenAssigner = class {
  constructor(name2, type4, format14) {
    this.name = name2;
    this.type = type4;
    this.format = format14;
  }
  _testTokenType(token) {
    return token.type === this.type;
  }
  assign(token) {
    if (this._testTokenType(token)) {
      token.format = !this.format || this.format === "default" ? `[${token.value}]` : token.value;
    }
  }
};
var ISODayOfWeekFormatTokenAssigner = class {
  constructor(name2, type4, format14) {
    this.name = name2;
    this.type = type4;
    this.format = format14;
    this._map = /* @__PURE__ */ new Map();
    if (!format14 || format14 === "default") {
      this._map.set(/[1-7]/, "E");
    } else {
      this._map.set(/[1-7]/, "%u");
    }
  }
  _testTokenType(token) {
    return token.type === this.type;
  }
  assign(token) {
    this._map.forEach((formatToken, pattern) => {
      if (this._testTokenType(token) && pattern.test(token.value)) {
        token.format = formatToken;
      }
    });
  }
};
var ISOWeekOfYearFormatTokenAssigner = class {
  constructor(name2, type4, format14) {
    this.name = name2;
    this.type = type4;
    this.format = format14;
    this._map = /* @__PURE__ */ new Map();
    if (!format14 || format14 === "default") {
      this._map.set(/\d{1,2}/, "W");
      this._map.set(/\d{2}/, "WW");
      this._map.set(/\d{1,2}(?:st|nd|rd|th)/, "Wo");
    } else {
      this._map.set(/\d{1,2}/, "NA");
      this._map.set(/\d{2}/, "%U");
      this._map.set(/\d{1,2}(?:st|nd|rd|th)/, "NA");
    }
  }
  _testTokenType(token) {
    return token.type === this.type;
  }
  assign(token) {
    this._map.forEach((formatToken, pattern) => {
      if (this._testTokenType(token) && pattern.test(token.value)) {
        token.format = formatToken;
      }
    });
  }
};
var TwentyFourHourFormatTokenAssigner = class {
  constructor(name2, type4, format14) {
    this.name = name2;
    this.type = type4;
    this.format = format14;
    this._map = /* @__PURE__ */ new Map();
    if (!format14 || format14 === "default") {
      this._map.set(/^(\d|1\d|2[0-3])$/, "H");
      this._map.set(/^([0-1]\d|2[0-3])$/, "HH");
    } else {
      this._map.set(/^(\d|1\d|2[0-3])$/, "%-k");
      this._map.set(/^([0-1]\d|2[0-3])$/, "%H");
    }
  }
  _testTokenType(token) {
    return token.type === this.type;
  }
  assign(token) {
    this._map.forEach((formatToken, pattern) => {
      if (this._testTokenType(token) && pattern.test(token.value)) {
        token.format = formatToken;
      }
    });
  }
};
var TwelveHourFormatTokenAssigner = class {
  constructor(name2, type4, format14) {
    this.name = name2;
    this.type = type4;
    this.format = format14;
    this._map = /* @__PURE__ */ new Map();
    if (!format14 || format14 === "default") {
      this._map.set(/^([1-9]|1[0-2])$/, "h");
      this._map.set(/^(0\d|1[0-2])$/, "hh");
    } else {
      this._map.set(/^([1-9]|1[0-2])$/, "%-l");
      this._map.set(/^(0\d|1[0-2])$/, "%I");
    }
  }
  _testTokenType(token) {
    return token.type === this.type;
  }
  assign(token) {
    this._map.forEach((formatToken, pattern) => {
      if (this._testTokenType(token) && pattern.test(token.value)) {
        token.format = formatToken;
      }
    });
  }
};
var DayOfWeekFormatTokenAssigner = class {
  constructor(name2, type4, format14) {
    this.name = name2;
    this.type = type4;
    this.format = format14;
    this._map = /* @__PURE__ */ new Map();
    if (!format14 || format14 === "default") {
      this._map.set(/[0-6]/, "d");
      this._map.set(/[0-6](?:st|nd|rd|th)/, "do");
      this._map.set(/(?:Su|Mo|Tu|We|Th|Fr|Sa)/, "dd");
      this._map.set(/(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)/, "ddd");
      this._map.set(/(?:Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday)/, "dddd");
    } else {
      this._map.set(/[0-6]/, "%w");
      this._map.set(/[0-6](?:st|nd|rd|th)/, "NA");
      this._map.set(/(?:Su|Mo|Tu|We|Th|Fr|Sa)/, "NA");
      this._map.set(/(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)/, "%a");
      this._map.set(/(?:Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday)/, "%A");
    }
  }
  _testTokenType(token) {
    return token.type === this.type;
  }
  assign(token) {
    this._map.forEach((formatToken, pattern) => {
      if (this._testTokenType(token) && pattern.test(token.value)) {
        token.format = formatToken;
      }
    });
  }
};
var MeridiemFormatTokenAssigner = class {
  constructor(name2, type4, format14) {
    this.name = name2;
    this.type = type4;
    this.format = format14;
    this._map = /* @__PURE__ */ new Map();
    if (!format14 || format14 === "default") {
      this._map.set(/am|pm/, "a");
      this._map.set(/AM|PM/, "A");
    } else {
      this._map.set(/am|pm/, "%P");
      this._map.set(/AM|PM/, "%p");
    }
  }
  _testTokenType(token) {
    return token.type === this.type;
  }
  assign(token) {
    this._map.forEach((formatToken, pattern) => {
      if (this._testTokenType(token) && pattern.test(token.value)) {
        token.format = formatToken;
      }
    });
  }
};
var dayOfMonthFormatTokenAssigner = new DayOfMonthFormatTokenAssigner("DelimiterFormatTokenAssigner", "dayOfMonth");
var dayOfWeekFormatTokenAssigner = new DayOfWeekFormatTokenAssigner("DayOfWeekFormatTokenAssigner", "dayOfWeek");
var dayOfYearFormatTokenAssigner = new DayOfYearFormatTokenAssigner("DayOfYearFormatTokenAssigner", "dayOfYear");
var delimiterFormatTokenAssigner = new DelimiterFormatTokenAssigner("DelimiterFormatTokenAssigner", "delimiter");
var escapeTextFormatTokenAssigner = new EscapeTextFormatTokenAssigner("EscapeTextFormatTokenAssigner", "escapeText");
var iSODayOfWeekFormatTokenAssigner = new ISODayOfWeekFormatTokenAssigner("ISODayOfWeekFormatTokenAssigner", "isoDayOfWeek");
var iSOWeekOfYearFormatTokenAssigner = new ISOWeekOfYearFormatTokenAssigner("ISOWeekOfYearFormatTokenAssigner", "isoWeekOfYear");
var meridiemFormatTokenAssigner = new MeridiemFormatTokenAssigner("MeridiemFormatTokenAssigner", "meridiem");
var millisecondFormatTokenAssigner = new MillisecondFormatTokenAssigner("MillisecondFormatTokenAssigner", "millisecond");
var minuteFormatTokenAssigner = new MinuteFormatTokenAssigner("MinuteFormatTokenAssigner", "minute");
var monthFormatTokenAssigner = new MonthFormatTokenAssigner("MonthFormatTokenAssigner", "month");
var secondFormatTokenAssigner = new SecondFormatTokenAssigner("SecondFormatTokenAssigner", "second");
var timezoneFormatTokenAssigner = new TimezoneFormatTokenAssigner("TimezoneFormatTokenAssigner", "timezone");
var twelveHourFormatTokenAssigner = new TwelveHourFormatTokenAssigner("TwelveHourFormatTokenAssigner", "twelveHour");
var twentyFourHourFormatTokenAssigner = new TwentyFourHourFormatTokenAssigner("TwentyFourHourFormatTokenAssigner", "twentyFourHour");
var yearFormatTokenAssigner = new YearFormatTokenAssigner("YearFormatTokenAssigner", "year");
var strftimeDayOfMonthFormatTokenAssigner = new DayOfMonthFormatTokenAssigner("DelimiterFormatTokenAssigner", "dayOfMonth", "strftime");
var strftimeDayOfWeekFormatTokenAssigner = new DayOfWeekFormatTokenAssigner("DayOfWeekFormatTokenAssigner", "dayOfWeek", "strftime");
var strftimeDayOfYearFormatTokenAssigner = new DayOfYearFormatTokenAssigner("DayOfYearFormatTokenAssigner", "dayOfYear", "strftime");
var strftimeDelimiterFormatTokenAssigner = new DelimiterFormatTokenAssigner("DelimiterFormatTokenAssigner", "delimiter", "strftime");
var strftimeEscapeTextFormatTokenAssigner = new EscapeTextFormatTokenAssigner("EscapeTextFormatTokenAssigner", "escapeText", "strftime");
var strftimeISODayOfWeekFormatTokenAssigner = new ISODayOfWeekFormatTokenAssigner("ISODayOfWeekFormatTokenAssigner", "isoDayOfWeek", "strftime");
var strftimeISOWeekOfYearFormatTokenAssigner = new ISOWeekOfYearFormatTokenAssigner("ISOWeekOfYearFormatTokenAssigner", "isoWeekOfYear", "strftime");
var strftimeMeridiemFormatTokenAssigner = new MeridiemFormatTokenAssigner("MeridiemFormatTokenAssigner", "meridiem", "strftime");
var strftimeMillisecondFormatTokenAssigner = new MillisecondFormatTokenAssigner("MillisecondFormatTokenAssigner", "millisecond", "strftime");
var strftimeMinuteFormatTokenAssigner = new MinuteFormatTokenAssigner("MinuteFormatTokenAssigner", "minute", "strftime");
var strftimeMonthFormatTokenAssigner = new MonthFormatTokenAssigner("MonthFormatTokenAssigner", "month", "strftime");
var strftimeSecondFormatTokenAssigner = new SecondFormatTokenAssigner("SecondFormatTokenAssigner", "second", "strftime");
var strftimeTimezoneFormatTokenAssigner = new TimezoneFormatTokenAssigner("TimezoneFormatTokenAssigner", "timezone", "strftime");
var strftimeTwelveHourFormatTokenAssigner = new TwelveHourFormatTokenAssigner("TwelveHourFormatTokenAssigner", "twelveHour", "strftime");
var strftimeTwentyFourHourFormatTokenAssigner = new TwentyFourHourFormatTokenAssigner("TwentyFourHourFormatTokenAssigner", "twentyFourHour", "strftime");
var strftimeYearFormatTokenAssigner = new YearFormatTokenAssigner("YearFormatTokenAssigner", "year", "strftime");
var defaultAssigners = [
  yearFormatTokenAssigner,
  monthFormatTokenAssigner,
  dayOfMonthFormatTokenAssigner,
  delimiterFormatTokenAssigner,
  minuteFormatTokenAssigner,
  secondFormatTokenAssigner,
  millisecondFormatTokenAssigner,
  timezoneFormatTokenAssigner,
  dayOfYearFormatTokenAssigner,
  escapeTextFormatTokenAssigner,
  iSODayOfWeekFormatTokenAssigner,
  iSOWeekOfYearFormatTokenAssigner,
  twentyFourHourFormatTokenAssigner,
  twelveHourFormatTokenAssigner,
  dayOfWeekFormatTokenAssigner,
  meridiemFormatTokenAssigner
];
var strftimeAssigners = [
  strftimeDayOfMonthFormatTokenAssigner,
  strftimeDayOfWeekFormatTokenAssigner,
  strftimeDayOfYearFormatTokenAssigner,
  strftimeDelimiterFormatTokenAssigner,
  strftimeEscapeTextFormatTokenAssigner,
  strftimeISODayOfWeekFormatTokenAssigner,
  strftimeISOWeekOfYearFormatTokenAssigner,
  strftimeMeridiemFormatTokenAssigner,
  strftimeMillisecondFormatTokenAssigner,
  strftimeMinuteFormatTokenAssigner,
  strftimeMonthFormatTokenAssigner,
  strftimeSecondFormatTokenAssigner,
  strftimeTimezoneFormatTokenAssigner,
  strftimeTwelveHourFormatTokenAssigner,
  strftimeTwentyFourHourFormatTokenAssigner,
  strftimeYearFormatTokenAssigner
];
var Guesser = class {
  constructor() {
  }
  static parse(date) {
    const parsedResults = [];
    parsers.forEach((parser) => {
      const parsedResult = parser.parse(date);
      if (parsedResult) {
        parsedResults.push(Object.assign({}, parsedResult));
      }
    });
    return parsedResults;
  }
  static refine(parsedResults) {
    let refinedParsedResults = [...parsedResults];
    refiners.forEach((refiner) => {
      refinedParsedResults = [
        ...refiner.refine(refinedParsedResults)
      ];
    });
    return refinedParsedResults;
  }
  static assign(tokens2, format14) {
    let assigners = !format14 || format14 === "default" ? defaultAssigners : strftimeAssigners;
    assigners.forEach((assigner) => {
      tokens2.forEach((token) => {
        assigner.assign(token);
      });
    });
  }
  static getFormatString(tokens2) {
    let formatString = "";
    tokens2.forEach((token) => {
      if (token.format === "NA") {
        throw Error(`Couldn't find strftime modifier for "${token.value}"`);
      }
      formatString += token.format ? token.format : token.value;
    });
    return formatString;
  }
};
function guessFormat(date, format14) {
  const parsedResults = Guesser.parse(date);
  const refinedParsedResults = Guesser.refine(parsedResults);
  if (refinedParsedResults.length === 0) {
    throw Error("Couldn't parse date");
  }
  refinedParsedResults.forEach((r5) => Guesser.assign(r5.tokens, format14));
  let matchedFormats = [];
  refinedParsedResults.forEach((r5) => matchedFormats.push(Guesser.getFormatString(r5.tokens)));
  return matchedFormats.length === 1 ? matchedFormats[0] : matchedFormats;
}
var moment_guess_default = guessFormat;

// https://jsr.io/@std/datetime/0.225.4/_date_time_formatter.ts
function digits(value, count = 2) {
  return String(value).padStart(count, "0");
}
var QUOTED_LITERAL_REGEXP = /^(')(?<value>\\.|[^\']*)\1/;
var LITERAL_REGEXP = /^(?<value>.+?\s*)/;
var SYMBOL_REGEXP = /^(?<symbol>([a-zA-Z])\2*)/;
function formatToFormatParts(format14) {
  const formatParts = [];
  let index2 = 0;
  while (index2 < format14.length) {
    const substring = format14.slice(index2);
    const symbol = SYMBOL_REGEXP.exec(substring)?.groups?.symbol;
    switch (symbol) {
      case "yyyy":
        formatParts.push({ type: "year", value: "numeric" });
        index2 += symbol.length;
        continue;
      case "yy":
        formatParts.push({ type: "year", value: "2-digit" });
        index2 += symbol.length;
        continue;
      case "MM":
        formatParts.push({ type: "month", value: "2-digit" });
        index2 += symbol.length;
        continue;
      case "M":
        formatParts.push({ type: "month", value: "numeric" });
        index2 += symbol.length;
        continue;
      case "dd":
        formatParts.push({ type: "day", value: "2-digit" });
        index2 += symbol.length;
        continue;
      case "d":
        formatParts.push({ type: "day", value: "numeric" });
        index2 += symbol.length;
        continue;
      case "HH":
        formatParts.push({ type: "hour", value: "2-digit" });
        index2 += symbol.length;
        continue;
      case "H":
        formatParts.push({ type: "hour", value: "numeric" });
        index2 += symbol.length;
        continue;
      case "hh":
        formatParts.push({ type: "hour", value: "2-digit", hour12: true });
        index2 += symbol.length;
        continue;
      case "h":
        formatParts.push({ type: "hour", value: "numeric", hour12: true });
        index2 += symbol.length;
        continue;
      case "mm":
        formatParts.push({ type: "minute", value: "2-digit" });
        index2 += symbol.length;
        continue;
      case "m":
        formatParts.push({ type: "minute", value: "numeric" });
        index2 += symbol.length;
        continue;
      case "ss":
        formatParts.push({ type: "second", value: "2-digit" });
        index2 += symbol.length;
        continue;
      case "s":
        formatParts.push({ type: "second", value: "numeric" });
        index2 += symbol.length;
        continue;
      case "SSS":
        formatParts.push({ type: "fractionalSecond", value: 3 });
        index2 += symbol.length;
        continue;
      case "SS":
        formatParts.push({ type: "fractionalSecond", value: 2 });
        index2 += symbol.length;
        continue;
      case "S":
        formatParts.push({ type: "fractionalSecond", value: 1 });
        index2 += symbol.length;
        continue;
      case "a":
        formatParts.push({ type: "dayPeriod", value: 1 });
        index2 += symbol.length;
        continue;
    }
    const quotedLiteralMatch = QUOTED_LITERAL_REGEXP.exec(substring);
    if (quotedLiteralMatch) {
      const value2 = quotedLiteralMatch.groups.value;
      formatParts.push({ type: "literal", value: value2 });
      index2 += quotedLiteralMatch[0].length;
      continue;
    }
    const literalGroups = LITERAL_REGEXP.exec(substring).groups;
    const value = literalGroups.value;
    formatParts.push({ type: "literal", value });
    index2 += value.length;
  }
  return formatParts;
}
function sortDateTimeFormatParts(parts) {
  let result2 = [];
  const typeArray = [
    "year",
    "month",
    "day",
    "hour",
    "minute",
    "second",
    "fractionalSecond"
  ];
  for (const type4 of typeArray) {
    const current3 = parts.findIndex((el) => el.type === type4);
    if (current3 !== -1) {
      result2 = result2.concat(parts.splice(current3, 1));
    }
  }
  result2 = result2.concat(parts);
  return result2;
}
var DateTimeFormatter = class {
  #formatParts;
  constructor(formatString) {
    this.#formatParts = formatToFormatParts(formatString);
  }
  format(date, options = {}) {
    let string2 = "";
    const utc = options.timeZone === "UTC";
    for (const part of this.#formatParts) {
      const type4 = part.type;
      switch (type4) {
        case "year": {
          const value = utc ? date.getUTCFullYear() : date.getFullYear();
          switch (part.value) {
            case "numeric": {
              string2 += value;
              break;
            }
            case "2-digit": {
              string2 += digits(value, 2).slice(-2);
              break;
            }
            default:
              throw new Error(
                `FormatterError: value "${part.value}" is not supported`
              );
          }
          break;
        }
        case "month": {
          const value = (utc ? date.getUTCMonth() : date.getMonth()) + 1;
          switch (part.value) {
            case "numeric": {
              string2 += value;
              break;
            }
            case "2-digit": {
              string2 += digits(value, 2);
              break;
            }
            default:
              throw new Error(
                `FormatterError: value "${part.value}" is not supported`
              );
          }
          break;
        }
        case "day": {
          const value = utc ? date.getUTCDate() : date.getDate();
          switch (part.value) {
            case "numeric": {
              string2 += value;
              break;
            }
            case "2-digit": {
              string2 += digits(value, 2);
              break;
            }
            default:
              throw new Error(
                `FormatterError: value "${part.value}" is not supported`
              );
          }
          break;
        }
        case "hour": {
          let value = utc ? date.getUTCHours() : date.getHours();
          if (part.hour12) {
            if (value === 0) value = 12;
            else if (value > 12) value -= 12;
          }
          switch (part.value) {
            case "numeric": {
              string2 += value;
              break;
            }
            case "2-digit": {
              string2 += digits(value, 2);
              break;
            }
            default:
              throw new Error(
                `FormatterError: value "${part.value}" is not supported`
              );
          }
          break;
        }
        case "minute": {
          const value = utc ? date.getUTCMinutes() : date.getMinutes();
          switch (part.value) {
            case "numeric": {
              string2 += value;
              break;
            }
            case "2-digit": {
              string2 += digits(value, 2);
              break;
            }
            default:
              throw new Error(
                `FormatterError: value "${part.value}" is not supported`
              );
          }
          break;
        }
        case "second": {
          const value = utc ? date.getUTCSeconds() : date.getSeconds();
          switch (part.value) {
            case "numeric": {
              string2 += value;
              break;
            }
            case "2-digit": {
              string2 += digits(value, 2);
              break;
            }
            default:
              throw new Error(
                `FormatterError: value "${part.value}" is not supported`
              );
          }
          break;
        }
        case "fractionalSecond": {
          const value = utc ? date.getUTCMilliseconds() : date.getMilliseconds();
          string2 += digits(value, 3).slice(0, Number(part.value));
          break;
        }
        // FIXME(bartlomieju)
        case "timeZoneName": {
          break;
        }
        case "dayPeriod": {
          string2 += date.getHours() >= 12 ? "PM" : "AM";
          break;
        }
        case "literal": {
          string2 += part.value;
          break;
        }
        default:
          throw new Error(`FormatterError: { ${part.type} ${part.value} }`);
      }
    }
    return string2;
  }
  formatToParts(string2) {
    const parts = [];
    for (const part of this.#formatParts) {
      const type4 = part.type;
      let length = 0;
      let value = "";
      switch (part.type) {
        case "year": {
          switch (part.value) {
            case "numeric": {
              value = /^\d{4}/.exec(string2)?.[0];
              length = value?.length;
              break;
            }
            case "2-digit": {
              value = /^\d{2}/.exec(string2)?.[0];
              length = value?.length;
              break;
            }
            default:
              throw new Error(
                `ParserError: value "${part.value}" is not supported`
              );
          }
          break;
        }
        case "month": {
          switch (part.value) {
            case "numeric": {
              value = /^\d{1,2}/.exec(string2)?.[0];
              length = value?.length;
              break;
            }
            case "2-digit": {
              value = /^\d{2}/.exec(string2)?.[0];
              length = value?.length;
              break;
            }
            case "narrow": {
              value = /^[a-zA-Z]+/.exec(string2)?.[0];
              length = value?.length;
              break;
            }
            case "short": {
              value = /^[a-zA-Z]+/.exec(string2)?.[0];
              length = value?.length;
              break;
            }
            case "long": {
              value = /^[a-zA-Z]+/.exec(string2)?.[0];
              length = value?.length;
              break;
            }
            default:
              throw new Error(
                `ParserError: value "${part.value}" is not supported`
              );
          }
          break;
        }
        case "day": {
          switch (part.value) {
            case "numeric": {
              value = /^\d{1,2}/.exec(string2)?.[0];
              length = value?.length;
              break;
            }
            case "2-digit": {
              value = /^\d{2}/.exec(string2)?.[0];
              length = value?.length;
              break;
            }
            default:
              throw new Error(
                `ParserError: value "${part.value}" is not supported`
              );
          }
          break;
        }
        case "hour": {
          switch (part.value) {
            case "numeric": {
              value = /^\d{1,2}/.exec(string2)?.[0];
              length = value?.length;
              if (part.hour12 && parseInt(value) > 12) {
                console.error(
                  `Trying to parse hour greater than 12, use 'H' instead of 'h'.`
                );
              }
              break;
            }
            case "2-digit": {
              value = /^\d{2}/.exec(string2)?.[0];
              length = value?.length;
              if (part.hour12 && parseInt(value) > 12) {
                console.error(
                  `Trying to parse hour greater than 12, use 'HH' instead of 'hh'.`
                );
              }
              break;
            }
            default:
              throw new Error(
                `ParserError: value "${part.value}" is not supported`
              );
          }
          break;
        }
        case "minute": {
          switch (part.value) {
            case "numeric": {
              value = /^\d{1,2}/.exec(string2)?.[0];
              length = value?.length;
              break;
            }
            case "2-digit": {
              value = /^\d{2}/.exec(string2)?.[0];
              length = value?.length;
              break;
            }
            default:
              throw new Error(
                `ParserError: value "${part.value}" is not supported`
              );
          }
          break;
        }
        case "second": {
          switch (part.value) {
            case "numeric": {
              value = /^\d{1,2}/.exec(string2)?.[0];
              length = value?.length;
              break;
            }
            case "2-digit": {
              value = /^\d{2}/.exec(string2)?.[0];
              length = value?.length;
              break;
            }
            default:
              throw new Error(
                `ParserError: value "${part.value}" is not supported`
              );
          }
          break;
        }
        case "fractionalSecond": {
          value = new RegExp(`^\\d{${part.value}}`).exec(string2)?.[0];
          length = value?.length;
          break;
        }
        case "timeZoneName": {
          value = part.value;
          length = value?.length;
          break;
        }
        case "dayPeriod": {
          value = /^[AP](?:\.M\.|M\.?)/i.exec(string2)?.[0];
          switch (value.toUpperCase()) {
            case "AM":
              value = "AM";
              length = 2;
              break;
            case "AM.":
              value = "AM";
              length = 3;
              break;
            case "A.M.":
              value = "AM";
              length = 4;
              break;
            case "PM":
              value = "PM";
              length = 2;
              break;
            case "PM.":
              value = "PM";
              length = 3;
              break;
            case "P.M.":
              value = "PM";
              length = 4;
              break;
            default:
              throw new Error(`DayPeriod '${value}' is not supported.`);
          }
          break;
        }
        case "literal": {
          if (!string2.startsWith(part.value)) {
            throw new Error(
              `Literal "${part.value}" not found "${string2.slice(0, 25)}"`
            );
          }
          value = part.value;
          length = value?.length;
          break;
        }
        default:
          throw new Error(
            `Cannot format the date, the value (${part.value}) of the type (${part.type}) is given`
          );
      }
      if (!value) {
        throw new Error(
          `Cannot format value: The value is not valid for part { ${type4} ${value} } ${string2.slice(
            0,
            25
          )}`
        );
      }
      parts.push({ type: type4, value });
      string2 = string2.slice(length);
    }
    if (string2.length) {
      throw new Error(
        `datetime string was not fully parsed! ${string2.slice(0, 25)}`
      );
    }
    return parts;
  }
  partsToDate(parts) {
    parts = sortDateTimeFormatParts(parts);
    const date = /* @__PURE__ */ new Date();
    const utc = parts.find(
      (part) => part.type === "timeZoneName" && part.value === "UTC"
    );
    const dayPart = parts.find((part) => part.type === "day");
    utc ? date.setUTCHours(0, 0, 0, 0) : date.setHours(0, 0, 0, 0);
    for (const part of parts) {
      switch (part.type) {
        case "year": {
          const value = Number(part.value.padStart(4, "20"));
          utc ? date.setUTCFullYear(value) : date.setFullYear(value);
          break;
        }
        case "month": {
          const value = Number(part.value) - 1;
          if (dayPart) {
            utc ? date.setUTCMonth(value, Number(dayPart.value)) : date.setMonth(value, Number(dayPart.value));
          } else {
            utc ? date.setUTCMonth(value) : date.setMonth(value);
          }
          break;
        }
        case "day": {
          const value = Number(part.value);
          utc ? date.setUTCDate(value) : date.setDate(value);
          break;
        }
        case "hour": {
          let value = Number(part.value);
          const dayPeriod = parts.find(
            (part2) => part2.type === "dayPeriod"
          );
          if (dayPeriod) {
            switch (dayPeriod.value.toUpperCase()) {
              case "AM":
              case "AM.":
              case "A.M.":
                break;
              case "PM":
              case "PM.":
              case "P.M.":
                value += 12;
                break;
              default:
                throw new Error(
                  `dayPeriod '${dayPeriod.value}' is not supported.`
                );
            }
          }
          utc ? date.setUTCHours(value) : date.setHours(value);
          break;
        }
        case "minute": {
          const value = Number(part.value);
          utc ? date.setUTCMinutes(value) : date.setMinutes(value);
          break;
        }
        case "second": {
          const value = Number(part.value);
          utc ? date.setUTCSeconds(value) : date.setSeconds(value);
          break;
        }
        case "fractionalSecond": {
          const value = Number(part.value);
          utc ? date.setUTCMilliseconds(value) : date.setMilliseconds(value);
          break;
        }
      }
    }
    return date;
  }
  parse(string2) {
    const parts = this.formatToParts(string2);
    return this.partsToDate(parts);
  }
};

// https://jsr.io/@std/datetime/0.225.4/parse.ts
function parse15(dateString, formatString) {
  const formatter = new DateTimeFormatter(formatString);
  return formatter.parse(dateString);
}

// https://cdn.skypack.dev/-/dayjs@v1.8.21-JKEGsMPHprCsv2aIquZ7/dist=es2019,mode=imports/optimized/dayjs.js
var commonjsGlobal3 = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
function createCommonjsModule3(fn, basedir, module2) {
  return module2 = {
    path: basedir,
    exports: {},
    require: function(path3, base3) {
      return commonjsRequire3(path3, base3 === void 0 || base3 === null ? module2.path : base3);
    }
  }, fn(module2, module2.exports), module2.exports;
}
function commonjsRequire3() {
  throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs");
}
var dayjs_min = createCommonjsModule3(function(module2, exports23) {
  !(function(t5, n5) {
    module2.exports = n5();
  })(commonjsGlobal3, function() {
    var t5 = "millisecond", n5 = "second", e5 = "minute", r5 = "hour", i6 = "day", s5 = "week", u5 = "month", o5 = "quarter", a5 = "year", h5 = /^(\d{4})-?(\d{1,2})-?(\d{0,2})[^0-9]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?.?(\d{1,3})?$/, f5 = /\[([^\]]+)]|Y{2,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g, c6 = function(t22, n22, e22) {
      var r22 = String(t22);
      return !r22 || r22.length >= n22 ? t22 : "" + Array(n22 + 1 - r22.length).join(e22) + t22;
    }, d4 = { s: c6, z: function(t22) {
      var n22 = -t22.utcOffset(), e22 = Math.abs(n22), r22 = Math.floor(e22 / 60), i22 = e22 % 60;
      return (n22 <= 0 ? "+" : "-") + c6(r22, 2, "0") + ":" + c6(i22, 2, "0");
    }, m: function(t22, n22) {
      var e22 = 12 * (n22.year() - t22.year()) + (n22.month() - t22.month()), r22 = t22.clone().add(e22, u5), i22 = n22 - r22 < 0, s22 = t22.clone().add(e22 + (i22 ? -1 : 1), u5);
      return Number(-(e22 + (n22 - r22) / (i22 ? r22 - s22 : s22 - r22)) || 0);
    }, a: function(t22) {
      return t22 < 0 ? Math.ceil(t22) || 0 : Math.floor(t22);
    }, p: function(h22) {
      return { M: u5, y: a5, w: s5, d: i6, D: "date", h: r5, m: e5, s: n5, ms: t5, Q: o5 }[h22] || String(h22 || "").toLowerCase().replace(/s$/, "");
    }, u: function(t22) {
      return t22 === void 0;
    } }, $2 = { name: "en", weekdays: "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"), months: "January_February_March_April_May_June_July_August_September_October_November_December".split("_") }, l6 = "en", m4 = {};
    m4[l6] = $2;
    var y4 = function(t22) {
      return t22 instanceof v4;
    }, M3 = function(t22, n22, e22) {
      var r22;
      if (!t22)
        return l6;
      if (typeof t22 == "string")
        m4[t22] && (r22 = t22), n22 && (m4[t22] = n22, r22 = t22);
      else {
        var i22 = t22.name;
        m4[i22] = t22, r22 = i22;
      }
      return e22 || (l6 = r22), r22;
    }, g3 = function(t22, n22, e22) {
      if (y4(t22))
        return t22.clone();
      var r22 = n22 ? typeof n22 == "string" ? { format: n22, pl: e22 } : n22 : {};
      return r22.date = t22, new v4(r22);
    }, D4 = d4;
    D4.l = M3, D4.i = y4, D4.w = function(t22, n22) {
      return g3(t22, { locale: n22.$L, utc: n22.$u, $offset: n22.$offset });
    };
    var v4 = (function() {
      function c22(t22) {
        this.$L = this.$L || M3(t22.locale, null, true), this.parse(t22);
      }
      var d22 = c22.prototype;
      return d22.parse = function(t22) {
        this.$d = (function(t32) {
          var n22 = t32.date, e22 = t32.utc;
          if (n22 === null)
            return /* @__PURE__ */ new Date(NaN);
          if (D4.u(n22))
            return /* @__PURE__ */ new Date();
          if (n22 instanceof Date)
            return new Date(n22);
          if (typeof n22 == "string" && !/Z$/i.test(n22)) {
            var r22 = n22.match(h5);
            if (r22)
              return e22 ? new Date(Date.UTC(r22[1], r22[2] - 1, r22[3] || 1, r22[4] || 0, r22[5] || 0, r22[6] || 0, r22[7] || 0)) : new Date(r22[1], r22[2] - 1, r22[3] || 1, r22[4] || 0, r22[5] || 0, r22[6] || 0, r22[7] || 0);
          }
          return new Date(n22);
        })(t22), this.init();
      }, d22.init = function() {
        var t22 = this.$d;
        this.$y = t22.getFullYear(), this.$M = t22.getMonth(), this.$D = t22.getDate(), this.$W = t22.getDay(), this.$H = t22.getHours(), this.$m = t22.getMinutes(), this.$s = t22.getSeconds(), this.$ms = t22.getMilliseconds();
      }, d22.$utils = function() {
        return D4;
      }, d22.isValid = function() {
        return !(this.$d.toString() === "Invalid Date");
      }, d22.isSame = function(t22, n22) {
        var e22 = g3(t22);
        return this.startOf(n22) <= e22 && e22 <= this.endOf(n22);
      }, d22.isAfter = function(t22, n22) {
        return g3(t22) < this.startOf(n22);
      }, d22.isBefore = function(t22, n22) {
        return this.endOf(n22) < g3(t22);
      }, d22.$g = function(t22, n22, e22) {
        return D4.u(t22) ? this[n22] : this.set(e22, t22);
      }, d22.year = function(t22) {
        return this.$g(t22, "$y", a5);
      }, d22.month = function(t22) {
        return this.$g(t22, "$M", u5);
      }, d22.day = function(t22) {
        return this.$g(t22, "$W", i6);
      }, d22.date = function(t22) {
        return this.$g(t22, "$D", "date");
      }, d22.hour = function(t22) {
        return this.$g(t22, "$H", r5);
      }, d22.minute = function(t22) {
        return this.$g(t22, "$m", e5);
      }, d22.second = function(t22) {
        return this.$g(t22, "$s", n5);
      }, d22.millisecond = function(n22) {
        return this.$g(n22, "$ms", t5);
      }, d22.unix = function() {
        return Math.floor(this.valueOf() / 1e3);
      }, d22.valueOf = function() {
        return this.$d.getTime();
      }, d22.startOf = function(t22, o22) {
        var h22 = this, f22 = !!D4.u(o22) || o22, c32 = D4.p(t22), d32 = function(t32, n22) {
          var e22 = D4.w(h22.$u ? Date.UTC(h22.$y, n22, t32) : new Date(h22.$y, n22, t32), h22);
          return f22 ? e22 : e22.endOf(i6);
        }, $22 = function(t32, n22) {
          return D4.w(h22.toDate()[t32].apply(h22.toDate(), (f22 ? [0, 0, 0, 0] : [23, 59, 59, 999]).slice(n22)), h22);
        }, l22 = this.$W, m22 = this.$M, y22 = this.$D, M22 = "set" + (this.$u ? "UTC" : "");
        switch (c32) {
          case a5:
            return f22 ? d32(1, 0) : d32(31, 11);
          case u5:
            return f22 ? d32(1, m22) : d32(0, m22 + 1);
          case s5:
            var g22 = this.$locale().weekStart || 0, v22 = (l22 < g22 ? l22 + 7 : l22) - g22;
            return d32(f22 ? y22 - v22 : y22 + (6 - v22), m22);
          case i6:
          case "date":
            return $22(M22 + "Hours", 0);
          case r5:
            return $22(M22 + "Minutes", 1);
          case e5:
            return $22(M22 + "Seconds", 2);
          case n5:
            return $22(M22 + "Milliseconds", 3);
          default:
            return this.clone();
        }
      }, d22.endOf = function(t22) {
        return this.startOf(t22, false);
      }, d22.$set = function(s22, o22) {
        var h22, f22 = D4.p(s22), c32 = "set" + (this.$u ? "UTC" : ""), d32 = (h22 = {}, h22[i6] = c32 + "Date", h22.date = c32 + "Date", h22[u5] = c32 + "Month", h22[a5] = c32 + "FullYear", h22[r5] = c32 + "Hours", h22[e5] = c32 + "Minutes", h22[n5] = c32 + "Seconds", h22[t5] = c32 + "Milliseconds", h22)[f22], $22 = f22 === i6 ? this.$D + (o22 - this.$W) : o22;
        if (f22 === u5 || f22 === a5) {
          var l22 = this.clone().set("date", 1);
          l22.$d[d32]($22), l22.init(), this.$d = l22.set("date", Math.min(this.$D, l22.daysInMonth())).toDate();
        } else
          d32 && this.$d[d32]($22);
        return this.init(), this;
      }, d22.set = function(t22, n22) {
        return this.clone().$set(t22, n22);
      }, d22.get = function(t22) {
        return this[D4.p(t22)]();
      }, d22.add = function(t22, o22) {
        var h22, f22 = this;
        t22 = Number(t22);
        var c32 = D4.p(o22), d32 = function(n22) {
          var e22 = g3(f22);
          return D4.w(e22.date(e22.date() + Math.round(n22 * t22)), f22);
        };
        if (c32 === u5)
          return this.set(u5, this.$M + t22);
        if (c32 === a5)
          return this.set(a5, this.$y + t22);
        if (c32 === i6)
          return d32(1);
        if (c32 === s5)
          return d32(7);
        var $22 = (h22 = {}, h22[e5] = 6e4, h22[r5] = 36e5, h22[n5] = 1e3, h22)[c32] || 1, l22 = this.$d.getTime() + t22 * $22;
        return D4.w(l22, this);
      }, d22.subtract = function(t22, n22) {
        return this.add(-1 * t22, n22);
      }, d22.format = function(t22) {
        var n22 = this;
        if (!this.isValid())
          return "Invalid Date";
        var e22 = t22 || "YYYY-MM-DDTHH:mm:ssZ", r22 = D4.z(this), i22 = this.$locale(), s22 = this.$H, u22 = this.$m, o22 = this.$M, a22 = i22.weekdays, h22 = i22.months, c32 = function(t32, r32, i32, s32) {
          return t32 && (t32[r32] || t32(n22, e22)) || i32[r32].substr(0, s32);
        }, d32 = function(t32) {
          return D4.s(s22 % 12 || 12, t32, "0");
        }, $22 = i22.meridiem || function(t32, n32, e32) {
          var r32 = t32 < 12 ? "AM" : "PM";
          return e32 ? r32.toLowerCase() : r32;
        }, l22 = { YY: String(this.$y).slice(-2), YYYY: this.$y, M: o22 + 1, MM: D4.s(o22 + 1, 2, "0"), MMM: c32(i22.monthsShort, o22, h22, 3), MMMM: h22[o22] || h22(this, e22), D: this.$D, DD: D4.s(this.$D, 2, "0"), d: String(this.$W), dd: c32(i22.weekdaysMin, this.$W, a22, 2), ddd: c32(i22.weekdaysShort, this.$W, a22, 3), dddd: a22[this.$W], H: String(s22), HH: D4.s(s22, 2, "0"), h: d32(1), hh: d32(2), a: $22(s22, u22, true), A: $22(s22, u22, false), m: String(u22), mm: D4.s(u22, 2, "0"), s: String(this.$s), ss: D4.s(this.$s, 2, "0"), SSS: D4.s(this.$ms, 3, "0"), Z: r22 };
        return e22.replace(f5, function(t32, n32) {
          return n32 || l22[t32] || r22.replace(":", "");
        });
      }, d22.utcOffset = function() {
        return 15 * -Math.round(this.$d.getTimezoneOffset() / 15);
      }, d22.diff = function(t22, h22, f22) {
        var c32, d32 = D4.p(h22), $22 = g3(t22), l22 = 6e4 * ($22.utcOffset() - this.utcOffset()), m22 = this - $22, y22 = D4.m(this, $22);
        return y22 = (c32 = {}, c32[a5] = y22 / 12, c32[u5] = y22, c32[o5] = y22 / 3, c32[s5] = (m22 - l22) / 6048e5, c32[i6] = (m22 - l22) / 864e5, c32[r5] = m22 / 36e5, c32[e5] = m22 / 6e4, c32[n5] = m22 / 1e3, c32)[d32] || m22, f22 ? y22 : D4.a(y22);
      }, d22.daysInMonth = function() {
        return this.endOf(u5).$D;
      }, d22.$locale = function() {
        return m4[this.$L];
      }, d22.locale = function(t22, n22) {
        if (!t22)
          return this.$L;
        var e22 = this.clone(), r22 = M3(t22, n22, true);
        return r22 && (e22.$L = r22), e22;
      }, d22.clone = function() {
        return D4.w(this.$d, this);
      }, d22.toDate = function() {
        return new Date(this.valueOf());
      }, d22.toJSON = function() {
        return this.isValid() ? this.toISOString() : null;
      }, d22.toISOString = function() {
        return this.$d.toISOString();
      }, d22.toString = function() {
        return this.$d.toUTCString();
      }, c22;
    })();
    return g3.prototype = v4.prototype, g3.extend = function(t22, n22) {
      return t22(n22, v4, g3), g3;
    }, g3.locale = M3, g3.isDayjs = y4, g3.unix = function(t22) {
      return g3(1e3 * t22);
    }, g3.en = m4[l6], g3.Ls = m4, g3;
  });
});
var Ls = dayjs_min.Ls;
var dayjs_default = dayjs_min;
var en = dayjs_min.en;
var extend6 = dayjs_min.extend;
var isDayjs = dayjs_min.isDayjs;
var locale = dayjs_min.locale;
var unix = dayjs_min.unix;

// resources/library/dayjs/plugins/constant.js
var SECONDS_A_MINUTE = 60;
var SECONDS_A_HOUR = SECONDS_A_MINUTE * 60;
var SECONDS_A_DAY = SECONDS_A_HOUR * 24;
var SECONDS_A_WEEK = SECONDS_A_DAY * 7;
var MILLISECONDS_A_SECOND = 1e3;
var MILLISECONDS_A_MINUTE = SECONDS_A_MINUTE * MILLISECONDS_A_SECOND;
var MILLISECONDS_A_HOUR = SECONDS_A_HOUR * MILLISECONDS_A_SECOND;
var MILLISECONDS_A_DAY = SECONDS_A_DAY * MILLISECONDS_A_SECOND;
var MILLISECONDS_A_WEEK = SECONDS_A_WEEK * MILLISECONDS_A_SECOND;
var MS = "millisecond";
var MIN = "minute";
var D3 = "day";
var W2 = "week";
var Y3 = "year";
var FORMAT_DEFAULT = "YYYY-MM-DDTHH:mm:ssZ";

// resources/library/dayjs/plugins/advanced.js
var advanced_default = (o5, c6, d4) => {
  const proto2 = c6.prototype;
  const oldFormat = proto2.format;
  d4.en.ordinal = (number2) => {
    const s5 = ["th", "st", "nd", "rd"];
    const v4 = number2 % 100;
    return `[${number2}${s5[(v4 - 20) % 10] || s5[v4] || s5[0]}]`;
  };
  proto2.format = function(formatStr) {
    const locale2 = this.$locale();
    if (!this.isValid()) {
      return oldFormat.bind(this)(formatStr);
    }
    const utils6 = this.$utils();
    const str3 = formatStr || FORMAT_DEFAULT;
    const result2 = str3.replace(
      /\[([^\]]+)]|Q|wo|ww|w|WW|W|zzz|z|gggg|GGGG|Do|X|x|k{1,2}|S/g,
      (match) => {
        switch (match) {
          case "Q":
            return Math.ceil((this.$M + 1) / 3);
          case "Do":
            return locale2.ordinal(this.$D);
          case "gggg":
            return this.weekYear();
          case "GGGG":
            return this.isoWeekYear();
          case "wo":
            return locale2.ordinal(this.week(), "W");
          // W for week
          case "w":
          case "ww":
            return utils6.s(this.week(), match === "w" ? 1 : 2, "0");
          case "W":
          case "WW":
            return utils6.s(this.isoWeek(), match === "W" ? 1 : 2, "0");
          case "k":
          case "kk":
            return utils6.s(
              String(this.$H === 0 ? 24 : this.$H),
              match === "k" ? 1 : 2,
              "0"
            );
          case "X":
            return Math.floor(this.$d.getTime() / 1e3);
          case "x":
            return this.$d.getTime();
          case "z":
            return `[${this.offsetName()}]`;
          case "zzz":
            return `[${this.offsetName("long")}]`;
          default:
            return match;
        }
      }
    );
    return oldFormat.bind(this)(result2);
  };
};

// resources/library/dayjs/plugins/timezone.js
var typeToPos = {
  year: 0,
  month: 1,
  day: 2,
  hour: 3,
  minute: 4,
  second: 5
};
var dtfCache = {};
var getDateTimeFormat = (timezone, options = {}) => {
  const timeZoneName = options.timeZoneName || "short";
  const key = `${timezone}|${timeZoneName}`;
  let dtf = dtfCache[key];
  if (!dtf) {
    dtf = new Intl.DateTimeFormat("en-US", {
      hour12: false,
      timeZone: timezone,
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
      second: "2-digit",
      timeZoneName
    });
    dtfCache[key] = dtf;
  }
  return dtf;
};
var timezone_default = (o5, c6, d4) => {
  let defaultTimezone;
  const makeFormatParts = (timestamp3, timezone, options = {}) => {
    const date = new Date(timestamp3);
    const dtf = getDateTimeFormat(timezone, options);
    return dtf.formatToParts(date);
  };
  const tzOffset = (timestamp3, timezone) => {
    const formatResult = makeFormatParts(timestamp3, timezone);
    const filled = [];
    for (let i6 = 0; i6 < formatResult.length; i6 += 1) {
      const { type: type4, value } = formatResult[i6];
      const pos = typeToPos[type4];
      if (pos >= 0) {
        filled[pos] = parseInt(value, 10);
      }
    }
    const hour = filled[3];
    const fixedHour = hour === 24 ? 0 : hour;
    const utcString = `${filled[0]}-${filled[1]}-${filled[2]} ${fixedHour}:${filled[4]}:${filled[5]}:000`;
    const utcTs = d4.utc(utcString).valueOf();
    let asTS = +timestamp3;
    const over = asTS % 1e3;
    asTS -= over;
    return (utcTs - asTS) / (60 * 1e3);
  };
  const fixOffset = (localTS, o0, tz) => {
    let utcGuess = localTS - o0 * 60 * 1e3;
    const o22 = tzOffset(utcGuess, tz);
    if (o0 === o22) {
      return [utcGuess, o0];
    }
    utcGuess -= (o22 - o0) * 60 * 1e3;
    const o32 = tzOffset(utcGuess, tz);
    if (o22 === o32) {
      return [utcGuess, o22];
    }
    return [localTS - Math.min(o22, o32) * 60 * 1e3, Math.max(o22, o32)];
  };
  const proto2 = c6.prototype;
  proto2.tz = function(timezone = defaultTimezone, keepLocalTime) {
    const oldOffset = this.utcOffset();
    const date = this.toDate();
    const target = date.toLocaleString("en-US", { timeZone: timezone });
    const diff3 = Math.round((date - new Date(target)) / 1e3 / 60);
    let ins = d4(target).$set(MS, this.$ms).utcOffset(-Math.round(date.getTimezoneOffset() / 15) * 15 - diff3, true);
    if (keepLocalTime) {
      const newOffset = ins.utcOffset();
      ins = ins.add(oldOffset - newOffset, MIN);
    }
    ins.$x.$timezone = timezone;
    return ins;
  };
  proto2.offsetName = function(type4) {
    const zone = this.$x?.$timezone || d4.tz.guess();
    const result2 = makeFormatParts(this.valueOf(), zone, {
      timeZoneName: type4
    }).find((m4) => m4.type.toLowerCase() === "timezonename");
    return result2 && result2.value;
  };
  const oldStartOf = proto2.startOf;
  proto2.startOf = function(units2, startOf) {
    if (!this.$x || !this.$x.$timezone) {
      return oldStartOf.call(this, units2, startOf);
    }
    const withoutTz = d4(this.format("YYYY-MM-DD HH:mm:ss:SSS"));
    const startOfWithoutTz = oldStartOf.call(withoutTz, units2, startOf);
    return startOfWithoutTz.tz(this.$x.$timezone, true);
  };
  d4.tz = function(input, arg1, arg2) {
    const parseFormat2 = arg2 && arg1;
    const timezone = arg2 || arg1 || defaultTimezone;
    const previousOffset = tzOffset(+d4(), timezone);
    if (typeof input !== "string") {
      return d4(input).tz(timezone);
    }
    const localTs = d4.utc(input, parseFormat2).valueOf();
    const [targetTs, targetOffset] = fixOffset(
      localTs,
      previousOffset,
      timezone
    );
    const ins = d4(targetTs).utcOffset(targetOffset);
    ins.$x.$timezone = timezone;
    return ins;
  };
  d4.tz.guess = function() {
    return Intl.DateTimeFormat().resolvedOptions().timeZone;
  };
  d4.tz.setDefault = function(timezone) {
    defaultTimezone = timezone;
  };
};

// resources/library/dayjs/plugins/utc.js
var REGEX_VALID_OFFSET_FORMAT = /[+-]\d\d(?::?\d\d)?/g;
var REGEX_OFFSET_HOURS_MINUTES_FORMAT = /([+-]|\d\d)/g;
function offsetFromString(value = "") {
  const offset3 = value.match(REGEX_VALID_OFFSET_FORMAT);
  if (!offset3) {
    return null;
  }
  const [indicator, hoursOffset, minutesOffset] = `${offset3[0]}`.match(
    REGEX_OFFSET_HOURS_MINUTES_FORMAT
  ) || ["-", 0, 0];
  const totalOffsetInMinutes = +hoursOffset * 60 + +minutesOffset;
  if (totalOffsetInMinutes === 0) {
    return 0;
  }
  return indicator === "+" ? totalOffsetInMinutes : -totalOffsetInMinutes;
}
var utc_default = (option, Dayjs, dayjs) => {
  const proto2 = Dayjs.prototype;
  dayjs.utc = function(date) {
    const cfg = { date, utc: true, args: arguments };
    return new Dayjs(cfg);
  };
  proto2.utc = function(keepLocalTime) {
    const ins = dayjs(this.toDate(), { locale: this.$L, utc: true });
    if (keepLocalTime) {
      return ins.add(this.utcOffset(), MIN);
    }
    return ins;
  };
  proto2.local = function() {
    return dayjs(this.toDate(), { locale: this.$L, utc: false });
  };
  const oldParse = proto2.parse;
  proto2.parse = function(cfg) {
    if (cfg.utc) {
      this.$u = true;
    }
    if (!this.$utils().u(cfg.$offset)) {
      this.$offset = cfg.$offset;
    }
    oldParse.call(this, cfg);
  };
  const oldInit = proto2.init;
  proto2.init = function() {
    if (this.$u) {
      const { $d } = this;
      this.$y = $d.getUTCFullYear();
      this.$M = $d.getUTCMonth();
      this.$D = $d.getUTCDate();
      this.$W = $d.getUTCDay();
      this.$H = $d.getUTCHours();
      this.$m = $d.getUTCMinutes();
      this.$s = $d.getUTCSeconds();
      this.$ms = $d.getUTCMilliseconds();
    } else {
      oldInit.call(this);
    }
  };
  const oldUtcOffset = proto2.utcOffset;
  proto2.utcOffset = function(input, keepLocalTime) {
    const { u: u5 } = this.$utils();
    if (u5(input)) {
      if (this.$u) {
        return 0;
      }
      if (!u5(this.$offset)) {
        return this.$offset;
      }
      return oldUtcOffset.call(this);
    }
    if (typeof input === "string") {
      input = offsetFromString(input);
      if (input === null) {
        return this;
      }
    }
    const offset3 = Math.abs(input) <= 16 ? input * 60 : input;
    let ins = this;
    if (keepLocalTime) {
      ins.$offset = offset3;
      ins.$u = input === 0;
      return ins;
    }
    if (input !== 0) {
      const localTimezoneOffset = this.$u ? this.toDate().getTimezoneOffset() : -1 * this.utcOffset();
      ins = this.local().add(offset3 + localTimezoneOffset, MIN);
      ins.$offset = offset3;
      ins.$x.$localOffset = localTimezoneOffset;
    } else {
      ins = this.utc();
    }
    return ins;
  };
  const oldFormat = proto2.format;
  const UTC_FORMAT_DEFAULT = "YYYY-MM-DDTHH:mm:ss[Z]";
  proto2.format = function(formatStr) {
    const str3 = formatStr || (this.$u ? UTC_FORMAT_DEFAULT : "");
    return oldFormat.call(this, str3);
  };
  proto2.valueOf = function() {
    const addedOffset = !this.$utils().u(this.$offset) ? this.$offset + (this.$x.$localOffset || this.$d.getTimezoneOffset()) : 0;
    return this.$d.valueOf() - addedOffset * MILLISECONDS_A_MINUTE;
  };
  proto2.isUTC = function() {
    return !!this.$u;
  };
  proto2.toISOString = function() {
    return this.toDate().toISOString();
  };
  proto2.toString = function() {
    return this.toDate().toUTCString();
  };
  const oldToDate = proto2.toDate;
  proto2.toDate = function(type4) {
    if (type4 === "s" && this.$offset) {
      return dayjs(this.format("YYYY-MM-DD HH:mm:ss:SSS")).toDate();
    }
    return oldToDate.call(this);
  };
  const oldDiff = proto2.diff;
  proto2.diff = function(input, units2, float4) {
    if (input && this.$u === input.$u) {
      return oldDiff.call(this, input, units2, float4);
    }
    const localThis = this.local();
    const localInput = dayjs(input).local();
    return oldDiff.call(localThis, localInput, units2, float4);
  };
};

// resources/library/dayjs/plugins/isoweek.js
var isoWeekPrettyUnit = "isoweek";
var isoweek_default = (o5, c6, d4) => {
  const getYearFirstThursday = (year, isUtc) => {
    const yearFirstDay = (isUtc ? d4.utc : d4)().year(year).startOf(Y3);
    let addDiffDays = 4 - yearFirstDay.isoWeekday();
    if (yearFirstDay.isoWeekday() > 4) {
      addDiffDays += 7;
    }
    return yearFirstDay.add(addDiffDays, D3);
  };
  const getCurrentWeekThursday = (ins) => ins.add(4 - ins.isoWeekday(), D3);
  const proto2 = c6.prototype;
  proto2.isoWeekYear = function() {
    const nowWeekThursday = getCurrentWeekThursday(this);
    return nowWeekThursday.year();
  };
  proto2.isoWeek = function(week) {
    if (!this.$utils().u(week)) {
      return this.add((week - this.isoWeek()) * 7, D3);
    }
    const nowWeekThursday = getCurrentWeekThursday(this);
    const diffWeekThursday = getYearFirstThursday(this.isoWeekYear(), this.$u);
    return nowWeekThursday.diff(diffWeekThursday, W2) + 1;
  };
  proto2.isoWeekday = function(week) {
    if (!this.$utils().u(week)) {
      return this.day(this.day() % 7 ? week : week - 7);
    }
    return this.day() || 7;
  };
  const oldStartOf = proto2.startOf;
  proto2.startOf = function(units2, startOf) {
    const utils6 = this.$utils();
    const isStartOf = !utils6.u(startOf) ? startOf : true;
    const unit = utils6.p(units2);
    if (unit === isoWeekPrettyUnit) {
      return isStartOf ? this.date(this.date() - (this.isoWeekday() - 1)).startOf("day") : this.date(this.date() - 1 - (this.isoWeekday() - 1) + 7).endOf("day");
    }
    return oldStartOf.bind(this)(units2, startOf);
  };
};

// resources/library/dayjs/plugins/weekofyear.js
var weekofyear_default = (o5, c6, d4) => {
  const proto2 = c6.prototype;
  proto2.week = function(week = null) {
    if (week !== null) {
      return this.add((week - this.week()) * 7, D3);
    }
    const yearStart = this.$locale().yearStart || 1;
    if (this.month() === 11 && this.date() > 25) {
      const nextYearStartDay = d4(this).startOf(Y3).add(1, Y3).date(yearStart);
      const thisEndOfWeek = d4(this).endOf(W2);
      if (nextYearStartDay.isBefore(thisEndOfWeek)) {
        return 1;
      }
    }
    const yearStartDay = d4(this).startOf(Y3).date(yearStart);
    const yearStartWeek = yearStartDay.startOf(W2).subtract(1, MS);
    const diffInWeek = this.diff(yearStartWeek, W2, true);
    if (diffInWeek < 0) {
      return d4(this).startOf("week").week();
    }
    return Math.ceil(diffInWeek);
  };
  proto2.weeks = function(week = null) {
    return this.week(week);
  };
};

// resources/library/dayjs/plugins/weekyear.js
var weekyear_default = (o5, c6) => {
  const proto2 = c6.prototype;
  proto2.weekYear = function() {
    const month = this.month();
    const weekOfYear = this.week();
    const year = this.year();
    if (weekOfYear === 1 && month === 11) {
      return year + 1;
    }
    if (month === 0 && weekOfYear >= 52) {
      return year - 1;
    }
    return year;
  };
};

// core/date.ts
init_fs();
init_path();
init_resources2();
var kLastModified = "last-modified";
var kToday = "today";
var kNow = "now";
function today() {
  const today2 = /* @__PURE__ */ new Date();
  today2.setHours(0);
  today2.setMinutes(0);
  today2.setSeconds(0);
  today2.setMilliseconds(0);
  return today2;
}
function resolveAndFormatDate(input, date, format14) {
  const resolveDate2 = (date2) => {
    if (date2) {
      if (typeof date2 === "string") {
        return {
          value: date2,
          format: format14 || "iso"
        };
      } else if (typeof date2 === "object") {
        const schemaDate = date2;
        return {
          value: schemaDate.value,
          format: schemaDate.format || format14 || "iso"
        };
      }
    } else {
      return void 0;
    }
  };
  const resolvedDate = resolveDate2(date);
  if (resolvedDate) {
    if (isSpecialDate(resolvedDate.value)) {
      resolvedDate.value = parseSpecialDate(
        input,
        resolvedDate.value
      );
    }
    const parsed = parsePandocDate(resolvedDate.value);
    return formatDate(
      parsed,
      resolvedDate.format
    );
  }
}
function resolveDate(input, val) {
  if (isSpecialDate(val)) {
    return parseSpecialDate(input, val);
  } else {
    return val;
  }
}
function isSpecialDate(val) {
  return val === kLastModified || val === kToday || val === kNow;
}
function parseSpecialDate(input, val) {
  if (val === kLastModified) {
    if (!Array.isArray(input)) {
      input = [input];
    }
    let lastModifiedTs = 0;
    for (const inp of input) {
      const stat = Deno.statSync(inp);
      if (stat.mtime) {
        lastModifiedTs = Math.max(lastModifiedTs, stat.mtime.getTime());
      }
    }
    return formatDate(new Date(lastModifiedTs), "YYYY-MM-DDTHH:mm:ssZ");
  } else if (val === kToday) {
    return formatDate(today(), "YYYY-MM-DDTHH:mm:ssZ");
  } else if (val === kNow) {
    return formatDate(/* @__PURE__ */ new Date(), "YYYY-MM-DDTHH:mm:ssZ");
  } else {
    return val;
  }
}
function initDayJsPlugins() {
  dayjs_default.extend(utc_default);
  dayjs_default.extend(timezone_default);
  dayjs_default.extend(isoweek_default);
  dayjs_default.extend(weekyear_default);
  dayjs_default.extend(weekofyear_default);
  dayjs_default.extend(advanced_default);
}
async function setDateLocale(localeStr) {
  localeStr = localeStr.toLowerCase();
  if (localeStr !== dayjs_default.locale()) {
    const findLocale = () => {
      const locales = [localeStr];
      if (localeStr.includes("-")) {
        locales.push(localeStr.split("-")[0]);
      }
      for (const locale3 of locales) {
        const path3 = resourcePath(
          `library/dayjs/locale/${locale3}.js`
        );
        if (existsSync2(path3)) {
          return {
            locale: locale3,
            path: path3
          };
        }
      }
      return void 0;
    };
    const locale2 = findLocale();
    if (locale2) {
      const localeUrl = toFileUrl4(locale2.path).href;
      const localeModule = await import(localeUrl);
      dayjs_default.locale(localeModule.default, null, true);
      dayjs_default.locale(locale2.locale);
    }
  }
}
var formatDate = (date, dateStyle, timeStyle) => {
  if (dateStyle === "full" || dateStyle === "long" || dateStyle === "medium" || dateStyle === "short") {
    const options = {
      dateStyle
    };
    if (timeStyle) {
      options.timeStyle = timeStyle;
    }
    return date.toLocaleString(dayjs_default.locale(), options);
  } else {
    if (dateStyle === "iso") dateStyle = "YYYY-MM-DD";
    return dayjs_default(date).format(dateStyle);
  }
};
var parsePandocDate = (dateRaw) => {
  const formats2 = [
    "MM/dd/yyyy",
    "MM-dd-yyyy",
    "MM/dd/yy",
    "MM-dd-yy",
    "yyyy-MM-dd",
    "dd MM yyyy",
    "MM dd, yyyy"
  ];
  const parseFormat2 = (dateStr) => {
    for (const format14 of formats2) {
      try {
        const date = parse15(dateStr, format14);
        return date;
      } catch {
      }
    }
    try {
      const formats3 = moment_guess_default(dateRaw);
      if (formats3) {
        try {
          const format14 = Array.isArray(formats3) ? formats3[0] : formats3;
          const date = dayjs_default(dateStr, format14);
          return date.toDate();
        } catch {
        }
      }
    } catch {
    }
    try {
      return new Date(dateStr);
    } catch {
      return void 0;
    }
  };
  return parseFormat2(dateRaw);
};

// format/html/format-html-math.ts
function katexPostProcessor() {
  return (doc) => {
    const katexScript2 = doc.querySelector(`script[src$="katex.min.js"]`);
    const katexCss = doc.querySelector(`link[href$="katex.min.css"]`);
    if (katexScript2 && katexCss) {
      katexScript2.removeAttribute("defer");
      const katexBefore = doc.createElement("script");
      katexBefore.innerText = "window.backupDefine = window.define; window.define = undefined;";
      katexScript2.parentNode?.insertBefore(katexBefore, katexScript2);
      const katexAfter = doc.createElement("script");
      katexAfter.innerText = "window.define = window.backupDefine; window.backupDefine = undefined;";
      katexCss?.parentNode?.insertBefore(
        katexAfter,
        katexCss
      );
    }
    return Promise.resolve(kHtmlEmptyPostProcessResult);
  };
}

// command/render/pandoc-dependencies-html.ts
init_path();
init_lodash();
init_deno_dom();
init_path2();
init_types5();
init_constants6();
init_text();
init_copy5();

// command/render/pandoc-dependencies.ts
init_file();
async function appendDependencies(dependenciesFile, dependencies) {
  const dependencyLines = [];
  for (const dependency of dependencies) {
    dependencyLines.push(
      JSON.stringify(dependency)
    );
  }
  if (dependencyLines.length > 0) {
    await appendTextFile(
      dependenciesFile,
      `${dependencyLines.join("\n")}
`
    );
  }
}

// command/render/pandoc-dependencies-html.ts
init_css();
init_fs();
await init_project_shared();
init_hash2();
init_safe_clone_deep();
async function writeDependencies(dependenciesFile, extras) {
  if (extras.html?.[kDependencies]) {
    const dependencies = extras.html[kDependencies].map((dep) => {
      return {
        type: "html",
        content: dep
      };
    });
    await appendDependencies(dependenciesFile, dependencies);
  }
}
function readAndInjectDependencies(dependenciesFile, inputDir, libDir, doc, project) {
  const dependencyJsonStream = Deno.readTextFileSync(dependenciesFile);
  const htmlDependencies = [];
  const htmlAttachments = [];
  lines(dependencyJsonStream).forEach((json3) => {
    if (json3) {
      const dependency = JSON.parse(json3);
      if (dependency.type === "html") {
        htmlDependencies.push(dependency.content);
      } else if (dependency.type === "html-attachment") {
        htmlAttachments.push(dependency);
      }
    }
  });
  const injectedDependencies = [];
  if (htmlDependencies.length > 0) {
    const injector = domDependencyInjector(doc);
    const injected2 = processHtmlDependencies(
      htmlDependencies,
      inputDir,
      libDir,
      injector,
      project
    );
    injectedDependencies.push(...injected2);
    injector.finalizeInjection();
  }
  if (htmlAttachments.length > 0) {
    for (const attachment of htmlAttachments) {
      const parentDependency = injectedDependencies.find((dep) => {
        return dep.name === attachment.content.name;
      });
      if (parentDependency) {
        const directoryInfo = targetDirectoryInfo(
          inputDir,
          libDir,
          parentDependency
        );
        copyDependencyFile(
          attachment.content.file,
          directoryInfo.absolute,
          !!parentDependency.external
        );
      }
    }
  }
  const relocateScripts = doc.querySelectorAll("script[data-relocate-top]");
  if (relocateScripts.length > 0) {
    const nextSiblingEl = doc.querySelector("head script:first-of-type");
    if (nextSiblingEl) {
      for (const relocateScript of relocateScripts) {
        relocateScript.removeAttribute("data-relocate-top");
        nextSiblingEl.parentElement?.insertBefore(
          relocateScript,
          nextSiblingEl
        );
      }
    }
  }
  return Promise.resolve({
    resources: [],
    supporting: []
  });
}
function resolveDependencies(extras, inputDir, libDir, temp, project) {
  extras = safeCloneDeep(extras);
  const lines2 = [];
  const afterBodyLines = [];
  if (extras.html?.[kDependencies]) {
    const injector = lineDependencyInjector(lines2, afterBodyLines);
    processHtmlDependencies(
      extras.html[kDependencies],
      inputDir,
      libDir,
      injector,
      project
    );
    injector.finalizeInjection();
    delete extras.html?.[kDependencies];
    const dependenciesHead = temp.createFile({
      prefix: "dependencies",
      suffix: ".html"
    });
    Deno.writeTextFileSync(dependenciesHead, lines2.join("\n"));
    extras[kIncludeInHeader] = [dependenciesHead].concat(
      extras[kIncludeInHeader] || []
    );
    if (afterBodyLines.length > 0) {
      const dependenciesAfter = temp.createFile({
        prefix: "dependencies-after",
        suffix: ".html"
      });
      Deno.writeTextFileSync(dependenciesAfter, afterBodyLines.join("\n"));
      extras[kIncludeAfterBody] = [dependenciesAfter].concat(
        extras[kIncludeAfterBody] || []
      );
    }
  }
  return extras;
}
function processHtmlDependencies(dependencies, inputDir, libDir, injector, project) {
  const copiedDependencies = [];
  for (const dependency of dependencies) {
    if (copiedDependencies.find((copiedDep) => {
      return copiedDep.name === dependency.name;
    })) {
      continue;
    }
    const directoryInfo = targetDirectoryInfo(
      inputDir,
      libDir,
      dependency
    );
    const copyFile3 = (file, attribs, afterBody, inject2) => {
      copyDependencyFile(
        file,
        directoryInfo.absolute,
        dependency.external || false
      );
      if (inject2) {
        const href = join4(directoryInfo.relative, file.name);
        inject2(href, attribs, afterBody);
      }
    };
    if (dependency.scripts) {
      dependency.scripts.forEach(
        (script) => copyFile3(
          script,
          script.attribs,
          script.afterBody,
          injector.injectScript
        )
      );
    }
    if (dependency.stylesheets) {
      dependency.stylesheets.forEach((stylesheet) => {
        copyFile3(
          stylesheet,
          stylesheet.attribs,
          stylesheet.afterBody,
          injector.injectStyle
        );
      });
    }
    if (dependency.serviceworkers) {
      dependency.serviceworkers.forEach((serviceWorker) => {
        const resolveDestination = (worker, inputDir2, project2) => {
          if (!worker.destination) {
            if (project2) {
              worker.destination = `/${basename4(worker.source)}`;
            } else {
              worker.destination = `${basename4(worker.source)}`;
            }
          }
          if (worker.destination.startsWith("/")) {
            if (project2) {
              const projectDir = projectOutputDir(project2);
              return join4(projectDir, worker.destination.slice(1));
            } else {
              throw new Error(
                "A service worker is being provided with a project relative destination path but no valid Quarto project was found."
              );
            }
          } else {
            return join4(inputDir2, worker.destination);
          }
        };
        const destinationFile = resolveDestination(
          serviceWorker,
          inputDir,
          project
        );
        const destinationDir = dirname4(destinationFile);
        ensureDirSync(destinationDir);
        copyFileIfNewer(
          serviceWorker.source,
          destinationFile
        );
      });
    }
    if (dependency.head) {
      injector.injectHtml(dependency.head);
    }
    if (dependency.links) {
      dependency.links.forEach((link2) => {
        injector.injectLink(link2.href, link2.rel, link2.type);
      });
    }
    if (dependency.meta) {
      injector.injectMeta(dependency.meta);
    }
    if (dependency.resources) {
      dependency.resources.forEach((resource) => copyFile3(resource));
    }
    copiedDependencies.push(dependency);
  }
  return copiedDependencies;
}
function copyDependencyFile(file, targetDir, external) {
  const targetPath = join4(targetDir, file.name);
  ensureDirSync(dirname4(targetPath));
  copyFileIfNewer(file.path, targetPath);
  if (external && isCssFile(file.path)) {
    processCssFile(dirname4(file.path), targetPath);
  }
}
function targetDirectoryInfo(inputDir, libDir, dependency) {
  const targetLibDir = dependency.external ? join4(libDir, "quarto-contrib") : libDir;
  const dir = dependency.version ? `${dependency.name}-${dependency.version}` : dependency.name;
  const relativeTargetDir = join4(targetLibDir, dir);
  const absoluteTargetDir = join4(inputDir, relativeTargetDir);
  return {
    absolute: absoluteTargetDir,
    relative: relativeTargetDir
  };
}
function processCssFile(srcDir, file) {
  const css = Deno.readTextFileSync(file);
  const destCss = fixupCssReferences(css, (ref3) => {
    const refPath = join4(srcDir, ref3);
    if (safeExistsSync(refPath)) {
      const refDir = dirname4(ref3);
      const targetRef = refDir && refDir !== "." && refDir.includes("..") ? join4(insecureHash(dirname4(ref3)), basename4(ref3)) : ref3;
      const refDestPath = join4(dirname4(file), targetRef);
      copyFileIfNewer(refPath, refDestPath);
      return pathWithForwardSlashes(targetRef);
    } else {
      return ref3;
    }
  });
  if (destCss !== css) {
    Deno.writeTextFileSync(file, destCss);
  }
}
var kDependencyTarget = "htmldependencies:E3FAD763";
function domDependencyInjector(doc) {
  const findTargetComment = () => {
    for (const node of doc.head.childNodes) {
      if (node.nodeType === 8 /* COMMENT_NODE */) {
        if (node.textContent && node.textContent.trim() === kDependencyTarget) {
          return node;
        }
      }
    }
    return doc.head.firstChild;
  };
  const targetComment = findTargetComment();
  const injectEl = (el, attribs, afterBody) => {
    if (attribs) {
      for (const key of Object.keys(attribs)) {
        el.setAttribute(key, attribs[key]);
      }
    }
    if (!afterBody) {
      doc.head.insertBefore(doc.createTextNode("\n"), targetComment);
      doc.head.insertBefore(el, targetComment);
    } else {
      doc.body.appendChild(el);
      doc.body.appendChild(doc.createTextNode("\n"));
    }
  };
  const injectScript = (href, attribs, afterBody) => {
    const scriptEl = doc.createElement("script");
    scriptEl.setAttribute("src", pathWithForwardSlashes(href));
    injectEl(scriptEl, attribs, afterBody);
  };
  const injectStyle = (href, attribs, afterBody) => {
    const linkEl = doc.createElement("link");
    linkEl.setAttribute("href", pathWithForwardSlashes(href));
    linkEl.setAttribute("rel", "stylesheet");
    injectEl(linkEl, attribs, afterBody);
  };
  const injectLink = (href, rel, type4) => {
    const linkEl = doc.createElement("link");
    linkEl.setAttribute("href", pathWithForwardSlashes(href));
    linkEl.setAttribute("rel", rel);
    if (type4) {
      linkEl.setAttribute("type", type4);
    }
    injectEl(linkEl);
  };
  const injectHtml = (html) => {
    const container = doc.createElement("div");
    container.innerHTML = html;
    for (const childEl of container.children) {
      injectEl(childEl);
    }
  };
  const injectMeta = (meta) => {
    Object.keys(meta).forEach((key) => {
      const metaEl = doc.createElement("meta");
      metaEl.setAttribute("name", key);
      metaEl.setAttribute("content", meta[key]);
      injectEl(metaEl);
    });
  };
  const finalizeInjection = () => {
    if (targetComment) {
      targetComment._remove();
    }
  };
  return {
    injectScript,
    injectStyle,
    injectLink,
    injectMeta,
    injectHtml,
    finalizeInjection
  };
}
function lineDependencyInjector(lines2, afterBodyLines) {
  const metaTemplate = template(
    `<meta name="<%- name %>" content="<%- value %>"/>`
  );
  const scriptTemplate = template(
    `<script <%= attribs %> src="<%- href %>"><\/script>`
  );
  const stylesheetTempate = template(
    `<link <%= attribs %> href="<%- href %>" rel="stylesheet" />`
  );
  const rawLinkTemplate = template(
    `<link href="<%- href %>" rel="<%- rel %>"<% if (type) { %> type="<%- type %>"<% } %> />`
  );
  const inject2 = (content, afterBody) => {
    if (afterBody) {
      afterBodyLines.push(content);
    } else {
      lines2.push(content);
    }
  };
  const formatAttribs = (attribs) => {
    return attribs ? Object.entries(attribs).map((entry) => {
      const attrib = `${entry[0]}="${entry[1]}"`;
      return attrib;
    }).join(" ") : "";
  };
  const injectScript = (href, attribs, afterBody) => {
    inject2(
      scriptTemplate(
        { href: pathWithForwardSlashes(href), attribs: formatAttribs(attribs) },
        afterBody
      )
    );
  };
  const injectStyle = (href, attribs, afterBody) => {
    inject2(
      stylesheetTempate(
        { href: pathWithForwardSlashes(href), attribs: formatAttribs(attribs) },
        afterBody
      )
    );
  };
  const injectLink = (href, rel, type4) => {
    if (!type4) {
      type4 = "";
    }
    lines2.push(
      rawLinkTemplate({ href: pathWithForwardSlashes(href), type: type4, rel })
    );
  };
  const injectHtml = (html) => {
    lines2.push(html + "\n");
  };
  const injectMeta = (meta) => {
    Object.keys(meta).forEach((name2) => {
      lines2.push(metaTemplate({ name: name2, value: meta[name2] }));
    });
  };
  const finalizeInjection = () => {
  };
  return {
    injectScript,
    injectStyle,
    injectLink,
    injectMeta,
    injectHtml,
    finalizeInjection
  };
}

// command/render/pandoc-dependencies-resources.ts
init_constants6();
init_copy5();
init_text2();
init_path();
init_fs();
async function writeFormatResources(inputDir, dependenciesFile, formatResources) {
  if (formatResources) {
    const files = Array.isArray(formatResources) ? formatResources : [formatResources];
    const dependencies = files.map((file) => {
      const absPath = join4(inputDir, file);
      if (!existsSync2(absPath)) {
        throw new Error(
          `The referenced format resource '${file}' does not exist.`
        );
      }
      return {
        type: kFormatResources,
        content: { file: absPath }
      };
    });
    await appendDependencies(dependenciesFile, dependencies);
  }
}
async function processFormatResources(inputDir, dependenciesFile) {
  const resources = [];
  const supporting = [];
  const dependencyJsonStream = await Deno.readTextFile(dependenciesFile);
  for (const jsonBlob of lines(dependencyJsonStream)) {
    if (jsonBlob) {
      const dependency = JSON.parse(jsonBlob);
      if (dependency.type === kFormatResources) {
        const formatResource = dependency.content;
        const targetPath = join4(inputDir, basename4(formatResource.file));
        copyTo(
          formatResource.file,
          targetPath,
          {
            overwrite: true,
            preserveTimestamps: true
          }
        );
      } else if (dependency.type === kResources) {
        const resource = dependency.content;
        resources.push(
          isAbsolute4(resource.file) ? relative4(inputDir, resource.file) : resource.file
        );
      } else if (dependency.type === kSupporting) {
        const supportingResource = dependency.content;
        supporting.push(supportingResource.file);
      }
    }
  }
  return { supporting, resources };
}

// command/render/pandoc.ts
init_timing();
init_format_markdown();
init_constants12();
init_format_html_shared();

// core/csl.ts
var kPdfUrl = "pdf-url";
var kAbstractUrl = "abstract-url";
var kEIssn = "eissn";
function suggestId(author, date) {
  let citeIdLeading = "";
  if (author && author.length > 0) {
    if (author[0].family) {
      citeIdLeading = author[0].family;
    } else if (author[0].literal) {
      citeIdLeading = author[0].literal;
    }
  }
  let datePart = "";
  if (date && date["date-parts"] && date["date-parts"].length > 0) {
    const yearIssued = date["date-parts"][0][0];
    if (yearIssued) {
      datePart = yearIssued + "";
    }
  }
  let suggestedId = `${citeIdLeading.replaceAll(/\s+/g, "_").toLowerCase()}${datePart}`;
  if (suggestedId.length === 0) {
    suggestedId = "untitled";
  }
  return suggestedId;
}
function cslDateToEDTFDate(date) {
  if (date["date-parts"] && date["date-parts"].length > 0) {
    const paddedParts = date["date-parts"][0].map((part) => {
      const partStr = part?.toString();
      if (partStr?.length === 1) {
        return `0${partStr}`;
      }
      return partStr;
    });
    return paddedParts.join("-");
  }
}
function cslNames(authors) {
  const cslNames2 = [];
  const authorList = Array.isArray(authors) ? authors : [authors];
  authorList.forEach((auth) => {
    if (auth) {
      const name2 = authorToCslName(auth);
      if (name2) {
        cslNames2.push(name2);
      }
    }
  });
  return cslNames2;
}
var isCslDate = (dateRaw) => {
  if (typeof dateRaw === "object") {
    return dateRaw["date-parts"] !== void 0 && // deno-lint-ignore no-explicit-any
    dateRaw["iso-8601"] !== void 0;
  } else {
    return false;
  }
};
function cslDate(dateRaw) {
  const toDateArray = (dateArr) => {
    if (dateArr.length === 0) {
      return void 0;
    } else if (dateArr.length === 1) {
      return {
        "date-parts": [[
          dateArr[0]
        ]],
        "iso-8601": `${dateArr[0]}`
      };
    } else if (dateArr.length === 2) {
      return {
        "date-parts": [[
          dateArr[0],
          dateArr[1]
        ]],
        "iso-8601": `${dateArr[0]}-${dateArr[1]}`
      };
    } else if (dateArr.length >= 3) {
      return {
        "date-parts": [[
          dateArr[0],
          dateArr[1],
          dateArr[2]
        ]],
        "iso-8601": `${dateArr[0]}-${dateArr[1]}-${dateArr[2]}`
      };
    }
  };
  if (Array.isArray(dateRaw)) {
    const dateArr = dateRaw;
    return toDateArray(dateArr);
  } else if (typeof dateRaw === "number") {
    const parseNumeric = (dateStr2) => {
      let dateParsed = dateStr2;
      const chomps = [4, 2, 2];
      const date = [];
      for (const chomp of chomps) {
        if (dateParsed.length >= chomp) {
          const part = dateParsed.substring(0, chomp);
          if (!isNaN(+part)) {
            date.push(+part);
            dateParsed = dateParsed.substring(chomp);
          } else {
            break;
          }
        } else {
          break;
        }
      }
      if (date.length > 0) {
        return date;
      } else {
        return void 0;
      }
    };
    const dateStr = String(dateRaw);
    const dateArr = parseNumeric(dateStr);
    if (dateArr) {
      return toDateArray(dateArr);
    }
  } else if (typeof dateRaw === "string") {
    const match = dateRaw.match(/^(\d\d\d\d)[-/](\d\d)$/);
    if (match) {
      return {
        "date-parts": [[
          parseInt(match[1]),
          parseInt(match[2])
        ]],
        "iso-8601": `${match[1]}-${match[2]}`
      };
    } else {
      const date = parsePandocDate(dateRaw);
      if (date) {
        const formatted = formatDate(date, "YYYY-MM-DD");
        return {
          "date-parts": [[
            date.getFullYear(),
            date.getMonth() + 1,
            date.getDate()
          ]],
          literal: formatDate(date, "YYYY-MM-DD"),
          raw: dateRaw,
          "iso-8601": formatted
        };
      }
    }
    return void 0;
  } else if (isCslDate(dateRaw)) {
    return dateRaw;
  } else if (dateRaw !== null && typeof dateRaw === "object") {
    const dateParts = [];
    if ("year" in dateRaw) {
      dateParts.push(dateRaw["year"]);
      if ("month" in dateRaw) {
        dateParts.push(dateRaw["month"]);
        if ("day" in dateRaw) {
          dateParts.push(dateRaw["day"]);
        }
      }
      return {
        "date-parts": [dateParts],
        "iso-8601": dateParts.join("-")
      };
    } else {
      return void 0;
    }
  }
}
function authorToCslName(author) {
  if (typeof author === "string") {
    const parts = author.split(" ");
    if (parts.length > 0) {
      const given = parts.shift() || "";
      const family = parts.length > 0 ? parts.join(" ") : "";
      return {
        family,
        given
      };
    }
  } else {
    return author;
  }
}
function cslType(type4) {
  if (types7.includes(type4)) {
    return type4;
  } else {
    if (type4 === "journal") {
      return "article-journal";
    } else if (type4 === "conference") {
      return "paper-conference";
    } else if (type4 === "dissertation") {
      return "thesis";
    }
    return "article";
  }
}
var types7 = [
  "article",
  "article-journal",
  "article-magazine",
  "article-newspaper",
  "bill",
  "book",
  "broadcast",
  "chapter",
  "classic",
  "collection",
  "dataset",
  "document",
  "entry",
  "entry-dictionary",
  "entry-encyclopedia",
  "event",
  "figure",
  "graphic",
  "hearing",
  "interview",
  "legal_case",
  "legislation",
  "manuscript",
  "map",
  "motion_picture",
  "musical_score",
  "pamphlet",
  "paper-conference",
  "patent",
  "performance",
  "periodical",
  "personal_communication",
  "post",
  "post-weblog",
  "regulation",
  "report",
  "review",
  "review-book",
  "software",
  "song",
  "speech",
  "standard",
  "thesis",
  "treaty",
  "webpage"
];

// core/markdown-pipeline.ts
init_base64();
var createMarkdownPipeline = (envelopeId, handlers3) => {
  return {
    markdownAfterBody() {
      const pipelineMarkdown = {};
      handlers3.forEach((handler) => {
        const handlerPipelineMarkdown = handler.getUnrendered();
        if (handlerPipelineMarkdown) {
          const inlines = handlerPipelineMarkdown.inlines;
          if (inlines) {
            pipelineMarkdown.inlines = pipelineMarkdown.inlines || {};
            for (const key of Object.keys(inlines)) {
              pipelineMarkdown.inlines[key] = inlines[key];
            }
          }
          const blocks = handlerPipelineMarkdown.blocks;
          if (blocks) {
            pipelineMarkdown.blocks = pipelineMarkdown.blocks || {};
            for (const key of Object.keys(blocks)) {
              pipelineMarkdown.blocks[key] = blocks[key];
            }
          }
        }
      });
      return createMarkdownRenderEnvelope(envelopeId, pipelineMarkdown);
    },
    readMarkdown(doc) {
      return readEnvelope(doc, envelopeId);
    },
    processRenderedMarkdown(doc) {
      processMarkdownRenderEnvelope(
        doc,
        envelopeId,
        handlers3.map((handler) => {
          return handler.processRendered;
        })
      );
    }
  };
};
function createMarkdownRenderEnvelope(envelopeId, pipelineMarkdown) {
  const envelope = markdownEnvelopeWriter(envelopeId);
  if (pipelineMarkdown.inlines) {
    for (const key of Object.keys(pipelineMarkdown.inlines)) {
      envelope.addInline(key, pipelineMarkdown.inlines[key]);
    }
  }
  if (pipelineMarkdown.blocks) {
    for (const key of Object.keys(pipelineMarkdown.blocks)) {
      envelope.addBlock(key, pipelineMarkdown.blocks[key]);
    }
  }
  return envelope.toMarkdown();
}
function processMarkdownRenderEnvelope(doc, envelopeId, processors) {
  const renderedMarkdown = readEnvelope(doc, envelopeId);
  processors.forEach((processor) => {
    processor(renderedMarkdown, doc);
  });
}
var markdownEnvelopeWriter = (envelopeId) => {
  const renderList = [];
  const hiddenSpan = (id, contents) => {
    id = encodeBase64(id);
    return `[${contents}]{.hidden .quarto-markdown-envelope-contents render-id="${id}"}`;
  };
  const hiddenDiv = (id, contents) => {
    id = encodeBase64(id);
    return `
:::{.hidden .quarto-markdown-envelope-contents render-id="${id}"}
${contents}
:::
`;
  };
  return {
    addBlock: (id, value) => {
      renderList.push(hiddenDiv(id, value));
    },
    addInline: (id, value) => {
      renderList.push(hiddenSpan(id, value));
    },
    toMarkdown: () => {
      const contents = renderList.join("\n");
      return `
:::{#${envelopeId} .hidden}
${contents}
:::
`;
    }
  };
};
var readEnvelope = (doc, envelopeId) => {
  const envelope = doc.getElementById(envelopeId);
  const contents = {};
  const addContent = (node) => {
    const el = node;
    const id = el.getAttribute("data-render-id");
    if (id) {
      contents[new TextDecoder().decode(decodeBase64(id))] = el;
    }
  };
  if (envelope) {
    const blockNodes = envelope.querySelectorAll("div[data-render-id]");
    blockNodes.forEach((blockNode) => {
      addContent(blockNode);
    });
    const inlineNodes = envelope.querySelectorAll("span[data-render-id]");
    inlineNodes.forEach((inlineNode) => {
      addContent(inlineNode);
    });
    envelope.remove();
  }
  return contents;
};

// command/render/pandoc.ts
init_env();
init_schema_types();

// project/types/website/listing/website-listing-shared.ts
init_path();
init_deno_dom_wasm_noinit();
await init_project_shared();
init_text2();
init_hash2();

// project/types/website/util/discover-meta.ts
init_html();
var kPreviewImgClass = "preview-image";
var kNamedFilePattern = "(.*?(?:preview|feature|cover|thumbnail).*?(?:\\.png|\\.gif|\\.jpg|\\.jpeg|\\.webp|\\.svg))";
var kNamedFileRegex = RegExp(kNamedFilePattern, "l");
function findDescription(doc) {
  const paras = doc.querySelectorAll(
    "main.content > p,  main.content > section > p"
  );
  for (const para of paras) {
    const paraEl = para;
    if (paraEl.innerText) {
      return paraEl.innerText;
    }
  }
  return void 0;
}
function findPreviewImg(doc) {
  const imgEl = findPreviewImgEl(doc);
  if (!imgEl) return void 0;
  const src2 = getDecodedAttribute(imgEl, "src");
  if (src2 === null) return void 0;
  const alt = getDecodedAttribute(imgEl, "alt");
  return {
    src: src2,
    alt: alt ?? void 0
  };
}
function findPreviewImgEl(doc) {
  const match = doc.querySelector(`img.${kPreviewImgClass}`);
  if (match) {
    return match;
  }
  const codeMatch = doc.querySelector(
    `div.${kPreviewImgClass} div.cell-output-display img`
  );
  if (codeMatch) {
    return codeMatch;
  }
  const imgs = doc.querySelectorAll("img");
  for (let i6 = 0; i6 < imgs.length; i6++) {
    const img = imgs[i6];
    const src2 = getDecodedAttribute(img, "src");
    if (src2 !== null && (src2.startsWith("data:") || kNamedFileRegex.test(src2))) {
      return img;
    }
  }
  const autoImgs = Array.from(
    doc.querySelectorAll("#quarto-document-content img")
  );
  for (const autoImgN of autoImgs) {
    const autoImg = autoImgN;
    const src2 = getDecodedAttribute(autoImg, "src");
    if (src2 && !src2.startsWith("http:") && !src2.startsWith("https:")) {
      return autoImg;
    }
  }
}
var kWpm = 200;
function estimateReadingTimeMinutes(markdown) {
  const wordCount = markdown.split(" ").length;
  return { wordCount, readingTime: Math.ceil(wordCount / kWpm) };
}

// project/types/website/listing/website-listing-shared.ts
init_html();
var kListing = "listing";
var kFields = "fields";
var kFieldDisplayNames = "field-display-names";
var kFieldTypes = "field-types";
var kFieldLinks = "field-links";
var kFieldRequired = "field-required";
var kFieldSort = "field-sort";
var kFieldFilter = "field-filter";
var kPageSize = "page-size";
var kMaxItems = "max-items";
var kFilterUi = "filter-ui";
var kSortUi = "sort-ui";
var kImageHeight2 = "image-height";
var kImageAlign = "image-align";
var kImageAlt2 = "image-alt";
var kImageLazyLoading = "image-lazy-loading";
var kImagePlaceholder = "image-placeholder";
var kGridColumns = "grid-columns";
var kMaxDescLength = "max-description-length";
var kDefaultMaxDescLength = 175;
var kTableStriped = "table-striped";
var kTableHover = "table-hover";
var kInclude2 = "include";
var kExclude = "exclude";
var kFieldTitle = "title";
var kFieldSubtitle = "subtitle";
var kFieldAuthor = "author";
var kFieldFileName = "filename";
var kFieldDateModified = "date-modified";
var kFieldFileModified = "file-modified";
var kFieldDate = "date";
var kFieldImage = "image";
var kFieldImageAlt = "image-alt";
var kFieldImageLazyLoading = "image-lazy-loading";
var kFieldDescription = "description";
var kFieldReadingTime = "reading-time";
var kFieldWordCount = "word-count";
var kFieldCategories = "categories";
var kFieldOrder = "order";
var kCategoryStyle = "category-style";
var kSortAsc = "asc";
var kSortDesc = "desc";
var kFeed = "feed";
var kItems = "items";
var kLanguage = "language";
var kDescription2 = "description";
var kXmlStyleSheet = "xml-stylesheet";
var kInlineCodeStyle = "inline-code-style";
var kUrlsToAbsolute = "urls-to-absolute";
var renderedContentReader = (project, options, siteUrl2) => {
  const renderedContent = {};
  return (filePath, renderedOptions) => {
    const cacheStr = renderedOptions ? JSON.stringify(renderedOptions) + filePath : filePath;
    const cacheHash = insecureHash(cacheStr);
    const mergedOptions = {
      ...options,
      ...renderedOptions
    };
    if (!renderedContent[cacheHash]) {
      renderedContent[cacheHash] = readRenderedContents(
        filePath,
        project,
        mergedOptions,
        siteUrl2
      );
    }
    return renderedContent[cacheHash];
  };
};
var isWebUrl = (url) => {
  return url.startsWith("http:") || url.startsWith("https:");
};
var absoluteUrl = (siteUrl2, url) => {
  if (isWebUrl(url)) {
    return url;
  } else {
    const baseUrl = siteUrl2.endsWith("/") ? siteUrl2.substring(0, siteUrl2.length - 1) : siteUrl2;
    let path3 = url.startsWith("/") ? url.substring(1, url.length) : url;
    if (path3.endsWith("/index.html")) {
      path3 = join4(dirname4(path3), "/");
    } else if (path3 === "index.html") {
      path3 = "";
    }
    return `${baseUrl}/${path3.replaceAll("\\", "/")}`;
  }
};
function readRenderedContents(filePath, project, options, siteUrl2) {
  const htmlInput = Deno.readTextFileSync(filePath);
  const doc = new DOMParser().parseFromString(htmlInput, "text/html");
  const fileRelPath = relative4(projectOutputDir(project), filePath);
  const fileRelFolder = dirname4(fileRelPath);
  const mainEl = doc.querySelector("main.content");
  const titleEl = doc.getElementById("title-block-header");
  const titleText = titleEl?.querySelector("h1.title")?.innerText;
  if (titleEl) {
    titleEl.remove();
  }
  let description = "";
  const descEl = doc.querySelector("meta[name='description']");
  if (descEl) {
    const descAttrVal = descEl.getAttribute("content");
    if (descAttrVal !== null) {
      description = descAttrVal;
    }
  }
  const navEls = doc.querySelectorAll("nav");
  if (navEls) {
    for (const navEl of navEls) {
      navEl.remove();
    }
  }
  if (options.transform?.[kUrlsToAbsolute] && siteUrl2) {
    const imgNodes = doc.querySelectorAll("img");
    if (imgNodes) {
      for (const imgNode of imgNodes) {
        const imgEl = imgNode;
        let src2 = imgEl.getAttribute("src");
        if (src2) {
          if (!src2.startsWith("/") && !isWebUrl(src2)) {
            src2 = join4(fileRelFolder, src2);
          }
          imgEl.setAttribute("src", absoluteUrl(siteUrl2, src2));
        }
      }
    }
  }
  const stripSelectors = [
    '*[aria-hidden="true"]',
    // Feeds should not contain aria hidden elements
    "button.code-copy-button"
    // Code copy buttons looks weird and don't work
  ];
  stripSelectors.forEach((sel) => {
    const nodes = doc.querySelectorAll(sel);
    nodes?.forEach((node) => {
      node.remove();
    });
  });
  const stripAttrs = [
    "role"
  ];
  stripAttrs.forEach((attr) => {
    const nodes = doc.querySelectorAll(`[${attr}]`);
    nodes?.forEach((node) => {
      const el = node;
      el.removeAttribute(attr);
    });
  });
  const stripTags = [];
  if (options.remove?.images) {
    stripTags.push("img");
  }
  stripTags.forEach((tag) => {
    const nodes = doc.querySelectorAll(`${tag}`);
    nodes?.forEach((node) => {
      const el = node;
      el.remove();
    });
  });
  if (options.remove?.anchors) {
    const relativeLinkSel = 'a[href^="#"]';
    const linkNodes = doc.querySelectorAll(relativeLinkSel);
    linkNodes.forEach((linkNode) => {
      const nodesToMove = linkNode.childNodes;
      const linkEl = linkNode;
      linkEl.after(...nodesToMove);
      linkEl.remove();
    });
  }
  if (options.transform?.[kInlineCodeStyle]) {
    const highlightingMap = defaultSyntaxHighlightingClassMap();
    const spanNodes = doc.querySelectorAll("code span");
    for (const spanNode of spanNodes) {
      const spanEl = spanNode;
      for (const clz of spanEl.classList) {
        const styles = highlightingMap[clz];
        if (styles) {
          spanEl.setAttribute("style", styles.join("\n"));
          break;
        }
      }
    }
    const codeStyle = "background: #f1f3f5;";
    const codeBlockNodes = doc.querySelectorAll("div.sourceCode");
    for (const codeBlockNode of codeBlockNodes) {
      const codeBlockEl = codeBlockNode;
      codeBlockEl.setAttribute("style", codeStyle);
    }
  }
  if (options.transform?.math) {
    const trimMath = (str3) => {
      if (str3.length > 4 && (str3.startsWith("\\[") || str3.startsWith("\\("))) {
        const trimStart = str3.slice(2);
        return trimStart.slice(0, trimStart.length - 2);
      } else {
        return str3;
      }
    };
    const mathNodes = doc.querySelectorAll("span.math");
    for (const mathNode of mathNodes) {
      const mathEl = mathNode;
      const math = trimMath(mathEl.innerText);
      const imgEl = doc.createElement("IMG");
      imgEl.setAttribute(
        "src",
        kWebTexUrl(math)
      );
      mathNode.parentElement?.replaceChild(imgEl, mathNode);
    }
  }
  if (options.remove?.links) {
    const relativeLinkSel = "a";
    const linkNodes = doc.querySelectorAll(relativeLinkSel);
    linkNodes.forEach((linkNode) => {
      const nodesToMove = linkNode.childNodes;
      const linkEl = linkNode;
      linkEl.after(...nodesToMove);
      linkEl.remove();
    });
  }
  const replaceTagRegex = /\/tag\{(.*)\}/g;
  const cleanMath = (contents) => {
    if (!contents) {
      return void 0;
    } else {
      return contents.replaceAll(replaceTagRegex, (_match, content) => {
        return `\\qquad{${content}}`;
      });
    }
  };
  const truncateNode = (node, maxLen) => {
    if (maxLen === void 0 || maxLen < 0) {
      return node;
    }
    let currentLength = 0;
    const shortenNode = (node2) => {
      const cloned = node2.cloneNode(true);
      for (const childNode of cloned.childNodes) {
        if (childNode.nodeType === 3 /* TEXT_NODE */) {
          const textNodeLen = childNode.nodeValue?.length || 0;
          if (currentLength > maxLen) {
            cloned.replaceChild(doc.createTextNode(""), childNode);
          } else if (currentLength + textNodeLen > maxLen) {
            const availableChars = maxLen - currentLength;
            cloned.replaceChild(
              doc.createTextNode(
                truncateText(
                  childNode.nodeValue || "",
                  availableChars,
                  "space"
                )
              ),
              childNode
            );
          }
          currentLength = textNodeLen + currentLength;
        } else {
          const newNode = shortenNode(childNode);
          cloned.replaceChild(newNode, childNode);
        }
      }
      return cloned;
    };
    return shortenNode(node);
  };
  const getFirstPara = () => {
    const paraNodes = mainEl?.querySelectorAll("p");
    if (paraNodes) {
      for (const paraNode of paraNodes) {
        const truncatedNode = truncateNode(paraNode, options["max-length"]);
        const paraContents = cleanMath(truncatedNode.innerHTML);
        if (paraContents) {
          return paraContents;
        }
      }
    }
    const anyNodes = mainEl?.childNodes;
    if (anyNodes) {
      for (const anyNode of anyNodes) {
        if (anyNode.nodeType === 1) {
          const el = anyNode;
          const headings = el.querySelectorAll("h1, h2, h3, h4, h5, h6");
          headings.forEach((heading) => heading.remove());
          const truncatedNode = truncateNode(anyNode, options["max-length"]);
          const contents = cleanMath(truncatedNode.innerHTML);
          if (contents) {
            return contents;
          }
        }
      }
    }
    return void 0;
  };
  const computePreviewImage = () => {
    const previewImageEl = findPreviewImgEl(doc);
    if (previewImageEl) {
      const previewImageSrc = getDecodedAttribute(previewImageEl, "src");
      if (previewImageSrc !== null) {
        const src2 = previewImageSrc;
        const alt = previewImageEl.getAttribute("alt") !== null ? previewImageEl.getAttribute("alt") : void 0;
        const title3 = previewImageEl.getAttribute("title") !== null ? previewImageEl.getAttribute("title") : void 0;
        return {
          src: src2,
          alt,
          title: title3
        };
      }
    }
  };
  const firstPara = getFirstPara();
  const fullContents = cleanMath(mainEl?.innerHTML);
  return {
    title: titleText,
    description,
    fullContents,
    firstPara,
    previewImage: computePreviewImage()
  };
}
var kWebTexUrl = (math, type4 = "png") => {
  const encodedMath = encodeURI(math);
  return `https://latex.codecogs.com/${type4}.latex?${encodedMath}`;
};
function defaultSyntaxHighlightingClassMap() {
  const classToStyleMapping = {};
  const theme = kDefaultHighlightStyle;
  const themeRaw = readTheme("", theme, "default");
  if (themeRaw) {
    const themeJson = JSON.parse(themeRaw);
    const textStyles = themeJson["text-styles"];
    if (textStyles) {
      Object.keys(textStyles).forEach((styleName) => {
        const abbr = kAbbrevs[styleName];
        if (abbr !== void 0) {
          const textValues = textStyles[styleName];
          const cssValues = generateCssKeyValues(textValues);
          classToStyleMapping[abbr] = cssValues;
        }
      });
    }
  }
  return classToStyleMapping;
}

// command/render/pandoc.ts
init_platform();

// core/performance/perfetto-utils.ts
function convertCombinedLuaProfileToCSV(profileName) {
  const combinedInformation = JSON.parse(
    Deno.readTextFileSync(profileName)
  );
  const lines2 = ["filter,name,time"];
  Object.entries(combinedInformation).forEach(([cat, data3]) => {
    Object.entries(data3).forEach(([fileName, time]) => {
      lines2.push(`${cat},${fileName},${time}`);
    });
  });
  Deno.writeTextFileSync(profileName, lines2.join("\n"));
}
function appendToCombinedLuaProfile(inputFileName, individualTraceFile, combinedInformationFile) {
  const individualTrace = JSON.parse(
    Deno.readTextFileSync(individualTraceFile)
  );
  let combinedInformation = {};
  try {
    combinedInformation = JSON.parse(
      Deno.readTextFileSync(combinedInformationFile)
    );
  } catch (_3) {
  }
  const earliestBEventByCat = {};
  const latestEEventByCat = {};
  individualTrace.traceEvents.forEach((event) => {
    const e5 = event;
    if (e5.cat && e5.ph === "B") {
      if (earliestBEventByCat[e5.cat] === void 0 || e5.ts < earliestBEventByCat[e5.cat]) {
        earliestBEventByCat[e5.cat] = e5.ts;
      }
    } else if (e5.cat && e5.ph === "E") {
      if (latestEEventByCat[e5.cat] === void 0 || e5.ts > latestEEventByCat[e5.cat]) {
        latestEEventByCat[e5.cat] = e5.ts;
      }
    }
  });
  Object.entries(earliestBEventByCat).forEach(([cat, start]) => {
    if (latestEEventByCat[cat] === void 0) {
      console.error("No end event for category", cat);
      return;
    }
    if (!combinedInformation[cat]) {
      combinedInformation[cat] = {};
    }
    combinedInformation[cat][inputFileName] = latestEEventByCat[cat] - start;
  });
  Deno.writeTextFileSync(
    combinedInformationFile,
    JSON.stringify(combinedInformation, null, 2)
  );
}

// command/render/pandoc.ts
init_function_times();

// core/json.ts
var walkJson = (obj, test, process4) => {
  if (test(obj)) {
    return process4(obj);
  }
  if (Array.isArray(obj)) {
    for (let i6 = 0; i6 < obj.length; i6++) {
      const v4 = obj[i6];
      const result2 = test(v4);
      if (!result2) {
        walkJson(v4, test, process4);
      } else {
        obj[i6] = walkJson(v4, test, process4);
      }
    }
  } else if (typeof obj === "object" && obj) {
    for (const key in obj) {
      const v4 = obj[key];
      const result2 = test(v4);
      if (!result2) {
        walkJson(v4, test, process4);
      } else {
        obj[key] = process4(v4);
      }
    }
  }
  return obj;
};

// command/render/pandoc.ts
init_safe_clone_deep();
init_asserts();

// deno_ral/process.ts
var call = async (path3, opts = {}) => {
  const cmd = new Deno.Command(path3, opts);
  return cmd.output();
};

// command/render/pandoc.ts
var traceCount = 0;
var handleCombinedLuaProfiles = (source2, paramsJson, temp) => {
  const beforePandocHooks = [];
  const afterPandocHooks = [];
  const tmp = temp.createFile();
  const combinedProfile = Deno.env.get("QUARTO_COMBINED_LUA_PROFILE");
  if (combinedProfile) {
    beforePandocHooks.push(() => {
      paramsJson["lua-profiler-output"] = tmp;
    });
    afterPandocHooks.push(() => {
      appendToCombinedLuaProfile(
        source2,
        tmp,
        combinedProfile
      );
    });
  }
  return {
    before: beforePandocHooks,
    after: afterPandocHooks
  };
};
function captureRenderCommand(args, temp, outputDir) {
  Deno.mkdirSync(outputDir, { recursive: true });
  const newArgs = (args.args ?? []).map((_arg) => {
    const arg = _arg;
    if (!arg.startsWith(temp.baseDir)) {
      return arg;
    }
    const newArg = join4(outputDir, basename4(arg));
    if (arg.match(/^.*quarto\-defaults.*.yml$/)) {
      const ymlDefaults = Deno.readTextFileSync(arg);
      const defaults = parse3(ymlDefaults);
      const templateDirectory = dirname4(defaults.template);
      const newTemplateDirectory = join4(
        outputDir,
        basename4(templateDirectory)
      );
      copyTo(templateDirectory, newTemplateDirectory);
      defaults.template = join4(
        newTemplateDirectory,
        basename4(defaults.template)
      );
      const defaultsOutputFile = join4(outputDir, basename4(arg));
      Deno.writeTextFileSync(defaultsOutputFile, stringify(defaults));
      return defaultsOutputFile;
    }
    Deno.copyFileSync(arg, newArg);
    return newArg;
  });
  const filterParams = JSON.parse(
    new TextDecoder().decode(decodeBase64(args.env["QUARTO_FILTER_PARAMS"]))
  );
  walkJson(
    filterParams,
    (v4) => typeof v4 === "string" && v4.startsWith(temp.baseDir),
    (_v) => {
      const v4 = _v;
      const newV = join4(outputDir, basename4(v4));
      Deno.copyFileSync(v4, newV);
      return newV;
    }
  );
  Deno.writeTextFileSync(
    join4(outputDir, "render-command.json"),
    JSON.stringify(
      {
        ...args,
        args: newArgs,
        env: {
          ...args.env,
          "QUARTO_FILTER_PARAMS": encodeBase64(JSON.stringify(filterParams))
        }
      },
      void 0,
      2
    )
  );
}
async function runPandoc(options, sysFilters) {
  const beforePandocHooks = [];
  const afterPandocHooks = [];
  const setupPandocHooks = (hooks) => {
    beforePandocHooks.push(...hooks.before);
    afterPandocHooks.push(...hooks.after);
  };
  const pandocEnv = {};
  const setupPandocEnv = () => {
    pandocEnv["QUARTO_FILTER_PARAMS"] = encodeBase64(
      JSON.stringify(paramsJson)
    );
    const traceFilters = (
      // deno-lint-ignore no-explicit-any
      pandocMetadata?.["_quarto"]?.["trace-filters"] || Deno.env.get("QUARTO_TRACE_FILTERS")
    );
    if (traceFilters) {
      let traceCountSuffix = "";
      if (traceCount > 0) {
        traceCountSuffix = `-${traceCount}`;
      }
      ++traceCount;
      if (traceFilters === true) {
        pandocEnv["QUARTO_TRACE_FILTERS"] = "quarto-filter-trace.json" + traceCountSuffix;
      } else {
        pandocEnv["QUARTO_TRACE_FILTERS"] = traceFilters + traceCountSuffix;
      }
    }
    if (Deno.env.get("QUARTO_LUA_CPATH") !== void 0) {
      pandocEnv["LUA_CPATH"] = getenv("QUARTO_LUA_CPATH");
    } else {
      pandocEnv["LUA_CPATH"] = "";
    }
  };
  const cwd2 = dirname4(options.source);
  const cmd = [pandocBinaryPath(), "+RTS", "-K512m", "-RTS"];
  const args = [...options.args];
  if (logLevel() === "DEBUG") {
    args.push("--verbose");
    args.push("--trace");
  }
  if (options.flags?.quiet || logLevel() === "ERROR") {
    args.push("--quiet");
  }
  if (options.metadata) {
    options.format.metadata = mergeConfigs(
      options.format.metadata,
      options.metadata
    );
  }
  const printArgs = [...args];
  let printMetadata = {
    ...options.format.metadata,
    crossref: {
      ...options.format.metadata.crossref || {}
    },
    ...options.flags?.metadata
  };
  const cleanQuartoTestsMetadata = (metadata) => {
    if (metadata["_quarto"] && typeof metadata["_quarto"] === "object") {
      delete metadata._quarto?.tests;
      if (Object.keys(metadata._quarto).length === 0) {
        delete metadata._quarto;
      }
    }
  };
  const cleanMetadataForPrinting = (metadata) => {
    delete metadata.params;
    delete metadata[kQuartoInternal];
    delete metadata[kQuartoVarsKey];
    delete metadata[kQuartoVersion];
    delete metadata[kFigResponsive];
    delete metadata[kQuartoTemplateParams];
    delete metadata[kRevealJsScripts];
    deleteProjectMetadata(metadata);
    deleteCrossrefMetadata(metadata);
    removeFilterParams(metadata);
    if (metadata[kRevealJSPlugins] && metadata[kRevealJSPlugins].length === 0) {
      delete metadata[kRevealJSPlugins];
    }
    cleanQuartoTestsMetadata(metadata);
    if (Array.isArray(metadata.engines)) {
      const filteredEngines = metadata.engines.filter((engine) => {
        const enginePath = typeof engine === "string" ? engine : engine.path;
        return !enginePath?.replace(/\\/g, "/").includes(
          "resources/extension-subtrees/"
        );
      });
      if (filteredEngines.length === 0) {
        delete metadata.engines;
      } else {
        metadata.engines = filteredEngines;
      }
    }
  };
  cleanMetadataForPrinting(printMetadata);
  kQuartoForwardedMetadataFields.forEach((field) => {
    if (options.flags?.pandocMetadata?.[field]) {
      options.format.metadata[field] = options.flags.pandocMetadata[field];
    }
  });
  let allDefaults = await generateDefaults(options) || {};
  let printAllDefaults = safeCloneDeep(allDefaults);
  const formatFilterParams = {};
  const forceMath = options.format.metadata[kMath];
  delete options.format.metadata[kMath];
  const kOJSFilter = "ojs";
  if (sysFilters.includes(kOJSFilter)) {
    formatFilterParams[kOJSFilter] = true;
    sysFilters = sysFilters.filter((filter3) => filter3 !== kOJSFilter);
  }
  formatFilterParams["language"] = options.format.language;
  if (!options.format.metadata[kTocTitle] && !isAstOutput(options.format.pandoc)) {
    options.format.metadata[kTocTitle] = options.format.language[projectIsWebsite(options.project) && !projectIsBook(options.project) && isHtmlOutput(options.format.pandoc, true) ? kTocTitleWebsite : kTocTitleDocument];
  }
  if (options.format.metadata[kTocLocation] && options.format.pandoc.toc === void 0) {
    options.format.pandoc.toc = true;
  }
  if (options.format.metadata[kAbstract] && (isHtmlDocOutput(options.format.pandoc) || isEpubOutput(options.format.pandoc))) {
    options.format.metadata[kAbstractTitle] = options.format.metadata[kAbstractTitle] || options.format.language[kSectionTitleAbstract];
  }
  const postprocessors = [];
  const htmlPostprocessors = [];
  const htmlFinalizers = [];
  const htmlRenderAfterBody = [];
  const dependenciesFile = options.services.temp.createFile();
  if (sysFilters.length > 0 || options.format.formatExtras || options.project?.formatExtras) {
    const projectExtras = options.project?.formatExtras ? await options.project.formatExtras(
      options.source,
      options.flags || {},
      options.format,
      options.services
    ) : {};
    const formatExtras = options.format.formatExtras ? await options.format.formatExtras(
      options.source,
      options.markdown,
      options.flags || {},
      options.format,
      options.libDir,
      options.services,
      options.offset,
      options.project,
      options.quiet
    ) : {};
    const inputExtras = mergeConfigs(
      projectExtras,
      formatExtras,
      {
        metadata: projectExtras.metadata?.[kDocumentClass] ? {
          [kDocumentClass]: projectExtras.metadata?.[kDocumentClass]
        } : void 0
      }
    );
    const extras = await resolveExtras(
      options.source,
      inputExtras,
      options.format,
      cwd2,
      options.libDir,
      dependenciesFile,
      options.project
    );
    postprocessors.push(...extras.postprocessors || []);
    if (options.format?.render[kKeepSource] || formatHasCodeTools(options.format)) {
      htmlPostprocessors.push(codeToolsPostprocessor(options.format));
    }
    htmlPostprocessors.push(...extras.html?.[kHtmlPostprocessors] || []);
    htmlFinalizers.push(...extras.html?.[kHtmlFinalizers] || []);
    if (isHtmlFileOutput(options.format.pandoc)) {
      htmlPostprocessors.push(overflowXPostprocessor);
      if (options.flags?.katex || options.format.pandoc[kHtmlMathMethod] === "katex") {
        htmlPostprocessors.push(katexPostProcessor());
      }
      if (!projectIsWebsite(options.project)) {
        htmlPostprocessors.push(discoverResourceRefs);
        htmlPostprocessors.push(fixEmptyHrefs);
      }
      if (forceMath) {
        const htmlMarkdownHandlers = [];
        htmlMarkdownHandlers.push({
          getUnrendered: () => {
            return {
              inlines: {
                "quarto-enable-math-inline": "$e = mC^2$"
              }
            };
          },
          processRendered: (_rendered, _doc) => {
          }
        });
        const htmlMarkdownPipeline = createMarkdownPipeline(
          "quarto-book-math",
          htmlMarkdownHandlers
        );
        const htmlPipelinePostProcessor = (doc) => {
          htmlMarkdownPipeline.processRenderedMarkdown(doc);
          return Promise.resolve({
            resources: [],
            supporting: []
          });
        };
        htmlRenderAfterBody.push(htmlMarkdownPipeline.markdownAfterBody());
        htmlPostprocessors.push(htmlPipelinePostProcessor);
      }
    }
    htmlRenderAfterBody.push(...extras.html?.[kMarkdownAfterBody] || []);
    if (sysFilters.length > 0) {
      extras.filters = extras.filters || {};
      extras.filters.post = extras.filters.post || [];
      extras.filters.post.unshift(
        ...sysFilters.map((filter3) => resourcePath(join4("filters", filter3)))
      );
    }
    if (extras.args) {
      args.push(...extras.args);
      printArgs.push(...extras.args);
    }
    if (extras.pandoc) {
      if (typeof allDefaults[kFrom] === "string" && typeof extras.pandoc[kFrom] === "string") {
        const userFrom = splitPandocFormatString(allDefaults[kFrom]);
        const extrasFrom = splitPandocFormatString(
          extras.pandoc[kFrom]
        );
        allDefaults[kFrom] = pandocFormatWith(
          userFrom.format,
          "",
          extrasFrom.options + userFrom.options
        );
        printAllDefaults[kFrom] = allDefaults[kFrom];
      }
      allDefaults = mergeConfigs(extras.pandoc, allDefaults);
      printAllDefaults = mergeConfigs(extras.pandoc, printAllDefaults);
      delete printAllDefaults[kHighlightStyle];
      delete allDefaults[kHighlightStyle];
      if (extras.pandoc[kSyntaxHighlighting] === null) {
        delete printAllDefaults[kSyntaxHighlighting];
        allDefaults[kSyntaxHighlighting] = null;
      } else if (extras.pandoc[kSyntaxHighlighting]) {
        delete printAllDefaults[kSyntaxHighlighting];
        allDefaults[kSyntaxHighlighting] = extras.pandoc[kSyntaxHighlighting];
      } else {
        delete printAllDefaults[kSyntaxHighlighting];
        delete allDefaults[kSyntaxHighlighting];
      }
    }
    if (extras.metadata || extras.metadataOverride) {
      resolveTemplatePartialPaths(
        options.format.metadata,
        cwd2,
        options.project
      );
      options.format.metadata = {
        ...mergeConfigs(
          extras.metadata || {},
          options.format.metadata
        ),
        ...extras.metadataOverride || {}
      };
      printMetadata = mergeConfigs(extras.metadata || {}, printMetadata);
      cleanMetadataForPrinting(printMetadata);
    }
    if (extras[kNotebooks]) {
      const documentNotebooks = options.format.render[kNotebookView];
      if (documentNotebooks !== false) {
        const userNotebooks = documentNotebooks === true ? [] : Array.isArray(documentNotebooks) ? documentNotebooks : documentNotebooks !== void 0 ? [documentNotebooks] : [];
        const uniqExtraNotebooks = extras[kNotebooks].filter((nb) => {
          return !userNotebooks.find((userNb) => {
            return userNb.notebook === nb.notebook;
          });
        });
        options.format.render[kNotebookView] = [
          ...userNotebooks,
          ...uniqExtraNotebooks
        ];
      }
    }
    if (isTypstOutput(options.format.pandoc)) {
      delete allDefaults[kColumns];
      delete printAllDefaults[kColumns];
    }
    const userTemplate = getPandocArg(args, "--template") || allDefaults[kTemplate];
    const userPartials = readPartials(options.format.metadata, cwd2);
    const inputDir = normalizePath(cwd2);
    const resolvePath = (path3) => {
      if (isAbsolute4(path3)) {
        return path3;
      } else {
        return join4(inputDir, path3);
      }
    };
    const templateContext = extras.templateContext;
    if (templateContext) {
      cleanTemplatePartialMetadata(
        printMetadata,
        templateContext.partials || []
      );
      const template2 = userTemplate ? resolvePath(userTemplate) : templateContext.template;
      if (!userTemplate && userPartials.length > 0) {
        const templateNames = templateContext.partials?.map(
          (temp) => basename4(temp)
        );
        if (templateNames) {
          const userPartialNames = userPartials.map(
            (userPartial) => basename4(userPartial)
          );
          const hasAtLeastOnePartial = userPartialNames.find((userPartial) => {
            return templateNames.includes(userPartial);
          });
          if (!hasAtLeastOnePartial) {
            const errorMsg = `The format '${allDefaults.to}' only supports the following partials:
${templateNames.join("\n")}

Please provide one or more of these partials.`;
            throw new Error(errorMsg);
          }
        } else {
          throw new Error(
            `The format ${allDefaults.to} does not support providing any template partials.`
          );
        }
      }
      const partials = templateContext.partials || [];
      partials.push(...userPartials);
      const stagedTemplate = await stageTemplate(
        options,
        extras,
        {
          template: template2,
          partials
        }
      );
      delete options.format.metadata[kTemplatePartials];
      allDefaults[kTemplate] = stagedTemplate;
    } else {
      if (userPartials.length > 0 && !isIpynbOutput(options.format.pandoc)) {
        throw new Error(
          `The format ${allDefaults.to} does not support providing any template partials.`
        );
      } else if (userTemplate) {
        allDefaults[kTemplate] = userTemplate;
      }
    }
    options.format.metadata = cleanupPandocMetadata({
      ...options.format.metadata
    });
    printMetadata = cleanupPandocMetadata(printMetadata);
    if (extras[kIncludeInHeader]) {
      if (allDefaults[kIncludeInHeader] !== void 0 && !isArray(allDefaults[kIncludeInHeader])) {
        allDefaults[kIncludeInHeader] = [
          allDefaults[kIncludeInHeader]
        ];
      }
      allDefaults = {
        ...allDefaults,
        [kIncludeInHeader]: [
          ...extras[kIncludeInHeader] || [],
          ...allDefaults[kIncludeInHeader] || []
        ]
      };
    }
    if (extras[kIncludeBeforeBody]) {
      if (allDefaults[kIncludeBeforeBody] !== void 0 && !isArray(allDefaults[kIncludeBeforeBody])) {
        allDefaults[kIncludeBeforeBody] = [
          allDefaults[kIncludeBeforeBody]
        ];
      }
      allDefaults = {
        ...allDefaults,
        [kIncludeBeforeBody]: [
          ...extras[kIncludeBeforeBody] || [],
          ...allDefaults[kIncludeBeforeBody] || []
        ]
      };
    }
    if (extras[kIncludeAfterBody]) {
      if (allDefaults[kIncludeAfterBody] !== void 0 && !isArray(allDefaults[kIncludeAfterBody])) {
        allDefaults[kIncludeAfterBody] = [
          allDefaults[kIncludeAfterBody]
        ];
      }
      allDefaults = {
        ...allDefaults,
        [kIncludeAfterBody]: [
          ...allDefaults[kIncludeAfterBody] || [],
          ...extras[kIncludeAfterBody] || []
        ]
      };
    }
    if (extras.html?.[kBodyEnvelope] && projectExtras.html?.[kBodyEnvelope]) {
      extras.html[kBodyEnvelope] = projectExtras.html[kBodyEnvelope];
    }
    resolveBodyEnvelope(allDefaults, extras, options.services.temp);
    allDefaults.filters = [
      ...extras.filters?.pre || [],
      ...allDefaults.filters || [],
      ...extras.filters?.post || []
    ];
    allDefaults.filters = allDefaults.filters.map((filter3) => {
      if (typeof filter3 === "string") {
        return pandocMetadataPath(filter3);
      } else {
        return {
          type: filter3.type,
          path: pandocMetadataPath(filter3.path)
        };
      }
    });
    const filterParams = extras[kFilterParams];
    if (filterParams) {
      Object.keys(filterParams).forEach((key) => {
        formatFilterParams[key] = filterParams[key];
      });
    }
  }
  if (isMarkdownOutput(options.format) && requiresShortcodeUnescapePostprocessor(options.markdown)) {
    postprocessors.push(shortcodeUnescapePostprocessor);
  }
  const title3 = allDefaults?.[kVariables]?.[kTitle] || options.format.metadata[kTitle];
  const pageTitle = allDefaults?.[kVariables]?.[kPageTitle] || options.format.metadata[kPageTitle];
  const titlePrefix = allDefaults?.[kTitlePrefix];
  if (!title3 && !pageTitle && isHtmlFileOutput(options.format.pandoc)) {
    const [_dir, stem] = dirAndStem(options.source);
    args.push(
      "--metadata",
      `pagetitle:${pandocAutoIdentifier(stem, false)}`
    );
  }
  if (pageTitle !== void 0 && pageTitle === titlePrefix || pageTitle === void 0 && title3 === titlePrefix) {
    delete allDefaults[kTitlePrefix];
  }
  if (options.keepYaml && allDefaults.to) {
    allDefaults.to = allDefaults.to.replaceAll(`+${kYamlMetadataBlock}`, "");
  }
  if (isWindows4) {
    await cacheCodePage();
  }
  const filterResultsFile = options.services.temp.createFile();
  const writerKeys = ["to", "writer"];
  for (const key of writerKeys) {
    if (allDefaults[key]?.match(/[.]lua$/)) {
      formatFilterParams["custom-writer"] = allDefaults[key];
      allDefaults[key] = resourcePath("filters/customwriter/customwriter.lua");
    }
  }
  if (allDefaults.from) {
    formatFilterParams["user-defined-from"] = allDefaults.from;
  }
  allDefaults.from = resourcePath("filters/qmd-reader.lua");
  let pandocArgs = args;
  const paramsJson = await filterParamsJson(
    pandocArgs,
    options,
    allDefaults,
    formatFilterParams,
    filterResultsFile,
    dependenciesFile
  );
  setupPandocHooks(
    handleCombinedLuaProfiles(
      options.source,
      paramsJson,
      options.services.temp
    )
  );
  if (!isLatexOutput(options.format.pandoc) && !isTypstOutput(options.format.pandoc) && !isMarkdownOutput(options.format) && crossrefFilterActive(options)) {
    delete allDefaults[kNumberSections];
    delete allDefaults[kNumberOffset];
    const removeArgs = /* @__PURE__ */ new Map();
    removeArgs.set("--number-sections", false);
    removeArgs.set("--number-offset", true);
    pandocArgs = removePandocArgs(pandocArgs, removeArgs);
  }
  if (typeof allDefaults[kNumberOffset] === "number") {
    allDefaults[kNumberOffset] = [allDefaults[kNumberOffset]];
  }
  const dataDirArgs = /* @__PURE__ */ new Map();
  dataDirArgs.set("--data-dir", true);
  pandocArgs = removePandocArgs(
    pandocArgs,
    dataDirArgs
  );
  pandocArgs.push("--data-dir", resourcePath("pandoc/datadir"));
  allDefaults[kSyntaxDefinitions] = allDefaults[kSyntaxDefinitions] || [];
  const syntaxDefinitions = expandGlobSync(
    join4(resourcePath(join4("pandoc", "syntax-definitions")), "*.xml")
  );
  for (const syntax of syntaxDefinitions) {
    allDefaults[kSyntaxDefinitions]?.push(syntax.path);
  }
  if (allDefaults[kHtmlMathMethod] === "webtex") {
    allDefaults[kHtmlMathMethod] = {
      method: "webtex",
      url: "https://latex.codecogs.com/svg.latex?"
    };
  }
  if (!allDefaults[kTemplate] && !havePandocArg(args, "--template") && !options.keepYaml && allDefaults.to) {
    const formatDesc = parseFormatString(allDefaults.to);
    const lookupTo = formatDesc.baseFormat;
    if ([
      "gfm",
      "commonmark",
      "commonmark_x",
      "markdown_strict",
      "markdown_phpextra",
      "markdown_github",
      "markua"
    ].includes(
      lookupTo
    )) {
      allDefaults[kTemplate] = resourcePath(
        join4("pandoc", "templates", "default.markdown")
      );
    }
  }
  if (isHtmlFileOutput(options.format.pandoc)) {
    pandocArgs = pandocArgs.filter((arg) => arg !== "--self-contained" && arg !== "--embed-resources");
    delete allDefaults[kSelfContained];
    delete allDefaults[kEmbedResources];
  }
  if (allDefaults) {
    const defaultsFile = await writeDefaultsFile(
      allDefaults,
      options.services.temp
    );
    cmd.push("--defaults", defaultsFile);
  }
  const paritioned = partitionYamlFrontMatter(options.markdown);
  const engineMetadata = paritioned?.yaml ? readYamlFromMarkdown(paritioned.yaml) : {};
  const markdown = paritioned?.markdown || options.markdown;
  const pandocMetadata = safeCloneDeep(options.format.metadata || {});
  for (const key of Object.keys(engineMetadata)) {
    const isChapterTitle = key === kTitle && projectIsBook(options.project);
    if (!isQuartoMetadata(key) && !isChapterTitle && !isIncludeMetadata(key)) {
      const formats2 = engineMetadata[kMetadataFormat];
      if (isObject(formats2) && metadataGetDeep(formats2, key).length > 0) {
        continue;
      }
      if (key === kTheme && isRevealjsOutput(options.format.pandoc)) {
        continue;
      }
      if (key === kFieldCategories && projectIsWebsite(options.project)) {
        continue;
      }
      pandocMetadata[key] = engineMetadata[key];
    }
  }
  const dateRaw = pandocMetadata[kDate];
  const dateFields = [kDate, kDateModified];
  dateFields.forEach((dateField) => {
    const date = pandocMetadata[dateField];
    const format14 = pandocMetadata[kDateFormat];
    assert7(format14 === void 0 || typeof format14 === "string");
    pandocMetadata[dateField] = resolveAndFormatDate(
      options.source,
      date,
      format14
    );
  });
  if (typeof pandocMetadata[kCitation] === "boolean" && pandocMetadata[kCitation] === true) {
    pandocMetadata[kCitation] = {};
  }
  const citationMetadata = pandocMetadata[kCitation];
  if (citationMetadata) {
    assert7(typeof citationMetadata === "object");
    const citationMetadataObj = citationMetadata;
    const docCSLDate = dateRaw ? cslDate(resolveDate(options.source, dateRaw)) : void 0;
    const fields = ["issued", "available-date"];
    fields.forEach((field) => {
      if (citationMetadataObj[field]) {
        citationMetadataObj[field] = cslDate(citationMetadataObj[field]);
      } else if (docCSLDate) {
        citationMetadataObj[field] = docCSLDate;
      }
    });
  }
  const authorsRaw = pandocMetadata[kAuthors] || pandocMetadata[kAuthor];
  if (authorsRaw) {
    const authors = parseAuthor(pandocMetadata[kAuthor], true);
    if (authors) {
      pandocMetadata[kAuthor] = authors.map(
        (author) => cslNameToString(author.name)
      );
      pandocMetadata[kAuthors] = Array.isArray(authorsRaw) ? authorsRaw : [authorsRaw];
    }
  }
  const instituteRaw = pandocMetadata[kInstitute];
  if (instituteRaw) {
    pandocMetadata[kInstitutes] = Array.isArray(instituteRaw) ? instituteRaw : [instituteRaw];
  }
  if (pandocMetadata.lang === "zh") {
    pandocMetadata.lang = "zh-Hans";
  }
  if (isLatexOutput(options.format.pandoc) && !isBeamerOutput(options.format.pandoc)) {
    const docClass = pandocMetadata[kDocumentClass];
    assert7(!docClass || typeof docClass === "string");
    const isPrintDocumentClass = docClass && ["book", "scrbook"].includes(docClass);
    if (!isPrintDocumentClass) {
      if (pandocMetadata[kColorLinks] === void 0) {
        pandocMetadata[kColorLinks] = true;
      }
      if (pandocMetadata[kLinkColor] === void 0) {
        pandocMetadata[kLinkColor] = "blue";
      }
    }
  }
  const markdownWithRenderAfter = isHtmlOutput(options.format.pandoc) && htmlRenderAfterBody.length > 0 ? markdown + "\n\n\n" + htmlRenderAfterBody.join("\n") + "\n\n" : markdown;
  const input = markdownWithRenderAfter + keepSourceBlock(options.format, options.source);
  const inputTemp = options.services.temp.createFile({
    prefix: "quarto-input",
    suffix: ".md"
  });
  Deno.writeTextFileSync(inputTemp, input);
  cmd.push(inputTemp);
  const metadataTemp = options.services.temp.createFile({
    prefix: "quarto-metadata",
    suffix: ".yml"
  });
  const pandocPassedMetadata = safeCloneDeep(pandocMetadata);
  delete pandocPassedMetadata.format;
  delete pandocPassedMetadata.project;
  delete pandocPassedMetadata.website;
  delete pandocPassedMetadata.about;
  cleanQuartoTestsMetadata(pandocPassedMetadata);
  if (Array.isArray(pandocPassedMetadata.engines)) {
    const filteredEngines = pandocPassedMetadata.engines.filter((engine) => {
      const enginePath = typeof engine === "string" ? engine : engine.path;
      if (!enginePath) return true;
      return !enginePath.replace(/\\/g, "/").includes(
        "resources/extension-subtrees/"
      );
    });
    if (filteredEngines.length === 0) {
      delete pandocPassedMetadata.engines;
    } else {
      pandocPassedMetadata.engines = filteredEngines;
    }
  }
  if (pandocPassedMetadata.book) {
    pandocPassedMetadata.book = escapeAtInMetadata(pandocPassedMetadata.book);
  }
  Deno.writeTextFileSync(
    metadataTemp,
    stringify(pandocPassedMetadata, {
      indent: 2,
      lineWidth: -1,
      sortKeys: false,
      skipInvalid: true
    })
  );
  cmd.push("--metadata-file", metadataTemp);
  cmd.push(...pandocArgs);
  if (!options.quiet && !options.flags?.quiet) {
    runPandocMessage(
      printArgs,
      printAllDefaults,
      sysFilters,
      printMetadata
    );
  }
  for (const hook of beforePandocHooks) {
    await hook();
  }
  setupPandocEnv();
  const params = {
    cmd: cmd[0],
    args: cmd.slice(1),
    cwd: cwd2,
    env: pandocEnv,
    ourEnv: Deno.env.toObject()
  };
  const captureCommand = Deno.env.get("QUARTO_CAPTURE_RENDER_COMMAND");
  if (captureCommand) {
    captureRenderCommand(params, options.services.temp, captureCommand);
  }
  const pandocRender = makeTimedFunctionAsync("pandoc-render", async () => {
    return await execProcess(params);
  });
  const result2 = await pandocRender();
  for (const hook of afterPandocHooks) {
    await hook();
  }
  const resources = resourcesFromMetadata(
    options.format.metadata[kResources]
  );
  let inputTraits = {};
  if (existsSync2(filterResultsFile)) {
    const filterResultsJSON = Deno.readTextFileSync(filterResultsFile);
    if (filterResultsJSON.trim().length > 0) {
      const filterResults = JSON.parse(filterResultsJSON);
      inputTraits = filterResults.inputTraits;
      const resourceFiles = filterResults.resourceFiles || [];
      resources.push(...resourceFiles);
    }
  }
  if (result2.success) {
    return {
      inputMetadata: pandocMetadata,
      inputTraits,
      resources,
      postprocessors,
      htmlPostprocessors: isHtmlOutput(options.format.pandoc) ? htmlPostprocessors : [],
      htmlFinalizers: isHtmlDocOutput(options.format.pandoc) ? htmlFinalizers : []
    };
  } else {
    if (isWindows4) {
      clearCodePageCache();
    }
    return null;
  }
}
function cleanupPandocMetadata(metadata) {
  const classoption = metadata[kClassOption];
  if (Array.isArray(classoption)) {
    metadata[kClassOption] = uniqBy(
      classoption.reverse(),
      (option) => {
        return option.replace(/=.+$/, "");
      }
    ).reverse();
  }
  return metadata;
}
async function resolveExtras(input, extras, format14, inputDir, libDir, dependenciesFile, project) {
  await writeFormatResources(
    inputDir,
    dependenciesFile,
    format14.render[kFormatResources]
  );
  if (isHtmlOutput(format14.pandoc)) {
    extras = await resolveSassBundles(
      inputDir,
      extras,
      format14,
      project
    );
    await writeDependencies(dependenciesFile, extras);
    const htmlDependenciesPostProcesor = (doc, _inputMedata) => {
      return withTiming(
        "pandocDependenciesPostProcessor",
        async () => await readAndInjectDependencies(
          dependenciesFile,
          inputDir,
          libDir,
          doc,
          project
        )
      );
    };
    extras.html = extras.html || {};
    extras.html[kHtmlPostprocessors] = extras.html?.[kHtmlPostprocessors] || [];
    if (isHtmlFileOutput(format14.pandoc)) {
      extras.html[kHtmlPostprocessors].unshift(htmlDependenciesPostProcesor);
    }
    delete extras.html?.[kDependencies];
  } else {
    delete extras.html;
  }
  if (isTypstOutput(format14.pandoc)) {
    const brand = (await project.resolveBrand(input))?.light;
    const fontdirs = /* @__PURE__ */ new Set();
    const base_urls = {
      google: "https://fonts.googleapis.com/css",
      bunny: "https://fonts.bunny.net/css"
    };
    const ttf_urls = [], woff_urls = [];
    if (brand?.data.typography) {
      const fonts = brand.data.typography.fonts || [];
      for (const _font of fonts) {
        const source2 = _font.source ?? "google";
        if (source2 === "file") {
          const font = Zod.BrandFontFile.parse(_font);
          for (const file of font.files || []) {
            const path3 = typeof file === "object" ? file.path : file;
            fontdirs.add(resolve4(dirname4(join4(brand.brandDir, path3))));
          }
        } else if (source2 === "bunny") {
          const font = Zod.BrandFontBunny.parse(_font);
          console.log(
            "Font bunny is not yet supported for Typst, skipping",
            font.family
          );
        } else if (source2 === "google") {
          const font = Zod.BrandFontGoogle.parse(_font);
          let { family, style, weight } = font;
          const parts = [family];
          if (style) {
            style = Array.isArray(style) ? style : [style];
            parts.push(style.join(","));
          }
          if (weight) {
            weight = Array.isArray(weight) ? weight : [weight];
            parts.push(weight.join(","));
          }
          const response = await fetch(
            `${base_urls[source2]}?family=${parts.join(":")}`
          );
          const lines2 = (await response.text()).split("\n");
          for (const line of lines2) {
            const sourcelist = line.match(/^ *src: (.*); *$/);
            if (sourcelist) {
              const sources = sourcelist[1].split(",").map((s5) => s5.trim());
              let found = false;
              const failed_formats = [];
              for (const source3 of sources) {
                const match = source3.match(
                  /url\(([^)]*)\) *format\('([^)]*)'\)/
                );
                if (match) {
                  const [_3, url, format15] = match;
                  if (["truetype", "opentype"].includes(format15)) {
                    ttf_urls.push(url);
                    found = true;
                    break;
                  }
                  failed_formats.push(format15);
                }
              }
              if (!found) {
                console.log(
                  "skipping",
                  family,
                  "\nnot currently able to use formats",
                  failed_formats.join(", ")
                );
              }
            }
          }
        }
      }
    }
    if (ttf_urls.length || woff_urls.length) {
      const font_cache = migrateProjectScratchPath(
        brand.projectDir,
        "typst-font-cache",
        "typst/fonts"
      );
      const url_to_path = (url) => url.replace(/^https?:\/\//, "");
      const cached = async (url) => {
        const path3 = url_to_path(url);
        try {
          await Deno.lstat(join4(font_cache, path3));
          return true;
        } catch (err2) {
          if (!(err2 instanceof Deno.errors.NotFound)) {
            throw err2;
          }
          return false;
        }
      };
      const download = async (url) => {
        const path3 = url_to_path(url);
        await ensureDir(
          join4(font_cache, dirname4(path3))
        );
        const response = await fetch(url);
        const blob = await response.blob();
        const buffer2 = await blob.arrayBuffer();
        const bytes = new Uint8Array(buffer2);
        await Deno.writeFile(join4(font_cache, path3), bytes);
      };
      const woff2ttf = async (url) => {
        const path3 = url_to_path(url);
        await call("ttx", { args: [join4(font_cache, path3)] });
        await call("ttx", {
          args: [join4(font_cache, path3.replace(/woff2?$/, "ttx"))]
        });
      };
      const ttf_urls2 = [], woff_urls2 = [];
      await Promise.all(ttf_urls.map(async (url) => {
        if (!await cached(url)) {
          ttf_urls2.push(url);
        }
      }));
      await woff_urls.reduce((cur, next) => {
        return cur.then(() => woff2ttf(next));
      }, Promise.resolve());
      await Promise.all(ttf_urls2.concat(woff_urls2).map(download));
      if (woff_urls2.length) {
        await Promise.all(woff_urls2.map(woff2ttf));
      }
      fontdirs.add(font_cache);
    }
    let fontPaths = format14.metadata[kFontPaths] || [];
    if (typeof fontPaths === "string") {
      fontPaths = [fontPaths];
    }
    fontPaths = fontPaths.map(
      (path3) => path3[0] === "/" ? join4(project.dir, path3) : path3
    );
    fontPaths.push(...fontdirs);
    format14.metadata[kFontPaths] = fontPaths;
  }
  if (format14.render[kLatexAutoMk] === false) {
    await processFormatResources(inputDir, dependenciesFile);
  } else {
    const resourceDependenciesPostProcessor = async (_output) => {
      return await processFormatResources(inputDir, dependenciesFile);
    };
    extras.postprocessors = extras.postprocessors || [];
    extras.postprocessors.push(resourceDependenciesPostProcessor);
  }
  extras = resolveTextHighlightStyle(
    inputDir,
    extras,
    format14.pandoc
  );
  return extras;
}
function resolveBodyEnvelope(pandoc2, extras, temp) {
  const envelope = extras.html?.[kBodyEnvelope];
  if (envelope) {
    const writeBodyFile = (type4, prepend, content) => {
      if (content) {
        const file = temp.createFile({ suffix: ".html" });
        Deno.writeTextFileSync(file, content);
        if (!prepend) {
          pandoc2[type4] = (pandoc2[type4] || []).concat(file);
        } else {
          pandoc2[type4] = [file].concat(pandoc2[type4] || []);
        }
      }
    };
    writeBodyFile(kIncludeInHeader, true, envelope.header);
    writeBodyFile(kIncludeBeforeBody, true, envelope.before);
    writeBodyFile(kIncludeAfterBody, true, envelope.afterPreamble);
    writeBodyFile(kIncludeAfterBody, false, envelope.afterPostamble);
  }
}
function runPandocMessage(args, pandoc2, sysFilters, metadata, debug4) {
  info(`pandoc ${args.join(" ")}`, { bold: true });
  if (pandoc2) {
    info(pandocDefaultsMessage(pandoc2, sysFilters, debug4), { indent: 2 });
  }
  const keys = Object.keys(metadata);
  if (keys.length > 0) {
    const printMetadata = safeCloneDeep(metadata);
    delete printMetadata.format;
    if (Object.keys(printMetadata).length > 0) {
      info("metadata", { bold: true });
      info(
        stringify(printMetadata, {
          indent: 2,
          lineWidth: -1,
          sortKeys: false,
          skipInvalid: true
        }),
        { indent: 2 }
      );
    }
  }
}
function resolveTextHighlightStyle(inputDir, extras, pandoc2) {
  extras = {
    ...extras,
    pandoc: extras.pandoc ? { ...extras.pandoc } : {}
  };
  const highlightTheme = pandoc2[kSyntaxHighlighting] || pandoc2[kHighlightStyle] || kDefaultHighlightStyle;
  const textHighlightingMode = extras.html?.[kTextHighlightingMode];
  if (highlightTheme === "none") {
    extras.pandoc = extras.pandoc || {};
    extras.pandoc[kSyntaxHighlighting] = "none";
    return extras;
  }
  if (highlightTheme === "idiomatic") {
    if (isRevealjsOutput(pandoc2)) {
      warn(
        "syntax-highlighting: idiomatic is not supported for reveal.js. Using default highlighting."
      );
    } else {
      extras.pandoc = extras.pandoc || {};
      extras.pandoc[kSyntaxHighlighting] = "idiomatic";
      return extras;
    }
  }
  switch (textHighlightingMode) {
    case "light":
    case "dark":
      extras.pandoc = extras.pandoc || {};
      extras.pandoc[kSyntaxHighlighting] = textHighlightThemePath2(
        inputDir,
        highlightTheme,
        textHighlightingMode
      ) || highlightTheme;
      break;
    case "none":
      if (extras.pandoc) {
        extras.pandoc = extras.pandoc || {};
        extras.pandoc[kSyntaxHighlighting] = textHighlightThemePath2(
          inputDir,
          "none"
        );
      }
      break;
    case void 0:
    default:
      extras.pandoc = extras.pandoc || {};
      extras.pandoc[kSyntaxHighlighting] = textHighlightThemePath2(inputDir, highlightTheme, "light") || highlightTheme;
      break;
  }
  return extras;
}
function escapeAtInMetadata(value) {
  if (typeof value === "string") {
    return isExternalPath(value) ? value.replaceAll("@", "&#64;") : value;
  }
  if (Array.isArray(value)) {
    return value.map(escapeAtInMetadata);
  }
  if (value !== null && typeof value === "object") {
    const result2 = {};
    for (const [k3, v4] of Object.entries(value)) {
      result2[k3] = escapeAtInMetadata(v4);
    }
    return result2;
  }
  return value;
}

// command/render/cleanup.ts
init_fs();
init_path();
init_lodash();
init_path2();
init_render();
init_format5();
init_constants6();
init_render_paths();
function renderCleanup(input, output, format14, project, supporting, keepMd) {
  const figureFormat = isLatexOutput(format14.pandoc) ? extname4(output).slice(1) : format14.pandoc.to;
  if (!isAbsolute4(output)) {
    output = join4(dirname4(input), output);
  }
  if (keepMd && !format14.execute[kKeepMd] && keepMd !== output) {
    removeIfExists(keepMd);
  }
  if (!format14.execute[kKeepMd] && !format14.render[kKeepTex] && !format14.render[kKeepTyp] && supporting) {
    if (isHtmlFileOutput(format14.pandoc)) {
      const libDir2 = join4(
        dirname4(input),
        filesDirLibDir(input)
      );
      if (existsSync2(libDir2)) {
        supporting.push(normalizePath(libDir2));
      }
    } else {
      let filesDir2 = join4(
        dirname4(input),
        inputFilesDir(input)
      );
      if (existsSync2(filesDir2)) {
        filesDir2 = normalizePath(filesDir2);
      }
      supporting = supporting.map((supportingDir) => {
        if (filesDir2 === supportingDir) {
          return join4(filesDir2, figuresDir(figureFormat));
        } else {
          return supportingDir;
        }
      });
    }
    const mediabagDir2 = join4(dirname4(input), filesDirMediabagDir(input));
    if (existsSync2(mediabagDir2)) {
      supporting.push(mediabagDir2);
    }
    uniq(supporting).forEach((path3) => {
      if (existsSync2(path3)) {
        safeRemoveDirSync(path3, project.dir);
      }
    });
  }
  const filesDir = join4(dirname4(input), inputFilesDir(input));
  const figsDir = join4(filesDir, figuresDir(figureFormat));
  const libDir = join4(dirname4(input), filesDirLibDir(input));
  const mediabagDir = join4(dirname4(input), filesDirMediabagDir(input));
  removeIfEmptyDir(figsDir);
  removeIfEmptyDir(libDir);
  removeIfEmptyDir(mediabagDir);
  removeIfEmptyDir(filesDir);
}

// command/render/render.ts
await init_project_shared();
init_format5();

// command/render/render-info.ts
init_constants6();
init_path();
init_log2();
function isSelfContained(flags, format14) {
  return !!(flags[kSelfContained] || format14.pandoc[kSelfContained] || flags[kEmbedResources] || format14.pandoc[kEmbedResources]);
}
var kStandaloneExtensionNames = [
  "pdf",
  "epub",
  "fb2",
  "docx",
  "rtf",
  "pptx",
  "odt",
  "ipynb"
];
var kStandaloneExtensions = kStandaloneExtensionNames.map(
  (name2) => `.${name2}`
);
function isSelfContainedOutput(flags, format14, finalOutput) {
  return isSelfContained(flags, format14) || kStandaloneExtensions.includes(extname4(finalOutput));
}
function renderProgress(message) {
  logProgress(message);
}

// command/render/render.ts
init_timing();
init_render_paths();

// core/jupyter/jupyter-embed.ts
init_resources2();
init_lifetimes();
init_jupyter();
init_constants6();
init_format5();
init_flags2();
init_path();
await init_base();
init_widgets();
init_temp();
init_pandoc_partition();
init_path2();
init_error2();
init_format_ipynb();
init_notebook_types();
init_log2();
init_lodash();
init_tex();
var kEcho2 = "echo";
var kWarning2 = "warning";
var kOutput2 = "output";
var kHashRegex = /(.*?)#(.*)/;
var kIndexRegex = /(.*)\[([0-9,-]*)\]/;
var placeholderRegex = () => {
  return /<!-- 12A0366C\|(.*)\|:(.*?) \| (.*?) \| (.*?) -->/g;
};
var kNotebookCache = "notebook-cache";
function parseNotebookAddress(path3) {
  const hashResult = path3.match(kHashRegex);
  if (hashResult) {
    const path4 = hashResult[1];
    if (isEmbeddable(path4)) {
      return {
        path: path4,
        ids: resolveCellIds(hashResult[2])
      };
    } else {
      unsupportedEmbed(path4);
    }
  }
  const indexResult = path3.match(kIndexRegex);
  if (indexResult) {
    const path4 = indexResult[1];
    if (isEmbeddable(path4)) {
      return {
        path: path4,
        indexes: resolveRange(indexResult[2])
      };
    } else {
      unsupportedEmbed(path4);
    }
  }
  if (isEmbeddable(path3)) {
    return {
      path: path3
    };
  } else {
    unsupportedEmbed(path3);
  }
}
function unsupportedEmbed(path3) {
  if (extname4(path3) === "") {
    throw new Error(
      `Unable to embed content from ${path3} - there is no extension on the file path.`
    );
  } else {
    throw new Error(
      `Unable to embed content from ${path3} - embedding content is not supported for this file type.`
    );
  }
}
async function ensureNotebookContext(markdown, services, context) {
  const regex = placeholderRegex();
  let match = regex.exec(markdown);
  const nbsToRender = [];
  while (match) {
    const inputPath = match[1];
    const nbAddr = match[2];
    const nbAddress = parseNotebookAddress(nbAddr);
    if (!nbAddress) {
      throw new InternalError(
        "Unexpected - there must be a notebook address since we matched."
      );
    }
    const nbAbsPath2 = resolveNbPath(inputPath, nbAddress.path, context);
    if (!isNotebook(nbAbsPath2)) {
      if (!services.notebook.get(nbAbsPath2, context)?.[kQmdIPynb]) {
        nbsToRender.push({ path: nbAbsPath2, name: nbAddress.path });
      }
    }
    match = regex.exec(markdown);
  }
  const uniqueRenders = uniqBy(
    nbsToRender,
    (nb) => nb.path
  );
  if (uniqueRenders.length) {
    logProgress("Rendering qmd embeds");
  }
  let count = 0;
  for (const nb of uniqueRenders) {
    logProgress(`[${++count}/${uniqueRenders.length}] ${nb.name}`);
    const partitioned = partitionMarkdown(Deno.readTextFileSync(nb.path));
    let notebookMeta;
    const filename = basename4(nb.path);
    if (partitioned.yaml && partitioned.yaml.title) {
      notebookMeta = {
        title: partitioned.yaml.title,
        filename
      };
    } else {
      notebookMeta = {
        title: filename,
        filename
      };
    }
    await services.notebook.render(
      nb.path,
      ipynbFormat(),
      kQmdIPynb,
      services,
      notebookMeta,
      context
    );
  }
}
function notebookMarkdownPlaceholder(input, nbPath, options, outputs) {
  return `<!-- 12A0366C|${input}|:${nbPath} | ${outputs || ""} | ${optionsToPlaceholder(options)} -->
`;
}
async function replaceNotebookPlaceholders(to, context, flags, markdown, services) {
  const assetCache = {};
  const regex = placeholderRegex();
  let match = regex.exec(markdown);
  let includes;
  const notebooks = [];
  while (match) {
    const inputPath = match[1];
    const nbAddressStr = match[2];
    const nbAddress = parseNotebookAddress(nbAddressStr);
    if (!nbAddress) {
      throw new InternalError(
        "Expected to find a valid notebook address string for an embed."
      );
    }
    const nbAbsPath2 = resolveNbPath(inputPath, nbAddress.path, context.project);
    let assets = assetCache[inputPath];
    if (!assets) {
      assets = jupyterAssets(
        inputPath,
        to
      );
      assetCache[inputPath] = assets;
    }
    if (nbAddress) {
      const outputsStr = match[3];
      const nbOutputs = outputsStr ? resolveRange(outputsStr) : void 0;
      const placeholderStr = match[4];
      const nbOptions = placeholderStr ? placeholderToOptions(placeholderStr) : {};
      const notebookIncludes = () => {
        if (safeExistsSync(nbAbsPath2)) {
          const notebook = jupyterFromNotebookOrQmd(
            nbAbsPath2,
            services,
            context.project
          );
          const dependencies = isHtmlOutput(context.format.pandoc) ? extractJupyterWidgetDependencies(notebook) : void 0;
          if (dependencies) {
            const tempDir2 = globalTempContext().createDir();
            return includesForJupyterWidgetDependencies(
              [dependencies],
              tempDir2
            );
          } else {
            return void 0;
          }
        } else {
          throw new Error(
            `Unable to embed content from notebook '${nbAddress.path}'
The file ${nbAbsPath2} doesn't exist or cannot be read.`
          );
        }
      };
      includes = notebookIncludes();
      const nbMarkdown = await notebookMarkdown(
        inputPath,
        nbAddress,
        nbAbsPath2,
        assets,
        context,
        flags,
        nbOptions,
        nbOutputs
      );
      if (nbMarkdown && !notebooks.includes(nbAddress.path)) {
        notebooks.push(nbAddress.path);
      }
      markdown = markdown.replaceAll(
        match[0],
        // https://github.com/quarto-dev/quarto-cli/issues/12853
        // we use a function here to avoid
        // escaping issues with $ in the markdown
        // (e.g. $x$ in math mode)
        () => nbMarkdown ?? ""
      );
    }
    match = regex.exec(markdown);
  }
  regex.lastIndex = 0;
  const supporting = Object.values(assetCache).map((assets) => {
    return join4(assets.base_dir, assets.supporting_dir);
  });
  return {
    notebooks,
    includes,
    markdown,
    supporting
  };
}
function resolveNbPath(input, path3, context) {
  if (!context.isSingleFile) {
    const projectMatch = path3.match(/^[\\/](.*)/);
    if (projectMatch) {
      return join4(context.dir, projectMatch[1]);
    }
  }
  if (isAbsolute4(path3)) {
    return path3;
  } else {
    if (isAbsolute4(input)) {
      return join4(dirname4(input), path3);
    } else {
      const baseDir = context.isSingleFile ? Deno.cwd() : context.dir;
      const result2 = join4(baseDir, dirname4(input), path3);
      return result2;
    }
  }
}
async function notebookMarkdown(inputPath, nbAddress, nbAbsPath2, assets, context, flags, options, outputs) {
  const notebookInfo = await getCachedNotebookInfo(
    inputPath,
    nbAddress,
    assets,
    context,
    flags,
    options,
    outputs
  );
  if (notebookInfo.outputs.length === 0) {
    return void 0;
  }
  const notebookMarkdown2 = (nbAbsPath3, cells, title3) => {
    const cellId = cells.length > 0 ? cells[0].id || "" : "";
    const markdown = [
      "",
      `:::{.quarto-embed-nb-cell notebook="${nbAbsPath3}" ${title3 ? `notebook-title="${title3}"` : ""} notebook-cellId="${cellId}"}`
    ];
    const cellOutput = cells.map((cell) => cell.markdown).join("");
    markdown.push("");
    markdown.push(cellOutput);
    markdown.push("");
    markdown.push(":::");
    return markdown.join("\n");
  };
  if (nbAddress.ids) {
    const theCells = nbAddress.ids.map((id) => {
      const cell = cellForId(id, notebookInfo.outputs);
      if (cell === void 0) {
        throw new Error(
          `The cell ${id} does not exist in notebook`
        );
      } else if (cell.markdown.trim() === "") {
        throw new Error(
          `The notebook ${nbAddress.path} doesn't contain output to embed with the cell id, tag, or label '${id}'. Please be sure to have executed any cells that you are embedding.`
        );
      } else {
        return cell;
      }
    });
    return notebookMarkdown2(nbAbsPath2, theCells, notebookInfo.title);
  } else if (nbAddress.indexes) {
    const theCells = nbAddress.indexes.map((idx) => {
      if (idx < 1 || idx > notebookInfo.outputs.length) {
        throw new Error(
          `The cell index ${idx} isn't within the range of cells`
        );
      } else {
        const cell = notebookInfo.outputs[idx - 1];
        if (cell.markdown.trim() === "") {
          throw new Error(
            `The notebook ${nbAddress.path} doesn't contain output to embed for the cell in position ${idx}. Please be sure to have executed any cells that you are embedding.`
          );
        }
        return cell;
      }
    });
    return notebookMarkdown2(nbAbsPath2, theCells, notebookInfo.title);
  } else {
    const notebookMd = notebookMarkdown2(
      nbAbsPath2,
      notebookInfo.outputs,
      notebookInfo.title
    );
    if (notebookMd.trim() === "") {
      throw new Error(
        `The notebook ${nbAddress.path} doesn't contain output to embed. Please be sure to have executed any cells that you are embedding.`
      );
    } else {
      return notebookMd;
    }
  }
}
var isNotebook = (path3) => {
  return extname4(path3) === ".ipynb";
};
var isEmbeddable = (path3) => {
  return isNotebook(path3) || extname4(path3) === ".qmd";
};
async function getCachedNotebookInfo(inputPath, nbAddress, assets, context, flags, options, outputs) {
  const lifetime = getNamedLifetime(kRenderFileLifetime);
  if (lifetime === void 0) {
    throw new InternalError(`named lifetime ${kRenderFileLifetime} not found`);
  }
  const nbCache = lifetime.get(kNotebookCache) || {
    cache: {},
    cleanup: () => {
    }
  };
  const cacheKey = notebookCacheKey(
    inputPath,
    nbAddress,
    assets,
    options,
    outputs
  );
  if (!nbCache.cache[cacheKey]) {
    const nbAbsPath2 = resolveNbPath(inputPath, nbAddress.path, context.project);
    const notebook = jupyterFromNotebookOrQmd(
      nbAbsPath2,
      context.options.services,
      context.project
    );
    if (options) {
      notebook.cells = notebook.cells.map((cell) => {
        if (options.echo !== void 0) {
          cell.metadata[kEcho2] = options.echo;
        }
        if (options.warning !== void 0) {
          cell.metadata[kWarning2] = options.warning;
        }
        if (options.asis !== void 0) {
          cell.metadata[kOutput2] = options.asis ? true : false;
        }
        if (outputs && cell.outputs) {
          cell.outputs = cell.outputs.map((output, index2) => {
            const oneBasedIdx = index2 + 1;
            output.metadata = output.metadata || {};
            if (!outputs.includes(oneBasedIdx)) {
              output.metadata[kQuartoOutputDisplay] = false;
            } else {
              const explicitOrder = outputs.indexOf(oneBasedIdx);
              if (explicitOrder > -1) {
                output.metadata[kQuartoOutputOrder] = explicitOrder;
              }
            }
            return output;
          });
        }
        return cell;
      });
    }
    if (options?.filter) {
      notebook.cells = notebook.cells.filter((cell) => {
        if (options?.filter) {
          return options?.filter(cell);
        } else {
          return true;
        }
      });
    }
    const format14 = context.format;
    const executeOptions = {
      target: context.target,
      resourceDir: resourcePath(),
      tempDir: context.options.services.temp.createDir(),
      dependencies: true,
      libDir: context.libDir,
      format: context.format,
      projectDir: context.project?.dir,
      cwd: flags.executeDir || dirname4(normalizePath(context.target.source)),
      params: resolveParams(flags.params, flags.paramsFile),
      quiet: flags.quiet,
      previewServer: context.options.previewServer,
      handledLanguages: languages(),
      project: context.project
    };
    const [dir, stem] = dirAndStem(nbAddress.path);
    const outputPrefix = texSafeFilename(
      `${dir !== "." ? dir + "-" : ""}${stem}`
    );
    const result2 = await jupyterToMarkdown(
      notebook,
      {
        executeOptions,
        language: notebook.metadata.kernelspec.language.toLowerCase(),
        assets,
        execute: format14.execute,
        keepHidden: format14.render[kKeepHidden],
        preserveCellMetadata: options?.preserveCellMetadata,
        toHtml: isHtmlCompatible(format14),
        toLatex: isLatexOutput(format14.pandoc),
        toMarkdown: isMarkdownOutput(format14),
        toIpynb: isIpynbOutput(format14.pandoc),
        toPresentation: isPresentationOutput(format14.pandoc),
        figFormat: format14.execute[kFigFormat],
        figDpi: format14.execute[kFigDpi],
        figPos: format14.render[kFigPos],
        fixups: "minimal",
        outputPrefix
      }
    );
    const title3 = findTitle(result2.cellOutputs);
    nbCache.cache[cacheKey] = { outputs: result2.cellOutputs, title: title3 };
    lifetime.attach(nbCache, kNotebookCache);
  }
  return nbCache.cache[cacheKey];
}
function findTitle(cells) {
  for (const cell of cells) {
    const partitioned = partitionMarkdown(cell.markdown);
    if (partitioned.yaml?.title) {
      return partitioned.yaml.title;
    } else if (partitioned.headingText) {
      return partitioned.headingText;
    }
  }
  return void 0;
}
function notebookCacheKey(inputPath, nbAddress, assets, nbOptions, nbOutputs) {
  const optionsKey = nbOptions ? Object.keys(nbOptions).reduce((current3, key) => {
    if (nbOptions[key] !== void 0 && typeof (nbOptions[key] === "boolean")) {
      return current3 + `${key}:${String(nbOptions[key])}`;
    } else {
      return current3;
    }
  }, "") : "";
  const coreKey = optionsKey ? `${inputPath}-${nbAddress.path}-${optionsKey}` : `${inputPath}-${nbAddress.path}`;
  const outputsKey = nbOutputs ? nbOutputs.join(",") : "";
  return `${coreKey}:${outputsKey}:${assets.supporting_dir}`;
}
function optionsToPlaceholder(options) {
  return Object.keys(options).map((key) => {
    return `${key}:${String(options[key])}`;
  }).join(",");
}
function placeholderToOptions(placeholder2) {
  const parts = placeholder2.split(",");
  const options = {};
  for (const part of parts) {
    const kv = part.split(":");
    if (kv.length > 1) {
      const key = part.split(":")[0];
      const value = part.split(":").slice(1).join(":");
      options[key] = value.toLowerCase() === "true";
    } else {
      throw new Error("Unexpected placeholder for notebook option: " + part);
    }
  }
  return options;
}
function cellForId(id, cells) {
  for (const cell of cells) {
    const hasId = cell.id ? id === cell.id : false;
    if (hasId) {
      return cell;
    }
    const hasLabel = cell.options && cell.options[kCellLabel] ? id === cell.options[kCellLabel] : false;
    if (hasLabel) {
      return cell;
    }
    const hasTag = cell.metadata && cell.metadata.tags ? cell.metadata.tags.find((tag) => id === tag) !== void 0 : false;
    if (hasTag) {
      return cell;
    }
    if (cell.markdown && cell.markdown.includes(id)) {
      if (cell.markdown.match(new RegExp(`.*{#${id}(\\s+[^}]*)*}$`, "gm"))) {
        return cell;
      }
    }
  }
}
function resolveCellIds(hash) {
  if (hash && hash.indexOf(",") > 0) {
    return hash.split(",");
  } else if (hash) {
    return [hash];
  } else {
    return void 0;
  }
}
function resolveRange(rangeRaw) {
  if (rangeRaw) {
    const result2 = [];
    const ranges = rangeRaw.split(",");
    ranges.forEach((range) => {
      if (range.indexOf("-") > -1) {
        const parts = range.split("-");
        const start = parseInt(parts[0]);
        const end = parseInt(parts[1]);
        const step = start > end ? -1 : 1;
        for (let i6 = start; step > 0 ? i6 <= end : i6 >= end; i6 = i6 + step) {
          result2.push(i6);
        }
      } else {
        result2.push(parseInt(range));
      }
    });
    return result2;
  } else {
    return void 0;
  }
}
function jupyterFromNotebookOrQmd(nbAbsPath2, services, project) {
  let jupyterNotebookPath = nbAbsPath2;
  if (!isNotebook(jupyterNotebookPath)) {
    const notebook = services.notebook.get(
      nbAbsPath2,
      project
    );
    if (notebook?.[kQmdIPynb] && notebook[kQmdIPynb]) {
      jupyterNotebookPath = notebook[kQmdIPynb].path;
    } else {
      throw new InternalError(
        `Expected an 'ipynb' file to be present for the 'qmd' file ${nbAbsPath2}`
      );
    }
  }
  return jupyterFromFile(jupyterNotebookPath);
}

// command/render/render.ts
init_constants6();

// core/pandoc/self-contained.ts
init_path();
init_resources2();
init_process();
init_deno_dom();

// core/data-url.ts
init_base64();
function asDataUrl(content, mimeType) {
  const b64Src = encodeBase64(content);
  return `data:${mimeType};base64,${b64Src}`;
}

// core/pandoc/self-contained.ts
var bundleModules = async (dom, workingDir) => {
  const modules = dom.querySelectorAll("script[type='module']");
  for (const module2 of modules) {
    const src2 = module2.getAttribute("src");
    if (src2) {
      const srcName = join4(workingDir, src2);
      const srcDir = dirname4(srcName);
      const jsSource = await esbuildCompile(
        Deno.readTextFileSync(srcName),
        srcDir,
        [],
        "esm"
      );
      module2.setAttribute(
        "src",
        asDataUrl(jsSource, "application/javascript")
      );
    }
  }
};
var pandocIngestSelfContainedContent = async (file, resourcePath2) => {
  const filename = basename4(file);
  const workingDir = dirname4(file);
  const template2 = formatResourcePath(
    "html",
    "pandoc-selfcontained/selfcontained.html"
  );
  const contents = Deno.readTextFileSync(file);
  const doctypeMatch = contents.match(/^<!DOCTYPE.*?>/);
  const dom = await parseHtml(contents);
  await bundleModules(dom, workingDir);
  const input = [];
  input.push("````````{=html}");
  if (doctypeMatch) {
    input.push(doctypeMatch[0]);
  }
  input.push(dom.documentElement.outerHTML);
  input.push("````````");
  const cmd = [pandocBinaryPath()];
  cmd.push("--to", "html");
  cmd.push("--from", "markdown");
  cmd.push("--template", template2);
  cmd.push("--output", filename);
  cmd.push("--metadata", "title=placeholder");
  cmd.push("--embed-resources");
  if (resourcePath2 && resourcePath2.length) {
    cmd.push("--resource-path", resourcePath2.join(":"));
  }
  const result2 = await execProcess({
    cmd: cmd[0],
    args: cmd.slice(1),
    stdout: "piped",
    cwd: workingDir
  }, input.join("\n"));
  if (result2.success) {
    return result2.stdout;
  } else {
    throw new Error();
  }
};

// command/render/render.ts
init_file();
init_project_types();
async function renderPandoc(file, quiet) {
  const { context, recipe, executeResult, resourceFiles } = file;
  const format14 = recipe.format;
  if (executeResult.includes) {
    format14.pandoc = mergePandocIncludes(
      format14.pandoc || {},
      executeResult.includes
    );
  }
  if (executeResult.pandoc) {
    format14.pandoc = mergeConfigs(
      format14.pandoc || {},
      executeResult.pandoc
    );
  }
  if (executeResult.engineDependencies) {
    for (const engineName of Object.keys(executeResult.engineDependencies)) {
      const engine = executionEngine(engineName);
      const engineInstance = engine.launch(engineProjectContext(context.project));
      const dependenciesResult = await engineInstance.dependencies({
        target: context.target,
        format: format14,
        output: recipe.output,
        resourceDir: resourcePath(),
        tempDir: context.options.services.temp.createDir(),
        projectDir: context.project?.dir,
        libDir: context.libDir,
        dependencies: executeResult.engineDependencies[engineName],
        quiet: context.options.flags?.quiet
      });
      format14.pandoc = mergePandocIncludes(
        format14.pandoc,
        dependenciesResult.includes
      );
    }
  }
  const mediabagDir = filesDirMediabagDir(context.target.source);
  ensureDirSync(join4(dirname4(context.target.source), mediabagDir));
  const notebookResult = await replaceNotebookPlaceholders(
    format14.pandoc.to || "html",
    context,
    context.options.flags || {},
    executeResult.markdown,
    context.options.services
  );
  const embedSupporting = [];
  if (notebookResult.supporting.length) {
    embedSupporting.push(...notebookResult.supporting);
  }
  const pandocIncludes = {
    [kIncludeAfterBody]: notebookResult.includes?.afterBody ? [notebookResult.includes?.afterBody] : void 0,
    [kIncludeInHeader]: notebookResult.includes?.inHeader ? [notebookResult.includes?.inHeader] : void 0
  };
  format14.pandoc = mergePandocIncludes(
    format14.pandoc,
    pandocIncludes
  );
  let markdownInput = notebookResult.markdown ? notebookResult.markdown : executeResult.markdown;
  if (format14.render[kInlineIncludes]) {
    const collectIncludes = (location) => {
      const includes = format14.pandoc[location];
      if (includes) {
        const append = location === "include-after-body";
        for (const include2 of includes) {
          const includeMd = Deno.readTextFileSync(include2);
          if (append) {
            markdownInput = `${markdownInput}

${includeMd}`;
          } else {
            markdownInput = `${includeMd}

${markdownInput}`;
          }
        }
        delete format14.pandoc[location];
      }
    };
    collectIncludes(kIncludeInHeader);
    collectIncludes(kIncludeBeforeBody);
    collectIncludes(kIncludeAfterBody);
  }
  const pandocOptions = {
    markdown: markdownInput,
    source: context.target.source,
    output: recipe.output,
    keepYaml: recipe.keepYaml,
    mediabagDir,
    libDir: context.libDir,
    format: format14,
    executionEngine: executeResult.engine,
    project: context.project,
    args: recipe.args,
    services: context.options.services,
    metadata: executeResult.metadata,
    quiet,
    flags: context.options.flags
  };
  if (context.project) {
    pandocOptions.offset = projectOffset(context.project, context.target.input);
  }
  const pandocResult = await runPandoc(pandocOptions, executeResult.filters);
  if (!pandocResult) {
    return Promise.reject();
  }
  return {
    complete: async (renderedFormats, cleanup2) => {
      push("render-postprocessor");
      if (executeResult.postProcess) {
        await withTimingAsync("engine-postprocess", async () => {
          return await context.engine.postprocess({
            engine: context.engine,
            target: context.target,
            format: format14,
            output: recipe.output,
            tempDir: context.options.services.temp.createDir(),
            projectDir: context.project?.dir,
            preserve: executeResult.preserve,
            quiet: context.options.flags?.quiet
          });
        });
      }
      const canHtmlPostProcess = isHtmlFileOutput(format14.pandoc);
      if (!canHtmlPostProcess && pandocResult.htmlPostprocessors.length > 0) {
        const postProcessorNames = pandocResult.htmlPostprocessors.map(
          (p5) => p5.name
        ).join(", ");
        const msg5 = `Attempt to HTML post process non HTML output using: ${postProcessorNames}`;
        throw new Error(msg5);
      }
      const htmlPostProcessors = canHtmlPostProcess ? pandocResult.htmlPostprocessors : [];
      const htmlFinalizers = canHtmlPostProcess ? pandocResult.htmlFinalizers || [] : [];
      const htmlPostProcessResult = await runHtmlPostprocessors(
        pandocResult.inputMetadata,
        pandocResult.inputTraits,
        pandocOptions,
        htmlPostProcessors,
        htmlFinalizers,
        renderedFormats,
        quiet
      );
      const outputFile5 = isAbsolute4(pandocOptions.output) ? pandocOptions.output : join4(dirname4(pandocOptions.source), pandocOptions.output);
      const postProcessSupporting = [];
      const postProcessResources = [];
      if (pandocResult.postprocessors) {
        for (const postprocessor of pandocResult.postprocessors) {
          const result3 = await postprocessor(outputFile5);
          if (result3 && result3.supporting) {
            postProcessSupporting.push(...result3.supporting);
          }
          if (result3 && result3.resources) {
            postProcessResources.push(...result3.resources);
          }
        }
      }
      let finalOutput;
      let selfContained;
      await withTimingAsync("postprocess-selfcontained", async () => {
        const flags = context.options.flags || {};
        finalOutput = recipe.output;
        selfContained = isSelfContainedOutput(
          flags,
          format14,
          finalOutput
        );
        if (selfContained && isHtmlFileOutput(format14.pandoc)) {
          await pandocIngestSelfContainedContent(
            outputFile5,
            format14.pandoc[kResourcePath]
          );
        }
        finalOutput = await recipe.complete(pandocOptions) || recipe.output;
        selfContained = isSelfContainedOutput(
          flags,
          format14,
          finalOutput
        );
      });
      let filesDir = inputFilesDir(context.target.source);
      filesDir = existsSync2(join4(dirname4(context.target.source), filesDir)) ? filesDir : void 0;
      let supporting = filesDir ? executeResult.supporting : void 0;
      if (filesDir && isHtmlFileOutput(format14.pandoc)) {
        const filesDirAbsolute = join4(dirname4(context.target.source), filesDir);
        if (existsSync2(filesDirAbsolute) && (!supporting || !supporting.includes(filesDirAbsolute))) {
          const filesLibs = join4(
            dirname4(context.target.source),
            context.libDir
          );
          if (existsSync2(filesLibs) && (!supporting || !supporting.includes(filesLibs))) {
            supporting = supporting || [];
            supporting.push(filesLibs);
          }
        }
      }
      if (htmlPostProcessResult.supporting && htmlPostProcessResult.supporting.length > 0) {
        supporting = supporting || [];
        supporting.push(...htmlPostProcessResult.supporting);
      }
      if (embedSupporting && embedSupporting.length > 0) {
        supporting = supporting || [];
        supporting.push(...embedSupporting);
      }
      if (postProcessSupporting && postProcessSupporting.length > 0) {
        supporting = supporting || [];
        supporting.push(...postProcessSupporting);
      }
      let cleanupSelfContained = void 0;
      if (selfContained && supporting) {
        cleanupSelfContained = [...supporting];
        if (context.project) {
          const libDir = context.project?.config?.project["lib-dir"];
          if (libDir) {
            const absLibDir = join4(context.project.dir, libDir);
            cleanupSelfContained = cleanupSelfContained.filter(
              (file2) => !file2.startsWith(absLibDir)
            );
          }
        }
      }
      if (cleanup2 !== false) {
        withTiming("render-cleanup", () => renderCleanup(
          context.target.input,
          finalOutput,
          format14,
          file.context.project,
          cleanupSelfContained,
          executionEngineKeepMd(context)
        ));
      }
      const projectRelativeInput = (sourcePath) => {
        if (context.project) {
          return relative4(
            normalizePath(context.project.dir),
            normalizePath(sourcePath)
          );
        }
        return sourcePath;
      };
      const projectOutputPath = (path3) => {
        if (context.project) {
          if (isAbsolute4(path3)) {
            return relative4(
              normalizePath(context.project.dir),
              normalizePath(path3)
            );
          } else {
            return relative4(
              normalizePath(context.project.dir),
              normalizePath(join4(dirname4(context.target.source), path3))
            );
          }
        } else {
          return path3;
        }
      };
      pop();
      const files = resourceFiles.concat(htmlPostProcessResult.resources).concat(postProcessResources);
      const result2 = {
        isTransient: recipe.isOutputTransient,
        input: projectRelativeInput(context.target.source),
        markdown: executeResult.markdown,
        format: format14,
        supporting: supporting ? supporting.filter(existsSync1).map(
          (file2) => context.project ? relative4(context.project.dir, file2) : file2
        ) : void 0,
        file: recipe.isOutputTransient ? finalOutput : projectOutputPath(finalOutput),
        resourceFiles: {
          globs: pandocResult.resources,
          files
        },
        selfContained
      };
      return result2;
    }
  };
}
function renderResultFinalOutput(renderResults, relativeToInputDir) {
  let result2 = renderResults.files.find((file) => {
    return !file.supplemental;
  });
  if (!result2) {
    return void 0;
  }
  for (const fileResult of renderResults.files) {
    if (fileResult.file === "index.html" && !fileResult.supplemental) {
      result2 = fileResult;
      break;
    }
  }
  if (renderResults.context) {
    const projType = projectType(renderResults.context.config?.project.type);
    if (projType && projType.renderResultFinalOutput) {
      const projectResult = projType.renderResultFinalOutput(
        renderResults,
        relativeToInputDir
      );
      if (projectResult) {
        result2 = projectResult;
      }
    }
  }
  let finalInput = result2.input;
  let finalOutput = result2.file;
  if (renderResults.baseDir) {
    finalInput = join4(renderResults.baseDir, finalInput);
    if (renderResults.outputDir) {
      finalOutput = join4(
        renderResults.baseDir,
        renderResults.outputDir,
        finalOutput
      );
    } else {
      finalOutput = join4(renderResults.baseDir, finalOutput);
    }
  } else {
    finalOutput = join4(dirname4(finalInput), finalOutput);
  }
  if (!safeExistsSync(finalOutput)) {
    return void 0;
  }
  if (relativeToInputDir) {
    const inputRealPath = normalizePath(relativeToInputDir);
    const outputRealPath = normalizePath(finalOutput);
    return relative4(inputRealPath, outputRealPath);
  } else {
    return finalOutput;
  }
}
function renderResultUrlPath(renderResult) {
  if (renderResult.baseDir && renderResult.outputDir) {
    const finalOutput = renderResultFinalOutput(
      renderResult
    );
    if (finalOutput) {
      const targetPath = pathWithForwardSlashes(relative4(
        join4(renderResult.baseDir, renderResult.outputDir),
        finalOutput
      ));
      return targetPath;
    }
  }
  return void 0;
}
function mergePandocIncludes(format14, pandocIncludes) {
  return mergeConfigs(format14, pandocIncludes);
}
async function runHtmlPostprocessors(inputMetadata, inputTraits, options, htmlPostprocessors, htmlFinalizers, renderedFormats, quiet) {
  const postProcessResult = {
    resources: [],
    supporting: []
  };
  if (htmlPostprocessors.length > 0 || htmlFinalizers.length > 0) {
    await withTimingAsync("htmlPostprocessors", async () => {
      const outputFile5 = isAbsolute4(options.output) ? options.output : join4(dirname4(options.source), options.output);
      const htmlInput = Deno.readTextFileSync(outputFile5);
      const doctypeMatch = htmlInput.match(/^<!DOCTYPE.*?>/);
      const doc = await parseHtml(htmlInput);
      for (let i6 = 0; i6 < htmlPostprocessors.length; i6++) {
        const postprocessor = htmlPostprocessors[i6];
        const result2 = await postprocessor(
          doc,
          {
            inputMetadata,
            inputTraits,
            renderedFormats,
            quiet
          }
        );
        postProcessResult.resources.push(...result2.resources);
        postProcessResult.supporting.push(...result2.supporting);
      }
      for (let i6 = 0; i6 < htmlFinalizers.length; i6++) {
        const finalizer = htmlFinalizers[i6];
        await finalizer(doc);
      }
      const htmlOutput = (doctypeMatch ? doctypeMatch[0] + "\n" : "") + doc.documentElement?.outerHTML;
      Deno.writeTextFileSync(outputFile5, htmlOutput);
    });
  }
  return postProcessResult;
}

// command/render/render-shared.ts
init_path();
init_log();
init_colors2();
await init_project_context();

// command/render/project.ts
init_fs();
init_path();
init_log();
init_colors2();
init_copy5();
init_lodash();
init_constants6();
init_types4();
init_project_scratch();
init_project_types();
init_project_resources();
init_project_gitignore();

// project/project-config.ts
init_path();
init_lodash();
init_path2();

// project/project-index.ts
init_path();
init_lodash();

// project/target-index-cache-metrics.ts
var inputTargetIndexCacheMetrics = {
  hits: 0,
  misses: 0,
  invalidations: 0
};

// project/project-index.ts
init_types4();
init_path2();
init_constants6();
await init_engine();
await init_project_shared();
init_project_scratch();
init_pandoc_partition();
init_yaml();
init_metadata();

// project/types/website/website-config.ts
init_lodash();
init_constants6();
init_format5();
init_metadata();
init_config2();
init_format_html_shared();
init_types4();
init_website_constants();
init_path2();
init_fs();
init_path();
function websiteConfigBoolean(name2, defaultValue, project) {
  const config2 = websiteConfig(name2, project);
  if (typeof config2 === "string") {
    return !!config2;
  } else if (typeof config2 == "boolean") {
    return config2;
  } else {
    return defaultValue;
  }
}
function websiteConfigString(name2, project) {
  const config2 = websiteConfig(name2, project);
  if (typeof config2 === "string") {
    return config2;
  } else {
    return void 0;
  }
}
function websiteConfigMetadata(name2, project) {
  const config2 = websiteConfig(name2, project);
  if (typeof config2 === "object" && !Array.isArray(config2)) {
    return config2;
  } else {
    return void 0;
  }
}
function websiteConfigArray(name2, project) {
  const config2 = websiteConfig(name2, project);
  if (Array.isArray(config2)) {
    return config2;
  } else {
    return void 0;
  }
}
function websiteConfig(name2, project) {
  const site = project?.[kWebsite];
  if (site) {
    return site[name2];
  } else {
    return void 0;
  }
}
function websiteConfigUnknown(name2, project) {
  const site = project?.[kWebsite];
  if (site) {
    return site[name2];
  } else {
    return void 0;
  }
}
function websiteTitle(project) {
  return websiteConfigString(kSiteTitle, project);
}
function websiteBaseurl(project) {
  return websiteConfigString(kSiteUrl, project);
}
function websiteImage(project) {
  const src2 = websiteConfigString(kImage, project);
  if (src2) {
    const alt = websiteConfigString("image-alt", project);
    return { src: src2, alt };
  } else {
    return void 0;
  }
}
function websiteDescription(project) {
  return websiteConfigString(kDescription, project);
}
function websitePath(project) {
  let path3 = websiteConfigString(kSitePath, project);
  if (path3) {
    if (!path3.endsWith("/")) {
      path3 = path3 + "/";
    }
    return path3;
  } else {
    const baseUrl = websiteBaseurl(project);
    if (baseUrl) {
      try {
        const url = new URL(baseUrl);
        let path4 = url.pathname;
        if (!path4.endsWith("/")) {
          path4 = path4 + "/";
        }
        return path4;
      } catch {
        return "/";
      }
    } else {
      return "/";
    }
  }
}
function websiteRepoInfo(format14, project) {
  let repoUrl = websiteConfigString(kSiteRepoUrl, project);
  if (format14.metadata[kSiteRepoUrl] !== void 0) {
    repoUrl = format14.metadata[kSiteRepoUrl];
  }
  if (repoUrl) {
    repoUrl = ensureTrailingSlash(repoUrl);
    const repoSubdir = websiteConfigString(kSiteRepoSubdir, project);
    if (repoSubdir) {
      return {
        baseUrl: repoUrl,
        path: ensureTrailingSlash(repoSubdir)
      };
    } else {
      return {
        baseUrl: repoUrl,
        path: ""
      };
    }
  } else {
    return void 0;
  }
}
function websiteRepoBranch(project) {
  return websiteConfigString(kSiteRepoBranch, project) || "main";
}
function websiteMetadataFields() {
  return [kWebsite, "site"];
}
function repoUrlIcon(url) {
  if (url.indexOf("github.com") !== -1) {
    return "github";
  } else {
    return "git";
  }
}
function websiteConfigActions(key, subkey, project) {
  const book = project?.[subkey];
  if (book) {
    const value = book[key];
    if (typeof value === "string") {
      if (value === "none") {
        return [];
      } else {
        return [value];
      }
    } else if (Array.isArray(value)) {
      return value.map((x3) => String(x3));
    } else {
      return [];
    }
  } else {
    return [];
  }
}
function websiteFormatPreferHtml(format14) {
  if (format14 !== void 0) {
    if (typeof format14 === "string") {
      return {
        [format14]: "default"
      };
    } else {
      const formats2 = Object.keys(format14);
      const orderedFormats = {};
      const htmlFormatPos = formats2.findIndex(
        (format15) => isHtmlOutput(format15, true)
      );
      if (htmlFormatPos !== -1) {
        const htmlFormatName = formats2.splice(htmlFormatPos, 1)[0];
        orderedFormats[htmlFormatName] = format14[htmlFormatName];
      }
      for (const formatName of formats2) {
        orderedFormats[formatName] = format14[formatName];
      }
      return orderedFormats;
    }
  } else {
    return {
      html: "default"
    };
  }
}
function formatsPreferHtml(formats2) {
  const orderedFormats = {};
  const formatNames = Object.keys(formats2);
  const htmlFormatPos = formatNames.findIndex(
    (format14) => isHtmlOutput(format14, true)
  );
  if (htmlFormatPos !== -1) {
    const htmlFormatName = formatNames.splice(htmlFormatPos, 1)[0];
    orderedFormats[htmlFormatName] = formats2[htmlFormatName];
  }
  for (const formatName of formatNames) {
    orderedFormats[formatName] = formats2[formatName];
  }
  return orderedFormats;
}
function websiteProjectConfig(project, config2, flags) {
  const projectDir = project.dir;
  config2 = cloneDeep(config2);
  const format14 = config2[kMetadataFormat];
  config2[kMetadataFormat] = websiteFormatPreferHtml(format14);
  const ensureArray = (val) => {
    if (Array.isArray(val)) {
      return val;
    } else if (typeof val === "string") {
      return [val];
    }
  };
  const siteMeta = config2[kWebsite] || {};
  siteMeta[kSiteTitle] = siteMeta[kSiteTitle] || config2.project[kProjectTitle];
  if (flags?.siteUrl) {
    siteMeta[kSiteUrl] = flags.siteUrl;
  }
  if (siteMeta[kBodyHeader]) {
    siteMeta[kBodyHeader] = ensureArray(siteMeta[kBodyHeader]);
  }
  if (siteMeta[kBodyFooter]) {
    siteMeta[kBodyFooter] = ensureArray(siteMeta[kBodyFooter]);
  }
  const resolveProjectPaths = (maybePath) => {
    if (existsSync2(maybePath)) {
      return join4(projectDir, maybePath);
    } else {
      return maybePath;
    }
  };
  if (siteMeta[kMarginHeader]) {
    siteMeta[kMarginHeader] = ensureArray(siteMeta[kMarginHeader])?.map(
      resolveProjectPaths
    );
  }
  if (siteMeta[kMarginFooter]) {
    siteMeta[kMarginFooter] = ensureArray(siteMeta[kMarginFooter])?.map(
      resolveProjectPaths
    );
  }
  config2[kWebsite] = siteMeta;
  const sidebarRaw = siteMeta[kSiteSidebar];
  const sidebars = Array.isArray(sidebarRaw) ? sidebarRaw : typeof sidebarRaw == "object" ? [sidebarRaw] : void 0;
  sidebars?.forEach((sidebar) => {
    const headerRaw = sidebar[kSiteSidebarHeader];
    if (headerRaw) {
      sidebar[kSiteSidebarHeader] = ensureArray(sidebar[kSiteSidebarHeader]);
    }
  });
  sidebars?.forEach((sidebar) => {
    const footerRaw = sidebar[kSiteSidebarFooter];
    if (footerRaw) {
      sidebar[kSiteSidebarFooter] = ensureArray(sidebar[kSiteSidebarFooter]);
    }
  });
  if (websiteConfigMetadata(kComments, config2) && config2[kComments] === void 0) {
    config2[kComments] = websiteConfigMetadata(kComments, config2);
  }
  if (websiteConfigUnknown(kOtherLinks, config2) && config2[kOtherLinks] === void 0) {
    config2[kOtherLinks] = websiteConfigUnknown(kOtherLinks, config2);
  }
  if (websiteConfigUnknown(kCodeLinks, config2) && config2[kCodeLinks] === void 0) {
    config2[kCodeLinks] = websiteConfigUnknown(kCodeLinks, config2);
  }
  const draftMode = websiteConfigString(kDraftMode, config2);
  if (draftMode) {
    config2[kDraftMode] = draftMode;
  }
  const drafts = websiteConfigArray(kDrafts, config2);
  if (drafts) {
    config2[kDrafts] = drafts;
  }
  return Promise.resolve(config2);
}
function websiteHtmlFormat(project) {
  const projConfig = project.config || {};
  const baseFormat = metadataAsFormat(projConfig);
  const format14 = formatFromMetadata(baseFormat, formatKeys(projConfig)[0]);
  return mergeConfigs(baseFormat, format14);
}

// project/project-index.ts
init_project_default();
init_render();
init_project_types();
await init_render_services();
init_format_html_shared();
async function inputTargetIndex(project, input) {
  const inputFile = join4(project.dir, input);
  if (!safeExistsSync(inputFile) || Deno.statSync(inputFile).isDirectory) {
    return Promise.resolve(void 0);
  }
  if (!project.files.input.includes(normalizePath(inputFile))) {
    return Promise.resolve(void 0);
  }
  const { index: targetIndex } = readInputTargetIndex(
    project.dir,
    input
  );
  if (targetIndex) {
    return targetIndex;
  }
  const index2 = await readBaseInputIndex(inputFile, project);
  if (index2) {
    const indexFile = inputTargetIndexFile(project.dir, input);
    Deno.writeTextFileSync(indexFile, JSON.stringify(index2));
  }
  return index2;
}
async function readBaseInputIndex(inputFile, project) {
  const engine = await fileExecutionEngine(inputFile, void 0, project);
  if (engine === void 0) {
    return Promise.resolve(void 0);
  }
  const formats2 = await withRenderServices(
    project.notebookContext,
    (services) => project.renderFormats(inputFile, services, "all", project)
  );
  const firstFormat = Object.values(formats2)[0];
  const markdown = await engine.partitionedMarkdown(inputFile, firstFormat);
  const index2 = {
    title: firstFormat?.metadata?.[kTitle] || markdown.yaml?.[kTitle] || markdown.headingText,
    markdown,
    formats: formats2,
    draft: firstFormat?.metadata?.[kDraft] || markdown.yaml?.[kDraft]
  };
  if (index2.title) {
    if (typeof index2.title !== "string") {
      throw new Error(
        `${relative4(project.dir, inputFile)}: Title must be a string, but is instead of type ${typeof index2.title}`
      );
    }
    const parsedTitle = parsePandocTitle(index2.title);
    index2.title = parsedTitle.heading;
  } else {
    index2.title = index2.markdown.headingText;
  }
  if (project.config) {
    index2.projectFormats = formatKeys(project.config);
  }
  return index2;
}
function readInputTargetIndex(projectDir, input) {
  const index2 = readInputTargetIndexIfStillCurrent(projectDir, input);
  if (!index2) {
    return {
      missingReason: "stale"
    };
  }
  if (Object.keys(index2.formats).includes("html")) {
    index2.formats = websiteFormatPreferHtml(index2.formats);
  }
  const formats2 = index2.projectFormats ?? Object.keys(index2.formats);
  const projConfigFile = projectConfigFile(projectDir);
  if (!projConfigFile) {
    return { index: index2 };
  }
  let contents = Deno.readTextFileSync(projConfigFile);
  if (contents.trim().length === 0) {
    contents = kDefaultProjectFileContents;
  }
  const config2 = readYamlFromString(contents);
  const projFormats = formatKeys(config2);
  if (isEqual(formats2, projFormats)) {
    return {
      index: index2
    };
  } else {
    return {
      missingReason: "formats"
    };
  }
}
function inputTargetIsEmpty(index2) {
  if (index2.markdown.markdown.trim().length > 0) {
    return false;
  }
  if (index2.markdown.yaml && Object.keys(index2.markdown.yaml).find((key) => key !== kTitle)) {
    return false;
  }
  return true;
}
var inputTargetIndexCache = /* @__PURE__ */ new Map();
function readInputTargetIndexIfStillCurrent(projectDir, input) {
  const inputFile = join4(projectDir, input);
  const indexFile = inputTargetIndexFile(projectDir, input);
  try {
    const inputMod = Deno.statSync(inputFile).mtime;
    const indexMod = Deno.statSync(indexFile).mtime;
    if (inputMod && indexMod) {
      if (inputMod > indexMod) {
        inputTargetIndexCacheMetrics.invalidations++;
        inputTargetIndexCache.delete(indexFile);
        return void 0;
      }
      if (inputTargetIndexCache.has(indexFile)) {
        inputTargetIndexCacheMetrics.hits++;
        return inputTargetIndexCache.get(indexFile);
      } else {
        inputTargetIndexCacheMetrics.misses++;
        try {
          const result2 = JSON.parse(
            Deno.readTextFileSync(indexFile)
          );
          inputTargetIndexCache.set(indexFile, result2);
          return result2;
        } catch {
          return void 0;
        }
      }
    }
  } catch (e5) {
    if (e5 instanceof Deno.errors.NotFound) {
      return void 0;
    } else {
      throw e5;
    }
  }
}
async function resolveInputTarget(project, href, absolute = true) {
  const index2 = await inputTargetIndex(project, href);
  if (index2) {
    const formats2 = formatsPreferHtml(index2.formats);
    const format14 = Object.values(formats2)[0];
    const projType = projectType(project.config?.project?.[kProjectType]);
    const projOutputFile = projType.outputFile ? projType.outputFile(href, format14, project) : void 0;
    const [hrefDir, hrefStem] = dirAndStem(href);
    const outputFile5 = projOutputFile || formatOutputFile(format14) || `${hrefStem}.html`;
    const outputHref = pathWithForwardSlashes(
      (absolute ? "/" : "") + join4(hrefDir, outputFile5)
    );
    const inputTarget = {
      input: href,
      title: index2.title,
      outputHref,
      draft: index2.draft === true
    };
    if (projType.filterInputTarget) {
      return projType.filterInputTarget(inputTarget, project);
    } else {
      return inputTarget;
    }
  } else {
    return void 0;
  }
}
async function inputFileForOutputFile(project, output) {
  const outputDir = projectOutputDir(project);
  output = isAbsolute4(output) ? output : join4(outputDir, output);
  if (project.outputNameIndex !== void 0) {
    return project.outputNameIndex.get(output);
  }
  project.outputNameIndex = /* @__PURE__ */ new Map();
  for (const file of project.files.input) {
    const inputRelative = relative4(project.dir, file);
    const index2 = await inputTargetIndex(
      project,
      relative4(project.dir, file)
    );
    if (index2) {
      Object.keys(index2.formats).forEach((key) => {
        const format14 = index2.formats[key];
        const outputFile5 = formatOutputFile(format14);
        if (outputFile5) {
          const formatOutputPath = join4(
            outputDir,
            dirname4(inputRelative),
            outputFile5
          );
          project.outputNameIndex.set(formatOutputPath, { file, format: format14 });
        }
      });
    }
  }
  return project.outputNameIndex.get(output);
}
async function inputTargetIndexForOutputFile(project, outputRelative) {
  const input = await inputFileForOutputFile(project, outputRelative);
  if (!input) {
    return void 0;
  }
  return await inputTargetIndex(
    project,
    relative4(project.dir, input.file)
  );
}
async function resolveInputTargetForOutputFile(project, outputRelative) {
  const input = await inputFileForOutputFile(project, outputRelative);
  if (!input) {
    return void 0;
  }
  return await resolveInputTarget(
    project,
    pathWithForwardSlashes(relative4(project.dir, input.file))
  );
}
function clearProjectIndex(projectDir) {
  const indexPath2 = projectScratchPath(projectDir, "idx");
  removeIfExists(indexPath2);
}
function inputTargetIndexFile(projectDir, input) {
  return indexPath(projectDir, `${input}.json`);
}
function indexPath(projectDir, path3) {
  return projectScratchPath(projectDir, join4("idx", path3));
}

// project/project-config.ts
await init_engine();
var sidebarContext = () => {
  return { counter: 0 };
};
function normalizeSidebarItem(projectDir, item, context) {
  item = cloneDeep(item);
  if (typeof item === "string") {
    if (safeExistsSync(join4(projectDir, item))) {
      item = {
        href: item
      };
    } else {
      item = {
        text: item
      };
    }
  } else {
    resolveHrefAttribute(item);
    const section = item.section;
    if (section) {
      context.counter = context.counter + 1;
      const sectionPath = join4(projectDir, section);
      if (safeExistsSync(sectionPath) && Deno.statSync(sectionPath).isFile) {
        item.href = section;
      } else {
        item.text = section;
      }
      item.sectionId = `${kQuartoSidebarPrefix}${context.counter}`;
      delete item.section;
      item.contents = item.contents || [];
    }
    if (item.contents) {
      for (let i6 = 0; i6 < item.contents.length; i6++) {
        item.contents[i6] = normalizeSidebarItem(
          projectDir,
          item.contents[i6],
          context
        );
      }
    }
  }
  return item;
}
var kQuartoSidebarPrefix = "quarto-sidebar-section-";
function resolveHrefAttribute(item) {
  item.href = item.href || item.file || item.url;
  delete item.file;
  delete item.url;
}
async function partitionedMarkdownForInput(project, input) {
  const { index: index2 } = readInputTargetIndex(project.dir, input);
  if (index2) {
    return index2.markdown;
  } else {
    const inputPath = join4(project.dir, input);
    const engine = await fileExecutionEngine(inputPath, void 0, project);
    if (engine) {
      return await engine.partitionedMarkdown(inputPath);
    } else {
      return void 0;
    }
  }
}

// core/handlers/mermaid.ts
await init_base();
init_resources2();
init_path();
init_format5();
init_mapped_text();

// core/svg.ts
init_constants6();
init_deno_dom();
init_error2();
init_mapped_text2();

// core/units.ts
function inInches(size) {
  if (size.endsWith("in")) {
    return Number(size.slice(0, -2));
  }
  if (size.endsWith("pt") || size.endsWith("px")) {
    return Number(size.slice(0, -2)) / 96;
  }
  return Number(size);
}

// core/svg.ts
async function resolveSize(svg, options) {
  const dom = (await getDomParser()).parseFromString(svg, "text/html");
  const svgEl = dom?.querySelector("svg");
  if (!svgEl) {
    throw new InternalError("Couldn't find an svg element in svg string");
  }
  let width = svgEl.getAttribute("width");
  let height = svgEl.getAttribute("height");
  const getViewBox = () => {
    const m4 = svg.match(/viewbox/i);
    if (!m4) return void 0;
    const vb = denoDomWorkaroundNamedItemAccessor(svg, svgEl, "viewbox")?.value;
    if (!vb) return void 0;
    const lst = vb.trim().split(" ").map(Number);
    if (lst.length !== 4) return void 0;
    if (lst.some(isNaN)) return void 0;
    return lst;
  };
  if (!width || !height) {
    const viewBox2 = getViewBox();
    if (viewBox2 !== void 0) {
      const [_mx, _my, vbWidth, vbHeight] = viewBox2;
      width = `${vbWidth}px`;
      height = `${vbHeight}px`;
    } else {
      throw new Error(
        "Mermaid generated an SVG without a viewbox attribute. Without knowing the diagram dimensions, quarto cannot convert it to a PNG"
      );
    }
  }
  let svgWidthInInches, svgHeightInInches;
  if (width.slice(0, -2) === "pt" && height.slice(0, -2) === "pt" || width.slice(0, -2) === "px" && height.slice(0, -2) === "px" || !isNaN(Number(width)) && !isNaN(Number(height))) {
    svgWidthInInches = Number(width.slice(0, -2)) / 96;
    svgHeightInInches = Number(height.slice(0, -2)) / 96;
  }
  const viewBox = getViewBox();
  if (viewBox !== void 0) {
    const [_mx, _my, vbWidth, vbHeight] = viewBox;
    svgWidthInInches = vbWidth / 96;
    svgHeightInInches = vbHeight / 96;
  } else {
    throw new InternalError("Couldn't resolve width and height of SVG");
  }
  const svgWidthOverHeight = svgWidthInInches / svgHeightInInches;
  let widthInInches, heightInInches;
  if (options?.[kFigWidth] && options?.[kFigHeight]) {
    widthInInches = inInches(String(options?.[kFigWidth]));
    heightInInches = inInches(String(options?.[kFigHeight]));
  } else if (options?.[kFigWidth]) {
    widthInInches = inInches(String(options?.[kFigWidth]));
    heightInInches = widthInInches / svgWidthOverHeight;
  } else if (options?.[kFigHeight]) {
    heightInInches = inInches(String(options?.[kFigHeight]));
    widthInInches = heightInInches * svgWidthOverHeight;
  } else {
    heightInInches = svgHeightInInches;
    widthInInches = svgWidthInInches;
  }
  return {
    widthInInches,
    heightInInches,
    widthInPoints: Math.round(widthInInches * 96),
    heightInPoints: Math.round(heightInInches * 96),
    explicitWidth: options?.[kFigWidth] !== void 0,
    explicitHeight: options?.[kFigHeight] !== void 0
  };
}
var fixupAlignment = (svg, align) => {
  let style = svg.getAttribute("style") ?? "";
  switch (align) {
    case "left":
      style = `${style}; display: block; margin: auto auto auto 0`;
      break;
    case "right":
      style = `${style}; display: block; margin: auto 0 auto auto`;
      break;
    case "center":
      style = `${style}; display: block; margin: auto auto auto auto`;
      break;
  }
  svg.setAttribute("style", style);
};
var denoDomWorkaroundNamedItemAccessor = (_str, el, key) => {
  key = key.toLocaleLowerCase();
  for (let i6 = 0; i6 < el.attributes.length; ++i6) {
    const attr = el.attributes.item(i6);
    if (attr?.name.toLowerCase() === key) {
      return attr;
    }
  }
  return null;
};
async function setSvgSize(svgSrc, options, extra) {
  const mappedSvgSrc = asMappedString(svgSrc);
  const {
    widthInPoints,
    heightInPoints,
    explicitHeight,
    explicitWidth
  } = await resolveSize(mappedSvgSrc.value, options);
  const dom = (await getDomParser()).parseFromString(
    mappedSvgSrc.value,
    "text/html"
  );
  const svg = dom.querySelector("svg");
  if (explicitWidth && explicitHeight) {
    svg.setAttribute("width", widthInPoints);
    svg.setAttribute("height", heightInPoints);
    svg.setAttribute(
      "style",
      (denoDomWorkaroundNamedItemAccessor(mappedSvgSrc.value, svg, "style")?.value || "") + "; max-width: none; max-height: none"
    );
  } else {
    let style = denoDomWorkaroundNamedItemAccessor(mappedSvgSrc.value, svg, "style")?.value || "";
    if (explicitWidth) {
      style = `${style}; max-width: ${widthInPoints}px`;
    }
    if (explicitHeight) {
      style = `${style}; max-height: ${heightInPoints}px`;
    }
    if (explicitWidth || explicitHeight) {
      svg.setAttribute("style", style);
    }
  }
  if (extra) {
    extra(svg);
  }
  return mappedDiff(mappedSvgSrc, svg.outerHTML);
}
async function makeResponsive(svgSrc, extras) {
  const mappedSvgSrc = asMappedString(svgSrc);
  const dom = (await getDomParser()).parseFromString(
    mappedSvgSrc.value,
    "text/html"
  );
  if (dom === null) {
    throw new Error("Couldn't parse element");
  }
  const svg = dom.querySelector("svg");
  if (svg === null) {
    throw new Error("Couldn't find SVG element");
  }
  const width = svg.getAttribute("width");
  if (width === null) {
    throw new Error("Couldn't find SVG width");
  }
  const numWidth = Number(width.slice(0, -2));
  let changed = false;
  if (numWidth > 650) {
    changed = true;
    svg.setAttribute("width", "100%");
    svg.removeAttribute("height");
  }
  if (extras) {
    changed = true;
    extras(svg);
  }
  if (changed) {
    return mappedDiff(mappedSvgSrc, svg.outerHTML);
  } else {
    return mappedSvgSrc;
  }
}

// core/handlers/mermaid.ts
init_constants6();
init_from_yaml();
init_yaml();
init_codegen();
init_located_error();
init_log();
init_mapped_text2();
init_lodash();
var mermaidHandler = {
  ...baseHandler,
  schema() {
    return Promise.resolve(convertFromYaml(readYamlFromString(`
object:
  properties:
    mermaid-format:
      enum: [png, svg, js]
    theme:
      anyOf:
        - null
        - string
`)));
  },
  type: "cell",
  stage: "post-engine",
  languageName: "mermaid",
  languageClass: (options) => {
    if (isMarkdownOutput(options.format, ["gfm"])) {
      return "mermaid-source";
    } else {
      return "default";
    }
  },
  defaultOptions: {
    echo: false,
    eval: true,
    include: true
  },
  comment: "%%",
  async cell(handlerContext, cell, options) {
    const mermaidOpts = {};
    if (typeof handlerContext.options.format.metadata.mermaid === "object" && handlerContext.options.format.metadata.mermaid) {
      const { mermaid } = handlerContext.options.format.metadata;
      if (mermaid.theme) {
        mermaidOpts.theme = mermaid.theme;
      } else {
        mermaidOpts.theme = "neutral";
      }
    }
    const cellContent = handlerContext.cellContent(cell);
    const content = `<html>
<head>
<script src="./mermaid.min.js"><\/script>
</head>
<body>
<pre class="mermaid">
${escape(cellContent.value)}
</pre> 
<script>
mermaid.initialize(${JSON.stringify(mermaidOpts)});
<\/script>
</html>`;
    const selector = "pre.mermaid svg";
    const resources = [[
      "mermaid.min.js",
      Deno.readTextFileSync(
        formatResourcePath("html", join4("mermaid", "mermaid.min.js"))
      )
    ]];
    const setupMermaidSvgJsRuntime = () => {
      if (handlerContext.getState().hasSetupMermaidSvgJsRuntime) {
        return;
      }
      handlerContext.getState().hasSetupMermaidSvgJsRuntime = true;
      const dep = {
        name: "quarto-diagram",
        scripts: [
          {
            name: "mermaid-postprocess-shim.js",
            path: formatResourcePath(
              "html",
              join4("mermaid", "mermaid-postprocess-shim.js")
            ),
            afterBody: true
          }
        ]
      };
      handlerContext.addHtmlDependency(dep);
    };
    const setupMermaidJsRuntime = () => {
      if (handlerContext.getState().hasSetupMermaidJsRuntime) {
        return;
      }
      handlerContext.getState().hasSetupMermaidJsRuntime = true;
      const jsName = handlerContext.options.context.format.metadata?.["mermaid-debug"] ? "mermaid.js" : "mermaid.min.js";
      if (mermaidOpts.theme) {
        const mermaidMeta = {};
        mermaidMeta["mermaid-theme"] = mermaidOpts.theme;
        handlerContext.addHtmlDependency({
          name: "quarto-mermaid-conf",
          meta: mermaidMeta
        });
      }
      const dep = {
        name: "quarto-diagram",
        scripts: [
          {
            name: jsName,
            path: formatResourcePath("html", join4("mermaid", jsName))
          },
          {
            name: "mermaid-init.js",
            path: formatResourcePath(
              "html",
              join4("mermaid", "mermaid-init.js")
            ),
            afterBody: true
          }
        ],
        stylesheets: [
          {
            name: "mermaid.css",
            path: formatResourcePath("html", join4("mermaid", "mermaid.css"))
          }
        ]
      };
      handlerContext.addHtmlDependency(dep);
    };
    const makeFigLink = (sourceName, width, height, includeCaption) => {
      const figEnvSpecifier = isLatexOutput(handlerContext.options.format.pandoc) ? ` fig-env='${cell.options?.["fig-env"] || "figure"}'` : "";
      let posSpecifier = "";
      if (isLatexOutput(handlerContext.options.format.pandoc) && cell.options?.["fig-pos"] !== false) {
        const v4 = Array.isArray(cell.options?.["fig-pos"]) ? cell.options?.["fig-pos"].join("") : cell.options?.["fig-pos"];
        posSpecifier = ` fig-pos='${v4 || "H"}'`;
      }
      const idSpecifier = cell.options?.label && includeCaption ? ` #${cell.options?.label}` : "";
      const widthSpecifier = width ? `width="${Math.round(width * 100) / 100}in"` : "";
      const heightSpecifier = height ? ` height="${Math.round(height * 100) / 100}in"` : "";
      const captionSpecifier = includeCaption ? cell.options?.["fig-cap"] || "" : "";
      return `
![${captionSpecifier}](${sourceName}){${widthSpecifier}${heightSpecifier}${posSpecifier}${figEnvSpecifier}${idSpecifier}}
`;
    };
    const responsive = handlerContext.options.context.format.metadata?.[kFigResponsive];
    const makeSvg = async () => {
      let svg = asMappedString(
        (await handlerContext.extractHtml({
          html: content,
          selector,
          resources
        }))[0]
      );
      const fixupRevealAlignment = (svg2) => {
        if (isRevealjsOutput(handlerContext.options.context.format.pandoc)) {
          const align = options?.[kFigAlign] ?? "center";
          fixupAlignment(svg2, align);
        }
      };
      let newId = void 0;
      const idsToPatch = [];
      const fixupMermaidSvg = (svg2) => {
        const { baseName: newMermaidId } = handlerContext.uniqueFigureName(
          "mermaid-figure-",
          ""
        );
        newId = newMermaidId;
        fixupRevealAlignment(svg2);
        const oldId = svg2.getAttribute("id");
        svg2.setAttribute("id", newMermaidId);
        const style = svg2.querySelector("style");
        style.innerHTML = style.innerHTML.replaceAll(oldId, () => newMermaidId);
        for (const defNode of svg2.querySelectorAll("defs")) {
          const defEl = defNode;
          const m4 = defEl.innerHTML.match(/id="([^\"]+)"/);
          if (m4) {
            const id = m4[1];
            idsToPatch.push(id);
          }
        }
      };
      if (responsive && options[kFigWidth] === void 0 && options[kFigHeight] === void 0) {
        svg = await makeResponsive(svg, fixupMermaidSvg);
      } else {
        svg = await setSvgSize(svg, options, (svg2) => {
          svg2.removeAttribute("style");
          fixupMermaidSvg(svg2);
        });
      }
      if (idsToPatch.length) {
        let oldSvgSrc = svg.value;
        for (const idToPatch of idsToPatch) {
          const to = `${newId}-${idToPatch}`;
          oldSvgSrc = oldSvgSrc.replaceAll(
            `"${idToPatch}"`,
            () => `"${to}"`
          );
          oldSvgSrc = oldSvgSrc.replaceAll(
            `#${idToPatch}`,
            () => `#${to}`
          );
        }
        svg = mappedDiff(svg, oldSvgSrc);
      }
      if (isMarkdownOutput(handlerContext.options.format, ["gfm"]) || !isJavascriptCompatible(handlerContext.options.format)) {
        if (!isMarkdownOutput(handlerContext.options.format, ["gfm"])) {
          let warning = `Using mermaid-format: svg with ${handlerContext.options.format.pandoc.to ?? "non-HTML"} format. Note: diagrams with multi-line text labels may experience clipping`;
          if (isLatexOutput(handlerContext.options.format.pandoc)) {
            warning += " and requires external tooling (rsvg-convert or Inkscape)";
          }
          warning += ". Consider using mermaid-format: png if issues occur.";
          info(warning);
        }
        const { sourceName, fullName } = handlerContext.uniqueFigureName(
          "mermaid-figure-",
          ".svg"
        );
        Deno.writeTextFileSync(fullName, svg.value);
        const {
          widthInInches,
          heightInInches
        } = await resolveSize(svg.value, cell.options ?? {});
        return asMappedString(
          makeFigLink(sourceName, widthInInches, heightInInches, true)
        );
      } else {
        setupMermaidSvgJsRuntime();
        return this.build(
          handlerContext,
          cell,
          svg,
          options,
          void 0,
          /* @__PURE__ */ new Set([kFigWidth, kFigHeight, kMermaidFormat])
        );
      }
    };
    const makePng = async () => {
      const {
        filenames: [sourceName],
        elements: [svgText]
      } = await handlerContext.createPngsFromHtml({
        prefix: "mermaid-figure-",
        selector,
        count: 1,
        deviceScaleFactor: Number(options.deviceScaleFactor) || 4,
        html: content,
        resources
      });
      const {
        widthInInches,
        heightInInches
      } = await resolveSize(svgText, cell.options ?? {});
      if (isMarkdownOutput(handlerContext.options.format, ["gfm"])) {
        return asMappedString(makeFigLink(
          sourceName,
          widthInInches,
          heightInInches,
          true
        ));
      } else {
        return this.build(
          handlerContext,
          cell,
          asMappedString(makeFigLink(
            sourceName,
            widthInInches,
            heightInInches
          )),
          options,
          void 0,
          /* @__PURE__ */ new Set([kFigWidth, kFigHeight, kMermaidFormat])
        );
      }
    };
    const makeJs = async () => {
      setupMermaidJsRuntime();
      const preAttrs = [];
      if (options.label) {
        preAttrs.push(`label="${options.label}"`);
      }
      const preEl = pandocHtmlBlock("pre")({
        classes: ["mermaid", "mermaid-js"],
        attrs: preAttrs
      });
      const content2 = handlerContext.cellContent(cell);
      preEl.push(pandocRawStr(escape(content2.value)));
      const attrs = {};
      if (isRevealjsOutput(handlerContext.options.context.format.pandoc)) {
        attrs.reveal = true;
      }
      return this.build(
        handlerContext,
        cell,
        mappedConcat([
          preEl.mappedString()
          // tooltips appear to be broken in mermaid 9.2.2?
          // They don't even work on their website: https://mermaid-js.github.io/mermaid/#/flowchart
          // we drop them for now.
          // `\n<div id="${tooltipName}" class="mermaidTooltip"></div>`,
        ]),
        options,
        attrs,
        /* @__PURE__ */ new Set([kMermaidFormat])
      );
    };
    const makeDefault = async () => {
      if (isIpynbOutput(handlerContext.options.format.pandoc)) {
        return await makePng();
      } else if (isJavascriptCompatible(handlerContext.options.format)) {
        return await makeJs();
      } else if (isMarkdownOutput(handlerContext.options.format, ["gfm"])) {
        return mappedConcat([
          "\n``` mermaid\n",
          cellContent,
          "\n```\n"
        ]);
      } else {
        return await makePng();
      }
    };
    const format14 = options[kMermaidFormat] || handlerContext.options.format.execute[kMermaidFormat];
    if (format14 === "svg") {
      return await makeSvg();
    } else if (format14 === "png") {
      return await makePng();
    } else if (format14 === "js") {
      if (!isJavascriptCompatible(handlerContext.options.format)) {
        const error2 = new LocalizedError3(
          "IncompatibleOutput",
          `\`mermaid-format: js\` not supported in format ${handlerContext.options.format.pandoc.to ?? ""}`,
          cell.sourceVerbatim,
          0
        );
        warn(error2.message);
        console.log("");
        return await makeDefault();
      } else {
        if (isRevealjsOutput(handlerContext.options.context.format.pandoc)) {
          const error2 = new LocalizedError3(
            "NotRecommended",
            `\`mermaid-format: js\` not recommended in format ${handlerContext.options.format.pandoc.to ?? ""}`,
            cell.sourceVerbatim,
            0
          );
          warn(error2.message);
          console.log("");
        }
        return await makeJs();
      }
    } else {
      return await makeDefault();
    }
  }
};
install2(mermaidHandler);

// core/handlers/include.ts
await init_base();
init_include_standalone();
var includeHandler = {
  ...baseHandler,
  languageName: "include",
  type: "directive",
  stage: "pre-engine",
  async directive(handlerContext, directive) {
    const param = directive.shortcode.params[0];
    if (!param) {
      throw new Error("Include directive needs filename as a parameter");
    }
    return await standaloneInclude(handlerContext, param);
  }
};
install2(includeHandler);

// core/handlers/dot.ts
await init_base();
init_resources2();
init_path();
init_format5();
init_mapped_text();
init_text();
init_constants6();
init_deno_dom();
var dotHandler = {
  ...baseHandler,
  type: "cell",
  stage: "post-engine",
  languageName: "dot",
  defaultOptions: {
    echo: false,
    eval: true,
    include: true,
    "graph-layout": "dot"
  },
  comment: "//",
  async cell(handlerContext, cell, options) {
    const cellContent = handlerContext.cellContent(cell);
    const graphvizModule = await import(toFileUrl4(resourcePath(join4("js", "graphviz-wasm.js"))).href);
    let svg;
    const oldConsoleLog = console.log;
    const oldConsoleWarn = console.warn;
    console.log = () => {
    };
    console.warn = () => {
    };
    try {
      svg = await graphvizModule.graphviz().layout(
        cellContent.value,
        "svg",
        options["graph-layout"]
      );
      console.log = oldConsoleLog;
      console.warn = oldConsoleWarn;
    } catch (e5) {
      if (!(e5 instanceof Error)) throw e5;
      console.log = oldConsoleLog;
      console.warn = oldConsoleWarn;
      const m4 = e5.message.match(
        /(.*)syntax error in line (\d+)(.*)/
      );
      if (m4) {
        const number2 = Number(m4[2]) - 1;
        const locF = mappedIndexToLineCol(cellContent);
        const offsets = Array.from(lineOffsets(cellContent.value));
        const offset3 = offsets[number2];
        const mapResult = cellContent.map(offset3, true);
        const { line } = locF(offset3);
        e5.message = e5.message.replace(
          m4[0],
          `${m4[1]}syntax error in file ${mapResult.originalString.fileName}, line ${line + 1}${m4[3]}`
        );
        throw e5;
      } else {
        throw e5;
      }
    }
    const makeFigLink = (sourceName, width, height, includeCaption) => {
      const figEnvSpecifier = isLatexOutput(handlerContext.options.format.pandoc) ? ` fig-env='${cell.options?.["fig-env"] || "figure"}'` : "";
      const heightOffset = isTypstOutput(handlerContext.options.format.pandoc) ? 0.1 : 0;
      let posSpecifier = "";
      if (isLatexOutput(handlerContext.options.format.pandoc) && cell.options?.["fig-pos"] !== false) {
        const v4 = Array.isArray(cell.options?.["fig-pos"]) ? cell.options?.["fig-pos"].join("") : cell.options?.["fig-pos"];
        posSpecifier = ` fig-pos='${v4 || "H"}'`;
      }
      const idSpecifier = cell.options?.label && includeCaption ? ` #${cell.options?.label}` : "";
      const widthSpecifier = width ? `width="${Math.round(width * 100) / 100}in"` : "";
      const heightSpecifier = height ? ` height="${Math.round(height * 100) / 100 + heightOffset}in"` : "";
      const captionSpecifier = includeCaption ? cell.options?.["fig-cap"] || "" : "";
      return `
![${captionSpecifier}](${sourceName}){${widthSpecifier}${heightSpecifier}${posSpecifier}${figEnvSpecifier}${idSpecifier}}
`;
    };
    const fixupRevealAlignment = (svg2) => {
      if (isRevealjsOutput(handlerContext.options.context.format.pandoc)) {
        const align = options?.[kFigAlign] ?? "center";
        fixupAlignment(svg2, align);
      }
    };
    if (isJavascriptCompatible(handlerContext.options.format) && !isIpynbOutput(handlerContext.options.format.pandoc)) {
      const responsive = options?.[kFigResponsive] ?? handlerContext.options.context.format.metadata?.[kFigResponsive];
      svg = (await parseHtml(svg)).querySelector("svg").outerHTML;
      if (responsive && options[kFigWidth] === void 0 && options[kFigHeight] === void 0) {
        svg = await makeResponsive(svg, fixupRevealAlignment);
      } else {
        svg = await setSvgSize(svg, options, fixupRevealAlignment);
      }
      svg = mappedConcat(["```{=html}\n", svg, "\n```\n"]);
      return this.build(handlerContext, cell, svg, options);
    } else {
      const {
        filenames: [sourceName]
      } = await handlerContext.createPngsFromHtml({
        prefix: "dot-figure-",
        selector: "svg",
        count: 1,
        deviceScaleFactor: Number(options.deviceScaleFactor) || 4,
        html: `<!DOCTYPE html><html><body>${svg}</body></html>`
      });
      const {
        widthInInches,
        heightInInches
      } = await resolveSize(svg, options);
      const isIpynbSourceOutput = isIpynbOutput(handlerContext.options.context.format.pandoc) && handlerContext.options.context.format.render[kIpynbProduceSourceNotebook];
      if (isIpynbSourceOutput) {
        const figLink = makeFigLink(
          sourceName,
          widthInInches,
          heightInInches,
          true
        );
        return mappedConcat(["\n:::{.cell .markdown}", figLink, ":::\n"]);
      } else {
        return this.build(
          handlerContext,
          cell,
          mappedConcat([
            makeFigLink(
              sourceName,
              widthInInches,
              heightInInches
            )
            //          `\n![](${sourceName}){width="${widthInInches}in" height="${heightInInches}in" fig-pos='H'}\n`,
          ]),
          options
        );
      }
    }
  }
};
install2(dotHandler);

// core/handlers/embed.ts
await init_base();
init_mapped_text();
var kHandlers = [
  {
    name: "Jupyter Notebook Embed",
    handle(filename, params, handlerContext) {
      const markdownFragments = [];
      const notebookAddress = parseNotebookAddress(filename);
      if (notebookAddress) {
        const outputs = params.outputs;
        const placeHolder = notebookMarkdownPlaceholder(
          handlerContext.options.context.target.input,
          filename,
          {
            echo: params.echo !== void 0 ? params.echo : false,
            warning: false,
            asis: true,
            eval: false
          },
          outputs
        );
        markdownFragments.push(placeHolder);
        return Promise.resolve({
          handled: true,
          markdownFragments,
          resources: [
            notebookAddress.path
          ]
        });
      } else {
        return Promise.resolve({
          handled: false,
          markdownFragments: []
        });
      }
    }
  }
];
var embedHandler = {
  ...baseHandler,
  languageName: "embed",
  type: "directive",
  stage: "post-engine",
  async directive(handlerContext, directive) {
    const textFragments = [];
    const filename = directive.shortcode.params[0];
    if (!filename) {
      throw new Error("Embed directive requires a filename as a parameter");
    }
    for (const handler of kHandlers) {
      const result2 = await handler.handle(
        filename,
        directive.shortcode.namedParams,
        handlerContext
      );
      if (result2.handled) {
        textFragments.push(...result2.markdownFragments);
        if (result2.resources) {
          result2.resources.forEach((res) => {
            handlerContext.addResource(res);
          });
        }
        break;
      }
    }
    return mappedConcat(textFragments);
  }
};
install2(embedHandler);

// command/render/render-files.ts
init_constants6();
init_format5();
init_config2();
init_deno_dom();
await init_base();
init_mapped_text2();

// core/schema/validate-document.ts
init_break_quarto_md();
init_mapped_text2();

// core/ranged-text.ts
init_ranged_text();

// core/schema/annotated-yaml.ts
init_annotated_yaml();

// core/schema/validate-document.ts
init_log();
init_partition_cell_options();
init_validator_queue();
init_validated_yaml2();
init_errors();
init_lodash();
init_front_matter();
async function validateDocumentFromSource(src2, engine, errorFn) {
  const result2 = [];
  const reportSet = /* @__PURE__ */ new Set();
  const nb = await breakQuartoMd(src2);
  if (nb.cells.length < 1) {
    return [];
  }
  const firstCell = nb.cells[0];
  let firstContentCellIndex;
  if (firstCell.source.value.startsWith("---")) {
    firstContentCellIndex = 1;
    if (!firstCell.source.value.trimEnd().endsWith("---")) {
      throw new Error("Expected YAML front matter to end with '---'");
    }
    const lineRanges = rangedLines(firstCell.source.value.trimEnd());
    if (lineRanges.length < 2) {
      if (src2.map(0)?.originalString?.fileName) {
        throw new Error(
          `${src2.map(0)?.originalString?.fileName}: Expected YAML front matter to contain at least 2 lines`
        );
      } else {
        throw new Error("Expected front matter to have at least 2 lines");
      }
    }
    const frontMatterText = mappedString(
      firstCell.source,
      [{
        start: lineRanges[1].range.start,
        end: lineRanges[lineRanges.length - 2].range.end
      }]
    );
    const annotation = readAnnotatedYamlFromMappedString(frontMatterText);
    if (annotation.result === null || !isObject(annotation.result) || annotation.result["validate-yaml"] !== false) {
      const frontMatterSchema = await getFrontMatterSchema();
      try {
        await withValidator(frontMatterSchema, async (frontMatterValidator) => {
          const fmValidation = await frontMatterValidator.validateParseWithErrors(
            frontMatterText,
            annotation,
            "Validation of YAML front matter failed.",
            errorFn,
            reportOnce(
              (err2) => error(tidyverseFormatError(err2), { colorize: false }),
              reportSet
            )
          );
          if (fmValidation && fmValidation.errors.length) {
            result2.push(...fmValidation.errors);
          }
        });
      } catch (e5) {
        if (!(e5 instanceof Error)) throw e5;
        if (e5.name === "NoExprTag") {
          const err2 = e5;
          error(tidyverseFormatError(err2.niceError), { colorize: false });
          throw e5;
        }
      }
    }
  } else {
    firstContentCellIndex = 0;
  }
  for (const cell of nb.cells.slice(firstContentCellIndex)) {
    if (cell.cell_type === "markdown" || cell.cell_type === "raw" || cell.cell_type?.language === "_directive") {
      continue;
    }
    const lang = cell.cell_type.language;
    try {
      if (cell.sourceWithYaml) {
        await partitionCellOptionsMapped(
          lang,
          cell.sourceWithYaml,
          true,
          engine
        );
      }
    } catch (e5) {
      if (e5 instanceof ValidationError4) {
        error("Validation of YAML cell metadata failed.");
        for (const err2 of e5.validationErrors) {
          error(tidyverseFormatError(err2.niceError), { colorize: false });
        }
        result2.push(...e5.validationErrors);
      } else {
        throw e5;
      }
    }
  }
  return result2;
}
async function validateDocument(context) {
  if (context.target.markdown.value === "") {
    return [];
  }
  return validateDocumentFromSource(
    context.target.markdown,
    context.engine.name,
    error
  );
}

// command/render/render-files.ts
init_temp();
await init_engine();

// execute/ojs/annotate-source.ts
init_text2();
init_jupyter();
function annotateOjsLineNumbers(context) {
  const canPatch = !isJupyterNotebook(context.target.source);
  if (canPatch) {
    const source2 = lines(Deno.readTextFileSync(context.target.source));
    const ojsBlockLineNumbers = [];
    let lineNumber = 1;
    const chunkBegin = /^[\t ]*```+\s*\{(ojs( *[ ,].*)?)\}\s*$/;
    source2.forEach((line) => {
      lineNumber++;
      if (line.match(chunkBegin)) {
        ojsBlockLineNumbers.push(lineNumber);
      }
    });
    return {
      ojsBlockLineNumbers
    };
  } else {
    return {
      ojsBlockLineNumbers: []
    };
  }
}

// execute/ojs/compile.ts
init_path();
init_log();
init_lodash();
init_types5();
init_constants6();
init_format5();

// execute/ojs/errors.ts
init_log();
init_mapped_text();
function ojsParseError(acornError, ojsSource) {
  const acornMsg = String(acornError).split("\n")[0].trim().replace(
    / *\(\d+:\d+\)$/,
    ""
  );
  const { line, column } = mappedIndexToLineCol(ojsSource)(acornError.pos);
  const errLines = [];
  const ourError = (msg5) => {
    if (msg5.length) {
      errLines.push(msg5);
    }
  };
  const errMsg = `OJS parsing failed on line ${line + 1}, column ${column + 1}`;
  ourError(errMsg);
  ourError(acornMsg);
  if (acornMsg.endsWith("Unexpected character '#'") && ojsSource.value.slice(acornError.pos, acornError.pos + 2) === "#|") {
    ourError("\n(Did you mean to use '//|' instead?)\n");
  }
  ourError("----- OJS Source:");
  const ojsSourceSplit = ojsSource.value.split("\n");
  for (let i6 = 0; i6 < ojsSourceSplit.length; ++i6) {
    ourError(ojsSourceSplit[i6]);
    if (i6 + 1 === acornError.loc.line) {
      ourError(" ".repeat(acornError.loc.column) + "^");
    }
  }
  ourError("-----");
  if (errLines.length) {
    error(errLines.join("\n"));
  }
}

// execute/ojs/compile.ts
init_constants6();
init_html();
init_quarto();
init_config2();
init_resources2();
init_log2();
init_break_quarto_md();
init_pandoc_partition();
init_codegen();
init_mapped_text();
await init_base();
init_path2();
init_execute_inline();
init_base64();
var ojsHasOutputs = (parse24) => {
  let hasOutputs = false;
  ojsSimpleWalker(parse24, {
    Cell(node) {
      if (node.id === null) {
        hasOutputs = true;
      }
    }
  });
  return hasOutputs;
};
async function ojsCompile(options) {
  const { markdown, project, ojsBlockLineNumbers } = options;
  const output = await breakQuartoMd(markdown, true);
  const hasOjsDefines = markdown.value.indexOf("ojs_define") !== -1;
  if (!isJavascriptCompatible(options.format) || options.format.metadata?.["ojs-engine"] === false) {
    return { markdown };
  }
  const languages2 = languagesInMarkdown(markdown.value);
  if (options.format.metadata?.["ojs-engine"] !== true && !languages2.has("ojs") && !hasOjsDefines) {
    return { markdown };
  }
  const projDir = project.isSingleFile ? void 0 : project.dir;
  const selfContained = options.format.pandoc?.[kSelfContained] ?? options.format.pandoc?.[kEmbedResources] ?? false;
  const isHtmlMarkdown = isMarkdownOutput(options.format, [
    "gfm",
    "commonmark"
  ]);
  let ojsCellID = 0;
  let ojsBlockIndex = 0;
  const userIds = /* @__PURE__ */ new Set();
  const scriptContents = [];
  const ojsRuntimeDir = resolve4(
    dirname4(options.source),
    options.libDir + "/ojs"
  );
  const docDir = dirname4(options.source);
  const rootDir = projDir ?? "./";
  const runtimeToDoc = pathWithForwardSlashes(relative4(ojsRuntimeDir, docDir));
  const runtimeToRoot = pathWithForwardSlashes(
    relative4(ojsRuntimeDir, rootDir)
  );
  const docToRoot = pathWithForwardSlashes(relative4(docDir, rootDir));
  scriptContents.push(
    `if (window.location.protocol === "file:") { alert("The OJS runtime does not work with file:// URLs. Please use a web server to view this document."); }`
  );
  scriptContents.push(`window._ojs.paths.runtimeToDoc = "${runtimeToDoc}";`);
  scriptContents.push(`window._ojs.paths.runtimeToRoot = "${runtimeToRoot}";`);
  scriptContents.push(`window._ojs.paths.docToRoot = "${docToRoot}";`);
  scriptContents.push(
    `window._ojs.selfContained = ${selfContained};`
  );
  const moduleContents = [];
  function interpret(jsSrc, inline, lenient) {
    const inlineStr = inline ? "inline-" : "";
    const methodName = lenient ? "interpretLenient" : "interpret";
    moduleContents.push({
      methodName,
      cellName: `ojs-${inlineStr}cell-${ojsCellID}`,
      inline,
      // FIXME This here is the big problem now. We'd like to send
      // jsSrc as is,
      //
      // but moduleContents needs to be JSON-serializable in order for
      // the runtime to interpret it. But that gives problems with
      // respect to our ability to compute offsets etc.
      source: jsSrc.value
    });
  }
  const ls = [];
  const resourceFiles = [];
  const pageResources = [];
  const ojsViews = /* @__PURE__ */ new Set();
  const ojsIdentifiers = /* @__PURE__ */ new Set();
  for (const cell of output.cells) {
    const errorVal = cell.options?.[kError] ?? options.format.execute?.[kError] ?? false;
    const handleOJSCell = async (cell2, mdClassList) => {
      const cellSrcStr = cell2.source;
      const bumpOjsCellIdString = () => {
        ojsCellID += 1;
        return `ojs-cell-${ojsCellID}`;
      };
      const ojsId = bumpOjsCellIdString();
      const userCellId = () => {
        const chooseId = (label) => {
          const htmlLabel = asHtmlId(label);
          if (userIds.has(htmlLabel)) {
            throw new Error(`FATAL: duplicate label ${htmlLabel}`);
          } else {
            userIds.add(htmlLabel);
            return htmlLabel;
          }
        };
        if (cell2.options?.label) {
          return chooseId(cell2.options.label);
        } else if (cell2.options?.[kCellLstLabel]) {
          return chooseId(cell2.options[kCellLstLabel]);
        } else if (cell2.options?.[kCellFigCap] || cell2.options?.[kCellFigSubCap] || cell2.options?.[kCellLstCap]) {
          return chooseId(`fig-${ojsId}`);
        } else {
          return void 0;
        }
      };
      const userId = userCellId();
      const attrs = [];
      const hasFigureSubCaptions = () => {
        return cell2.options?.[kCellFigSubCap];
      };
      const cellStartingLoc = ojsBlockLineNumbers[ojsBlockIndex++] || 0;
      if (cellStartingLoc === 0) {
        warn(
          "OJS block count mismatch. Line number reporting is likely to be wrong"
        );
      }
      const handleError = (err2, cellSrc) => {
        const div2 = pandocDiv({
          classes: ["quarto-ojs-syntax-error"]
        });
        const msg5 = String(err2).split("\n")[0].trim().replace(
          / *\(\d+:\d+\)$/,
          ""
        );
        ojsParseError(err2, cellSrc);
        const preDiv = pandocCode({
          classes: ["numberLines", "java"],
          attrs: [
            `startFrom="${cellStartingLoc - 1}"`,
            `syntax-error-position="${err2.pos}"`,
            `source-offset="${cell2.sourceOffset}"`
          ]
        });
        preDiv.push(pandocRawStr(cell2.sourceVerbatim.value.trim()));
        div2.push(preDiv);
        const errMsgDiv = pandocDiv({
          classes: ["cell-output", "cell-output-error"]
        });
        const calloutDiv = pandocDiv({
          classes: ["callout-important"]
        });
        const [_heading, fullMsg] = msg5.split(": ");
        calloutDiv.push(
          pandocRawStr(
            `#### OJS Syntax Error (line ${err2.loc.line + cellStartingLoc + cell2.sourceStartLine - 1}, column ${err2.loc.column + 1})`
          )
        );
        calloutDiv.push(pandocRawStr(`${fullMsg}`));
        errMsgDiv.push(calloutDiv);
        div2.push(errMsgDiv);
        div2.emit(ls);
      };
      let nCells = 0;
      const parsedCells = [];
      let hasOutputs = true;
      try {
        const parse24 = parseModule(cellSrcStr.value);
        hasOutputs = ojsHasOutputs(parse24);
        let info2 = [];
        const flushSeqSrc = () => {
          parsedCells.push({ info: info2 });
          for (let i6 = 1; i6 < info2.length; ++i6) {
            parsedCells.push({ info: [] });
          }
          info2 = [];
        };
        ojsSimpleWalker(parse24, {
          // deno-lint-ignore no-explicit-any
          Cell(node) {
            if (node.id && node.id.type === "ViewExpression") {
              ojsViews.add(node.id.id.name);
            } else if (node.id && node.id.type === "Identifier") {
              ojsIdentifiers.add(node.id.name);
            }
            if (node.id === null && node.body.type !== "ImportDeclaration") {
              info2.push({
                start: node.start,
                end: node.end,
                cellType: "expression"
              });
              flushSeqSrc();
            } else {
              info2.push({
                start: node.start,
                end: node.end,
                cellType: "declaration"
              });
            }
          }
        });
        nCells = parse24.cells.length;
        if (info2.length > 0) {
          flushSeqSrc();
        }
      } catch (e5) {
        if (e5 instanceof SyntaxError) {
          handleError(e5, cellSrcStr);
          return;
        } else {
          logError(e5);
          throw new Error();
        }
      }
      pageResources.push(
        ...await extractResourceDescriptionsFromOJSChunk(
          cellSrcStr,
          dirname4(options.source),
          projDir
        )
      );
      const hasManyRowsCols = () => {
        const cols = cell2.options?.[kLayoutNcol];
        const rows = cell2.options?.[kLayoutNrow];
        return Number(cols) && Number(cols) > 1 || Number(rows) && Number(rows) > 1 || nCells > 1;
      };
      const nCol = () => {
        const col = cell2.options?.[kLayoutNcol];
        if (!col) {
          return 1;
        }
        return Number(col);
      };
      const nRow = () => {
        const row = cell2.options?.[kLayoutNrow];
        if (!row) {
          return Math.ceil(nCells / nCol());
        }
        return Number(row);
      };
      const hasSubFigures = () => {
        return hasFigureSubCaptions() || hasManyRowsCols() && nRow() * nCol() > 1;
      };
      const idPlacement = () => {
        if (hasSubFigures() || cell2.options?.[kCellLstLabel]) {
          return "outer";
        } else {
          return "inner";
        }
      };
      let outputVal = cell2.options?.[kOutput] ?? options.format.execute[kOutput];
      outputVal = outputVal ?? true;
      if (outputVal === "all" || outputVal === "asis") {
        attrs.push(`output="${outputVal}"`);
      }
      const {
        classes,
        attrs: otherAttrs
      } = getDivAttributes(cell2.options || {});
      attrs.push(...otherAttrs);
      const evalVal = cell2.options?.[kEval] ?? options.format.execute[kEval] ?? true;
      const echoVal = cell2.options?.[kEcho] ?? options.format.execute[kEcho] ?? true;
      const ojsCellClasses = ["cell"];
      if (!outputVal) {
        ojsCellClasses.push("hidden");
      }
      const div = pandocDiv({
        id: idPlacement() === "outer" ? userId : void 0,
        classes: [
          ...ojsCellClasses,
          ...classes
        ],
        attrs
      });
      const includeVal = cell2.options?.[kInclude] ?? options.format.execute[kInclude] ?? true;
      const srcClasses = mdClassList ?? ["js", "cell-code"];
      const srcAttrs = [];
      if (!echoVal) {
        srcClasses.push("hidden");
      }
      if (cell2.options?.[kCodeOverflow] === "wrap") {
        srcClasses.push("code-overflow-wrap");
      } else if (cell2.options?.[kCodeOverflow] === "scroll") {
        srcClasses.push("code-overflow-scroll");
      }
      if (asUndefined(options.format.render?.[kCodeFold], "none") ?? cell2.options?.[kCodeFold]) {
        srcAttrs.push(`${kCodeFold}="${cell2.options?.[kCodeFold]}"`);
      }
      if (cell2.options?.[kCodeSummary]) {
        srcAttrs.push(
          `${kCodeSummary}="${escape(cell2.options?.[kCodeSummary])}"`
        );
      }
      if (cell2.options?.[kCodeLineNumbers]) {
        srcAttrs.push(
          `${kCodeLineNumbers}="${cell2.options?.[kCodeLineNumbers]}"`
        );
      }
      const srcConfig = {
        classes: srcClasses.slice(),
        attrs: srcAttrs.slice()
      };
      if (evalVal) {
        interpret(cell2.source, false, errorVal);
      }
      const outputCellClasses = ["cell-output", "cell-output-display"];
      if (!outputVal || !includeVal) {
        outputCellClasses.push("hidden");
      }
      if (echoVal === "fenced") {
        const ourAttrs = srcConfig.attrs.slice();
        const ourClasses = srcConfig.classes.filter((d4) => d4 !== "js");
        ourClasses.push("java");
        ourAttrs.push(
          `startFrom="${cellStartingLoc - 1}"`,
          `source-offset="${cell2.sourceOffset}"`
        );
        const srcDiv = pandocCode({
          classes: ourClasses,
          attrs: ourAttrs
        });
        srcDiv.push(pandocRawStr(cell2.sourceVerbatim.value.trim()));
        div.push(srcDiv);
      }
      const shouldEmitSource = echoVal !== "fenced" && !(echoVal === false && isHtmlMarkdown);
      const makeSubFigures = (specs) => {
        let subfigIx = 1;
        const cellInfo = [].concat(
          ...parsedCells.map((n5) => n5.info)
        );
        for (const spec of specs) {
          const outputDiv = pandocDiv({
            classes: outputCellClasses
          });
          const outputInnerDiv = pandocDiv({
            id: userId && `${userId}-${subfigIx}`
          });
          const innerInfo = parsedCells[subfigIx - 1].info;
          const ojsDiv = pandocDiv({
            id: `${ojsId}-${subfigIx}`,
            attrs: [`nodetype="${cellInfo[subfigIx - 1].cellType}"`]
          });
          if (shouldEmitSource && innerInfo.length > 0 && srcConfig !== void 0) {
            const ourAttrs = srcConfig.attrs.slice();
            const linesSkipped = cellSrcStr.value.substring(0, innerInfo[0].start).split("\n").length;
            ourAttrs.push(
              `startFrom="${cellStartingLoc + cell2.sourceStartLine - 1 + linesSkipped}"`
            );
            ourAttrs.push(`source-offset="-${innerInfo[0].start}"`);
            const srcDiv = pandocCode({
              attrs: ourAttrs,
              classes: srcConfig.classes
            });
            srcDiv.push(pandocRawStr(
              cellSrcStr.value.substring(
                innerInfo[0].start,
                innerInfo[innerInfo.length - 1].end
              ).trim()
            ));
            div.push(srcDiv);
          }
          subfigIx++;
          outputDiv.push(outputInnerDiv);
          outputInnerDiv.push(ojsDiv);
          if (spec.caption) {
            outputInnerDiv.push(pandocRawStr(spec.caption));
          }
          div.push(outputDiv);
        }
      };
      if (!hasFigureSubCaptions() && hasManyRowsCols()) {
        const cellCount = Math.max(nRow() * nCol(), nCells, 1);
        const specs = [];
        for (let i6 = 0; i6 < cellCount; ++i6) {
          specs.push({ caption: "" });
        }
        makeSubFigures(specs);
        if (cell2.options?.[kCellFigCap]) {
          div.push(pandocRawStr(cell2.options[kCellFigCap]));
        }
      } else if (hasFigureSubCaptions()) {
        let subCap = cell2.options?.[kCellFigSubCap];
        if (subCap === true) {
          subCap = [""];
        }
        if (!Array.isArray(subCap)) {
          subCap = [subCap];
        }
        if (hasManyRowsCols() && subCap.length !== nRow() * nCol()) {
          throw new Error(
            "Cannot have subcaptions and multi-row/col layout with mismatched number of cells"
          );
        }
        const specs = subCap.map(
          (caption) => ({ caption })
        );
        makeSubFigures(specs);
        if (cell2.options?.[kCellFigCap]) {
          div.push(pandocRawStr(cell2.options[kCellFigCap]));
        }
      } else {
        if (parsedCells.length === 0) {
          throw new Error(
            `Fatal: OJS cell starting on line ${cellStartingLoc} is empty. OJS cells require at least one declaration.`
          );
        }
        const innerInfo = parsedCells[0].info;
        if (innerInfo.length > 0 && srcConfig !== void 0) {
          const ourAttrs = srcConfig.attrs.slice();
          ourAttrs.push(
            `startFrom="${cellStartingLoc + cell2.sourceStartLine - 1}"`
          );
          ourAttrs.push(`source-offset="0"`);
          if (shouldEmitSource) {
            const srcDiv = pandocCode({
              attrs: ourAttrs,
              classes: srcConfig.classes
            });
            srcDiv.push(
              pandocRawStr(mappedTrim(cellSrcStr))
            );
            div.push(srcDiv);
          }
        }
        const outputDiv = pandocDiv({
          id: idPlacement() === "inner" ? userId : void 0,
          classes: outputCellClasses
        });
        div.push(outputDiv);
        outputDiv.push(pandocDiv({
          id: ojsId,
          attrs: [`nodetype="${innerInfo[0].cellType}"`]
        }));
        if (cell2.options?.[kCellFigCap]) {
          outputDiv.push(pandocRawStr(cell2.options[kCellFigCap]));
        }
      }
      div.emit(ls);
    };
    if (cell.cell_type === "raw") {
      ls.push(cell.sourceVerbatim);
    } else if (cell.cell_type === "markdown") {
      const markdown2 = executeInlineCodeHandlerMapped(
        "ojs",
        (exec2) => "${" + exec2 + "}"
      )(cell.sourceVerbatim);
      ls.push(markdown2);
    } else if (cell.cell_type?.language === "ojs") {
      await handleOJSCell(cell);
    } else {
      ls.push(cell.sourceVerbatim);
    }
  }
  if (selfContained) {
    const selfContainedPageResources = await makeSelfContainedResources(
      pageResources,
      docDir
    );
    const resolver = JSON.stringify(
      Object.fromEntries(Array.from(selfContainedPageResources))
    );
    scriptContents.unshift(
      `window._ojs.runtime.setLocalResolver(${resolver});`
    );
  } else {
    for (const resource of uniqueResources(pageResources)) {
      resourceFiles.push(resource.filename);
    }
  }
  const serverMetadata = options.format.metadata?.server;
  const normalizeMetadata = (key, def) => {
    if (!serverMetadata || serverMetadata["type"] !== "shiny" || !serverMetadata[key]) {
      return def;
    }
    if (typeof serverMetadata[key] === "string") {
      return [serverMetadata[key]];
    } else {
      return serverMetadata[key];
    }
  };
  const shinyInputMetadata = normalizeMetadata("ojs-export", ["viewof"]);
  const shinyOutputMetadata = normalizeMetadata("ojs-import", []);
  const shinyInputs2 = /* @__PURE__ */ new Set();
  const shinyInputExcludes = /* @__PURE__ */ new Set();
  if (serverMetadata?.["ojs-exports"]) {
    throw new Error(
      "Document metadata contains server.ojs-exports; did you mean 'ojs-export' instead?"
    );
  }
  if (serverMetadata?.["ojs-imports"]) {
    throw new Error(
      "Document metadata contains server.ojs-imports; did you mean 'ojs-import' instead?"
    );
  }
  let importAllViews = false;
  let importEverything = false;
  for (const shinyInput of shinyInputMetadata) {
    if (shinyInput === "viewof") {
      importAllViews = true;
    } else if (shinyInput === "all") {
      importEverything = true;
    } else if (shinyInput.startsWith("~")) {
      shinyInputExcludes.add(shinyInput.slice(1));
    } else {
      shinyInputs2.add(shinyInput);
    }
  }
  const resultSet = /* @__PURE__ */ new Set();
  if (importEverything) {
    for (const el of ojsViews) {
      resultSet.add(el);
    }
    for (const el of ojsIdentifiers) {
      resultSet.add(el);
    }
  }
  if (importAllViews) {
    for (const el of ojsViews) {
      resultSet.add(el);
    }
  }
  for (const el of shinyInputs2) {
    resultSet.add(el);
  }
  for (const el of shinyInputExcludes) {
    resultSet.delete(el);
  }
  for (const el of resultSet) {
    moduleContents.push({
      methodName: "interpretQuiet",
      source: `shinyInput('${el}')`
    });
  }
  for (const el of shinyOutputMetadata) {
    moduleContents.push({
      methodName: "interpretQuiet",
      source: `${el} = shinyOutput('${el}')`
    });
  }
  scriptContents.push("window._ojs.runtime.interpretFromScriptTags();");
  const afterBody = [
    `<script type="ojs-module-contents">`,
    encodeBase64(JSON.stringify({ contents: moduleContents })),
    `<\/script>`,
    `<script type="module">`,
    ...scriptContents,
    `<\/script>`
  ].join("\n");
  const includeAfterBodyFile = options.temp.createFile();
  Deno.writeTextFileSync(includeAfterBodyFile, afterBody);
  const extras = resolveDependencies(
    {
      html: {
        [kDependencies]: [ojsFormatDependency(selfContained)]
      }
    },
    dirname4(options.source),
    options.libDir,
    options.temp,
    project
  );
  const ojsBundleTempFiles = [];
  if (selfContained) {
    const ojsBundleFilename = join4(
      quartoConfig.sharePath(),
      "formats/html/ojs/quarto-ojs-runtime.js"
    );
    const ojsBundle = [
      `<script type="module">`,
      Deno.readTextFileSync(ojsBundleFilename),
      `<\/script>`
    ];
    const filename = options.temp.createFile();
    Deno.writeTextFileSync(filename, ojsBundle.join("\n"));
    ojsBundleTempFiles.push(filename);
  }
  const includeInHeader = [
    ...extras?.[kIncludeInHeader] || [],
    ...ojsBundleTempFiles
  ];
  return {
    markdown: join5(ls, ""),
    filters: [
      "ojs"
    ],
    includes: {
      [kIncludeInHeader]: includeInHeader,
      [kIncludeAfterBody]: [includeAfterBodyFile]
    },
    resourceFiles
  };
}
async function ojsExecuteResult(context, executeResult, ojsBlockLineNumbers) {
  executeResult = {
    ...executeResult
  };
  const { markdown, includes, filters, resourceFiles } = await ojsCompile({
    source: context.target.source,
    format: context.format,
    markdown: executeResult.markdown,
    libDir: context.libDir,
    project: context.project,
    temp: context.options.services.temp,
    ojsBlockLineNumbers
  });
  executeResult.markdown = markdown;
  if (includes) {
    executeResult.includes = mergeConfigs(
      includes,
      executeResult.includes || {}
    );
  }
  if (filters) {
    executeResult.filters = (executeResult.filters || []).concat(filters);
  }
  return {
    executeResult,
    resourceFiles: resourceFiles || []
  };
}
function asUndefined(value, test) {
  if (value === test) {
    return void 0;
  }
  return value;
}
function ojsFormatDependency(selfContained) {
  const ojsResource = (resource) => formatResourcePath(
    "html",
    join4("ojs", resource)
  );
  const ojsDependency = (resource, attribs) => ({
    name: resource,
    path: ojsResource(resource),
    attribs
  });
  const scripts = selfContained ? [] : [
    ojsDependency("quarto-ojs-runtime.js", { type: "module" })
  ];
  return {
    name: "quarto-ojs",
    stylesheets: [
      ojsDependency("quarto-ojs.css")
    ],
    scripts
  };
}

// command/render/render-files.ts
init_types4();

// command/render/output.ts
init_path();

// https://deno.land/x/cliffy@v1.0.0-rc.3/ansi/ansi_escapes.ts
var ansi_escapes_exports = {};
__export(ansi_escapes_exports, {
  bel: () => bel,
  clearScreen: () => clearScreen,
  clearTerminal: () => clearTerminal,
  cursorBackward: () => cursorBackward,
  cursorDown: () => cursorDown,
  cursorForward: () => cursorForward,
  cursorHide: () => cursorHide,
  cursorLeft: () => cursorLeft,
  cursorMove: () => cursorMove,
  cursorNextLine: () => cursorNextLine,
  cursorPosition: () => cursorPosition,
  cursorPrevLine: () => cursorPrevLine,
  cursorRestore: () => cursorRestore,
  cursorSave: () => cursorSave,
  cursorShow: () => cursorShow,
  cursorTo: () => cursorTo,
  cursorUp: () => cursorUp,
  eraseDown: () => eraseDown,
  eraseLine: () => eraseLine,
  eraseLineEnd: () => eraseLineEnd,
  eraseLineStart: () => eraseLineStart,
  eraseLines: () => eraseLines,
  eraseScreen: () => eraseScreen,
  eraseUp: () => eraseUp,
  image: () => image,
  link: () => link,
  scrollDown: () => scrollDown,
  scrollUp: () => scrollUp
});

// https://deno.land/x/cliffy@v1.0.0-rc.3/ansi/deps.ts
init_base642();

// https://deno.land/x/cliffy@v1.0.0-rc.3/ansi/ansi_escapes.ts
var ESC = "\x1B";
var CSI = `${ESC}[`;
var OSC = `${ESC}]`;
var SEP5 = ";";
var bel = "\x07";
var cursorPosition = `${CSI}6n`;
function cursorTo(x3, y4) {
  if (typeof y4 !== "number") {
    return `${CSI}${x3}G`;
  }
  return `${CSI}${y4};${x3}H`;
}
function cursorMove(x3, y4) {
  let ret = "";
  if (x3 < 0) {
    ret += `${CSI}${-x3}D`;
  } else if (x3 > 0) {
    ret += `${CSI}${x3}C`;
  }
  if (y4 < 0) {
    ret += `${CSI}${-y4}A`;
  } else if (y4 > 0) {
    ret += `${CSI}${y4}B`;
  }
  return ret;
}
function cursorUp(count = 1) {
  return `${CSI}${count}A`;
}
function cursorDown(count = 1) {
  return `${CSI}${count}B`;
}
function cursorForward(count = 1) {
  return `${CSI}${count}C`;
}
function cursorBackward(count = 1) {
  return `${CSI}${count}D`;
}
function cursorNextLine(count = 1) {
  return `${CSI}E`.repeat(count);
}
function cursorPrevLine(count = 1) {
  return `${CSI}F`.repeat(count);
}
var cursorLeft = `${CSI}G`;
var cursorHide = `${CSI}?25l`;
var cursorShow = `${CSI}?25h`;
var cursorSave = `${ESC}7`;
var cursorRestore = `${ESC}8`;
function scrollUp(count = 1) {
  return `${CSI}S`.repeat(count);
}
function scrollDown(count = 1) {
  return `${CSI}T`.repeat(count);
}
var eraseScreen = `${CSI}2J`;
function eraseUp(count = 1) {
  return `${CSI}1J`.repeat(count);
}
function eraseDown(count = 1) {
  return `${CSI}0J`.repeat(count);
}
var eraseLine = `${CSI}2K`;
var eraseLineEnd = `${CSI}0K`;
var eraseLineStart = `${CSI}1K`;
function eraseLines(count) {
  let clear = "";
  for (let i6 = 0; i6 < count; i6++) {
    clear += eraseLine + (i6 < count - 1 ? cursorUp() : "");
  }
  clear += cursorLeft;
  return clear;
}
var clearScreen = "\x1Bc";
var clearTerminal = Deno.build.os === "windows" ? `${eraseScreen}${CSI}0f` : `${eraseScreen}${CSI}3J${CSI}H`;
function link(text, url) {
  return [
    OSC,
    "8",
    SEP5,
    SEP5,
    url,
    bel,
    text,
    OSC,
    "8",
    SEP5,
    SEP5,
    bel
  ].join("");
}
function image(buffer2, options) {
  let ret = `${OSC}1337;File=inline=1`;
  if (options?.width) {
    ret += `;width=${options.width}`;
  }
  if (options?.height) {
    ret += `;height=${options.height}`;
  }
  if (options?.preserveAspectRatio === false) {
    ret += ";preserveAspectRatio=0";
  }
  return ret + ":" + encode2(buffer2) + bel;
}

// https://deno.land/x/cliffy@v1.0.0-rc.3/ansi/ansi.ts
var ansi = factory();
var encoder = new TextEncoder();
function factory() {
  let result2 = [];
  let stack = [];
  const ansi2 = function(...args) {
    if (this) {
      if (args.length) {
        update(args);
        return this;
      }
      return this.toString();
    }
    return factory();
  };
  ansi2.text = function(text) {
    stack.push([text, []]);
    return this;
  };
  ansi2.toArray = function() {
    update();
    const ret = result2;
    result2 = [];
    return ret;
  };
  ansi2.toString = function() {
    return this.toArray().join("");
  };
  ansi2.bytes = function() {
    return encoder.encode(this.toString());
  };
  const methodList = Object.entries(
    ansi_escapes_exports
  );
  for (const [name2, method] of methodList) {
    Object.defineProperty(ansi2, name2, {
      get() {
        stack.push([method, []]);
        return this;
      }
    });
  }
  return ansi2;
  function update(args) {
    if (!stack.length) {
      return;
    }
    if (args) {
      stack[stack.length - 1][1] = args;
    }
    result2.push(
      ...stack.map(
        ([prop, args2]) => typeof prop === "string" ? prop : prop.call(ansi2, ...args2)
      )
    );
    stack = [];
  }
}

// https://deno.land/x/cliffy@v1.0.0-rc.3/ansi/colors.ts
var proto = /* @__PURE__ */ Object.create(null);
var methodNames = Object.keys(colors_exports);
for (const name2 of methodNames) {
  if (name2 === "setColorEnabled" || name2 === "getColorEnabled") {
    continue;
  }
  Object.defineProperty(proto, name2, {
    get() {
      return factory2([...this._stack, name2]);
    }
  });
}
var colors = factory2();
function factory2(stack = []) {
  const colors2 = function(str3, ...args) {
    if (typeof str3 !== "undefined") {
      const lastIndex = stack.length - 1;
      return stack.reduce(
        (str4, name2, index2) => index2 === lastIndex ? colors_exports[name2](str4, ...args) : colors_exports[name2](str4),
        str3
      );
    }
    const tmp = stack.slice();
    stack = [];
    return factory2(tmp);
  };
  Object.setPrototypeOf(colors2, proto);
  colors2._stack = stack;
  return colors2;
}

// https://deno.land/x/cliffy@v1.0.0-rc.3/ansi/cursor_position.ts
var encoder2 = new TextEncoder();
var decoder2 = new TextDecoder();
function getCursorPosition({
  reader = Deno.stdin,
  writer = Deno.stdout
} = {}) {
  const data3 = new Uint8Array(8);
  reader.setRaw(true);
  writer.writeSync(encoder2.encode(cursorPosition));
  reader.readSync(data3);
  reader.setRaw(false);
  const [y4, x3] = decoder2.decode(data3).match(/\[(\d+);(\d+)R/)?.slice(1, 3).map(Number) ?? [0, 0];
  return { x: x3, y: y4 };
}

// https://deno.land/x/cliffy@v1.0.0-rc.3/ansi/tty.ts
var tty = factory3();
var encoder3 = new TextEncoder();
function factory3(options) {
  let result2 = "";
  let stack = [];
  const writer = options?.writer ?? Deno.stdout;
  const reader = options?.reader ?? Deno.stdin;
  const tty2 = function(...args) {
    if (this) {
      update(args);
      writer.writeSync(encoder3.encode(result2));
      return this;
    }
    return factory3(args[0] ?? options);
  };
  tty2.text = function(text) {
    stack.push([text, []]);
    update();
    writer.writeSync(encoder3.encode(result2));
    return this;
  };
  tty2.getCursorPosition = () => getCursorPosition({ writer, reader });
  const methodList = Object.entries(
    ansi_escapes_exports
  );
  for (const [name2, method] of methodList) {
    if (name2 === "cursorPosition") {
      continue;
    }
    Object.defineProperty(tty2, name2, {
      get() {
        stack.push([method, []]);
        return this;
      }
    });
  }
  return tty2;
  function update(args) {
    if (!stack.length) {
      return;
    }
    if (args) {
      stack[stack.length - 1][1] = args;
    }
    result2 = stack.reduce(
      (prev, [cur, args2]) => prev + (typeof cur === "string" ? cur : cur.call(tty2, ...args2)),
      ""
    );
    stack = [];
  }
}

// core/console.ts
init_write_all();

// https://jsr.io/@std/io/0.224.0/read_all.ts
init_concat2();
async function readAll(reader) {
  const chunks = [];
  while (true) {
    let chunk = new Uint8Array(DEFAULT_CHUNK_SIZE);
    const n5 = await reader.read(chunk);
    if (n5 === null) {
      break;
    }
    if (n5 < DEFAULT_CHUNK_SIZE) {
      chunk = chunk.subarray(0, n5);
    }
    chunks.push(chunk);
  }
  return concat2(chunks);
}
function readAllSync(reader) {
  const chunks = [];
  while (true) {
    const chunk = new Uint8Array(DEFAULT_CHUNK_SIZE);
    const n5 = reader.readSync(chunk);
    if (n5 === null) {
      break;
    }
    if (n5 < DEFAULT_CHUNK_SIZE) {
      chunks.push(chunk.subarray(0, n5));
      break;
    }
    chunks.push(chunk);
  }
  return concat2(chunks);
}

// core/console.ts
init_log();

// core/ci-info.ts
function runningInCI() {
  if ([
    "CI",
    // Travis CI, CircleCI, Cirrus CI, Gitlab CI, // Appveyor, CodeShip, dsari
    "CONTINUOUS_INTEGRATION",
    // Travis CI, Cirrus CI
    "BUILD_NUMBER",
    // Jenkins, TeamCity
    "RUN_ID"
    // TaskCluster, dsari
  ].some(checkEnv)) {
    return true;
  }
  return vendors.some((vendor) => {
    const envs = Array.isArray(vendor.env) ? vendor.env : [vendor.env];
    return envs.some(checkEnv);
  });
}
function checkEnv(obj) {
  if (typeof obj === "string") {
    return !!Deno.env.get(obj);
  } else {
    return Object.keys(obj).every(function(k3) {
      return Deno.env.get(k3) === obj[k3];
    });
  }
}
var vendors = [
  {
    "name": "AppVeyor",
    "constant": "APPVEYOR",
    "env": "APPVEYOR",
    "pr": "APPVEYOR_PULL_REQUEST_NUMBER"
  },
  {
    "name": "Azure Pipelines",
    "constant": "AZURE_PIPELINES",
    "env": "SYSTEM_TEAMFOUNDATIONCOLLECTIONURI",
    "pr": "SYSTEM_PULLREQUEST_PULLREQUESTID"
  },
  {
    "name": "Appcircle",
    "constant": "APPCIRCLE",
    "env": "AC_APPCIRCLE"
  },
  {
    "name": "Bamboo",
    "constant": "BAMBOO",
    "env": "bamboo_planKey"
  },
  {
    "name": "Bitbucket Pipelines",
    "constant": "BITBUCKET",
    "env": "BITBUCKET_COMMIT",
    "pr": "BITBUCKET_PR_ID"
  },
  {
    "name": "Bitrise",
    "constant": "BITRISE",
    "env": "BITRISE_IO",
    "pr": "BITRISE_PULL_REQUEST"
  },
  {
    "name": "Buddy",
    "constant": "BUDDY",
    "env": "BUDDY_WORKSPACE_ID",
    "pr": "BUDDY_EXECUTION_PULL_REQUEST_ID"
  },
  {
    "name": "Buildkite",
    "constant": "BUILDKITE",
    "env": "BUILDKITE",
    "pr": { "env": "BUILDKITE_PULL_REQUEST", "ne": "false" }
  },
  {
    "name": "CircleCI",
    "constant": "CIRCLE",
    "env": "CIRCLECI",
    "pr": "CIRCLE_PULL_REQUEST"
  },
  {
    "name": "Cirrus CI",
    "constant": "CIRRUS",
    "env": "CIRRUS_CI",
    "pr": "CIRRUS_PR"
  },
  {
    "name": "AWS CodeBuild",
    "constant": "CODEBUILD",
    "env": "CODEBUILD_BUILD_ARN"
  },
  {
    "name": "Codefresh",
    "constant": "CODEFRESH",
    "env": "CF_BUILD_ID",
    "pr": { "any": ["CF_PULL_REQUEST_NUMBER", "CF_PULL_REQUEST_ID"] }
  },
  {
    "name": "Codeship",
    "constant": "CODESHIP",
    "env": { "CI_NAME": "codeship" }
  },
  {
    "name": "Drone",
    "constant": "DRONE",
    "env": "DRONE",
    "pr": { "DRONE_BUILD_EVENT": "pull_request" }
  },
  {
    "name": "dsari",
    "constant": "DSARI",
    "env": "DSARI"
  },
  {
    "name": "GitHub Actions",
    "constant": "GITHUB_ACTIONS",
    "env": "GITHUB_ACTIONS",
    "pr": { "GITHUB_EVENT_NAME": "pull_request" }
  },
  {
    "name": "GitLab CI",
    "constant": "GITLAB",
    "env": "GITLAB_CI",
    "pr": "CI_MERGE_REQUEST_ID"
  },
  {
    "name": "GoCD",
    "constant": "GOCD",
    "env": "GO_PIPELINE_LABEL"
  },
  {
    "name": "LayerCI",
    "constant": "LAYERCI",
    "env": "LAYERCI",
    "pr": "LAYERCI_PULL_REQUEST"
  },
  {
    "name": "Hudson",
    "constant": "HUDSON",
    "env": "HUDSON_URL"
  },
  {
    "name": "Jenkins",
    "constant": "JENKINS",
    "env": ["JENKINS_URL", "BUILD_ID"],
    "pr": { "any": ["ghprbPullId", "CHANGE_ID"] }
  },
  {
    "name": "Magnum CI",
    "constant": "MAGNUM",
    "env": "MAGNUM"
  },
  {
    "name": "Netlify CI",
    "constant": "NETLIFY",
    "env": "NETLIFY",
    "pr": { "env": "PULL_REQUEST", "ne": "false" }
  },
  {
    "name": "Nevercode",
    "constant": "NEVERCODE",
    "env": "NEVERCODE",
    "pr": { "env": "NEVERCODE_PULL_REQUEST", "ne": "false" }
  },
  {
    "name": "Render",
    "constant": "RENDER",
    "env": "RENDER",
    "pr": { "IS_PULL_REQUEST": "true" }
  },
  {
    "name": "Sail CI",
    "constant": "SAIL",
    "env": "SAILCI",
    "pr": "SAIL_PULL_REQUEST_NUMBER"
  },
  {
    "name": "Semaphore",
    "constant": "SEMAPHORE",
    "env": "SEMAPHORE",
    "pr": "PULL_REQUEST_NUMBER"
  },
  {
    "name": "Screwdriver",
    "constant": "SCREWDRIVER",
    "env": "SCREWDRIVER",
    "pr": { "env": "SD_PULL_REQUEST", "ne": "false" }
  },
  {
    "name": "Shippable",
    "constant": "SHIPPABLE",
    "env": "SHIPPABLE",
    "pr": { "IS_PULL_REQUEST": "true" }
  },
  {
    "name": "Solano CI",
    "constant": "SOLANO",
    "env": "TDDIUM",
    "pr": "TDDIUM_PR_ID"
  },
  {
    "name": "Strider CD",
    "constant": "STRIDER",
    "env": "STRIDER"
  },
  {
    "name": "TaskCluster",
    "constant": "TASKCLUSTER",
    "env": ["TASK_ID", "RUN_ID"]
  },
  {
    "name": "TeamCity",
    "constant": "TEAMCITY",
    "env": "TEAMCITY_VERSION"
  },
  {
    "name": "Travis CI",
    "constant": "TRAVIS",
    "env": "TRAVIS",
    "pr": { "env": "TRAVIS_PULL_REQUEST", "ne": "false" }
  },
  {
    "name": "Vercel",
    "constant": "VERCEL",
    "env": "NOW_BUILDER"
  },
  {
    "name": "Visual Studio App Center",
    "constant": "APPCENTER",
    "env": "APPCENTER_BUILD_ID"
  }
];

// core/console.ts
init_platform();
var kSpinnerChars = ["|", "/", "-", "\\"];
var kSpinerContainerChars = ["(", ")"];
var kSpinerCompleteContainerChars = ["[", "]"];
var kSpinnerCompleteChar = !isWindows4 ? "\u2713" : ">";
var kProgressIncrementChar = "#";
var kProgressContainerChars = ["[", "]"];
var kProgressBarWidth = 35;
function progressBar(total, prefixMessage) {
  const isCi = runningInCI();
  if (isCi && prefixMessage) {
    info(prefixMessage);
  }
  const updateProgress = (progress, status) => {
    if (!isCi) {
      const progressBar2 = `${asciiProgressBar(progress / total * 100, kProgressBarWidth)}`;
      const progressText = `\r${prefixMessage ? prefixMessage + " " : ""}${progressBar2}${status ? " " + status : ""}`;
      clearLine();
      info(progressText, { newline: false });
    }
  };
  return {
    update: updateProgress,
    complete: (finalMsg) => {
      if (!isCi) {
        clearLine();
      }
      if (typeof finalMsg === "string") {
        if (isCi) {
          info(finalMsg);
        } else {
          updateProgress(total, finalMsg);
        }
      } else {
        if (finalMsg !== false && prefixMessage) {
          completeMessage(prefixMessage);
        } else if (finalMsg !== false) {
          updateProgress(total);
        }
      }
    }
  };
}
async function withSpinner(options, op) {
  const cancel = spinner(options.message);
  try {
    return await op();
  } finally {
    cancel(options.doneMessage);
  }
}
function spinner(status, timeInterval = 100) {
  let spin = 0;
  const statusFn = typeof status === "string" ? () => {
    return status;
  } : () => {
    if (!runningInCI()) {
      clearLine();
    }
    return status();
  };
  const id = setInterval(() => {
    const char = kSpinnerChars[spin % kSpinnerChars.length];
    const msg5 = `${spinContainer(char)} ${statusFn()}`;
    if (!runningInCI() || spin === 0) {
      info(`\r${msg5}`, {
        newline: false
      });
    }
    spin = spin + 1;
  }, timeInterval);
  return (finalMsg) => {
    clearInterval(id);
    clearLine();
    if (typeof finalMsg === "string") {
      completeMessage(finalMsg);
    } else {
      if (finalMsg !== false) {
        completeMessage(statusFn());
      }
    }
  };
}
function spinContainer(body) {
  return `${kSpinerContainerChars[0]}${body}${kSpinerContainerChars[1]}`;
}
function completeMessage(msg5) {
  info(
    `\r${kSpinerCompleteContainerChars[0]}${kSpinnerCompleteChar}${kSpinerCompleteContainerChars[1]} ${msg5}`,
    {
      newline: true
    }
  );
}
function writeFileToStdout(file) {
  const df = Deno.openSync(file, { read: true });
  const contents = readAllSync(df);
  writeAllSync(Deno.stdout, contents);
  df.close();
}
function clearLine() {
  info(ansi.eraseLine.cursorLeft(), { newline: false });
}
function asciiProgressBar(percent, width = 25) {
  const segsComplete = Math.floor(percent / (100 / width));
  let progressBar2 = kProgressContainerChars[0];
  for (let i6 = 0; i6 < width; i6++) {
    progressBar2 = progressBar2 + (i6 < segsComplete ? kProgressIncrementChar : " ");
  }
  progressBar2 = progressBar2 + kProgressContainerChars[1];
  return progressBar2;
}

// command/render/output.ts
init_path2();
init_yaml();
init_constants6();

// command/render/latexmk/latexmk.ts
init_constants6();
init_pdf();

// command/render/latexmk/pdf.ts
init_path();
init_fs();
init_path2();

// command/render/latexmk/texlive.ts
init_lodash();
init_process();
init_text2();
init_windows();
init_path();
init_log2();
init_platform();
async function texLiveContext(preferTinyTex) {
  const hasTiny = hasTinyTex();
  const hasTex = await hasTexLive();
  const binDir3 = tinyTexBinDir();
  const usingGlobal = await texLiveInPath() && !hasTiny;
  return {
    preferTinyTex,
    hasTinyTex: hasTiny,
    hasTexLive: hasTex,
    usingGlobal,
    binDir: binDir3
  };
}
function systemTexLiveContext() {
  return {
    preferTinyTex: false,
    hasTinyTex: false,
    hasTexLive: false,
    usingGlobal: true
  };
}
async function hasTexLive() {
  if (hasTinyTex()) {
    return true;
  } else {
    if (await texLiveInPath()) {
      return true;
    } else {
      return false;
    }
  }
}
async function texLiveInPath() {
  try {
    const systemContext = systemTexLiveContext();
    const result2 = await tlmgrCommand("--version", [], systemContext);
    return result2.code === 0;
  } catch {
    return false;
  }
}
async function findPackages(searchTerms, context, opts, quiet) {
  const results = [];
  const args = ["--file", "--global"];
  for (const searchTerm of searchTerms) {
    if (!quiet) {
      logProgress(
        `finding package for ${searchTerm}`
      );
    }
    const knownPackages = ["fandol", "latex-lab", "colorprofiles"];
    if (knownPackages.includes(searchTerm)) {
      results.push(searchTerm);
    } else {
      const result2 = await tlmgrCommand(
        "search",
        [...args, ...opts || [], searchTerm],
        context,
        true
      );
      if (result2.code === 0 && result2.stdout) {
        const text = result2.stdout;
        const packageNameRegex = /^(.+)\:$/;
        const searchTermRegex = new RegExp(`/${searchTerm}$`);
        let currentPackage = void 0;
        lines(text).forEach((line) => {
          const packageMatch = line.match(packageNameRegex);
          if (packageMatch) {
            const packageName = packageMatch[1];
            if (packageName.includes(".")) {
              currentPackage = packageName.split(".")[0];
            } else {
              currentPackage = packageName;
            }
          } else {
            if (currentPackage) {
              const searchTermMatch = line.match(searchTermRegex);
              if (searchTermMatch) {
                results.push(currentPackage);
                currentPackage = void 0;
              }
            }
          }
        });
      } else {
        const errorMessage = tlMgrError(result2.stderr);
        if (errorMessage) {
          throw new Error(errorMessage);
        }
      }
    }
  }
  return uniq(results);
}
function updatePackages(all2, self2, context, opts, quiet) {
  const args = [];
  if (opts) {
    args.push(...opts);
  }
  if (all2) {
    args.push("--all");
  }
  if (self2) {
    args.push("--self");
  }
  return tlmgrCommand("update", args || [], context, quiet);
}
async function installPackages(pkgs, context, opts, quiet) {
  if (!quiet) {
    logProgress(
      `> ${pkgs.length} ${pkgs.length === 1 ? "package" : "packages"} to install`
    );
  }
  let count = 1;
  for (const pkg of pkgs) {
    if (!quiet) {
      logProgress(
        `> installing ${pkg} (${count} of ${pkgs.length})`
      );
    }
    await installPackage(pkg, context, opts, quiet);
    count = count + 1;
  }
  if (context.usingGlobal) {
    await addPath(context);
  }
}
function addPath(context, opts) {
  return tlmgrCommand("path", ["add", ...opts || []], context, true);
}
function removePath(context, opts, quiet) {
  return tlmgrCommand("path", ["remove", ...opts || []], context, quiet);
}
async function installPackage(pkg, context, opts, quiet) {
  let isInstalled2 = await verifyPackageInstalled(pkg, context);
  if (isInstalled2) {
    const updateResult = await updatePackages(
      true,
      true,
      context,
      opts,
      quiet
    );
    if (updateResult.code !== 0) {
      return Promise.reject("Problem running `tlmgr update`.");
    }
    const fmtutilResult = await fmtutilCommand(context);
    if (fmtutilResult.code !== 0) {
      return Promise.reject(
        "Problem running `fmtutil-sys --all` to rebuild format tree."
      );
    }
  }
  let installResult = await tlmgrCommand(
    "install",
    [...opts || [], pkg],
    context,
    quiet
  );
  if (installResult.code !== 0 && installResult.code !== 255) {
    return Promise.reject(
      `tlmgr returned a non zero status code
${installResult.stderr}`
    );
  }
  isInstalled2 = await verifyPackageInstalled(pkg, context);
  if (!isInstalled2) {
    const updateResult = await updatePackages(
      false,
      true,
      context,
      opts,
      quiet
    );
    if (updateResult.code !== 0) {
      return Promise.reject("Problem running `tlmgr update`.");
    }
    const fmtutilResult = await fmtutilCommand(context);
    if (fmtutilResult.code !== 0) {
      return Promise.reject(
        "Problem running `fmtutil-sys --all` to rebuild format tree."
      );
    }
    installResult = await tlmgrCommand(
      "install",
      [...opts || [], pkg],
      context,
      quiet
    );
  }
  return installResult;
}
async function tlVersion(context) {
  try {
    const result2 = await tlmgrCommand(
      "--version",
      ["--machine-readable"],
      context,
      true
    );
    if (result2.success) {
      const versionStr = result2.stdout;
      const match = versionStr && versionStr.match(/tlversion (\d*)/);
      if (match) {
        return match[1];
      } else {
        return void 0;
      }
    } else {
      return void 0;
    }
  } catch {
    return void 0;
  }
}
function texLiveCmd(cmd, context) {
  if (context.preferTinyTex && context.hasTinyTex) {
    if (context.binDir) {
      return {
        cmd,
        fullPath: join4(context.binDir, cmd)
      };
    } else {
      return { cmd, fullPath: cmd };
    }
  } else {
    return { cmd, fullPath: cmd };
  }
}
function tlMgrError(msg5) {
  if (msg5 && msg5.indexOf("is older than remote repository") > -1) {
    const message = `Your TexLive version is not updated enough to connect to the remote repository and download packages. Please update your installation of TexLive or TinyTex.

Underlying message:`;
    return `${message} ${msg5.replace("\ntlmgr: ", "")}`;
  } else {
    return void 0;
  }
}
async function verifyPackageInstalled(pkg, context, opts) {
  const result2 = await tlmgrCommand(
    "info",
    [
      "--list",
      "--only-installed",
      "--data",
      "name",
      ...opts || [],
      pkg
    ],
    context
  );
  return result2.stdout?.trim() === pkg;
}
function tlmgrCommand(tlmgrCmd, args, context, _quiet) {
  const execTlmgr = (tlmgrCmd2) => {
    return execProcess(
      {
        cmd: tlmgrCmd2[0],
        args: tlmgrCmd2.slice(1),
        stdout: "piped",
        stderr: "piped"
      }
    );
  };
  const tlmgr = texLiveCmd("tlmgr", context);
  if (isWindows4) {
    const quoted = requireQuoting(args);
    return safeWindowsExec(
      tlmgr.fullPath,
      [tlmgrCmd, ...quoted.args],
      execTlmgr
    );
  } else {
    return execTlmgr([tlmgr.fullPath, tlmgrCmd, ...args]);
  }
}
function fmtutilCommand(context) {
  const fmtutil = texLiveCmd("fmtutil-sys", context);
  return execProcess(
    {
      cmd: fmtutil.fullPath,
      args: ["--all"],
      stdout: "piped",
      stderr: "piped"
    }
  );
}

// command/render/latexmk/latex.ts
init_path();
init_fs();
init_log();
init_path2();
init_process();

// command/render/latexmk/types.ts
var kLatexBodyMessageOptions = { indent: 2 };

// command/render/latexmk/latex.ts
init_env();
init_log2();
async function hasLatexDistribution() {
  try {
    const result2 = await execProcess({
      cmd: "pdftex",
      args: ["--version"],
      stdout: "piped",
      stderr: "piped"
    });
    return result2.code === 0;
  } catch {
    return false;
  }
}
var kLatexMkEngineFlags = [
  "-pdf",
  "-pdfdvi",
  "-pdfps",
  "-pdflua",
  "-pdfxe",
  "-pdf-"
];
async function runPdfEngine(input, engine, texLive, outputDir, texInputDirs, pkgMgr, quiet) {
  const [cwd2, stem] = dirAndStem(input);
  const targetDir = outputDir ? join4(cwd2, outputDir) : cwd2;
  const output = join4(targetDir, `${stem}.pdf`);
  const log3 = join4(targetDir, `${stem}.log`);
  [log3, output].forEach((file) => {
    if (existsSync2(file)) {
      safeRemoveSync(file);
    }
  });
  const computeEngineArgs = () => {
    if (engine.pdfEngine === "latexmk") {
      const engineArgs = ["-interaction=batchmode", "-halt-on-error"];
      if (!engine.pdfEngineOpts || engine.pdfEngineOpts.find((opt) => {
        return kLatexMkEngineFlags.includes(opt);
      }) === void 0) {
        engineArgs.push("-pdf");
      }
      engineArgs.push("-quiet");
      return engineArgs;
    } else {
      return ["-interaction=batchmode", "-halt-on-error"];
    }
  };
  const args = computeEngineArgs();
  if (outputDir !== void 0) {
    args.push(`-output-directory=${outputDir}`);
  }
  if (engine.pdfEngineOpts) {
    args.push(...engine.pdfEngineOpts);
  }
  args.push(basename4(input));
  const result2 = await runLatexCommand(
    engine.pdfEngine,
    args,
    {
      pkgMgr,
      cwd: cwd2,
      texInputDirs,
      texLive
    },
    quiet
  );
  return {
    result: result2,
    output,
    log: log3
  };
}
async function runIndexEngine(input, texLive, engine, args, pkgMgr, quiet) {
  const [cwd2, stem] = dirAndStem(input);
  const log3 = join4(cwd2, `${stem}.ilg`);
  if (existsSync2(log3)) {
    safeRemoveSync(log3);
  }
  const result2 = await runLatexCommand(
    engine || "makeindex",
    [...args || [], basename4(input)],
    {
      cwd: cwd2,
      pkgMgr,
      texLive
    },
    quiet
  );
  return {
    result: result2,
    log: log3
  };
}
async function runBibEngine(engine, input, cwd2, texLive, pkgMgr, texInputDirs, quiet) {
  const [dir, stem] = dirAndStem(input);
  const log3 = join4(dir, `${stem}.blg`);
  if (existsSync2(log3)) {
    safeRemoveSync(log3);
  }
  const result2 = await runLatexCommand(
    engine,
    [input],
    {
      pkgMgr,
      cwd: cwd2,
      texInputDirs,
      texLive
    },
    quiet
  );
  return {
    result: result2,
    log: log3
  };
}
async function runLatexCommand(latexCmd, args, context, quiet) {
  const fullLatexCmd = texLiveCmd(latexCmd, context.texLive);
  const runOptions = {
    cmd: fullLatexCmd.fullPath,
    args,
    stdout: "piped",
    stderr: "piped"
  };
  if (context.texLive.binDir) {
    runOptions.env = runOptions.env || {};
    runOptions.env["PATH"] = withPath({ prepend: [context.texLive.binDir] });
  }
  if (context.cwd) {
    runOptions.cwd = context.cwd;
  }
  if (context.texInputDirs && context.texInputDirs.length > 0) {
    runOptions.env = runOptions.env || {};
    runOptions.env["TEXINPUTS"] = `${context.texInputDirs.join(";")};`;
    runOptions.env["BSTINPUTS"] = `${context.texInputDirs.join(";")};`;
  }
  const runCmd = async () => {
    const result2 = await execProcess(runOptions, void 0, "stdout>stderr");
    if (!quiet && result2.stderr) {
      info(result2.stderr, kLatexBodyMessageOptions);
    }
    return result2;
  };
  try {
    return await runCmd();
  } catch (_e) {
    const tex = await hasTexLive() || await hasLatexDistribution();
    if (!tex) {
      info(
        "\nNo TeX installation was detected.\n\nPlease run 'quarto install tinytex' to install TinyTex.\nIf you prefer, you may install TexLive or another TeX distribution.\n"
      );
      return Promise.reject();
    } else if (context.pkgMgr && context.pkgMgr.autoInstall) {
      if (!quiet) {
        logProgress(
          `command ${latexCmd} not found, attempting install`
        );
      }
      const packageForCommand = await context.pkgMgr.searchPackages([latexCmd]);
      if (packageForCommand) {
        await context.pkgMgr.installPackages(packagesForCommand(latexCmd));
      }
      return await runCmd();
    } else {
      error(
        `Error executing ${latexCmd}`
      );
      return Promise.reject();
    }
  }
}
function packagesForCommand(cmd) {
  if (cmd === "texindy") {
    return ["xindy"];
  } else {
    return [cmd];
  }
}

// command/render/latexmk/pkgmgr.ts
init_lodash();
function packageManager(mkOptions, texLive) {
  let lastPkgs = [];
  return {
    autoInstall: mkOptions.autoInstall === void 0 ? true : mkOptions.autoInstall,
    installPackages: async (pkgs) => {
      const difference2 = difference(pkgs, lastPkgs);
      if (difference2.length > 0) {
        await installPackages(
          pkgs,
          texLive,
          mkOptions.engine.tlmgrOpts,
          mkOptions.quiet
        );
        lastPkgs = pkgs;
        return true;
      } else {
        return false;
      }
    },
    updatePackages: (all2, self2) => {
      return updatePackages(
        all2,
        self2,
        texLive,
        mkOptions.engine.tlmgrOpts,
        mkOptions.quiet
      );
    },
    searchPackages: (searchTerms) => {
      return findPackages(
        searchTerms,
        texLive,
        mkOptions.engine.tlmgrOpts,
        mkOptions.quiet
      );
    }
  };
}

// command/render/latexmk/parse-error.ts
init_path();
init_fs();
init_lodash();
init_text2();
var kMissingFontLog = "missfont.log";
function findMissingFontsAndPackages(logText, dir) {
  const missingFonts = findMissingFonts(dir);
  const missingPackages = findMissingPackages(logText);
  return uniq([...missingPackages, ...missingFonts]);
}
function needsRecompilation(log3) {
  if (existsSync2(log3)) {
    const logContents = Deno.readTextFileSync(log3);
    const explicitMatches = explicitMatchers.some((matcher) => {
      return logContents.match(matcher);
    });
    if (explicitMatches) {
      return true;
    } else {
      const unresolvedMatches = resolvingMatchers.some((resolvingMatcher) => {
        resolvingMatcher.unresolvedMatch.lastIndex = 0;
        let unresolvedMatch = resolvingMatcher.unresolvedMatch.exec(
          logContents
        );
        const unresolvedMatches2 = [];
        while (unresolvedMatch) {
          const resolvedRegex = new RegExp(
            resolvingMatcher.resolvedMatch.replace(
              kCaptureToken,
              unresolvedMatch[1]
            ),
            "gm"
          );
          if (!logContents.match(resolvedRegex)) {
            unresolvedMatches2.push(unresolvedMatch[1]);
          }
          unresolvedMatch = resolvingMatcher.unresolvedMatch.exec(
            logContents
          );
        }
        if (unresolvedMatches2.length > 0) {
          return true;
        } else {
          return false;
        }
      });
      return !!unresolvedMatches;
    }
  }
  return false;
}
var explicitMatchers = [
  /(Rerun to get | Please \(re\)run | [rR]erun LaTeX\.)/,
  // explicitly request recompile
  /^No file .*?.aux\.\s*$/gm
  // missing aux file from a beamer run using lualatex #6226
];
var kCaptureToken = "${unresolvedCapture}";
var resolvingMatchers = [
  {
    unresolvedMatch: /^.*xpos seems to be \\@mn@currxpos.*?line ([0-9]*)\.$/gm,
    resolvedMatch: `^.*xpos seems to be [0-9]*.[0-9]*pt.*?line ${kCaptureToken}.$`
  }
];
function findPdfAccessibilityWarnings(logText) {
  const result2 = {
    missingAltText: [],
    missingLanguage: false,
    otherWarnings: []
  };
  const altTextRegex = /Package tagpdf Warning: Alternative text for graphic is missing\.\s*\n\(tagpdf\)\s*Using ['`]([^'`]+)['`]\s*(?:\n\(tagpdf\)\s*)?instead\./g;
  let match;
  while ((match = altTextRegex.exec(logText)) !== null) {
    result2.missingAltText.push(match[1]);
  }
  if (/LaTeX DocumentMetadata Warning: The language has not been set in/.test(
    logText
  )) {
    result2.missingLanguage = true;
  }
  const otherTagpdfRegex = /Package tagpdf Warning: ([^\n]+)/g;
  while ((match = otherTagpdfRegex.exec(logText)) !== null) {
    const warning = match[1];
    if (!warning.startsWith("Alternative text for graphic is missing")) {
      result2.otherWarnings.push(warning);
    }
  }
  return result2;
}
function findMissingHyphenationFiles(logText) {
  const filterLang = (lang) => {
    const noHyphen = ["chinese-hans", "chinese"];
    if (noHyphen.includes(lang)) {
      return;
    }
    if (lang === "ngerman") {
      return "hyphen-german";
    }
    return `hyphen-${lang.toLowerCase()}`;
  };
  const babelWarningRegex = /^Package babel Warning:/m;
  const hasWarning = logText.match(babelWarningRegex);
  if (hasWarning) {
    const languageRegex = /^\(babel\).* language [`'](\S+)[`'].*$/m;
    const languageMatch = logText.match(languageRegex);
    if (languageMatch) {
      return filterLang(languageMatch[1]);
    }
  }
  const hyphenRulesRegex = /Package babel Info: Hyphen rules for '(.*?)' set to \\l@nil/m;
  const match = logText.match(hyphenRulesRegex);
  if (match) {
    const language = match[1];
    if (language) {
      return filterLang(language);
    }
  }
}
var kErrorRegex = /^\!\s([\s\S]+)?Here is how much/m;
var kEmptyRegex = /(No pages of output)\./;
function findLatexError(logText, stderr2) {
  const errors2 = [];
  const match = logText.match(kErrorRegex);
  if (match) {
    const hint = suggestHint(logText, stderr2);
    if (hint) {
      errors2.push(`${match[1]}
${hint}`);
    } else {
      errors2.push(match[1]);
    }
  }
  if (errors2.length === 0) {
    const emptyMatch = logText.match(kEmptyRegex);
    if (emptyMatch) {
      errors2.push(
        `${emptyMatch[1]} - the document appears to have produced no output.`
      );
    }
  }
  return errors2.join("\n");
}
var kIndexErrorRegex = /^\s\s\s--\s(.*)/m;
function findIndexError(logText) {
  const match = logText.match(kIndexErrorRegex);
  if (match) {
    return match[1];
  } else {
    return void 0;
  }
}
function findMissingFonts(dir) {
  const missingFonts = [];
  const missFontLog = join4(dir, kMissingFontLog);
  if (existsSync2(missFontLog)) {
    const missFontLogText = Deno.readTextFileSync(missFontLog);
    const fontSearchTerms = findInMissingFontLog(missFontLogText);
    missingFonts.push(...fontSearchTerms);
  }
  return missingFonts;
}
var formatFontFilter = (match, _text) => {
  const base3 = basename4(match).replace(/^.*?:|:.*$/g, "");
  return /[.]/.test(base3) ? base3 : fontSearchTerm(base3);
};
var estoPdfFilter = (_match, _text) => {
  return "epstopdf";
};
var packageMatchers = [
  // Fonts
  {
    regex: /.*! Font [^=]+=([^ ]+).+ not loadable.*/g,
    filter: formatFontFilter
  },
  {
    regex: /.*! .*The font "([^"]+)" cannot be found.*/g,
    filter: formatFontFilter
  },
  {
    regex: /.*!.+ error:.+\(file ([^)]+)\): .*/g,
    filter: formatFontFilter
  },
  {
    regex: /.*Unable to find TFM file "([^"]+)".*/g,
    filter: formatFontFilter
  },
  {
    regex: /.*\(fontspec\)\s+The font "([^"]+)" cannot be.*/g,
    filter: formatFontFilter
  },
  {
    regex: /.*Package widetext error: Install the ([^ ]+) package.*/g,
    filter: (match, _text) => {
      return `${match}.sty`;
    }
  },
  { regex: /.* File [`'](.+eps-converted-to.pdf)'.*/g, filter: estoPdfFilter },
  { regex: /.*xdvipdfmx:fatal: pdf_ref_obj.*/g, filter: estoPdfFilter },
  {
    regex: /.* (tikzlibrary[^ ]+?[.]code[.]tex).*/g,
    filter: (match, text) => {
      if (text.match(/! Package tikz Error:/)) {
        return match;
      } else {
        return void 0;
      }
    }
  },
  {
    regex: /module 'lua-uni-normalize' not found:/g,
    filter: (_match, _text) => {
      return "lua-uni-algos.lua";
    }
  },
  {
    regex: /.* Package pdfx Error: No color profile ([^\s]*).*/g,
    filter: (_match, _text) => {
      return "colorprofiles.sty";
    }
  },
  {
    regex: /.*No support files for \\DocumentMetadata found.*/g,
    filter: (_match, _text) => {
      return "latex-lab";
    }
  },
  {
    // PDF/A requires embedded color profiles - pdfmanagement-testphase needs colorprofiles
    regex: /.*\(pdf backend\): cannot open file for embedding.*/g,
    filter: (_match, _text) => {
      return "colorprofiles";
    }
  },
  {
    regex: /.*No file ([^`'. ]+[.]fd)[.].*/g,
    filter: (match, _text) => {
      return match.toLowerCase();
    }
  },
  { regex: /.* Loading '([^']+)' aborted!.*/g },
  { regex: /.*! LaTeX Error: File [`']([^']+)' not found.*/g },
  { regex: /.* [fF]ile ['`]?([^' ]+)'? not found.*/g },
  { regex: /.*the language definition file ([^\s]*).*/g },
  {
    regex: /.*! Package babel Error: Unknown option [`']([^'`]+)'[.].*/g,
    filter: (match, _text) => {
      return `${match}.ldf`;
    }
  },
  { regex: /.* \\(file ([^)]+)\\): cannot open .*/g },
  { regex: /.*file [`']([^']+)' .*is missing.*/g },
  { regex: /.*! CTeX fontset [`']([^']+)' is unavailable.*/g },
  { regex: /.*: ([^:]+): command not found.*/g },
  { regex: /.*! I can't find file [`']([^']+)'.*/g }
];
function fontSearchTerm(font) {
  const fontPattern = font.replace(/\s+/g, "\\s*");
  return `${fontPattern}(-(Bold|Italic|Regular).*)?[.](tfm|afm|mf|otf|ttf)`;
}
function findMissingPackages(logFileText) {
  const toInstall = [];
  packageMatchers.forEach((packageMatcher) => {
    packageMatcher.regex.lastIndex = 0;
    let match = packageMatcher.regex.exec(logFileText);
    while (match != null) {
      const file = match[1];
      const filteredFile = packageMatcher.filter ? packageMatcher.filter(file, logFileText) : file;
      if (filteredFile) {
        toInstall.push(filteredFile);
      }
      match = packageMatcher.regex.exec(logFileText);
    }
    packageMatcher.regex.lastIndex = 0;
  });
  return uniq(toInstall);
}
function findInMissingFontLog(missFontLogText) {
  const toInstall = [];
  lines(missFontLogText).forEach((line) => {
    line = line.trim();
    const fontMatch = line.match(/([^\s]*)$/);
    if (fontMatch && fontMatch[1].trim() !== "") {
      toInstall.push(fontMatch[1]);
    }
    const commandMatch = line.match(/^([^\s]*)/);
    if (commandMatch && commandMatch[1].trim() !== "") {
      toInstall.push(commandMatch[1]);
    }
  });
  return uniq(toInstall);
}
var kUnicodePattern = {
  regex: /\! Package inputenc Error: Unicode character/,
  hint: "Possible unsupported unicode character in this configuration. Perhaps try another LaTeX engine (e.g. XeLaTeX)."
};
var kInlinePattern = {
  regex: /Missing \$ inserted\./,
  hint: "You may need to $ $ around an expression in this file."
};
var kGhostPattern = {
  regex: /^\!\!\! Error: Cannot open Ghostscript for piped input/m,
  hint: "GhostScript is likely required to compile this document. Please be sure GhostScript (https://ghostscript.com) is installed and try again."
};
var kGhostCorruptPattern = {
  regex: /^GPL Ghostscript .*: Can't find initialization file gs_init.ps/m,
  hint: "GhostScript is likely required to compile this document. Please be sure GhostScript (https://ghostscript.com) is installed and configured properly and try again."
};
var kLogOutputPatterns = [kUnicodePattern, kInlinePattern];
var kStdErrPatterns = [kGhostPattern, kGhostCorruptPattern];
function suggestHint(logText, stderr2) {
  const stderrHint = kStdErrPatterns.find(
    (errPattern) => stderr2?.match(errPattern.regex)
  );
  if (stderrHint) {
    return stderrHint.hint;
  } else {
    const logHint = kLogOutputPatterns.find(
      (logPattern) => logText.match(logPattern.regex)
    );
    if (logHint) {
      return logHint.hint;
    } else {
      return void 0;
    }
  }
}

// command/render/latexmk/pdf.ts
init_log();
init_log2();
init_platform();
async function generatePdf(mkOptions) {
  if (!mkOptions.quiet) {
    logProgress("\nRendering PDF");
    logProgress(
      `running ${mkOptions.engine.pdfEngine} - 1`
    );
  }
  const [cwd2, stem] = dirAndStem(mkOptions.input);
  const workingDir = mkOptions.outputDir ? join4(cwd2, mkOptions.outputDir) : cwd2;
  if (!existsSync2(workingDir)) {
    Deno.mkdirSync(workingDir);
  } else {
    cleanup(workingDir, stem);
  }
  const allowUpdate = await hasTexLive();
  mkOptions.autoInstall = mkOptions.autoInstall && allowUpdate;
  const texLive = await texLiveContext(mkOptions.tinyTex !== false);
  const pkgMgr = packageManager(mkOptions, texLive);
  const response = await initialCompileLatex(
    mkOptions.input,
    mkOptions.engine,
    pkgMgr,
    texLive,
    mkOptions.outputDir,
    mkOptions.texInputDirs,
    mkOptions.quiet
  );
  const initialCompileNeedsRerun = needsRecompilation(response.log);
  const indexIntermediateFile = indexIntermediate(workingDir, stem);
  let indexCreated = false;
  if (indexIntermediateFile) {
    info("  Re-compiling document for index");
    await runPdfEngine(
      mkOptions.input,
      mkOptions.engine,
      texLive,
      mkOptions.outputDir,
      mkOptions.texInputDirs,
      pkgMgr,
      mkOptions.quiet
    );
    indexCreated = await makeIndexIntermediates(
      indexIntermediateFile,
      pkgMgr,
      texLive,
      mkOptions.engine.indexEngine,
      mkOptions.engine.indexEngineOpts,
      mkOptions.quiet
    );
  }
  const bibliographyCreated = await makeBibliographyIntermediates(
    mkOptions.input,
    mkOptions.engine.bibEngine || "citeproc",
    pkgMgr,
    texLive,
    mkOptions.outputDir,
    mkOptions.texInputDirs,
    mkOptions.quiet
  );
  const minRuns = (mkOptions.minRuns || 1) - 1;
  const maxRuns = (mkOptions.maxRuns || 10) - 1;
  if ((indexCreated || bibliographyCreated || minRuns || initialCompileNeedsRerun) && maxRuns > 0) {
    await recompileLatexUntilComplete(
      mkOptions.input,
      mkOptions.engine,
      pkgMgr,
      mkOptions.minRuns || 1,
      maxRuns,
      texLive,
      mkOptions.outputDir,
      mkOptions.texInputDirs,
      mkOptions.quiet
    );
  }
  if (mkOptions.clean) {
    cleanup(workingDir, stem);
  }
  if (!mkOptions.quiet) {
    info("");
  }
  return mkOptions.outputDir ? join4(mkOptions.outputDir, stem + ".pdf") : join4(cwd2, stem + ".pdf");
}
async function initialCompileLatex(input, engine, pkgMgr, texLive, outputDir, texInputDirs, quiet) {
  let packagesUpdated = false;
  while (true) {
    const response = await runPdfEngine(
      input,
      engine,
      texLive,
      outputDir,
      texInputDirs,
      pkgMgr,
      quiet
    );
    const success = response.result.code === 0 && (!response.output || existsSync2(response.output));
    if (success) {
      const logText = Deno.readTextFileSync(response.log);
      const missingHyphenationFile = findMissingHyphenationFiles(logText);
      if (missingHyphenationFile) {
        if (pkgMgr.autoInstall) {
          logProgress("Installing missing hyphenation file...");
          if (await pkgMgr.installPackages([missingHyphenationFile])) {
            continue;
          } else {
            logProgress("Installing missing hyphenation file failed.");
          }
        }
        warn(
          `Possibly missing hyphenation file: '${missingHyphenationFile}'. See more in logfile (by setting 'latex-clean: false').
`
        );
      }
      const accessibilityWarnings = findPdfAccessibilityWarnings(logText);
      if (accessibilityWarnings.missingAltText.length > 0) {
        const fileList = accessibilityWarnings.missingAltText.join(", ");
        warn(
          `PDF accessibility: Missing alt text for image(s): ${fileList}. Add alt text using fig-alt in YAML or {fig-alt="description"} on the image for PDF/UA compliance.
`
        );
      }
      if (accessibilityWarnings.missingLanguage) {
        warn(
          `PDF accessibility: Document language not set. Add 'lang: en' (or appropriate language) to document metadata for PDF/UA compliance.
`
        );
      }
      if (accessibilityWarnings.otherWarnings.length > 0) {
        for (const warn2 of accessibilityWarnings.otherWarnings) {
          warn(`PDF accessibility: ${warn2}
`);
        }
      }
    } else if (pkgMgr.autoInstall) {
      if (!packagesUpdated) {
        if (!quiet) {
          logProgress("updating tlmgr");
        }
        await pkgMgr.updatePackages(false, true);
        info("");
        if (!quiet) {
          logProgress("updating existing packages");
        }
        await pkgMgr.updatePackages(true, false);
        packagesUpdated = true;
      }
      const packagesInstalled = await findAndInstallPackages(
        pkgMgr,
        response.log,
        response.result.stderr,
        quiet
      );
      if (packagesInstalled) {
        continue;
      } else {
        displayError(
          "missing packages (automatic installation failed)",
          response.log,
          response.result
        );
        return Promise.reject();
      }
    } else {
      displayError(
        "missing packages (automatic installed disabled)",
        response.log,
        response.result
      );
      return Promise.reject();
    }
    return Promise.resolve(response);
  }
}
function displayError(title3, log3, result2) {
  if (existsSync2(log3)) {
    const logText = Deno.readTextFileSync(log3);
    writeError(
      title3,
      findLatexError(logText, result2.stderr),
      log3
    );
  } else {
    writeError(title3);
  }
}
function indexIntermediate(dir, stem) {
  const indexFile = join4(dir, `${stem}.idx`);
  if (existsSync2(indexFile)) {
    return indexFile;
  } else {
    return void 0;
  }
}
async function makeIndexIntermediates(indexFile, pkgMgr, texLive, engine, args, quiet) {
  if (indexFile) {
    if (!quiet) {
      logProgress("making index");
    }
    try {
      const response = await runIndexEngine(
        indexFile,
        texLive,
        engine,
        args,
        pkgMgr,
        quiet
      );
      const indexLogExists = existsSync2(response.log);
      if (response.result.code !== 0) {
        writeError(
          `result code ${response.result.code}`,
          "",
          response.log
        );
        return Promise.reject();
      } else if (indexLogExists) {
        const logText = Deno.readTextFileSync(response.log);
        const error2 = findIndexError(logText);
        if (error2) {
          writeError(
            `error generating index`,
            error2,
            response.log
          );
          return Promise.reject();
        }
      }
      return true;
    } catch {
      writeError(
        `error generating index`
      );
      return Promise.reject();
    }
  } else {
    return false;
  }
}
async function makeBibliographyIntermediates(input, engine, pkgMgr, texLive, outputDir, texInputDirs, quiet) {
  const bibCommand = engine === "natbib" ? "bibtex" : "biber";
  const [cwd2, stem] = dirAndStem(input);
  while (true) {
    const auxBibFile = bibCommand === "biber" ? `${stem}.bcf` : `${stem}.aux`;
    const auxBibPath = outputDir ? join4(outputDir, auxBibFile) : auxBibFile;
    const auxBibFullPath = join4(cwd2, auxBibPath);
    if (existsSync2(auxBibFullPath)) {
      const auxFileData = Deno.readTextFileSync(auxBibFullPath);
      const requiresProcessing = bibCommand === "biber" ? true : containsBiblioData(auxFileData);
      if (requiresProcessing) {
        if (!quiet) {
          logProgress("generating bibliography");
        }
        if (isWindows4) {
          if (bibCommand !== "biber" && !hasTexLive()) {
            const fixedAuxFileData = auxFileData.replaceAll(
              /(^\\bibdata{.+)\.bib(.*})$/gm,
              (_substr, prefix, postfix) => {
                return prefix + postfix;
              }
            );
            Deno.writeTextFileSync(auxBibFullPath, fixedAuxFileData);
          }
        }
        const response = await runBibEngine(
          bibCommand,
          auxBibPath,
          cwd2,
          texLive,
          pkgMgr,
          texInputDirs,
          quiet
        );
        if (response.result.code !== 0 && pkgMgr.autoInstall) {
          const log3 = join4(dirname4(auxBibFullPath), `${stem}.blg`);
          if (existsSync2(log3)) {
            const logOutput = Deno.readTextFileSync(log3);
            const match = logOutput.match(/.* open style file ([^ ]+).*/);
            if (match) {
              const file = match[1];
              if (await findAndInstallPackages(
                pkgMgr,
                file,
                response.result.stderr,
                quiet
              )) {
                continue;
              } else {
                writeError(`error generating bibliography`, "", log3);
                return Promise.reject();
              }
            }
          }
        }
        return true;
      }
    }
    return false;
  }
}
async function findAndInstallPackages(pkgMgr, logFile, stderr2, _quiet) {
  if (existsSync2(logFile)) {
    const logText = Deno.readTextFileSync(logFile);
    const searchTerms = findMissingFontsAndPackages(logText, dirname4(logFile));
    if (searchTerms.length > 0) {
      const packages = await pkgMgr.searchPackages(searchTerms);
      if (packages.length > 0) {
        const packagesInstalled = await pkgMgr.installPackages(
          packages
        );
        if (packagesInstalled) {
          return true;
        } else {
          writeError(
            "package installation error",
            findLatexError(logText, stderr2),
            logFile
          );
          return Promise.reject();
        }
      } else {
        writeError(
          "no matching packages",
          findLatexError(logText, stderr2),
          logFile
        );
        return Promise.reject();
      }
    } else {
      writeError("error", findLatexError(logText, stderr2), logFile);
      return Promise.reject();
    }
  }
  return false;
}
function writeError(primary, secondary, logFile) {
  error(
    `
compilation failed- ${primary}`
  );
  if (secondary) {
    info(secondary);
  }
  if (logFile) {
    info(`see ${logFile} for more information.`);
  }
}
async function recompileLatexUntilComplete(input, engine, pkgMgr, minRuns, maxRuns, texLive, outputDir, texInputDirs, quiet) {
  let runCount = 0;
  minRuns = minRuns - 1;
  while (true) {
    if (runCount >= maxRuns) {
      if (!quiet) {
        warn(
          `maximum number of runs (${maxRuns}) reached`
        );
      }
      break;
    }
    if (!quiet) {
      logProgress(
        `running ${engine.pdfEngine} - ${runCount + 2}`
      );
    }
    const result2 = await runPdfEngine(
      input,
      engine,
      texLive,
      outputDir,
      texInputDirs,
      pkgMgr,
      quiet
    );
    if (!result2.result.success) {
      displayError("Error compiling latex", result2.log, result2.result);
      return Promise.reject();
    } else {
      runCount = runCount + 1;
      if (existsSync2(result2.log) && needsRecompilation(result2.log) || runCount < minRuns) {
        continue;
      }
      break;
    }
  }
}
function containsBiblioData(auxData) {
  return auxData.match(/^\\(bibdata|citation|bibstyle)\{/m);
}
function auxFile(stem, ext) {
  return `${stem}.${ext}`;
}
function cleanup(workingDir, stem) {
  const auxFiles = [
    "log",
    "idx",
    "aux",
    "bcf",
    "blg",
    "bbl",
    "fls",
    "out",
    "lof",
    "lot",
    "toc",
    "nav",
    "snm",
    "vrb",
    "ilg",
    "ind",
    "xwm",
    "brf",
    "run.xml"
  ].map((aux) => join4(workingDir, auxFile(stem, aux)));
  auxFiles.push(join4(workingDir, kMissingFontLog));
  auxFiles.forEach((auxFile2) => {
    if (existsSync2(auxFile2)) {
      safeRemoveSync(auxFile2);
    }
  });
}

// command/render/output-tex.ts
init_path();
init_fs();
init_path2();
init_tex();
init_constants6();
init_array();

// core/verapdf.ts
init_log();
init_path();
init_colors2();
init_process();
init_path2();
init_appdirs();
init_fs();
init_log2();
var kVerapdfEnvVar = "QUARTO_VERAPDF";
var kVerapdfMainClass = "org.verapdf.apps.GreenfieldCliWrapper";
var kVerapdfFlavours = {
  // PDF/A standards
  "a-1a": "1a",
  "a-1b": "1b",
  "a-2a": "2a",
  "a-2b": "2b",
  "a-2u": "2u",
  "a-3a": "3a",
  "a-3b": "3b",
  "a-3u": "3u",
  "a-4": "4",
  "a-4e": "4e",
  "a-4f": "4f",
  // PDF/UA standards
  "ua-1": "ua1",
  "ua-2": "ua2"
};
var kVerapdfSupportedStandards = new Set(Object.keys(kVerapdfFlavours));
function getVerapdfFlavour(standard) {
  const normalized = standard.toLowerCase().replace(/^pdf[/-]?/, "");
  return kVerapdfFlavours[normalized];
}
async function buildVerapdfCommand(flavour, pdfPath) {
  const envOverride = Deno.env.get(kVerapdfEnvVar);
  if (envOverride) {
    const looksLikePath = envOverride.startsWith("/") || envOverride.startsWith("./") || envOverride.startsWith("~") || /^[A-Za-z]:[\\/]/.test(envOverride);
    if (looksLikePath && !existsSync2(envOverride)) {
      warnOnce(
        `Specified ${kVerapdfEnvVar} does not exist, using built-in verapdf`
      );
    } else {
      info(`Using ${kVerapdfEnvVar}: ${envOverride}`);
      return {
        cmd: envOverride,
        args: ["-f", flavour, pdfPath]
      };
    }
  }
  const quartoVerapdfDir = quartoDataDir("verapdf");
  const binDir3 = join4(quartoVerapdfDir, "bin");
  if (existsSync2(binDir3)) {
    const javaPath = await which("java");
    if (javaPath) {
      return {
        cmd: javaPath,
        args: [
          "-classpath",
          join4(binDir3, "*"),
          "-Dfile.encoding=UTF8",
          "-XX:+IgnoreUnrecognizedVMOptions",
          `-Dbasedir=${quartoVerapdfDir}`,
          "--add-exports=java.base/sun.security.pkcs=ALL-UNNAMED",
          kVerapdfMainClass,
          "-f",
          flavour,
          pdfPath
        ]
      };
    }
  }
  const systemVerapdf = await which("verapdf");
  if (systemVerapdf) {
    return {
      cmd: systemVerapdf,
      args: ["-f", flavour, pdfPath]
    };
  }
  return void 0;
}
async function findVerapdfPath() {
  const quartoVerapdfDir = quartoDataDir("verapdf");
  const binDir3 = join4(quartoVerapdfDir, "bin");
  if (existsSync2(binDir3)) {
    return binDir3;
  }
  const pathResult = await which("verapdf");
  if (pathResult) {
    return pathResult;
  }
  return void 0;
}
async function validatePdf(pdfPath, flavour, quiet = false) {
  const invocation = await buildVerapdfCommand(flavour, pdfPath);
  if (!invocation) {
    throw new Error("verapdf not found");
  }
  if (!quiet) {
    info(
      `[verapdf]: Validating ${basename4(pdfPath)} against PDF/${flavour.toUpperCase()}...`,
      { newline: false }
    );
  }
  const result2 = await execProcess({
    cmd: invocation.cmd,
    args: invocation.args,
    stdout: "piped",
    stderr: "piped"
  });
  const output = result2.stdout || "";
  const isCompliantMatch = output.match(/isCompliant="(true|false)"/);
  const batchSummaryMatch = output.match(
    /validationReports[^>]*compliant="(\d+)"[^>]*nonCompliant="(\d+)"/
  );
  let valid = false;
  if (isCompliantMatch) {
    valid = isCompliantMatch[1] === "true";
  } else if (batchSummaryMatch) {
    const compliant = parseInt(batchSummaryMatch[1]);
    const nonCompliant = parseInt(batchSummaryMatch[2]);
    valid = nonCompliant === 0 && compliant > 0;
  } else {
    valid = result2.success;
  }
  const errors2 = [];
  if (!valid) {
    const ruleDescMatches = output.matchAll(
      /<rule[^>]*>[\s\S]*?<description>([^<]+)<\/description>/g
    );
    for (const match of ruleDescMatches) {
      const desc = match[1].trim();
      if (desc && !errors2.includes(desc)) {
        errors2.push(desc);
      }
    }
    if (errors2.length === 0) {
      const clauseMatches = output.matchAll(
        /<ruleId[^>]*clause="([^"]*)"[^>]*specification="([^"]*)"/g
      );
      for (const match of clauseMatches) {
        errors2.push(`${match[2]} clause ${match[1]} violation`);
      }
    }
    const failedChecksMatch = output.match(/failedChecks="(\d+)"/);
    if (failedChecksMatch && parseInt(failedChecksMatch[1]) > 0) {
      const count = failedChecksMatch[1];
      if (errors2.length === 0) {
        errors2.push(`${count} compliance check(s) failed`);
      }
    }
  }
  if (!quiet) {
    if (valid) {
      info(green2("PASSED\n"));
    } else {
      info(red3("FAILED\n"));
    }
  }
  return {
    valid,
    flavour,
    errors: errors2,
    output
  };
}
async function validatePdfStandards(pdfPath, standards, options = {}) {
  const quiet = options.quiet ?? false;
  const warnOnMissingVerapdf = options.warnOnMissingVerapdf ?? true;
  const validatableStandards = [];
  const nonValidatableStandards = [];
  for (const standard of standards) {
    const standardStr = String(standard);
    const normalized = standardStr.toLowerCase().replace(/^pdf[/-]?/, "");
    if (/^\d+\.\d+$/.test(normalized)) {
      continue;
    }
    const flavour = getVerapdfFlavour(normalized);
    if (flavour) {
      validatableStandards.push({ standard: normalized, flavour });
    } else {
      nonValidatableStandards.push(standardStr);
    }
  }
  if (validatableStandards.length === 0) {
    return true;
  }
  const verapdfPath = await findVerapdfPath();
  if (!verapdfPath) {
    if (warnOnMissingVerapdf) {
      warn(
        `PDF standard validation requested but verapdf is not installed.
Install with: quarto install verapdf
Standards requested: ${validatableStandards.map((s5) => s5.standard).join(", ")}`
      );
    }
    return true;
  }
  if (nonValidatableStandards.length > 0) {
    warn(
      `The following PDF standards cannot be validated by verapdf and will be skipped: ` + nonValidatableStandards.join(", ")
    );
  }
  let allValid = true;
  for (const { standard, flavour } of validatableStandards) {
    try {
      const result2 = await validatePdf(pdfPath, flavour, quiet);
      if (!result2.valid) {
        allValid = false;
        if (!quiet) {
          warn(
            `PDF validation failed for ${standard}:
` + (result2.errors.length > 0 ? result2.errors.slice(0, 5).join("\n") : "See verapdf output for details")
          );
        }
      }
    } catch (error2) {
      if (!quiet) {
        warn(`Failed to run verapdf validation: ${error2}`);
      }
    }
  }
  return allValid;
}

// command/render/output-tex.ts
init_flags2();
init_pdf();
init_process();
init_pandoc_formats();

// command/render/output-shared.ts
init_path();
function normalizeOutputPath(input, output) {
  if (isAbsolute4(output)) {
    return output;
  } else {
    return relative4(
      dirname4(input),
      output
    );
  }
}

// command/render/output-tex.ts
function texToPdfOutputRecipe(input, finalOutput, options, format14, pdfIntermediateTo, pdfGenerator, pdfOutputDir) {
  const [inputDir, inputStem] = dirAndStem(input);
  let fixupInputName = "";
  if (format14.identifier[kTargetFormat]) {
    const formatDesc = parseFormatString(format14.identifier[kTargetFormat]);
    fixupInputName = `${formatDesc.variants.join("")}${formatDesc.modifiers.join("")}`;
  }
  const texStem = texSafeFilename(`${inputStem}${fixupInputName}`);
  const output = texStem + ".tex";
  let args = options.pandocArgs || [];
  const pandoc2 = { ...format14.pandoc };
  if (options.flags?.output) {
    args = replacePandocOutputArg(args, output);
  } else {
    pandoc2[kOutputFile] = output;
  }
  const complete = async (pandocOptions) => {
    const input2 = join4(inputDir, output);
    const pdfOutput2 = await pdfGenerator.generate(input2, format14, pandocOptions);
    const pdfStandards = asArray(
      pandocOptions.format.metadata?.[kPdfStandardApplied] ?? format14.render?.[kPdfStandard] ?? format14.metadata?.[kPdfStandard] ?? pdfStandardEnv()
    );
    if (pdfStandards.length > 0) {
      await validatePdfStandards(pdfOutput2, pdfStandards, {
        quiet: pandocOptions.flags?.quiet
      });
    }
    const compileTex = join4(inputDir, output);
    if (!format14.render[kKeepTex]) {
      safeRemoveSync(compileTex);
    }
    if (finalOutput) {
      if (finalOutput === kStdOut) {
        writeFileToStdout(pdfOutput2);
        safeRemoveSync(pdfOutput2);
      } else {
        const outputPdf = expandPath(finalOutput);
        if (normalize4(pdfOutput2) !== normalize4(outputPdf)) {
          ensureDirSync(dirname4(outputPdf));
          Deno.renameSync(pdfOutput2, outputPdf);
        }
      }
      if (pdfOutputDir) {
        console.log({ pdfOutputDir });
        try {
          safeRemoveSync(pdfOutputDir, { recursive: false });
        } catch {
        }
      }
      return normalizeOutputPath(input2, finalOutput);
    } else {
      return normalizeOutputPath(input2, pdfOutput2);
    }
  };
  const pdfOutput = finalOutput ? finalOutput === kStdOut ? void 0 : normalizeOutputPath(input, finalOutput) : normalizeOutputPath(
    input,
    pdfGenerator.computePath(texStem, dirname4(input), format14)
  );
  const to = format14.pandoc.to === "pdf" ? pdfIntermediateTo : format14.pandoc.to;
  return {
    output,
    keepYaml: false,
    args,
    format: {
      ...format14,
      pandoc: {
        ...pandoc2,
        to
      }
    },
    complete,
    finalOutput: pdfOutput ? relative4(inputDir, pdfOutput) : void 0
  };
}
function useContextPdfOutputRecipe(format14, flags) {
  const kContextPdfEngine = "context";
  if (format14.pandoc.to === "pdf" && format14.render[kOutputExt] === "pdf") {
    const engine = pdfEngine(format14.pandoc, format14.render, flags);
    return engine.pdfEngine === kContextPdfEngine;
  } else {
    return false;
  }
}
function contextPdfOutputRecipe(input, finalOutput, options, format14) {
  const computePath = (stem, dir, _format5) => {
    return join4(dir, stem + ".pdf");
  };
  const generate = async (input2, format15, pandocOptions) => {
    const engine = pdfEngine(format15.pandoc, format15.render, pandocOptions.flags);
    const cmd = "context";
    const args = [input2];
    if (engine.pdfEngineOpts) {
      args.push(...engine.pdfEngineOpts);
    }
    args.push(
      // ConTeXt produces some auxiliary files:
      // direct PDF generation by Pandoc never produces these auxiliary
      // files because Pandoc runs ConTeXt in a temporary directory.
      // Replicate Pandoc's behavior using "--purgeall" option
      "--purgeall",
      // Pandoc runs ConteXt with "--batchmode" option. Do the same.
      "--batchmode"
    );
    const result2 = await execProcess({
      cmd,
      args
    });
    if (result2.success) {
      const [dir, stem] = dirAndStem(input2);
      return computePath(stem, dir, format15);
    } else {
      throw new Error();
    }
  };
  return texToPdfOutputRecipe(
    input,
    finalOutput,
    options,
    format14,
    "context",
    {
      generate,
      computePath
    }
  );
}

// command/render/latexmk/latexmk.ts
init_path();
function useQuartoLatexmk(format14, flags) {
  const to = format14.pandoc.to;
  const ext = format14.render[kOutputExt] || "html";
  if (format14.render[kLatexAutoMk] === false) {
    return false;
  }
  if (["beamer", "pdf"].includes(to || "") && ext === "pdf") {
    const engine = pdfEngine(format14.pandoc, format14.render, flags);
    return isLatexPdfEngine(engine);
  }
  return false;
}
function quartoLatexmkOutputRecipe(input, finalOutput, options, format14) {
  const outputDir = format14.render[kLatexOutputDir];
  const generate = (input2, format15, pandocOptions) => {
    const texInputDirs = [];
    if (format15.render[kLatexInputPaths]) {
      texInputDirs.push(...format15.render[kLatexInputPaths]);
    }
    const mkOptions = {
      input: input2,
      engine: pdfEngine(format15.pandoc, format15.render, pandocOptions.flags),
      autoInstall: format15.render[kLatexAutoInstall],
      autoMk: format15.render[kLatexAutoMk],
      minRuns: format15.render[kLatexMinRuns],
      maxRuns: format15.render[kLatexMaxRuns],
      tinyTex: format15.render[kLatexTinyTex],
      texInputDirs,
      outputDir: outputDir === null ? void 0 : outputDir,
      clean: !options.flags?.debug && format15.render[kLatexClean] !== false,
      quiet: pandocOptions.flags?.quiet
    };
    return generatePdf(mkOptions);
  };
  const computePath = (texStem, inputDir, format15) => {
    const mkOutputdir = format15.render[kLatexOutputDir];
    return mkOutputdir ? join4(mkOutputdir, texStem + ".pdf") : join4(inputDir, texStem + ".pdf");
  };
  return texToPdfOutputRecipe(
    input,
    finalOutput,
    options,
    format14,
    "latex",
    {
      generate,
      computePath
    },
    outputDir
  );
}

// command/render/output.ts
init_flags2();
init_render();
init_pandoc_formats();

// command/render/output-typst.ts
init_path();
init_fs();
await init_extension();
init_project_scratch();
init_resources2();
init_constants6();
init_log();
init_error2();
init_path2();
init_flags2();

// core/typst-gather.ts
init_fs();
init_platform();
init_resources2();
init_process();
function toTomlPath(p5) {
  return p5.replace(/\\/g, "/");
}
function typstGatherBinaryPath() {
  const binaryName = isWindows4 ? "typst-gather.exe" : "typst-gather";
  const binary3 = Deno.env.get("QUARTO_TYPST_GATHER") || architectureToolsPath(binaryName);
  if (!existsSync2(binary3)) {
    throw new Error(
      `typst-gather binary not found.
Run ./configure.sh to build and install it.`
    );
  }
  return binary3;
}
async function runAnalyze(tomlConfig) {
  const binary3 = typstGatherBinaryPath();
  const result2 = await execProcess(
    {
      cmd: binary3,
      args: ["analyze", "-"],
      stdout: "piped",
      stderr: "piped"
    },
    tomlConfig
  );
  if (!result2.success) {
    throw new Error(
      result2.stderr || "typst-gather analyze failed"
    );
  }
  return JSON.parse(result2.stdout);
}

// command/render/output-typst.ts
init_array();
async function collectPackageSources(input, projectDir) {
  const sources = [];
  const builtinPackages = resourcePath("formats/typst/packages");
  if (existsSync2(builtinPackages)) {
    sources.push(builtinPackages);
  }
  const extensionDirs = inputExtensionDirs(input, projectDir);
  const subtreePath = builtinSubtreeExtensions();
  for (const extDir of extensionDirs) {
    const extensions2 = extDir === subtreePath ? await readSubtreeExtensions(extDir) : await readExtensions(extDir);
    for (const ext of extensions2) {
      const packagesDir = join4(ext.path, "typst/packages");
      if (existsSync2(packagesDir)) {
        sources.push(packagesDir);
      }
    }
  }
  return sources;
}
function buildAnalyzeToml(typstInput, packageSources) {
  const discoverPath = toTomlPath(typstInput);
  const cachePaths = packageSources.map((p5) => `"${toTomlPath(p5)}"`).join(", ");
  return [
    `discover = ["${discoverPath}"]`,
    `package-cache = [${cachePaths}]`
  ].join("\n");
}
async function analyzeNeededPackages(typstInput, packageSources) {
  const tomlConfig = buildAnalyzeToml(typstInput, packageSources);
  try {
    const result2 = await runAnalyze(tomlConfig);
    return result2.imports.map(({ namespace, name: name2, version: version4 }) => ({
      namespace,
      name: name2,
      version: version4
    }));
  } catch {
    warn("typst-gather analyze failed; staging all packages as fallback");
    return null;
  }
}
function stageSelectedPackages(sources, cacheDir, needed) {
  if (needed === null) {
    stageAllPackages(sources, cacheDir);
    return;
  }
  for (const pkg of needed) {
    const relPath = join4(pkg.namespace, pkg.name, pkg.version);
    const destPath = join4(cacheDir, relPath);
    for (const source2 of sources) {
      const srcPath = join4(source2, relPath);
      if (existsSync2(srcPath)) {
        ensureDirSync(dirname4(destPath));
        copySync(srcPath, destPath, { overwrite: true });
      }
    }
  }
}
function stageAllPackages(sources, cacheDir) {
  for (const source2 of sources) {
    for (const nsEntry of Deno.readDirSync(source2)) {
      if (!nsEntry.isDirectory) continue;
      const nsSrc = join4(source2, nsEntry.name);
      const nsDest = join4(cacheDir, nsEntry.name);
      ensureDirSync(nsDest);
      for (const pkgEntry of Deno.readDirSync(nsSrc)) {
        const pkgSrc = join4(nsSrc, pkgEntry.name);
        const pkgDest = join4(nsDest, pkgEntry.name);
        copySync(pkgSrc, pkgDest, { overwrite: true });
      }
    }
  }
}
async function stageTypstPackages(input, typstInput, projectDir) {
  if (!projectDir) {
    return void 0;
  }
  const packageSources = await collectPackageSources(input, projectDir);
  if (packageSources.length === 0) {
    return void 0;
  }
  const neededPackages = await analyzeNeededPackages(
    typstInput,
    packageSources
  );
  const cacheDir = projectScratchPath(projectDir, "typst/packages");
  stageSelectedPackages(packageSources, cacheDir, neededPackages);
  return cacheDir;
}
function useTypstPdfOutputRecipe(format14) {
  return format14.pandoc.to === "typst" && format14.render[kOutputExt] === "pdf";
}
function typstPdfOutputRecipe(input, finalOutput, options, format14, project) {
  const [inputDir, inputStem] = dirAndStem(input);
  const output = inputStem + ".typ";
  let args = options.pandocArgs || [];
  const pandoc2 = { ...format14.pandoc };
  if (options.flags?.output) {
    args = replacePandocOutputArg(args, output);
  } else {
    pandoc2[kOutputFile] = output;
  }
  const complete = async () => {
    const typstInput = join4(inputDir, output);
    await validateRequiredTypstVersion();
    const pdfOutput2 = join4(inputDir, inputStem + ".pdf");
    const typstOptions = {
      quiet: options.flags?.quiet,
      fontPaths: asArray(format14.metadata?.[kFontPaths]).map(
        (p5) => isAbsolute4(p5) ? p5 : resolve4(inputDir, p5)
      ),
      pdfStandard: normalizePdfStandardForTypst(
        asArray(
          format14.render?.[kPdfStandard] ?? format14.metadata?.[kPdfStandard] ?? pdfStandardEnv()
        )
      )
    };
    if (project?.dir) {
      typstOptions.rootDir = project.dir;
      const packagePath = await stageTypstPackages(
        input,
        typstInput,
        project.dir
      );
      if (packagePath) {
        typstOptions.packagePath = packagePath;
      }
    }
    const result2 = await typstCompile(
      typstInput,
      pdfOutput2,
      typstOptions
    );
    if (!result2.success) {
      if (result2.stderr) {
        error(result2.stderr);
      }
      throw new ErrorEx("Error", "Typst compilation failed", false, false);
    }
    const pdfStandards = asArray(
      format14.render?.[kPdfStandard] ?? format14.metadata?.[kPdfStandard] ?? pdfStandardEnv()
    );
    if (pdfStandards.length > 0) {
      await validatePdfStandards(pdfOutput2, pdfStandards, {
        quiet: options.flags?.quiet
      });
    }
    if (!format14.render[kKeepTyp]) {
      safeRemoveSync(typstInput);
    }
    if (finalOutput) {
      if (finalOutput === kStdOut) {
        writeFileToStdout(pdfOutput2);
        safeRemoveSync(pdfOutput2);
      } else {
        const outputPdf = expandPath(finalOutput);
        if (normalize4(pdfOutput2) !== normalize4(outputPdf)) {
          ensureDirSync(dirname4(outputPdf));
          Deno.renameSync(pdfOutput2, outputPdf);
        }
      }
      return normalizeOutputPath(typstInput, finalOutput);
    } else {
      return normalizeOutputPath(typstInput, pdfOutput2);
    }
  };
  const pdfOutput = finalOutput ? finalOutput === kStdOut ? void 0 : normalizeOutputPath(input, finalOutput) : normalizeOutputPath(input, join4(inputDir, inputStem + ".pdf"));
  const recipe = {
    output,
    keepYaml: false,
    args,
    format: { ...format14, pandoc: pandoc2 },
    complete,
    finalOutput: pdfOutput ? relative4(inputDir, pdfOutput) : void 0
  };
  if (format14.render?.[kVariant]) {
    const to = format14.pandoc.to;
    const variant = format14.render[kVariant];
    recipe.format = {
      ...recipe.format,
      pandoc: {
        ...recipe.format.pandoc,
        to: `${to}${variant}`
      }
    };
  }
  return recipe;
}
var kTypstSupportedStandards = /* @__PURE__ */ new Set([
  "1.4",
  "1.5",
  "1.6",
  "1.7",
  "2.0",
  "a-1b",
  "a-1a",
  "a-2b",
  "a-2u",
  "a-2a",
  "a-3b",
  "a-3u",
  "a-3a",
  "a-4",
  "a-4f",
  "a-4e",
  "ua-1"
]);
function normalizePdfStandardForTypst(standards) {
  const result2 = [];
  for (const s5 of standards) {
    let str3;
    if (typeof s5 === "number") {
      str3 = Number.isInteger(s5) ? `${s5}.0` : String(s5);
    } else if (typeof s5 === "string") {
      str3 = s5;
    } else {
      continue;
    }
    const normalized = str3.toLowerCase().replace(/^pdf[/-]?/, "");
    if (kTypstSupportedStandards.has(normalized)) {
      result2.push(normalized);
    } else {
      warn(
        `PDF standard '${s5}' is not supported by Typst and will be ignored`
      );
    }
  }
  return result2;
}

// command/render/output.ts
function outputRecipe(context) {
  const input = context.target.input;
  const options = context.options;
  const format14 = context.format;
  let output = options.flags?.output;
  if (!output) {
    const outputFile5 = formatOutputFile(format14);
    if (outputFile5) {
      if (outputFile5.match(SEP_PATTERN)) {
        throw new Error(
          `
In file ${context.target.source}
  Invalid value for \`output-file\`: paths are not allowed`
        );
      }
      output = join4(dirname4(input), outputFile5);
    } else {
      output = "";
    }
  }
  if (useQuartoLatexmk(format14, options.flags)) {
    return quartoLatexmkOutputRecipe(input, output, options, format14);
  } else if (useContextPdfOutputRecipe(format14, options.flags)) {
    return contextPdfOutputRecipe(input, output, options, format14);
  } else if (useTypstPdfOutputRecipe(format14)) {
    return typstPdfOutputRecipe(
      input,
      output,
      options,
      format14,
      context.project
    );
  } else {
    const completeActions = [];
    const recipe = {
      output,
      keepYaml: false,
      args: options.pandocArgs || [],
      format: { ...format14 },
      complete: () => {
        completeActions.forEach((action) => action());
        return Promise.resolve();
      }
    };
    resolveKeepSource(recipe.format, context.engine, context.target);
    const updateOutput = (output2) => {
      recipe.output = output2;
      if (options.flags?.output) {
        recipe.args = replacePandocOutputArg(recipe.args, output2);
      } else {
        recipe.format.pandoc[kOutputFile] = output2;
      }
    };
    const ext = format14.render[kOutputExt] || "html";
    const [inputDir, inputStem] = dirAndStem(input);
    if (format14.render[kVariant]) {
      const to = format14.pandoc.to;
      const variant = format14.render[kVariant];
      recipe.format = {
        ...recipe.format,
        pandoc: {
          ...recipe.format.pandoc,
          to: `${to}${variant}`
        }
      };
      if (recipe.format.pandoc.to?.includes(`+${kYamlMetadataBlock}`)) {
        recipe.keepYaml = true;
      }
    }
    if (recipe.keepYaml || recipe.format.render[kPreserveYaml]) {
      completeActions.push(() => {
        const inputMd = partitionYamlFrontMatter(context.target.markdown.value);
        if (inputMd) {
          const outputFile5 = isAbsolute4(recipe.output) ? recipe.output : join4(dirname4(context.target.input), recipe.output);
          const output2 = Deno.readTextFileSync(outputFile5);
          const outputMd = partitionYamlFrontMatter(
            Deno.readTextFileSync(outputFile5)
          );
          const yaml = parse3(
            inputMd.yaml.replace(/^---+\n/m, "").replace(/\n---+\n*$/m, "\n")
          );
          delete yaml._quarto;
          const yamlString = `---
${stringify(yaml)}---
`;
          const markdown = outputMd?.markdown || output2;
          Deno.writeTextFileSync(
            outputFile5,
            yamlString + "\n\n" + markdown
          );
        }
      });
    }
    const deriveAutoOutput = () => {
      let output2 = inputStem + "." + ext;
      if (extname4(input) === ".md" && ext === "md") {
        output2 = `${inputStem}-${format14.identifier["base-format"]}.md`;
      }
      if (output2 === basename4(context.target.source)) {
        output2 = inputStem + `.${kOutExt}.` + ext;
      }
      updateOutput(output2);
    };
    if (!recipe.output) {
      deriveAutoOutput();
    } else if (recipe.output === kStdOut) {
      deriveAutoOutput();
      recipe.isOutputTransient = true;
      completeActions.push(() => {
        writeFileToStdout(join4(inputDir, recipe.output));
        safeRemoveSync(join4(inputDir, recipe.output));
      });
    } else if (!isAbsolute4(recipe.output)) {
      updateOutput(relative4(inputDir, recipe.output));
    } else {
      updateOutput(expandPath(recipe.output));
    }
    return recipe;
  }
}
var kOutExt = "out";

// command/render/render-files.ts
await init_render_contexts();
init_log();
init_lodash();
init_path();
init_render();
init_path2();
init_resources2();
init_yaml();
init_flags2();

// command/render/freeze.ts
init_path();
init_fs();
init_render();
init_hash2();
init_path2();
init_constants6();
init_types4();
init_project_scratch();
init_copy5();
init_log();
var kProjectFreezeDir = "_freeze";
var kOldFreezeExecuteResults = "execute";
var kFreezeExecuteResults = "execute-results";
function freezeExecuteResult(input, output, result2) {
  const innerResult = {
    ...result2,
    includes: result2.includes ? { ...result2.includes } : void 0
  };
  const resolveIncludes = (name2) => {
    if (innerResult.includes) {
      if (innerResult.includes[name2]) {
        innerResult.includes[name2] = innerResult.includes[name2].map(
          (file) => (
            // Storing file content using LF line ending
            format3(Deno.readTextFileSync(file), LF)
          )
        );
      }
    }
  };
  resolveIncludes(kIncludeInHeader);
  resolveIncludes(kIncludeBeforeBody);
  resolveIncludes(kIncludeAfterBody);
  innerResult.supporting = innerResult.supporting.map((file) => {
    if (isAbsolute4(file)) {
      return relative4(normalizePath(dirname4(input)), file);
    } else {
      return file;
    }
  });
  const hash = freezeInputHash(input);
  const freezeJsonFile = freezeResultFile(input, output, true);
  Deno.writeTextFileSync(
    freezeJsonFile,
    JSON.stringify({ hash, result: innerResult }, void 0, 2)
  );
  return freezeJsonFile;
}
function defrostExecuteResult(source2, output, temp, force = false) {
  const resultFile = freezeResultFile(source2, output);
  if (existsSync2(resultFile)) {
    let hash;
    let result2;
    const contents = Deno.readTextFileSync(resultFile);
    try {
      const inp = JSON.parse(contents);
      hash = inp.hash;
      result2 = inp.result;
    } catch (_e) {
      if (contents.match("<<<<<<<") && contents.match(">>>>>>>") && contents.match("=======")) {
        warn(
          `Error parsing ${resultFile}; it looks possibly like a git merge conflict.`
        );
      } else {
        warn(`Error parsing ${resultFile}; it may be corrupt.`);
      }
      return;
    }
    if (force || hash === freezeInputHash(source2)) {
      result2.supporting = result2.supporting.map(
        (file) => join4(normalizePath(dirname4(source2)), file)
      );
      const resolveIncludes = (name2) => {
        if (result2.includes) {
          if (result2.includes[name2]) {
            result2.includes[name2] = result2.includes[name2].map((content) => {
              const includeFile = temp.createFile();
              content = format3(content, EOL);
              Deno.writeTextFileSync(includeFile, content);
              return includeFile;
            });
          }
        }
      };
      resolveIncludes(kIncludeInHeader);
      resolveIncludes(kIncludeBeforeBody);
      resolveIncludes(kIncludeAfterBody);
      return result2;
    }
  }
}
function projectFreezerDir(dir, hidden2) {
  const freezeDir = hidden2 ? projectScratchPath(dir, kProjectFreezeDir) : join4(dir, kProjectFreezeDir);
  ensureDirSync(freezeDir);
  return normalizePath(freezeDir);
}
function copyToProjectFreezer(project, file, hidden2, incremental) {
  const freezerDir = projectFreezerDir(project.dir, hidden2);
  const srcFilesDir = join4(project.dir, file);
  const destFilesDir = join4(freezerDir, asFreezerDir(file));
  if (incremental) {
    for (const dir of Deno.readDirSync(srcFilesDir)) {
      if (dir.name === kFreezeExecuteResults) {
        const resultsDir = join4(srcFilesDir, dir.name);
        const destResultsDir = join4(destFilesDir, kFreezeExecuteResults);
        ensureDirSync(destResultsDir);
        for (const json3 of Deno.readDirSync(resultsDir)) {
          if (json3.isFile) {
            copyTo(
              join4(resultsDir, json3.name),
              join4(destResultsDir, json3.name)
            );
          }
        }
      } else {
        copyMinimal(
          join4(srcFilesDir, dir.name),
          join4(destFilesDir, dir.name)
        );
      }
    }
  } else {
    copyMinimal(srcFilesDir, destFilesDir);
  }
}
function copyFromProjectFreezer(project, file, hidden2) {
  const freezerDir = projectFreezerDir(project.dir, hidden2);
  const srcFilesDir = join4(
    freezerDir,
    asFreezerDir(file)
  );
  const destFilesDir = join4(project.dir, file);
  if (existsSync2(srcFilesDir)) {
    copyMinimal(srcFilesDir, destFilesDir);
  }
}
function pruneProjectFreezerDir(project, dir, files, hidden2) {
  const freezerDir = projectFreezerDir(project.dir, hidden2);
  files.map((file) => {
    const filePath = join4(freezerDir, dir, file);
    safeRemoveIfExists(filePath);
  });
  removeIfEmptyDir(join4(freezerDir, dir));
}
function pruneProjectFreezer(project, hidden2) {
  const freezerDir = projectFreezerDir(project.dir, hidden2);
  const libDir = project.config?.project[kProjectLibDir];
  if (libDir) {
    let remove = true;
    for (const entry of Deno.readDirSync(freezerDir)) {
      if (entry.isFile || entry.name !== libDir) {
        remove = false;
        break;
      }
    }
    if (remove) {
      removeIfExists(freezerDir);
    }
  } else {
    removeIfEmptyDir(freezerDir);
  }
}
function freezerFreezeFile(project, freezeFile) {
  const filesDir = asFreezerDir(dirname4(dirname4(freezeFile)));
  return join4(
    project.dir,
    kProjectFreezeDir,
    filesDir,
    kFreezeExecuteResults,
    basename4(freezeFile)
  );
}
function freezerFigsDir(project, filesDir, figsDir) {
  return join4(
    project.dir,
    kProjectFreezeDir,
    asFreezerDir(filesDir),
    figsDir
  );
}
function freezeResultFile(input, output, ensureDir3 = false) {
  const filesDir = join4(dirname4(input), inputFilesDir(input));
  const freezeDir = join4(filesDir, kFreezeExecuteResults);
  if (ensureDir3) {
    ensureDirSync(freezeDir);
  }
  return join4(freezeDir, extname4(output).slice(1) + ".json");
}
function removeFreezeResults(filesDir) {
  const freezeDir = join4(filesDir, kFreezeExecuteResults);
  removeIfExists(freezeDir);
  const oldFreezeDir = join4(filesDir, kOldFreezeExecuteResults);
  removeIfExists(oldFreezeDir);
  if (existsSync2(filesDir)) {
    removeIfEmptyDir(filesDir);
  }
}
function freezeInputHash(input) {
  return md5HashSync(format3(Deno.readTextFileSync(input), LF));
}
function asFreezerDir(dir) {
  return dir.replace(/_files$/, "");
}

// command/render/render-files.ts
init_jupyter();
init_lifetimes();
init_timing();
init_mod6();
init_quarto();
await init_project_shared();

// execute/environment.ts
init_path();
init_error2();
init_path();
var setExecuteEnvironment = (options) => {
  if (options.projectDir) {
    Deno.env.set("QUARTO_PROJECT_ROOT", options.projectDir);
    Deno.env.set("QUARTO_DOCUMENT_PATH", dirname4(options.target.source));
    Deno.env.set("QUARTO_DOCUMENT_FILE", basename4(options.target.source));
  } else {
    if (!options.cwd) {
      throw new InternalError(
        "No project directory or current working directory"
      );
    }
    Deno.env.set("QUARTO_PROJECT_ROOT", options.cwd);
    Deno.env.set("QUARTO_DOCUMENT_PATH", options.cwd);
    Deno.env.set("QUARTO_DOCUMENT_FILE", basename4(options.target.source));
  }
  const executeInfo = {
    "document-path": resolve4(options.target.source),
    format: options.format
  };
  Deno.env.set(
    "QUARTO_EXECUTE_INFO",
    options.project.temp.createFileFromString(JSON.stringify(executeInfo))
  );
};

// command/render/render-files.ts
init_safe_clone_deep();
init_mod();
async function renderExecute(context, output, options) {
  const versionConstraint = context.format.metadata[kQuartoRequired];
  if (versionConstraint) {
    const ourVersion = quartoConfig.version();
    let result2;
    try {
      result2 = satisfies(ourVersion, versionConstraint);
    } catch (_e) {
      throw new Error(
        `In file ${context.target.source}:
Version constraint is invalid: ${versionConstraint}.`
      );
    }
    if (!result2) {
      throw new Error(
        `in file ${context.target.source}:
Quarto version ${ourVersion} does not satisfy version constraint ${versionConstraint}.`
      );
    }
  }
  const { resolveDependencies: resolveDependencies2 = true, alwaysExecute = false } = options;
  const flags = context.options.flags || {};
  const filesDir = inputFilesDir(context.target.source);
  let projRelativeFilesDir;
  if (context.project) {
    const inputDir = relative4(
      context.project.dir,
      dirname4(context.target.source)
    );
    projRelativeFilesDir = join4(inputDir, filesDir);
  }
  const canFreeze = context.engine.canFreeze && context.format.execute[kExecuteEnabled] !== false;
  if (context.project && !context.project.isSingleFile && !alwaysExecute) {
    const thaw = canFreeze && (context.format.execute[kFreeze] || (context.options.useFreezer ? "auto" : false));
    if (thaw) {
      const hidden2 = context.format.execute[kFreeze] === false;
      copyFromProjectFreezer(
        context.project,
        projRelativeFilesDir,
        hidden2
      );
      const thawedResult = defrostExecuteResult(
        context.target.source,
        output,
        context.options.services.temp,
        thaw === true
      );
      if (thawedResult) {
        const libDir = context.project?.config?.project[kProjectLibDir];
        if (libDir) {
          copyFromProjectFreezer(context.project, libDir, hidden2);
        }
        removeFreezeResults(join4(context.project.dir, projRelativeFilesDir));
        if (context.engine.executeTargetSkipped) {
          context.engine.executeTargetSkipped(
            context.target,
            context.format
          );
        }
        return thawedResult;
      }
    }
  }
  const figsDir = join4(filesDir, figuresDir(context.format.pandoc.to));
  push("render-execute");
  const executeOptions = {
    target: context.target,
    resourceDir: resourcePath(),
    tempDir: context.options.services.temp.createDir(),
    dependencies: resolveDependencies2,
    libDir: context.libDir,
    format: context.format,
    projectDir: context.project?.dir,
    cwd: flags.executeDir || dirname4(normalizePath(context.target.source)),
    params: resolveParams(flags.params, flags.paramsFile),
    quiet: flags.quiet,
    previewServer: context.options.previewServer,
    handledLanguages: languages(),
    project: context.project
  };
  setExecuteEnvironment(executeOptions);
  const executeResult = await context.engine.execute(executeOptions);
  pop();
  if (context.project && !context.project.isSingleFile && canFreeze) {
    const freezeFile = freezeExecuteResult(
      context.target.source,
      output,
      executeResult
    );
    copyToProjectFreezer(context.project, projRelativeFilesDir, true, true);
    if (context.format.execute[kFreeze] !== false) {
      copyToProjectFreezer(context.project, projRelativeFilesDir, false, true);
    } else {
      const freezeFigsDir = freezerFigsDir(
        context.project,
        projRelativeFilesDir,
        basename4(figsDir)
      );
      removeIfExists(freezeFigsDir);
      const projRelativeFreezeFile = relative4(context.project.dir, freezeFile);
      const freezerFile = freezerFreezeFile(
        context.project,
        projRelativeFreezeFile
      );
      removeIfExists(freezerFile);
      removeIfEmptyDir(dirname4(freezerFile));
      removeIfEmptyDir(dirname4(freezeFigsDir));
      removeIfEmptyDir(join4(context.project.dir, kProjectFreezeDir));
    }
    removeFreezeResults(join4(context.project.dir, projRelativeFilesDir));
  }
  return executeResult;
}
async function renderFiles(files, options, notebookContext2, alwaysExecuteFiles, pandocRenderer, project) {
  pandocRenderer = pandocRenderer || defaultPandocRenderer(options, project);
  const tempContext2 = createTempContext();
  try {
    options = cloneDeep(options);
    const progress = options.progress || project && files.length > 1 && !options.flags?.quiet;
    const pandocQuiet = !!progress || !!options.quietPandoc;
    const numWidth = String(files.length).length;
    for (let i6 = 0; i6 < files.length; i6++) {
      const file = files[i6];
      if (progress) {
        renderProgress(
          `\r[${String(i6 + 1).padStart(numWidth)}/${files.length}] ${relative4(project.dir, file.path)}`
        );
      }
      const fileLifetime = await waitUntilNamedLifetime("render-file");
      try {
        await renderFileInternal(
          fileLifetime,
          file,
          options,
          project,
          pandocRenderer,
          files,
          tempContext2,
          alwaysExecuteFiles,
          pandocQuiet,
          notebookContext2
        );
      } finally {
        fileLifetime.cleanup();
      }
    }
    if (progress) {
      info("");
    }
    return await pandocRenderer.onComplete(false, options.flags?.quiet);
  } catch (error2) {
    if (!(error2 instanceof Error)) {
      warn(`Error encountered when rendering files`);
    }
    return {
      files: (await pandocRenderer.onComplete(true)).files,
      error: error2 instanceof Error ? error2 : new Error(error2 ? String(error2) : void 0)
    };
  } finally {
    tempContext2.cleanup();
    if (Deno.env.get("QUARTO_PROFILER_OUTPUT")) {
      Deno.writeTextFileSync(
        Deno.env.get("QUARTO_PROFILER_OUTPUT"),
        JSON.stringify(getData())
      );
    }
  }
}
async function renderFile(file, options, services, project, enforceProjectFormats = true) {
  const pandocRenderer = defaultPandocRenderer(options, project);
  try {
    options = cloneDeep(options);
    const pandocQuiet = !!options.quietPandoc;
    const fileLifetime = createNamedLifetime("render-single-file");
    try {
      await renderFileInternal(
        fileLifetime,
        file,
        options,
        project,
        pandocRenderer,
        [file],
        services.temp,
        [],
        pandocQuiet,
        services.notebook,
        enforceProjectFormats
      );
    } finally {
      fileLifetime.cleanup();
    }
    return await pandocRenderer.onComplete(false, options.flags?.quiet);
  } catch (error2) {
    if (!(error2 instanceof Error)) {
      warn(`Error encountered when rendering ${file.path}`);
    }
    return {
      files: (await pandocRenderer.onComplete(true)).files,
      error: error2 instanceof Error ? error2 : new Error(error2 ? String(error2) : void 0)
    };
  } finally {
    if (Deno.env.get("QUARTO_PROFILER_OUTPUT")) {
      Deno.writeTextFileSync(
        Deno.env.get("QUARTO_PROFILER_OUTPUT"),
        JSON.stringify(getData())
      );
    }
  }
}
async function renderFileInternal(lifetime, file, options, project, pandocRenderer, files, tempContext2, alwaysExecuteFiles, pandocQuiet, notebookContext2, enforceProjectFormats = true) {
  const outputs = [];
  let contexts;
  try {
    contexts = await renderContexts(
      file,
      options,
      true,
      notebookContext2,
      project,
      false,
      enforceProjectFormats
    );
    contexts = pandocRenderer.onFilterContexts(
      file.path,
      contexts,
      files,
      options
    );
  } catch (e5) {
    const { engine, target } = await fileExecutionEngineAndTarget(
      file.path,
      options.flags,
      project
    );
    const validationResult = await validateDocumentFromSource(
      target.markdown,
      engine.name,
      error
    );
    if (validationResult.length) {
      throw new RenderInvalidYAMLError();
    } else {
      throw e5;
    }
  }
  const mergeHandlerResults = (results, executeResult, context) => {
    if (results === void 0) {
      return;
    }
    if (executeResult.includes) {
      executeResult.includes = mergeConfigs(
        executeResult.includes,
        results.includes
      );
    } else {
      executeResult.includes = results.includes;
    }
    const extras = resolveDependencies(
      results.extras,
      dirname4(context.target.source),
      context.libDir,
      tempContext2,
      project
    );
    if (extras[kIncludeInHeader]) {
      executeResult.includes[kIncludeInHeader] = [
        ...extras[kIncludeInHeader] || [],
        ...executeResult.includes[kIncludeInHeader] || []
      ];
    }
    executeResult.supporting.push(...results.supporting);
  };
  for (const format14 of Object.keys(contexts)) {
    push("render-context");
    const context = safeCloneDeep(contexts[format14]);
    if (isServerShiny(context.format) && context.project) {
      const src2 = relative4(context.project?.dir, context.target.source);
      if (projectIsWebsite(context.project)) {
        error(
          `${src2} uses server: shiny so cannot be included in a website project (shiny documents require a backend server and so can't be published as static web content).`
        );
        throw new Error();
      } else if (projectOutputDir(context.project) !== normalizePath(context.project.dir) && isServerShinyKnitr(context.format, context.engine.name)) {
        error(
          `${src2} is a knitr engine document that uses server: shiny so cannot be included in a project with an output-dir (shiny document output must be rendered alongside its source document).`
        );
        throw new Error();
      }
    }
    const recipe = outputRecipe(context);
    outputs.push({
      path: recipe.finalOutput || recipe.output,
      isTransient: recipe.isOutputTransient,
      format: context.format
    });
    if (context.active) {
      initDayJsPlugins();
      const resolveLang = () => {
        const lang = context.format.metadata[kLang] || options.flags?.pandocMetadata?.[kLang];
        if (typeof lang === "string") {
          return lang;
        } else {
          return void 0;
        }
      };
      const dateFormatLang = resolveLang();
      if (dateFormatLang) {
        await setDateLocale(
          dateFormatLang
        );
      }
      lifetime.attach({
        cleanup() {
          resetFigureCounter();
        }
      });
      try {
        if (isHtmlCompatible(context.format)) {
          await initDenoDom();
        }
        const executeOptions = mergeConfigs(
          {
            alwaysExecute: alwaysExecuteFiles?.includes(file.path)
          },
          pandocRenderer.onBeforeExecute(recipe.format)
        );
        const validate2 = context.format.render?.["validate-yaml"];
        if (validate2 !== false) {
          const validationResult = await validateDocument(context);
          if (validationResult.length) {
            throw new RenderInvalidYAMLError();
          }
        }
        const { ojsBlockLineNumbers } = annotateOjsLineNumbers(context);
        const baseExecuteResult = await renderExecute(
          context,
          recipe.output,
          executeOptions
        );
        let mappedMarkdown;
        withTiming("diff-execute-result", () => {
          if (!isJupyterNotebook(context.target.source)) {
            mappedMarkdown = mappedDiff(
              context.target.markdown,
              baseExecuteResult.markdown
            );
          } else {
            mappedMarkdown = asMappedString(baseExecuteResult.markdown);
          }
        });
        const resourceFiles = [];
        if (baseExecuteResult.resourceFiles) {
          resourceFiles.push(...baseExecuteResult.resourceFiles);
        }
        const languageCellHandlerOptions = {
          name: "",
          temp: tempContext2,
          format: recipe.format,
          markdown: mappedMarkdown,
          context,
          flags: options.flags || {},
          stage: "post-engine"
        };
        let unmappedExecuteResult;
        await withTimingAsync("handle-language-cells", async () => {
          const { markdown, results } = await handleLanguageCells(
            languageCellHandlerOptions
          );
          const mappedExecuteResult = {
            ...baseExecuteResult,
            markdown
          };
          mergeHandlerResults(
            context.target.preEngineExecuteResults,
            mappedExecuteResult,
            context
          );
          mergeHandlerResults(results, mappedExecuteResult, context);
          const { executeResult, resourceFiles: ojsResourceFiles } = await ojsExecuteResult(
            context,
            mappedExecuteResult,
            ojsBlockLineNumbers
          );
          resourceFiles.push(...ojsResourceFiles);
          const keepMd = executionEngineKeepMd(context);
          if (keepMd && context.format.execute[kKeepMd]) {
            Deno.writeTextFileSync(keepMd, executeResult.markdown.value);
          }
          unmappedExecuteResult = {
            ...executeResult,
            markdown: executeResult.markdown.value
          };
        });
        await ensureNotebookContext(
          unmappedExecuteResult.markdown,
          context.options.services,
          project
        );
        push("render-pandoc");
        await pandocRenderer.onRender(format14, {
          context,
          recipe,
          executeResult: unmappedExecuteResult,
          resourceFiles
        }, pandocQuiet);
        pop();
      } finally {
        pop();
      }
    }
  }
  await pandocRenderer.onPostProcess(outputs, project);
}
function defaultPandocRenderer(_options, _project) {
  const renderCompletions = [];
  const renderedFiles = [];
  return {
    onFilterContexts: (_file, contexts, _files, _options2) => {
      return contexts;
    },
    onBeforeExecute: (_format5) => ({}),
    onRender: async (_format5, executedFile, quiet) => {
      renderCompletions.push(await renderPandoc(executedFile, quiet));
    },
    onPostProcess: async (renderedFormats) => {
      let completion = renderCompletions.pop();
      while (completion) {
        renderedFiles.push(await completion.complete(renderedFormats));
        completion = renderCompletions.pop();
      }
      renderedFiles.reverse();
    },
    onComplete: async () => {
      return {
        files: await Promise.resolve(renderedFiles)
      };
    }
  };
}
var RenderInvalidYAMLError = class extends YAMLValidationError {
  constructor() {
    super("Render failed due to invalid YAML.");
  }
};

// command/render/project.ts
init_render();
init_path2();

// core/run/run.ts
var kRunHandlers = [];
function installRunHandler(handler) {
  kRunHandlers.push(handler);
}
function handlerForScript(script) {
  return kRunHandlers.find((handler) => handler.canHandle(script));
}

// command/render/project.ts
init_process();

// core/run/shell.ts
function parseShellRunCommand(cmdLine) {
  let space = "{{space}}";
  while (cmdLine.indexOf(space) > -1) {
    space += "&";
  }
  const noSpaces = cmdLine.replace(
    /"([^"]*)"?/g,
    (_3, capture) => {
      return capture.replace(/ /g, space);
    }
  );
  const paramArray = noSpaces.split(/ +/);
  return paramArray.map((mangled) => {
    return mangled.replace(RegExp(space, "g"), " ");
  });
}

// command/render/project.ts
await init_project_shared();
init_array();
init_path2();
init_fs();
await init_engine();
await init_project_context();
var noMutationValidations = (projType, projOutputDir, projDir) => {
  return [{
    val: projType,
    newVal: (context) => {
      return projectType(context.config?.project?.[kProjectType]);
    },
    msg: "The project type may not be mutated by the pre-render script"
  }, {
    val: projOutputDir,
    newVal: (context) => {
      return projectOutputDir(context);
    },
    msg: "The project output-dir may not be mutated by the pre-render script"
  }, {
    val: projDir,
    newVal: (context) => {
      return normalizePath(context.dir);
    },
    msg: "The project dir may not be mutated by the pre-render script"
  }];
};
var computeProjectRenderConfig = async (inputs) => {
  const incremental = !!inputs.files;
  let alwaysExecuteFiles = incremental && !inputs.options.useFreezer ? [...inputs.files] : void 0;
  const normalizeFiles = (targetFiles) => {
    return targetFiles.map((file) => {
      const target = isAbsolute4(file) ? file : join4(Deno.cwd(), file);
      if (!existsSync2(target)) {
        throw new Error("Render target does not exist: " + file);
      }
      return normalizePath(target);
    });
  };
  if (inputs.files) {
    if (alwaysExecuteFiles) {
      alwaysExecuteFiles = normalizeFiles(alwaysExecuteFiles);
      inputs.files = normalizeFiles(inputs.files);
    } else if (inputs.options.useFreezer) {
      inputs.files = normalizeFiles(inputs.files);
    }
  }
  if (inputs.files && alwaysExecuteFiles && inputs.projType.incrementalRenderAll && await inputs.projType.incrementalRenderAll(
    inputs.context,
    inputs.options,
    inputs.files
  )) {
    inputs.files = inputs.context.files.input;
    inputs.options = { ...inputs.options, useFreezer: true };
  }
  const renderAll = !inputs.files || inputs.files.length === inputs.context.files.input.length;
  inputs.files = inputs.files || inputs.context.files.input;
  const filesToRender = inputs.files.map((file) => {
    return { path: file };
  });
  const projectSupplement = (filesToRender2) => {
    if (inputs.projType.supplementRender && !inputs.options.devServerReload) {
      return inputs.projType.supplementRender(
        inputs.context,
        filesToRender2,
        incremental
      );
    } else {
      return { files: [] };
    }
  };
  const supplements = projectSupplement(filesToRender);
  filesToRender.push(...supplements.files);
  return {
    alwaysExecuteFiles,
    filesToRender,
    options: inputs.options,
    supplements,
    behavior: {
      renderAll,
      incremental
    }
  };
};
var getProjectRenderScripts = async (context) => {
  const preRenderScripts = [], postRenderScripts = [];
  if (context.config?.project?.[kProjectPreRender]) {
    preRenderScripts.push(
      ...asArray(context.config?.project?.[kProjectPreRender])
    );
  }
  if (context.config?.project?.[kProjectPostRender]) {
    postRenderScripts.push(
      ...asArray(context.config?.project?.[kProjectPostRender])
    );
  }
  return { preRenderScripts, postRenderScripts };
};
async function renderProject(context, pOptions, pFiles) {
  const { preRenderScripts, postRenderScripts } = await getProjectRenderScripts(
    context
  );
  const projType = projectType(context.config?.project?.[kProjectType]);
  const projOutputDir = projectOutputDir(context);
  const projDir = normalizePath(context.dir);
  let projectRenderConfig = await computeProjectRenderConfig({
    context,
    projType,
    projOutputDir,
    projDir,
    options: pOptions,
    files: pFiles
  });
  await ensureGitignore(context.dir);
  const progress = !!projectRenderConfig.options.progress || projectRenderConfig.filesToRender.length > 1;
  if (projectRenderConfig.behavior.renderAll && hasProjectOutputDir(context) && (projectRenderConfig.options.forceClean || projectRenderConfig.options.flags?.clean == true && projType.cleanOutputDir === true)) {
    const realProjectDir = normalizePath(context.dir);
    if (existsSync2(projOutputDir)) {
      const realOutputDir = normalizePath(projOutputDir);
      try {
        safeRemoveDirSync(realOutputDir, realProjectDir);
      } catch (e5) {
        if (!(e5 instanceof UnsafeRemovalError)) {
          throw e5;
        }
      }
    }
    clearProjectIndex(realProjectDir);
  }
  const prePostEnv = {
    "QUARTO_PROJECT_OUTPUT_DIR": projOutputDir,
    ...projectRenderConfig.behavior.renderAll ? { QUARTO_PROJECT_RENDER_ALL: "1" } : {}
  };
  if (preRenderScripts.length) {
    const filesToRender = projectRenderConfig.filesToRender.map((fileToRender) => fileToRender.path).map((file) => relative4(projDir, file));
    const env2 = {
      ...prePostEnv
    };
    if (Deno.env.get("QUARTO_USE_FILE_FOR_PROJECT_INPUT_FILES")) {
      Deno.writeTextFileSync(
        Deno.env.get("QUARTO_USE_FILE_FOR_PROJECT_INPUT_FILES"),
        filesToRender.join("\n")
      );
    } else {
      env2.QUARTO_PROJECT_INPUT_FILES = filesToRender.join("\n");
    }
    await runPreRender(
      projDir,
      preRenderScripts,
      progress,
      !!projectRenderConfig.options.flags?.quiet,
      env2
    );
    context = await projectContextForDirectory(
      context.dir,
      context.notebookContext,
      projectRenderConfig.options
    );
    noMutationValidations(projType, projOutputDir, projDir).some(
      (validation) => {
        if (!isEqual(validation.newVal(context), validation.val)) {
          throw new Error(
            `Pre-render script resulted in a project change that is now allowed.
${validation.msg}`
          );
        }
      }
    );
    projectRenderConfig = await computeProjectRenderConfig({
      context,
      projType,
      projOutputDir,
      projDir,
      options: pOptions,
      files: pFiles
    });
  }
  if (projType.preRender) {
    await projType.preRender(context);
  }
  const executeDir = context.config?.project?.[kProjectExecuteDir];
  if (projectRenderConfig.options.flags?.executeDir === void 0 && executeDir === "project") {
    projectRenderConfig.options = {
      ...projectRenderConfig.options,
      flags: {
        ...projectRenderConfig.options.flags,
        executeDir: projDir
      }
    };
  }
  if (projectRenderConfig.filesToRender.length > 3 && projectRenderConfig.options.flags && projectRenderConfig.options.flags.executeDaemon === void 0) {
    projectRenderConfig.options.flags.executeDaemon = 0;
  }
  const projResults = {
    context,
    baseDir: projDir,
    outputDir: relative4(projDir, projOutputDir),
    files: []
  };
  const outputDir = projResults.outputDir;
  const outputDirAbsolute = outputDir ? join4(projDir, outputDir) : void 0;
  if (outputDirAbsolute) {
    ensureDirSync(outputDirAbsolute);
  }
  const libDir = context.config?.project[kProjectLibDir];
  const resourcesFrom = async (file) => {
    const partitioned = await partitionedMarkdownForInput(
      context,
      file.input
    );
    const excludeDirs = context ? projectExcludeDirs(context) : [];
    const resourceFiles = resourceFilesFromRenderedFile(
      projDir,
      excludeDirs,
      file,
      partitioned
    );
    return resourceFiles;
  };
  const fileResults = await renderFiles(
    projectRenderConfig.filesToRender,
    projectRenderConfig.options,
    context.notebookContext,
    projectRenderConfig.alwaysExecuteFiles,
    projType?.pandocRenderer ? projType.pandocRenderer(projectRenderConfig.options, context) : void 0,
    context
  );
  const directoryRelocator = (destinationDir) => {
    return (dir, copy6 = false) => {
      const targetDir = join4(destinationDir, dir);
      const srcDir = join4(projDir, dir);
      if (!existsSync2(srcDir)) {
        return;
      }
      if (existsSync2(targetDir)) {
        try {
          safeRemoveDirSync(targetDir, context.dir);
        } catch (e5) {
          if (e5 instanceof UnsafeRemovalError) {
            warn(
              `Refusing to remove directory ${targetDir} since it is not a subdirectory of the main project directory.`
            );
            warn(
              `Quarto did not expect the path configuration being used in this project, and strange behavior may result.`
            );
          }
        }
      }
      ensureDirSync(dirname4(targetDir));
      if (copy6) {
        copyTo(srcDir, targetDir);
      } else {
        try {
          Deno.renameSync(srcDir, targetDir);
        } catch (_e) {
          copyTo(srcDir, targetDir);
          safeRemoveDirSync(srcDir, context.dir);
        }
      }
    };
  };
  let moveOutputResult;
  if (outputDirAbsolute) {
    let keepLibsDir = false;
    const fileOperations = [];
    for (let i6 = 0; i6 < fileResults.files.length; i6++) {
      const renderedFile = fileResults.files[i6];
      const formatOutputDir = projectFormatOutputDir(
        renderedFile.format,
        context,
        projectType(context.config?.project.type)
      );
      const formatRelocateDir = directoryRelocator(formatOutputDir);
      const moveFormatDir = formatRelocateDir;
      const copyFormatDir = (dir) => formatRelocateDir(dir, true);
      if (!renderedFile.isTransient) {
        const outputFile5 = join4(formatOutputDir, renderedFile.file);
        ensureDirSync(dirname4(outputFile5));
        safeMoveSync(join4(projDir, renderedFile.file), outputFile5);
      }
      const keepFiles = !!renderedFile.format.execute[kKeepMd] || !!renderedFile.format.render[kKeepTex] || !!renderedFile.format.render[kKeepTyp];
      keepLibsDir = keepLibsDir || keepFiles;
      if (renderedFile.supporting) {
        renderedFile.supporting = renderedFile.supporting.filter(
          (file) => file !== libDir
        );
        renderedFile.supporting = renderedFile.supporting.filter((file) => {
          return !renderedFile.supporting.some(
            (dir) => file.startsWith(dir) && file !== dir
          );
        });
        if (keepFiles) {
          renderedFile.supporting.forEach((file) => {
            fileOperations.push({
              key: `${file}|copy`,
              src: file,
              performOperation: () => {
                copyFormatDir(file);
              }
            });
          });
        } else {
          renderedFile.supporting.forEach((file) => {
            fileOperations.push({
              key: `${file}|move`,
              src: file,
              performOperation: () => {
                moveFormatDir(file);
                removeIfEmptyDir(dirname4(file));
              }
            });
          });
        }
      }
      if (!keepFiles) {
        const filesDir = join4(
          projDir,
          dirname4(renderedFile.file),
          inputFilesDir(renderedFile.file)
        );
        removeIfEmptyDir(filesDir);
      }
      projResults.files.push({
        isTransient: renderedFile.isTransient,
        input: renderedFile.input,
        markdown: renderedFile.markdown,
        format: renderedFile.format,
        file: renderedFile.file,
        supporting: renderedFile.supporting,
        resourceFiles: await resourcesFrom(renderedFile)
      });
    }
    const uniqOps = uniqBy(fileOperations, (op) => {
      return op.key;
    });
    const sortedOperations = uniqOps.sort((a5, b3) => {
      if (a5.src === b3.src) {
        return 0;
      }
      if (isSubdir2(a5.src, b3.src)) {
        return -1;
      }
      return a5.src.localeCompare(b3.src);
    });
    if (projType.beforeMoveOutput) {
      moveOutputResult = await projType.beforeMoveOutput(
        context,
        projResults.files
      );
    }
    sortedOperations.forEach((op) => {
      op.performOperation();
    });
    if (libDir) {
      const libDirFull = join4(context.dir, libDir);
      if (existsSync2(libDirFull)) {
        const libsIncremental = !!(projectRenderConfig.behavior.incremental || projectRenderConfig.options.useFreezer);
        const formatLibDirs = projType.formatLibDirs ? projType.formatLibDirs() : [];
        const freezeLibDir = (hidden2) => {
          copyToProjectFreezer(context, libDir, hidden2, false);
          pruneProjectFreezerDir(context, libDir, formatLibDirs, hidden2);
          pruneProjectFreezer(context, hidden2);
        };
        freezeLibDir(true);
        if (existsSync2(join4(context.dir, kProjectFreezeDir))) {
          freezeLibDir(false);
        }
        if (libsIncremental) {
          for (const lib2 of Deno.readDirSync(libDirFull)) {
            if (lib2.isDirectory) {
              const copyDir3 = join4(libDir, lib2.name);
              const srcDir = join4(projDir, copyDir3);
              const targetDir = join4(outputDirAbsolute, copyDir3);
              copyMinimal(srcDir, targetDir);
              if (!keepLibsDir) {
                safeRemoveIfExists(srcDir);
              }
            }
          }
          if (!keepLibsDir) {
            safeRemoveIfExists(libDirFull);
          }
        } else {
          const relocateDir = directoryRelocator(outputDirAbsolute);
          if (keepLibsDir) {
            relocateDir(libDir, true);
          } else {
            relocateDir(libDir);
          }
        }
      }
    }
    const outputFiles = projResults.files.map(
      (result2) => join4(projDir, result2.file)
    );
    projResults.files.forEach((file) => {
      file.resourceFiles = file.resourceFiles.filter(
        (resource) => !outputFiles.includes(resource)
      );
    });
    const resourceFilesToCopy = {};
    const projectFormats = {};
    projResults.files.forEach((file) => {
      if (file.format.identifier[kTargetFormat] && projectFormats[file.format.identifier[kTargetFormat]] === void 0) {
        projectFormats[file.format.identifier[kTargetFormat]] = file.format;
      }
    });
    const isSelfContainedOutput2 = (format14) => {
      return projType.selfContainedOutput && projType.selfContainedOutput(format14);
    };
    Object.values(projectFormats).forEach((format14) => {
      if (isSelfContainedOutput2(format14)) {
        return;
      }
      const formatOutputDir = projectFormatOutputDir(
        format14,
        context,
        projType
      );
      context.files.resources?.forEach((resource) => {
        resourceFilesToCopy[resource] = resourceFilesToCopy[resource] || /* @__PURE__ */ new Set();
        const relativePath = relative4(context.dir, resource);
        resourceFilesToCopy[resource].add(
          join4(formatOutputDir, relativePath)
        );
      });
    });
    projResults.files.forEach((file) => {
      if (isSelfContainedOutput2(file.format)) {
        return;
      }
      const formatOutputDir = projectFormatOutputDir(
        file.format,
        context,
        projType
      );
      file.resourceFiles.forEach((file2) => {
        resourceFilesToCopy[file2] = resourceFilesToCopy[file2] || /* @__PURE__ */ new Set();
        const relativePath = relative4(projDir, file2);
        resourceFilesToCopy[file2].add(join4(formatOutputDir, relativePath));
      });
    });
    Object.keys(resourceFilesToCopy).forEach((srcPath) => {
      const destinationFiles = resourceFilesToCopy[srcPath];
      destinationFiles.forEach((destPath) => {
        if (existsSync2(srcPath)) {
          if (Deno.statSync(srcPath).isFile) {
            copyResourceFile(context.dir, srcPath, destPath);
          }
        } else if (!existsSync2(destPath)) {
          warn(`File '${srcPath}' was not found.`);
        }
      });
    });
  } else {
    for (const result2 of fileResults.files) {
      const resourceFiles = await resourcesFrom(result2);
      projResults.files.push({
        input: result2.input,
        markdown: result2.markdown,
        format: result2.format,
        file: result2.file,
        supporting: result2.supporting,
        resourceFiles
      });
    }
  }
  projResults.error = fileResults.error;
  if (!projResults.error) {
    for (const file of projResults.files) {
      const path3 = join4(context.dir, file.input);
      const engine = await fileExecutionEngine(
        path3,
        projectRenderConfig.options.flags,
        context
      );
      if (engine?.postRender) {
        await engine.postRender(file);
      }
    }
    const outputFiles = projResults.files.filter((x3) => !x3.isTransient).map((result2) => {
      const outputDir2 = projectFormatOutputDir(
        result2.format,
        context,
        projType
      );
      const file = outputDir2 ? join4(outputDir2, result2.file) : join4(projDir, result2.file);
      return {
        file,
        input: join4(projDir, result2.input),
        format: result2.format,
        resources: result2.resourceFiles,
        supporting: result2.supporting
      };
    });
    if (projType.postRender) {
      await projType.postRender(
        context,
        projectRenderConfig.behavior.incremental,
        outputFiles,
        moveOutputResult
      );
    }
    if (postRenderScripts.length) {
      const env2 = {
        ...prePostEnv
      };
      if (Deno.env.get("QUARTO_USE_FILE_FOR_PROJECT_OUTPUT_FILES")) {
        Deno.writeTextFileSync(
          Deno.env.get("QUARTO_USE_FILE_FOR_PROJECT_OUTPUT_FILES"),
          outputFiles.map((outputFile5) => relative4(projDir, outputFile5.file)).join("\n")
        );
      } else {
        env2.QUARTO_PROJECT_OUTPUT_FILES = outputFiles.map((outputFile5) => relative4(projDir, outputFile5.file)).join("\n");
      }
      await runPostRender(
        projDir,
        postRenderScripts,
        progress,
        !!projectRenderConfig.options.flags?.quiet,
        env2
      );
    }
  }
  const supplements = projectRenderConfig.supplements;
  projResults.files.forEach((file) => {
    if (supplements.files.find((supFile) => {
      return supFile.path === join4(projDir, file.input);
    })) {
      file.supplemental = true;
    }
  });
  const nonSupplementalFiles = projResults.files.filter(
    (file) => !file.supplemental
  ).map((file) => file.file);
  if (supplements.onRenderComplete) {
    await supplements.onRenderComplete(
      context,
      nonSupplementalFiles,
      projectRenderConfig.behavior.incremental
    );
  }
  if (projectRenderConfig.options.forceClean) {
    context.cleanup();
    const scratchDir = join4(projDir, kQuartoScratch);
    if (existsSync2(scratchDir)) {
      safeRemoveSync(scratchDir, { recursive: true });
    }
  }
  return projResults;
}
async function runPreRender(projDir, preRender, progress, quiet, env2) {
  await runScripts(projDir, preRender, progress, quiet, env2);
}
async function runPostRender(projDir, postRender, progress, quiet, env2) {
  await runScripts(projDir, postRender, progress, quiet, env2);
}
async function runScripts(projDir, scripts, progress, quiet, env2) {
  if (env2) {
    env2 = {
      ...env2
    };
  } else {
    env2 = {};
  }
  if (!env2) throw new Error("should never get here");
  env2["QUARTO_PROJECT_SCRIPT_PROGRESS"] = progress ? "1" : "0";
  env2["QUARTO_PROJECT_SCRIPT_QUIET"] = quiet ? "1" : "0";
  for (let i6 = 0; i6 < scripts.length; i6++) {
    const args = parseShellRunCommand(scripts[i6]);
    const script = args[0];
    if (progress && !quiet) {
      info(bold3(blue3(`Running script '${script}'`)));
    }
    const handler = handlerForScript(script) ?? {
      run: async (script2, args2, _stdin, options) => {
        return await execProcess({
          cmd: script2,
          args: args2,
          cwd: options?.cwd,
          stdout: options?.stdout,
          env: options?.env
        });
      }
    };
    const input = Deno.env.get("QUARTO_USE_FILE_FOR_PROJECT_INPUT_FILES");
    const output = Deno.env.get("QUARTO_USE_FILE_FOR_PROJECT_OUTPUT_FILES");
    if (input) {
      env2["QUARTO_USE_FILE_FOR_PROJECT_INPUT_FILES"] = input;
    }
    if (output) {
      env2["QUARTO_USE_FILE_FOR_PROJECT_OUTPUT_FILES"] = output;
    }
    const result2 = await handler.run(script, args.slice(1), void 0, {
      cwd: projDir,
      stdout: quiet ? "piped" : "inherit",
      env: env2
    });
    if (!result2.success) {
      throw new Error();
    }
  }
  if (scripts.length > 0) {
    info("");
  }
}

// command/render/render-shared.ts
await init_project_shared();

// core/lib/yaml-validation/state.ts
init_error2();
init_semaphore();
function makeInitializer(thunk) {
  let initStarted = false;
  const hasInitSemaphore = new Semaphore(0);
  return async () => {
    if (initStarted) {
      await hasInitSemaphore.runExclusive(async () => {
      });
      return;
    }
    initStarted = true;
    await thunk();
    hasInitSemaphore.release();
  };
}
var initializer = () => {
  throw new InternalError("initializer not set!!");
};
async function initState() {
  await initializer();
}
var hasSet = false;
function setInitializer(init5) {
  if (hasSet) {
    return;
  }
  initializer = makeInitializer(init5);
  hasSet = true;
}

// core/schema/utils.ts
init_path();
init_resources2();

// core/schema/deno-init-tree-sitter.ts
init_resources2();

// core/lib/external/tree-sitter-deno.js
var Module = {};
var wasmBinaryFile;
var wasmInstantiateResolve;
var wasmInstantiatePromise = new Promise((resolve16, reject2) => {
  wasmInstantiateResolve = resolve16;
});
function setWasmBinaryFile(wbf) {
  wasmBinaryFile = wbf;
}
var init4 = false;
var TreeSitter = /* @__PURE__ */ (function() {
  var initPromise;
  class Parser6 {
    constructor() {
      this.initialize();
    }
    initialize() {
      throw new Error("cannot construct a Parser before calling `init()`");
    }
    static async init(moduleOptions) {
      if (init4) return;
      Module = Object.assign({}, Module, moduleOptions);
      var moduleOverrides = {};
      var key;
      for (key in Module) {
        if (Module.hasOwnProperty(key)) {
          moduleOverrides[key] = Module[key];
        }
      }
      var arguments_ = [];
      var thisProgram = "./this.program";
      var quit_ = function(status, toThrow) {
        throw toThrow;
      };
      var ENVIRONMENT_IS_WEB = false;
      var ENVIRONMENT_IS_NODE = false;
      var ENVIRONMENT_IS_DENO = true;
      var scriptDirectory = "";
      var read_, readBinary, setWindowTitle;
      var nodeFS;
      var nodePath;
      if (ENVIRONMENT_IS_DENO) {
        read_ = function shell_read(filename, binary3) {
          var ret = tryParseAsDataURI(filename);
          if (ret) {
            return binary3 ? ret : ret.toString();
          }
          filename = Deno.realPathSync(filename);
          if (binary3) {
            return Deno.readFileSync(filename);
          } else {
            return Deno.readTextFileSync(filename);
          }
        };
        readBinary = function readBinary2(filename) {
          var ret = read_(filename, true);
          if (!ret.buffer) {
            ret = new Uint8Array(ret);
          }
          assert10(ret.buffer);
          return ret;
        };
        quit_ = function(status) {
          Deno.exit(status);
        };
        Module["inspect"] = function() {
          return "[Emscripten Module object]";
        };
      } else {
        throw new Error("environment detection error");
      }
      var out = Module["print"] || console.log.bind(console);
      var err2 = Module["printErr"] || console.warn.bind(console);
      for (key in moduleOverrides) {
        if (moduleOverrides.hasOwnProperty(key)) {
          Module[key] = moduleOverrides[key];
        }
      }
      moduleOverrides = null;
      var STACK_ALIGN = 16;
      function alignMemory(size, factor) {
        if (!factor) factor = STACK_ALIGN;
        return Math.ceil(size / factor) * factor;
      }
      function getNativeTypeSize(type4) {
        switch (type4) {
          case "i1":
          case "i8":
            return 1;
          case "i16":
            return 2;
          case "i32":
            return 4;
          case "i64":
            return 8;
          case "float":
            return 4;
          case "double":
            return 8;
          default: {
            if (type4[type4.length - 1] === "*") {
              return 4;
            } else if (type4[0] === "i") {
              var bits = Number(type4.substr(1));
              assert10(bits % 8 === 0, "getNativeTypeSize invalid bits " + bits + ", type " + type4);
              return bits / 8;
            } else {
              return 0;
            }
          }
        }
      }
      function warnOnce2(text) {
        if (!warnOnce2.shown) warnOnce2.shown = {};
        if (!warnOnce2.shown[text]) {
          warnOnce2.shown[text] = 1;
          err2(text);
        }
      }
      function convertJsFunctionToWasm(func, sig) {
        if (typeof WebAssembly.Function === "function") {
          var typeNames = {
            "i": "i32",
            "j": "i64",
            "f": "f32",
            "d": "f64"
          };
          var type4 = {
            parameters: [],
            results: sig[0] == "v" ? [] : [typeNames[sig[0]]]
          };
          for (var i6 = 1; i6 < sig.length; ++i6) {
            type4.parameters.push(typeNames[sig[i6]]);
          }
          return new WebAssembly.Function(type4, func);
        }
        var typeSection = [
          1,
          // id: section,
          0,
          // length: 0 (placeholder)
          1,
          // count: 1
          96
          // form: func
        ];
        var sigRet = sig.slice(0, 1);
        var sigParam = sig.slice(1);
        var typeCodes = {
          "i": 127,
          // i32
          "j": 126,
          // i64
          "f": 125,
          // f32
          "d": 124
          // f64
        };
        typeSection.push(sigParam.length);
        for (var i6 = 0; i6 < sigParam.length; ++i6) {
          typeSection.push(typeCodes[sigParam[i6]]);
        }
        if (sigRet == "v") {
          typeSection.push(0);
        } else {
          typeSection = typeSection.concat([1, typeCodes[sigRet]]);
        }
        typeSection[1] = typeSection.length - 2;
        var bytes = new Uint8Array([
          0,
          97,
          115,
          109,
          // magic ("\0asm")
          1,
          0,
          0,
          0
          // version: 1
        ].concat(typeSection, [
          2,
          7,
          // import section
          // (import "e" "f" (func 0 (type 0)))
          1,
          1,
          101,
          1,
          102,
          0,
          0,
          7,
          5,
          // export section
          // (export "f" (func 0 (type 0)))
          1,
          1,
          102,
          0,
          0
        ]));
        var module2 = new WebAssembly.Module(bytes);
        var instance = new WebAssembly.Instance(module2, {
          "e": {
            "f": func
          }
        });
        var wrappedFunc = instance.exports["f"];
        return wrappedFunc;
      }
      var freeTableIndexes = [];
      var functionsInTableMap;
      function getEmptyTableSlot() {
        if (freeTableIndexes.length) {
          return freeTableIndexes.pop();
        }
        try {
          wasmTable.grow(1);
        } catch (err3) {
          if (!(err3 instanceof RangeError)) {
            throw err3;
          }
          throw "Unable to grow wasm table. Set ALLOW_TABLE_GROWTH.";
        }
        return wasmTable.length - 1;
      }
      function addFunctionWasm(func, sig) {
        if (!functionsInTableMap) {
          functionsInTableMap = /* @__PURE__ */ new WeakMap();
          for (var i6 = 0; i6 < wasmTable.length; i6++) {
            var item = wasmTable.get(i6);
            if (item) {
              functionsInTableMap.set(item, i6);
            }
          }
        }
        if (functionsInTableMap.has(func)) {
          return functionsInTableMap.get(func);
        }
        var ret = getEmptyTableSlot();
        try {
          wasmTable.set(ret, func);
        } catch (err3) {
          if (!(err3 instanceof TypeError)) {
            throw err3;
          }
          assert10(typeof sig !== "undefined", "Missing signature argument to addFunction: " + func);
          var wrapped = convertJsFunctionToWasm(func, sig);
          wasmTable.set(ret, wrapped);
        }
        functionsInTableMap.set(func, ret);
        return ret;
      }
      function removeFunction(index2) {
        functionsInTableMap.delete(wasmTable.get(index2));
        freeTableIndexes.push(index2);
      }
      function addFunction(func, sig) {
        assert10(typeof func !== "undefined");
        return addFunctionWasm(func, sig);
      }
      var tempRet0 = 0;
      var setTempRet0 = function(value) {
        tempRet0 = value;
      };
      var getTempRet0 = function() {
        return tempRet0;
      };
      var dynamicLibraries = Module["dynamicLibraries"] || [];
      var wasmBinary;
      if (typeof WebAssembly !== "object") {
        abort2("no native wasm support detected");
      }
      function setValue(ptr, value, type4, noSafe) {
        type4 = type4 || "i8";
        if (type4.charAt(type4.length - 1) === "*") type4 = "i32";
        switch (type4) {
          case "i1":
            HEAP8[ptr >> 0] = value;
            break;
          case "i8":
            HEAP8[ptr >> 0] = value;
            break;
          case "i16":
            HEAP16[ptr >> 1] = value;
            break;
          case "i32":
            HEAP32[ptr >> 2] = value;
            break;
          case "i64":
            tempI64 = [value >>> 0, (tempDouble = value, +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? (Math.min(+Math.floor(tempDouble / 4294967296), 4294967295) | 0) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)], HEAP32[ptr >> 2] = tempI64[0], HEAP32[ptr + 4 >> 2] = tempI64[1];
            break;
          case "float":
            HEAPF32[ptr >> 2] = value;
            break;
          case "double":
            HEAPF64[ptr >> 3] = value;
            break;
          default:
            abort2("invalid type for setValue: " + type4);
        }
      }
      function getValue(ptr, type4, noSafe) {
        type4 = type4 || "i8";
        if (type4.charAt(type4.length - 1) === "*") type4 = "i32";
        switch (type4) {
          case "i1":
            return HEAP8[ptr >> 0];
          case "i8":
            return HEAP8[ptr >> 0];
          case "i16":
            return HEAP16[ptr >> 1];
          case "i32":
            return HEAP32[ptr >> 2];
          case "i64":
            return HEAP32[ptr >> 2];
          case "float":
            return HEAPF32[ptr >> 2];
          case "double":
            return HEAPF64[ptr >> 3];
          default:
            abort2("invalid type for getValue: " + type4);
        }
        return null;
      }
      var wasmMemory;
      var ABORT = false;
      var EXITSTATUS;
      function assert10(condition, text) {
        if (!condition) {
          abort2("Assertion failed: " + text);
        }
      }
      function getCFunc(ident) {
        var func = Module["_" + ident];
        assert10(func, "Cannot call unknown function " + ident + ", make sure it is exported");
        return func;
      }
      function ccall(ident, returnType, argTypes, args, opts) {
        var toC = {
          "string": function(str3) {
            var ret2 = 0;
            if (str3 !== null && str3 !== void 0 && str3 !== 0) {
              var len = (str3.length << 2) + 1;
              ret2 = stackAlloc(len);
              stringToUTF8(str3, ret2, len);
            }
            return ret2;
          },
          "array": function(arr) {
            var ret2 = stackAlloc(arr.length);
            writeArrayToMemory(arr, ret2);
            return ret2;
          }
        };
        function convertReturnValue(ret2) {
          if (returnType === "string") return UTF8ToString(ret2);
          if (returnType === "boolean") return Boolean(ret2);
          return ret2;
        }
        var func = getCFunc(ident);
        var cArgs = [];
        var stack = 0;
        assert10(returnType !== "array", 'Return type should not be "array".');
        if (args) {
          for (var i6 = 0; i6 < args.length; i6++) {
            var converter = toC[argTypes[i6]];
            if (converter) {
              if (stack === 0) stack = stackSave();
              cArgs[i6] = converter(args[i6]);
            } else {
              cArgs[i6] = args[i6];
            }
          }
        }
        var ret = func.apply(null, cArgs);
        ret = convertReturnValue(ret);
        if (stack !== 0) stackRestore(stack);
        return ret;
      }
      function cwrap(ident, returnType, argTypes, opts) {
        return function() {
          return ccall(ident, returnType, argTypes, arguments, opts);
        };
      }
      var ALLOC_NORMAL = 0;
      var ALLOC_STACK = 1;
      function allocate(slab, allocator) {
        var ret;
        assert10(typeof allocator === "number", "allocate no longer takes a type argument");
        assert10(typeof slab !== "number", "allocate no longer takes a number as arg0");
        if (allocator == ALLOC_STACK) {
          ret = stackAlloc(slab.length);
        } else {
          ret = _malloc(slab.length);
        }
        if (slab.subarray || slab.slice) {
          HEAPU8.set(
            /** @type {!Uint8Array} */
            slab,
            ret
          );
        } else {
          HEAPU8.set(new Uint8Array(slab), ret);
        }
        return ret;
      }
      var UTF8Decoder = typeof TextDecoder !== "undefined" ? new TextDecoder("utf8") : void 0;
      function UTF8ArrayToString(heap3, idx, maxBytesToRead) {
        var endIdx = idx + maxBytesToRead;
        var endPtr = idx;
        while (heap3[endPtr] && !(endPtr >= endIdx)) ++endPtr;
        if (endPtr - idx > 16 && heap3.subarray && UTF8Decoder) {
          return UTF8Decoder.decode(heap3.subarray(idx, endPtr));
        } else {
          var str3 = "";
          while (idx < endPtr) {
            var u0 = heap3[idx++];
            if (!(u0 & 128)) {
              str3 += String.fromCharCode(u0);
              continue;
            }
            var u1 = heap3[idx++] & 63;
            if ((u0 & 224) == 192) {
              str3 += String.fromCharCode((u0 & 31) << 6 | u1);
              continue;
            }
            var u22 = heap3[idx++] & 63;
            if ((u0 & 240) == 224) {
              u0 = (u0 & 15) << 12 | u1 << 6 | u22;
            } else {
              if ((u0 & 248) != 240) warnOnce2("Invalid UTF-8 leading byte 0x" + u0.toString(16) + " encountered when deserializing a UTF-8 string in wasm memory to a JS string!");
              u0 = (u0 & 7) << 18 | u1 << 12 | u22 << 6 | heap3[idx++] & 63;
            }
            if (u0 < 65536) {
              str3 += String.fromCharCode(u0);
            } else {
              var ch = u0 - 65536;
              str3 += String.fromCharCode(55296 | ch >> 10, 56320 | ch & 1023);
            }
          }
        }
        return str3;
      }
      function UTF8ToString(ptr, maxBytesToRead) {
        return ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead) : "";
      }
      function stringToUTF8Array(str3, heap3, outIdx, maxBytesToWrite) {
        if (!(maxBytesToWrite > 0))
          return 0;
        var startIdx = outIdx;
        var endIdx = outIdx + maxBytesToWrite - 1;
        for (var i6 = 0; i6 < str3.length; ++i6) {
          var u5 = str3.charCodeAt(i6);
          if (u5 >= 55296 && u5 <= 57343) {
            var u1 = str3.charCodeAt(++i6);
            u5 = 65536 + ((u5 & 1023) << 10) | u1 & 1023;
          }
          if (u5 <= 127) {
            if (outIdx >= endIdx) break;
            heap3[outIdx++] = u5;
          } else if (u5 <= 2047) {
            if (outIdx + 1 >= endIdx) break;
            heap3[outIdx++] = 192 | u5 >> 6;
            heap3[outIdx++] = 128 | u5 & 63;
          } else if (u5 <= 65535) {
            if (outIdx + 2 >= endIdx) break;
            heap3[outIdx++] = 224 | u5 >> 12;
            heap3[outIdx++] = 128 | u5 >> 6 & 63;
            heap3[outIdx++] = 128 | u5 & 63;
          } else {
            if (outIdx + 3 >= endIdx) break;
            if (u5 >= 2097152) warnOnce2("Invalid Unicode code point 0x" + u5.toString(16) + " encountered when serializing a JS string to a UTF-8 string in wasm memory! (Valid unicode code points should be in range 0-0x1FFFFF).");
            heap3[outIdx++] = 240 | u5 >> 18;
            heap3[outIdx++] = 128 | u5 >> 12 & 63;
            heap3[outIdx++] = 128 | u5 >> 6 & 63;
            heap3[outIdx++] = 128 | u5 & 63;
          }
        }
        heap3[outIdx] = 0;
        return outIdx - startIdx;
      }
      function stringToUTF8(str3, outPtr, maxBytesToWrite) {
        assert10(typeof maxBytesToWrite == "number", "stringToUTF8(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!");
        return stringToUTF8Array(str3, HEAPU8, outPtr, maxBytesToWrite);
      }
      function lengthBytesUTF8(str3) {
        var len = 0;
        for (var i6 = 0; i6 < str3.length; ++i6) {
          var u5 = str3.charCodeAt(i6);
          if (u5 >= 55296 && u5 <= 57343) u5 = 65536 + ((u5 & 1023) << 10) | str3.charCodeAt(++i6) & 1023;
          if (u5 <= 127) ++len;
          else if (u5 <= 2047) len += 2;
          else if (u5 <= 65535) len += 3;
          else len += 4;
        }
        return len;
      }
      function AsciiToString(ptr) {
        var str3 = "";
        while (1) {
          var ch = HEAPU8[ptr++ >> 0];
          if (!ch) return str3;
          str3 += String.fromCharCode(ch);
        }
      }
      function stringToAscii(str3, outPtr) {
        return writeAsciiToMemory(str3, outPtr, false);
      }
      var UTF16Decoder = typeof TextDecoder !== "undefined" ? new TextDecoder("utf-16le") : void 0;
      function UTF16ToString(ptr, maxBytesToRead) {
        assert10(ptr % 2 == 0, "Pointer passed to UTF16ToString must be aligned to two bytes!");
        var endPtr = ptr;
        var idx = endPtr >> 1;
        var maxIdx = idx + maxBytesToRead / 2;
        while (!(idx >= maxIdx) && HEAPU16[idx]) ++idx;
        endPtr = idx << 1;
        if (endPtr - ptr > 32 && UTF16Decoder) {
          return UTF16Decoder.decode(HEAPU8.subarray(ptr, endPtr));
        } else {
          var str3 = "";
          for (var i6 = 0; !(i6 >= maxBytesToRead / 2); ++i6) {
            var codeUnit = HEAP16[ptr + i6 * 2 >> 1];
            if (codeUnit == 0) break;
            str3 += String.fromCharCode(codeUnit);
          }
          return str3;
        }
      }
      function stringToUTF16(str3, outPtr, maxBytesToWrite) {
        assert10(outPtr % 2 == 0, "Pointer passed to stringToUTF16 must be aligned to two bytes!");
        assert10(typeof maxBytesToWrite == "number", "stringToUTF16(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!");
        if (maxBytesToWrite === void 0) {
          maxBytesToWrite = 2147483647;
        }
        if (maxBytesToWrite < 2) return 0;
        maxBytesToWrite -= 2;
        var startPtr = outPtr;
        var numCharsToWrite = maxBytesToWrite < str3.length * 2 ? maxBytesToWrite / 2 : str3.length;
        for (var i6 = 0; i6 < numCharsToWrite; ++i6) {
          var codeUnit = str3.charCodeAt(i6);
          HEAP16[outPtr >> 1] = codeUnit;
          outPtr += 2;
        }
        HEAP16[outPtr >> 1] = 0;
        return outPtr - startPtr;
      }
      function lengthBytesUTF16(str3) {
        return str3.length * 2;
      }
      function UTF32ToString(ptr, maxBytesToRead) {
        assert10(ptr % 4 == 0, "Pointer passed to UTF32ToString must be aligned to four bytes!");
        var i6 = 0;
        var str3 = "";
        while (!(i6 >= maxBytesToRead / 4)) {
          var utf32 = HEAP32[ptr + i6 * 4 >> 2];
          if (utf32 == 0) break;
          ++i6;
          if (utf32 >= 65536) {
            var ch = utf32 - 65536;
            str3 += String.fromCharCode(55296 | ch >> 10, 56320 | ch & 1023);
          } else {
            str3 += String.fromCharCode(utf32);
          }
        }
        return str3;
      }
      function stringToUTF32(str3, outPtr, maxBytesToWrite) {
        assert10(outPtr % 4 == 0, "Pointer passed to stringToUTF32 must be aligned to four bytes!");
        assert10(typeof maxBytesToWrite == "number", "stringToUTF32(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!");
        if (maxBytesToWrite === void 0) {
          maxBytesToWrite = 2147483647;
        }
        if (maxBytesToWrite < 4) return 0;
        var startPtr = outPtr;
        var endPtr = startPtr + maxBytesToWrite - 4;
        for (var i6 = 0; i6 < str3.length; ++i6) {
          var codeUnit = str3.charCodeAt(i6);
          if (codeUnit >= 55296 && codeUnit <= 57343) {
            var trailSurrogate = str3.charCodeAt(++i6);
            codeUnit = 65536 + ((codeUnit & 1023) << 10) | trailSurrogate & 1023;
          }
          HEAP32[outPtr >> 2] = codeUnit;
          outPtr += 4;
          if (outPtr + 4 > endPtr) break;
        }
        HEAP32[outPtr >> 2] = 0;
        return outPtr - startPtr;
      }
      function lengthBytesUTF32(str3) {
        var len = 0;
        for (var i6 = 0; i6 < str3.length; ++i6) {
          var codeUnit = str3.charCodeAt(i6);
          if (codeUnit >= 55296 && codeUnit <= 57343) ++i6;
          len += 4;
        }
        return len;
      }
      function allocateUTF8(str3) {
        var size = lengthBytesUTF8(str3) + 1;
        var ret = _malloc(size);
        if (ret) stringToUTF8Array(str3, HEAP8, ret, size);
        return ret;
      }
      function allocateUTF8OnStack(str3) {
        var size = lengthBytesUTF8(str3) + 1;
        var ret = stackAlloc(size);
        stringToUTF8Array(str3, HEAP8, ret, size);
        return ret;
      }
      function writeStringToMemory(string2, buffer3, dontAddNull) {
        warnOnce2("writeStringToMemory is deprecated and should not be called! Use stringToUTF8() instead!");
        var lastChar, end;
        if (dontAddNull) {
          end = buffer3 + lengthBytesUTF8(string2);
          lastChar = HEAP8[end];
        }
        stringToUTF8(string2, buffer3, Infinity);
        if (dontAddNull) HEAP8[end] = lastChar;
      }
      function writeArrayToMemory(array, buffer3) {
        assert10(array.length >= 0, "writeArrayToMemory array must have a length (should be an array or typed array)");
        HEAP8.set(array, buffer3);
      }
      function writeAsciiToMemory(str3, buffer3, dontAddNull) {
        for (var i6 = 0; i6 < str3.length; ++i6) {
          assert10(str3.charCodeAt(i6) === str3.charCodeAt(i6) & 255);
          HEAP8[buffer3++ >> 0] = str3.charCodeAt(i6);
        }
        if (!dontAddNull) HEAP8[buffer3 >> 0] = 0;
      }
      function alignUp(x3, multiple) {
        if (x3 % multiple > 0) {
          x3 += multiple - x3 % multiple;
        }
        return x3;
      }
      var HEAP, buffer2, HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAPF64;
      function updateGlobalBufferAndViews(buf) {
        buffer2 = buf;
        Module["HEAP8"] = HEAP8 = new Int8Array(buf);
        Module["HEAP16"] = HEAP16 = new Int16Array(buf);
        Module["HEAP32"] = HEAP32 = new Int32Array(buf);
        Module["HEAPU8"] = HEAPU8 = new Uint8Array(buf);
        Module["HEAPU16"] = HEAPU16 = new Uint16Array(buf);
        Module["HEAPU32"] = HEAPU32 = new Uint32Array(buf);
        Module["HEAPF32"] = HEAPF32 = new Float32Array(buf);
        Module["HEAPF64"] = HEAPF64 = new Float64Array(buf);
      }
      var TOTAL_STACK = 5242880;
      if (Module["TOTAL_STACK"]) assert10(TOTAL_STACK === Module["TOTAL_STACK"], "the stack size can no longer be determined at runtime");
      var INITIAL_MEMORY = Module["INITIAL_MEMORY"] || 33554432;
      if (!Object.getOwnPropertyDescriptor(Module, "INITIAL_MEMORY")) {
        Object.defineProperty(Module, "INITIAL_MEMORY", {
          configurable: true,
          get: function() {
            abort2("Module.INITIAL_MEMORY has been replaced with plain INITIAL_MEMORY (the initial value can be provided on Module, but after startup the value is only looked for on a local variable of that name)");
          }
        });
      }
      assert10(INITIAL_MEMORY >= TOTAL_STACK, "INITIAL_MEMORY should be larger than TOTAL_STACK, was " + INITIAL_MEMORY + "! (TOTAL_STACK=" + TOTAL_STACK + ")");
      assert10(
        typeof Int32Array !== "undefined" && typeof Float64Array !== "undefined" && Int32Array.prototype.subarray !== void 0 && Int32Array.prototype.set !== void 0,
        "JS engine does not provide full typed array support"
      );
      if (Module["wasmMemory"]) {
        wasmMemory = Module["wasmMemory"];
      } else {
        wasmMemory = new WebAssembly.Memory({
          "initial": INITIAL_MEMORY / 65536,
          // In theory we should not need to emit the maximum if we want "unlimited"
          // or 4GB of memory, but VMs error on that atm, see
          // https://github.com/emscripten-core/emscripten/issues/14130
          // And in the pthreads case we definitely need to emit a maximum. So
          // always emit one.
          "maximum": 2147483648 / 65536
        });
      }
      if (wasmMemory) {
        buffer2 = wasmMemory.buffer;
      }
      INITIAL_MEMORY = buffer2.byteLength;
      assert10(INITIAL_MEMORY % 65536 === 0);
      updateGlobalBufferAndViews(buffer2);
      var wasmTable = new WebAssembly.Table({
        "initial": 21,
        "element": "anyfunc"
      });
      function writeStackCookie() {
        var max = _emscripten_stack_get_end();
        assert10((max & 3) == 0);
        HEAPU32[(max >> 2) + 1] = 34821223;
        HEAPU32[(max >> 2) + 2] = 2310721022;
        HEAP32[0] = 1668509029;
      }
      function checkStackCookie() {
        if (ABORT) return;
        var max = _emscripten_stack_get_end();
        var cookie1 = HEAPU32[(max >> 2) + 1];
        var cookie2 = HEAPU32[(max >> 2) + 2];
        if (cookie1 != 34821223 || cookie2 != 2310721022) {
          abort2("Stack overflow! Stack cookie has been overwritten, expected hex dwords 0x89BACDFE and 0x2135467, but received 0x" + cookie2.toString(16) + " " + cookie1.toString(16));
        }
        if (HEAP32[0] !== 1668509029) abort2("Runtime error: The application has corrupted its heap memory area (address zero)!");
      }
      (function() {
        var h16 = new Int16Array(1);
        var h8 = new Int8Array(h16.buffer);
        h16[0] = 25459;
        if (h8[0] !== 115 || h8[1] !== 99) throw "Runtime error: expected the system to be little-endian! (Run with -s SUPPORT_BIG_ENDIAN=1 to bypass)";
      })();
      var __ATPRERUN__ = [];
      var __ATINIT__ = [];
      var __ATMAIN__ = [];
      var __ATEXIT__ = [];
      var __ATPOSTRUN__ = [];
      var runtimeInitialized = false;
      var runtimeExited = false;
      function preRun() {
        if (Module["preRun"]) {
          if (typeof Module["preRun"] == "function") Module["preRun"] = [Module["preRun"]];
          while (Module["preRun"].length) {
            addOnPreRun(Module["preRun"].shift());
          }
        }
        callRuntimeCallbacks(__ATPRERUN__);
      }
      function initRuntime() {
        checkStackCookie();
        assert10(!runtimeInitialized);
        runtimeInitialized = true;
        callRuntimeCallbacks(__ATINIT__);
      }
      function preMain() {
        checkStackCookie();
        callRuntimeCallbacks(__ATMAIN__);
      }
      function exitRuntime() {
        checkStackCookie();
        runtimeExited = true;
      }
      function postRun() {
        checkStackCookie();
        if (Module["postRun"]) {
          if (typeof Module["postRun"] == "function") Module["postRun"] = [Module["postRun"]];
          while (Module["postRun"].length) {
            addOnPostRun(Module["postRun"].shift());
          }
        }
        callRuntimeCallbacks(__ATPOSTRUN__);
      }
      function addOnPreRun(cb) {
        __ATPRERUN__.unshift(cb);
      }
      function addOnInit(cb) {
        __ATINIT__.unshift(cb);
      }
      function addOnPreMain(cb) {
        __ATMAIN__.unshift(cb);
      }
      function addOnExit(cb) {
      }
      function addOnPostRun(cb) {
        __ATPOSTRUN__.unshift(cb);
      }
      assert10(Math.imul, "This browser does not support Math.imul(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill");
      assert10(Math.fround, "This browser does not support Math.fround(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill");
      assert10(Math.clz32, "This browser does not support Math.clz32(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill");
      assert10(Math.trunc, "This browser does not support Math.trunc(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill");
      var runDependencies = 0;
      var runDependencyWatcher = null;
      var dependenciesFulfilled = null;
      var runDependencyTracking = {};
      function getUniqueRunDependency(id) {
        var orig = id;
        while (1) {
          if (!runDependencyTracking[id]) return id;
          id = orig + Math.random();
        }
      }
      function addRunDependency(id) {
        runDependencies++;
        if (Module["monitorRunDependencies"]) {
          Module["monitorRunDependencies"](runDependencies);
        }
        if (id) {
          assert10(!runDependencyTracking[id]);
          runDependencyTracking[id] = 1;
          if (runDependencyWatcher === null && typeof setInterval !== "undefined") {
            runDependencyWatcher = setInterval(function() {
              if (ABORT) {
                clearInterval(runDependencyWatcher);
                runDependencyWatcher = null;
                return;
              }
              var shown = false;
              for (var dep in runDependencyTracking) {
                if (!shown) {
                  shown = true;
                  err2("still waiting on run dependencies:");
                }
                err2("dependency: " + dep);
              }
              if (shown) {
                err2("(end of list)");
              }
            }, 1e4);
          }
        } else {
          err2("warning: run dependency added without ID");
        }
      }
      function removeRunDependency(id) {
        runDependencies--;
        if (Module["monitorRunDependencies"]) {
          Module["monitorRunDependencies"](runDependencies);
        }
        if (id) {
          assert10(runDependencyTracking[id]);
          delete runDependencyTracking[id];
        } else {
          err2("warning: run dependency removed without ID");
        }
        if (runDependencies == 0) {
          if (runDependencyWatcher !== null) {
            clearInterval(runDependencyWatcher);
            runDependencyWatcher = null;
          }
          if (dependenciesFulfilled) {
            var callback = dependenciesFulfilled;
            dependenciesFulfilled = null;
            callback();
          }
        }
      }
      Module["preloadedImages"] = {};
      Module["preloadedAudios"] = {};
      Module["preloadedWasm"] = {};
      function abort2(what) {
        if (Module["onAbort"]) {
          Module["onAbort"](what);
        }
        what += "";
        err2(what);
        ABORT = true;
        EXITSTATUS = 1;
        var output = "abort(" + what + ") at " + stackTrace();
        what = output;
        var e5 = new WebAssembly.RuntimeError(what);
        throw e5;
      }
      var FS = {
        error: function() {
          abort2("Filesystem support (FS) was not included. The problem is that you are using files from JS, but files were not used from C/C++, so filesystem support was not auto-included. You can force-include filesystem support with  -s FORCE_FILESYSTEM=1");
        },
        init: function() {
          FS.error();
        },
        createDataFile: function() {
          FS.error();
        },
        createPreloadedFile: function() {
          FS.error();
        },
        createLazyFile: function() {
          FS.error();
        },
        open: function() {
          FS.error();
        },
        mkdev: function() {
          FS.error();
        },
        registerDevice: function() {
          FS.error();
        },
        analyzePath: function() {
          FS.error();
        },
        loadFilesFromDB: function() {
          FS.error();
        },
        ErrnoError: function ErrnoError() {
          FS.error();
        }
      };
      Module["FS_createDataFile"] = FS.createDataFile;
      Module["FS_createPreloadedFile"] = FS.createPreloadedFile;
      var dataURIPrefix = "data:application/octet-stream;base64,";
      function isDataURI(filename) {
        return filename.startsWith(dataURIPrefix);
      }
      function isFileURI(filename) {
        return filename.startsWith("file://");
      }
      function createExportWrapper(name2, fixedasm) {
        return function() {
          var displayName = name2;
          var asm2 = fixedasm;
          if (!fixedasm) {
            asm2 = Module["asm"];
          }
          assert10(runtimeInitialized, "native function `" + displayName + "` called before runtime initialization");
          assert10(!runtimeExited, "native function `" + displayName + "` called after runtime exit (use NO_EXIT_RUNTIME to keep it alive after main() exits)");
          if (!asm2[name2]) {
            assert10(asm2[name2], "exported native function `" + displayName + "` not found");
          }
          return asm2[name2].apply(null, arguments);
        };
      }
      async function createWasm() {
        var info2 = {
          "env": asmLibraryArg,
          "wasi_snapshot_preview1": asmLibraryArg,
          "GOT.mem": new Proxy(asmLibraryArg, GOTHandler),
          "GOT.func": new Proxy(asmLibraryArg, GOTHandler)
        };
        function receiveInstance(instance, module2) {
          var exports23 = instance.exports;
          exports23 = relocateExports(exports23, 1024);
          Module["asm"] = exports23;
          var metadata = getDylinkMetadata(module2);
          if (metadata.neededDynlibs) {
            dynamicLibraries = metadata.neededDynlibs.concat(dynamicLibraries);
          }
          mergeLibSymbols(exports23, "main");
          addOnInit(Module["asm"]["__wasm_call_ctors"]);
          removeRunDependency("wasm-instantiate");
          wasmInstantiateResolve();
        }
        addRunDependency("wasm-instantiate");
        var trueModule = Module;
        function receiveInstantiationResult(result2) {
          assert10(Module === trueModule, "the Module object should not be replaced during async compilation - perhaps the order of HTML elements is wrong?");
          trueModule = null;
          receiveInstance(result2["instance"], result2["module"]);
        }
        let wasmModule = new WebAssembly.Module(wasmBinaryFile);
        let wasmInstance = new WebAssembly.Instance(wasmModule, info2);
        receiveInstantiationResult({ module: wasmModule, instance: wasmInstance });
        return {};
      }
      var tempDouble;
      var tempI64;
      var ASM_CONSTS = {};
      var GOT = {};
      var GOTHandler = { get: function(obj, symName) {
        if (!GOT[symName]) {
          GOT[symName] = new WebAssembly.Global({ "value": "i32", "mutable": true });
        }
        return GOT[symName];
      } };
      function callRuntimeCallbacks(callbacks) {
        while (callbacks.length > 0) {
          var callback = callbacks.shift();
          if (typeof callback == "function") {
            callback(Module);
            continue;
          }
          var func = callback.func;
          if (typeof func === "number") {
            if (callback.arg === void 0) {
              wasmTable.get(func)();
            } else {
              wasmTable.get(func)(callback.arg);
            }
          } else {
            func(callback.arg === void 0 ? null : callback.arg);
          }
        }
      }
      function demangle(func) {
        warnOnce2("warning: build with  -s DEMANGLE_SUPPORT=1  to link in libcxxabi demangling");
        return func;
      }
      function demangleAll(text) {
        var regex = /\b_Z[\w\d_]+/g;
        return text.replace(
          regex,
          function(x3) {
            var y4 = demangle(x3);
            return x3 === y4 ? x3 : y4 + " [" + x3 + "]";
          }
        );
      }
      function getDylinkMetadata(binary3) {
        var next = 0;
        function getLEB() {
          var ret = 0;
          var mul = 1;
          while (1) {
            var byte = binary3[next++];
            ret += (byte & 127) * mul;
            mul *= 128;
            if (!(byte & 128)) break;
          }
          return ret;
        }
        if (binary3 instanceof WebAssembly.Module) {
          var dylinkSection = WebAssembly.Module.customSections(binary3, "dylink");
          assert10(dylinkSection.length != 0, "need dylink section");
          binary3 = new Int8Array(dylinkSection[0]);
        } else {
          var int32View = new Uint32Array(new Uint8Array(binary3.subarray(0, 24)).buffer);
          assert10(int32View[0] == 1836278016, "need to see wasm magic number");
          assert10(binary3[8] === 0, "need the dylink section to be first");
          next = 9;
          getLEB();
          assert10(binary3[next] === 6);
          next++;
          assert10(binary3[next] === "d".charCodeAt(0));
          next++;
          assert10(binary3[next] === "y".charCodeAt(0));
          next++;
          assert10(binary3[next] === "l".charCodeAt(0));
          next++;
          assert10(binary3[next] === "i".charCodeAt(0));
          next++;
          assert10(binary3[next] === "n".charCodeAt(0));
          next++;
          assert10(binary3[next] === "k".charCodeAt(0));
          next++;
        }
        var customSection = {};
        customSection.memorySize = getLEB();
        customSection.memoryAlign = getLEB();
        customSection.tableSize = getLEB();
        customSection.tableAlign = getLEB();
        var tableAlign = Math.pow(2, customSection.tableAlign);
        assert10(tableAlign === 1, "invalid tableAlign " + tableAlign);
        var neededDynlibsCount = getLEB();
        customSection.neededDynlibs = [];
        for (var i6 = 0; i6 < neededDynlibsCount; ++i6) {
          var nameLen = getLEB();
          var nameUTF8 = binary3.subarray(next, next + nameLen);
          next += nameLen;
          var name2 = UTF8ArrayToString(nameUTF8, 0);
          customSection.neededDynlibs.push(name2);
        }
        return customSection;
      }
      function jsStackTrace() {
        var error2 = new Error();
        if (!error2.stack) {
          try {
            throw new Error();
          } catch (e5) {
            error2 = e5;
          }
          if (!error2.stack) {
            return "(no stack trace available)";
          }
        }
        return error2.stack.toString();
      }
      var runtimeKeepaliveCounter = 0;
      function keepRuntimeAlive() {
        return noExitRuntime || runtimeKeepaliveCounter > 0;
      }
      function asmjsMangle(x3) {
        var unmangledSymbols = ["stackAlloc", "stackSave", "stackRestore"];
        return x3.indexOf("dynCall_") == 0 || unmangledSymbols.includes(x3) ? x3 : "_" + x3;
      }
      function mergeLibSymbols(exports23, libName) {
        for (var sym in exports23) {
          if (!exports23.hasOwnProperty(sym)) {
            continue;
          }
          if (!asmLibraryArg.hasOwnProperty(sym)) {
            asmLibraryArg[sym] = exports23[sym];
          }
          var module_sym = asmjsMangle(sym);
          if (!Module.hasOwnProperty(module_sym)) {
            Module[module_sym] = exports23[sym];
          }
        }
      }
      var LDSO = { nextHandle: 1, loadedLibs: {}, loadedLibNames: {} };
      function dynCallLegacy(sig, ptr, args) {
        assert10("dynCall_" + sig in Module, "bad function pointer type - no table for sig '" + sig + "'");
        if (args && args.length) {
          assert10(args.length === sig.substring(1).replace(/j/g, "--").length);
        } else {
          assert10(sig.length == 1);
        }
        var f5 = Module["dynCall_" + sig];
        return args && args.length ? f5.apply(null, [ptr].concat(args)) : f5.call(null, ptr);
      }
      function dynCall(sig, ptr, args) {
        if (sig.includes("j")) {
          return dynCallLegacy(sig, ptr, args);
        }
        assert10(wasmTable.get(ptr), "missing table entry in dynCall: " + ptr);
        return wasmTable.get(ptr).apply(null, args);
      }
      function createInvokeFunction(sig) {
        return function() {
          var sp = stackSave();
          try {
            return dynCall(sig, arguments[0], Array.prototype.slice.call(arguments, 1));
          } catch (e5) {
            stackRestore(sp);
            if (e5 !== e5 + 0 && e5 !== "longjmp") throw e5;
            _setThrew(1, 0);
          }
        };
      }
      var ___heap_base = 5251008;
      Module["___heap_base"] = ___heap_base;
      function getMemory(size) {
        if (runtimeInitialized)
          return _malloc(size);
        var ret = ___heap_base;
        var end = ret + size + 15 & -16;
        assert10(end <= HEAP8.length, "failure to getMemory - memory growth etc. is not supported there, call malloc/sbrk directly or increase INITIAL_MEMORY");
        ___heap_base = end;
        GOT["__heap_base"].value = end;
        return ret;
      }
      function isInternalSym(symName) {
        return [
          "__cpp_exception",
          "__wasm_apply_data_relocs",
          "__dso_handle",
          "__set_stack_limits"
        ].includes(symName);
      }
      function updateGOT(exports23) {
        for (var symName in exports23) {
          if (isInternalSym(symName)) {
            continue;
          }
          var replace = false;
          var value = exports23[symName];
          if (symName.startsWith("orig$")) {
            symName = symName.split("$")[1];
            replace = true;
          }
          if (!GOT[symName]) {
            GOT[symName] = new WebAssembly.Global({ "value": "i32", "mutable": true });
          }
          if (replace || GOT[symName].value == 0) {
            if (typeof value === "function") {
              GOT[symName].value = addFunctionWasm(value);
            } else if (typeof value === "number") {
              GOT[symName].value = value;
            } else {
              err2("unhandled export type for `" + symName + "`: " + typeof value);
            }
          }
        }
      }
      function relocateExports(exports23, memoryBase) {
        var relocated = {};
        for (var e5 in exports23) {
          var value = exports23[e5];
          if (typeof value === "object") {
            value = value.value;
          }
          if (typeof value === "number") {
            value += memoryBase;
          }
          relocated[e5] = value;
        }
        updateGOT(relocated);
        return relocated;
      }
      function resolveGlobalSymbol(symName, direct) {
        var sym;
        if (direct) {
          sym = asmLibraryArg["orig$" + symName];
        }
        if (!sym) {
          sym = asmLibraryArg[symName];
        }
        if (!sym) {
          sym = Module[asmjsMangle(symName)];
        }
        if (!sym && symName.startsWith("invoke_")) {
          sym = createInvokeFunction(symName.split("_")[1]);
        }
        return sym;
      }
      function loadWebAssemblyModule(binary3, flags) {
        var metadata = getDylinkMetadata(binary3);
        var originalTable = wasmTable;
        function loadModule() {
          var memAlign = Math.pow(2, metadata.memoryAlign);
          memAlign = Math.max(memAlign, STACK_ALIGN);
          var memoryBase = alignMemory(getMemory(metadata.memorySize + memAlign), memAlign);
          var tableBase = wasmTable.length;
          wasmTable.grow(metadata.tableSize);
          for (var i6 = memoryBase; i6 < memoryBase + metadata.memorySize; i6++) {
            HEAP8[i6] = 0;
          }
          for (var i6 = tableBase; i6 < tableBase + metadata.tableSize; i6++) {
            wasmTable.set(i6, null);
          }
          var moduleExports;
          function resolveSymbol(sym) {
            var resolved = resolveGlobalSymbol(sym, false);
            if (!resolved) {
              resolved = moduleExports[sym];
            }
            assert10(resolved, "undefined symbol `" + sym + "`. perhaps a side module was not linked in? if this global was expected to arrive from a system library, try to build the MAIN_MODULE with EMCC_FORCE_STDLIBS=1 in the environment");
            return resolved;
          }
          var proxyHandler = {
            "get": function(stubs, prop) {
              switch (prop) {
                case "__memory_base":
                  return memoryBase;
                case "__table_base":
                  return tableBase;
              }
              if (prop in asmLibraryArg) {
                return asmLibraryArg[prop];
              }
              if (!(prop in stubs)) {
                var resolved;
                stubs[prop] = function() {
                  if (!resolved) resolved = resolveSymbol(prop, true);
                  return resolved.apply(null, arguments);
                };
              }
              return stubs[prop];
            }
          };
          var proxy = new Proxy({}, proxyHandler);
          var info2 = {
            "GOT.mem": new Proxy({}, GOTHandler),
            "GOT.func": new Proxy({}, GOTHandler),
            "env": proxy,
            wasi_snapshot_preview1: proxy
          };
          function postInstantiation(instance2) {
            assert10(wasmTable === originalTable);
            for (var i7 = 0; i7 < metadata.tableSize; i7++) {
              var item = wasmTable.get(tableBase + i7);
              assert10(item !== void 0, "table entry was not filled in");
              if (item) {
                functionsInTableMap.set(item, tableBase + i7);
              }
            }
            moduleExports = relocateExports(instance2.exports, memoryBase);
            if (!flags.allowUndefined) {
              reportUndefinedSymbols();
            }
            var init5 = moduleExports["__wasm_call_ctors"];
            if (!init5) {
              init5 = moduleExports["__post_instantiate"];
            }
            if (init5) {
              if (runtimeInitialized) {
                init5();
              } else {
                __ATINIT__.push(init5);
              }
            }
            return moduleExports;
          }
          var module2 = binary3 instanceof WebAssembly.Module ? binary3 : new WebAssembly.Module(binary3);
          var instance = new WebAssembly.Instance(module2, info2);
          return postInstantiation(instance);
        }
        if (flags.loadAsync) {
          return metadata.neededDynlibs.reduce(function(chain, dynNeeded) {
            return chain.then(function() {
              return loadDynamicLibrary(dynNeeded, flags);
            });
          }, Promise.resolve()).then(function() {
            return loadModule();
          });
        }
        metadata.neededDynlibs.forEach(function(dynNeeded) {
          loadDynamicLibrary(dynNeeded, flags);
        });
        return loadModule();
      }
      function fetchBinary(url) {
        return fetch(url, { credentials: "same-origin" }).then(function(response) {
          if (!response["ok"]) {
            throw "failed to load binary file at '" + url + "'";
          }
          return response["arrayBuffer"]();
        }).then(function(buffer3) {
          return new Uint8Array(buffer3);
        });
      }
      function loadDynamicLibrary(lib2, flags) {
        if (lib2 == "__main__" && !LDSO.loadedLibNames[lib2]) {
          LDSO.loadedLibs[-1] = {
            refcount: Infinity,
            // = nodelete
            name: "__main__",
            module: Module["asm"],
            global: true
          };
          LDSO.loadedLibNames["__main__"] = -1;
        }
        flags = flags || { global: true, nodelete: true };
        var handle = LDSO.loadedLibNames[lib2];
        var dso;
        if (handle) {
          dso = LDSO.loadedLibs[handle];
          if (flags.global && !dso.global) {
            dso.global = true;
            if (dso.module !== "loading") {
              mergeLibSymbols(dso.module, lib2);
            }
          }
          if (flags.nodelete && dso.refcount !== Infinity) {
            dso.refcount = Infinity;
          }
          dso.refcount++;
          return flags.loadAsync ? Promise.resolve(handle) : handle;
        }
        handle = LDSO.nextHandle++;
        dso = {
          refcount: flags.nodelete ? Infinity : 1,
          name: lib2,
          module: "loading",
          global: flags.global
        };
        LDSO.loadedLibNames[lib2] = handle;
        LDSO.loadedLibs[handle] = dso;
        function loadLibData(libFile) {
          if (flags.fs) {
            var libData = flags.fs.readFile(libFile, { encoding: "binary" });
            if (!(libData instanceof Uint8Array)) {
              libData = new Uint8Array(libData);
            }
            return flags.loadAsync ? Promise.resolve(libData) : libData;
          }
          if (flags.loadAsync) {
            return fetchBinary(libFile);
          }
          return readBinary(libFile);
        }
        function getLibModule() {
          if (Module["preloadedWasm"] !== void 0 && Module["preloadedWasm"][lib2] !== void 0) {
            var libModule = Module["preloadedWasm"][lib2];
            return flags.loadAsync ? Promise.resolve(libModule) : libModule;
          }
          if (flags.loadAsync) {
            return loadLibData(lib2).then(function(libData) {
              return loadWebAssemblyModule(libData, flags);
            });
          }
          return loadWebAssemblyModule(loadLibData(lib2), flags);
        }
        function moduleLoaded(libModule) {
          if (dso.global) {
            mergeLibSymbols(libModule, lib2);
          }
          dso.module = libModule;
        }
        if (flags.loadAsync) {
          return getLibModule().then(function(libModule) {
            moduleLoaded(libModule);
            return handle;
          });
        }
        moduleLoaded(getLibModule());
        return handle;
      }
      function reportUndefinedSymbols() {
        for (var symName in GOT) {
          if (GOT[symName].value == 0) {
            var value = resolveGlobalSymbol(symName, true);
            assert10(value, "undefined symbol `" + symName + "`. perhaps a side module was not linked in? if this global was expected to arrive from a system library, try to build the MAIN_MODULE with EMCC_FORCE_STDLIBS=1 in the environment");
            if (typeof value === "function") {
              GOT[symName].value = addFunctionWasm(value, value.sig);
            } else if (typeof value === "number") {
              GOT[symName].value = value;
            } else {
              assert10(false, "bad export type for `" + symName + "`: " + typeof value);
            }
          }
        }
      }
      function preloadDylibs() {
        if (!dynamicLibraries.length) {
          reportUndefinedSymbols();
          return;
        }
        if (!readBinary) {
          addRunDependency("preloadDylibs");
          dynamicLibraries.reduce(function(chain, lib2) {
            return chain.then(function() {
              return loadDynamicLibrary(lib2, { loadAsync: true, global: true, nodelete: true, allowUndefined: true });
            });
          }, Promise.resolve()).then(function() {
            removeRunDependency("preloadDylibs");
            reportUndefinedSymbols();
          });
          return;
        }
        dynamicLibraries.forEach(function(lib2) {
          loadDynamicLibrary(lib2, { global: true, nodelete: true, allowUndefined: true });
        });
        reportUndefinedSymbols();
      }
      function stackTrace() {
        var js = jsStackTrace();
        if (Module["extraStackTrace"]) js += "\n" + Module["extraStackTrace"]();
        return demangleAll(js);
      }
      var ___stack_pointer = new WebAssembly.Global({ "value": "i32", "mutable": true }, 5251008);
      function _abort() {
        abort2();
      }
      Module["_abort"] = _abort;
      _abort.sig = "v";
      var _emscripten_get_now = function() {
        return performance.now();
      };
      var _emscripten_get_now_is_monotonic = true;
      ;
      function setErrNo(value) {
        HEAP32[___errno_location() >> 2] = value;
        return value;
      }
      function _clock_gettime(clk_id, tp) {
        var now;
        if (clk_id === 0) {
          now = Date.now();
        } else if ((clk_id === 1 || clk_id === 4) && _emscripten_get_now_is_monotonic) {
          now = _emscripten_get_now();
        } else {
          setErrNo(28);
          return -1;
        }
        HEAP32[tp >> 2] = now / 1e3 | 0;
        HEAP32[tp + 4 >> 2] = now % 1e3 * 1e3 * 1e3 | 0;
        return 0;
      }
      _clock_gettime.sig = "iii";
      function _emscripten_memcpy_big(dest, src2, num) {
        HEAPU8.copyWithin(dest, src2, src2 + num);
      }
      function emscripten_realloc_buffer(size) {
        try {
          wasmMemory.grow(size - buffer2.byteLength + 65535 >>> 16);
          updateGlobalBufferAndViews(wasmMemory.buffer);
          return 1;
        } catch (e5) {
          console.error("emscripten_realloc_buffer: Attempted to grow heap from " + buffer2.byteLength + " bytes to " + size + " bytes, but got error: " + e5);
        }
      }
      function _emscripten_resize_heap(requestedSize) {
        var oldSize = HEAPU8.length;
        requestedSize = requestedSize >>> 0;
        assert10(requestedSize > oldSize);
        var maxHeapSize = 2147483648;
        if (requestedSize > maxHeapSize) {
          err2("Cannot enlarge memory, asked to go up to " + requestedSize + " bytes, but the limit is " + maxHeapSize + " bytes!");
          return false;
        }
        for (var cutDown = 1; cutDown <= 4; cutDown *= 2) {
          var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown);
          overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + 100663296);
          var newSize = Math.min(maxHeapSize, alignUp(Math.max(requestedSize, overGrownHeapSize), 65536));
          var replacement = emscripten_realloc_buffer(newSize);
          if (replacement) {
            return true;
          }
        }
        err2("Failed to grow the heap from " + oldSize + " bytes to " + newSize + " bytes, not enough memory!");
        return false;
      }
      function _exit(status) {
        exit2(status);
      }
      _exit.sig = "vi";
      var SYSCALLS = { mappings: {}, DEFAULT_POLLMASK: 5, umask: 511, calculateAt: function(dirfd, path3, allowEmpty) {
        if (path3[0] === "/") {
          return path3;
        }
        var dir;
        if (dirfd === -100) {
          dir = FS.cwd();
        } else {
          var dirstream = FS.getStream(dirfd);
          if (!dirstream) throw new FS.ErrnoError(8);
          dir = dirstream.path;
        }
        if (path3.length == 0) {
          if (!allowEmpty) {
            throw new FS.ErrnoError(44);
            ;
          }
          return dir;
        }
        return PATH.join2(dir, path3);
      }, doStat: function(func, path3, buf) {
        try {
          var stat = func(path3);
        } catch (e5) {
          if (e5 && e5.node && PATH.normalize(path3) !== PATH.normalize(FS.getPath(e5.node))) {
            return -54;
          }
          throw e5;
        }
        HEAP32[buf >> 2] = stat.dev;
        HEAP32[buf + 4 >> 2] = 0;
        HEAP32[buf + 8 >> 2] = stat.ino;
        HEAP32[buf + 12 >> 2] = stat.mode;
        HEAP32[buf + 16 >> 2] = stat.nlink;
        HEAP32[buf + 20 >> 2] = stat.uid;
        HEAP32[buf + 24 >> 2] = stat.gid;
        HEAP32[buf + 28 >> 2] = stat.rdev;
        HEAP32[buf + 32 >> 2] = 0;
        tempI64 = [stat.size >>> 0, (tempDouble = stat.size, +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? (Math.min(+Math.floor(tempDouble / 4294967296), 4294967295) | 0) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)], HEAP32[buf + 40 >> 2] = tempI64[0], HEAP32[buf + 44 >> 2] = tempI64[1];
        HEAP32[buf + 48 >> 2] = 4096;
        HEAP32[buf + 52 >> 2] = stat.blocks;
        HEAP32[buf + 56 >> 2] = stat.atime.getTime() / 1e3 | 0;
        HEAP32[buf + 60 >> 2] = 0;
        HEAP32[buf + 64 >> 2] = stat.mtime.getTime() / 1e3 | 0;
        HEAP32[buf + 68 >> 2] = 0;
        HEAP32[buf + 72 >> 2] = stat.ctime.getTime() / 1e3 | 0;
        HEAP32[buf + 76 >> 2] = 0;
        tempI64 = [stat.ino >>> 0, (tempDouble = stat.ino, +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? (Math.min(+Math.floor(tempDouble / 4294967296), 4294967295) | 0) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)], HEAP32[buf + 80 >> 2] = tempI64[0], HEAP32[buf + 84 >> 2] = tempI64[1];
        return 0;
      }, doMsync: function(addr, stream, len, flags, offset3) {
        var buffer3 = HEAPU8.slice(addr, addr + len);
        FS.msync(stream, buffer3, offset3, len, flags);
      }, doMkdir: function(path3, mode) {
        path3 = PATH.normalize(path3);
        if (path3[path3.length - 1] === "/") path3 = path3.substr(0, path3.length - 1);
        FS.mkdir(path3, mode, 0);
        return 0;
      }, doMknod: function(path3, mode, dev) {
        switch (mode & 61440) {
          case 32768:
          case 8192:
          case 24576:
          case 4096:
          case 49152:
            break;
          default:
            return -28;
        }
        FS.mknod(path3, mode, dev);
        return 0;
      }, doReadlink: function(path3, buf, bufsize) {
        if (bufsize <= 0) return -28;
        var ret = FS.readlink(path3);
        var len = Math.min(bufsize, lengthBytesUTF8(ret));
        var endChar = HEAP8[buf + len];
        stringToUTF8(ret, buf, bufsize + 1);
        HEAP8[buf + len] = endChar;
        return len;
      }, doAccess: function(path3, amode) {
        if (amode & ~7) {
          return -28;
        }
        var node;
        var lookup3 = FS.lookupPath(path3, { follow: true });
        node = lookup3.node;
        if (!node) {
          return -44;
        }
        var perms = "";
        if (amode & 4) perms += "r";
        if (amode & 2) perms += "w";
        if (amode & 1) perms += "x";
        if (perms && FS.nodePermissions(node, perms)) {
          return -2;
        }
        return 0;
      }, doDup: function(path3, flags, suggestFD) {
        var suggest = FS.getStream(suggestFD);
        if (suggest) FS.close(suggest);
        return FS.open(path3, flags, 0, suggestFD, suggestFD).fd;
      }, doReadv: function(stream, iov, iovcnt, offset3) {
        var ret = 0;
        for (var i6 = 0; i6 < iovcnt; i6++) {
          var ptr = HEAP32[iov + i6 * 8 >> 2];
          var len = HEAP32[iov + (i6 * 8 + 4) >> 2];
          var curr = FS.read(stream, HEAP8, ptr, len, offset3);
          if (curr < 0) return -1;
          ret += curr;
          if (curr < len) break;
        }
        return ret;
      }, doWritev: function(stream, iov, iovcnt, offset3) {
        var ret = 0;
        for (var i6 = 0; i6 < iovcnt; i6++) {
          var ptr = HEAP32[iov + i6 * 8 >> 2];
          var len = HEAP32[iov + (i6 * 8 + 4) >> 2];
          var curr = FS.write(stream, HEAP8, ptr, len, offset3);
          if (curr < 0) return -1;
          ret += curr;
        }
        return ret;
      }, varargs: void 0, get: function() {
        assert10(SYSCALLS.varargs != void 0);
        SYSCALLS.varargs += 4;
        var ret = HEAP32[SYSCALLS.varargs - 4 >> 2];
        return ret;
      }, getStr: function(ptr) {
        var ret = UTF8ToString(ptr);
        return ret;
      }, getStreamFromFD: function(fd) {
        var stream = FS.getStream(fd);
        if (!stream) throw new FS.ErrnoError(8);
        return stream;
      }, get64: function(low, high) {
        if (low >= 0) assert10(high === 0);
        else assert10(high === -1);
        return low;
      } };
      function _fd_close(fd) {
        try {
          var stream = SYSCALLS.getStreamFromFD(fd);
          FS.close(stream);
          return 0;
        } catch (e5) {
          if (typeof FS === "undefined" || !(e5 instanceof FS.ErrnoError)) abort2(e5);
          return e5.errno;
        }
      }
      _fd_close.sig = "ii";
      function _fd_seek(fd, offset_low, offset_high, whence, newOffset) {
        try {
          var stream = SYSCALLS.getStreamFromFD(fd);
          var HIGH_OFFSET = 4294967296;
          var offset3 = offset_high * HIGH_OFFSET + (offset_low >>> 0);
          var DOUBLE_LIMIT = 9007199254740992;
          if (offset3 <= -DOUBLE_LIMIT || offset3 >= DOUBLE_LIMIT) {
            return -61;
          }
          FS.llseek(stream, offset3, whence);
          tempI64 = [stream.position >>> 0, (tempDouble = stream.position, +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? (Math.min(+Math.floor(tempDouble / 4294967296), 4294967295) | 0) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)], HEAP32[newOffset >> 2] = tempI64[0], HEAP32[newOffset + 4 >> 2] = tempI64[1];
          if (stream.getdents && offset3 === 0 && whence === 0) stream.getdents = null;
          return 0;
        } catch (e5) {
          if (typeof FS === "undefined" || !(e5 instanceof FS.ErrnoError)) abort2(e5);
          return e5.errno;
        }
      }
      function _fd_write(fd, iov, iovcnt, pnum) {
        try {
          var stream = SYSCALLS.getStreamFromFD(fd);
          var num = SYSCALLS.doWritev(stream, iov, iovcnt);
          HEAP32[pnum >> 2] = num;
          return 0;
        } catch (e5) {
          if (typeof FS === "undefined" || !(e5 instanceof FS.ErrnoError)) abort2(e5);
          return e5.errno;
        }
      }
      _fd_write.sig = "iiiii";
      function _setTempRet0(val) {
        setTempRet0(val);
      }
      _setTempRet0.sig = "vi";
      function _tree_sitter_log_callback(isLexMessage, messageAddress) {
        if (currentLogCallback) {
          const message = UTF8ToString(messageAddress);
          currentLogCallback(message, isLexMessage !== 0);
        }
      }
      function _tree_sitter_parse_callback(inputBufferAddress, index2, row, column, lengthAddress) {
        var INPUT_BUFFER_SIZE = 10 * 1024;
        var string2 = currentParseCallback(index2, { row, column });
        if (typeof string2 === "string") {
          setValue(lengthAddress, string2.length, "i32");
          stringToUTF16(string2, inputBufferAddress, INPUT_BUFFER_SIZE);
        } else {
          setValue(lengthAddress, 0, "i32");
        }
      }
      var ___memory_base = 1024;
      var ___table_base = 1;
      var ASSERTIONS = true;
      function intArrayFromString(stringy, dontAddNull, length) {
        var len = length > 0 ? length : lengthBytesUTF8(stringy) + 1;
        var u8array = new Array(len);
        var numBytesWritten = stringToUTF8Array(stringy, u8array, 0, u8array.length);
        if (dontAddNull) u8array.length = numBytesWritten;
        return u8array;
      }
      function intArrayToString(array) {
        var ret = [];
        for (var i6 = 0; i6 < array.length; i6++) {
          var chr = array[i6];
          if (chr > 255) {
            if (ASSERTIONS) {
              assert10(false, "Character code " + chr + " (" + String.fromCharCode(chr) + ")  at offset " + i6 + " not in 0x00-0xFF.");
            }
            chr &= 255;
          }
          ret.push(String.fromCharCode(chr));
        }
        return ret.join("");
      }
      var decodeBase642 = typeof atob === "function" ? atob : function(input) {
        var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i6 = 0;
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
        do {
          enc1 = keyStr.indexOf(input.charAt(i6++));
          enc2 = keyStr.indexOf(input.charAt(i6++));
          enc3 = keyStr.indexOf(input.charAt(i6++));
          enc4 = keyStr.indexOf(input.charAt(i6++));
          chr1 = enc1 << 2 | enc2 >> 4;
          chr2 = (enc2 & 15) << 4 | enc3 >> 2;
          chr3 = (enc3 & 3) << 6 | enc4;
          output = output + String.fromCharCode(chr1);
          if (enc3 !== 64) {
            output = output + String.fromCharCode(chr2);
          }
          if (enc4 !== 64) {
            output = output + String.fromCharCode(chr3);
          }
        } while (i6 < input.length);
        return output;
      };
      function intArrayFromBase64(s5) {
        try {
          var decoded = decodeBase642(s5);
          var bytes = new Uint8Array(decoded.length);
          for (var i6 = 0; i6 < decoded.length; ++i6) {
            bytes[i6] = decoded.charCodeAt(i6);
          }
          return bytes;
        } catch (_3) {
          throw new Error("Converting base64 string to bytes failed.");
        }
      }
      function tryParseAsDataURI(filename) {
        if (!isDataURI(filename)) {
          return void 0;
        }
        return intArrayFromBase64(filename.slice(dataURIPrefix.length));
      }
      var asmLibraryArg = {
        "__heap_base": ___heap_base,
        "__indirect_function_table": wasmTable,
        "__memory_base": ___memory_base,
        "__stack_pointer": ___stack_pointer,
        "__table_base": ___table_base,
        "abort": _abort,
        "clock_gettime": _clock_gettime,
        "emscripten_memcpy_big": _emscripten_memcpy_big,
        "emscripten_resize_heap": _emscripten_resize_heap,
        "exit": _exit,
        "fd_close": _fd_close,
        "fd_seek": _fd_seek,
        "fd_write": _fd_write,
        "memory": wasmMemory,
        "setTempRet0": _setTempRet0,
        "tree_sitter_log_callback": _tree_sitter_log_callback,
        "tree_sitter_parse_callback": _tree_sitter_parse_callback
      };
      var asm = await createWasm();
      var ___wasm_call_ctors = Module["___wasm_call_ctors"] = createExportWrapper("__wasm_call_ctors");
      var _ts_language_symbol_count = Module["_ts_language_symbol_count"] = createExportWrapper("ts_language_symbol_count");
      var _ts_language_version = Module["_ts_language_version"] = createExportWrapper("ts_language_version");
      var _ts_language_field_count = Module["_ts_language_field_count"] = createExportWrapper("ts_language_field_count");
      var _ts_language_symbol_name = Module["_ts_language_symbol_name"] = createExportWrapper("ts_language_symbol_name");
      var _ts_language_symbol_for_name = Module["_ts_language_symbol_for_name"] = createExportWrapper("ts_language_symbol_for_name");
      var _ts_language_symbol_type = Module["_ts_language_symbol_type"] = createExportWrapper("ts_language_symbol_type");
      var _ts_language_field_name_for_id = Module["_ts_language_field_name_for_id"] = createExportWrapper("ts_language_field_name_for_id");
      var _memcpy = Module["_memcpy"] = createExportWrapper("memcpy");
      var _free = Module["_free"] = createExportWrapper("free");
      var _calloc = Module["_calloc"] = createExportWrapper("calloc");
      var _ts_parser_delete = Module["_ts_parser_delete"] = createExportWrapper("ts_parser_delete");
      var _ts_parser_set_language = Module["_ts_parser_set_language"] = createExportWrapper("ts_parser_set_language");
      var _ts_parser_reset = Module["_ts_parser_reset"] = createExportWrapper("ts_parser_reset");
      var _ts_parser_timeout_micros = Module["_ts_parser_timeout_micros"] = createExportWrapper("ts_parser_timeout_micros");
      var _ts_parser_set_timeout_micros = Module["_ts_parser_set_timeout_micros"] = createExportWrapper("ts_parser_set_timeout_micros");
      var _ts_query_new = Module["_ts_query_new"] = createExportWrapper("ts_query_new");
      var _ts_query_delete = Module["_ts_query_delete"] = createExportWrapper("ts_query_delete");
      var _malloc = Module["_malloc"] = createExportWrapper("malloc");
      var _iswspace = Module["_iswspace"] = createExportWrapper("iswspace");
      var _ts_query_pattern_count = Module["_ts_query_pattern_count"] = createExportWrapper("ts_query_pattern_count");
      var _ts_query_capture_count = Module["_ts_query_capture_count"] = createExportWrapper("ts_query_capture_count");
      var _ts_query_string_count = Module["_ts_query_string_count"] = createExportWrapper("ts_query_string_count");
      var _ts_query_capture_name_for_id = Module["_ts_query_capture_name_for_id"] = createExportWrapper("ts_query_capture_name_for_id");
      var _ts_query_string_value_for_id = Module["_ts_query_string_value_for_id"] = createExportWrapper("ts_query_string_value_for_id");
      var _ts_query_predicates_for_pattern = Module["_ts_query_predicates_for_pattern"] = createExportWrapper("ts_query_predicates_for_pattern");
      var _memmove = Module["_memmove"] = createExportWrapper("memmove");
      var _memcmp = Module["_memcmp"] = createExportWrapper("memcmp");
      var _ts_tree_copy = Module["_ts_tree_copy"] = createExportWrapper("ts_tree_copy");
      var _ts_tree_delete = Module["_ts_tree_delete"] = createExportWrapper("ts_tree_delete");
      var _iswalnum = Module["_iswalnum"] = createExportWrapper("iswalnum");
      var _ts_init = Module["_ts_init"] = createExportWrapper("ts_init");
      var _ts_parser_new_wasm = Module["_ts_parser_new_wasm"] = createExportWrapper("ts_parser_new_wasm");
      var _ts_parser_enable_logger_wasm = Module["_ts_parser_enable_logger_wasm"] = createExportWrapper("ts_parser_enable_logger_wasm");
      var _ts_parser_parse_wasm = Module["_ts_parser_parse_wasm"] = createExportWrapper("ts_parser_parse_wasm");
      var _ts_language_type_is_named_wasm = Module["_ts_language_type_is_named_wasm"] = createExportWrapper("ts_language_type_is_named_wasm");
      var _ts_language_type_is_visible_wasm = Module["_ts_language_type_is_visible_wasm"] = createExportWrapper("ts_language_type_is_visible_wasm");
      var _ts_tree_root_node_wasm = Module["_ts_tree_root_node_wasm"] = createExportWrapper("ts_tree_root_node_wasm");
      var _ts_tree_edit_wasm = Module["_ts_tree_edit_wasm"] = createExportWrapper("ts_tree_edit_wasm");
      var _ts_tree_get_changed_ranges_wasm = Module["_ts_tree_get_changed_ranges_wasm"] = createExportWrapper("ts_tree_get_changed_ranges_wasm");
      var _ts_tree_cursor_new_wasm = Module["_ts_tree_cursor_new_wasm"] = createExportWrapper("ts_tree_cursor_new_wasm");
      var _ts_tree_cursor_delete_wasm = Module["_ts_tree_cursor_delete_wasm"] = createExportWrapper("ts_tree_cursor_delete_wasm");
      var _ts_tree_cursor_reset_wasm = Module["_ts_tree_cursor_reset_wasm"] = createExportWrapper("ts_tree_cursor_reset_wasm");
      var _ts_tree_cursor_goto_first_child_wasm = Module["_ts_tree_cursor_goto_first_child_wasm"] = createExportWrapper("ts_tree_cursor_goto_first_child_wasm");
      var _ts_tree_cursor_goto_next_sibling_wasm = Module["_ts_tree_cursor_goto_next_sibling_wasm"] = createExportWrapper("ts_tree_cursor_goto_next_sibling_wasm");
      var _ts_tree_cursor_goto_parent_wasm = Module["_ts_tree_cursor_goto_parent_wasm"] = createExportWrapper("ts_tree_cursor_goto_parent_wasm");
      var _ts_tree_cursor_current_node_type_id_wasm = Module["_ts_tree_cursor_current_node_type_id_wasm"] = createExportWrapper("ts_tree_cursor_current_node_type_id_wasm");
      var _ts_tree_cursor_current_node_is_named_wasm = Module["_ts_tree_cursor_current_node_is_named_wasm"] = createExportWrapper("ts_tree_cursor_current_node_is_named_wasm");
      var _ts_tree_cursor_current_node_is_missing_wasm = Module["_ts_tree_cursor_current_node_is_missing_wasm"] = createExportWrapper("ts_tree_cursor_current_node_is_missing_wasm");
      var _ts_tree_cursor_current_node_id_wasm = Module["_ts_tree_cursor_current_node_id_wasm"] = createExportWrapper("ts_tree_cursor_current_node_id_wasm");
      var _ts_tree_cursor_start_position_wasm = Module["_ts_tree_cursor_start_position_wasm"] = createExportWrapper("ts_tree_cursor_start_position_wasm");
      var _ts_tree_cursor_end_position_wasm = Module["_ts_tree_cursor_end_position_wasm"] = createExportWrapper("ts_tree_cursor_end_position_wasm");
      var _ts_tree_cursor_start_index_wasm = Module["_ts_tree_cursor_start_index_wasm"] = createExportWrapper("ts_tree_cursor_start_index_wasm");
      var _ts_tree_cursor_end_index_wasm = Module["_ts_tree_cursor_end_index_wasm"] = createExportWrapper("ts_tree_cursor_end_index_wasm");
      var _ts_tree_cursor_current_field_id_wasm = Module["_ts_tree_cursor_current_field_id_wasm"] = createExportWrapper("ts_tree_cursor_current_field_id_wasm");
      var _ts_tree_cursor_current_node_wasm = Module["_ts_tree_cursor_current_node_wasm"] = createExportWrapper("ts_tree_cursor_current_node_wasm");
      var _ts_node_symbol_wasm = Module["_ts_node_symbol_wasm"] = createExportWrapper("ts_node_symbol_wasm");
      var _ts_node_child_count_wasm = Module["_ts_node_child_count_wasm"] = createExportWrapper("ts_node_child_count_wasm");
      var _ts_node_named_child_count_wasm = Module["_ts_node_named_child_count_wasm"] = createExportWrapper("ts_node_named_child_count_wasm");
      var _ts_node_child_wasm = Module["_ts_node_child_wasm"] = createExportWrapper("ts_node_child_wasm");
      var _ts_node_named_child_wasm = Module["_ts_node_named_child_wasm"] = createExportWrapper("ts_node_named_child_wasm");
      var _ts_node_child_by_field_id_wasm = Module["_ts_node_child_by_field_id_wasm"] = createExportWrapper("ts_node_child_by_field_id_wasm");
      var _ts_node_next_sibling_wasm = Module["_ts_node_next_sibling_wasm"] = createExportWrapper("ts_node_next_sibling_wasm");
      var _ts_node_prev_sibling_wasm = Module["_ts_node_prev_sibling_wasm"] = createExportWrapper("ts_node_prev_sibling_wasm");
      var _ts_node_next_named_sibling_wasm = Module["_ts_node_next_named_sibling_wasm"] = createExportWrapper("ts_node_next_named_sibling_wasm");
      var _ts_node_prev_named_sibling_wasm = Module["_ts_node_prev_named_sibling_wasm"] = createExportWrapper("ts_node_prev_named_sibling_wasm");
      var _ts_node_parent_wasm = Module["_ts_node_parent_wasm"] = createExportWrapper("ts_node_parent_wasm");
      var _ts_node_descendant_for_index_wasm = Module["_ts_node_descendant_for_index_wasm"] = createExportWrapper("ts_node_descendant_for_index_wasm");
      var _ts_node_named_descendant_for_index_wasm = Module["_ts_node_named_descendant_for_index_wasm"] = createExportWrapper("ts_node_named_descendant_for_index_wasm");
      var _ts_node_descendant_for_position_wasm = Module["_ts_node_descendant_for_position_wasm"] = createExportWrapper("ts_node_descendant_for_position_wasm");
      var _ts_node_named_descendant_for_position_wasm = Module["_ts_node_named_descendant_for_position_wasm"] = createExportWrapper("ts_node_named_descendant_for_position_wasm");
      var _ts_node_start_point_wasm = Module["_ts_node_start_point_wasm"] = createExportWrapper("ts_node_start_point_wasm");
      var _ts_node_end_point_wasm = Module["_ts_node_end_point_wasm"] = createExportWrapper("ts_node_end_point_wasm");
      var _ts_node_start_index_wasm = Module["_ts_node_start_index_wasm"] = createExportWrapper("ts_node_start_index_wasm");
      var _ts_node_end_index_wasm = Module["_ts_node_end_index_wasm"] = createExportWrapper("ts_node_end_index_wasm");
      var _ts_node_to_string_wasm = Module["_ts_node_to_string_wasm"] = createExportWrapper("ts_node_to_string_wasm");
      var _ts_node_children_wasm = Module["_ts_node_children_wasm"] = createExportWrapper("ts_node_children_wasm");
      var _ts_node_named_children_wasm = Module["_ts_node_named_children_wasm"] = createExportWrapper("ts_node_named_children_wasm");
      var _ts_node_descendants_of_type_wasm = Module["_ts_node_descendants_of_type_wasm"] = createExportWrapper("ts_node_descendants_of_type_wasm");
      var _ts_node_is_named_wasm = Module["_ts_node_is_named_wasm"] = createExportWrapper("ts_node_is_named_wasm");
      var _ts_node_has_changes_wasm = Module["_ts_node_has_changes_wasm"] = createExportWrapper("ts_node_has_changes_wasm");
      var _ts_node_has_error_wasm = Module["_ts_node_has_error_wasm"] = createExportWrapper("ts_node_has_error_wasm");
      var _ts_node_is_missing_wasm = Module["_ts_node_is_missing_wasm"] = createExportWrapper("ts_node_is_missing_wasm");
      var _ts_query_matches_wasm = Module["_ts_query_matches_wasm"] = createExportWrapper("ts_query_matches_wasm");
      var _ts_query_captures_wasm = Module["_ts_query_captures_wasm"] = createExportWrapper("ts_query_captures_wasm");
      var ___errno_location = Module["___errno_location"] = createExportWrapper("__errno_location");
      var _iswalpha = Module["_iswalpha"] = createExportWrapper("iswalpha");
      var _towupper = Module["_towupper"] = createExportWrapper("towupper");
      var _iswlower = Module["_iswlower"] = createExportWrapper("iswlower");
      var _iswdigit = Module["_iswdigit"] = createExportWrapper("iswdigit");
      var _memchr = Module["_memchr"] = createExportWrapper("memchr");
      var _strlen = Module["_strlen"] = createExportWrapper("strlen");
      var stackSave = Module["stackSave"] = createExportWrapper("stackSave");
      var stackRestore = Module["stackRestore"] = createExportWrapper("stackRestore");
      var stackAlloc = Module["stackAlloc"] = createExportWrapper("stackAlloc");
      var _emscripten_stack_set_limits = Module["_emscripten_stack_set_limits"] = function() {
        return (_emscripten_stack_set_limits = Module["_emscripten_stack_set_limits"] = Module["asm"]["emscripten_stack_set_limits"]).apply(null, arguments);
      };
      var _emscripten_stack_get_free = Module["_emscripten_stack_get_free"] = function() {
        return (_emscripten_stack_get_free = Module["_emscripten_stack_get_free"] = Module["asm"]["emscripten_stack_get_free"]).apply(null, arguments);
      };
      var _emscripten_stack_get_end = Module["_emscripten_stack_get_end"] = function() {
        return (_emscripten_stack_get_end = Module["_emscripten_stack_get_end"] = Module["asm"]["emscripten_stack_get_end"]).apply(null, arguments);
      };
      var _setThrew = Module["_setThrew"] = createExportWrapper("setThrew");
      var __Znwm = Module["__Znwm"] = createExportWrapper("_Znwm");
      var __ZdlPv = Module["__ZdlPv"] = createExportWrapper("_ZdlPv");
      var __ZNKSt3__220__vector_base_commonILb1EE20__throw_length_errorEv = Module["__ZNKSt3__220__vector_base_commonILb1EE20__throw_length_errorEv"] = createExportWrapper("_ZNKSt3__220__vector_base_commonILb1EE20__throw_length_errorEv");
      var __ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEED2Ev = Module["__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEED2Ev"] = createExportWrapper("_ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEED2Ev");
      var __ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE9__grow_byEmmmmmm = Module["__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE9__grow_byEmmmmmm"] = createExportWrapper("_ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE9__grow_byEmmmmmm");
      var __ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE6__initEPKcm = Module["__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE6__initEPKcm"] = createExportWrapper("_ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE6__initEPKcm");
      var __ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE7reserveEm = Module["__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE7reserveEm"] = createExportWrapper("_ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE7reserveEm");
      var __ZNKSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE4copyEPcmm = Module["__ZNKSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE4copyEPcmm"] = createExportWrapper("_ZNKSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE4copyEPcmm");
      var __ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE9push_backEc = Module["__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE9push_backEc"] = createExportWrapper("_ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE9push_backEc");
      var __ZNSt3__212basic_stringIwNS_11char_traitsIwEENS_9allocatorIwEEED2Ev = Module["__ZNSt3__212basic_stringIwNS_11char_traitsIwEENS_9allocatorIwEEED2Ev"] = createExportWrapper("_ZNSt3__212basic_stringIwNS_11char_traitsIwEENS_9allocatorIwEEED2Ev");
      var __ZNSt3__212basic_stringIwNS_11char_traitsIwEENS_9allocatorIwEEE9push_backEw = Module["__ZNSt3__212basic_stringIwNS_11char_traitsIwEENS_9allocatorIwEEE9push_backEw"] = createExportWrapper("_ZNSt3__212basic_stringIwNS_11char_traitsIwEENS_9allocatorIwEEE9push_backEw");
      var dynCall_jiji = Module["dynCall_jiji"] = createExportWrapper("dynCall_jiji");
      var _orig$ts_parser_timeout_micros = Module["_orig$ts_parser_timeout_micros"] = createExportWrapper("orig$ts_parser_timeout_micros");
      var _orig$ts_parser_set_timeout_micros = Module["_orig$ts_parser_set_timeout_micros"] = createExportWrapper("orig$ts_parser_set_timeout_micros");
      var _stderr = Module["_stderr"] = 7088;
      var _TRANSFER_BUFFER = Module["_TRANSFER_BUFFER"] = 7472;
      var ___THREW__ = Module["___THREW__"] = 8116;
      var ___threwValue = Module["___threwValue"] = 8120;
      var ___cxa_new_handler = Module["___cxa_new_handler"] = 8112;
      var ___data_end = Module["___data_end"] = 8124;
      if (!Object.getOwnPropertyDescriptor(Module, "intArrayFromString")) Module["intArrayFromString"] = function() {
        abort2("'intArrayFromString' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "intArrayToString")) Module["intArrayToString"] = function() {
        abort2("'intArrayToString' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "ccall")) Module["ccall"] = function() {
        abort2("'ccall' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "cwrap")) Module["cwrap"] = function() {
        abort2("'cwrap' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "setValue")) Module["setValue"] = function() {
        abort2("'setValue' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "getValue")) Module["getValue"] = function() {
        abort2("'getValue' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      Module["allocate"] = allocate;
      if (!Object.getOwnPropertyDescriptor(Module, "UTF8ArrayToString")) Module["UTF8ArrayToString"] = function() {
        abort2("'UTF8ArrayToString' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "UTF8ToString")) Module["UTF8ToString"] = function() {
        abort2("'UTF8ToString' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "stringToUTF8Array")) Module["stringToUTF8Array"] = function() {
        abort2("'stringToUTF8Array' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "stringToUTF8")) Module["stringToUTF8"] = function() {
        abort2("'stringToUTF8' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "lengthBytesUTF8")) Module["lengthBytesUTF8"] = function() {
        abort2("'lengthBytesUTF8' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "stackTrace")) Module["stackTrace"] = function() {
        abort2("'stackTrace' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "addOnPreRun")) Module["addOnPreRun"] = function() {
        abort2("'addOnPreRun' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "addOnInit")) Module["addOnInit"] = function() {
        abort2("'addOnInit' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "addOnPreMain")) Module["addOnPreMain"] = function() {
        abort2("'addOnPreMain' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "addOnExit")) Module["addOnExit"] = function() {
        abort2("'addOnExit' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "addOnPostRun")) Module["addOnPostRun"] = function() {
        abort2("'addOnPostRun' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "writeStringToMemory")) Module["writeStringToMemory"] = function() {
        abort2("'writeStringToMemory' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "writeArrayToMemory")) Module["writeArrayToMemory"] = function() {
        abort2("'writeArrayToMemory' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "writeAsciiToMemory")) Module["writeAsciiToMemory"] = function() {
        abort2("'writeAsciiToMemory' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "addRunDependency")) Module["addRunDependency"] = function() {
        abort2("'addRunDependency' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "removeRunDependency")) Module["removeRunDependency"] = function() {
        abort2("'removeRunDependency' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "FS_createFolder")) Module["FS_createFolder"] = function() {
        abort2("'FS_createFolder' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "FS_createPath")) Module["FS_createPath"] = function() {
        abort2("'FS_createPath' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "FS_createDataFile")) Module["FS_createDataFile"] = function() {
        abort2("'FS_createDataFile' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "FS_createPreloadedFile")) Module["FS_createPreloadedFile"] = function() {
        abort2("'FS_createPreloadedFile' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "FS_createLazyFile")) Module["FS_createLazyFile"] = function() {
        abort2("'FS_createLazyFile' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "FS_createLink")) Module["FS_createLink"] = function() {
        abort2("'FS_createLink' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "FS_createDevice")) Module["FS_createDevice"] = function() {
        abort2("'FS_createDevice' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "FS_unlink")) Module["FS_unlink"] = function() {
        abort2("'FS_unlink' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "getLEB")) Module["getLEB"] = function() {
        abort2("'getLEB' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "getFunctionTables")) Module["getFunctionTables"] = function() {
        abort2("'getFunctionTables' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "alignFunctionTables")) Module["alignFunctionTables"] = function() {
        abort2("'alignFunctionTables' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "registerFunctions")) Module["registerFunctions"] = function() {
        abort2("'registerFunctions' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "addFunction")) Module["addFunction"] = function() {
        abort2("'addFunction' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "removeFunction")) Module["removeFunction"] = function() {
        abort2("'removeFunction' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "getFuncWrapper")) Module["getFuncWrapper"] = function() {
        abort2("'getFuncWrapper' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "prettyPrint")) Module["prettyPrint"] = function() {
        abort2("'prettyPrint' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "dynCall")) Module["dynCall"] = function() {
        abort2("'dynCall' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "getCompilerSetting")) Module["getCompilerSetting"] = function() {
        abort2("'getCompilerSetting' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "print")) Module["print"] = function() {
        abort2("'print' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "printErr")) Module["printErr"] = function() {
        abort2("'printErr' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "getTempRet0")) Module["getTempRet0"] = function() {
        abort2("'getTempRet0' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "setTempRet0")) Module["setTempRet0"] = function() {
        abort2("'setTempRet0' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "callMain")) Module["callMain"] = function() {
        abort2("'callMain' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "abort")) Module["abort"] = function() {
        abort2("'abort' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "stringToNewUTF8")) Module["stringToNewUTF8"] = function() {
        abort2("'stringToNewUTF8' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "setFileTime")) Module["setFileTime"] = function() {
        abort2("'setFileTime' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "emscripten_realloc_buffer")) Module["emscripten_realloc_buffer"] = function() {
        abort2("'emscripten_realloc_buffer' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "ENV")) Module["ENV"] = function() {
        abort2("'ENV' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "ERRNO_CODES")) Module["ERRNO_CODES"] = function() {
        abort2("'ERRNO_CODES' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "ERRNO_MESSAGES")) Module["ERRNO_MESSAGES"] = function() {
        abort2("'ERRNO_MESSAGES' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "setErrNo")) Module["setErrNo"] = function() {
        abort2("'setErrNo' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "inetPton4")) Module["inetPton4"] = function() {
        abort2("'inetPton4' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "inetNtop4")) Module["inetNtop4"] = function() {
        abort2("'inetNtop4' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "inetPton6")) Module["inetPton6"] = function() {
        abort2("'inetPton6' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "inetNtop6")) Module["inetNtop6"] = function() {
        abort2("'inetNtop6' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "readSockaddr")) Module["readSockaddr"] = function() {
        abort2("'readSockaddr' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "writeSockaddr")) Module["writeSockaddr"] = function() {
        abort2("'writeSockaddr' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "DNS")) Module["DNS"] = function() {
        abort2("'DNS' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "getHostByName")) Module["getHostByName"] = function() {
        abort2("'getHostByName' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "GAI_ERRNO_MESSAGES")) Module["GAI_ERRNO_MESSAGES"] = function() {
        abort2("'GAI_ERRNO_MESSAGES' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "Protocols")) Module["Protocols"] = function() {
        abort2("'Protocols' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "Sockets")) Module["Sockets"] = function() {
        abort2("'Sockets' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "getRandomDevice")) Module["getRandomDevice"] = function() {
        abort2("'getRandomDevice' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "traverseStack")) Module["traverseStack"] = function() {
        abort2("'traverseStack' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "UNWIND_CACHE")) Module["UNWIND_CACHE"] = function() {
        abort2("'UNWIND_CACHE' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "withBuiltinMalloc")) Module["withBuiltinMalloc"] = function() {
        abort2("'withBuiltinMalloc' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "readAsmConstArgsArray")) Module["readAsmConstArgsArray"] = function() {
        abort2("'readAsmConstArgsArray' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "readAsmConstArgs")) Module["readAsmConstArgs"] = function() {
        abort2("'readAsmConstArgs' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "mainThreadEM_ASM")) Module["mainThreadEM_ASM"] = function() {
        abort2("'mainThreadEM_ASM' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "jstoi_q")) Module["jstoi_q"] = function() {
        abort2("'jstoi_q' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "jstoi_s")) Module["jstoi_s"] = function() {
        abort2("'jstoi_s' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "getExecutableName")) Module["getExecutableName"] = function() {
        abort2("'getExecutableName' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "listenOnce")) Module["listenOnce"] = function() {
        abort2("'listenOnce' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "autoResumeAudioContext")) Module["autoResumeAudioContext"] = function() {
        abort2("'autoResumeAudioContext' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "dynCallLegacy")) Module["dynCallLegacy"] = function() {
        abort2("'dynCallLegacy' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "getDynCaller")) Module["getDynCaller"] = function() {
        abort2("'getDynCaller' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "dynCall")) Module["dynCall"] = function() {
        abort2("'dynCall' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "callRuntimeCallbacks")) Module["callRuntimeCallbacks"] = function() {
        abort2("'callRuntimeCallbacks' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "runtimeKeepaliveCounter")) Module["runtimeKeepaliveCounter"] = function() {
        abort2("'runtimeKeepaliveCounter' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "keepRuntimeAlive")) Module["keepRuntimeAlive"] = function() {
        abort2("'keepRuntimeAlive' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "runtimeKeepalivePush")) Module["runtimeKeepalivePush"] = function() {
        abort2("'runtimeKeepalivePush' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "runtimeKeepalivePop")) Module["runtimeKeepalivePop"] = function() {
        abort2("'runtimeKeepalivePop' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "callUserCallback")) Module["callUserCallback"] = function() {
        abort2("'callUserCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "maybeExit")) Module["maybeExit"] = function() {
        abort2("'maybeExit' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "asmjsMangle")) Module["asmjsMangle"] = function() {
        abort2("'asmjsMangle' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "reallyNegative")) Module["reallyNegative"] = function() {
        abort2("'reallyNegative' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "unSign")) Module["unSign"] = function() {
        abort2("'unSign' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "reSign")) Module["reSign"] = function() {
        abort2("'reSign' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "formatString")) Module["formatString"] = function() {
        abort2("'formatString' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "PATH")) Module["PATH"] = function() {
        abort2("'PATH' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "PATH_FS")) Module["PATH_FS"] = function() {
        abort2("'PATH_FS' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "SYSCALLS")) Module["SYSCALLS"] = function() {
        abort2("'SYSCALLS' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "syscallMmap2")) Module["syscallMmap2"] = function() {
        abort2("'syscallMmap2' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "syscallMunmap")) Module["syscallMunmap"] = function() {
        abort2("'syscallMunmap' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "getSocketFromFD")) Module["getSocketFromFD"] = function() {
        abort2("'getSocketFromFD' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "getSocketAddress")) Module["getSocketAddress"] = function() {
        abort2("'getSocketAddress' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "JSEvents")) Module["JSEvents"] = function() {
        abort2("'JSEvents' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "registerKeyEventCallback")) Module["registerKeyEventCallback"] = function() {
        abort2("'registerKeyEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "specialHTMLTargets")) Module["specialHTMLTargets"] = function() {
        abort2("'specialHTMLTargets' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "maybeCStringToJsString")) Module["maybeCStringToJsString"] = function() {
        abort2("'maybeCStringToJsString' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "findEventTarget")) Module["findEventTarget"] = function() {
        abort2("'findEventTarget' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "findCanvasEventTarget")) Module["findCanvasEventTarget"] = function() {
        abort2("'findCanvasEventTarget' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "getBoundingClientRect")) Module["getBoundingClientRect"] = function() {
        abort2("'getBoundingClientRect' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "fillMouseEventData")) Module["fillMouseEventData"] = function() {
        abort2("'fillMouseEventData' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "registerMouseEventCallback")) Module["registerMouseEventCallback"] = function() {
        abort2("'registerMouseEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "registerWheelEventCallback")) Module["registerWheelEventCallback"] = function() {
        abort2("'registerWheelEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "registerUiEventCallback")) Module["registerUiEventCallback"] = function() {
        abort2("'registerUiEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "registerFocusEventCallback")) Module["registerFocusEventCallback"] = function() {
        abort2("'registerFocusEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "fillDeviceOrientationEventData")) Module["fillDeviceOrientationEventData"] = function() {
        abort2("'fillDeviceOrientationEventData' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "registerDeviceOrientationEventCallback")) Module["registerDeviceOrientationEventCallback"] = function() {
        abort2("'registerDeviceOrientationEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "fillDeviceMotionEventData")) Module["fillDeviceMotionEventData"] = function() {
        abort2("'fillDeviceMotionEventData' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "registerDeviceMotionEventCallback")) Module["registerDeviceMotionEventCallback"] = function() {
        abort2("'registerDeviceMotionEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "screenOrientation")) Module["screenOrientation"] = function() {
        abort2("'screenOrientation' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "fillOrientationChangeEventData")) Module["fillOrientationChangeEventData"] = function() {
        abort2("'fillOrientationChangeEventData' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "registerOrientationChangeEventCallback")) Module["registerOrientationChangeEventCallback"] = function() {
        abort2("'registerOrientationChangeEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "fillFullscreenChangeEventData")) Module["fillFullscreenChangeEventData"] = function() {
        abort2("'fillFullscreenChangeEventData' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "registerFullscreenChangeEventCallback")) Module["registerFullscreenChangeEventCallback"] = function() {
        abort2("'registerFullscreenChangeEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "registerRestoreOldStyle")) Module["registerRestoreOldStyle"] = function() {
        abort2("'registerRestoreOldStyle' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "hideEverythingExceptGivenElement")) Module["hideEverythingExceptGivenElement"] = function() {
        abort2("'hideEverythingExceptGivenElement' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "restoreHiddenElements")) Module["restoreHiddenElements"] = function() {
        abort2("'restoreHiddenElements' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "setLetterbox")) Module["setLetterbox"] = function() {
        abort2("'setLetterbox' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "currentFullscreenStrategy")) Module["currentFullscreenStrategy"] = function() {
        abort2("'currentFullscreenStrategy' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "restoreOldWindowedStyle")) Module["restoreOldWindowedStyle"] = function() {
        abort2("'restoreOldWindowedStyle' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "softFullscreenResizeWebGLRenderTarget")) Module["softFullscreenResizeWebGLRenderTarget"] = function() {
        abort2("'softFullscreenResizeWebGLRenderTarget' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "doRequestFullscreen")) Module["doRequestFullscreen"] = function() {
        abort2("'doRequestFullscreen' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "fillPointerlockChangeEventData")) Module["fillPointerlockChangeEventData"] = function() {
        abort2("'fillPointerlockChangeEventData' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "registerPointerlockChangeEventCallback")) Module["registerPointerlockChangeEventCallback"] = function() {
        abort2("'registerPointerlockChangeEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "registerPointerlockErrorEventCallback")) Module["registerPointerlockErrorEventCallback"] = function() {
        abort2("'registerPointerlockErrorEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "requestPointerLock")) Module["requestPointerLock"] = function() {
        abort2("'requestPointerLock' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "fillVisibilityChangeEventData")) Module["fillVisibilityChangeEventData"] = function() {
        abort2("'fillVisibilityChangeEventData' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "registerVisibilityChangeEventCallback")) Module["registerVisibilityChangeEventCallback"] = function() {
        abort2("'registerVisibilityChangeEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "registerTouchEventCallback")) Module["registerTouchEventCallback"] = function() {
        abort2("'registerTouchEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "fillGamepadEventData")) Module["fillGamepadEventData"] = function() {
        abort2("'fillGamepadEventData' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "registerGamepadEventCallback")) Module["registerGamepadEventCallback"] = function() {
        abort2("'registerGamepadEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "registerBeforeUnloadEventCallback")) Module["registerBeforeUnloadEventCallback"] = function() {
        abort2("'registerBeforeUnloadEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "fillBatteryEventData")) Module["fillBatteryEventData"] = function() {
        abort2("'fillBatteryEventData' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "battery")) Module["battery"] = function() {
        abort2("'battery' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "registerBatteryEventCallback")) Module["registerBatteryEventCallback"] = function() {
        abort2("'registerBatteryEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "setCanvasElementSize")) Module["setCanvasElementSize"] = function() {
        abort2("'setCanvasElementSize' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "getCanvasElementSize")) Module["getCanvasElementSize"] = function() {
        abort2("'getCanvasElementSize' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "polyfillSetImmediate")) Module["polyfillSetImmediate"] = function() {
        abort2("'polyfillSetImmediate' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "demangle")) Module["demangle"] = function() {
        abort2("'demangle' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "demangleAll")) Module["demangleAll"] = function() {
        abort2("'demangleAll' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "jsStackTrace")) Module["jsStackTrace"] = function() {
        abort2("'jsStackTrace' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "stackTrace")) Module["stackTrace"] = function() {
        abort2("'stackTrace' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "getEnvStrings")) Module["getEnvStrings"] = function() {
        abort2("'getEnvStrings' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "checkWasiClock")) Module["checkWasiClock"] = function() {
        abort2("'checkWasiClock' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "writeI53ToI64")) Module["writeI53ToI64"] = function() {
        abort2("'writeI53ToI64' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "writeI53ToI64Clamped")) Module["writeI53ToI64Clamped"] = function() {
        abort2("'writeI53ToI64Clamped' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "writeI53ToI64Signaling")) Module["writeI53ToI64Signaling"] = function() {
        abort2("'writeI53ToI64Signaling' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "writeI53ToU64Clamped")) Module["writeI53ToU64Clamped"] = function() {
        abort2("'writeI53ToU64Clamped' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "writeI53ToU64Signaling")) Module["writeI53ToU64Signaling"] = function() {
        abort2("'writeI53ToU64Signaling' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "readI53FromI64")) Module["readI53FromI64"] = function() {
        abort2("'readI53FromI64' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "readI53FromU64")) Module["readI53FromU64"] = function() {
        abort2("'readI53FromU64' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "convertI32PairToI53")) Module["convertI32PairToI53"] = function() {
        abort2("'convertI32PairToI53' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "convertU32PairToI53")) Module["convertU32PairToI53"] = function() {
        abort2("'convertU32PairToI53' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "resolveGlobalSymbol")) Module["resolveGlobalSymbol"] = function() {
        abort2("'resolveGlobalSymbol' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "GOT")) Module["GOT"] = function() {
        abort2("'GOT' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "GOTHandler")) Module["GOTHandler"] = function() {
        abort2("'GOTHandler' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "isInternalSym")) Module["isInternalSym"] = function() {
        abort2("'isInternalSym' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "updateGOT")) Module["updateGOT"] = function() {
        abort2("'updateGOT' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "relocateExports")) Module["relocateExports"] = function() {
        abort2("'relocateExports' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "reportUndefinedSymbols")) Module["reportUndefinedSymbols"] = function() {
        abort2("'reportUndefinedSymbols' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "DLFCN")) Module["DLFCN"] = function() {
        abort2("'DLFCN' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "LDSO")) Module["LDSO"] = function() {
        abort2("'LDSO' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "createInvokeFunction")) Module["createInvokeFunction"] = function() {
        abort2("'createInvokeFunction' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "getMemory")) Module["getMemory"] = function() {
        abort2("'getMemory' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "fetchBinary")) Module["fetchBinary"] = function() {
        abort2("'fetchBinary' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "getDylinkMetadata")) Module["getDylinkMetadata"] = function() {
        abort2("'getDylinkMetadata' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "mergeLibSymbols")) Module["mergeLibSymbols"] = function() {
        abort2("'mergeLibSymbols' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "loadWebAssemblyModule")) Module["loadWebAssemblyModule"] = function() {
        abort2("'loadWebAssemblyModule' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "loadDynamicLibrary")) Module["loadDynamicLibrary"] = function() {
        abort2("'loadDynamicLibrary' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "preloadDylibs")) Module["preloadDylibs"] = function() {
        abort2("'preloadDylibs' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "uncaughtExceptionCount")) Module["uncaughtExceptionCount"] = function() {
        abort2("'uncaughtExceptionCount' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "exceptionLast")) Module["exceptionLast"] = function() {
        abort2("'exceptionLast' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "exceptionCaught")) Module["exceptionCaught"] = function() {
        abort2("'exceptionCaught' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "ExceptionInfoAttrs")) Module["ExceptionInfoAttrs"] = function() {
        abort2("'ExceptionInfoAttrs' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "ExceptionInfo")) Module["ExceptionInfo"] = function() {
        abort2("'ExceptionInfo' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "CatchInfo")) Module["CatchInfo"] = function() {
        abort2("'CatchInfo' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "exception_addRef")) Module["exception_addRef"] = function() {
        abort2("'exception_addRef' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "exception_decRef")) Module["exception_decRef"] = function() {
        abort2("'exception_decRef' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "Browser")) Module["Browser"] = function() {
        abort2("'Browser' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "funcWrappers")) Module["funcWrappers"] = function() {
        abort2("'funcWrappers' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "getFuncWrapper")) Module["getFuncWrapper"] = function() {
        abort2("'getFuncWrapper' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "setMainLoop")) Module["setMainLoop"] = function() {
        abort2("'setMainLoop' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "tempFixedLengthArray")) Module["tempFixedLengthArray"] = function() {
        abort2("'tempFixedLengthArray' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "miniTempWebGLFloatBuffers")) Module["miniTempWebGLFloatBuffers"] = function() {
        abort2("'miniTempWebGLFloatBuffers' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "heapObjectForWebGLType")) Module["heapObjectForWebGLType"] = function() {
        abort2("'heapObjectForWebGLType' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "heapAccessShiftForWebGLHeap")) Module["heapAccessShiftForWebGLHeap"] = function() {
        abort2("'heapAccessShiftForWebGLHeap' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "GL")) Module["GL"] = function() {
        abort2("'GL' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "emscriptenWebGLGet")) Module["emscriptenWebGLGet"] = function() {
        abort2("'emscriptenWebGLGet' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "computeUnpackAlignedImageSize")) Module["computeUnpackAlignedImageSize"] = function() {
        abort2("'computeUnpackAlignedImageSize' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "emscriptenWebGLGetTexPixelData")) Module["emscriptenWebGLGetTexPixelData"] = function() {
        abort2("'emscriptenWebGLGetTexPixelData' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "emscriptenWebGLGetUniform")) Module["emscriptenWebGLGetUniform"] = function() {
        abort2("'emscriptenWebGLGetUniform' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "webglGetUniformLocation")) Module["webglGetUniformLocation"] = function() {
        abort2("'webglGetUniformLocation' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "webglPrepareUniformLocationsBeforeFirstUse")) Module["webglPrepareUniformLocationsBeforeFirstUse"] = function() {
        abort2("'webglPrepareUniformLocationsBeforeFirstUse' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "webglGetLeftBracePos")) Module["webglGetLeftBracePos"] = function() {
        abort2("'webglGetLeftBracePos' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "emscriptenWebGLGetVertexAttrib")) Module["emscriptenWebGLGetVertexAttrib"] = function() {
        abort2("'emscriptenWebGLGetVertexAttrib' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "writeGLArray")) Module["writeGLArray"] = function() {
        abort2("'writeGLArray' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "AL")) Module["AL"] = function() {
        abort2("'AL' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "SDL_unicode")) Module["SDL_unicode"] = function() {
        abort2("'SDL_unicode' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "SDL_ttfContext")) Module["SDL_ttfContext"] = function() {
        abort2("'SDL_ttfContext' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "SDL_audio")) Module["SDL_audio"] = function() {
        abort2("'SDL_audio' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "SDL")) Module["SDL"] = function() {
        abort2("'SDL' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "SDL_gfx")) Module["SDL_gfx"] = function() {
        abort2("'SDL_gfx' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "GLUT")) Module["GLUT"] = function() {
        abort2("'GLUT' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "EGL")) Module["EGL"] = function() {
        abort2("'EGL' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "GLFW_Window")) Module["GLFW_Window"] = function() {
        abort2("'GLFW_Window' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "GLFW")) Module["GLFW"] = function() {
        abort2("'GLFW' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "GLEW")) Module["GLEW"] = function() {
        abort2("'GLEW' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "IDBStore")) Module["IDBStore"] = function() {
        abort2("'IDBStore' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "runAndAbortIfError")) Module["runAndAbortIfError"] = function() {
        abort2("'runAndAbortIfError' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "warnOnce")) Module["warnOnce"] = function() {
        abort2("'warnOnce' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "stackSave")) Module["stackSave"] = function() {
        abort2("'stackSave' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "stackRestore")) Module["stackRestore"] = function() {
        abort2("'stackRestore' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "stackAlloc")) Module["stackAlloc"] = function() {
        abort2("'stackAlloc' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "AsciiToString")) Module["AsciiToString"] = function() {
        abort2("'AsciiToString' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "stringToAscii")) Module["stringToAscii"] = function() {
        abort2("'stringToAscii' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "UTF16ToString")) Module["UTF16ToString"] = function() {
        abort2("'UTF16ToString' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "stringToUTF16")) Module["stringToUTF16"] = function() {
        abort2("'stringToUTF16' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "lengthBytesUTF16")) Module["lengthBytesUTF16"] = function() {
        abort2("'lengthBytesUTF16' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "UTF32ToString")) Module["UTF32ToString"] = function() {
        abort2("'UTF32ToString' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "stringToUTF32")) Module["stringToUTF32"] = function() {
        abort2("'stringToUTF32' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "lengthBytesUTF32")) Module["lengthBytesUTF32"] = function() {
        abort2("'lengthBytesUTF32' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "allocateUTF8")) Module["allocateUTF8"] = function() {
        abort2("'allocateUTF8' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "allocateUTF8OnStack")) Module["allocateUTF8OnStack"] = function() {
        abort2("'allocateUTF8OnStack' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      Module["writeStackCookie"] = writeStackCookie;
      Module["checkStackCookie"] = checkStackCookie;
      if (!Object.getOwnPropertyDescriptor(Module, "intArrayFromBase64")) Module["intArrayFromBase64"] = function() {
        abort2("'intArrayFromBase64' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "tryParseAsDataURI")) Module["tryParseAsDataURI"] = function() {
        abort2("'tryParseAsDataURI' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      };
      if (!Object.getOwnPropertyDescriptor(Module, "ALLOC_NORMAL")) Object.defineProperty(Module, "ALLOC_NORMAL", { configurable: true, get: function() {
        abort2("'ALLOC_NORMAL' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      } });
      if (!Object.getOwnPropertyDescriptor(Module, "ALLOC_STACK")) Object.defineProperty(Module, "ALLOC_STACK", { configurable: true, get: function() {
        abort2("'ALLOC_STACK' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
      } });
      var calledRun;
      function ExitStatus(status) {
        this.name = "ExitStatus";
        this.message = "Program terminated with exit(" + status + ")";
        this.status = status;
      }
      var calledMain = false;
      dependenciesFulfilled = function runCaller() {
        if (!calledRun) run5();
        if (!calledRun) dependenciesFulfilled = runCaller;
      };
      function callMain(args) {
        assert10(runDependencies == 0, 'cannot call main when async dependencies remain! (listen on Module["onRuntimeInitialized"])');
        assert10(__ATPRERUN__.length == 0, "cannot call main when preRun functions remain to be called");
        var entryFunction = Module["_main"];
        if (!entryFunction) return;
        args = args || [];
        var argc = args.length + 1;
        var argv2 = stackAlloc((argc + 1) * 4);
        HEAP32[argv2 >> 2] = allocateUTF8OnStack(thisProgram);
        for (var i6 = 1; i6 < argc; i6++) {
          HEAP32[(argv2 >> 2) + i6] = allocateUTF8OnStack(args[i6 - 1]);
        }
        HEAP32[(argv2 >> 2) + argc] = 0;
        try {
          var ret = entryFunction(argc, argv2);
          exit2(
            ret,
            /* implicit = */
            true
          );
        } catch (e5) {
          if (e5 instanceof ExitStatus) {
            return;
          } else if (e5 == "unwind") {
            return;
          } else {
            var toLog = e5;
            if (e5 && typeof e5 === "object" && e5.stack) {
              toLog = [e5, e5.stack];
            }
            err2("exception thrown: " + toLog);
            quit_(1, e5);
          }
        } finally {
          calledMain = true;
        }
      }
      function stackCheckInit() {
        _emscripten_stack_set_limits(5251008, 8128);
        writeStackCookie();
      }
      var dylibsLoaded = false;
      async function run5(args) {
        args = args || arguments_;
        await wasmInstantiatePromise;
        if (runDependencies > 0) {
          return;
        }
        stackCheckInit();
        if (!dylibsLoaded) {
          preloadDylibs();
          dylibsLoaded = true;
          if (runDependencies > 0) {
            return;
          }
        }
        preRun();
        if (runDependencies > 0) {
          return;
        }
        function doRun() {
          if (calledRun) return;
          calledRun = true;
          Module["calledRun"] = true;
          if (ABORT) return;
          initRuntime();
          preMain();
          if (Module["onRuntimeInitialized"]) Module["onRuntimeInitialized"]();
          if (shouldRunNow) callMain(args);
          postRun();
        }
        doRun();
        checkStackCookie();
      }
      Module["run"] = run5;
      function checkUnflushedContent() {
        var oldOut = out;
        var oldErr = err2;
        var has3 = false;
        out = err2 = function(x3) {
          has3 = true;
        };
        try {
          var flush = Module["_fflush"];
          if (flush) flush(0);
        } catch (e5) {
        }
        out = oldOut;
        err2 = oldErr;
        if (has3) {
          warnOnce2("stdio streams had content in them that was not flushed. you should set EXIT_RUNTIME to 1 (see the FAQ), or make sure to emit a newline when you printf etc.");
          warnOnce2("(this may also be due to not including full filesystem support - try building with -s FORCE_FILESYSTEM=1)");
        }
      }
      function exit2(status, implicit) {
        EXITSTATUS = status;
        checkUnflushedContent();
        if (implicit && keepRuntimeAlive() && status === 0) {
          return;
        }
        if (keepRuntimeAlive()) {
          if (!implicit) {
            var msg5 = "program exited (with status: " + status + "), but EXIT_RUNTIME is not set, so halting execution but not exiting the runtime or preventing further async execution (build with EXIT_RUNTIME=1, if you want a true shutdown)";
            err2(msg5);
          }
        } else {
          exitRuntime();
          if (Module["onExit"]) Module["onExit"](status);
          ABORT = true;
        }
        quit_(status, new ExitStatus(status));
      }
      if (Module["preInit"]) {
        if (typeof Module["preInit"] == "function") Module["preInit"] = [Module["preInit"]];
        while (Module["preInit"].length > 0) {
          Module["preInit"].pop()();
        }
      }
      var shouldRunNow = true;
      if (Module["noInitialRun"]) shouldRunNow = false;
      const C3 = Module;
      const INTERNAL2 = {};
      const SIZE_OF_INT = 4;
      const SIZE_OF_NODE = 5 * SIZE_OF_INT;
      const SIZE_OF_POINT = 2 * SIZE_OF_INT;
      const SIZE_OF_RANGE = 2 * SIZE_OF_INT + 2 * SIZE_OF_POINT;
      const ZERO_POINT = { row: 0, column: 0 };
      const QUERY_WORD_REGEX = /[\w-.]*/g;
      const PREDICATE_STEP_TYPE_CAPTURE = 1;
      const PREDICATE_STEP_TYPE_STRING = 2;
      const LANGUAGE_FUNCTION_REGEX = /^_?tree_sitter_\w+/;
      var VERSION;
      var MIN_COMPATIBLE_VERSION;
      var TRANSFER_BUFFER;
      var currentParseCallback;
      var currentLogCallback;
      class ParserImpl {
        static init() {
          TRANSFER_BUFFER = C3._ts_init();
          VERSION = getValue(TRANSFER_BUFFER, "i32");
          MIN_COMPATIBLE_VERSION = getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
        }
        initialize() {
          C3._ts_parser_new_wasm();
          this[0] = getValue(TRANSFER_BUFFER, "i32");
          this[1] = getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
        }
        delete() {
          C3._ts_parser_delete(this[0]);
          C3._free(this[1]);
          this[0] = 0;
          this[1] = 0;
        }
        setLanguage(language) {
          let address;
          if (!language) {
            address = 0;
            language = null;
          } else if (language.constructor === Language) {
            address = language[0];
            const version4 = C3._ts_language_version(address);
            if (version4 < MIN_COMPATIBLE_VERSION || VERSION < version4) {
              throw new Error(
                `Incompatible language version ${version4}. Compatibility range ${MIN_COMPATIBLE_VERSION} through ${VERSION}.`
              );
            }
          } else {
            throw new Error("Argument must be a Language");
          }
          this.language = language;
          C3._ts_parser_set_language(this[0], address);
          return this;
        }
        getLanguage() {
          return this.language;
        }
        parse(callback, oldTree, options) {
          if (typeof callback === "string") {
            currentParseCallback = (index2, _3, endIndex) => callback.slice(index2, endIndex);
          } else if (typeof callback === "function") {
            currentParseCallback = callback;
          } else {
            throw new Error("Argument must be a string or a function");
          }
          if (this.logCallback) {
            currentLogCallback = this.logCallback;
            C3._ts_parser_enable_logger_wasm(this[0], 1);
          } else {
            currentLogCallback = null;
            C3._ts_parser_enable_logger_wasm(this[0], 0);
          }
          let rangeCount = 0;
          let rangeAddress = 0;
          if (options && options.includedRanges) {
            rangeCount = options.includedRanges.length;
            rangeAddress = C3._calloc(rangeCount, SIZE_OF_RANGE);
            let address = rangeAddress;
            for (let i6 = 0; i6 < rangeCount; i6++) {
              marshalRange(address, options.includedRanges[i6]);
              address += SIZE_OF_RANGE;
            }
          }
          const treeAddress = C3._ts_parser_parse_wasm(
            this[0],
            this[1],
            oldTree ? oldTree[0] : 0,
            rangeAddress,
            rangeCount
          );
          if (!treeAddress) {
            currentParseCallback = null;
            currentLogCallback = null;
            throw new Error("Parsing failed");
          }
          const result2 = new Tree(INTERNAL2, treeAddress, this.language, currentParseCallback);
          currentParseCallback = null;
          currentLogCallback = null;
          return result2;
        }
        reset() {
          C3._ts_parser_reset(this[0]);
        }
        setTimeoutMicros(timeout) {
          C3._ts_parser_set_timeout_micros(this[0], timeout);
        }
        getTimeoutMicros() {
          return C3._ts_parser_timeout_micros(this[0]);
        }
        setLogger(callback) {
          if (!callback) {
            callback = null;
          } else if (typeof callback !== "function") {
            throw new Error("Logger callback must be a function");
          }
          this.logCallback = callback;
          return this;
        }
        getLogger() {
          return this.logCallback;
        }
      }
      class Tree {
        constructor(internal, address, language, textCallback) {
          assertInternal(internal);
          this[0] = address;
          this.language = language;
          this.textCallback = textCallback;
        }
        copy() {
          const address = C3._ts_tree_copy(this[0]);
          return new Tree(INTERNAL2, address, this.language, this.textCallback);
        }
        delete() {
          C3._ts_tree_delete(this[0]);
          this[0] = 0;
        }
        edit(edit) {
          marshalEdit(edit);
          C3._ts_tree_edit_wasm(this[0]);
        }
        get rootNode() {
          C3._ts_tree_root_node_wasm(this[0]);
          return unmarshalNode(this);
        }
        getLanguage() {
          return this.language;
        }
        walk() {
          return this.rootNode.walk();
        }
        getChangedRanges(other) {
          if (other.constructor !== Tree) {
            throw new TypeError("Argument must be a Tree");
          }
          C3._ts_tree_get_changed_ranges_wasm(this[0], other[0]);
          const count = getValue(TRANSFER_BUFFER, "i32");
          const buffer3 = getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
          const result2 = new Array(count);
          if (count > 0) {
            let address = buffer3;
            for (let i6 = 0; i6 < count; i6++) {
              result2[i6] = unmarshalRange(address);
              address += SIZE_OF_RANGE;
            }
            C3._free(buffer3);
          }
          return result2;
        }
      }
      class Node7 {
        constructor(internal, tree) {
          assertInternal(internal);
          this.tree = tree;
        }
        get typeId() {
          marshalNode(this);
          return C3._ts_node_symbol_wasm(this.tree[0]);
        }
        get type() {
          return this.tree.language.types[this.typeId] || "ERROR";
        }
        get endPosition() {
          marshalNode(this);
          C3._ts_node_end_point_wasm(this.tree[0]);
          return unmarshalPoint(TRANSFER_BUFFER);
        }
        get endIndex() {
          marshalNode(this);
          return C3._ts_node_end_index_wasm(this.tree[0]);
        }
        get text() {
          return getText(this.tree, this.startIndex, this.endIndex);
        }
        isNamed() {
          marshalNode(this);
          return C3._ts_node_is_named_wasm(this.tree[0]) === 1;
        }
        hasError() {
          marshalNode(this);
          return C3._ts_node_has_error_wasm(this.tree[0]) === 1;
        }
        hasChanges() {
          marshalNode(this);
          return C3._ts_node_has_changes_wasm(this.tree[0]) === 1;
        }
        isMissing() {
          marshalNode(this);
          return C3._ts_node_is_missing_wasm(this.tree[0]) === 1;
        }
        equals(other) {
          return this.id === other.id;
        }
        child(index2) {
          marshalNode(this);
          C3._ts_node_child_wasm(this.tree[0], index2);
          return unmarshalNode(this.tree);
        }
        namedChild(index2) {
          marshalNode(this);
          C3._ts_node_named_child_wasm(this.tree[0], index2);
          return unmarshalNode(this.tree);
        }
        childForFieldId(fieldId) {
          marshalNode(this);
          C3._ts_node_child_by_field_id_wasm(this.tree[0], fieldId);
          return unmarshalNode(this.tree);
        }
        childForFieldName(fieldName) {
          const fieldId = this.tree.language.fields.indexOf(fieldName);
          if (fieldId !== -1) return this.childForFieldId(fieldId);
          return void 0;
        }
        get childCount() {
          marshalNode(this);
          return C3._ts_node_child_count_wasm(this.tree[0]);
        }
        get namedChildCount() {
          marshalNode(this);
          return C3._ts_node_named_child_count_wasm(this.tree[0]);
        }
        get firstChild() {
          return this.child(0);
        }
        get firstNamedChild() {
          return this.namedChild(0);
        }
        get lastChild() {
          return this.child(this.childCount - 1);
        }
        get lastNamedChild() {
          return this.namedChild(this.namedChildCount - 1);
        }
        get children() {
          if (!this._children) {
            marshalNode(this);
            C3._ts_node_children_wasm(this.tree[0]);
            const count = getValue(TRANSFER_BUFFER, "i32");
            const buffer3 = getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
            this._children = new Array(count);
            if (count > 0) {
              let address = buffer3;
              for (let i6 = 0; i6 < count; i6++) {
                this._children[i6] = unmarshalNode(this.tree, address);
                address += SIZE_OF_NODE;
              }
              C3._free(buffer3);
            }
          }
          return this._children;
        }
        get namedChildren() {
          if (!this._namedChildren) {
            marshalNode(this);
            C3._ts_node_named_children_wasm(this.tree[0]);
            const count = getValue(TRANSFER_BUFFER, "i32");
            const buffer3 = getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
            this._namedChildren = new Array(count);
            if (count > 0) {
              let address = buffer3;
              for (let i6 = 0; i6 < count; i6++) {
                this._namedChildren[i6] = unmarshalNode(this.tree, address);
                address += SIZE_OF_NODE;
              }
              C3._free(buffer3);
            }
          }
          return this._namedChildren;
        }
        descendantsOfType(types8, startPosition, endPosition) {
          if (!Array.isArray(types8)) types8 = [types8];
          if (!startPosition) startPosition = ZERO_POINT;
          if (!endPosition) endPosition = ZERO_POINT;
          const symbols = [];
          const typesBySymbol = this.tree.language.types;
          for (let i6 = 0, n5 = typesBySymbol.length; i6 < n5; i6++) {
            if (types8.includes(typesBySymbol[i6])) {
              symbols.push(i6);
            }
          }
          const symbolsAddress = C3._malloc(SIZE_OF_INT * symbols.length);
          for (let i6 = 0, n5 = symbols.length; i6 < n5; i6++) {
            setValue(symbolsAddress + i6 * SIZE_OF_INT, symbols[i6], "i32");
          }
          marshalNode(this);
          C3._ts_node_descendants_of_type_wasm(
            this.tree[0],
            symbolsAddress,
            symbols.length,
            startPosition.row,
            startPosition.column,
            endPosition.row,
            endPosition.column
          );
          const descendantCount = getValue(TRANSFER_BUFFER, "i32");
          const descendantAddress = getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
          const result2 = new Array(descendantCount);
          if (descendantCount > 0) {
            let address = descendantAddress;
            for (let i6 = 0; i6 < descendantCount; i6++) {
              result2[i6] = unmarshalNode(this.tree, address);
              address += SIZE_OF_NODE;
            }
          }
          C3._free(descendantAddress);
          C3._free(symbolsAddress);
          return result2;
        }
        get nextSibling() {
          marshalNode(this);
          C3._ts_node_next_sibling_wasm(this.tree[0]);
          return unmarshalNode(this.tree);
        }
        get previousSibling() {
          marshalNode(this);
          C3._ts_node_prev_sibling_wasm(this.tree[0]);
          return unmarshalNode(this.tree);
        }
        get nextNamedSibling() {
          marshalNode(this);
          C3._ts_node_next_named_sibling_wasm(this.tree[0]);
          return unmarshalNode(this.tree);
        }
        get previousNamedSibling() {
          marshalNode(this);
          C3._ts_node_prev_named_sibling_wasm(this.tree[0]);
          return unmarshalNode(this.tree);
        }
        get parent() {
          marshalNode(this);
          C3._ts_node_parent_wasm(this.tree[0]);
          return unmarshalNode(this.tree);
        }
        descendantForIndex(start, end = start) {
          if (typeof start !== "number" || typeof end !== "number") {
            throw new Error("Arguments must be numbers");
          }
          marshalNode(this);
          let address = TRANSFER_BUFFER + SIZE_OF_NODE;
          setValue(address, start, "i32");
          setValue(address + SIZE_OF_INT, end, "i32");
          C3._ts_node_descendant_for_index_wasm(this.tree[0]);
          return unmarshalNode(this.tree);
        }
        namedDescendantForIndex(start, end = start) {
          if (typeof start !== "number" || typeof end !== "number") {
            throw new Error("Arguments must be numbers");
          }
          marshalNode(this);
          let address = TRANSFER_BUFFER + SIZE_OF_NODE;
          setValue(address, start, "i32");
          setValue(address + SIZE_OF_INT, end, "i32");
          C3._ts_node_named_descendant_for_index_wasm(this.tree[0]);
          return unmarshalNode(this.tree);
        }
        descendantForPosition(start, end = start) {
          if (!isPoint(start) || !isPoint(end)) {
            throw new Error("Arguments must be {row, column} objects");
          }
          marshalNode(this);
          let address = TRANSFER_BUFFER + SIZE_OF_NODE;
          marshalPoint(address, start);
          marshalPoint(address + SIZE_OF_POINT, end);
          C3._ts_node_descendant_for_position_wasm(this.tree[0]);
          return unmarshalNode(this.tree);
        }
        namedDescendantForPosition(start, end = start) {
          if (!isPoint(start) || !isPoint(end)) {
            throw new Error("Arguments must be {row, column} objects");
          }
          marshalNode(this);
          let address = TRANSFER_BUFFER + SIZE_OF_NODE;
          marshalPoint(address, start);
          marshalPoint(address + SIZE_OF_POINT, end);
          C3._ts_node_named_descendant_for_position_wasm(this.tree[0]);
          return unmarshalNode(this.tree);
        }
        walk() {
          marshalNode(this);
          C3._ts_tree_cursor_new_wasm(this.tree[0]);
          return new TreeCursor(INTERNAL2, this.tree);
        }
        toString() {
          marshalNode(this);
          const address = C3._ts_node_to_string_wasm(this.tree[0]);
          const result2 = AsciiToString(address);
          C3._free(address);
          return result2;
        }
      }
      class TreeCursor {
        constructor(internal, tree) {
          assertInternal(internal);
          this.tree = tree;
          unmarshalTreeCursor(this);
        }
        delete() {
          marshalTreeCursor(this);
          C3._ts_tree_cursor_delete_wasm(this.tree[0]);
          this[0] = this[1] = this[2] = 0;
        }
        reset(node) {
          marshalNode(node);
          marshalTreeCursor(this, TRANSFER_BUFFER + SIZE_OF_NODE);
          C3._ts_tree_cursor_reset_wasm(this.tree[0]);
          unmarshalTreeCursor(this);
        }
        get nodeType() {
          return this.tree.language.types[this.nodeTypeId] || "ERROR";
        }
        get nodeTypeId() {
          marshalTreeCursor(this);
          return C3._ts_tree_cursor_current_node_type_id_wasm(this.tree[0]);
        }
        get nodeId() {
          marshalTreeCursor(this);
          return C3._ts_tree_cursor_current_node_id_wasm(this.tree[0]);
        }
        get nodeIsNamed() {
          marshalTreeCursor(this);
          return C3._ts_tree_cursor_current_node_is_named_wasm(this.tree[0]) === 1;
        }
        get nodeIsMissing() {
          marshalTreeCursor(this);
          return C3._ts_tree_cursor_current_node_is_missing_wasm(this.tree[0]) === 1;
        }
        get nodeText() {
          marshalTreeCursor(this);
          const startIndex = C3._ts_tree_cursor_start_index_wasm(this.tree[0]);
          const endIndex = C3._ts_tree_cursor_end_index_wasm(this.tree[0]);
          return getText(this.tree, startIndex, endIndex);
        }
        get startPosition() {
          marshalTreeCursor(this);
          C3._ts_tree_cursor_start_position_wasm(this.tree[0]);
          return unmarshalPoint(TRANSFER_BUFFER);
        }
        get endPosition() {
          marshalTreeCursor(this);
          C3._ts_tree_cursor_end_position_wasm(this.tree[0]);
          return unmarshalPoint(TRANSFER_BUFFER);
        }
        get startIndex() {
          marshalTreeCursor(this);
          return C3._ts_tree_cursor_start_index_wasm(this.tree[0]);
        }
        get endIndex() {
          marshalTreeCursor(this);
          return C3._ts_tree_cursor_end_index_wasm(this.tree[0]);
        }
        currentNode() {
          marshalTreeCursor(this);
          C3._ts_tree_cursor_current_node_wasm(this.tree[0]);
          return unmarshalNode(this.tree);
        }
        currentFieldId() {
          marshalTreeCursor(this);
          return C3._ts_tree_cursor_current_field_id_wasm(this.tree[0]);
        }
        currentFieldName() {
          return this.tree.language.fields[this.currentFieldId()];
        }
        gotoFirstChild() {
          marshalTreeCursor(this);
          const result2 = C3._ts_tree_cursor_goto_first_child_wasm(this.tree[0]);
          unmarshalTreeCursor(this);
          return result2 === 1;
        }
        gotoNextSibling() {
          marshalTreeCursor(this);
          const result2 = C3._ts_tree_cursor_goto_next_sibling_wasm(this.tree[0]);
          unmarshalTreeCursor(this);
          return result2 === 1;
        }
        gotoParent() {
          marshalTreeCursor(this);
          const result2 = C3._ts_tree_cursor_goto_parent_wasm(this.tree[0]);
          unmarshalTreeCursor(this);
          return result2 === 1;
        }
      }
      class Language {
        constructor(internal, address) {
          assertInternal(internal);
          this[0] = address;
          this.types = new Array(C3._ts_language_symbol_count(this[0]));
          for (let i6 = 0, n5 = this.types.length; i6 < n5; i6++) {
            if (C3._ts_language_symbol_type(this[0], i6) < 2) {
              this.types[i6] = UTF8ToString(C3._ts_language_symbol_name(this[0], i6));
            }
          }
          this.fields = new Array(C3._ts_language_field_count(this[0]) + 1);
          for (let i6 = 0, n5 = this.fields.length; i6 < n5; i6++) {
            const fieldName = C3._ts_language_field_name_for_id(this[0], i6);
            if (fieldName !== 0) {
              this.fields[i6] = UTF8ToString(fieldName);
            } else {
              this.fields[i6] = null;
            }
          }
        }
        get version() {
          return C3._ts_language_version(this[0]);
        }
        get fieldCount() {
          return this.fields.length - 1;
        }
        fieldIdForName(fieldName) {
          const result2 = this.fields.indexOf(fieldName);
          if (result2 !== -1) {
            return result2;
          } else {
            return null;
          }
        }
        fieldNameForId(fieldId) {
          return this.fields[fieldId] || null;
        }
        idForNodeType(type4, named) {
          const typeLength = lengthBytesUTF8(type4);
          const typeAddress = C3._malloc(typeLength + 1);
          stringToUTF8(type4, typeAddress, typeLength + 1);
          const result2 = C3._ts_language_symbol_for_name(this[0], typeAddress, typeLength, named);
          C3._free(typeAddress);
          return result2 || null;
        }
        get nodeTypeCount() {
          return C3._ts_language_symbol_count(this[0]);
        }
        nodeTypeForId(typeId) {
          const name2 = C3._ts_language_symbol_name(this[0], typeId);
          return name2 ? UTF8ToString(name2) : null;
        }
        nodeTypeIsNamed(typeId) {
          return C3._ts_language_type_is_named_wasm(this[0], typeId) ? true : false;
        }
        nodeTypeIsVisible(typeId) {
          return C3._ts_language_type_is_visible_wasm(this[0], typeId) ? true : false;
        }
        query(source2) {
          const sourceLength = lengthBytesUTF8(source2);
          const sourceAddress = C3._malloc(sourceLength + 1);
          stringToUTF8(source2, sourceAddress, sourceLength + 1);
          const address = C3._ts_query_new(
            this[0],
            sourceAddress,
            sourceLength,
            TRANSFER_BUFFER,
            TRANSFER_BUFFER + SIZE_OF_INT
          );
          if (!address) {
            const errorId = getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
            const errorByte = getValue(TRANSFER_BUFFER, "i32");
            const errorIndex = UTF8ToString(sourceAddress, errorByte).length;
            const suffix = source2.substr(errorIndex, 100).split("\n")[0];
            let word = suffix.match(QUERY_WORD_REGEX)[0];
            let error2;
            switch (errorId) {
              case 2:
                error2 = new RangeError(`Bad node name '${word}'`);
                break;
              case 3:
                error2 = new RangeError(`Bad field name '${word}'`);
                break;
              case 4:
                error2 = new RangeError(`Bad capture name @${word}`);
                break;
              case 5:
                error2 = new TypeError(`Bad pattern structure at offset ${errorIndex}: '${suffix}'...`);
                word = "";
                break;
              default:
                error2 = new SyntaxError(`Bad syntax at offset ${errorIndex}: '${suffix}'...`);
                word = "";
                break;
            }
            error2.index = errorIndex;
            error2.length = word.length;
            C3._free(sourceAddress);
            throw error2;
          }
          const stringCount = C3._ts_query_string_count(address);
          const captureCount = C3._ts_query_capture_count(address);
          const patternCount = C3._ts_query_pattern_count(address);
          const captureNames = new Array(captureCount);
          const stringValues = new Array(stringCount);
          for (let i6 = 0; i6 < captureCount; i6++) {
            const nameAddress = C3._ts_query_capture_name_for_id(
              address,
              i6,
              TRANSFER_BUFFER
            );
            const nameLength = getValue(TRANSFER_BUFFER, "i32");
            captureNames[i6] = UTF8ToString(nameAddress, nameLength);
          }
          for (let i6 = 0; i6 < stringCount; i6++) {
            const valueAddress = C3._ts_query_string_value_for_id(
              address,
              i6,
              TRANSFER_BUFFER
            );
            const nameLength = getValue(TRANSFER_BUFFER, "i32");
            stringValues[i6] = UTF8ToString(valueAddress, nameLength);
          }
          const setProperties = new Array(patternCount);
          const assertedProperties = new Array(patternCount);
          const refutedProperties = new Array(patternCount);
          const predicates = new Array(patternCount);
          const textPredicates = new Array(patternCount);
          for (let i6 = 0; i6 < patternCount; i6++) {
            const predicatesAddress = C3._ts_query_predicates_for_pattern(
              address,
              i6,
              TRANSFER_BUFFER
            );
            const stepCount = getValue(TRANSFER_BUFFER, "i32");
            predicates[i6] = [];
            textPredicates[i6] = [];
            const steps = [];
            let stepAddress = predicatesAddress;
            for (let j3 = 0; j3 < stepCount; j3++) {
              const stepType = getValue(stepAddress, "i32");
              stepAddress += SIZE_OF_INT;
              const stepValueId = getValue(stepAddress, "i32");
              stepAddress += SIZE_OF_INT;
              if (stepType === PREDICATE_STEP_TYPE_CAPTURE) {
                steps.push({ type: "capture", name: captureNames[stepValueId] });
              } else if (stepType === PREDICATE_STEP_TYPE_STRING) {
                steps.push({ type: "string", value: stringValues[stepValueId] });
              } else if (steps.length > 0) {
                if (steps[0].type !== "string") {
                  throw new Error("Predicates must begin with a literal value");
                }
                const operator = steps[0].value;
                let isPositive = true;
                switch (operator) {
                  case "not-eq?":
                    isPositive = false;
                  case "eq?":
                    if (steps.length !== 3) throw new Error(
                      `Wrong number of arguments to \`#eq?\` predicate. Expected 2, got ${steps.length - 1}`
                    );
                    if (steps[1].type !== "capture") throw new Error(
                      `First argument of \`#eq?\` predicate must be a capture. Got "${steps[1].value}"`
                    );
                    if (steps[2].type === "capture") {
                      const captureName1 = steps[1].name;
                      const captureName2 = steps[2].name;
                      textPredicates[i6].push(function(captures) {
                        let node1, node2;
                        for (const c6 of captures) {
                          if (c6.name === captureName1) node1 = c6.node;
                          if (c6.name === captureName2) node2 = c6.node;
                        }
                        if (node1 === void 0 || node2 === void 0) return true;
                        return node1.text === node2.text === isPositive;
                      });
                    } else {
                      const captureName2 = steps[1].name;
                      const stringValue = steps[2].value;
                      textPredicates[i6].push(function(captures) {
                        for (const c6 of captures) {
                          if (c6.name === captureName2) {
                            return c6.node.text === stringValue === isPositive;
                          }
                          ;
                        }
                        return true;
                      });
                    }
                    break;
                  case "not-match?":
                    isPositive = false;
                  case "match?":
                    if (steps.length !== 3) throw new Error(
                      `Wrong number of arguments to \`#match?\` predicate. Expected 2, got ${steps.length - 1}.`
                    );
                    if (steps[1].type !== "capture") throw new Error(
                      `First argument of \`#match?\` predicate must be a capture. Got "${steps[1].value}".`
                    );
                    if (steps[2].type !== "string") throw new Error(
                      `Second argument of \`#match?\` predicate must be a string. Got @${steps[2].value}.`
                    );
                    const captureName = steps[1].name;
                    const regex = new RegExp(steps[2].value);
                    textPredicates[i6].push(function(captures) {
                      for (const c6 of captures) {
                        if (c6.name === captureName) return regex.test(c6.node.text) === isPositive;
                      }
                      return true;
                    });
                    break;
                  case "set!":
                    if (steps.length < 2 || steps.length > 3) throw new Error(
                      `Wrong number of arguments to \`#set!\` predicate. Expected 1 or 2. Got ${steps.length - 1}.`
                    );
                    if (steps.some((s5) => s5.type !== "string")) throw new Error(
                      `Arguments to \`#set!\` predicate must be a strings.".`
                    );
                    if (!setProperties[i6]) setProperties[i6] = {};
                    setProperties[i6][steps[1].value] = steps[2] ? steps[2].value : null;
                    break;
                  case "is?":
                  case "is-not?":
                    if (steps.length < 2 || steps.length > 3) throw new Error(
                      `Wrong number of arguments to \`#${operator}\` predicate. Expected 1 or 2. Got ${steps.length - 1}.`
                    );
                    if (steps.some((s5) => s5.type !== "string")) throw new Error(
                      `Arguments to \`#${operator}\` predicate must be a strings.".`
                    );
                    const properties = operator === "is?" ? assertedProperties : refutedProperties;
                    if (!properties[i6]) properties[i6] = {};
                    properties[i6][steps[1].value] = steps[2] ? steps[2].value : null;
                    break;
                  default:
                    predicates[i6].push({ operator, operands: steps.slice(1) });
                }
                steps.length = 0;
              }
            }
            Object.freeze(setProperties[i6]);
            Object.freeze(assertedProperties[i6]);
            Object.freeze(refutedProperties[i6]);
          }
          C3._free(sourceAddress);
          return new Query(
            INTERNAL2,
            address,
            captureNames,
            textPredicates,
            predicates,
            Object.freeze(setProperties),
            Object.freeze(assertedProperties),
            Object.freeze(refutedProperties)
          );
        }
        static load(input) {
          let bytes;
          if (input instanceof Uint8Array) {
            bytes = Promise.resolve(input);
          } else {
            bytes = Promise.resolve(Deno.readFileSync(input));
          }
          const loadModule = loadWebAssemblyModule;
          return bytes.then((bytes2) => loadModule(bytes2, { loadAsync: true })).then((mod) => {
            const symbolNames = Object.keys(mod);
            const functionName = symbolNames.find(
              (key2) => LANGUAGE_FUNCTION_REGEX.test(key2) && !key2.includes("external_scanner_")
            );
            if (!functionName) {
              console.log(`Couldn't find language function in WASM file. Symbols:
${JSON.stringify(symbolNames, null, 2)}`);
            }
            const languageAddress = mod[functionName]();
            return new Language(INTERNAL2, languageAddress);
          });
        }
      }
      class Query {
        constructor(internal, address, captureNames, textPredicates, predicates, setProperties, assertedProperties, refutedProperties) {
          assertInternal(internal);
          this[0] = address;
          this.captureNames = captureNames;
          this.textPredicates = textPredicates;
          this.predicates = predicates;
          this.setProperties = setProperties;
          this.assertedProperties = assertedProperties;
          this.refutedProperties = refutedProperties;
          this.exceededMatchLimit = false;
        }
        delete() {
          C3._ts_query_delete(this[0]);
          this[0] = 0;
        }
        matches(node, startPosition, endPosition, options) {
          if (!startPosition) startPosition = ZERO_POINT;
          if (!endPosition) endPosition = ZERO_POINT;
          if (!options) options = {};
          let matchLimit = options.matchLimit;
          if (typeof matchLimit === "undefined") {
            matchLimit = 0;
          } else if (typeof matchLimit !== "number") {
            throw new Error("Arguments must be numbers");
          }
          marshalNode(node);
          C3._ts_query_matches_wasm(
            this[0],
            node.tree[0],
            startPosition.row,
            startPosition.column,
            endPosition.row,
            endPosition.column,
            matchLimit
          );
          const rawCount = getValue(TRANSFER_BUFFER, "i32");
          const startAddress = getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
          const didExceedMatchLimit = getValue(TRANSFER_BUFFER + 2 * SIZE_OF_INT, "i32");
          const result2 = new Array(rawCount);
          this.exceededMatchLimit = !!didExceedMatchLimit;
          let filteredCount = 0;
          let address = startAddress;
          for (let i6 = 0; i6 < rawCount; i6++) {
            const pattern = getValue(address, "i32");
            address += SIZE_OF_INT;
            const captureCount = getValue(address, "i32");
            address += SIZE_OF_INT;
            const captures = new Array(captureCount);
            address = unmarshalCaptures(this, node.tree, address, captures);
            if (this.textPredicates[pattern].every((p5) => p5(captures))) {
              result2[filteredCount++] = { pattern, captures };
              const setProperties = this.setProperties[pattern];
              if (setProperties) result2[i6].setProperties = setProperties;
              const assertedProperties = this.assertedProperties[pattern];
              if (assertedProperties) result2[i6].assertedProperties = assertedProperties;
              const refutedProperties = this.refutedProperties[pattern];
              if (refutedProperties) result2[i6].refutedProperties = refutedProperties;
            }
          }
          result2.length = filteredCount;
          C3._free(startAddress);
          return result2;
        }
        captures(node, startPosition, endPosition, options) {
          if (!startPosition) startPosition = ZERO_POINT;
          if (!endPosition) endPosition = ZERO_POINT;
          if (!options) options = {};
          let matchLimit = options.matchLimit;
          if (typeof matchLimit === "undefined") {
            matchLimit = 0;
          } else if (typeof matchLimit !== "number") {
            throw new Error("Arguments must be numbers");
          }
          marshalNode(node);
          C3._ts_query_captures_wasm(
            this[0],
            node.tree[0],
            startPosition.row,
            startPosition.column,
            endPosition.row,
            endPosition.column,
            matchLimit
          );
          const count = getValue(TRANSFER_BUFFER, "i32");
          const startAddress = getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
          const didExceedMatchLimit = getValue(TRANSFER_BUFFER + 2 * SIZE_OF_INT, "i32");
          const result2 = [];
          this.exceededMatchLimit = !!didExceedMatchLimit;
          const captures = [];
          let address = startAddress;
          for (let i6 = 0; i6 < count; i6++) {
            const pattern = getValue(address, "i32");
            address += SIZE_OF_INT;
            const captureCount = getValue(address, "i32");
            address += SIZE_OF_INT;
            const captureIndex = getValue(address, "i32");
            address += SIZE_OF_INT;
            captures.length = captureCount;
            address = unmarshalCaptures(this, node.tree, address, captures);
            if (this.textPredicates[pattern].every((p5) => p5(captures))) {
              const capture = captures[captureIndex];
              const setProperties = this.setProperties[pattern];
              if (setProperties) capture.setProperties = setProperties;
              const assertedProperties = this.assertedProperties[pattern];
              if (assertedProperties) capture.assertedProperties = assertedProperties;
              const refutedProperties = this.refutedProperties[pattern];
              if (refutedProperties) capture.refutedProperties = refutedProperties;
              result2.push(capture);
            }
          }
          C3._free(startAddress);
          return result2;
        }
        predicatesForPattern(patternIndex) {
          return this.predicates[patternIndex];
        }
        didExceedMatchLimit() {
          return this.exceededMatchLimit;
        }
      }
      function getText(tree, startIndex, endIndex) {
        const length = endIndex - startIndex;
        let result2 = tree.textCallback(startIndex, null, endIndex);
        startIndex += result2.length;
        while (startIndex < endIndex) {
          const string2 = tree.textCallback(startIndex, null, endIndex);
          if (string2 && string2.length > 0) {
            startIndex += string2.length;
            result2 += string2;
          } else {
            break;
          }
        }
        if (startIndex > endIndex) {
          result2 = result2.slice(0, length);
        }
        return result2;
      }
      function unmarshalCaptures(query, tree, address, result2) {
        for (let i6 = 0, n5 = result2.length; i6 < n5; i6++) {
          const captureIndex = getValue(address, "i32");
          address += SIZE_OF_INT;
          const node = unmarshalNode(tree, address);
          address += SIZE_OF_NODE;
          result2[i6] = { name: query.captureNames[captureIndex], node };
        }
        return address;
      }
      function assertInternal(x3) {
        if (x3 !== INTERNAL2) throw new Error("Illegal constructor");
      }
      function isPoint(point) {
        return point && typeof point.row === "number" && typeof point.column === "number";
      }
      function marshalNode(node) {
        let address = TRANSFER_BUFFER;
        setValue(address, node.id, "i32");
        address += SIZE_OF_INT;
        setValue(address, node.startIndex, "i32");
        address += SIZE_OF_INT;
        setValue(address, node.startPosition.row, "i32");
        address += SIZE_OF_INT;
        setValue(address, node.startPosition.column, "i32");
        address += SIZE_OF_INT;
        setValue(address, node[0], "i32");
      }
      function unmarshalNode(tree, address = TRANSFER_BUFFER) {
        const id = getValue(address, "i32");
        address += SIZE_OF_INT;
        if (id === 0) return null;
        const index2 = getValue(address, "i32");
        address += SIZE_OF_INT;
        const row = getValue(address, "i32");
        address += SIZE_OF_INT;
        const column = getValue(address, "i32");
        address += SIZE_OF_INT;
        const other = getValue(address, "i32");
        const result2 = new Node7(INTERNAL2, tree);
        result2.id = id;
        result2.startIndex = index2;
        result2.startPosition = { row, column };
        result2[0] = other;
        return result2;
      }
      function marshalTreeCursor(cursor, address = TRANSFER_BUFFER) {
        setValue(address + 0 * SIZE_OF_INT, cursor[0], "i32"), setValue(address + 1 * SIZE_OF_INT, cursor[1], "i32"), setValue(address + 2 * SIZE_OF_INT, cursor[2], "i32");
      }
      function unmarshalTreeCursor(cursor) {
        cursor[0] = getValue(TRANSFER_BUFFER + 0 * SIZE_OF_INT, "i32"), cursor[1] = getValue(TRANSFER_BUFFER + 1 * SIZE_OF_INT, "i32"), cursor[2] = getValue(TRANSFER_BUFFER + 2 * SIZE_OF_INT, "i32");
      }
      function marshalPoint(address, point) {
        setValue(address, point.row, "i32");
        setValue(address + SIZE_OF_INT, point.column, "i32");
      }
      function unmarshalPoint(address) {
        return {
          row: getValue(address, "i32"),
          column: getValue(address + SIZE_OF_INT, "i32")
        };
      }
      function marshalRange(address, range) {
        marshalPoint(address, range.startPosition);
        address += SIZE_OF_POINT;
        marshalPoint(address, range.endPosition);
        address += SIZE_OF_POINT;
        setValue(address, range.startIndex, "i32");
        address += SIZE_OF_INT;
        setValue(address, range.endIndex, "i32");
        address += SIZE_OF_INT;
      }
      function unmarshalRange(address) {
        const result2 = {};
        result2.startPosition = unmarshalPoint(address);
        address += SIZE_OF_POINT;
        result2.endPosition = unmarshalPoint(address);
        address += SIZE_OF_POINT;
        result2.startIndex = getValue(address, "i32");
        address += SIZE_OF_INT;
        result2.endIndex = getValue(address, "i32");
        return result2;
      }
      function marshalEdit(edit) {
        let address = TRANSFER_BUFFER;
        marshalPoint(address, edit.startPosition);
        address += SIZE_OF_POINT;
        marshalPoint(address, edit.oldEndPosition);
        address += SIZE_OF_POINT;
        marshalPoint(address, edit.newEndPosition);
        address += SIZE_OF_POINT;
        setValue(address, edit.startIndex, "i32");
        address += SIZE_OF_INT;
        setValue(address, edit.oldEndIndex, "i32");
        address += SIZE_OF_INT;
        setValue(address, edit.newEndIndex, "i32");
        address += SIZE_OF_INT;
      }
      for (const name2 of Object.getOwnPropertyNames(ParserImpl.prototype)) {
        Object.defineProperty(Parser6.prototype, name2, {
          value: ParserImpl.prototype[name2],
          enumerable: false,
          writable: false
        });
      }
      Parser6.Language = Language;
      Module.onRuntimeInitialized = () => {
        ParserImpl.init();
      };
      await run5();
      init4 = true;
    }
  }
  return Parser6;
})();

// core/lib/yaml-intelligence/paths.ts
var mainPath = "";
function setMainPath(path3) {
  mainPath = path3;
}

// core/schema/deno-init-tree-sitter.ts
init_parsing();
async function initTreeSitter() {
  setWasmBinaryFile(
    Deno.readFileSync(resourcePath("editor/tools/yaml/tree-sitter.wasm"))
  );
  const treeSitter = TreeSitter;
  await treeSitter.init();
  const parser = new treeSitter();
  const language = await treeSitter.Language.load(
    resourcePath("editor/tools/yaml/tree-sitter-yaml.wasm")
  );
  parser.setLanguage(language);
  setMainPath("https://example.com");
  setTreeSitter(parser);
}

// core/lib/yaml-intelligence/yaml-intelligence.ts
init_annotated_yaml();
init_parsing();
init_guess_chunk_options_format();
init_mapped_text();
init_text();
init_break_quarto_md();
init_ranged_text();
init_partition_cell_options();
init_schema();
init_validator_queue();
init_schema_navigation();
init_resolve4();
init_schema_utils();
init_mapped_text();
init_text();
init_types2();
init_format_aliases();
init_front_matter();
init_chunk_metadata();
init_project_config();
init_resources();
init_definitions();

// core/lib/yaml-intelligence/descriptions.ts
init_schema_utils();
init_schema();
init_resources();
function patchMarkdownDescriptions() {
  const descriptionList = getYamlIntelligenceResource(
    "schema/html-descriptions.yml"
  );
  const schemaList = Object.values(getSchemaDefinitionsObject());
  let cursor = 0;
  for (const schema4 of schemaList) {
    walkSchema(schema4, (s5) => {
      if (s5 === false || s5 === true) {
        return;
      }
      const description = s5 && s5.tags && s5.tags.description;
      if (!description) {
        return;
      }
      const fixedDescription = descriptionList[cursor++];
      if (typeof fixedDescription === "string") {
        s5.documentation = fixedDescription;
      } else if (typeof (fixedDescription && fixedDescription.short) === "string") {
        s5.documentation = fixedDescription.short;
      }
    });
  }
}

// core/lib/yaml-intelligence/hover.ts
init_annotated_yaml();
init_break_quarto_md();
init_mapped_text();
init_partition_cell_options();
init_ranged_text();
init_text();
init_schema_navigation();
init_resolve4();
init_front_matter();
init_chunk_metadata();
init_project_config();

// core/lib/yaml-schema/brand.ts
init_common4();

// core/lib/yaml-intelligence/yaml-intelligence.ts
async function initYamlIntelligence(obj) {
  const {
    resourceModule,
    patchMarkdown
  } = obj;
  setYamlIntelligenceResources(resourceModule);
  await loadDefaultSchemaDefinitions();
  getFormatAliases();
  await getFrontMatterSchema();
  await getProjectConfigSchema();
  await getEngineOptionsSchema();
  for (const schema4 of getYamlIntelligenceResource(
    "schema/external-schemas.yml"
  )) {
    setSchemaDefinition(schema4);
  }
  try {
    const extendedLangCommentChars = getYamlIntelligenceResource(
      "handlers/lang-comment-chars.yml"
    );
    for (const [lang, comment] of Object.entries(extendedLangCommentChars)) {
      kLangCommentChars[lang] = comment;
    }
  } catch (_e) {
    console.warn(`"handlers/lang-comment-chars.yml" not found.
initialization does not contain language extensions`);
  }
  if (patchMarkdown === void 0 || patchMarkdown) {
    patchMarkdownDescriptions();
  }
}

// core/schema/utils.ts
async function initYamlIntelligenceResourcesFromFilesystem() {
  const resourceModule = (await import(toFileUrl4(
    resourcePath("editor/tools/yaml/yaml-intelligence-resources.json")
  ).href, {
    with: { type: "json" }
  })).default;
  await initYamlIntelligence({
    resourceModule
  });
  await initTreeSitter();
}

// command/render/render-shared.ts
init_mime();
init_path2();

// render/notebook/notebook-context.ts
init_error2();
init_format_jats_types();
init_notebook_types();
init_path();

// render/notebook/notebook-contributor-jats.ts
init_constants6();
init_error2();
init_path2();
init_format_jats_types();

// format/jats/format-jats-paths.ts
init_path();
init_resources2();
var subarticleTemplatePath = formatResourcePath(
  "jats",
  join4("pandoc", "subarticle", "template.xml")
);

// render/notebook/notebook-contributor-jats.ts
init_log();
init_safe_clone_deep();
var jatsContributor = {
  resolve: resolveJats,
  render: renderJats,
  outputFile
};
function outputFile(nbAbsPath2) {
  return jatsOutputFile(nbAbsPath2);
}
function resolveJats(nbAbsPath2, token, executedFile, _notebookMetadata) {
  const resolved = safeCloneDeep(executedFile);
  const to = resolved.recipe.format.render[kVariant]?.includes("+element_citations") ? "jats+element_citations" : "jats";
  resolved.recipe.format.metadata[kLintXml] = false;
  resolved.recipe.format.metadata[kJatsSubarticle] = true;
  resolved.recipe.format.metadata[kJatsSubarticleId] = token;
  resolved.recipe.format.pandoc[kOutputFile] = outputFile(
    nbAbsPath2
  );
  resolved.recipe.output = resolved.recipe.format.pandoc[kOutputFile];
  resolved.recipe.format.pandoc.to = to;
  resolved.recipe.format.pandoc[kTemplate] = subarticleTemplatePath;
  resolved.recipe.format.execute.echo = false;
  resolved.recipe.format.execute.warning = false;
  resolved.recipe.format.render[kKeepHidden] = true;
  resolved.recipe.format.metadata[kClearHiddenClasses] = "all";
  resolved.recipe.format.metadata[kRemoveHidden] = "none";
  if (resolved.recipe.format.render[kIpynbProduceSourceNotebook]) {
    resolved.recipe.format.render[kClearCellOptions] = true;
  }
  return resolved;
}
async function renderJats(nbPath, format14, subArticleToken, services, _notebookMetadata, project) {
  const to = format14.render[kVariant]?.includes("+element_citations") ? "jats+element_citations" : "jats";
  const rendered = await renderFile(
    { path: nbPath, formats: ["jats"] },
    {
      services,
      flags: {
        metadata: {
          [kTo]: to,
          [kLintXml]: false,
          [kJatsSubarticle]: true,
          [kJatsSubarticleId]: subArticleToken,
          [kOutputFile]: outputFile(nbPath),
          [kTemplate]: subarticleTemplatePath,
          [kNotebookPreserveCells]: true
        },
        quiet: false
      },
      echo: true,
      warning: true,
      quietPandoc: true
    },
    services,
    project
  );
  if (rendered.error) {
    error("Rendering of subarticle produced an unexpected result");
    throw rendered.error;
  }
  if (rendered.files.length !== 1) {
    throw new InternalError(
      `Rendering a JATS subarticle should only result in a single file. This attempt resulted in ${rendered.files.length} file(s).`
    );
  }
  return rendered.files[0];
}
function jatsOutputFile(nbAbsPath2) {
  const [_dir, stem] = dirAndStem(nbAbsPath2);
  return `${stem}.subarticle.xml`;
}

// render/notebook/notebook-contributor-html.ts
init_constants6();
init_error2();
init_log();
init_resources2();
init_format_html_shared();
init_path();
init_path2();
await init_project_shared();
init_fs();
init_safe_clone_deep();
var htmlNotebookContributor = {
  resolve: resolveHtmlNotebook,
  render: renderHtmlNotebook,
  outputFile: outputFile2,
  cachedPath
};
function outputFile2(nbAbsPath2) {
  const [_dir, stem] = dirAndStem(basename4(nbAbsPath2));
  return `${stem}-preview.html`;
}
function cachedPath(nbAbsPath2, project) {
  if (project) {
    const nbRelative = relative4(project.dir, dirname4(nbAbsPath2));
    const nbOutputDir = join4(projectOutputDir(project), nbRelative);
    const outFile = outputFile2(nbAbsPath2);
    const outPath = join4(nbOutputDir, outFile);
    if (existsSync2(outPath)) {
      return outPath;
    }
  }
}
function resolveHtmlNotebook(nbAbsPath2, _token, executedFile, notebookMetadata) {
  const resolved = safeCloneDeep(executedFile);
  resolved.recipe.format.pandoc[kOutputFile] = `${outputFile2(nbAbsPath2)}`;
  resolved.recipe.output = resolved.recipe.format.pandoc[kOutputFile];
  resolved.recipe.format.execute.echo = false;
  resolved.recipe.format.execute.warning = false;
  resolved.recipe.format.render[kKeepHidden] = true;
  resolved.recipe.format.metadata[kClearHiddenClasses] = "all";
  resolved.recipe.format.metadata[kRemoveHidden] = "none";
  if (resolved.recipe.format.render[kIpynbProduceSourceNotebook]) {
    resolved.recipe.format.render[kClearCellOptions] = true;
  }
  const template2 = formatResourcePath(
    "html",
    join4("embed", "template.html")
  );
  resolved.recipe.format.pandoc[kTemplate] = template2;
  resolved.recipe.format.metadata["nbMeta"] = {
    ...notebookMetadata,
    downloadLabel: downloadLabel(
      notebookMetadata?.filename || nbAbsPath2,
      resolved.recipe.format
    ),
    backLabel: resolved.recipe.format.language[kNotebookPreviewBack]
  };
  resolved.recipe.format.render[kNotebookViewStyle] = kNotebookViewStyleNotebook;
  resolved.recipe.format.render[kNotebookPreserveCells] = true;
  resolved.recipe.format.metadata[kUnrollMarkdownCells] = false;
  resolved.recipe.format.pandoc[kToc] = true;
  resolved.recipe.format.metadata[kTocLocation] = "left";
  resolved.recipe.format.metadata[kAppendixStyle] = "none";
  resolved.recipe.format.render[kFormatLinks] = false;
  resolved.recipe.format.metadata[kDisableArticleLayout] = true;
  return resolved;
}
async function renderHtmlNotebook(nbPath, format14, _subArticleToken, services, notebookMetadata, project) {
  const template2 = formatResourcePath(
    "html",
    join4("embed", "template.html")
  );
  const rendered = await renderFile(
    { path: nbPath, formats: ["html"] },
    {
      services,
      flags: {
        metadata: {
          [kTo]: "html",
          [kTheme]: format14.metadata[kTheme],
          [kOutputFile]: `${outputFile2(nbPath)}`,
          [kTemplate]: template2,
          [kNotebookViewStyle]: kNotebookViewStyleNotebook,
          [kAppendixStyle]: "none",
          [kNotebookPreserveCells]: true,
          ["nbMeta"]: {
            ...notebookMetadata,
            downloadLabel: downloadLabel(
              notebookMetadata?.filename || nbPath,
              format14
            ),
            backLabel: format14.language[kNotebookPreviewBack]
          },
          [kToc]: true,
          [kTocLocation]: "left",
          [kDisableArticleLayout]: true
        },
        quiet: false
      },
      echo: true,
      warning: true,
      quietPandoc: true
    },
    services,
    project
  );
  if (rendered.error) {
    error("Rendering of output notebook produced an unexpected result");
    throw rendered.error;
  }
  if (rendered.files.length !== 1) {
    throw new InternalError(
      `Rendering an output notebook should only result in a single file. This attempt resulted in ${rendered.files.length} file(s).`
    );
  }
  return rendered.files[0];
}
function downloadLabel(file, format14) {
  return isQmdFile(file) ? format14.language[kNotebookPreviewDownloadSrc] : format14.language[kNotebookPreviewDownload];
}

// render/notebook/notebook-contributor-ipynb.ts
init_constants6();
init_error2();
init_path2();
init_log();
init_format_ipynb();
await init_project_shared();
init_fs();
init_path();
init_safe_clone_deep();
var outputNotebookContributor = {
  resolve: resolveOutputNotebook,
  render: renderOutputNotebook,
  outputFile: outputFile3,
  cachedPath: cachedPath2
};
function outputFile3(nbAbsPath2) {
  return ipynbOutputFile(nbAbsPath2);
}
function cachedPath2(nbAbsPath2, project) {
  if (project) {
    const nbRelative = relative4(project.dir, dirname4(nbAbsPath2));
    const nbOutputDir = join4(projectOutputDir(project), nbRelative);
    const outFile = outputFile3(nbAbsPath2);
    const outPath = join4(nbOutputDir, outFile);
    if (existsSync2(outPath)) {
      return outPath;
    }
  }
}
function resolveOutputNotebook(nbAbsPath2, _token, executedFile, _notebookMetadata) {
  const resolved = safeCloneDeep(executedFile);
  resolved.recipe.format.pandoc[kOutputFile] = outputFile3(nbAbsPath2);
  resolved.recipe.output = resolved.recipe.format.pandoc[kOutputFile];
  resolved.recipe.format.pandoc.to = "ipynb";
  const template2 = ipynbTitleTemplatePath();
  resolved.recipe.format.execute.echo = false;
  resolved.recipe.format.execute.warning = false;
  resolved.recipe.format.render[kKeepHidden] = true;
  resolved.recipe.format.metadata[kClearHiddenClasses] = "all";
  resolved.recipe.format.metadata[kRemoveHidden] = "none";
  resolved.recipe.format.metadata[kIPynbTitleBlockTemplate] = template2;
  if (resolved.recipe.format.render[kIpynbProduceSourceNotebook]) {
    resolved.recipe.format.render[kClearCellOptions] = true;
  }
  resolved.recipe.format.metadata[kUnrollMarkdownCells] = false;
  return resolved;
}
async function renderOutputNotebook(nbPath, _format5, _subArticleToken, services, _notebookMetadata, project) {
  const rendered = await renderFile(
    { path: nbPath, formats: ["ipynb"] },
    {
      services,
      flags: {
        metadata: {
          [kTo]: "ipynb",
          [kOutputFile]: outputFile3(nbPath)
        },
        quiet: false
      },
      echo: true,
      warning: true,
      quietPandoc: true
    },
    services,
    project
  );
  if (rendered.error) {
    error("Rendering of output notebook produced an unexpected result");
    throw rendered.error;
  }
  if (rendered.files.length !== 1) {
    throw new InternalError(
      `Rendering an output notebook should only result in a single file. This attempt resulted in ${rendered.files.length} file(s).`
    );
  }
  return rendered.files[0];
}
function ipynbOutputFile(nbAbsPath2) {
  const [_dir, stem] = dirAndStem(nbAbsPath2);
  return `${stem}.out.ipynb`;
}

// render/notebook/notebook-context.ts
init_path2();

// render/notebook/notebook-contributor-qmd.ts
init_constants6();
init_error2();
init_path2();
init_log();
init_format_ipynb();
init_project_scratch();
init_fs();
init_path();
init_safe_clone_deep();
var qmdNotebookContributor = {
  resolve: resolveOutputNotebook2,
  render: renderOutputNotebook2,
  outputFile: outputFile4,
  cache: cache2,
  cachedPath: cachedPath3
};
function cache2(output, project) {
  if (project) {
    const path3 = cachePath(output.path, project);
    ensureDirSync(dirname4(path3));
    Deno.copyFileSync(output.path, path3);
  }
}
function cachedPath3(nbAbsPath2, project) {
  if (project) {
    const output = outputFile4(nbAbsPath2);
    const outputPath = join4(dirname4(nbAbsPath2), output);
    const path3 = cachePath(outputPath, project);
    if (existsSync2(path3)) {
      return path3;
    }
  }
}
function cachePath(nbAbsPath2, project) {
  const basePath = projectScratchPath(project.dir, "embed");
  const outputRel = relative4(project.dir, nbAbsPath2);
  return join4(basePath, outputRel);
}
function outputFile4(nbAbsPath2) {
  return ipynbOutputFile2(nbAbsPath2);
}
function resolveOutputNotebook2(nbAbsPath2, _token, executedFile, _notebookMetadata) {
  const resolved = safeCloneDeep(executedFile);
  resolved.recipe.format.pandoc[kOutputFile] = ipynbOutputFile2(nbAbsPath2);
  resolved.recipe.output = resolved.recipe.format.pandoc[kOutputFile];
  resolved.recipe.format.pandoc.to = "ipynb";
  const template2 = ipynbTitleTemplatePath();
  resolved.recipe.format.execute.echo = false;
  resolved.recipe.format.execute.warning = false;
  resolved.recipe.format.render[kKeepHidden] = true;
  resolved.recipe.format.render[kNotebookPreserveCells] = true;
  resolved.recipe.format.metadata[kClearHiddenClasses] = "all";
  resolved.recipe.format.metadata[kRemoveHidden] = "none";
  resolved.recipe.format.metadata[kIPynbTitleBlockTemplate] = template2;
  resolved.recipe.format.render[kIpynbProduceSourceNotebook] = true;
  resolved.recipe.format.pandoc.citeproc = false;
  resolved.recipe.format.metadata[kUnrollMarkdownCells] = false;
  return resolved;
}
async function renderOutputNotebook2(nbPath, _format5, _subArticleToken, services, _notebookMetadata, project) {
  const rendered = await renderFile(
    { path: nbPath, formats: ["ipynb"] },
    {
      services,
      flags: {
        metadata: {
          [kTo]: "ipynb",
          [kOutputFile]: ipynbOutputFile2(nbPath),
          [kNotebookPreserveCells]: true,
          [kIpynbProduceSourceNotebook]: true,
          citeproc: false
        },
        quiet: false
      },
      echo: true,
      warning: true,
      quietPandoc: true
    },
    services,
    project,
    false
    // Don't enforce project constraints on format since this is an intermediary rendering
  );
  if (rendered.error) {
    error("Rendering of qmd notebook produced an unexpected result");
    throw rendered.error;
  }
  if (rendered.files.length !== 1) {
    throw new InternalError(
      `Rendering an qmd notebook should only result in a single file. This attempt resulted in ${rendered.files.length} file(s).`
    );
  }
  return rendered.files[0];
}
function ipynbOutputFile2(nbAbsPath2) {
  const [_dir, stem] = dirAndStem(nbAbsPath2);
  return `${stem}.embed.ipynb`;
}

// render/notebook/notebook-context.ts
init_log();
var contributors = {
  [kJatsSubarticle]: jatsContributor,
  [kHtmlPreview]: htmlNotebookContributor,
  [kRenderedIPynb]: outputNotebookContributor,
  [kQmdIPynb]: qmdNotebookContributor
};
function notebookContext() {
  const notebooks = {};
  const preserveNotebooks = {};
  let nbCount = 0;
  const token = () => {
    return `nb-${++nbCount}`;
  };
  const emptyNotebook = (nbAbsPath2) => {
    return {
      source: nbAbsPath2
    };
  };
  const addRendering = (nbAbsPath2, renderType, result2, context, cached) => {
    debug(`[NotebookContext]: Add Rendering (${renderType}):${nbAbsPath2}`);
    const hrefPath = join4(dirname4(nbAbsPath2), basename4(result2.file));
    const absPath = isAbsolute4(result2.file) ? result2.file : hrefPath;
    const output = {
      path: absPath,
      hrefPath,
      supporting: result2.supporting || [],
      resourceFiles: result2.resourceFiles,
      cached
    };
    const nb = notebooks[nbAbsPath2] || emptyNotebook(nbAbsPath2);
    nb[renderType] = output;
    notebooks[nbAbsPath2] = nb;
    needRewrite = true;
    if (context) {
      const contrib = contributor(renderType);
      if (contrib.cache) {
        contrib.cache(output, context);
      }
    }
  };
  const removeRendering = (nbAbsPath2, renderType, preserveFiles) => {
    debug(`[NotebookContext]: Remove Rendering (${renderType}):${nbAbsPath2}`);
    if (preserveNotebooks[nbAbsPath2] && preserveNotebooks[nbAbsPath2].includes(renderType)) {
      return;
    }
    const nb = notebooks[nbAbsPath2];
    if (nb) {
      const rendering = nb[renderType];
      if (rendering) {
        safeRemoveIfExists(rendering.path);
        const filteredSupporting = rendering.supporting.filter(
          (file) => {
            const absPath = join4(dirname4(nbAbsPath2), file);
            return !preserveFiles.includes(absPath);
          }
        );
        for (const supporting of filteredSupporting) {
          safeRemoveIfExists(supporting);
        }
      }
    }
  };
  function contributor(renderType) {
    const contributor2 = contributors[renderType];
    if (contributor2) {
      return contributor2;
    } else {
      throw new InternalError(
        `Missing contributor ${renderType} when resolving`
      );
    }
  }
  function addMetadata(nbAbsPath2, nbMeta) {
    debug(`[NotebookContext]: Add Notebook Metadata:${nbAbsPath2}`);
    const nb = notebooks[nbAbsPath2] || emptyNotebook(nbAbsPath2);
    nb.metadata = nbMeta;
    notebooks[nbAbsPath2] = nb;
  }
  function reviveOutput(nbAbsPath2, renderType, context) {
    debug(
      `[NotebookContext]: Attempting to Revive Rendering (${renderType}):${nbAbsPath2}`
    );
    const contrib = contributor(renderType);
    if (contrib.cachedPath) {
      const existingPath = contrib.cachedPath(nbAbsPath2, context);
      if (existingPath) {
        if (safeExistsSync(existingPath)) {
          const inputTime = Deno.statSync(nbAbsPath2).mtime?.valueOf() || 0;
          const outputTime = Deno.statSync(existingPath).mtime?.valueOf() || 0;
          if (inputTime <= outputTime) {
            debug(
              `[NotebookContext]: Revived Rendering (${renderType}):${nbAbsPath2}`
            );
            addRendering(
              nbAbsPath2,
              renderType,
              {
                file: existingPath,
                supporting: [],
                resourceFiles: {
                  globs: [],
                  files: []
                }
              },
              context,
              true
            );
          }
        }
      }
    }
  }
  function preserve(nbAbsPath2, renderType) {
    debug(`[NotebookContext]: Preserving (${renderType}):${nbAbsPath2}`);
    preserveNotebooks[nbAbsPath2] = preserveNotebooks[nbAbsPath2] || [];
    if (!preserveNotebooks[nbAbsPath2].includes(renderType)) {
      preserveNotebooks[nbAbsPath2].push(renderType);
    }
  }
  let allNotebooksTempFilename;
  let needRewrite = true;
  return {
    all: (context) => {
      if (!allNotebooksTempFilename) {
        allNotebooksTempFilename = context.temp.createFile({
          suffix: ".json"
        });
      }
      if (needRewrite) {
        debug(
          `[NotebookContext]: Writing all notebooks to ${allNotebooksTempFilename}`
        );
        const objs = Object.values(notebooks);
        Deno.writeTextFileSync(
          allNotebooksTempFilename,
          JSON.stringify(objs)
        );
        needRewrite = false;
      }
      return allNotebooksTempFilename;
    },
    get: (nbAbsPath2, context) => {
      debug(`[NotebookContext]: Get Notebook:${nbAbsPath2}`);
      const notebook = notebooks[nbAbsPath2];
      const reviveRenders = [];
      if (notebook) {
        [kJatsSubarticle, kHtmlPreview, kRenderedIPynb].forEach(
          (renderTypeStr) => {
            const renderType = renderTypeStr;
            if (!notebook[renderType]) {
              reviveRenders.push(renderType);
            }
          }
        );
      } else {
        reviveRenders.push(kHtmlPreview);
        reviveRenders.push(kJatsSubarticle);
        reviveRenders.push(kRenderedIPynb);
        reviveRenders.push(kQmdIPynb);
      }
      if (context) {
        for (const renderType of reviveRenders) {
          reviveOutput(nbAbsPath2, renderType, context);
        }
      }
      return notebooks[nbAbsPath2];
    },
    addMetadata: (nbAbsPath2, notebookMetadata) => {
      addMetadata(nbAbsPath2, notebookMetadata);
    },
    resolve: (nbAbsPath2, renderType, executedFile, notebookMetadata) => {
      debug(
        `[NotebookContext]: Resolving ExecutedFile (${renderType}):${nbAbsPath2}`
      );
      if (notebookMetadata) {
        addMetadata(nbAbsPath2, notebookMetadata);
      }
      return contributor(renderType).resolve(
        nbAbsPath2,
        token(),
        executedFile,
        notebookMetadata
      );
    },
    addRendering,
    removeRendering,
    render: async (nbAbsPath2, format14, renderType, services, notebookMetadata, project) => {
      debug(`[NotebookContext]: Rendering (${renderType}):${nbAbsPath2}`);
      if (notebookMetadata) {
        addMetadata(nbAbsPath2, notebookMetadata);
      }
      const notebook = notebooks[nbAbsPath2];
      const toRenderPath = notebook ? notebook[kQmdIPynb] ? notebook[kQmdIPynb].path : nbAbsPath2 : nbAbsPath2;
      const renderedFile = await contributor(renderType).render(
        toRenderPath,
        format14,
        token(),
        services,
        notebookMetadata,
        project
      );
      addRendering(nbAbsPath2, renderType, renderedFile, project);
      if (!notebooks[nbAbsPath2][renderType]) {
        throw new InternalError(
          "We just rendered and contributed a notebook, but it isn't present in the notebook context."
        );
      }
      return notebooks[nbAbsPath2][renderType];
    },
    preserve,
    cleanup: () => {
      debug(`[NotebookContext]: Starting Cleanup`);
      const hasNotebooks = Object.keys(notebooks).length > 0;
      if (hasNotebooks) {
        Object.keys(contributors).forEach((renderTypeStr) => {
          Object.values(notebooks).forEach((notebook) => {
            const renderType = renderTypeStr;
            if (!preserveNotebooks[notebook.source] || !preserveNotebooks[notebook.source].includes(renderType)) {
              const notebookOutput = notebook[renderType];
              if (notebookOutput && notebookOutput.cached !== true) {
                debug(
                  `[NotebookContext]: Cleanup (${renderType}):${notebook.source}`
                );
                debug(
                  `[NotebookContext]: Deleting (${notebookOutput.path}`
                );
                safeRemoveIfExists(notebookOutput.path);
                for (const supporting of notebookOutput.supporting) {
                  safeRemoveIfExists(supporting);
                }
              }
            }
          });
        });
      }
    }
  };
}

// project/types/single-file/single-file.ts
init_path();
init_log();
init_path2();
await init_project_environment();
await init_render_contexts();
await init_engine();
await init_project_shared();
init_cache3();
init_temp();
await init_project_context();
await init_extension();
async function singleFileProjectContext(source2, notebookContext2, renderOptions) {
  const environmentMemoizer = makeProjectEnvironmentMemoizer(notebookContext2);
  const temp = globalTempContext();
  const projectCacheBaseDir = temp.createDir();
  const normalizedDir = normalizePath(dirname4(source2));
  const result2 = {
    clone: () => result2,
    resolveBrand: (fileName) => projectResolveBrand(result2, fileName),
    dir: normalizedDir,
    engines: [],
    files: {
      input: []
    },
    notebookContext: notebookContext2,
    environment: () => environmentMemoizer(result2),
    renderFormats,
    fileInformationCache: new FileInformationCacheMap(),
    fileExecutionEngineAndTarget: (file) => {
      return fileExecutionEngineAndTarget(
        file,
        renderOptions?.flags,
        result2
      );
    },
    resolveFullMarkdownForFile: (engine, file, markdown, force) => {
      return projectResolveFullMarkdownForFile(
        result2,
        engine,
        file,
        markdown,
        force
      );
    },
    fileMetadata: async (file, force) => {
      return projectFileMetadata(result2, file, force);
    },
    isSingleFile: true,
    diskCache: await createProjectCache(projectCacheBaseDir),
    temp,
    cleanup: () => {
      cleanupFileInformationCache(result2);
      result2.diskCache.close();
    }
  };
  const extensionContext = renderOptions?.services.extension || createExtensionContext();
  result2.config = result2.config || { project: {} };
  result2.config = await resolveEngineExtensions(
    extensionContext,
    result2.config,
    result2.dir
  );
  if (renderOptions) {
    await mergeExtensionMetadata(result2, renderOptions);
    const outputDir = result2.config?.project?.["output-dir"];
    if (outputDir) {
      const willForceClean = renderOptions.flags?.clean !== false;
      warn(
        `An extension contributed 'output-dir: ${outputDir}' metadata for single-file render.
Output will go to that directory. The temporary .quarto directory will ${willForceClean ? "be cleaned up" : "NOT be cleaned up (--no-clean specified)"} after rendering.
To suppress this warning, use --output-dir flag instead of extension metadata.`
      );
      renderOptions.forceClean = willForceClean;
    }
  }
  temp.onCleanup(result2.cleanup);
  return result2;
}

// command/render/render-shared.ts
async function render(path3, options, pContext) {
  setInitializer(initYamlIntelligenceResourcesFromFilesystem);
  await initState();
  const nbContext = pContext?.notebookContext || notebookContext();
  let context = pContext || await projectContext(path3, nbContext, options);
  if (!context && options.flags?.outputDir) {
    context = await projectContextForDirectory(path3, nbContext, options);
    options.forceClean = options.flags.clean !== false;
  }
  if (!context) {
    context = await singleFileProjectContext(path3, nbContext, options);
  }
  if (context && options.setProjectDir) {
    Deno.env.set("QUARTO_PROJECT_DIR", context.dir);
  }
  if (Deno.statSync(path3).isDirectory) {
    let files;
    if (context) {
      const renderDir = normalizePath(path3);
      const projectDir = normalizePath(context.dir);
      if (renderDir !== projectDir) {
        files = context.files.input.filter(
          (file) => file.startsWith(renderDir)
        );
      }
      return renderProject(
        context,
        options,
        files
      );
    } else {
      throw new Error(
        "The specified directory ('" + path3 + "') is not a Quarto project.\n(If you have not specified a path, quarto will attempt to render the entire current directory as a project.)"
      );
    }
  } else if (context?.config) {
    if (isProjectInputFile(path3, context)) {
      return renderProject(context, options, [path3]);
    }
  }
  validateDocumentRenderFlags(options.flags);
  const result2 = await renderFiles(
    [{ path: path3 }],
    options,
    nbContext,
    void 0,
    void 0,
    context
  );
  const { engine } = await context.fileExecutionEngineAndTarget(
    path3
  );
  const partitioned = engine && result2.files.length > 0 ? await engine.partitionedMarkdown(path3) : void 0;
  const excludeDirs = context ? projectExcludeDirs(context) : [];
  const renderResult = {
    context,
    files: await Promise.all(result2.files.map(async (file) => {
      const resourceFiles = await resourceFilesFromRenderedFile(
        dirname4(path3),
        excludeDirs,
        file,
        partitioned
      );
      return {
        input: file.input,
        markdown: file.markdown,
        format: file.format,
        file: file.file,
        supporting: file.supporting,
        resourceFiles
      };
    })),
    error: result2.error,
    baseDir: normalizePath(dirname4(path3))
  };
  if (!renderResult.error && engine?.postRender) {
    for (const file of renderResult.files) {
      await engine.postRender(file);
    }
  }
  return renderResult;
}
function printWatchingForChangesMessage() {
  info("Watching files for changes", { format: green2 });
}
function previewUnableToRenderResponse() {
  return new Response("not found", {
    status: 404,
    headers: {
      "Content-Type": kTextPlain
    }
  });
}
var quartoRenderToken;
function renderToken() {
  const kQuartoRenderToken = "QUARTO_RENDER_TOKEN";
  if (quartoRenderToken === void 0) {
    quartoRenderToken = Deno.env.get(kQuartoRenderToken) || null;
    Deno.env.delete(kQuartoRenderToken);
  }
  return quartoRenderToken;
}
function validateDocumentRenderFlags(flags) {
  if (flags) {
    const projectOnly = {
      ["--output-dir"]: flags.outputDir,
      ["--site-url"]: flags.siteUrl
    };
    for (const arg of Object.keys(projectOnly)) {
      if (projectOnly[arg]) {
        throw new Error(
          `The ${arg} flag can only be used when rendering projects.`
        );
      }
    }
  }
}

// command/render/cmd.ts
await init_render_services();
init_constants6();
init_error2();
var renderCommand = new Command().name("render").stopEarly().arguments("[input:string] [...args]").description(
  "Render files or projects to various document types."
).option(
  "-t, --to",
  "Specify output format(s)."
).option(
  "-o, --output",
  "Write output to FILE (use '--output -' for stdout)."
).option(
  "--output-dir",
  "Write output to DIR (path is input/project relative)"
).option(
  "-M, --metadata",
  "Metadata value (KEY:VALUE)."
).option(
  "--site-url",
  "Override site-url for website or book output"
).option(
  "--execute",
  "Execute code (--no-execute to skip execution)."
).option(
  "-P, --execute-param",
  "Execution parameter (KEY:VALUE)."
).option(
  "--execute-params",
  "YAML file with execution parameters."
).option(
  "--execute-dir",
  "Working directory for code execution."
).option(
  "--execute-daemon",
  "Keep Jupyter kernel alive (defaults to 300 seconds)."
).option(
  "--execute-daemon-restart",
  "Restart keepalive Jupyter kernel before render."
).option(
  "--execute-debug",
  "Show debug output when executing computations."
).option(
  "--use-freezer",
  "Force use of frozen computations for an incremental file render."
).option(
  "--cache",
  "Cache execution output (--no-cache to prevent cache)."
).option(
  "--cache-refresh",
  "Force refresh of execution cache."
).option(
  "--no-clean",
  "Do not clean project output-dir prior to render"
).option(
  "--debug",
  "Leave intermediate files in place after render."
).option(
  "pandoc-args...",
  "Additional pandoc command line arguments."
).example(
  "Render Markdown",
  "quarto render document.qmd\nquarto render document.qmd --to html\nquarto render document.qmd --to pdf --toc"
).example(
  "Render Notebook",
  "quarto render notebook.ipynb\nquarto render notebook.ipynb --to docx\nquarto render notebook.ipynb --to pdf --toc"
).example(
  "Render Project",
  "quarto render\nquarto render projdir"
).example(
  "Render w/ Metadata",
  "quarto render document.qmd -M echo:false\nquarto render document.qmd -M code-fold:true"
).example(
  "Render to Stdout",
  "quarto render document.qmd --output -"
).action(async (options, input, ...args) => {
  if (options === void 0) {
    throw new InternalError("Expected `options` to be an object");
  }
  delete options.clean;
  if (Object.keys(options).length === 1) {
    const option = Object.keys(options)[0];
    const optionArg = option.replaceAll(
      /([A-Z])/g,
      (_match, p1) => `-${p1.toLowerCase()}`
    );
    if (input) {
      args.unshift(input);
      input = void 0;
    }
    args.unshift("--" + optionArg);
    delete options[option];
  }
  if (args.length > 0 && args[0] === "--help" || args[0] === "-h") {
    renderCommand.showHelp();
    return;
  }
  if (!input || input === kCliffyImplicitCwd) {
    input = Deno.cwd();
    debug(`Render: Using current directory (${input}) as implicit input`);
    const firstArg = args.find(
      (arg) => arg.endsWith(".qmd") || arg.endsWith(".ipynb")
    );
    if (firstArg) {
      warn(
        `\`quarto render\` invoked with no input file specified (the parameter order matters).
Quarto will render the current directory by default.
Did you mean to run \`quarto render ${firstArg} ${args.filter((arg) => arg !== firstArg).join(" ")}\`?
Use \`quarto render --help\` for more information.`
      );
    }
  }
  const inputs = [input];
  const firstPandocArg = args.findIndex((arg) => arg.startsWith("-"));
  if (firstPandocArg !== -1) {
    inputs.push(...args.slice(0, firstPandocArg));
    args = args.slice(firstPandocArg);
  }
  const pandocArgsWithOptionalValues = [
    "--file-scope",
    "--sandbox",
    "--standalone",
    "--ascii",
    "--toc",
    "--preserve-tabs",
    "--self-contained",
    "--embed-resources",
    "--no-check-certificate",
    "--strip-comments",
    "--reference-links",
    "--list-tables",
    "--listings",
    "--incremental",
    "--section-divs",
    "--html-q-tags",
    "--epub-title-page",
    "--webtex",
    "--mathjax",
    "--katex",
    "--trace",
    "--dump-args",
    "--ignore-args",
    "--fail-if-warnings",
    "--list-extensions"
  ];
  const normalizedArgs = [];
  for (const arg of args) {
    const equalSignIndex = arg.indexOf("=");
    if (equalSignIndex > 0 && arg.startsWith("-") && !pandocArgsWithOptionalValues.includes(arg.slice(0, equalSignIndex))) {
      normalizedArgs.push(arg.slice(0, equalSignIndex));
      normalizedArgs.push(arg.slice(equalSignIndex + 1));
    } else {
      normalizedArgs.push(arg);
    }
  }
  args = normalizedArgs;
  const flags = await parseRenderFlags(args);
  args = fixupPandocArgs(args, flags);
  let renderResult;
  let renderResultInput;
  for (const input2 of inputs) {
    for (const walk5 of expandGlobSync(input2)) {
      const services = renderServices(notebookContext());
      try {
        renderResultInput = relative4(Deno.cwd(), walk5.path) || ".";
        if (renderResult) {
          renderResult.context.cleanup();
        }
        renderResult = await render(renderResultInput, {
          services,
          flags,
          pandocArgs: args,
          useFreezer: flags.useFreezer === true,
          setProjectDir: true
        });
        if (renderResult.error) {
          renderResult.context.cleanup();
          throw renderResult.error;
        }
      } finally {
        services.cleanup();
      }
    }
  }
  if (renderResult && renderResultInput) {
    if (!options.flags?.quiet && options.flags?.output !== kStdOut) {
      const finalOutput = renderResultFinalOutput(
        renderResult,
        Deno.statSync(renderResultInput).isDirectory ? renderResultInput : dirname4(renderResultInput)
      );
      if (finalOutput) {
        info("Output created: " + finalOutput + "\n");
      }
      if (renderResult) {
        renderResult.context.cleanup();
      }
    }
  } else {
    throw new Error(`No valid input files passed to render`);
  }
});

// command/serve/cmd.ts
init_colors2();
init_log();
await init_project_context();

// command/serve/serve.ts
init_process();
await init_engine();
await init_render_services();

// core/previewurl.ts
init_log();
init_colors2();
init_process();
init_port_consts();
init_port();
async function resolveHostAndPort(options) {
  const host = options.host || kLocalhost;
  let port = options.port;
  if (port) {
    if (!await waitForPort({ port, hostname: host })) {
      throw new Error(`Requested port ${options.port} is already in use.`);
    }
  } else {
    port = findOpenPort();
  }
  return { host, port };
}
function previewURL(host, port, path3) {
  const showHost = host == "127.0.0.1" ? "localhost" : host;
  const url = `http://${showHost}:${port}/${path3}`;
  return url;
}
async function printBrowsePreviewMessage(host, port, path3) {
  if ((isJupyterServer() || isVSCodeTerminal()) && isPositWorkbench()) {
    const url = await rswURL(port, path3);
    info(`
Preview server: ${previewURL(host, port, path3 = "")}`);
    info(`
Browse at ${url}`, { format: green2 });
  } else if (isVSCodeTerminal() && isVSCodeServer()) {
    const proxyUrl = vsCodeServerProxyUri();
    if (proxyUrl.endsWith("/")) {
      path3 = path3.startsWith("/") ? path3.slice(1) : path3;
    } else {
      path3 = path3.startsWith("/") ? path3 : "/" + path3;
    }
    const browseUrl = proxyUrl.replace("{{port}}", `${port}`) + path3;
    info(`
Browse at ${browseUrl}`, { format: green2 });
  } else if (isJupyterHubServer()) {
    const httpReferrer = `${jupyterHubHttpReferrer() || "<jupyterhub-server-url>/"}user/${jupyterHubUser()}/`;
    info(
      `
Browse at ${httpReferrer}proxy/${port}/${path3}`,
      {
        format: green2
      }
    );
  } else {
    const url = previewURL(host, port, path3);
    if (!isRStudioServer()) {
      info(`Browse at `, {
        newline: false,
        format: green2
      });
    }
    info(url, { format: (str3) => underline2(green2(str3)) });
  }
}
async function rswURL(port, path3) {
  const server = Deno.env.get("RS_SERVER_URL");
  const session = Deno.env.get("RS_SESSION_URL");
  const portToken = await rswPortToken(port);
  const url = `${server}${session.slice(1)}p/${portToken}/${path3}`;
  return url;
}
async function rswPortToken(port) {
  const result2 = await execProcess(
    {
      cmd: "/usr/lib/rstudio-server/bin/rserver-url",
      args: [String(port)],
      stdout: "piped",
      stderr: "piped"
    }
  );
  if (result2.success) {
    return result2.stdout;
  } else {
    throw new Error(
      `Failed to map RSW port token (status ${result2.code})
${result2.stderr}`
    );
  }
}

// core/shell.ts
init_path2();
init_windows();
init_process();
init_platform();
async function openUrl(url) {
  const shellOpen = {
    windows: "explorer",
    darwin: "open"
    // otherwise "xdg-open"
    // assume generic unix
    // in 1.32.5 this is:
    // case "linux":
    // case "netbsd":
    // case "aix":
    // case "solaris":
    // case "illumos":
    // case "freebsd":
  };
  const cmd = shellOpen[os] || "xdg-open";
  const safeWindowsArgs = (() => {
    if (!isWindows4) {
      return void 0;
    }
    const safeArgs = requireQuoting([url]);
    if (safeArgs.status) {
      return safeArgs.args;
    }
    return void 0;
  })();
  if (safeWindowsArgs) {
    await safeWindowsExec(
      cmd,
      safeWindowsArgs,
      (cmd2) => {
        return execProcess({
          cmd: cmd2[0],
          args: cmd2.slice(1),
          stdout: "piped",
          stderr: "piped"
        });
      }
    );
  } else {
    if (await which(cmd)) {
      execProcess({ cmd, args: [url] });
    }
  }
}

// command/serve/serve.ts
init_log();
await init_project_context();
async function renderForServe(file, format14) {
  const services = renderServices(notebookContext());
  try {
    const result2 = await render(file, {
      services,
      flags: {
        to: format14,
        execute: true
      },
      previewServer: true
    });
    return result2;
  } finally {
    services.cleanup();
  }
}
async function serve(options) {
  const { host, port } = await resolveHostAndPort(options);
  const nbContext = notebookContext();
  const project = await projectContext(options.input, nbContext) || await singleFileProjectContext(options.input, nbContext);
  const engine = await fileExecutionEngine(options.input, void 0, project);
  if (engine?.run) {
    if (options.render) {
      const result2 = await renderForServe(options.input, options.format);
      if (result2.error) {
        throw result2.error;
      }
    }
    const onReady = async () => {
      if (isRStudio()) {
        const url = previewURL(host, port, "");
        info(`Listening on ${url}`);
      } else {
        printBrowsePreviewMessage(host, port, "");
      }
      if (options.browser && !isServerSession()) {
        await openUrl(previewURL(host, port, ""));
      }
    };
    await engine.run({
      ...options,
      input: options.input,
      host,
      port,
      onReady
    });
    return processSuccessResult();
  }
  return Promise.reject(
    new Error("Unable to run computations for input file")
  );
}

// command/serve/cmd.ts
await init_render_contexts();

// command/preview/preview.ts
init_log();
init_path();
init_fs();
init_lodash();
init_css();
init_log2();
init_http();

// core/http-devserver.ts
init_path();
init_lodash();

// core/ejs.ts
init_path();
init_lodash();
init_text2();
init_error2();
function renderEjs(file, data3, removeEmptyLines = true, cache3 = true) {
  const template2 = compileTemplate(file, removeEmptyLines, cache3);
  if (!template2) {
    throw new InternalError(
      `Rendering the template ${file} failed unexpectedly.`
    );
  }
  return lines(template2(data3).trimLeft()).filter((line) => !removeEmptyLines || line.trim().length > 0).join("\n") + "\n";
}
var compiledTemplates = /* @__PURE__ */ new Map();
function compileTemplate(file, removeEmptyLines, cache3 = true) {
  const mtime = Deno.statSync(file).mtime?.getTime() || Number.MAX_VALUE;
  const compile = () => {
    const template2 = `<% const partial = (file, data) => print(include(file, data)); %>
    ${Deno.readTextFileSync(file)}`;
    return template(template2, {
      imports: {
        include: (includeFile, includeData) => {
          return renderEjs(
            join4(dirname4(file), includeFile),
            includeData,
            removeEmptyLines
          );
        }
      }
    });
  };
  if (!cache3) {
    return compile();
  } else {
    const cachedTemplate = compiledTemplates.get(file);
    if (!cachedTemplate || cachedTemplate.mtime < mtime) {
      compiledTemplates.set(
        file,
        {
          mtime,
          compileTemplate: compile()
        }
      );
    }
  }
  return compiledTemplates.get(file)?.compileTemplate;
}

// core/http-devserver.ts
init_http();
init_log2();
init_resources2();
init_mime();
function httpDevServer(timeout, isRendering, stopServer, isPresentation) {
  const clients = [];
  const hasClients = () => {
    return isRendering() || !!clients.find((client) => client.socket.readyState !== WebSocket.CLOSED);
  };
  let onSocketClose;
  if (timeout > 0 && !isRStudioPreview()) {
    onSocketClose = debounce(() => {
      if (!hasClients()) {
        stopServer();
      }
    }, timeout * 1e3);
  }
  const broadcast = (msg5) => {
    for (let i6 = clients.length - 1; i6 >= 0; i6--) {
      const socket = clients[i6].socket;
      try {
        socket.send(msg5);
      } catch (_e) {
      }
    }
  };
  HttpDevServerRenderMonitor.monitor({
    onRenderStart: (lastRenderTime) => {
      broadcast(`render:start:${lastRenderTime || 0}`);
    },
    onRenderStop: (success) => {
      broadcast(`render:stop:${success}`);
    }
  });
  LogEventsHandler.onLog(async (logRecord, msg5) => {
    broadcast(
      "log:" + JSON.stringify({
        ...logRecord,
        msgFormatted: msg5
      })
    );
  });
  let injectClientInitialized = false;
  let iframeURL;
  const getiFrameURL = (req) => {
    if (!injectClientInitialized) {
      iframeURL = viewerIFrameURL(req);
      injectClientInitialized = true;
    }
    return iframeURL;
  };
  const kQuartoPreviewJs = "quarto-preview.js";
  return {
    handle: (req) => {
      const url = new URL(req.url);
      if (url.pathname.endsWith(kQuartoPreviewJs)) {
        return true;
      }
      if (req.headers.get("upgrade") === "websocket") {
        return true;
      }
      return false;
    },
    request: async (req) => {
      const url = new URL(req.url);
      if (url.pathname.endsWith(kQuartoPreviewJs)) {
        const path3 = resourcePath(join4("preview", kQuartoPreviewJs));
        const contents = await Deno.readFile(path3);
        return httpContentResponse(contents, "text/javascript");
      } else {
        try {
          const { socket, response } = Deno.upgradeWebSocket(req);
          const client = { socket };
          socket.onmessage = (ev) => {
            if (ev.data === "stop") {
              stopServer();
            }
          };
          if (onSocketClose) {
            socket.onclose = onSocketClose;
          }
          clients.push(client);
          return Promise.resolve(response);
        } catch (e5) {
          maybeDisplaySocketError(e5);
          return Promise.resolve(void 0);
        }
      }
    },
    clientHtml: (req, inputFile) => {
      const script = devServerClientScript(
        inputFile,
        isPresentation,
        getiFrameURL(req)
      );
      return script;
    },
    injectClient: (req, file, inputFile, contentType2) => {
      const script = devServerClientScript(
        inputFile,
        isPresentation,
        getiFrameURL(req)
      );
      const scriptContents = new TextEncoder().encode("\n" + script);
      const fileWithScript = new Uint8Array(
        file.length + scriptContents.length
      );
      fileWithScript.set(file);
      fileWithScript.set(scriptContents, file.length);
      return {
        contentType: contentType2 || kTextHtml,
        body: fileWithScript
      };
    },
    reloadClients: async (reloadTarget = "") => {
      for (let i6 = clients.length - 1; i6 >= 0; i6--) {
        const socket = clients[i6].socket;
        try {
          const message = "reload";
          await socket.send(`${message}${reloadTarget}`);
        } catch (e5) {
          maybeDisplaySocketError(e5);
        } finally {
          if (!socket.CLOSED && !socket.CLOSING) {
            try {
              socket.close();
            } catch (e5) {
              maybeDisplaySocketError(e5);
            }
          }
          clients.splice(i6, 1);
        }
      }
    },
    hasClients
  };
}
var HttpDevServerRenderMonitor = class {
  static onRenderStart() {
    this.renderStart_ = Date.now();
    this.handlers_.forEach(
      (handler) => handler.onRenderStart(this.lastRenderTime_)
    );
  }
  static onRenderStop(success) {
    if (this.renderStart_) {
      this.lastRenderTime_ = Date.now() - this.renderStart_;
      this.renderStart_ = void 0;
    }
    this.handlers_.forEach((handler) => handler.onRenderStop(success));
  }
  static monitor(handler) {
    this.handlers_.push(handler);
  }
  static handlers_ = new Array();
  static renderStart_;
  static lastRenderTime_;
};
function devServerClientScript(inputFile, isPresentation, iframeURL) {
  const options = {
    origin: iframeURL ? devserverOrigin(iframeURL) : null,
    search: iframeURL ? iframeURL.search : null,
    inputFile: inputFile || null,
    isPresentation: !!isPresentation
  };
  return renderEjs(resourcePath(`preview/quarto-preview.html`), options);
}
function devserverOrigin(iframeURL) {
  if (isRStudioServer()) {
    return iframeURL.searchParams.get("host") || iframeURL.origin;
  } else {
    return iframeURL.origin;
  }
}
function viewerIFrameURL(req) {
  for (const url of [req.url, req.referrer]) {
    const isViewer = url && (url.includes("capabilities=") || // rstudio viewer
    url.includes("vscodeBrowserReqId=") || // vscode simple browser
    url.includes("quartoPreviewReqId="));
    if (isViewer) {
      return new URL(url);
    }
  }
}

// command/preview/preview.ts
init_mime();

// core/lib/promise.ts
var PromiseQueue = class {
  queue = new Array();
  running = false;
  enqueue(promise, clearPending = false) {
    return new Promise((resolve16, reject2) => {
      if (clearPending) {
        this.queue.splice(0, this.queue.length);
      }
      this.queue.push({
        promise,
        resolve: resolve16,
        reject: reject2
      });
      this.dequeue();
    });
  }
  isRunning() {
    return this.running;
  }
  dequeue() {
    if (this.running) {
      return false;
    }
    const item = this.queue.shift();
    if (!item) {
      return false;
    }
    try {
      this.running = true;
      item.promise().then((value) => {
        this.running = false;
        item.resolve(value);
        this.dequeue();
      }).catch((err2) => {
        this.running = false;
        item.reject(err2);
        this.dequeue();
      });
    } catch (err2) {
      if (!(err2 instanceof Error)) throw err2;
      this.running = false;
      item.reject(err2);
      this.dequeue();
    }
    return true;
  }
};

// command/preview/preview.ts
init_render();
await init_render_services();
await init_render_contexts();
init_flags2();
init_types5();

// core/pdfjs.ts
init_path();
init_hash2();
init_mime();
init_path2();
init_resources2();
init_text2();
var kPdfJsDefaultFile = "compressed.tracemonkey-pldi-09.pdf";
var kPdfJsViewerToolbarButtonSelector = `.toolbarButton,
.dropdownToolbarButton,
.secondaryToolbarButton,
.overlayButton {`;
var kPdfJsViewerSidebarTransitionDurationPattern = /(--sidebar-transition-duration: )(\d+ms)/;
var kPdfJsInitialPath = "web/viewer.html";
function pdfJsBaseDir() {
  return formatResourcePath("pdf", "pdfjs");
}
function pdfJsFileHandler(pdfFile, htmlHandler) {
  let isViewer;
  return async (file, req) => {
    if (isViewer === void 0) {
      isViewer = !!viewerIFrameURL(req);
    }
    if (htmlHandler) {
      const contents = await htmlHandler(file, req);
      if (contents) {
        return contents;
      }
    }
    const previewPath = (dir, file2) => {
      return pathWithForwardSlashes(join4(pdfJsBaseDir(), dir, file2));
    };
    if (file === previewPath("web", "viewer.js")) {
      let viewerJs = Deno.readTextFileSync(file).replace(
        kPdfJsDefaultFile,
        basename4(pdfFile())
      );
      if (isViewer) {
        viewerJs = viewerJs.replace(
          "sidebarView: sidebarView",
          "sidebarView: _ui_utils.SidebarView.NONE"
        );
      }
      return {
        contentType: contentType(file),
        body: new TextEncoder().encode(viewerJs)
      };
    } else if (file == previewPath("web", "viewer.css")) {
      const viewerCss = normalizeNewlines(Deno.readTextFileSync(file)).replace(
        kPdfJsViewerToolbarButtonSelector,
        kPdfJsViewerToolbarButtonSelector + "\n  z-index: 199;"
      ).replace(
        kPdfJsViewerSidebarTransitionDurationPattern,
        "$1 0"
      );
      return {
        contentType: contentType(file),
        body: new TextEncoder().encode(viewerCss)
      };
    } else if (file === previewPath("build", "pdf.worker.js")) {
      const filePathHash = "quarto-preview-pdf-" + await md5HashAsync(pdfFile());
      const workerJs = Deno.readTextFileSync(file).replace(
        /(key: "fingerprint",\s+get: function get\(\) {\s+)(var hash;)/,
        `$1return "${filePathHash}"; $2`
      );
      return {
        contentType: contentType(file),
        body: new TextEncoder().encode(workerJs)
      };
    } else if (file === previewPath("web", basename4(pdfFile()))) {
      return {
        contentType: contentType(file),
        body: Deno.readFileSync(pdfFile())
      };
    }
  };
}

// command/preview/preview.ts
init_types4();
await init_project_shared();
await init_project_context();
init_path2();
init_jupyter();

// core/watch.ts
init_fs();
init_log();
init_async();
function watchForFileChanges(files, pollingInterval) {
  const fileList = () => {
    if (Array.isArray(files)) {
      return files;
    } else {
      return files();
    }
  };
  const lastModified = /* @__PURE__ */ new Map();
  fileList().forEach(
    (file) => lastModified.set(file, existsSync2(file) ? Deno.statSync(file).mtime : null)
  );
  if (!pollingInterval) {
    pollingInterval = Math.max(200, lastModified.size);
  }
  let stop = false;
  return {
    close: () => {
      stop = true;
    },
    async *[Symbol.asyncIterator]() {
      try {
        while (!stop) {
          await sleep(pollingInterval);
          const created = [];
          const modified = [];
          const currentFiles = fileList();
          for (let i6 = 0; i6 < currentFiles.length; i6++) {
            const file = currentFiles[i6];
            if (existsSync2(file)) {
              const prevMod = lastModified.get(file);
              const lastMod = Deno.statSync(file).mtime;
              lastModified.set(file, lastMod);
              if (!prevMod) {
                created.push(file);
              } else if (lastMod?.getTime() !== prevMod?.getTime()) {
                modified.push(file);
              }
            }
          }
          if (created.length > 0) {
            yield {
              kind: "create",
              paths: created
            };
          }
          if (modified.length > 0) {
            yield {
              kind: "modify",
              paths: modified
            };
          }
        }
      } catch (err2) {
        if (!(err2 instanceof Error)) throw err2;
        error(
          "Unexpected error while scanning for file changes: " + err2.message
        );
      }
    }
  };
}

// command/preview/preview.ts
init_quarto();
init_cleanup();
await init_extension();
init_constants6();
init_config2();
init_port_consts();
init_port();

// preview/preview-static.ts
init_path();
init_resources2();

// preview/preview-text.ts
init_constants6();
init_format5();
init_mime();
init_process();
init_resources2();
init_fs();
init_path();
var jatsStaticResources = () => {
  return [
    {
      name: "quarto-jats-preview.css",
      dir: "jats",
      contentType: "text/css"
    },
    {
      name: "quarto-jats-html.xsl",
      dir: "jats",
      contentType: "text/xsl",
      injectClient: (contents, client) => {
        const protectedClient = client.replaceAll(
          /(<style.*?>)|(<script.*?>)/g,
          (substring) => {
            return `${substring}
<![CDATA[`;
          }
        ).replaceAll(
          /(<\/style.*?>)|(<\/script.*?>)/g,
          (substring) => {
            return `]]>
${substring}`;
          }
        ).replaceAll("data-micromodal-close", 'data-micromodal-close="true"');
        const bodyContents = contents.replace(
          "<!-- quarto-after-body -->",
          protectedClient
        );
        return new TextEncoder().encode(bodyContents);
      }
    }
  ];
};
async function previewTextContent(file, inputFile, format14, req, injectClient) {
  const rawPreviewMode = format14.metadata[kPreviewMode] === kPreviewModeRaw;
  if (!rawPreviewMode && isJatsOutput(format14.pandoc)) {
    const xml = await jatsPreviewXml(file, req);
    return {
      contentType: kTextXml,
      body: new TextEncoder().encode(xml)
    };
  } else if (!rawPreviewMode && format14.identifier[kBaseFormat] === "gfm") {
    const html = await gfmPreview(file, req);
    return injectClient(
      req,
      new TextEncoder().encode(html),
      inputFile
    );
  } else {
    const html = await textPreviewHtml(file, req);
    const fileContents = new TextEncoder().encode(html);
    return injectClient(req, fileContents, inputFile);
  }
}
async function jatsPreviewXml(file, _request) {
  const fileContents = await Deno.readTextFile(file);
  let xmlContents = fileContents.replace(
    /<\?xml version="1.0" encoding="utf-8"\s*\?>/,
    '<?xml version="1.0" encoding="utf-8" ?>\n<?xml-stylesheet href="quarto-jats-html.xsl" type="text/xsl" ?>'
  );
  xmlContents = xmlContents.replace(
    /<!DOCTYPE((.|\n)*?)>/,
    ""
  );
  return xmlContents;
}
function darkHighlightStyle(request2) {
  const kQuartoPreviewThemeCategory = "quartoPreviewThemeCategory";
  const themeCategory = new URL(request2.url).searchParams.get(
    kQuartoPreviewThemeCategory
  );
  return themeCategory && themeCategory !== "light";
}
async function textPreviewHtml(file, req) {
  const darkMode = darkHighlightStyle(req);
  const backgroundColor = darkMode ? "rgb(30,30,30)" : "#FFFFFF";
  const frontMatter = ["---"];
  frontMatter.push(`pagetitle: "Quarto Preview"`);
  frontMatter.push(`document-css: false`);
  frontMatter.push("---");
  const styles = [
    "```{=html}",
    `<style type="text/css">`,
    `body { margin: 8px 12px; background-color: ${backgroundColor} }`,
    `div.sourceCode { background-color: transparent; }`,
    `</style>`,
    "```"
  ];
  const lang = (extname4(file) || ".default").slice(1).toLowerCase();
  const kFence = "````````````````";
  const markdown = frontMatter.join("\n") + "\n\n" + styles.join("\n") + "\n\n" + kFence + lang + "\n" + Deno.readTextFileSync(file) + "\n" + kFence;
  const cmd = [pandocBinaryPath()];
  cmd.push("--to", "html");
  cmd.push(
    "--syntax-highlighting",
    textHighlightThemePath("atom-one", darkMode ? "dark" : "light")
  );
  cmd.push("--standalone");
  const result2 = await execProcess({
    cmd: cmd[0],
    args: cmd.slice(1),
    stdout: "piped"
  }, markdown);
  if (result2.success) {
    return result2.stdout;
  } else {
    throw new Error();
  }
}
async function gfmPreview(file, request2) {
  const workingDir = Deno.makeTempDirSync();
  try {
    const darkMode = darkHighlightStyle(request2);
    const template2 = formatResourcePath("gfm", "template.html");
    const filter3 = formatResourcePath("gfm", "mermaid.lua");
    const mermaidJs = formatResourcePath(
      "html",
      join4("mermaid", "mermaid.min.js")
    );
    const includeInHeader = [];
    for (const path3 of [mermaidJs]) {
      const js = Deno.readTextFileSync(path3);
      const contents = `<script type="text/javascript">
${js}
<\/script>`;
      const target = join4(workingDir, basename4(path3));
      Deno.writeTextFileSync(target, contents);
      includeInHeader.push(target);
    }
    const jsInit = `
<script>
  mermaid.initialize({startOnLoad:true, theme: '${darkMode ? "dark" : "default"}'});
<\/script>`;
    const css = formatResourcePath(
      "gfm",
      join4(
        "github-markdown-css",
        darkMode ? "github-markdown-dark.css" : "github-markdown-light.css"
      )
    );
    const cssTempFile = join4(workingDir, "github.css");
    const cssContents = `<style>
${Deno.readTextFileSync(css)}
</style>
${jsInit}`;
    Deno.writeTextFileSync(cssTempFile, cssContents);
    includeInHeader.push(cssTempFile);
    const highlightPath = textHighlightThemePath(
      "github",
      darkMode ? "dark" : "light"
    );
    const cmd = [pandocBinaryPath()];
    cmd.push("-f");
    cmd.push("gfm");
    cmd.push("-t");
    cmd.push("html");
    cmd.push("--template");
    cmd.push(template2);
    includeInHeader.forEach((include2) => {
      cmd.push("--include-in-header");
      cmd.push(include2);
    });
    cmd.push("--lua-filter");
    cmd.push(filter3);
    if (highlightPath) {
      cmd.push("--syntax-highlighting");
      cmd.push(highlightPath);
    }
    cmd.push("--mathjax");
    const result2 = await execProcess(
      { cmd: cmd[0], args: cmd.slice(1), stdout: "piped", stderr: "piped" },
      Deno.readTextFileSync(file)
    );
    if (result2.success) {
      return result2.stdout;
    } else {
      throw new Error(
        `Failed to render citation: error code ${result2.code}
${result2.stderr}`
      );
    }
  } finally {
    safeRemoveSync(workingDir, { recursive: true });
  }
}

// preview/preview-static.ts
var staticResource = async (baseDir, file) => {
  const filename = relative4(baseDir, file);
  const resource = kStaticResources.find((resource2) => {
    return resource2.name === filename;
  });
  if (resource) {
    const dir = resource.dir ? join4("preview", resource.dir) : "preview";
    const path3 = resourcePath(join4(dir, filename));
    const contents = await Deno.readFile(path3);
    return {
      ...resource,
      contents
    };
  }
};
var kStaticResources = [
  ...jatsStaticResources()
];

// command/preview/preview.ts
async function resolvePreviewOptions(options, project) {
  if (project?.config?.project.preview) {
    options = mergeConfigs(project.config.project.preview, options);
  }
  const resolved = mergeConfigs({
    host: kLocalhost,
    browser: true,
    [kProjectWatchInputs]: !isRStudio(),
    timeout: 0,
    navigate: true
  }, options);
  if (resolved.port) {
    if (!await waitForPort({ port: resolved.port, hostname: resolved.host })) {
      throw new Error(`Requested port ${options.port} is already in use.`);
    }
  } else {
    resolved.port = findOpenPort();
  }
  return resolved;
}
function previewInitialPath(outputFile5, project) {
  if (isPdfContent(outputFile5)) {
    return kPdfJsInitialPath;
  }
  if (project && !project.isSingleFile) {
    return pathWithForwardSlashes(
      relative4(projectOutputDir(project), outputFile5)
    );
  }
  return "";
}
async function preview(file, flags, pandocArgs, options, pProject) {
  const nbContext = pProject?.notebookContext ?? notebookContext();
  const project = pProject ?? await projectContext(file, nbContext) ?? await singleFileProjectContext(file, nbContext);
  onCleanup(() => {
    project.cleanup();
  });
  const format14 = await previewFormat(file, project, flags.to, void 0);
  setPreviewFormat(format14, flags, pandocArgs);
  let isRendering = false;
  const render2 = async (to) => {
    const renderFlags = { ...flags, to: to || flags.to };
    const services = renderServices(nbContext);
    try {
      HttpDevServerRenderMonitor.onRenderStart();
      isRendering = true;
      const result3 = await renderForPreview(
        file,
        services,
        renderFlags,
        pandocArgs,
        project
      );
      HttpDevServerRenderMonitor.onRenderStop(true);
      return result3;
    } catch (error2) {
      HttpDevServerRenderMonitor.onRenderStop(false);
      throw error2;
    } finally {
      isRendering = false;
      services.cleanup();
    }
  };
  const result2 = await render2();
  options = {
    ...options,
    ...await resolvePreviewOptions(options)
  };
  const ac = new AbortController();
  const stopServer = () => ac.abort();
  const reloader = httpDevServer(
    options.timeout,
    () => isRendering,
    stopServer,
    options.presentation || format14 === "revealjs"
  );
  const changeHandler = createChangeHandler(
    result2,
    reloader,
    render2,
    options[kProjectWatchInputs]
  );
  const handler = isPdfContent(result2.outputFile) ? pdfFileRequestHandler(
    result2.outputFile,
    normalizePath(file),
    flags,
    result2.format,
    options.port,
    reloader,
    changeHandler.render,
    project
  ) : project && !project.isSingleFile ? projectHtmlFileRequestHandler(
    project,
    normalizePath(file),
    flags,
    result2.format,
    reloader,
    changeHandler.render
  ) : htmlFileRequestHandler(
    result2.outputFile,
    normalizePath(file),
    flags,
    result2.format,
    reloader,
    changeHandler.render,
    project
  );
  const initialPath = previewInitialPath(result2.outputFile, project);
  if (options.browser && !isServerSession() && isBrowserPreviewable(result2.outputFile)) {
    await openUrl(previewURL(options.host, options.port, initialPath));
  }
  await printBrowsePreviewMessage(options.host, options.port, initialPath);
  previewMonitorResources(stopServer);
  const server = Deno.serve(
    { signal: ac.signal, port: options.port, hostname: options.host },
    async (req) => {
      try {
        return await handler(req);
      } catch (err2) {
        if (err2 instanceof Error) {
          warn(err2.message);
        }
        throw err2;
      }
    }
  );
  await server.finished;
}
function isPreviewRenderRequest(req) {
  if (req.url.includes(kQuartoRenderCommand)) {
    return true;
  } else {
    const token = renderToken();
    if (token) {
      return req.url.includes(token);
    } else {
      return false;
    }
  }
}
function isPreviewTerminateRequest(req) {
  const kTerminateToken = "4231F431-58D3-4320-9713-994558E4CC45";
  return req.url.includes(kTerminateToken);
}
function previewRenderRequest(req, hasClients, baseDir) {
  const match = req.url.match(
    new RegExp(`/${kQuartoRenderCommand}/(.*)$`)
  );
  if (match && baseDir) {
    return {
      version: 1,
      path: join4(baseDir, match[1])
    };
  } else {
    const token = renderToken();
    if (token && req.url.includes(token)) {
      const url = new URL(req.url);
      const path3 = url.searchParams.get("path");
      if (path3) {
        if (hasClients) {
          return {
            version: 2,
            path: path3,
            format: url.searchParams.get("format") || void 0
          };
        }
      }
    }
  }
}
async function previewRenderRequestIsCompatible(request2, project, format14) {
  if (request2.version === 1) {
    return true;
  } else {
    const reqFormat = await previewFormat(
      request2.path,
      project,
      request2.format,
      void 0
    );
    return reqFormat === format14;
  }
}
async function previewFormat(file, project, format14, formats2) {
  if (format14) {
    return format14;
  }
  formats2 = formats2 || await withRenderServices(
    project.notebookContext,
    (services) => renderFormats(file, services, "all", project)
  );
  format14 = Object.keys(formats2)[0] || "html";
  return format14;
}
function setPreviewFormat(format14, flags, pandocArgs) {
  flags.to = format14;
  replacePandocArg(pandocArgs, "--to", format14);
}
function handleRenderResult(file, renderResult) {
  const finalOutput = renderResultFinalOutput(
    renderResult,
    dirname4(file)
  );
  if (!finalOutput) {
    throw new Error("No output created by quarto render " + basename4(file));
  }
  info("Output created: " + finalOutput + "\n");
  return finalOutput;
}
async function renderForPreview(file, services, flags, pandocArgs, project) {
  if (project?.fileInformationCache) {
    project.fileInformationCache.invalidateForFile(file);
  }
  const renderResult = await render(file, {
    services,
    flags,
    pandocArgs,
    previewServer: true,
    setProjectDir: project !== void 0
  }, project);
  if (renderResult.error) {
    throw renderResult.error;
  }
  const finalOutput = handleRenderResult(file, renderResult);
  printWatchingForChangesMessage();
  file = normalizePath(file);
  const filesDir = join4(dirname4(file), inputFilesDir(file));
  const resourceFiles = renderResult.files.reduce(
    (resourceFiles2, file2) => {
      const resources = file2.resourceFiles.concat(
        cssFileResourceReferences(file2.resourceFiles)
      );
      return resourceFiles2.concat(
        resources.filter((resFile) => !resFile.startsWith(filesDir))
      );
    },
    []
  );
  const extensionFiles = extensionFilesFromDirs(
    inputExtensionDirs(file, project?.dir)
  );
  extensionFiles.push(...renderResult.files.reduce(
    (extensionFiles2, file2) => {
      const shortcodes = file2.format.render.shortcodes || [];
      const filters = (file2.format.pandoc.filters || []).map(
        (filter3) => isPandocFilter(filter3) ? filter3.path : filter3
      );
      const ipynbFilters = file2.format.execute["ipynb-filters"] || [];
      [...shortcodes, ...filters.map((filter3) => filter3), ...ipynbFilters].forEach((extensionFile2) => {
        if (!isAbsolute4(extensionFile2)) {
          const extensionFullPath = join4(dirname4(file2.input), extensionFile2);
          if (existsSync2(extensionFullPath)) {
            extensionFiles2.push(normalizePath(extensionFullPath));
          }
        }
      });
      return extensionFiles2;
    },
    []
  ));
  return {
    file,
    format: renderResult.files[0].format,
    outputFile: join4(dirname4(file), finalOutput),
    extensionFiles,
    resourceFiles
  };
}
function createChangeHandler(result2, reloader, render2, renderOnChange, reloadFileFilter = () => true, ignoreChanges) {
  const renderQueue = new PromiseQueue();
  let watcher;
  let lastResult = result2;
  const renderHandler = async (to) => {
    try {
      if (to && watcher) {
        watcher.stop();
      }
      const result3 = await renderQueue.enqueue(async () => {
        return render2(to);
      }, true);
      if (result3) {
        sync(result3);
      }
      return result3;
    } catch (e5) {
      if (e5 instanceof Error && e5.message) {
        if (isJupyterNotebook(result2.file) && e5.message.indexOf("Unexpected end of JSON input") !== -1) {
          return;
        }
        logError(e5);
      }
    }
  };
  const sync = (result3) => {
    const requiresSync = !watcher || resultRequiresSync(result3, lastResult);
    lastResult = result3;
    if (requiresSync) {
      if (watcher) {
        watcher.stop();
      }
      const watches = [];
      if (renderOnChange) {
        watches.push({
          files: [result3.file],
          handler: debounce(renderHandler, 50)
        });
      }
      watches.push({
        files: result3.extensionFiles,
        handler: debounce(renderHandler, 50)
      });
      const reloadFiles = isPdfContent(result3.outputFile) ? pdfReloadFiles(result3) : resultReloadFiles(result3);
      const reloadTarget = isPdfContent(result3.outputFile) ? "/" + kPdfJsInitialPath : "";
      const removeUrlFragment = (file) => file.replace(/#.*$/, "").replace(/\?.*$/, "");
      watches.push({
        files: reloadFiles.filter(reloadFileFilter).map(removeUrlFragment),
        handler: debounce(async () => {
          await renderQueue.enqueue(async () => {
            await reloader.reloadClients(reloadTarget);
            return void 0;
          });
        }, 50)
      });
      watcher = previewWatcher(watches, ignoreChanges);
      watcher.start();
    }
  };
  sync(result2);
  return {
    render: renderHandler
  };
}
function previewWatcher(watches, ignoreChanges) {
  existsSync2;
  watches = watches.map((watch) => {
    return {
      ...watch,
      files: watch.files.filter((s5) => existsSync2(s5)).map((file) => {
        return normalizePath(file);
      })
    };
  });
  const handlerForFile = (file) => {
    const watch = watches.find((watch2) => watch2.files.includes(file));
    return watch?.handler;
  };
  const files = watches.flatMap((watch) => watch.files);
  const fsWatcher = watchForFileChanges(files);
  const watchForChanges = async () => {
    for await (const event of fsWatcher) {
      try {
        if (event.kind === "modify" && (!ignoreChanges || !ignoreChanges(event.paths))) {
          const handlers3 = /* @__PURE__ */ new Set();
          event.paths.forEach((path3) => {
            const handler = handlerForFile(path3);
            if (handler && !handlers3.has(handler)) {
              handlers3.add(handler);
            }
          });
          for (const handler of handlers3) {
            await handler();
          }
        }
      } catch (e5) {
        logError(e5);
      }
    }
  };
  return {
    start: watchForChanges,
    stop: () => fsWatcher.close()
  };
}
function projectHtmlFileRequestHandler(context, inputFile, flags, format14, reloader, renderHandler) {
  return httpFileRequestHandler(
    htmlFileRequestHandlerOptions(
      projectOutputDir(context),
      "index.html",
      inputFile,
      flags,
      format14,
      reloader,
      renderHandler,
      context
    )
  );
}
function htmlFileRequestHandler(htmlFile, inputFile, flags, format14, reloader, renderHandler, context) {
  return httpFileRequestHandler(
    htmlFileRequestHandlerOptions(
      dirname4(htmlFile),
      basename4(htmlFile),
      inputFile,
      flags,
      format14,
      reloader,
      renderHandler,
      context
    )
  );
}
function htmlFileRequestHandlerOptions(baseDir, defaultFile, inputFile, flags, format14, devserver, renderHandler, project) {
  let invalidateDevServerReRender = false;
  return {
    baseDir,
    defaultFile,
    printUrls: "404",
    onRequest: async (req) => {
      if (devserver.handle(req)) {
        return Promise.resolve(devserver.request(req));
      } else if (isPreviewTerminateRequest(req)) {
        exitWithCleanup(0);
      } else if (req.url.endsWith("/quarto-render/")) {
        renderHandler();
        return Promise.resolve(httpContentResponse("rendered"));
      } else if (isPreviewRenderRequest(req)) {
        const outputFile5 = format14.pandoc[kOutputFile];
        const prevReq = previewRenderRequest(
          req,
          !isBrowserPreviewable(outputFile5) || devserver.hasClients()
        );
        if (!invalidateDevServerReRender && prevReq && existsSync2(prevReq.path) && normalizePath(prevReq.path) === normalizePath(inputFile) && await previewRenderRequestIsCompatible(prevReq, project, flags.to)) {
          renderHandler();
          return Promise.resolve(httpContentResponse("rendered"));
        } else {
          return Promise.resolve(previewUnableToRenderResponse());
        }
      } else {
        return Promise.resolve(void 0);
      }
    },
    onFile: async (file, req) => {
      const staticResponse = await staticResource(baseDir, file);
      if (staticResponse) {
        const resolveBody = () => {
          if (staticResponse.injectClient) {
            const client = devserver.clientHtml(
              req,
              inputFile
            );
            const contents = new TextDecoder().decode(
              staticResponse.contents
            );
            return staticResponse.injectClient(contents, client);
          } else {
            return staticResponse.contents;
          }
        };
        const body = resolveBody();
        return {
          body,
          contentType: staticResponse.contentType
        };
      }
      let renderFormat = format14;
      if (project) {
        const input = await inputFileForOutputFile(
          project,
          relative4(baseDir, file)
        );
        if (input) {
          renderFormat = input.format;
          if (renderFormat !== format14 && fileRequiresRender(input.file, file)) {
            invalidateDevServerReRender = true;
            await renderHandler(renderFormat.identifier[kTargetFormat]);
          }
        }
      }
      if (req.headers.get("sec-fetch-dest") === "empty" && req.headers.get("sec-fetch-mode") === "cors") {
        return;
      }
      if (isHtmlContent(file)) {
        if (renderFormat.formatPreviewFile) {
          file = renderFormat.formatPreviewFile(file, renderFormat);
        }
        const fileContents = await Deno.readFile(file);
        return devserver.injectClient(req, fileContents, inputFile);
      } else if (isTextContent(file)) {
        return previewTextContent(
          file,
          inputFile,
          format14,
          req,
          devserver.injectClient
        );
      }
    }
  };
}
function fileRequiresRender(inputFile, outputFile5) {
  if (safeExistsSync(outputFile5)) {
    return (Deno.statSync(inputFile).mtime?.valueOf() || 0) > (Deno.statSync(outputFile5).mtime?.valueOf() || 0);
  } else {
    return true;
  }
}
function resultReloadFiles(result2) {
  return [result2.outputFile].concat(result2.resourceFiles);
}
function pdfFileRequestHandler(pdfFile, inputFile, flags, format14, port, reloader, renderHandler, project) {
  const pdfOptions = htmlFileRequestHandlerOptions(
    dirname4(pdfFile),
    basename4(pdfFile),
    inputFile,
    flags,
    format14,
    reloader,
    renderHandler,
    project
  );
  pdfOptions.baseDir = pdfJsBaseDir();
  if (pdfOptions.onRequest) {
    const onRequest = pdfOptions.onRequest;
    pdfOptions.onRequest = async (req) => {
      if (new URL(req.url).pathname === "/") {
        const url = isPositWorkbench() ? await rswURL(port, kPdfJsInitialPath) : isVSCodeServer() ? vsCodeServerProxyUri().replace("{{port}}", `${port}`) + kPdfJsInitialPath : "/" + kPdfJsInitialPath;
        return Promise.resolve(serveRedirect(url));
      } else {
        return Promise.resolve(onRequest(req));
      }
    };
  }
  pdfOptions.onFile = pdfJsFileHandler(() => pdfFile, pdfOptions.onFile);
  return httpFileRequestHandler(pdfOptions);
}
function pdfReloadFiles(result2) {
  return [result2.outputFile];
}
function resultRequiresSync(result2, lastResult) {
  if (!lastResult) {
    return true;
  }
  return result2.file !== lastResult.file || result2.outputFile !== lastResult.outputFile || !isEqual(result2.extensionFiles, lastResult.extensionFiles) || !isEqual(result2.resourceFiles, lastResult.resourceFiles);
}

// command/serve/cmd.ts
await init_render_services();
init_cleanup();
var serveCommand = new Command().name("serve").arguments("[input:string]").option(
  "--no-render",
  "Do not render the document before serving."
).option(
  "-p, --port [port:number]",
  "The TCP port that the application should listen on."
).option(
  "--host [host:string]",
  "Hostname to bind to (defaults to 127.0.0.1)"
).option(
  "--browser",
  "Open a browser to preview the site."
).description(
  "Serve a Shiny interactive document.\n\nBy default, the document will be rendered first and then served. If you have previously rendered the document, pass --no-render to skip the rendering step."
).example(
  "Serve an interactive Shiny document",
  "quarto serve dashboard.qmd"
).example(
  "Serve a document without rendering",
  "quarto serve dashboard.qmd --no-render"
).action(async (options, input) => {
  await initYamlIntelligenceResourcesFromFilesystem();
  if (!input) {
    error(
      "No input passed to serve.\nIf you are attempting to preview a website or book use the " + bold3("quarto preview") + " command instead."
    );
    exitWithCleanup(1);
    throw new Error();
  }
  const { host, port } = await resolveHostAndPort(options);
  const nbContext = notebookContext();
  const context = await projectContext(input, nbContext) || await singleFileProjectContext(input, nbContext);
  const formats2 = await withRenderServices(
    nbContext,
    (services) => renderFormats(input, services, void 0, context)
  );
  const format14 = await previewFormat(input, context, void 0, formats2);
  const result2 = await serve({
    input,
    render: options.render,
    format: format14,
    port,
    host,
    browser: options.browser,
    projectDir: context?.dir,
    tempDir: Deno.makeTempDirSync()
  });
  if (!result2.success) {
    exitWithCleanup(result2.code);
  }
});

// command/create-project/cmd.ts
init_path();
await init_engine();

// command/command-utils.ts
await init_project_context();
await init_engine();
async function zeroFileProjectContext(dir) {
  const { createExtensionContext: createExtensionContext2 } = await init_extension().then(() => extension_exports);
  const { resolveEngineExtensions: resolveEngineExtensions2 } = await init_project_context().then(() => project_context_exports);
  const extensionContext = createExtensionContext2();
  const config2 = await resolveEngineExtensions2(
    extensionContext,
    { project: {} },
    dir || Deno.cwd()
  );
  return {
    dir: dir || Deno.cwd(),
    config: config2
  };
}
async function initializeProjectContextAndEngines(dir) {
  await initYamlIntelligenceResourcesFromFilesystem();
  const context = await projectContext(dir || Deno.cwd(), notebookContext()) || await zeroFileProjectContext(dir);
  await resolveEngines(context);
}

// project/project-create.ts
init_lodash();
init_fs();
init_path();
init_log();
init_kernels();

// core/jupyter/venv.ts
init_log();
init_path();
init_colors2();
init_lodash();
init_platform();
init_process();
init_capabilities();
init_path2();
async function jupyterCreateVenv(dir, packages) {
  const kEnvDir = "env";
  info(`Creating virtual environment at ${bold3(kEnvDir + "/")}:`);
  const caps = await jupyterCapabilitiesNoConda();
  if (caps) {
    const executable = caps.pyLauncher ? "py" : caps.executable;
    const result2 = await execProcess({
      cmd: executable,
      args: ["-m", "venv", kEnvDir],
      cwd: dir
    });
    if (!result2.success) {
      throw new Error();
    }
    const pip3 = join4(
      dir,
      kEnvDir,
      isWindows4 ? "Scripts\\pip.exe" : "bin/pip3"
    );
    const pkgList = uniq(["jupyter"].concat(packages || []));
    const installResult = await execProcess({
      cmd: pip3,
      args: ["install", ...pkgList],
      cwd: dir
    });
    if (!installResult.success) {
      throw new Error();
    }
  } else {
    throw new Error("Unable to create venv (Non-conda Python 3 not found)");
  }
}
async function jupyterCreateCondaenv(dir, packages) {
  const kEnvDir = "env";
  info(`Creating conda environment at ${bold3(kEnvDir + "/")}:`);
  const conda = await which("conda");
  if (conda) {
    info(`Using conda at ${conda}`);
    const pkgList = uniq(["jupyter"].concat(packages || []));
    const installResult = await execProcess({
      cmd: "conda",
      args: ["create", "--yes", "--prefix", "env", ...pkgList],
      cwd: dir
    });
    if (!installResult.success) {
      throw new Error();
    }
  } else {
    throw new Error("Unable to create condaenv (conda not found)");
  }
}

// project/project-create.ts
init_project_types();
await init_engine();
await init_project_shared();
init_project_gitignore();
init_website_constants();
init_copy5();
init_path2();
async function projectCreate(options) {
  options = await readOptions(options);
  const engine = executionEngine(options.engine);
  if (!engine) {
    throw Error(`Invalid execution engine: ${options.engine}`);
  }
  ensureDirSync(options.dir);
  options.dir = normalizePath(options.dir);
  if (!options.quiet) {
    info(`Creating project at `, { newline: false });
    info(`${options.dir}`, { bold: true, newline: false });
    info(":");
  }
  if (options.type === "site") {
    options.type = kWebsite;
  }
  const projType = projectType(options.type);
  const projCreate = projType.create(options.title, options.template);
  const quartoConfig2 = renderEjs(projCreate.configTemplate, {
    title: options.title,
    editor: options.editor,
    ext: engine.defaultExt
  }, false);
  Deno.writeTextFileSync(join4(options.dir, "_quarto.yml"), quartoConfig2);
  if (!options.quiet) {
    info(
      "- Created _quarto.yml",
      { indent: 2 }
    );
  }
  if (await ensureGitignore(options.dir, !!options.venv || !!options.condaenv) && !options.quiet) {
    info(
      "- Created .gitignore",
      { indent: 2 }
    );
  }
  if (options.scaffold && projCreate.scaffold) {
    for (const scaffold of projCreate.scaffold(
      options.engine,
      options.kernel,
      options.envPackages
    )) {
      const md = projectMarkdownFile(
        options.dir,
        scaffold.name,
        scaffold.content,
        engine,
        options.kernel,
        scaffold.title,
        scaffold.noEngineContent,
        scaffold.yaml,
        scaffold.subdirectory,
        scaffold.supporting
      );
      if (md && !options.quiet) {
        info("- Created " + md, { indent: 2 });
      }
    }
  }
  if (projCreate.supporting) {
    for (const supporting of projCreate.supporting) {
      let src2;
      let dest;
      let displayName;
      if (typeof supporting === "string") {
        src2 = join4(projCreate.resourceDir, supporting);
        dest = join4(options.dir, supporting);
        displayName = supporting;
      } else {
        src2 = join4(projCreate.resourceDir, supporting.from);
        dest = join4(options.dir, supporting.to);
        displayName = supporting.to;
      }
      if (!existsSync2(dest)) {
        ensureDirSync(dirname4(dest));
        copyTo(src2, dest);
        ensureUserWritable(dest);
        if (!options.quiet) {
          info("- Created " + displayName, { indent: 2 });
        }
      }
    }
  }
  if (options.venv) {
    await jupyterCreateVenv(options.dir, options.envPackages);
  } else if (options.condaenv) {
    await jupyterCreateCondaenv(options.dir, options.envPackages);
  }
}
async function readOptions(options) {
  options = cloneDeep(options);
  if (options.engine === "jupyter") {
    const kernel = options.kernel || "python3";
    const kernelspec = await jupyterKernelspec(kernel);
    if (!kernelspec) {
      throw new Error(
        `Specified jupyter kernel ('${kernel}') not found.`
      );
    }
  } else {
    if (options.venv) {
      throw new Error("You can only use --with-venv with the jupyter engine");
    }
  }
  options.title = options.title || basename4(options.dir);
  if (projectConfigFile(options.dir)) {
    throw new Error(
      `The directory '${options.dir}' already contains a quarto project`
    );
  }
  return options;
}
function projectMarkdownFile(dir, name2, content, engine, kernel, title3, noEngineContent, yaml, subdirectory, supporting) {
  const lines2 = ["---"];
  if (title3) {
    lines2.push(`title: "${title3}"`);
  }
  if (yaml) {
    lines2.push(yaml);
  }
  if (!noEngineContent) {
    lines2.push(...engine.defaultYaml(kernel));
  }
  lines2.push("---", "");
  if (lines2.length === 3) {
    lines2.splice(0, lines2.length);
  }
  lines2.push(content);
  if (!noEngineContent) {
    const engineContent = engine.defaultContent(kernel);
    if (engineContent.length > 0) {
      lines2.push("");
      lines2.push(...engineContent);
    }
  }
  name2 = name2 + engine.defaultExt;
  const ensureSubDir = (dir2, name3, subdirectory2) => {
    if (subdirectory2) {
      const newDir = join4(dir2, subdirectory2);
      ensureDirSync(newDir);
      return join4(newDir, name3);
    } else {
      return join4(dir2, name3);
    }
  };
  const path3 = ensureSubDir(dir, name2, subdirectory);
  if (!existsSync2(path3)) {
    Deno.writeTextFileSync(path3, lines2.join("\n") + "\n");
    supporting?.forEach((from) => {
      const name3 = basename4(from);
      const target = join4(dirname4(path3), name3);
      copyTo(from, target);
      ensureUserWritable(target);
    });
    return subdirectory ? join4(subdirectory, name2) : name2;
  } else {
    return void 0;
  }
}

// command/create-project/cmd.ts
init_project_types();
init_types3();

// project/types/book/book.ts
init_path();
init_resources2();
init_config2();
init_types5();
init_format5();
init_constants6();

// project/types/website/website.ts
init_path();
init_resources2();
init_path2();
init_mime();
init_types4();
init_types5();
await init_project_shared();
init_format5();
init_constants6();
init_format_html_info();

// project/types/website/website-navigation.ts
init_path();
init_log();
init_lodash();
init_path2();
init_resources2();
init_url();
init_log2();
init_html();
init_sass();

// project/types/website/website-utils.ts
init_html();
init_path2();
init_url();
await init_project_shared();
await init_engine();
init_log();
init_path();
init_website_constants();
function removeChapterNumber(item) {
  const numberSpan = item.querySelector(".chapter-number");
  const titleSpan = item.querySelector(".chapter-title");
  if (numberSpan && titleSpan) {
    item.innerHTML = "";
    item.appendChild(titleSpan);
  }
}
function isProjectDraft(input, project) {
  const drafts = websiteConfigArray(kDrafts, project.config);
  if (drafts) {
    return drafts.includes(pathWithForwardSlashes(input));
  }
  return false;
}
function projectDraftMode(project) {
  if (project.previewServer) {
    return kDraftModeVisible;
  }
  const draftMode = websiteConfigString(kDraftMode, project.config);
  return draftMode || kDraftModeGone;
}
function isDraftVisible(draftMode) {
  return draftMode === "visible" || draftMode === "preview";
}
async function resolveProjectInputLinks(source2, project, doc) {
  const sourceRelative = relative4(project.dir, source2);
  const offset3 = projectOffset(project, source2);
  const draftMode = projectDraftMode(project);
  const links = doc.querySelectorAll("a[href]");
  for (let i6 = 0; i6 < links.length; i6++) {
    const link2 = links[i6];
    const resolveInput = link2.getAttribute("data-noresolveinput") === null;
    if (!resolveInput) {
      link2.removeAttribute("data-noresolveinput");
    }
    const linkHref = getDecodedAttribute(link2, "href");
    if (linkHref && !isExternalPath(linkHref)) {
      let projRelativeHref = linkHref.startsWith("/") ? linkHref.slice(1) : join4(dirname4(sourceRelative), linkHref);
      const hashLoc = projRelativeHref.indexOf("#");
      const hash = hashLoc !== -1 ? projRelativeHref.slice(hashLoc) : "";
      if (hash) {
        projRelativeHref = projRelativeHref.slice(0, hashLoc);
      }
      const resolved = resolveInput ? await resolveInputTarget(
        project,
        pathWithForwardSlashes(projRelativeHref)
      ) : {
        outputHref: pathWithForwardSlashes(join4("/", projRelativeHref)),
        draft: false
      };
      if (resolved) {
        if (resolved.draft && !isDraftVisible(draftMode)) {
          link2.replaceWith(link2.innerHTML);
        } else {
          link2.setAttribute("href", offset3 + resolved.outputHref + hash);
        }
      } else {
        if (!safeExistsSync(join4(project.dir, projRelativeHref))) {
          const targetFile = join4(
            projectOutputDir(project),
            projRelativeHref
          );
          if (engineValidExtensions().includes(extname4(targetFile)) && !safeExistsSync(join4(projectOutputDir(project), projRelativeHref))) {
            warn("Unable to resolve link target: " + projRelativeHref);
          }
        }
      }
    }
  }
}

// project/types/website/website-shared.ts
init_path();
init_lodash();
init_path2();
init_types4();
init_website_constants();

// project/types/website/website-analytics.ts
init_path();
init_fs();
init_constants6();
init_resources2();
init_website_constants();
var kGoogleAnalytics = "google-analytics";
var kTrackingId = "tracking-id";
var kStorage = "storage";
var kAnonymizeIp = "anonymize-ip";
var kVersion2 = "version";
var kPlausibleAnalytics = "plausible-analytics";
var kPlausiblePath = "path";
var kCookieConsent = "cookie-consent";
var kCookieConsentType = "type";
var kCookieConsentStyle = "style";
var kCookieConsentPalette = "palette";
var kCookieConsentPolicyUrl = "policy-url";
var kCookiePrefsText = "prefs-text";
function scriptTagWithConsent(consentRequired, consentlevel, contents, src2) {
  const srcAttr = src2 ? ` src="${src2}"` : "";
  if (consentRequired) {
    return `
<script type="text/plain" cookie-consent="${consentlevel}"${srcAttr}>
${contents}
<\/script>`;
  } else {
    return `
<script type="text/javascript"${srcAttr}>
${contents}
<\/script>`;
  }
}
function websiteAnalyticsScriptFile(project, temp) {
  const siteMeta = project.config?.[kWebsite];
  const scripts = [];
  if (siteMeta) {
    let gaConfig = void 0;
    const siteGa = siteMeta[kGoogleAnalytics];
    if (typeof siteGa === "object") {
      const siteGaMeta = siteGa;
      const trackingId = siteGaMeta[kTrackingId];
      const storage = siteGaMeta[kStorage];
      const anonymizedIp = siteGaMeta[kAnonymizeIp];
      const version4 = siteGaMeta[kVersion2];
      gaConfig = googleAnalyticsConfig(
        project,
        trackingId,
        storage,
        anonymizedIp,
        version4
      );
    } else if (siteGa && typeof siteGa === "string") {
      gaConfig = googleAnalyticsConfig(project, siteGa);
    }
    if (gaConfig) {
      const gaScript = analyticsScript(gaConfig);
      if (gaScript) {
        scripts.push(gaScript);
      }
    }
    const plausibleSnippet = siteMeta[kPlausibleAnalytics];
    if (plausibleSnippet) {
      if (typeof plausibleSnippet === "string") {
        scripts.push(plausibleSnippet);
      } else if (typeof plausibleSnippet === "object") {
        const plausibleMeta = plausibleSnippet;
        const snippetPath = plausibleMeta[kPlausiblePath];
        if (snippetPath) {
          const absolutePath = join4(project.dir, snippetPath);
          if (existsSync2(absolutePath)) {
            const snippetContent = Deno.readTextFileSync(absolutePath);
            scripts.push(snippetContent);
          } else {
            throw new Error(
              `Plausible Analytics snippet file not found: ${snippetPath}`
            );
          }
        }
      }
    }
  }
  if (scripts.length > 0) {
    return scriptFile(scripts.join("\n"), temp);
  } else {
    return void 0;
  }
}
function cookieConsentDependencies(project, format14, temp) {
  const siteMeta = project.config?.[kWebsite];
  if (siteMeta) {
    const title3 = siteMeta[kTitle] || "";
    let configuration = void 0;
    let changePrefsText = void 0;
    const consent = siteMeta[kCookieConsent];
    if (typeof consent === "object") {
      const cookieMeta = consent;
      configuration = cookieConsentConfiguration(
        title3,
        cookieMeta[kCookieConsentType],
        cookieMeta[kCookieConsentStyle],
        cookieMeta[kCookieConsentPalette],
        cookieMeta[kCookieConsentPolicyUrl],
        cookieMeta[kLanguage] || format14.metadata[kLang]
      );
      changePrefsText = cookieMeta[kCookiePrefsText];
    } else if (consent) {
      configuration = cookieConsentConfiguration(
        title3,
        void 0,
        void 0,
        void 0,
        void 0,
        format14.metadata[kLang]
      );
    }
    if (configuration) {
      const consentResourcesDir = join4(
        projectTypeResourcePath("website"),
        "cookie-consent"
      );
      const name2 = "cookie-consent.js";
      const path3 = join4(consentResourcesDir, name2);
      const cssName = "cookie-consent.css";
      const cssPath = join4(consentResourcesDir, cssName);
      return {
        scriptFile: scriptFile(
          cookieConsentScript(configuration),
          temp
        ),
        dependency: {
          name: "cookie-consent",
          scripts: [{
            name: name2,
            path: path3
          }],
          stylesheets: [{
            name: cssName,
            path: cssPath
          }]
        },
        htmlPostProcessor: (doc) => {
          const anchorId = "open_preferences_center";
          const prefsAnchor = doc.getElementById(anchorId);
          if (!prefsAnchor) {
            const footer = doc.querySelector(
              "div.nav-footer .nav-footer-center"
            );
            if (footer) {
              const anchor = doc.createElement("a");
              anchor.setAttribute("href", "#");
              anchor.setAttribute("id", anchorId);
              anchor.innerHTML = changePrefsText || "Cookie Preferences";
              const anchorContainer = doc.createElement("div");
              anchorContainer.setAttribute("class", "cookie-consent-footer");
              anchorContainer.appendChild(anchor);
              footer.appendChild(anchorContainer);
            }
          }
          return Promise.resolve(kHtmlEmptyPostProcessResult);
        }
      };
    } else {
      return void 0;
    }
  } else {
    return void 0;
  }
}
function cookieConsentEnabled(project) {
  const siteMeta = project.config?.[kWebsite];
  if (siteMeta) {
    return !!siteMeta[kCookieConsent];
  } else {
    return false;
  }
}
function cookieConsentConfiguration(_siteName, type4, style, palette, policyUrl, language) {
  return {
    siteName: "",
    type: type4 || "express",
    style: style || "simple",
    palette: palette || "light",
    policyUrl,
    language
  };
}
function googleAnalyticsConfig(project, trackingId, storage, anoymizeIp, version4) {
  return {
    trackingId,
    consent: cookieConsentEnabled(project),
    storage: storage || "cookies",
    anonymizeIp: anoymizeIp === void 0 ? true : !!anoymizeIp,
    version: version4 || (trackingId.startsWith("UA-") ? 3 : 4)
  };
}
function analyticsScript(config2) {
  if (config2.version === 3) {
    return ga3Script(config2);
  } else if (config2.version === 4) {
    return ga4Script(config2);
  } else {
    return void 0;
  }
}
function ga3Script(config2) {
  const scripts = [];
  scripts.push(`
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');`);
  if (config2.storage === "none") {
    scripts.push(
      `ga('create', '${config2.trackingId}', { 'storage': 'none' });`
    );
  } else {
    scripts.push(`ga('create', '${config2.trackingId}', 'auto');`);
  }
  scripts.push(`
ga('send', {
  hitType: 'pageview',
  'anonymizeIp': ${config2.anonymizeIp},
});`);
  return scriptTagWithConsent(
    !!config2.consent,
    "tracking",
    scripts.join("\n")
  );
}
function ga4Script(config2) {
  const scripts = [];
  scripts.push(`
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());`);
  if (config2.storage === "none") {
    scripts.push(` 
  gtag('consent', 'default', {
    'ad_storage': 'denied',
    'analytics_storage': 'denied'
  });`);
  }
  scripts.push(
    `gtag('config', '${config2.trackingId}', { 'anonymize_ip': ${config2.anonymizeIp}});`
  );
  return [
    `<script async src="https://www.googletagmanager.com/gtag/js?id=${config2.trackingId}"><\/script>`,
    scriptTagWithConsent(
      !!config2.consent,
      "tracking",
      scripts.join("\n")
    )
  ].join("\n");
}
function cookieConsentScript(config2) {
  const consentLevels = config2.type === "implied" ? `["strictly-necessary","functionality","tracking","targeting"]` : `["strictly-necessary"]`;
  const privacyJs = config2.policyUrl !== void 0 ? `,
"website_privacy_policy_url":"${config2.policyUrl}"` : "";
  const language = config2.language !== void 0 ? `,
"language":"${config2.language}"` : "";
  return `
<script type="text/javascript" charset="UTF-8">
document.addEventListener('DOMContentLoaded', function () {
cookieconsent.run({
  "notice_banner_type":"${config2.style}",
  "consent_type":"${config2.type}",
  "palette":"${config2.palette === "dark" ? "dark" : "light"}",
  "language":"en",
  "page_load_consent_levels":${consentLevels},
  "notice_banner_reject_button_hide":false,
  "preferences_center_close_button_hide":false,
  "website_name":"${config2.siteName}"${privacyJs}
  ${language}
  });
});
<\/script> 
  `;
}
function scriptFile(script, temp) {
  const analyticsScriptFile = temp.createFile({ suffix: "-lytics.js" });
  Deno.writeTextFileSync(analyticsScriptFile, script);
  return analyticsScriptFile;
}

// project/types/website/website-shared.ts
init_constants6();
init_hash2();
init_brand();
function computePageTitle(format14, extras) {
  const meta = extras?.metadata || {};
  const pageTitle = meta[kPageTitle] || format14.metadata[kPageTitle];
  const titlePrefix = extras?.pandoc?.[kTitlePrefix] || format14.pandoc[kTitlePrefix] || format14.metadata[kWebsite]?.[kTitle];
  const title3 = format14.metadata[kTitle];
  if (pageTitle !== void 0) {
    return pageTitle;
  } else if (titlePrefix !== void 0) {
    if (titlePrefix === title3) {
      return title3;
    } else if (title3 !== void 0) {
      return title3 + " \u2013 " + titlePrefix;
    } else {
      return titlePrefix + "";
    }
  } else {
    return title3;
  }
}
function inputFileHref(href) {
  const [hrefDir, hrefStem] = dirAndStem(href);
  const htmlHref = "/" + join4(hrefDir, `${hrefStem}.html`);
  return pathWithForwardSlashes(htmlHref);
}
async function websiteNavigationConfig(project) {
  let navbar = websiteConfig(kSiteNavbar, project.config);
  if (typeof navbar === "boolean" && navbar) {
    navbar = { background: "primary" };
  } else if (typeof navbar !== "object") {
    navbar = void 0;
  }
  const projectBrand = await project.resolveBrand();
  if (navbar && navbar.logo !== false) {
    let navLogo = navbar.logo;
    if (navbar[kLogoAlt]) {
      if (typeof navLogo === "string") {
        navLogo = { path: navLogo, alt: navbar[kLogoAlt] };
      }
    }
    let logo = resolveLogo(projectBrand, navLogo, [
      "small",
      "medium",
      "large"
    ]);
    logo = logoAddLeadingSlashes(logo, projectBrand, void 0);
    navbar.logo = logo;
  }
  const sidebar = websiteConfig(kSiteSidebar, project.config);
  const sidebars = Array.isArray(sidebar) ? sidebar : typeof sidebar == "object" ? [sidebar] : void 0;
  if (sidebars && sidebars[0]) {
    if (sidebars[0].style === void 0) {
      sidebars[0].style = "floating";
    }
    if (sidebars[0].contents === void 0) {
      sidebars[0].contents = [];
    }
    if (sidebars[0].tools === void 0) {
      sidebars[0].tools = [];
    }
    let sideLogo = sidebars[0].logo;
    if (sideLogo !== false) {
      if (sideLogo && sidebars[0][kLogoAlt]) {
        const alt = sidebars[0][kLogoAlt];
        if (typeof sideLogo === "string") {
          sideLogo = { path: sideLogo, alt };
        }
      }
      let logo = resolveLogo(projectBrand, sideLogo, [
        "medium",
        "small",
        "large"
      ]);
      logo = logoAddLeadingSlashes(logo, projectBrand, void 0);
      sidebars[0].logo = logo;
    }
    for (const sb of sidebars) {
      if (sb.contents && !Array.isArray(sb.contents)) {
        if (typeof sb.contents === "string") {
          if (sb.contents === "auto") {
            sb.contents = [{ auto: true }];
          } else {
            sb.contents = [{ auto: sb.contents }];
          }
        } else {
          sb.contents = [sb.contents];
        }
      }
    }
  }
  if (sidebars && sidebars.length > 1) {
    const sidebarOptions = cloneDeep(sidebars[0]);
    delete sidebarOptions.id;
    delete sidebarOptions.title;
    sidebarOptions.contents.splice(0, sidebarOptions.contents.length);
    for (let i6 = 1; i6 < sidebars.length; i6++) {
      sidebars[i6] = {
        ...sidebarOptions,
        ...sidebars[i6]
      };
    }
  }
  const pageNavigation = websiteConfigBoolean(
    kSitePageNavigation,
    false,
    project.config
  );
  const footer = resolvePageFooter(project.config);
  if (footer.center === void 0 && cookieConsentEnabled(project)) {
    footer.center = " ";
  }
  const pageMargin = {};
  const headerVal = websiteConfigArray(kMarginHeader, project.config);
  if (headerVal) {
    pageMargin.header = headerVal;
  }
  const footerVal = websiteConfigArray(kMarginFooter, project.config);
  if (footerVal) {
    pageMargin.footer = footerVal;
  }
  const bodyDecorators = {};
  const bodyHeaderVal = websiteConfigArray(kBodyHeader, project.config);
  if (bodyHeaderVal) {
    bodyDecorators.header = bodyHeaderVal;
  }
  const bodyFooterVal = websiteConfigArray(kBodyFooter, project.config);
  if (bodyFooterVal) {
    bodyDecorators.footer = bodyFooterVal;
  }
  const announcementRaw = websiteConfig(kAnnouncement, project.config);
  let announcement;
  if (typeof announcementRaw === "string") {
    announcement = {
      id: await md5HashAsync(announcementRaw),
      icon: void 0,
      dismissable: true,
      content: announcementRaw,
      position: "above-navbar",
      type: "primary"
    };
  } else if (announcementRaw && !Array.isArray(announcementRaw)) {
    announcement = {
      id: await md5HashAsync(announcementRaw.content),
      icon: announcementRaw.icon,
      dismissable: announcementRaw.dismissable !== false,
      content: announcementRaw.content,
      type: announcementRaw.type || "primary",
      position: announcementRaw.position || "above-navbar"
    };
  }
  return {
    navbar,
    sidebars,
    pageNavigation,
    footer,
    pageMargin,
    bodyDecorators,
    announcement
  };
}
function resolvePageFooter(config2) {
  const footerValue = (value) => {
    if (typeof value === "string") {
      return value;
    } else if (Array.isArray(value)) {
      return value;
    } else {
      return void 0;
    }
  };
  const footer = {};
  const footerConfig = websiteConfig(kPageFooter, config2);
  if (typeof footerConfig === "string") {
    footer.center = footerConfig;
  } else if (!Array.isArray(footerConfig)) {
    footer.left = footerValue(footerConfig?.left);
    footer.center = footerValue(footerConfig?.center);
    footer.right = footerValue(footerConfig?.right);
  }
  return footer;
}
function flattenItems(sidebarItems, includeItem) {
  const items = [];
  const flatten = (sidebarItem) => {
    if (includeItem(sidebarItem)) {
      items.push(sidebarItem);
    }
    if (sidebarItem.contents) {
      items.push(...flattenItems(sidebarItem.contents, includeItem));
    }
  };
  sidebarItems.forEach(flatten);
  return items;
}
function breadCrumbs(href, sidebar) {
  if (sidebar?.contents) {
    const crumbs = [];
    const makeBreadCrumbs2 = (href2, sidebarItems) => {
      if (sidebarItems) {
        for (const item of sidebarItems) {
          if (item.href === href2) {
            crumbs.push(item);
            return true;
          } else {
            if (item.contents) {
              if (makeBreadCrumbs2(href2, item.contents)) {
                const breadCrumbItem = { ...item };
                if (!breadCrumbItem.href && breadCrumbItem.contents && breadCrumbItem.contents.length > 0) {
                  breadCrumbItem.href = breadCrumbItem.contents[0].href;
                }
                crumbs.push(breadCrumbItem);
                return true;
              }
            }
          }
        }
        return false;
      } else {
        return false;
      }
    };
    makeBreadCrumbs2(href, sidebar.contents);
    return crumbs.reverse();
  } else {
    return [];
  }
}
var navigation = {
  sidebars: []
};
function sidebarForHref(href, format14) {
  if (navigation.sidebars.length === 1 && navigation.sidebars[0].id === void 0) {
    return navigation.sidebars[0];
  } else {
    const explicitSidebar = navigation.sidebars.find((sidebar) => {
      return sidebar.id === format14.metadata[kSiteSidebar];
    });
    if (explicitSidebar) {
      return explicitSidebar;
    } else {
      const containingSidebar = navigation.sidebars.find((sidebar) => {
        return containsHref(href, sidebar.contents);
      });
      if (containingSidebar) {
        return containingSidebar;
      } else {
        return void 0;
      }
    }
  }
}
function navbarItemForSidebar(sidebar, format14) {
  const findNavItemWithSidebar = (navItems) => {
    if (navItems) {
      const navItem = navItems.find((val) => {
        let href;
        if (typeof val === "object") {
          href = val.href;
        } else {
          href = val;
        }
        if (href) {
          const navSidebar = sidebarForHref(
            href,
            format14
          );
          if (navSidebar === sidebar) {
            return true;
          }
        }
        return false;
      });
      if (navItem) {
        return navItem;
      }
    }
  };
  const leftNavItem = findNavItemWithSidebar(navigation.navbar?.left);
  if (leftNavItem) {
    return leftNavItem;
  }
  const rightNavItem = findNavItemWithSidebar(navigation.navbar?.right);
  if (rightNavItem) {
    return rightNavItem;
  }
  return void 0;
}
function containsHref(href, items) {
  for (let i6 = 0; i6 < items.length; i6++) {
    if (items[i6].href && items[i6].href === href) {
      return true;
    } else if (Object.keys(items[i6]).includes("contents")) {
      const subItems = items[i6].contents || [];
      const subItemsHasHref = containsHref(href, subItems);
      if (subItemsHasHref) {
        return true;
      }
    } else {
      if (itemHasNavTarget(items[i6], href)) {
        return true;
      }
    }
  }
  return false;
}
function itemHasNavTarget(item, href) {
  return item.href === href || item.href === href.replace(/\/index\.html/, "/");
}

// project/types/website/website-navigation.ts
init_types5();

// config/toc.ts
init_constants6();
function hasTableOfContents(flags, format14) {
  return !!(flags[kToc] || format14.pandoc[kToc] || format14.pandoc[kTableOfContents]);
}
function disabledTableOfContents(format14) {
  return format14.pandoc[kToc] === false || format14.pandoc[kTableOfContents] === false;
}

// project/types/website/website-navigation.ts
init_format_html_shared();
init_format_html_info();
init_format_html_shared();
init_types4();
await init_project_shared();
init_types4();
init_project_types();

// project/types/website/website-search.ts
init_fs();
init_path();
init_deno_dom();
init_resources2();
init_types4();
init_format_html_shared();
await init_project_shared();
await init_project_shared();
init_sass();
init_log();
init_constants6();
init_path2();
init_format5();
await init_project_shared();
init_html();
var kSearch = "search";
var kType = "type";
var kLocation = "location";
var kCopyButton = "copy-button";
var kCollapseAfter = "collapse-after";
var kPanelPlacement = "panel-placement";
var kKbShortcutSearch = "keyboard-shortcut";
var kLimit = "limit";
var kShowItemContext = "show-item-context";
var kAlgolia = "algolia";
var kSearchOnlyApiKey = "search-only-api-key";
var kSearchApplicationId = "application-id";
var kSearchParams = "params";
var kSearchIndexName = "index-name";
var kIndexFields = "index-fields";
var kAnalyticsEvents = "analytics-events";
var kShowLogo = "show-logo";
var kCookieConsentEnabled = "cookie-consent-enabled";
async function updateSearchIndex(context, outputFiles, incremental) {
  const outputDir = projectOutputDir(context);
  const searchJsonPath = join4(outputDir, "search.json");
  const searchJson = existsSync2(searchJsonPath) ? Deno.readTextFileSync(searchJsonPath) : void 0;
  const searchDocs = new Array();
  let generateIndex = true;
  if (incremental && searchJson) {
    try {
      const existingSearchJson = JSON.parse(searchJson);
      searchDocs.push(...existingSearchJson);
    } catch {
      generateIndex = false;
      warn(
        "Unable to read search index - it may be corrupt. Please re-render the entire site to create a valid search index."
      );
    }
  }
  if (generateIndex) {
    const draftMode = projectDraftMode(context);
    let updatedSearchDocs = [...searchDocs];
    for (const outputFile5 of outputFiles) {
      const file = outputFile5.file;
      const href = pathWithForwardSlashes(relative4(outputDir, file));
      const index2 = await resolveInputTargetForOutputFile(
        context,
        relative4(outputDir, outputFile5.file)
      );
      const draft = index2 ? index2.draft : false;
      if (outputFile5.format.metadata[kSearch] === false || draft === true && !isDraftVisible(draftMode)) {
        updatedSearchDocs = updatedSearchDocs.filter((doc2) => {
          return doc2.href !== href && !doc2.href.startsWith(href + "#");
        });
        continue;
      }
      if (!isHtmlFileOutput(outputFile5.format.pandoc)) {
        continue;
      }
      const updateDoc = (doc2) => {
        const idx = updatedSearchDocs.findIndex((d4) => d4.href === doc2.href);
        if (idx !== -1) {
          updatedSearchDocs[idx] = doc2;
        } else {
          updatedSearchDocs.push(doc2);
        }
      };
      const contents = Deno.readTextFileSync(file);
      const doc = new DOMParser().parseFromString(contents, "text/html");
      const findTitle2 = () => {
        const titleEl2 = doc.querySelector("h1.title");
        if (titleEl2) {
          return titleEl2;
        } else {
          const title4 = doc.querySelector("main h1");
          if (title4) {
            return title4;
          } else {
            return void 0;
          }
        }
      };
      const navHref = `/${href}`;
      const sidebar = sidebarForHref(navHref, outputFile5.format);
      const bc = breadCrumbs(navHref, sidebar);
      const crumbs = bc.length > 0 ? bc.filter((crumb) => {
        return crumb.text !== void 0;
      }).map((crumb) => {
        return crumb.text;
      }) : void 0;
      const mergeNavBarSearchCrumbs = outputFile5.format.metadata?.website?.search?.["merge-navbar-crumbs"];
      if (mergeNavBarSearchCrumbs !== false && crumbs && sidebar) {
        const navItem = navbarItemForSidebar(sidebar, outputFile5.format);
        if (navItem) {
          if (typeof navItem === "object") {
            const navbarParentText = navItem.text;
            if (navbarParentText) {
              if (crumbs.length > 0 && crumbs[0] !== navbarParentText) {
                crumbs.unshift(navbarParentText);
              }
            }
          }
        }
      }
      const titleEl = findTitle2();
      const title3 = titleEl ? titleEl.textContent : websiteTitle(context.config) || "";
      const header = doc.getElementById("title-block-header");
      if (header) {
        header.remove();
      }
      const toc = doc.querySelector(`nav[role="doc-toc"]`);
      if (toc) {
        toc.remove();
      }
      ["script", "style"].forEach((tag) => {
        const els = doc.querySelectorAll(tag);
        if (els) {
          els.forEach((el) => el.remove());
        }
      });
      const sections = doc.querySelectorAll(
        "section.level2,section.footnotes"
      );
      if (sections.length > 0) {
        const mainSelector = projectIsBook(context) ? "main > section:first-of-type" : "main.content";
        const mainEl = doc.querySelector(mainSelector);
        const firstEl = mainEl?.firstElementChild;
        const pageText = [];
        if (firstEl) {
          const headings = firstEl.querySelectorAll("h1, h2, h3, h4, h5, h6");
          headings.forEach((heading) => heading.remove());
          const trimmed = firstEl.textContent.trim();
          if (trimmed) {
            pageText.push(trimmed);
          }
          firstEl.remove();
        }
        const paragraphNodes = doc.querySelectorAll(
          `${mainSelector} > p, ${mainSelector} > div.cell, main > p`
        );
        const addToIndex = (paragraphNode) => {
          const text = paragraphNode.textContent.trim();
          if (text) {
            pageText.push(text);
          }
          paragraphNode.remove();
        };
        for (const paragraphNode of paragraphNodes) {
          addToIndex(paragraphNode);
        }
        const forcedInclusions = doc.querySelectorAll(
          `.quarto-include-in-search-index`
        );
        for (const forcedInclusion of forcedInclusions) {
          addToIndex(forcedInclusion);
        }
        if (pageText.length > 0) {
          updateDoc({
            objectID: href,
            href,
            title: title3,
            section: "",
            text: encodeHtml(pageText.join("\n")),
            crumbs
          });
        }
        for (let i6 = 0; i6 < sections.length; i6++) {
          const section = sections[i6];
          const h22 = section.querySelector("h2");
          if (section.id) {
            const sectionTitle = h22 ? h22.textContent : "";
            const hrefWithAnchor = `${href}#${section.id}`;
            const sectionText = section.textContent.trim();
            if (h22) {
              h22.remove();
            }
            if (sectionText) {
              updateDoc({
                objectID: hrefWithAnchor,
                href: hrefWithAnchor,
                title: title3,
                section: sectionTitle,
                text: encodeHtml(sectionText),
                crumbs
              });
            }
          }
        }
      } else {
        const main2 = doc.querySelector("main");
        if (main2) {
          const mainText = main2.textContent.trim();
          if (mainText) {
            updateDoc({
              objectID: href,
              href,
              title: title3,
              section: "",
              text: encodeHtml(mainText),
              crumbs
            });
          }
        }
      }
    }
    if (updatedSearchDocs.length > 0) {
      const updatedSearchJson = JSON.stringify(updatedSearchDocs, void 0, 2);
      if (searchJson !== updatedSearchJson) {
        Deno.writeTextFileSync(searchJsonPath, updatedSearchJson);
      }
    }
  }
}
var kDefaultCollapse = 3;
async function searchOptions(project) {
  const searchMetadata = websiteConfigMetadata(kSearch, project.config);
  const location = await searchInputLocation(project);
  if (searchMetadata) {
    const collapseMatches = typeof searchMetadata[kCollapseAfter] === "number" ? searchMetadata[kCollapseAfter] : searchMetadata[kCollapseAfter] !== false ? kDefaultCollapse : false;
    return {
      [kLocation]: location,
      [kCopyButton]: searchMetadata[kCopyButton] === true,
      [kCollapseAfter]: collapseMatches,
      [kPanelPlacement]: location === "navbar" ? "end" : "start",
      [kType]: searchType(searchMetadata[kType], location),
      [kLimit]: searchInputLimit(searchMetadata),
      [kAlgolia]: algoliaOptions(searchMetadata, project),
      [kKbShortcutSearch]: searchKbdShortcut(searchMetadata),
      [kShowItemContext]: searchShowItemContext(searchMetadata)
    };
  } else {
    const searchRaw = websiteConfig(kSearch, project.config);
    if (searchRaw === void 0 || !!searchRaw) {
      return {
        [kLocation]: location,
        [kCopyButton]: false,
        [kCollapseAfter]: kDefaultCollapse,
        [kPanelPlacement]: location === "navbar" ? "end" : "start",
        [kType]: searchType(void 0, location),
        [kLimit]: searchInputLimit(void 0),
        [kKbShortcutSearch]: searchKbdShortcut(void 0),
        [kShowItemContext]: searchShowItemContext(searchMetadata)
      };
    }
  }
}
function searchInputLimit(searchConfig) {
  if (searchConfig && typeof searchConfig === "object") {
    const limit = searchConfig[kLimit];
    if (typeof limit === "number") {
      return limit;
    }
  }
  return 50;
}
function searchKbdShortcut(searchConfig) {
  if (searchConfig && typeof searchConfig === "object") {
    const kbd = searchConfig[kKbShortcutSearch];
    if (kbd) {
      if (Array.isArray(kbd)) {
        return kbd;
      } else {
        return [kbd];
      }
    }
  }
  return ["f", "/", "s"];
}
function searchShowItemContext(searchConfig) {
  if (searchConfig && typeof searchConfig === "object") {
    return searchConfig[kShowItemContext];
  } else {
    return false;
  }
}
function searchType(userType, location) {
  if (userType && typeof userType === "string") {
    switch (userType) {
      case "overlay":
        return "overlay";
      default:
      case "textbox":
        return "textbox";
    }
  } else {
    if (location === "sidebar") {
      return "textbox";
    } else {
      return "overlay";
    }
  }
}
function algoliaOptions(searchConfig, project) {
  const algoliaRaw = searchConfig[kAlgolia];
  if (algoliaRaw && typeof algoliaRaw === "object") {
    const algoliaObj = algoliaRaw;
    const applicationId = algoliaObj[kSearchApplicationId];
    const apiKey = algoliaObj[kSearchOnlyApiKey];
    const indexName = algoliaObj[kSearchIndexName];
    const params = algoliaObj[kSearchParams];
    const indexKeys = algoliaObj[kIndexFields];
    const analytics = !!algoliaObj[kAnalyticsEvents];
    const showLogo = !!algoliaObj[kShowLogo];
    return {
      [kSearchApplicationId]: applicationId,
      [kSearchOnlyApiKey]: apiKey,
      [kSearchIndexName]: indexName,
      [kSearchParams]: params,
      [kIndexFields]: indexKeys,
      [kAnalyticsEvents]: analytics,
      [kShowLogo]: showLogo,
      libDir: project?.config?.project[kProjectLibDir]
    };
  } else {
    return void 0;
  }
}
async function searchInputLocation(project) {
  const searchConfig = websiteConfigMetadata(kSearch, project.config);
  if (searchConfig && searchConfig[kLocation]) {
    switch (searchConfig[kLocation]) {
      case "sidebar":
        return "sidebar";
      case "navbar":
      default:
        return "navbar";
    }
  } else {
    const { navbar } = await websiteNavigationConfig(project);
    if (navbar) {
      return "navbar";
    } else {
      return "sidebar";
    }
  }
}
var kDependencyName = "quarto-search";
function websiteSearchSassBundle() {
  const scssPath = searchDependency("quarto-search.scss").path;
  const layer = sassLayer(scssPath);
  return {
    dependency: kBootstrapDependencyName,
    key: scssPath,
    quarto: {
      name: "quarto-search.css",
      ...layer
    }
  };
}
async function websiteSearchIncludeInHeader(project, format14, temp) {
  const websiteSearchScript = temp.createFile({ suffix: "-search.html" });
  const options = await searchOptions(project) || {};
  options[kLanguageDefaults] = {};
  Object.keys(format14.language).forEach((key) => {
    if (key.startsWith("search-")) {
      options[kLanguageDefaults][key] = format14.language[key];
    }
  });
  const includes = [];
  if (options[kAlgolia]) {
    includes.push(kAlogioSearchApiScript);
    if (options[kAlgolia][kAnalyticsEvents]) {
      const cookieConsent = cookieConsentEnabled(project);
      options[kAlgolia][kCookieConsentEnabled] = cookieConsent;
      includes.push(algoliaSearchInsightsScript(cookieConsent));
      includes.push(autocompleteInsightsPluginScript(cookieConsent));
    }
  }
  const searchOptionsJson = JSON.stringify(options, null, 2);
  const searchOptionsScript = `<script id="quarto-search-options" type="application/json">${searchOptionsJson}<\/script>`;
  includes.unshift(searchOptionsScript);
  Deno.writeTextFileSync(websiteSearchScript, includes.join("\n"));
  return websiteSearchScript;
}
async function websiteSearchDependency(project, source2) {
  const searchDependencies = [];
  const resources = [];
  const options = await searchOptions(project);
  if (options) {
    const sourceRelative = relative4(project.dir, source2);
    const offset3 = projectOffset(project, source2);
    const href = inputFileHref(sourceRelative);
    const scripts = [
      searchDependency("autocomplete.umd.js"),
      searchDependency("fuse.min.js"),
      searchDependency("quarto-search.js")
    ];
    const algoliaOpts = options[kAlgolia];
    if (algoliaOpts) {
      if (algoliaOpts[kShowLogo]) {
        resources.push(searchDependency("search-by-algolia.svg"));
      }
      if (algoliaOpts[kSearchApplicationId] && algoliaOpts[kSearchOnlyApiKey] && algoliaOpts[kSearchIndexName]) {
        scripts.push(searchDependency("autocomplete-preset-algolia.umd.js"));
      } else {
        warn(
          "Algolia search is misconfigured. Please ensure that you provide an application-id, search-only-api-key, and index-name."
        );
      }
    }
    searchDependencies.push(clipboardDependency());
    searchDependencies.push({
      name: kDependencyName,
      meta: {
        "quarto:offset": href === "/404.html" ? websitePath(project.config) : offset3 + "/"
      },
      stylesheets: [],
      scripts,
      resources
    });
  }
  return searchDependencies;
}
function searchDependency(resource) {
  return {
    name: basename4(resource),
    path: resourcePath(`projects/website/search/${resource}`)
  };
}
function autocompleteInsightsPluginScript(cookieConsent) {
  return scriptTagWithConsent(
    cookieConsent,
    "tracking",
    "",
    "https://cdn.jsdelivr.net/npm/@algolia/autocomplete-plugin-algolia-insights"
  );
}
function algoliaSearchInsightsScript(cookieConsent) {
  return scriptTagWithConsent(
    cookieConsent,
    "tracking",
    `var ALGOLIA_INSIGHTS_SRC = "https://cdn.jsdelivr.net/npm/search-insights/dist/search-insights.iife.min.js";
!function(e,a,t,n,s,i,c){e.AlgoliaAnalyticsObject=s,e[s]=e[s]||function(){
(e[s].queue=e[s].queue||[]).push(arguments)},i=a.createElement(t),c=a.getElementsByTagName(t)[0],
i.async=1,i.src=n,c.parentNode.insertBefore(i,c)
}(window,document,"script",ALGOLIA_INSIGHTS_SRC,"aa");`
  );
}
var kAlogioSearchApiScript = `<script src="https://cdn.jsdelivr.net/npm/algoliasearch@4.5.1/dist/algoliasearch-lite.umd.js"><\/script>
`;

// project/types/website/website-navigation.ts
init_website_constants();
init_constants6();

// project/types/website/website-navigation-md.ts
init_path();
init_website_constants();
init_constants6();
init_path2();
var kSidebarTitleId = "quarto-int-sidebar-title";
var kNavbarTitleId = "quarto-int-navbar-title";
var kNavNextId = "quarto-int-next";
var kNavPrevId = "quarto-int-prev";
var kSidebarIdPrefix = "quarto-int-sidebar:";
var kBreadcrumbPrefix = "quarto-breadcrumbs";
var kNavbarIdPrefix = "quarto-int-navbar:";
var kToolsPrefix = "quarto-navbar-tools:";
function navigationMarkdownHandlers(context) {
  return [
    sidebarTitleHandler(context),
    navbarTitleHandler(context),
    nextPageTitleHandler(context),
    prevPageTitleHandler(context),
    sidebarContentsHandler(context),
    sidebarHeaderFooterHandler(context),
    navbarContentsHandler(context),
    footerHandler(context),
    marginHeaderFooterHandler(context),
    bodyHeaderFooterHandler(context),
    breadCrumbHandler(context),
    announcementHandler(context)
  ];
}
function title2(format14) {
  const site = format14.metadata[kWebsite];
  if (site && site[kTitle] && typeof site[kTitle] !== "object") {
    return String(site[kTitle]);
  } else if (format14.metadata[kTitle] && typeof format14.metadata[kTitle] !== "object") {
    return String(format14.metadata[kTitle]);
  }
}
var sidebarTitleHandler = (context) => {
  return {
    getUnrendered() {
      if (context.sidebar?.title) {
        return {
          inlines: {
            [kSidebarTitleId]: context.sidebar.title
          }
        };
      } else {
        const mainTitle = title2(context.format);
        if (mainTitle) {
          return {
            inlines: {
              [kSidebarTitleId]: mainTitle
            }
          };
        }
      }
    },
    processRendered(rendered, doc) {
      const renderedEl = rendered[kSidebarTitleId];
      if (renderedEl) {
        const sidebarTitleEl = doc.querySelector("#quarto-sidebar .sidebar-title a") || doc.querySelector("#quarto-sidebar .sidebar-title");
        if (sidebarTitleEl && sidebarTitleEl.innerText) {
          sidebarTitleEl.innerHTML = renderedEl.innerHTML;
        }
      }
    }
  };
};
var navbarTitleHandler = (context) => {
  return {
    getUnrendered() {
      if (context.navigation?.navbar?.title) {
        return {
          inlines: { [kNavbarTitleId]: context.navigation.navbar.title }
        };
      } else {
        const mainTitle = title2(context.format);
        if (mainTitle) {
          return {
            inlines: {
              [kNavbarTitleId]: mainTitle
            }
          };
        }
      }
    },
    processRendered(rendered, doc) {
      const renderedEl = rendered[kNavbarTitleId];
      if (renderedEl) {
        const navbarTitleEl = doc.querySelector(
          "#quarto-header .navbar-brand .navbar-title"
        );
        if (navbarTitleEl && navbarTitleEl.innerText) {
          navbarTitleEl.innerHTML = renderedEl.innerHTML;
        }
      }
    }
  };
};
var nextPageTitleHandler = (context) => {
  return {
    getUnrendered() {
      if (context.pageNavigation.nextPage?.text) {
        return {
          inlines: { [kNavNextId]: context.pageNavigation.nextPage.text }
        };
      }
    },
    processRendered(rendered, doc) {
      const renderedEl = rendered[kNavNextId];
      if (renderedEl) {
        const el = doc.querySelector(
          `.page-navigation .nav-page-next a .nav-page-text`
        );
        if (el) {
          el.innerHTML = renderedEl.innerHTML;
        }
      }
    }
  };
};
var prevPageTitleHandler = (context) => {
  return {
    getUnrendered() {
      if (context.pageNavigation.prevPage?.text) {
        return {
          inlines: { [kNavPrevId]: context.pageNavigation.prevPage.text }
        };
      }
    },
    processRendered(rendered, doc) {
      const renderedEl = rendered[kNavPrevId];
      if (renderedEl) {
        const el = doc.querySelector(
          `.page-navigation .nav-page-previous a .nav-page-text`
        );
        if (el) {
          el.innerHTML = renderedEl.innerHTML;
        }
      }
    }
  };
};
var breadCrumbHandler = (context) => {
  return {
    getUnrendered() {
      if (context.breadCrumbs) {
        const markdown = {};
        for (const item of context.breadCrumbs) {
          if (item.text) {
            markdown[`${kBreadcrumbPrefix}-${textKey(item.text)}`] = item.text;
          }
        }
        return { inlines: markdown };
      }
    },
    processRendered(rendered, doc) {
      const breadCrumbs2 = doc.querySelectorAll(
        ".quarto-page-breadcrumbs .breadcrumb-item"
      );
      for (const breadCrumb of breadCrumbs2) {
        const linkEl = breadCrumb.querySelector("a");
        const breadCrumbEl = linkEl !== null ? linkEl : breadCrumb;
        const key = breadCrumbEl.innerHTML;
        const renderedEl = rendered[`${kBreadcrumbPrefix}-${textKey(key)}`];
        if (renderedEl) {
          breadCrumbEl.innerHTML = renderedEl.innerHTML;
        }
      }
    }
  };
};
var announcementHandler = (context) => {
  return {
    getUnrendered() {
      if (context.announcement?.content) {
        return { blocks: { announcement: context.announcement.content } };
      }
    },
    processRendered(rendered, doc) {
      const announceEl = doc.querySelector(
        "#quarto-announcement .quarto-announcement-content"
      );
      if (announceEl) {
        const renderedEl = rendered["announcement"];
        announceEl.innerHTML = renderedEl.innerHTML;
      }
    }
  };
};
var textKey = (text) => {
  return text.replaceAll(/\s|&nbsp;/gm, "-").replaceAll(/"/gm, "'");
};
var sidebarContentsHandler = (context) => {
  return {
    getUnrendered() {
      if (context.sidebar?.contents) {
        const sidebarItems = flattenItems(context.sidebar?.contents, (_3) => {
          return true;
        });
        const markdown = {};
        sidebarItems.forEach((item) => {
          if (item.text) {
            if (item.sectionId) {
              markdown[`${kSidebarIdPrefix}${item.sectionId}`] = item.text;
            } else {
              markdown[`${kSidebarIdPrefix}${item.href}${textKey(item.text)}`] = item.text;
            }
          }
        });
        return { inlines: markdown };
      }
    },
    processRendered(rendered, doc) {
      const sidebarItemEls = doc.querySelectorAll(
        ".sidebar-item:not(.sidebar-item-section) .sidebar-item-text"
      );
      for (let i6 = 0; i6 < sidebarItemEls.length; i6++) {
        const sidebarEl = sidebarItemEls[i6];
        const href = sidebarEl.getAttribute("href");
        const link2 = sidebarEl.querySelector(".menu-text");
        if (link2) {
          const text = textKey(link2.innerHTML);
          const sidebarText = rendered[`${kSidebarIdPrefix}${href}${text}`];
          if (sidebarText) {
            link2.innerHTML = sidebarText.innerHTML;
          }
        }
      }
      const sidebarSectionEls = doc.querySelectorAll(
        ".sidebar-item.sidebar-item-section .sidebar-item-text"
      );
      for (let i6 = 0; i6 < sidebarSectionEls.length; i6++) {
        const sectionEl = sidebarSectionEls[i6];
        const target = sectionEl.getAttribute("data-bs-target");
        if (target) {
          const id = target.slice(1);
          const sectionText = rendered[`${kSidebarIdPrefix}${id}`];
          if (sectionText) {
            const link2 = sectionEl.querySelector(".menu-text");
            if (link2) {
              link2.innerHTML = sectionText.innerHTML;
            }
          }
        }
      }
    }
  };
};
var navbarContentsHandler = (context) => {
  return {
    getUnrendered() {
      if (context.navigation?.navbar) {
        const markdown = {};
        const entries = [
          ...context.navigation.navbar.left || [],
          ...context.navigation.navbar.right || []
        ];
        const addEntry = (entry) => {
          if (typeof entry === "string") {
            markdown[`${kNavbarIdPrefix}${entry.trim()}`] = entry;
            return;
          }
          if (entry.text) {
            markdown[`${kNavbarIdPrefix}${entry.text.trim()}`] = entry.text;
          }
          if (entry.href) {
            markdown[`${kNavbarIdPrefix}${entry.href.trim()}`] = mdSafeHref(
              entry.href
            );
          }
          if (entry.menu?.entries) {
            for (const childEntry of entry.menu) {
              addEntry(childEntry);
            }
          }
        };
        entries.forEach((entry) => {
          addEntry(entry);
        });
        const tools = context.navigation.navbar.tools;
        if (tools) {
          tools.forEach((tool) => {
            if (tool.href) {
              markdown[`${kToolsPrefix}${tool.href.trim()}`] = mdSafeHref(
                tool.href
              );
            }
          });
        }
        return { inlines: markdown };
      }
    },
    processRendered(rendered, doc) {
      const selectors = [
        ".navbar-nav .nav-item a.nav-link .menu-text",
        ".navbar-nav .dropdown-menu .dropdown-item .dropdown-text",
        ".navbar-nav .dropdown-menu .dropdown-header"
      ];
      selectors.forEach((selector) => {
        const navItemEls = doc.querySelectorAll(selector);
        for (let i6 = 0; i6 < navItemEls.length; i6++) {
          const link2 = navItemEls[i6];
          const id = link2.innerText.trim();
          if (id) {
            const renderedEl = rendered[`${kNavbarIdPrefix}${id}`];
            if (renderedEl) {
              link2.innerHTML = renderedEl?.innerHTML;
            }
          }
          const textParent = link2.parentElement;
          if (textParent) {
            const href = textParent.getAttribute("href");
            if (href) {
              const renderedHref = rendered[`${kNavbarIdPrefix}${href}`];
              if (renderedHref) {
                textParent.setAttribute("href", renderedHref?.innerText);
              }
            }
          }
        }
      });
      [".navbar .quarto-navbar-tools .quarto-navigation-tool"].forEach(
        (sel) => {
          const toolNodes = doc.querySelectorAll(sel);
          for (let i6 = 0; i6 < toolNodes.length; i6++) {
            const toolEl = toolNodes[i6];
            const href = toolEl.getAttribute("href");
            if (href) {
              const renderedHref = rendered[`${kToolsPrefix}${href}`];
              if (renderedHref) {
                toolEl.setAttribute("href", renderedHref?.innerText);
              }
            }
          }
        }
      );
    }
  };
};
var toHeaderFooterMarkdown = (source2, prefix, content) => {
  const markdown = content.map((con) => {
    return expandMarkdown(source2, prefix, con);
  });
  return markdown.reduce(
    (previousValue, currentValue) => {
      return `${previousValue}
:::{.${prefix}-item}
${currentValue}
:::
`;
    },
    ""
  );
};
var toHeaderFooterContainer = (doc, prefix, contentEl) => {
  const containerEl = doc.createElement("div");
  containerEl.classList.add(`quarto-${prefix}`);
  for (const child of contentEl.children) {
    containerEl.appendChild(child);
  }
  return containerEl;
};
var sidebarHeaderFooterHandler = (context) => {
  const kSidebarHeader = "sidebar-header";
  const kSidebarFooter = "sidebar-footer";
  return {
    getUnrendered() {
      const result2 = {};
      if (context.sidebar?.header) {
        if (context.sidebar?.header && context.sidebar?.header.length > 0) {
          result2[kSidebarHeader] = toHeaderFooterMarkdown(
            context.source,
            kSidebarHeader,
            context.sidebar.header
          );
        }
      }
      if (context.sidebar?.footer) {
        if (context.sidebar?.footer && context.sidebar?.footer.length > 0) {
          result2[kSidebarFooter] = toHeaderFooterMarkdown(
            context.source,
            kSidebarFooter,
            context.sidebar.footer
          );
        }
      }
      return { blocks: result2 };
    },
    processRendered(rendered, doc) {
      const sidebarEl = doc.getElementById("quarto-sidebar");
      if (sidebarEl) {
        const renderedHeaderEl = rendered[kSidebarHeader];
        if (renderedHeaderEl) {
          const headerEl = toHeaderFooterContainer(
            doc,
            kSidebarHeader,
            renderedHeaderEl
          );
          sidebarEl.insertBefore(headerEl, sidebarEl.firstChild);
        }
        const renderedFooterEl = rendered[kSidebarFooter];
        if (renderedFooterEl) {
          const footerEl = toHeaderFooterContainer(
            doc,
            kSidebarFooter,
            renderedFooterEl
          );
          sidebarEl.appendChild(footerEl);
        }
      }
    }
  };
};
var bodyHeaderFooterHandler = (context) => {
  return {
    getUnrendered() {
      const result2 = {};
      if (context.bodyDecorators?.header) {
        result2[kBodyHeader] = toHeaderFooterMarkdown(
          context.source,
          kBodyHeader,
          context.bodyDecorators?.header
        );
      }
      if (context.bodyDecorators?.footer) {
        result2[kBodyFooter] = toHeaderFooterMarkdown(
          context.source,
          kBodyFooter,
          context.bodyDecorators?.footer
        );
      }
      return { blocks: result2 };
    },
    processRendered(rendered, doc) {
      const mainEl = doc.querySelector("main");
      if (mainEl) {
        const renderedHeaderEl = rendered[kBodyHeader];
        if (renderedHeaderEl) {
          const headerEl = renderedHeaderEl.querySelector(
            `.${kBodyHeader}-item`
          );
          if (headerEl) {
            const titleBlock = mainEl.querySelector("#title-block-header");
            const insertBefore = titleBlock?.nextElementSibling || mainEl.childNodes[0] || null;
            for (const child of headerEl.children) {
              if (insertBefore) {
                mainEl.insertBefore(child, insertBefore);
              } else {
                mainEl.appendChild(child);
              }
            }
          }
        }
        const renderedFooterEl = rendered[kBodyFooter];
        if (renderedFooterEl) {
          const footerEl = renderedFooterEl.querySelector(
            `.${kBodyFooter}-item`
          );
          if (footerEl) {
            for (const child of footerEl.children) {
              mainEl.appendChild(child);
            }
          }
        }
      }
    }
  };
};
var marginHeaderFooterHandler = (context) => {
  return {
    getUnrendered() {
      const result2 = {};
      if (context.navigation?.pageMargin) {
        const projectHeaders = context.navigation.pageMargin.header;
        const pageHeaderRaw = context.format.metadata[kMarginHeader];
        const pageHeaders = pageHeaderRaw !== void 0 ? Array.isArray(pageHeaderRaw) ? pageHeaderRaw : [pageHeaderRaw] : [];
        const marginHeaders = [
          ...projectHeaders || [],
          ...pageHeaders || []
        ];
        if (marginHeaders && marginHeaders.length > 0) {
          result2[kMarginHeader] = toHeaderFooterMarkdown(
            context.source,
            kMarginHeader,
            marginHeaders
          );
        }
        const projectFooters = context.navigation.pageMargin.footer;
        const pageFooterRaw = context.format.metadata[kMarginFooter];
        const pageFooters = pageFooterRaw !== void 0 ? Array.isArray(pageFooterRaw) ? pageFooterRaw : [pageFooterRaw] : [];
        const marginFooters = [
          ...projectFooters || [],
          ...pageFooters || []
        ].filter((item) => item !== void 0);
        if (marginFooters && marginFooters.length > 0) {
          result2[kMarginFooter] = toHeaderFooterMarkdown(
            context.source,
            kMarginFooter,
            marginFooters
          );
        }
      }
      return { blocks: result2 };
    },
    processRendered(rendered, doc) {
      const sidebarEl = doc.getElementById("quarto-margin-sidebar");
      if (sidebarEl) {
        const renderedHeaderEl = rendered[kMarginHeader];
        if (renderedHeaderEl) {
          const headerEl = toHeaderFooterContainer(
            doc,
            kMarginHeader,
            renderedHeaderEl
          );
          sidebarEl.insertBefore(headerEl, sidebarEl.firstChild);
        }
        const renderedFooterEl = rendered[kMarginFooter];
        if (renderedFooterEl) {
          const footerEl = toHeaderFooterContainer(
            doc,
            kMarginFooter,
            renderedFooterEl
          );
          sidebarEl.appendChild(footerEl);
        }
      }
    }
  };
};
var kNavFooterPrefix = "footer-";
var footerHandler = (context) => {
  return {
    getUnrendered() {
      if (context.navigation?.footer) {
        const markdown = {};
        const addEntry = (key, value) => {
          if (typeof value === "string") {
            markdown[`${kNavFooterPrefix}${key}`] = value;
          } else {
            value.forEach((navItem) => {
              if (typeof navItem === "object") {
                if (navItem.text) {
                  markdown[`${kNavFooterPrefix}${key}-${navItem.href || navItem.text}`] = navItem.text;
                }
              }
            });
          }
        };
        if (context.navigation.footer.left) {
          addEntry("left", context.navigation.footer.left);
        }
        if (context.navigation.footer.center) {
          addEntry("center", context.navigation.footer.center);
        }
        if (context.navigation.footer.right) {
          addEntry("right", context.navigation.footer.right);
        }
        return { blocks: markdown };
      }
    },
    processRendered(rendered, doc) {
      const process4 = (key) => {
        const footerEl = doc.querySelector(`.nav-footer .nav-footer-${key}`);
        if (footerEl) {
          const footer = rendered[`${kNavFooterPrefix}${key}`];
          if (footer) {
            footerEl.innerHTML = footer.innerHTML;
          }
        }
        const navItemEls = doc.querySelectorAll(
          ".nav-footer .nav-item a.nav-link"
        );
        for (let i6 = 0; i6 < navItemEls.length; i6++) {
          const link2 = navItemEls[i6];
          const href = link2.getAttribute("href");
          const id = href || link2.innerText;
          if (id) {
            const renderedEl = rendered[`${kNavFooterPrefix}${key}-${id}`];
            if (renderedEl) {
              removeChapterNumber(renderedEl);
              link2.innerHTML = renderedEl?.innerHTML;
            }
          }
        }
      };
      process4("left");
      process4("center");
      process4("right");
    }
  };
};
function expandMarkdown(source2, name2, val) {
  if (Array.isArray(val)) {
    return val.map((pathOrMarkdown) => {
      return expandMarkdownFilePath(source2, pathOrMarkdown);
    });
  } else if (typeof val == "string") {
    return [expandMarkdownFilePath(source2, val)];
  } else {
    throw Error(`Invalid value for ${name2}:
${val}`);
  }
}
function expandMarkdownFilePath(source2, path3) {
  const absPath = isAbsolute4(path3) ? path3 : join4(dirname4(source2), path3);
  if (safeExistsSync(absPath)) {
    const fileContents = Deno.readTextFileSync(absPath);
    const ext = extname4(absPath);
    if (ext === ".html") {
      return "```{=html}\n" + fileContents + "\n```";
    } else {
      return fileContents;
    }
  } else {
    return path3;
  }
}
function mdSafeHref(href) {
  href = href.replaceAll("---", "\\-\\-\\-");
  href = href.replaceAll("--", "\\-\\-");
  href = href.replaceAll("@", "\\@");
  return href;
}

// project/types/website/website-navigation.ts
init_jupyter();

// project/types/website/website-sidebar-auto.ts
init_path();
init_constants6();

// core/cast.ts
function asNumber(x3, defaultValue = 0) {
  if (x3 === void 0) {
    return x3;
  } else if (typeof x3 === "number") {
    return x3;
  } else if (typeof x3 === "string") {
    try {
      return parseFloat(x3);
    } catch {
      return defaultValue;
    }
  } else if (typeof x3 === "boolean") {
    return x3 ? 1 : 0;
  } else {
    return defaultValue;
  }
}

// project/types/website/website-sidebar-auto.ts
init_lodash();
init_path2();
init_text2();
await init_engine();
async function expandAutoSidebarItems(project, items) {
  items = normalizeSidebarItems(cloneDeep(items));
  const expanded = [];
  for (const item of items) {
    if (item.auto) {
      const autoItems = await sidebarItemsFromAuto(project, item.auto);
      expanded.push(...autoItems);
    } else {
      if (item.contents) {
        if (typeof item.contents === "string") {
          if (item.section) {
            const hasProjectHref = project.files.input.includes(
              join4(project.dir, item.section)
            ) || item.href && project.files.input.includes(
              join4(project.dir, item.href)
            );
            if (!hasProjectHref) {
              const globbedDir = globbedDirectory(project, item.contents);
              if (globbedDir) {
                const indexFileHref = indexFileHrefForDir(project, globbedDir);
                if (indexFileHref) {
                  item.text = item.section;
                  item.section = indexFileHref;
                }
              }
            }
          }
        }
        item.contents = await expandAutoSidebarItems(project, item.contents);
      }
      expanded.push(item);
    }
  }
  return expanded;
}
function globbedDirectory(project, contentsGlob) {
  const isValidDirectory = (dir) => {
    return safeExistsSync(dir) && Deno.statSync(dir).isDirectory;
  };
  const literalTargetDir = join4(project.dir, contentsGlob);
  if (isValidDirectory(literalTargetDir)) {
    return literalTargetDir;
  }
  const match = contentsGlob.match(/(.*?)\/\*.*$/);
  if (match) {
    const globTargetDir = join4(project.dir, match[1]);
    if (isValidDirectory(globTargetDir)) {
      return globTargetDir;
    }
  }
}
function normalizeSidebarItems(items) {
  if (!Array.isArray(items)) {
    if (typeof items === "string") {
      if (items === "auto") {
        items = [{ auto: true }];
      } else {
        items = [{ auto: items }];
      }
    } else {
      items = [items];
    }
  }
  return items;
}
async function sidebarItemsFromAuto(project, auto) {
  const isAutoDir = typeof auto === "string" && !!auto.match(/^[^\*]+$/) && safeExistsSync(join4(project.dir, auto));
  const globs = globsFromAuto(project, auto);
  const entries = [];
  for (const nodeSet of autoSidebarNodes(project, globs)) {
    if (isAutoDir) {
      const root = nodeSet.root.split("/");
      nodeSet.root = root.slice(0, -1).join("/");
      nodeSet.nodes = {
        [root.slice(-1)[0]]: nodeSet.nodes
      };
    }
    entries.push(
      ...await nodesToEntries(
        project,
        `${nodeSet.root ? nodeSet.root + "/" : ""}`,
        nodeSet.nodes
      )
    );
  }
  return sidebarItemsFromEntries(entries.sort(sortEntries));
}
function globsFromAuto(project, auto) {
  const globs = [];
  if (typeof auto === "boolean") {
    if (auto === true) {
      globs.push("*");
    }
  } else {
    if (!Array.isArray(auto)) {
      auto = [auto];
    }
    globs.push(...auto.map((glob) => {
      const target = join4(project.dir, glob);
      if (safeExistsSync(target) && Deno.statSync(target).isDirectory) {
        glob = join4(glob, "**");
      }
      return glob;
    }));
  }
  return globs;
}
function autoSidebarNodes(project, globs) {
  return globs.map((glob) => {
    const inputs = uniq(
      filterPaths(
        project.dir,
        project.files.input,
        [glob],
        { mode: "always" }
      ).include
    ).filter((input) => !/^index\.\w+$/.test(input)).map((input) => pathWithForwardSlashes(relative4(project.dir, input)));
    let directory = "";
    const match = glob.match(/(.*?)[\/\\]\*.*$/);
    if (match && safeExistsSync(join4(project.dir, match[1]))) {
      directory = match[1];
    }
    let result2 = {};
    inputs.forEach(
      (p5) => p5.split("/").reduce(
        (o5, k3) => o5[k3] = o5[k3] || {},
        result2
      )
    );
    if (directory) {
      directory.split("/").forEach((p5) => {
        result2 = result2[p5];
      });
    }
    return {
      root: directory,
      nodes: result2
    };
  });
}
function indexFileHrefForDir(project, dir) {
  const indexFileExt = engineValidExtensions().find((ext) => {
    return safeExistsSync(join4(dir, `index${ext}`));
  });
  if (indexFileExt) {
    return relative4(project.dir, join4(dir, `index${indexFileExt}`));
  }
}
async function nodesToEntries(project, root, nodes) {
  nodes = cloneDeep(nodes);
  const indexFile = findIndexFile(nodes);
  if (indexFile) {
    delete nodes[indexFile];
  }
  const entries = [];
  for (const node of Object.keys(nodes)) {
    const href = `${root}${node}`;
    const path3 = join4(project.dir, href);
    if (safeExistsSync(path3)) {
      if (Deno.statSync(path3).isDirectory) {
        const childNodes = cloneDeep(nodes[node]);
        const indexFile2 = findIndexFile(childNodes);
        if (indexFile2) {
          delete childNodes[indexFile2];
        }
        if (indexFile2) {
          entries.push({
            ...await entryFromHref(
              project,
              relative4(project.dir, join4(path3, indexFile2))
            ),
            children: childNodes && Object.keys(childNodes).length > 0 ? await nodesToEntries(
              project,
              `${root}${node}/`,
              childNodes
            ) : void 0
          });
        } else {
          entries.push({
            title: titleFromPath(href),
            basename: basename4(href),
            children: await nodesToEntries(
              project,
              `${root}${node}/`,
              childNodes
            )
          });
        }
      } else {
        entries.push(await entryFromHref(project, href));
      }
    }
  }
  return entries.sort(sortEntries);
}
function findIndexFile(nodes) {
  return Object.keys(nodes).find((input) => /^index\.\w+$/.test(input));
}
function sortEntries(a5, b3) {
  const filenameOrder = a5.basename.toLocaleUpperCase().localeCompare(
    b3.basename.toLocaleUpperCase()
  );
  if (a5.order !== void 0 && b3.order !== void 0) {
    const order = a5.order - b3.order;
    return order !== 0 ? order : filenameOrder;
  } else if (a5.order !== void 0) {
    return -1;
  } else if (b3.order !== void 0) {
    return 1;
  } else {
    if (a5.children && !b3.children) {
      return 1;
    } else if (b3.children && !a5.children) {
      return -1;
    } else {
      return filenameOrder;
    }
  }
}
async function entryFromHref(project, href) {
  const index2 = await inputTargetIndex(project, pathWithForwardSlashes(href));
  const resolved = await resolveInputTarget(
    project,
    pathWithForwardSlashes(href)
  );
  const basename13 = dirAndStem(href)[1];
  return {
    title: index2?.title || resolved?.title || titleFromPath(basename13),
    basename: basename13,
    href,
    order: asNumber(index2?.markdown.yaml?.[kOrder]),
    empty: index2 ? inputTargetIsEmpty(index2) : false,
    draft: resolved?.draft
  };
}
function titleFromPath(path3) {
  const name2 = basename4(path3);
  if (!name2.includes(" ")) {
    return capitalizeTitle(name2.replaceAll(/[_\-]+/g, " "));
  } else {
    return name2;
  }
}
function sidebarItemsFromEntries(entries) {
  return entries.map((entry) => {
    if (entry.children) {
      return {
        section: !entry.href || entry.empty ? entry.title : entry.href,
        contents: sidebarItemsFromEntries(entry.children)
      };
    } else {
      return {
        text: entry.title,
        href: entry.href,
        draft: entry.draft
      };
    }
  });
}

// format/dashboard/format-dashboard-shared.ts
init_log();
init_constants6();
init_github2();
init_resources2();
init_sass();
init_format_html_info();
init_format_html_shared();
var kDashboard = "dashboard";
var kDTTableSentinel = "data-dt-support";
var kLayoutAttr = "data-layout";
var kFillAttr = "data-fill";
var kLayoutFill = "fill";
var kLayoutFlow = "flow";
var kCardClass = "card";
var kDashboardGridSkip = "grid-skip";
var kNavButtons = "nav-buttons";
var kDontMutateTags = ["P", "SCRIPT"];
var kValueboxClass = "valuebox";
function dashboardScssLayer() {
  const dashboardScss = formatResourcePath(
    "dashboard",
    "quarto-dashboard.scss"
  );
  const dashboardLayer = sassLayer(dashboardScss);
  const dashboardScssDependency = {
    dependency: kBootstrapDependencyName,
    key: dashboardScss,
    quarto: {
      name: "quarto-dashboard.css",
      ...dashboardLayer
    }
  };
  return dashboardScssDependency;
}
async function dashboardMeta(format14) {
  const dashboardRaw = format14.metadata;
  const orientation = dashboardRaw && dashboardRaw.orientation === "columns" ? "columns" : "rows";
  const scrolling = dashboardRaw.scrolling === true;
  const expandable = dashboardRaw.expandable !== false;
  const dashboardTitle = format14.metadata[kTitle];
  const processNavbarButton = async (buttonRaw) => {
    if (typeof buttonRaw === "string") {
      if (kNavButtonAliases[buttonRaw] !== void 0) {
        return kNavButtonAliases[buttonRaw](dashboardTitle);
      }
      return void 0;
    } else {
      return buttonRaw;
    }
  };
  const navbarButtons = [];
  const navbarButtonsRaw = format14.metadata[kNavButtons];
  if (Array.isArray(navbarButtonsRaw)) {
    for (const btnRaw of navbarButtonsRaw) {
      const btn = await processNavbarButton(btnRaw);
      if (btn) {
        navbarButtons.push(btn);
      }
    }
  } else {
    const btn = await processNavbarButton(navbarButtonsRaw);
    if (btn) {
      navbarButtons.push(btn);
    }
  }
  const hasDarkMode = formatDarkMode(format14) !== void 0;
  return {
    orientation,
    scrolling,
    expandable,
    hasDarkMode,
    [kNavButtons]: navbarButtons
  };
}
function hasFlowLayout(el) {
  return el.getAttribute(kLayoutAttr) === kLayoutFlow;
}
function makeEl(name2, attr, doc) {
  const el = doc.createElement(name2);
  if (attr.id) {
    el.id = attr.id;
  }
  for (const cls of attr.classes || []) {
    el.classList.add(cls);
  }
  const attribs = attr.attributes || {};
  for (const key of Object.keys(attribs)) {
    el.setAttribute(key, attribs[key]);
  }
  return el;
}
var processAndRemoveAttr = (el, attr, process4, defaultValue) => {
  const resolvedAttr = el.getAttribute(attr);
  if (resolvedAttr !== null) {
    process4(el, resolvedAttr);
    el.removeAttribute(attr);
  } else if (defaultValue) {
    process4(el, defaultValue);
  }
};
var ensureCssUnits = (fn) => {
  return (el, attrValue) => {
    if (attrValue === "0") {
      fn(el, attrValue);
    } else {
      const attrWithUnits = attrValue.match(kEndsWithNumber) ? `${attrValue}px` : attrValue;
      fn(el, attrWithUnits);
    }
  };
};
var kEndsWithNumber = /[0-9]$/;
var attrToStyle = (style) => {
  return (el, attrValue) => {
    const newStyle = [];
    const currentStyle = el.getAttribute("style");
    if (currentStyle !== null) {
      newStyle.push(currentStyle);
    }
    newStyle.push(`${style}: ${attrValue};`);
    el.setAttribute("style", newStyle.join(" "));
  };
};
var attrToCardBodyStyle = (style) => {
  return (el, attrValue) => {
    const cardBodyNodes = el.querySelectorAll(".card-body");
    for (const cardBodyNode of cardBodyNodes) {
      const cardBodyEl = cardBodyNode;
      const newStyle = [];
      const currentStyle = el.getAttribute("style");
      if (currentStyle !== null) {
        newStyle.push(currentStyle);
      }
      newStyle.push(`${style}: ${attrValue};`);
      cardBodyEl.setAttribute("style", newStyle.join(" "));
    }
  };
};
var applyClasses = (el, clz) => {
  for (const cls of clz) {
    el.classList.add(cls);
  }
};
var applyAttributes = (el, attr) => {
  for (const key of Object.keys(attr)) {
    el.setAttribute(key, attr[key]);
  }
};
var kNavButtonAliases = {
  linkedin: (text) => {
    return Promise.resolve({
      icon: "linkedin",
      title: "LinkedIn",
      href: `https://www.linkedin.com/sharing/share-offsite/?url=|url|&title=${text ? encodeURI(text) : void 0}`
    });
  },
  facebook: (_text) => {
    return Promise.resolve({
      icon: "facebook",
      title: "Facebook",
      href: "https://www.facebook.com/sharer/sharer.php?u=|url|"
    });
  },
  reddit: (text) => {
    return Promise.resolve({
      icon: "reddit",
      title: "Reddit",
      href: `https://reddit.com/submit?url=|url|&title=${text ? encodeURI(text) : void 0}`
    });
  },
  twitter: (text) => {
    return Promise.resolve({
      icon: "twitter",
      title: "Twitter",
      href: `https://twitter.com/intent/tweet?url=|url|&text=${text ? encodeURI(text) : void 0}`
    });
  },
  github: async (_text) => {
    const context = await gitHubContext(Deno.cwd());
    if (context.repoUrl) {
      return {
        icon: "github",
        title: "GitHub",
        href: context.repoUrl
      };
    } else {
      warn(
        "Unable to determine GitHub repository for the `github` nav-button. Is this directory a GitHub repository?"
      );
      return void 0;
    }
  }
};

// project/types/website/about/website-about.ts
init_path();
init_constants6();
init_types5();
init_quarto();
init_resources2();
init_sass();
init_format_html_shared();
init_website_constants();
var kAbout = "about";
var kTemplate2 = "template";
var kType2 = "type";
var kLinks = "links";
var kImageWidth2 = "image-width";
var kImageAlt3 = "image-alt";
var kImageTitle = "image-title";
var kImageShape = "image-shape";
var kImageShapeRound = "round";
var kImageShapeRounded = "rounded";
var kTemplateJolla = "jolla";
var kTemplateTrestles = "trestles";
var kTemplateSolana = "solana";
var kTemplateMarquee = "marquee";
var kTemplateBroadside = "broadside";
var kTemplates = [
  kTemplateJolla,
  kTemplateTrestles,
  kTemplateSolana,
  kTemplateMarquee,
  kTemplateBroadside
];
function isAboutPage(format14) {
  return !!format14.metadata[kAbout];
}
async function aboutHtmlDependencies(source2, project, format14, _temp, _extras) {
  const aboutPage = await readAbout(source2, project, format14);
  if (aboutPage) {
    format14.pandoc[kToc] = false;
    format14.metadata[kTocLocation] = "right";
    format14.metadata[kAnchorSections] = false;
  }
  const scssPath = join4(
    projectTypeResourcePath("website"),
    `about/about.scss`
  );
  const aboutLayer = sassLayerFile(scssPath);
  const sassBundles = [
    {
      dependency: kBootstrapDependencyName,
      key: scssPath,
      quarto: {
        name: `quarto-about.css`,
        ...aboutLayer
      }
    }
  ];
  const markdownHandlers = [];
  if (aboutPage) {
    markdownHandlers.push(aboutLinksMarkdownHandler(aboutPage));
  }
  const pipeline2 = createMarkdownPipeline(
    `quarto-about-pipeline`,
    markdownHandlers
  );
  return {
    [kMarkdownAfterBody]: markdownHandlers.length > 0 ? [pipeline2.markdownAfterBody()] : [""],
    [kHtmlPostprocessors]: aboutPage ? aboutPagePostProcessor(aboutPage, pipeline2) : void 0,
    [kSassBundles]: sassBundles
  };
}
async function readAbout(source2, project, format14) {
  const about = format14.metadata[kAbout];
  if (about) {
    const resolveOptions3 = (aboutTemplate, aboutObj, aboutPage) => {
      const knownFieldList = [
        "image",
        kImageAlt3,
        kImageTitle,
        "template",
        "links"
      ];
      for (const key of Object.keys(aboutObj)) {
        if (!knownFieldList.includes(key)) {
          aboutPage.options[key] = aboutObj[key];
        }
      }
      if (aboutPage.options[kImageShape] === void 0) {
        if (aboutTemplate === kTemplateJolla) {
          aboutPage.options[kImageShape] = kImageShapeRound;
        } else if (aboutTemplate === kTemplateSolana) {
          aboutPage.options[kImageShape] = kImageShapeRounded;
        } else if (aboutTemplate === kTemplateTrestles) {
          aboutPage.options[kImageShape] = kImageShapeRounded;
        }
      }
      if (aboutPage.options[kImageWidth2] === void 0) {
        if (aboutTemplate === kTemplateJolla) {
          aboutPage.options[kImageWidth2] = "15em";
        } else if (aboutTemplate === kTemplateSolana) {
          aboutPage.options[kImageWidth2] = "15em";
        } else if (aboutTemplate === kTemplateTrestles) {
          aboutPage.options[kImageWidth2] = "20em";
        } else if (aboutTemplate === kTemplateMarquee) {
          aboutPage.options[kImageWidth2] = "100%";
        } else if (aboutTemplate === kTemplateBroadside) {
          aboutPage.options[kImageWidth2] = "15em";
        }
      }
      return aboutPage;
    };
    if (typeof about === "string") {
      const [template2, custom2] = templatePath(about, source2);
      const aboutPage = {
        template: template2,
        custom: custom2,
        options: {}
      };
      if (format14.metadata[kImage]) {
        aboutPage.image = format14.metadata[kImage];
      }
      if (format14.metadata[kImageAlt3]) {
        aboutPage[kImageAlt3] = format14.metadata[kImageAlt3];
      }
      if (format14.metadata[kImageTitle]) {
        aboutPage[kImageTitle] = format14.metadata[kImageTitle];
      }
      resolveOptions3(about, {}, aboutPage);
      return aboutPage;
    } else if (typeof about === "object") {
      const aboutObj = about;
      const aboutTemplate = aboutObj[kType2] || aboutObj[kTemplate2];
      const [template2, custom2] = templatePath(aboutTemplate, source2);
      const id = aboutObj.id;
      const aboutPage = {
        id,
        template: template2,
        custom: custom2,
        options: {}
      };
      const aboutImage = aboutObj[kImage];
      if (aboutImage) {
        aboutPage.image = aboutImage;
      } else {
        if (format14.metadata[kImage]) {
          aboutPage.image = format14.metadata[kImage];
        }
      }
      const aboutImageAlt = aboutObj[kImageAlt3];
      if (aboutImageAlt) {
        aboutPage[kImageAlt3] = aboutImageAlt;
      } else {
        if (format14.metadata[kImageAlt3]) {
          aboutPage[kImageAlt3] = format14.metadata[kImageAlt3];
        }
      }
      const aboutImageTitle = aboutObj[kImageTitle];
      if (aboutImageTitle) {
        aboutPage[kImageTitle] = aboutImageTitle;
      } else {
        if (format14.metadata[kImageTitle]) {
          aboutPage[kImageTitle] = format14.metadata[kImageTitle];
        }
      }
      const aboutLinks = aboutObj[kLinks];
      if (aboutLinks) {
        const links = [];
        for (const aboutLink of aboutLinks) {
          links.push(await navigationItem(project, aboutLink, 0, false));
        }
        aboutPage.links = links;
      }
      resolveOptions3(aboutTemplate, aboutObj, aboutPage);
      return aboutPage;
    } else {
      return void 0;
    }
  } else {
    return void 0;
  }
}
function templatePath(template2, source2) {
  if (kTemplates.includes(template2)) {
    return [
      join4(
        projectTypeResourcePath("website"),
        `about/${template2}.ejs.html`
      ),
      false
    ];
  } else {
    return [join4(dirname4(source2), template2), true];
  }
}
var aboutPagePostProcessor = (aboutPage, pipeline2) => {
  return (doc) => {
    const titleEl = doc.getElementById("title-block-header");
    titleEl?.remove();
    const title3 = titleEl?.outerHTML || "";
    let aboutEl = aboutPage.id ? doc.getElementById(aboutPage.id) : void 0;
    if (!aboutEl) {
      aboutEl = doc.querySelector("main.content");
    }
    const body = aboutEl?.outerHTML || "";
    const ejsData2 = {
      title: title3,
      body,
      image: aboutPage.image,
      [kImageAlt3]: aboutPage[kImageAlt3],
      [kImageTitle]: aboutPage[kImageTitle],
      links: aboutPage.links,
      options: aboutPage.options
    };
    const aboutPageHtml = renderEjs(
      aboutPage.template,
      { about: ejsData2 },
      true,
      !aboutPage.custom && !quartoConfig.isDebug()
    );
    const aboutPageContainer = doc.createElement("div");
    aboutPageContainer.innerHTML = aboutPageHtml;
    aboutEl?.after(...aboutPageContainer.childNodes);
    aboutEl?.remove();
    const result2 = {
      resources: [],
      supporting: []
    };
    if (aboutPage.image) {
      result2.resources.push(aboutPage.image);
    }
    pipeline2.processRenderedMarkdown(doc);
    return Promise.resolve(result2);
  };
};
var aboutLinksMarkdownHandler = (aboutPage) => {
  return {
    getUnrendered: () => {
      const pipelineMarkdown = {};
      let count = 1;
      aboutPage.links?.forEach((link2) => {
        if (typeof link2 === "string") {
          pipelineMarkdown.inlines = pipelineMarkdown.inlines || {};
          pipelineMarkdown.inlines[link2] = link2;
        } else {
          if (link2.text) {
            pipelineMarkdown.inlines = pipelineMarkdown.inlines || {};
            pipelineMarkdown.inlines[link2.text] = link2.text;
          }
          if (link2.href) {
            const newId = `8B1E46B7-render-about-link-${count}`;
            pipelineMarkdown.inlines = pipelineMarkdown.inlines || {};
            pipelineMarkdown.inlines[newId] = mdSafeHref(link2.href);
          }
        }
        count++;
      });
      return pipelineMarkdown;
    },
    processRendered: (rendered, doc) => {
      const aboutLinkNodes = doc.querySelectorAll(
        ".about-links .about-link"
      );
      for (const aboutLinkNode of aboutLinkNodes) {
        const aboutLinkEl = aboutLinkNode;
        const aboutLinkTextNode = aboutLinkEl.querySelector(".about-link-text");
        if (aboutLinkTextNode) {
          const aboutLinkTextEl = aboutLinkTextNode;
          const aboutLinkRendered = rendered[aboutLinkTextEl.innerText.trim()];
          if (aboutLinkRendered) {
            aboutLinkTextEl.innerHTML = aboutLinkRendered.innerHTML;
          }
        }
        const href = aboutLinkEl.getAttribute("href");
        if (href !== null) {
          const aboutLinkHref = rendered[href];
          if (aboutLinkHref) {
            aboutLinkEl.setAttribute("href", aboutLinkHref.innerText);
          }
        }
      }
    }
  };
};

// project/types/website/website-navigation.ts
var kSidebarLogo = "logo";
var kSidebarLogoHref = "logo-href";
var kSidebarLogoAlt = "logo-alt";
async function initWebsiteNavigation(project) {
  resetMenuIds();
  const {
    navbar,
    sidebars,
    pageNavigation,
    footer,
    pageMargin,
    bodyDecorators,
    announcement
  } = await websiteNavigationConfig(
    project
  );
  if (!navbar && !sidebars && !pageNavigation && !footer && !pageMargin && !bodyDecorators) {
    return;
  }
  if (sidebars) {
    navigation.sidebars = await sidebarsEjsData(project, sidebars);
    navigation.sidebars = resolveNavReferences(
      navigation.sidebars
    );
  } else {
    navigation.sidebars = [];
  }
  if (navbar) {
    navigation.navbar = await navbarEjsData(project, navbar);
    navigation.navbar = resolveNavReferences(navigation.navbar);
  } else {
    navigation.navbar = void 0;
  }
  navigation.pageNavigation = pageNavigation;
  navigation.footer = await resolveFooter(project, footer);
  navigation.bodyDecorators = bodyDecorators;
  navigation.pageMargin = pageMargin;
  navigation.announcement = announcement;
}
async function websiteNoThemeExtras(project, source2, _flags, _format5, _temp) {
  return {
    html: {
      [kHtmlPostprocessors]: [
        async (doc) => {
          await resolveProjectInputLinks(source2, project, doc);
          return Promise.resolve({
            resources: [],
            supporting: []
          });
        }
      ]
    }
  };
}
async function websiteNavigationExtras(project, source2, flags, format14, temp) {
  const usesCustomLayout = !formatHasArticleLayout(format14);
  const hasToc = () => {
    if (disabledTableOfContents(format14)) {
      return false;
    } else if (hasTableOfContents(flags, format14)) {
      return true;
    } else if (usesCustomLayout) {
      return false;
    } else {
      return true;
    }
  };
  const tocLocation = () => {
    if (isAboutPage(format14)) {
      return "right";
    } else {
      return format14.metadata[kTocLocation] || "right";
    }
  };
  const inputRelative = relative4(project.dir, source2);
  const dependencies = [
    await websiteNavigationDependency(project)
  ];
  const includeInHeader = [];
  const sassBundles = [websiteNavigationSassBundle()];
  const searchDep = await websiteSearchDependency(project, source2);
  if (searchDep) {
    dependencies.push(...searchDep);
    sassBundles.push(websiteSearchSassBundle());
    includeInHeader.push(
      await websiteSearchIncludeInHeader(project, format14, temp)
    );
  }
  sassBundles.push(dashboardScssLayer());
  const disableNavbar = format14.metadata[kSiteNavbar] !== void 0 && format14.metadata[kSiteNavbar] === false;
  const disableSidebar = format14.metadata[kSiteSidebar] !== void 0 && format14.metadata[kSiteSidebar] === false || usesCustomLayout;
  const target = await resolveInputTarget(project, inputRelative);
  const href = target?.outputHref || inputFileHref(inputRelative);
  const sidebar = sidebarForHref(href, format14);
  const draftMode = projectDraftMode(project);
  const nav = {
    hasToc: hasToc(),
    [kTocLocation]: tocLocation(),
    layout: formatPageLayout(format14),
    navbar: disableNavbar ? void 0 : navigation.navbar,
    sidebar: disableSidebar ? void 0 : expandedSidebar(href, sidebar),
    sidebarStyle: sidebarStyle(),
    footer: navigation.footer,
    language: format14.language,
    showBreadCrumbs: websiteConfigBoolean(
      kBreadCrumbNavigation,
      true,
      project.config
    ),
    announcement: navigation.announcement,
    draftMode
  };
  const formatPageNav = format14.metadata[kSitePageNavigation];
  const pageNavigation = nextAndPrevious(href, sidebar);
  if (formatPageNav !== false && (navigation.pageNavigation || formatPageNav === true) && !usesCustomLayout) {
    nav.prevPage = pageNavigation.prevPage;
    nav.nextPage = pageNavigation.nextPage;
    const metaLinks = [];
    if (pageNavigation.nextPage?.href) {
      metaLinks.push(
        { rel: "next", href: pageNavigation.nextPage?.href }
      );
    }
    if (pageNavigation.prevPage?.href) {
      metaLinks.push(
        { rel: "prev", href: pageNavigation.prevPage?.href }
      );
    }
    if (metaLinks.length > 0) {
      dependencies.push({ name: "website-pagination", links: metaLinks });
    }
  }
  const crumbs = breadCrumbs(href, sidebar);
  navigation.breadCrumbs = crumbs;
  if (navigation.footer) {
    nav.footer = navigation.footer;
  }
  const darkMode = formatDarkMode(format14);
  if (darkMode !== void 0 && nav.navbar) {
    nav.navbar.darkToggle = true;
  } else if (darkMode !== void 0 && nav.sidebar) {
    nav.sidebar.darkToggle = true;
  }
  const readerMode = websiteConfigBoolean(
    kSiteReaderMode,
    false,
    project.config
  );
  if (readerMode && nav.navbar) {
    nav.navbar.readerToggle = true;
  } else if (readerMode && nav.sidebar) {
    nav.sidebar.readerToggle = true;
  }
  const projTemplate = (template2) => resourcePath(`projects/website/templates/${template2}`);
  const bodyEnvelope = {
    before: renderEjs(projTemplate("nav-before-body.ejs"), { nav }),
    afterPreamble: renderEjs(projTemplate("nav-after-body-preamble.ejs"), {
      nav
    }),
    afterPostamble: renderEjs(projTemplate("nav-after-body-postamble.ejs"), {
      nav
    })
  };
  const pipelineHandlers = navigationMarkdownHandlers({
    source: source2,
    format: format14,
    sidebar,
    navigation,
    pageNavigation,
    bodyDecorators: navigation.bodyDecorators,
    breadCrumbs: navigation.breadCrumbs,
    announcement: navigation.announcement
  });
  const markdownPipeline = createMarkdownPipeline(
    "quarto-navigation-envelope",
    pipelineHandlers
  );
  return {
    [kIncludeInHeader]: includeInHeader,
    html: {
      [kSassBundles]: sassBundles,
      [kDependencies]: dependencies,
      [kBodyEnvelope]: bodyEnvelope,
      [kHtmlPostprocessors]: [
        navigationHtmlPostprocessor(
          project,
          format14,
          source2,
          markdownPipeline,
          format14.language
        )
      ],
      [kMarkdownAfterBody]: [
        markdownPipeline.markdownAfterBody()
      ]
    }
  };
}
async function ensureIndexPage(project) {
  const outputDir = projectOutputDir(project);
  const indexPage = join4(outputDir, "index.html");
  if (!safeExistsSync(indexPage)) {
    const firstInput = project.files.input[0];
    if (firstInput) {
      const firstInputHref = relative4(project.dir, firstInput);
      const resolved = await resolveInputTarget(project, firstInputHref, false);
      if (resolved) {
        writeRedirectPage(indexPage, resolved.outputHref);
      }
    }
  }
}
function writeRedirectPage(path3, href) {
  const redirectTemplate = resourcePath(
    "projects/website/templates/redirect-simple.ejs"
  );
  const redirectHtml = renderEjs(redirectTemplate, {
    url: href
  });
  Deno.writeTextFileSync(path3, redirectHtml);
}
function navigationHtmlPostprocessor(project, format14, source2, markdownPipeline, language) {
  const sourceRelative = relative4(project.dir, source2);
  const href = inputFileHref(sourceRelative);
  const showBreadCrumbs = websiteConfigBoolean(
    kBreadCrumbNavigation,
    true,
    project.config
  ) && format14.metadata[kBreadCrumbNavigation] !== false;
  return async (doc) => {
    const secondaryNavTitleEl = doc.querySelector(
      ".quarto-secondary-nav .quarto-secondary-nav-title"
    );
    if (secondaryNavTitleEl) {
      if (showBreadCrumbs) {
        const navEl = makeBreadCrumbs(doc);
        if (secondaryNavTitleEl.parentElement) {
          secondaryNavTitleEl.parentElement.replaceChild(
            navEl,
            secondaryNavTitleEl
          );
        }
      } else {
        const titleEl = doc.querySelector("h1.title");
        if (titleEl) {
          for (const child of titleEl.childNodes) {
            secondaryNavTitleEl.append(child.cloneNode(true));
          }
          titleEl.classList.add("d-none");
          titleEl.classList.add("d-lg-block");
        }
      }
      const titleBlock = doc.querySelector("header > .quarto-title-block");
      if (titleBlock) {
        titleBlock.classList.add("d-none");
        titleBlock.classList.add("d-lg-block");
      }
    }
    const titleBlockEl = doc.querySelector(".quarto-title-block");
    if (showBreadCrumbs && titleBlockEl) {
      if (navigation.breadCrumbs && navigation.breadCrumbs.length > 1) {
        const titleBreadCrumbEl = makeBreadCrumbs(
          doc,
          ["quarto-title-breadcrumbs", "d-none", "d-lg-block"]
        );
        const bannerTitle = titleBlockEl.querySelector(
          ".quarto-title-banner .quarto-title"
        );
        if (bannerTitle !== null) {
          bannerTitle.prepend(titleBreadCrumbEl);
        } else {
          titleBlockEl.prepend(titleBreadCrumbEl);
        }
      }
    }
    markdownPipeline.processRenderedMarkdown(doc);
    const sidebar = sidebarForHref(href, format14);
    const sidebarHidden = format14.metadata[kSiteSidebar] === false;
    if (sidebar && !sidebarHidden) {
      doc.body.classList.add("nav-sidebar");
    }
    const sidebarEl = doc.body.getElementById("quarto-sidebar");
    if (sidebarEl?.classList.contains("floating")) {
      doc.body.classList.add("floating");
    } else if (sidebarEl?.classList.contains("docked")) {
      doc.body.classList.add("docked");
    }
    const headerEl = doc.body.querySelector(
      "#quarto-header.fixed-top nav.navbar"
    );
    if (headerEl) {
      doc.body.classList.add("nav-fixed");
    }
    const navLinks = doc.querySelectorAll("a.nav-link");
    for (let i6 = 0; i6 < navLinks.length; i6++) {
      const navLink = navLinks[i6];
      const navLinkHref = navLink.getAttribute("href");
      const sidebarLink = doc.querySelector(
        '.sidebar-navigation a[href="' + navLinkHref + '"]:not(.sidebar-logo-link)'
      );
      if (sidebarLink || navLinkHref === href) {
        navLink.classList.add("active");
        navLink.setAttribute("aria-current", "page");
        break;
      }
    }
    await resolveProjectInputLinks(source2, project, doc);
    handleRepoLinks(
      format14,
      doc,
      pathWithForwardSlashes(sourceRelative),
      language,
      project.config
    );
    const numberSections = websiteHtmlFormat(project).pandoc[kNumberSections] !== false;
    if (numberSections === false) {
      const sidebarItems = doc.querySelectorAll(
        ".sidebar-item .sidebar-item-text"
      );
      for (let i6 = 0; i6 < sidebarItems.length; i6++) {
        const sidebarItem = sidebarItems[i6];
        removeChapterNumber(sidebarItem);
      }
      const sels = [
        "h1.title",
        ".page-navigation .nav-page-next .nav-page-text",
        ".page-navigation .nav-page-previous .nav-page-text",
        "h1.quarto-secondary-nav-title",
        ".breadcrumb-item a"
      ];
      for (const sel of sels) {
        const nodes = doc.querySelectorAll(sel);
        if (nodes !== null) {
          for (const node of nodes) {
            removeChapterNumber(node);
          }
        }
      }
    }
    const projBackToTop = websiteConfigBoolean(
      kBackToTopNavigation,
      false,
      project.config
    );
    const formatBackToTop = format14.metadata[kBackToTopNavigation];
    if (projBackToTop && formatBackToTop !== false) {
      const contentEl = doc.querySelector("main");
      const backToTopEl = doc.createElement("a");
      backToTopEl.setAttribute(
        "onclick",
        "window.scrollTo(0, 0); return false;"
      );
      const backText = language[kBackToTop];
      const backIcon = "arrow-up";
      backToTopEl.setAttribute("role", "button");
      backToTopEl.innerHTML = `<i class='bi bi-${backIcon}'></i> ${backText}`;
      backToTopEl.id = "quarto-back-to-top";
      contentEl?.appendChild(backToTopEl);
    }
    return Promise.resolve(kHtmlEmptyPostProcessResult);
  };
}
function handleRepoLinks(format14, doc, source2, language, config2) {
  if (format14.metadata[kSiteRepoActions] === false) {
    return;
  }
  const forceRepoActions = format14.metadata[kSiteRepoActions] === true;
  const repoActions = websiteConfigActions(
    kSiteRepoActions,
    kWebsite,
    config2
  );
  const issueUrl = websiteConfigString(kSiteIssueUrl, config2);
  if (issueUrl && !repoActions.includes("issue")) {
    repoActions.push("issue");
  }
  const elRepoSource = doc.querySelector(
    "[" + kDataQuartoSourceUrl + '="repo"]'
  );
  if (repoActions.length > 0 || elRepoSource) {
    const repoInfo2 = websiteRepoInfo(format14, config2);
    if (repoInfo2 || issueUrl) {
      if (repoActions.length > 0) {
        const repoTargets = [];
        const tocRepoTarget = doc.querySelector(`nav[role="doc-toc"]`);
        if (tocRepoTarget) {
          repoTargets.push({ el: tocRepoTarget });
        }
        if (repoTargets.length === 0 && forceRepoActions) {
          const sidebarRepoTarget = doc.querySelector("#quarto-margin-sidebar");
          if (sidebarRepoTarget) {
            repoTargets.push({ el: sidebarRepoTarget });
          }
        }
        const footerRepoTarget = doc.querySelector(
          ".nav-footer .nav-footer-center"
        );
        if (footerRepoTarget) {
          repoTargets.push({
            el: footerRepoTarget,
            clz: repoTargets.length > 0 ? ["d-sm-block", "d-md-none"] : void 0
          });
        } else {
          const ensureEl = (doc2, tagname, classname, parent, afterEl) => {
            let el = parent.querySelector(`${tagname}.${classname}`);
            if (!el) {
              el = doc2.createElement(tagname);
              el.classList.add(classname);
              if (afterEl !== null && afterEl && afterEl.nextElementSibling) {
                parent.insertBefore(el, afterEl.nextElementSibling);
              } else {
                parent.appendChild(el);
              }
            }
            return el;
          };
          const footerEl = ensureEl(
            doc,
            "footer",
            "footer",
            doc.body,
            doc.querySelector("div#quarto-content")
          );
          const footerContainer = ensureEl(
            doc,
            "div",
            "nav-footer",
            footerEl
          );
          const footerCenterEl = ensureEl(
            doc,
            "div",
            "nav-footer-center",
            footerContainer,
            footerContainer.querySelector(".nav-footer-left")
          );
          repoTargets.push({
            el: footerCenterEl,
            clz: repoTargets.length > 0 ? ["d-sm-block", "d-md-none"] : void 0
          });
        }
        if (repoTargets.length > 0) {
          const linkTarget = websiteConfigString(kSiteRepoLinkTarget, config2);
          const linkRel = websiteConfigString(kSiteRepoLinkRel, config2);
          const links = repoInfo2 ? repoActionLinks(
            repoActions,
            repoInfo2,
            websiteRepoBranch(config2),
            source2,
            language,
            issueUrl
          ) : [{
            text: language[kRepoActionLinksIssue],
            url: issueUrl,
            icon: "chat-right"
          }];
          repoTargets.forEach((repoTarget) => {
            const actionsDiv = doc.createElement("div");
            actionsDiv.classList.add("toc-actions");
            const ulEl = doc.createElement("ul");
            links.forEach((link2) => {
              const a5 = doc.createElement("a");
              a5.setAttribute("href", link2.url);
              if (linkTarget) {
                a5.setAttribute("target", linkTarget);
              }
              if (linkRel) {
                a5.setAttribute("rel", linkRel);
              }
              a5.classList.add("toc-action");
              a5.innerHTML = link2.text;
              const i6 = doc.createElement("i");
              i6.classList.add("bi");
              if (link2.icon) {
                i6.classList.add(`bi-${link2.icon}`);
              } else {
                i6.classList.add(`empty`);
              }
              a5.prepend(i6);
              const liEl = doc.createElement("li");
              liEl.appendChild(a5);
              ulEl.appendChild(liEl);
            });
            actionsDiv.appendChild(ulEl);
            repoTarget.el.appendChild(actionsDiv);
            if (repoTarget.clz) {
              repoTarget.clz.forEach((cls) => {
                actionsDiv.classList.add(cls);
              });
            }
          });
        }
      }
      if (elRepoSource && repoInfo2) {
        elRepoSource.setAttribute(
          kDataQuartoSourceUrl,
          `${repoInfo2.baseUrl}blob/${websiteRepoBranch(config2)}/${repoInfo2.path}${source2}`
        );
      }
    } else {
      warnOnce(
        `Repository links require that you specify a ${kSiteRepoUrl}`
      );
    }
  }
}
function repoActionLinks(actions, repoInfo2, branch, source2, language, issueUrl) {
  const firstIcon = repoUrlIcon(repoInfo2.baseUrl);
  return actions.map((action, i6) => {
    switch (action) {
      case "edit":
        if (!isJupyterNotebook(source2)) {
          return {
            text: language[kRepoActionLinksEdit],
            url: `${repoInfo2.baseUrl}edit/${branch}/${repoInfo2.path}${source2}`,
            icon: i6 === 0 ? firstIcon : void 0
          };
        } else if (repoInfo2.baseUrl.indexOf("github.com") !== -1) {
          return {
            text: language[kRepoActionLinksEdit],
            url: `${repoInfo2.baseUrl.replace("github.com", "github.dev")}blob/${branch}/${repoInfo2.path}${source2}`,
            icon: i6 === 0 ? firstIcon : void 0
          };
        } else {
          return null;
        }
      case "source":
        return {
          text: language[kRepoActionLinksSource],
          url: `${repoInfo2.baseUrl}blob/${branch}/${repoInfo2.path}${source2}`,
          icon: i6 === 0 ? firstIcon : void 0
        };
      case "issue":
        return {
          text: language[kRepoActionLinksIssue],
          url: issueUrl || `${repoInfo2.baseUrl}issues/new`,
          icon: i6 === 0 ? firstIcon : void 0
        };
      default: {
        warnOnce(`Unknown repo action '${action}'`);
        return null;
      }
    }
  }).filter((action) => action !== null);
}
async function resolveFooter(project, footer) {
  const resolveItems = async (contents) => {
    if (Array.isArray(contents)) {
      const resolvedItems = [];
      for (let i6 = 0; i6 < contents.length; i6++) {
        const item = contents[i6];
        const navItem = await navigationItem(project, item);
        resolvedItems.push(navItem);
      }
      return resolvedItems;
    } else {
      return contents;
    }
  };
  if (footer) {
    footer.left = await resolveItems(footer.left);
    footer.center = await resolveItems(footer.center);
    footer.right = await resolveItems(footer.right);
  }
  return footer;
}
function makeBreadCrumbs(doc, clz) {
  const navEl = doc.createElement("nav");
  navEl.classList.add("quarto-page-breadcrumbs");
  if (clz && clz.length) {
    clz.forEach((cls) => {
      navEl.classList.add(cls);
    });
  }
  navEl.setAttribute("aria-label", "breadcrumb");
  const olEl = doc.createElement("ol");
  olEl.classList.add("breadcrumb");
  navEl.append(olEl);
  const breadCrumbEl = () => {
    const liEl = doc.createElement("li");
    liEl.classList.add("breadcrumb-item");
    return liEl;
  };
  if (navigation.breadCrumbs && navigation.breadCrumbs.length > 0) {
    for (const item of navigation.breadCrumbs) {
      if (item.text || item.icon) {
        const liEl = breadCrumbEl();
        const maybeLink = (liEl2, contents) => {
          if (item.href) {
            const linkEl = doc.createElement("a");
            linkEl.setAttribute("href", item.href);
            if (typeof contents === "string") {
              linkEl.innerHTML = contents;
            } else {
              linkEl.appendChild(contents);
            }
            liEl2.appendChild(linkEl);
            return liEl2;
          } else {
            if (typeof contents === "string") {
              liEl2.innerHTML = item.text || "";
            } else {
              liEl2.appendChild(contents);
            }
            return liEl2;
          }
        };
        if (item.text) {
          olEl.appendChild(
            maybeLink(
              liEl,
              item.text || ""
            )
          );
        } else if (item.icon) {
          const iconEl = doc.createElement("i");
          iconEl.classList.add("bi");
          iconEl.classList.add(`bi-${item.icon}`);
          olEl.appendChild(maybeLink(liEl, iconEl));
        }
      }
    }
  } else {
    const sidebarTitle2 = doc.querySelector(".sidebar-title a");
    if (sidebarTitle2) {
      const liEl = breadCrumbEl();
      liEl.innerHTML = sidebarTitle2.innerHTML;
      olEl.appendChild(liEl);
    } else {
      const sidebarTitleBare = doc.querySelector(".sidebar-title");
      if (sidebarTitleBare) {
        const liEl = breadCrumbEl();
        liEl.innerHTML = sidebarTitleBare.innerHTML;
        olEl.appendChild(liEl);
      } else {
        const title3 = doc.querySelector(
          "header .title .quarto-section-identifier"
        ) || doc.querySelector("header .title");
        if (title3) {
          const liEl = breadCrumbEl();
          liEl.innerHTML = title3.innerHTML;
          olEl.appendChild(liEl);
        }
      }
    }
  }
  return navEl;
}
async function sidebarsEjsData(project, sidebars) {
  const ejsSidebars = [];
  for (let i6 = 0; i6 < sidebars.length; i6++) {
    ejsSidebars.push(await sidebarEjsData(project, sidebars[i6]));
  }
  return ejsSidebars;
}
async function sidebarEjsData(project, sidebar) {
  sidebar = cloneDeep(sidebar);
  if (sidebar.title && !sidebar.id) {
    sidebar.id = asHtmlId(sidebar.title);
  }
  sidebar.title = await sidebarTitle(sidebar, project);
  const searchOpts = await searchOptions(project);
  sidebar.search = sidebar.search !== void 0 ? sidebar.search : searchOpts && searchOpts.location === "sidebar" ? searchOpts.type : false;
  sidebar[kCollapseLevel] = sidebar[kCollapseLevel] || 2;
  sidebar.alignment = sidebar.alignment || sidebar.align || "left";
  sidebar.pinned = sidebar.pinned !== void 0 ? !!sidebar.pinned : false;
  await resolveSidebarItems(project, sidebar);
  await resolveSidebarTools(project, sidebar.tools);
  return sidebar;
}
async function resolveSidebarItems(project, container) {
  if (!container.contents) {
    return;
  }
  const context = sidebarContext();
  container.contents = await expandAutoSidebarItems(
    project,
    container.contents || []
  );
  const items = container.contents;
  for (let i6 = 0; i6 < items.length; i6++) {
    let item = normalizeSidebarItem(project.dir, items[i6], context);
    if (Object.keys(item).includes("contents")) {
      const subItems = item.contents || [];
      if (item.href) {
        item = await resolveItem(project, item.href, item, true);
      }
      for (let i7 = 0; i7 < subItems.length; i7++) {
        subItems[i7] = await resolveSidebarItem(
          project,
          normalizeSidebarItem(project.dir, subItems[i7], context)
        );
      }
      items[i6] = item;
    } else {
      items[i6] = await resolveSidebarItem(
        project,
        item
      );
    }
  }
}
async function resolveSidebarItem(project, item) {
  if (item.href) {
    item = await resolveItem(
      project,
      item.href,
      item,
      true
    );
  }
  if (item.contents !== void 0) {
    await resolveSidebarItems(project, item);
    return item;
  } else {
    return item;
  }
}
async function resolveSidebarTools(project, tools) {
  if (tools) {
    for (let i6 = 0; i6 < tools.length; i6++) {
      if (Object.keys(tools[i6]).includes("menu")) {
        const items = tools[i6].menu || [];
        for (let i7 = 0; i7 < items.length; i7++) {
          const toolItem = await navigationItem(project, items[i7], 1);
          if (typeof toolItem === "object" && toolItem.href) {
            const tool = await resolveItem(
              project,
              toolItem.href,
              toolItem
            );
            validateTool(tool);
            items[i7] = tool;
          }
        }
      } else {
        const toolItem = tools[i6];
        resolveHrefAttribute(toolItem);
        if (toolItem.href) {
          tools[i6] = await resolveItem(
            project,
            toolItem.href,
            toolItem
          );
          validateTool(tools[i6]);
        }
      }
    }
  }
}
function validateTool(tool) {
  if (tool.icon === void 0 && tool.text === void 0) {
    warn("A sidebar tool is defined without text or an icon.");
  }
}
function sidebarStyle() {
  if (navigation.sidebars.length > 0) {
    return navigation.sidebars[0].style;
  } else {
    return void 0;
  }
}
function expandedSidebar(href, sidebar) {
  if (sidebar) {
    const resolveExpandedItems = (href2, items) => {
      for (let i6 = 0; i6 < items.length; i6++) {
        const item = items[i6];
        item.active = itemHasNavTarget(item, href2);
        if (Object.keys(item).includes("contents")) {
          if (resolveExpandedItems(href2, item.contents || []) || item.href === href2) {
            item.expanded = true;
            return true;
          }
        } else if (item.active) {
          return true;
        }
      }
      return false;
    };
    const expandedSidebar2 = cloneDeep(sidebar);
    resolveExpandedItems(href, expandedSidebar2.contents);
    return expandedSidebar2;
  }
}
function isSeparator(item) {
  return !!item && !!item.text?.match(/^\-\-\-[\-\s]*$/);
}
function nextAndPrevious(href, sidebar) {
  if (sidebar?.contents) {
    const sidebarItems = flattenItems(
      sidebar?.contents,
      (item) => {
        return item.href !== void 0 && !isExternalPath(item.href) || isSeparator(item);
      }
    );
    const sidebarItemsUniq = uniqBy(
      sidebarItems,
      (sidebarItem) => {
        return sidebarItem.href || Math.random().toString();
      }
    );
    const index2 = sidebarItemsUniq.findIndex((item) => item.href === href);
    const nextPage = index2 > -1 && index2 < sidebarItemsUniq.length - 1 && !isSeparator(sidebarItemsUniq[index2 + 1]) ? sidebarItemsUniq[index2 + 1] : void 0;
    const prevPage = index2 > -1 && index2 <= sidebarItemsUniq.length - 1 && !isSeparator(sidebarItemsUniq[index2 - 1]) ? sidebarItemsUniq[index2 - 1] : void 0;
    return {
      nextPage,
      prevPage
    };
  } else {
    return {};
  }
}
async function navbarEjsData(project, navbar) {
  const collapse = navbar.collapse !== void 0 ? !!navbar.collapse : true;
  const searchOpts = await searchOptions(project);
  const data3 = {
    ...navbar,
    search: navbar.search !== void 0 ? navbar.search : searchOpts && searchOpts.location === "navbar" ? searchOpts.type : false,
    background: navbar.background || "primary",
    logo: cloneDeep(navbar.logo),
    [kLogoAlt]: navbar[kLogoAlt],
    [kLogoHref]: navbar[kLogoHref],
    collapse,
    [kCollapseBelow]: !collapse ? "" : "-" + (navbar[kCollapseBelow] || "lg"),
    pinned: navbar.pinned !== void 0 ? !!navbar.pinned : false
  };
  if (!data3.title && data3.title !== false) {
    data3.title = websiteTitle(project.config);
  }
  data3.title = data3.title || "";
  const sidebarMenus = navbar[kSidebarMenus] !== false;
  if (navbar.left) {
    if (!Array.isArray(navbar.left)) {
      throw new Error("navbar 'left' must be an array of nav items");
    }
    data3.left = new Array();
    for (let i6 = 0; i6 < navbar.left.length; i6++) {
      data3.left.push(
        await navigationItem(project, navbar.left[i6], 0, sidebarMenus)
      );
    }
  }
  if (navbar.right) {
    if (!Array.isArray(navbar.right)) {
      throw new Error("navbar 'right' must be an array of nav items");
    }
    data3.right = new Array();
    for (let i6 = 0; i6 < navbar.right.length; i6++) {
      data3.right.push(
        await navigationItem(project, navbar.right[i6], 0, sidebarMenus)
      );
    }
  }
  if (navbar.tools) {
    await resolveSidebarTools(
      project,
      navbar.tools
    );
    data3.tools = navbar.tools;
  }
  return data3;
}
function resolveIcon(navItem) {
  navItem.icon = navItem.icon ? !navItem.icon.startsWith("bi-") ? `bi-${navItem.icon}` : navItem.icon : navItem.icon;
}
function resolveSidebarRef(navItem) {
  const ref3 = navItem.href || navItem.text;
  if (ref3) {
    const id = sidebarTargetId(ref3);
    if (id) {
      const sidebar = navigation.sidebars.find(sidebarHasId(id));
      if (sidebar) {
        navItem.href = void 0;
        navItem.text = sidebar.title || id;
        navItem.menu = new Array();
        for (const item of sidebar.contents) {
          if (item.text && item.contents) {
            if (navItem.menu.length > 0) {
              navItem.menu.push({
                text: "---"
              });
            }
            navItem.menu.push({
              text: item.text
            });
            for (const subItem of item.contents) {
              const targetItem = subItem.contents?.length ? !subItem.contents[0].contents ? subItem.contents[0] : void 0 : subItem;
              if (targetItem?.href) {
                navItem.menu.push({
                  text: subItem.text,
                  href: targetItem.href
                });
              }
            }
          } else if (item.href) {
            navItem.menu.push({
              text: item.text,
              href: item.href
            });
          }
        }
      }
    }
  }
}
async function navigationItem(project, navItem, level = 0, sidebarMenus = false) {
  navItem = cloneDeep(navItem);
  if (typeof navItem === "string") {
    const navItemPath = join4(project.dir, navItem);
    if (safeExistsSync(navItemPath) && Deno.statSync(navItemPath).isFile) {
      navItem = { href: navItem };
    } else {
      navItem = { text: navItem };
    }
  }
  resolveIcon(navItem);
  resolveHrefAttribute(navItem);
  if (level === 0 && sidebarMenus) {
    resolveSidebarRef(navItem);
  }
  if (navItem.href) {
    return await resolveItem(project, navItem.href, navItem);
  } else if (navItem.menu) {
    if (level > 0) {
      throw Error(
        `"${navItem.text || ""}" menu: this menu does not support sub-menus`
      );
    }
    for (let i6 = 0; i6 < navItem.menu.length; i6++) {
      navItem.menu[i6] = await navigationItem(
        project,
        navItem.menu[i6],
        level + 1,
        false
      );
    }
    return {
      ...navItem,
      id: uniqueMenuId(navItem),
      text: navItem.text || ""
    };
  } else {
    return navItem;
  }
}
var menuIds = /* @__PURE__ */ new Map();
function resetMenuIds() {
  menuIds.clear();
}
function uniqueMenuId(navItem) {
  const id = asHtmlId(navItem.text || navItem.icon || "");
  const number2 = menuIds.get(id) || 0;
  menuIds.set(id, number2 + 1);
  return `nav-menu-${id}${number2 ? "-" + number2 : ""}`;
}
async function resolveItem(project, href, item, number2 = false) {
  if (!isExternalPath(href)) {
    const resolved = await resolveInputTarget(
      project,
      pathWithForwardSlashes(href)
    );
    if (resolved) {
      const inputItem = {
        ...item,
        href: resolved.outputHref,
        text: item.text || resolved.title || basename4(resolved.outputHref),
        draft: resolved.draft
      };
      const projType = projectType(project.config?.project?.[kProjectType]);
      if (projType.navItemText) {
        const navItemFormatted = await projType.navItemText(
          project,
          href,
          inputItem.text,
          number2
        );
        inputItem.text = navItemFormatted.html;
        inputItem.plainText = navItemFormatted.text;
      }
      return inputItem;
    } else if (looksLikeShortCode(href)) {
      return item;
    } else {
      return {
        ...item,
        href: !href.startsWith("/") ? "/" + href : href
      };
    }
  } else {
    if (!item.text && !item.icon) {
      item.text = item.href;
    }
    return item;
  }
}
function looksLikeShortCode(href) {
  return href.startsWith("{{<") && href.endsWith(">}}");
}
async function sidebarTitle(sidebar, project) {
  const { navbar } = await websiteNavigationConfig(project);
  if (sidebar.title) {
    return sidebar.title;
  } else if (!sidebar.logo) {
    if (!navbar) {
      return websiteTitle(project.config);
    } else {
      return void 0;
    }
  } else {
    return void 0;
  }
}
async function websiteHeadroom(project) {
  const { navbar, sidebars } = await websiteNavigationConfig(project);
  if (navbar || sidebars?.length) {
    const navbarPinned = navbar?.pinned === true;
    const anySidebarPinned = sidebars && sidebars.some((sidebar) => sidebar.pinned === true);
    return !navbarPinned && !anySidebarPinned;
  } else {
    return false;
  }
}
var kDependencyName2 = "quarto-nav";
function websiteNavigationSassBundle() {
  const scssPath = navigationDependency("quarto-nav.scss").path;
  const navSassLayer = sassLayer(scssPath);
  return {
    dependency: kBootstrapDependencyName,
    key: scssPath,
    quarto: {
      ...navSassLayer,
      name: "quarto-nav.css"
    }
  };
}
async function websiteNavigationDependency(project) {
  const scripts = [navigationDependency("quarto-nav.js")];
  if (await websiteHeadroom(project)) {
    scripts.push(navigationDependency("headroom.min.js"));
  }
  return {
    name: kDependencyName2,
    scripts
  };
}
function navigationDependency(resource) {
  return {
    name: basename4(resource),
    path: resourcePath(`projects/website/navigation/${resource}`)
  };
}
function resolveNavReferences(collection) {
  if (!collection) {
    return collection;
  }
  forEach(
    collection,
    (value, index2, collection2) => {
      const assign3 = (value2) => {
        if (typeof index2 === "number") {
          collection2[index2] = value2;
        } else if (typeof index2 === "string") {
          collection2[index2] = value2;
        }
      };
      if (Array.isArray(value)) {
        assign3(resolveNavReferences(value));
      } else if (typeof value === "object") {
        assign3(resolveNavReferences(value));
      } else if (typeof value === "string") {
        const navRef = resolveNavReference(value);
        if (navRef) {
          const navItem = collection2;
          navItem["href"] = navRef.href;
          navItem["text"] = navRef.text;
        }
      }
    }
  );
  return collection;
}
function resolveNavReference(href) {
  const id = sidebarTargetId(href);
  if (id) {
    const sidebar = navigation.sidebars.find(sidebarHasId(id));
    if (sidebar && sidebar.contents?.length) {
      const item = findFirstItem(sidebar.contents[0]);
      if (item) {
        return {
          href: item.href,
          text: sidebar.title || id
        };
      }
    }
  }
  return void 0;
}
function sidebarTargetId(href) {
  if (href) {
    const match = href.match(/^sidebar:([^\s]+).*$/);
    if (match) {
      return match[1];
    } else {
      return void 0;
    }
  } else {
    return void 0;
  }
}
function sidebarHasId(id) {
  return (sidebar) => {
    return sidebar.id === id;
  };
}
function findFirstItem(item) {
  if (item.contents?.length) {
    return findFirstItem(item.contents[0]);
  } else if (item.href) {
    return item;
  } else {
    return void 0;
  }
}

// project/types/website/website-sitemap.ts
init_fs();
init_path();

// https://deno.land/x/xmlp@v0.2.8/context.ts
var QName = class {
  _qName;
  _prefix;
  _localPart;
  constructor(qName) {
    this._qName = qName;
    const i6 = qName.indexOf(":");
    const q2 = i6 < 0 ? ["", qName] : qName.split(":");
    this._prefix = q2[0];
    this._localPart = q2[1];
  }
  get qName() {
    return this._qName;
  }
  get prefix() {
    return this._prefix;
  }
  get localPart() {
    return this._localPart;
  }
};
var Attribute = class extends QName {
  uri;
  value = "";
  constructor(qName) {
    super(qName);
    if (qName === "xmlns") {
      this._prefix = "xmlns";
      this._localPart = "";
    }
  }
};
var Element9 = class extends QName {
  _attributes = [];
  _parent;
  uri;
  emptyElement = false;
  constructor(name2, parent) {
    super(name2);
    this._parent = parent;
  }
  get parent() {
    return this._parent;
  }
  newAttribute(qName) {
    const attribute = new Attribute(qName);
    this._attributes.push(attribute);
  }
  peekAttribute() {
    const i6 = this._attributes.length - 1;
    if (i6 < 0) {
      return void 0;
    }
    return this._attributes[i6];
  }
  get attributes() {
    return this._attributes;
  }
  get prefixMappings() {
    const filterd = this._attributes.filter((attr) => attr.prefix === "xmlns");
    return filterd.map((attr) => ({ ns: attr.localPart, uri: attr.value }));
  }
};
var AttributeInfo = class extends QName {
  _attribute;
  constructor(attribute) {
    super(attribute.qName);
    if (attribute.qName === "xmlns") {
      this._prefix = "xmlns";
      this._localPart = "";
    }
    this._attribute = attribute;
  }
  get uri() {
    return this._attribute.uri;
  }
  get value() {
    return this._attribute.value;
  }
};
var ElementInfo = class _ElementInfo extends QName {
  _element;
  constructor(element) {
    super(element.qName);
    this._element = element;
  }
  get uri() {
    return this._element.uri;
  }
  get parent() {
    const parent = this._element.parent;
    if (parent) {
      return new _ElementInfo(parent);
    }
    return void 0;
  }
  get attributes() {
    return this._element.attributes.map((attribute) => {
      return new AttributeInfo(attribute);
    });
  }
  get emptyElement() {
    return this._element.emptyElement;
  }
};
var XMLParseContext = class {
  _locator;
  _memento = "";
  _elementStack = [];
  _namespaces = {};
  quote = "";
  state = "BEFORE_DOCUMENT";
  constructor(locator) {
    this._locator = locator;
  }
  get position() {
    return this._locator?.position || { line: -1, column: -1 };
  }
  appendMemento(value) {
    this._memento += value;
  }
  clearMemento() {
    this._memento = "";
  }
  get memento() {
    return this._memento;
  }
  newElement(qName) {
    const parent = this.peekElement();
    this._elementStack.push(new Element9(qName, parent));
  }
  peekElement() {
    return this._elementStack[this._elementStack.length - 1];
  }
  popElement() {
    const element = this._elementStack.pop();
    element?.prefixMappings.forEach(({ ns }) => {
      this._namespaces[ns] = void 0;
    });
    return element;
  }
  get elementLength() {
    return this._elementStack.length;
  }
  registerNamespace(ns, uri) {
    this._namespaces[ns] = uri;
  }
  getNamespaceURI(ns) {
    return this._namespaces[ns];
  }
};
var XMLParseError = class extends Error {
  _position;
  constructor(message, cx) {
    super(message);
    this._position = cx.position;
  }
  /** line number on XML source */
  get line() {
    return this._position.line;
  }
  /** column number on XML source */
  get column() {
    return this._position.column;
  }
};

// https://deno.land/x/xmlp@v0.2.8/handler.ts
var NAME_HEAD = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/;
var NAME_BODY = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/;
function isWhitespace3(c6) {
  return c6 === " " || c6 === "\n" || c6 === "\r" || c6 === "	";
}
function isQuote(c6) {
  return c6 === '"' || c6 === "'";
}
function resolveEntity(text) {
  let result2 = text;
  [
    { reg: /&amp;/g, ch: "&" },
    { reg: /&gt;/g, ch: ">" },
    { reg: /&lt;/g, ch: "<" },
    { reg: /&quot;/g, ch: '"' },
    { reg: /&apos;/g, ch: "'" }
  ].forEach(({ reg, ch }) => {
    result2 = result2.replace(reg, ch);
  });
  return result2;
}
function handleBeforeDocument(cx, c6) {
  if (c6 === "<") {
    cx.state = "FOUND_LT";
  } else {
    if (!isWhitespace3(c6)) {
      throw new XMLParseError("Non-whitespace before document.", cx);
    }
  }
  return [];
}
function handleGeneralStuff(cx, c6) {
  if (c6 === "<") {
    cx.state = "FOUND_LT";
  } else {
    cx.appendMemento(c6);
  }
  return [];
}
function handleFoundLT(cx, c6) {
  let events = [];
  const text = resolveEntity(cx.memento).trim();
  cx.clearMemento();
  if (text) {
    events = [["text", text, new ElementInfo(cx.peekElement()), false]];
  }
  if (!isWhitespace3(c6)) {
    if (c6 === "?") {
      cx.state = "PROC_INST";
    } else if (c6 === "!") {
      cx.state = "SGML_DECL";
    } else if (NAME_HEAD.test(c6)) {
      cx.appendMemento(c6);
      cx.state = "START_TAG";
    } else if (c6 === "/") {
      cx.state = "END_TAG";
    } else {
      throw new XMLParseError("Unencoded <", cx);
    }
  }
  return events;
}
function handleProcInst(cx, c6) {
  if (c6 === "?") {
    cx.state = "PROC_INST_ENDING";
  } else {
    cx.appendMemento(c6);
  }
  return [];
}
function handleProcInstEnding(cx, c6) {
  let events = [];
  if (c6 === ">") {
    events = [["processing_instruction", cx.memento]];
    cx.clearMemento();
    cx.state = cx.elementLength > 0 ? "GENERAL_STUFF" : "BEFORE_DOCUMENT";
  } else {
    cx.appendMemento(`?${c6}`);
    cx.state = "PROC_INST";
  }
  return events;
}
function handleSgmlDecl(cx, c6) {
  let events = [];
  const sgmlCmd = `${cx.memento}${c6}`.toUpperCase();
  if (sgmlCmd === "[CDATA[") {
    cx.clearMemento();
    cx.state = "CDATA";
  } else if (sgmlCmd === "--") {
    cx.clearMemento();
    cx.state = "COMMENT";
  } else if (sgmlCmd === "DOCTYPE") {
    if (cx.elementLength > 0) {
      throw new XMLParseError("Inappropriately located doctype declaration", cx);
    }
    cx.clearMemento();
    cx.state = "DOCTYPE";
  } else if (c6 === ">") {
    events = [["sgml_declaration", cx.memento]];
    cx.clearMemento();
    cx.state = cx.elementLength > 0 ? "GENERAL_STUFF" : "BEFORE_DOCUMENT";
  } else {
    cx.appendMemento(c6);
  }
  return events;
}
function handleCdata(cx, c6) {
  if (c6 === "]") {
    cx.state = "CDATA_ENDING";
  } else {
    cx.appendMemento(c6);
  }
  return [];
}
function handleCdataEnding(cx, c6) {
  if (c6 === "]") {
    cx.state = "CDATA_ENDING_2";
  } else {
    cx.appendMemento(`]${c6}`);
    cx.state = "CDATA";
  }
  return [];
}
function handleCdataEnding2(cx, c6) {
  let events = [];
  if (c6 === ">") {
    if (cx.memento) {
      events = [["text", cx.memento, new ElementInfo(cx.peekElement()), true]];
      cx.clearMemento();
    }
    cx.state = "GENERAL_STUFF";
  } else if (c6 === "]") {
    cx.appendMemento("]");
  } else {
    cx.appendMemento(`]]${c6}`);
    cx.state = "CDATA";
  }
  return events;
}
function handleComment(cx, c6) {
  if (c6 === "-") {
    cx.state = "COMMENT_ENDING";
  } else {
    cx.appendMemento(c6);
  }
  return [];
}
function handleCommentEnding(cx, c6) {
  if (c6 === "-") {
    cx.state = "COMMENT_ENDING_2";
  } else {
    cx.appendMemento(`-${c6}`);
    cx.state = "COMMENT";
  }
  return [];
}
function handleCommentEnding2(cx, c6) {
  let events = [];
  if (c6 === ">") {
    const comment = cx.memento;
    if (comment) {
      events = [["comment", comment]];
    }
    cx.clearMemento();
    cx.state = "GENERAL_STUFF";
  } else {
    cx.appendMemento(`--${c6}`);
    cx.state = "COMMENT";
  }
  return events;
}
function handleDoctype(cx, c6) {
  let events = [];
  if (c6 === ">") {
    events = [["doctype", cx.memento]];
    cx.clearMemento();
    cx.state = "BEFORE_DOCUMENT";
  } else {
    cx.appendMemento(c6);
  }
  return events;
}
function emitStartElement(cx) {
  const events = [];
  if (cx.elementLength === 1) {
    events.push(["start_document"]);
  }
  const element = cx.peekElement();
  for (const { ns, uri } of element.prefixMappings) {
    cx.registerNamespace(ns, uri);
    events.push(["start_prefix_mapping", ns, uri]);
  }
  element.uri = cx.getNamespaceURI(element.prefix);
  for (const attribute of element.attributes) {
    attribute.uri = cx.getNamespaceURI(attribute.prefix);
  }
  events.push(["start_element", new ElementInfo(element)]);
  return events;
}
function handleStartTag(cx, c6) {
  let events = [];
  if (NAME_BODY.test(c6)) {
    cx.appendMemento(c6);
  } else {
    cx.newElement(cx.memento);
    cx.clearMemento();
    if (c6 === ">") {
      events = emitStartElement(cx);
      cx.state = "GENERAL_STUFF";
    } else if (c6 === "/") {
      cx.state = "EMPTY_ELEMENT_TAG";
    } else {
      if (!isWhitespace3(c6)) {
        throw new XMLParseError("Invalid character in element name", cx);
      }
      cx.state = "START_TAG_STUFF";
    }
  }
  return events;
}
function handleStartTagStuff(cx, c6) {
  let events = [];
  if (!isWhitespace3(c6)) {
    if (c6 === ">") {
      events = emitStartElement(cx);
      cx.state = "GENERAL_STUFF";
    } else if (c6 === "/") {
      cx.state = "EMPTY_ELEMENT_TAG";
    } else if (NAME_HEAD.test(c6)) {
      cx.appendMemento(c6);
      cx.state = "ATTRIBUTE_NAME";
    } else {
      throw new XMLParseError("Invalid attribute name", cx);
    }
  }
  return events;
}
function emitEndElement(cx, qName) {
  let events = [];
  const element = cx.popElement();
  if (element.qName !== qName) {
    throw new XMLParseError(`Illegal element structure, ${element.qName} & ${qName}`, cx);
  }
  events = [["end_element", new ElementInfo(element)]];
  for (const { ns, uri } of element.prefixMappings) {
    events.push(["end_prefix_mapping", ns, uri]);
  }
  return events;
}
function handleEmptyElementTag(cx, c6) {
  let events = [];
  if (c6 !== ">") {
    throw new XMLParseError("Forward-slash in start-tag not followed by &gt", cx);
  }
  const element = cx.peekElement();
  element.emptyElement = true;
  events = emitStartElement(cx).concat(emitEndElement(cx, element.qName));
  cx.state = "GENERAL_STUFF";
  return events;
}
function newAttribute(cx) {
  const qName = cx.memento;
  cx.clearMemento();
  cx.peekElement().newAttribute(qName);
  cx.state = "ATTRIBUTE_EQUAL";
}
function handleAttributeName(cx, c6) {
  if (NAME_BODY.test(c6)) {
    cx.appendMemento(c6);
  } else if (isWhitespace3(c6)) {
    cx.state = "ATTRIBUTE_NAME_SAW_WHITE";
  } else if (c6 === "=") {
    newAttribute(cx);
  } else {
    throw new XMLParseError(c6 === ">" ? "Attribute without value" : "Invalid attribute name", cx);
  }
  return [];
}
function handleAttributeNameSawWhite(cx, c6) {
  if (c6 === "=") {
    newAttribute(cx);
  } else if (!isWhitespace3(c6)) {
    throw new XMLParseError("Attribute without value", cx);
  }
  return [];
}
function handleAttributeEqual(cx, c6) {
  if (!isWhitespace3(c6)) {
    if (isQuote(c6)) {
      cx.quote = c6;
      cx.state = "ATTRIBUTE_VALUE_START";
    } else {
      throw new XMLParseError("Unquoted attribute value", cx);
    }
  }
  return [];
}
function handleAttributeValueStart(cx, c6) {
  if (c6 === cx.quote) {
    const value = cx.memento;
    cx.clearMemento();
    cx.peekElement().peekAttribute().value = resolveEntity(value);
    cx.quote = "";
    cx.state = "ATTRIBUTE_VALUE_END";
  } else {
    cx.appendMemento(c6);
  }
  return [];
}
function handleAttributeValueEnd(cx, c6) {
  let events = [];
  if (isWhitespace3(c6)) {
    cx.state = "START_TAG_STUFF";
  } else if (c6 === "/") {
    cx.state = "EMPTY_ELEMENT_TAG";
  } else if (c6 === ">") {
    events = emitStartElement(cx);
    cx.state = "GENERAL_STUFF";
  } else {
    throw new XMLParseError("Invalid attribute name", cx);
  }
  return events;
}
function closeElement(cx) {
  const events = emitEndElement(cx, cx.memento);
  cx.clearMemento();
  if (cx.elementLength === 0) {
    events.push(["end_document"]);
    cx.state = "AFTER_DOCUMENT";
  } else {
    cx.state = "GENERAL_STUFF";
  }
  return events;
}
function handleEndTag(cx, c6) {
  let events = [];
  if (NAME_BODY.test(c6)) {
    cx.appendMemento(c6);
  } else if (c6 === ">") {
    events = closeElement(cx);
  } else if (isWhitespace3(c6)) {
    cx.state = "END_TAG_SAW_WHITE";
  } else {
    throw new XMLParseError("Invalid element name", cx);
  }
  return events;
}
function handleEndTagSawWhite(cx, c6) {
  let events = [];
  if (c6 === ">") {
    events = closeElement(cx);
  } else if (!isWhitespace3(c6)) {
    throw new XMLParseError("Invalid characters in end-tag", cx);
  }
  return events;
}
function handleAfterDocument(cx, c6) {
  if (!isWhitespace3(c6)) {
    throw new XMLParseError("Non-whitespace after document.", cx);
  }
  return [];
}

// https://deno.land/x/xmlp@v0.2.8/parser.ts
var ParserBase = class {
  _cx = new XMLParseContext(this);
  _handlers = {};
  _chunk = "";
  _index = -1;
  _position = { line: 1, column: 0 };
  /*
          The basic logic of this XML parser was obtained by reading the source code of sax-js.
          Thanks & see: https://github.com/isaacs/sax-js
  
          STATE                     XML
          ------------------------  ------------------
          BEFORE_DOCUMENT
          GENERAL_STUFF
          FOUND_LT                  <
          PROC_INST                 <?
          PROC_INST_ENDING          <? proc ?
          SGML_DECL                 <!
          CDATA                     <![CDATA[
          CDATA_ENDING              <![CDATA[ cdata ]
          CDATA_ENDING_2            <![CDATA[ cdata ]]
          COMMENT                   <!--
          COMMENT_ENDING            <!-- comment -
          COMMENT_ENDING_2          <!-- comment --
          DOCTYPE                   <!DOCTYPE
          START_TAG                 <element
          START_TAG_STUFF           <element%20
          EMPTY_ELEMENT_TAG         <element/
          ATTRIBUTE_NAME            <element a
          ATTRIBUTE_NAME_SAW_WHITE  <element a%20
          ATTRIBUTE_EQUAL           <element a=
          ATTRIBUTE_VALUE_START     <element a="
          ATTRIBUTE_VALUE_END       <element a="value"
          END_TAG                   </element
          END_TAG_SAW_WHITE         </element%20
          AFTER_DOCUMENT
      */
  constructor() {
    this.appendHandler("BEFORE_DOCUMENT", handleBeforeDocument);
    this.appendHandler("GENERAL_STUFF", handleGeneralStuff);
    this.appendHandler("FOUND_LT", handleFoundLT);
    this.appendHandler("PROC_INST", handleProcInst);
    this.appendHandler("PROC_INST_ENDING", handleProcInstEnding);
    this.appendHandler("SGML_DECL", handleSgmlDecl);
    this.appendHandler("CDATA", handleCdata);
    this.appendHandler("CDATA_ENDING", handleCdataEnding);
    this.appendHandler("CDATA_ENDING_2", handleCdataEnding2);
    this.appendHandler("COMMENT", handleComment);
    this.appendHandler("COMMENT_ENDING", handleCommentEnding);
    this.appendHandler("COMMENT_ENDING_2", handleCommentEnding2);
    this.appendHandler("DOCTYPE", handleDoctype);
    this.appendHandler("START_TAG", handleStartTag);
    this.appendHandler("START_TAG_STUFF", handleStartTagStuff);
    this.appendHandler("EMPTY_ELEMENT_TAG", handleEmptyElementTag);
    this.appendHandler("ATTRIBUTE_NAME", handleAttributeName);
    this.appendHandler("ATTRIBUTE_NAME_SAW_WHITE", handleAttributeNameSawWhite);
    this.appendHandler("ATTRIBUTE_EQUAL", handleAttributeEqual);
    this.appendHandler("ATTRIBUTE_VALUE_START", handleAttributeValueStart);
    this.appendHandler("ATTRIBUTE_VALUE_END", handleAttributeValueEnd);
    this.appendHandler("END_TAG", handleEndTag);
    this.appendHandler("END_TAG_SAW_WHITE", handleEndTagSawWhite);
    this.appendHandler("AFTER_DOCUMENT", handleAfterDocument);
  }
  get cx() {
    return this._cx;
  }
  appendHandler(state2, handler) {
    this._handlers[state2] = handler;
    return this;
  }
  get handlers() {
    return this._handlers;
  }
  set chunk(chunk) {
    this._chunk = chunk;
    this._index = -1;
  }
  hasNext() {
    return this._index < this._chunk.length - 1;
  }
  readNext() {
    this._index += 1;
    const c6 = this._chunk[this._index];
    if (c6 === "\n") {
      this._position.line += 1;
      this._position.column = 0;
    } else {
      this._position.column += 1;
    }
    return c6;
  }
  get position() {
    return this._position;
  }
};
var SAXParser = class extends ParserBase {
  // deno-lint-ignore no-explicit-any
  _listeners = {};
  _controller;
  fireListeners(event) {
    const [name2, ...args] = event;
    const list = this._listeners[name2] || [];
    for (const listener of list) {
      listener.call(this, ...args);
    }
  }
  run() {
    try {
      while (this.hasNext()) {
        const state2 = this.cx.state;
        const handler = this.handlers[state2];
        if (!handler) {
          throw new Error(`Handler for ${state2} not found`);
        }
        const events = handler(this.cx, this.readNext());
        for (const event of events) {
          this.fireListeners(event);
        }
      }
    } catch (e5) {
      if (e5 instanceof XMLParseError) {
        this.fireListeners(["error", e5]);
        this._controller?.error(e5);
      } else {
        throw e5;
      }
    }
  }
  /**
   * implements UnderlyingSink<Uint8Array>
   * @param chunk XML data chunk
   * @param controller error reporter, Deno writable stream uses internal.
   */
  write(chunk, controller) {
    try {
      this._controller = controller;
      this.chunk = new TextDecoder().decode(chunk);
      this.run();
    } finally {
      this._controller = void 0;
    }
  }
  /**
   * Convenient function.
   */
  getStream() {
    return new WritableStream(this);
  }
  /**
   * Convenient function. {@code SAXParser#getStream} is used internally.
   */
  getWriter() {
    const streamWriter = this.getStream().getWriter();
    return {
      async write(p5) {
        await streamWriter.ready;
        await streamWriter.write(p5);
        return p5.length;
      }
    };
  }
  /**
   * Execute XML pull parsing.
   * @param source Target XML.
   */
  async parse(source2) {
    if (typeof source2 === "string") {
      this.chunk = source2;
      this.run();
    } else if (source2 instanceof Uint8Array) {
      this.write(source2);
    } else {
      await Deno.copy(source2, this.getWriter());
    }
  }
  on(event, listener) {
    const list = this._listeners[event] || [];
    list.push(listener);
    this._listeners[event] = list;
    return this;
  }
};

// project/types/website/website-sitemap.ts
init_lodash();
await init_project_shared();
init_path2();
init_resources2();
init_copy5();
async function updateSitemap(context, outputFiles, incremental) {
  const outputDir = projectOutputDir(context);
  const filteredOutputFiles = [];
  for (const outputFile5 of outputFiles) {
    if (basename4(outputFile5.file) === "index.html") {
      const index2 = await inputTargetIndexForOutputFile(
        context,
        relative4(outputDir, outputFile5.file)
      );
      if (index2 && inputTargetIsEmpty(index2)) {
        continue;
      }
    }
    filteredOutputFiles.push(outputFile5);
  }
  outputFiles = filteredOutputFiles;
  const robotsTxtPath = join4(context.dir, "robots.txt");
  const srcRobotsTxt = existsSync2(robotsTxtPath) ? robotsTxtPath : void 0;
  const destRobotsTxt = join4(outputDir, "robots.txt");
  if (srcRobotsTxt && destRobotsTxt !== srcRobotsTxt) {
    if (existsSync2(destRobotsTxt)) {
      safeRemoveSync(destRobotsTxt);
    }
    copyTo(srcRobotsTxt, destRobotsTxt);
  }
  const baseUrlConfig = websiteBaseurl(context.config);
  const sitemapPath = join4(outputDir, "sitemap.xml");
  if (typeof baseUrlConfig === "string") {
    let baseUrl = baseUrlConfig;
    if (!baseUrl.endsWith("/")) {
      baseUrl += "/";
    }
    const fileLoc = (file) => baseUrl + pathWithForwardSlashes(relative4(outputDir, file));
    const fileLastMod = (file) => (Deno.statSync(file).mtime || /* @__PURE__ */ new Date(0)).toISOString();
    const inputModified = async (output, project) => {
      const inputFile = await inputFileForOutputFile(project, output);
      if (inputFile) {
        return fileLastMod(inputFile.file);
      } else {
        return fileLastMod(output);
      }
    };
    const isDraft = async (outputFile5) => {
      const index2 = await resolveInputTargetForOutputFile(
        context,
        relative4(outputDir, outputFile5.file)
      );
      return index2 ? index2.draft : void 0;
    };
    const urlsetEntry = async (outputFile5) => {
      const file = outputFile5.file;
      return {
        loc: fileLoc(file),
        lastmod: await inputModified(file, context),
        draft: await isDraft(outputFile5)
      };
    };
    const draftMode = projectDraftMode(context);
    if (!incremental || !existsSync2(sitemapPath)) {
      const urlset = [];
      for (const file of outputFiles) {
        urlset.push(await urlsetEntry(file));
      }
      writeSitemap(sitemapPath, urlset, draftMode);
    } else {
      const urlSet = await readSitemap(sitemapPath);
      for (const outputFile5 of outputFiles) {
        const file = outputFile5.file;
        const loc = fileLoc(file);
        const url = urlSet.find((url2) => url2.loc === loc);
        if (url) {
          url.lastmod = await inputModified(file, context);
          url.draft = await isDraft(outputFile5);
        } else {
          urlSet.push(await urlsetEntry(outputFile5));
        }
      }
      writeSitemap(sitemapPath, urlSet, draftMode);
    }
    if (!srcRobotsTxt) {
      const robotsTxt = `Sitemap: ${baseUrl}sitemap.xml
`;
      if (!existsSync2(destRobotsTxt) || Deno.readTextFileSync(destRobotsTxt) !== robotsTxt) {
        Deno.writeTextFileSync(destRobotsTxt, robotsTxt);
      }
    }
  } else {
    removeIfExists(sitemapPath);
  }
}
async function readSitemap(sitemapPath) {
  const urlset = new Array();
  const parser = new SAXParser();
  let loc;
  let lastmod;
  parser.on("text", (text, element) => {
    if (element.qName === "loc") {
      loc = text;
    } else if (element.qName == "lastmod") {
      lastmod = text;
    }
  });
  parser.on("end_element", (element) => {
    if (element.qName === "url" && loc && lastmod) {
      urlset.push({ loc, lastmod });
    }
  });
  const reader = await Deno.open(sitemapPath);
  await parser.parse(reader);
  reader.close();
  return urlset;
}
function writeSitemap(sitemapPath, urlset, draftMode) {
  const nonDraftUrls = urlset.filter(
    (url) => !url.draft || isDraftVisible(draftMode)
  );
  const escapedUrls = nonDraftUrls.map((url) => {
    url.loc = escape(url.loc);
    return url;
  });
  const sitemap = renderEjs(
    resourcePath(
      join4("projects", "website", "templates", "sitemap.ejs.xml")
    ),
    { urlset: escapedUrls }
  );
  Deno.writeTextFileSync(sitemapPath, sitemap);
}

// project/types/website/website.ts
init_website_constants();

// project/types/website/website-aliases.ts
init_fs();
init_path();
await init_project_shared();
init_resources2();
init_log();
var kAliases = "aliases";
async function updateAliases(context, outputFiles, incremental) {
  const redirectMap = {};
  const allOutputFiles = [];
  const outputDir = projectOutputDir(context);
  for (const outputFile5 of outputFiles) {
    const aliases = outputFile5.format.metadata[kAliases];
    if (aliases && Array.isArray(aliases)) {
      addRedirectsToMap(aliases, outputFile5.file, outputDir, true, redirectMap);
    }
  }
  if (Object.keys(redirectMap).length > 0) {
    for (const file of context.files.input) {
      const relativePath = relative4(context.dir, file);
      const inputIndexEntry = await inputTargetIndex(
        context,
        relativePath
      );
      if (inputIndexEntry) {
        const format14 = Object.values(inputIndexEntry.formats)[0];
        const outputTarget = await resolveInputTarget(
          context,
          relativePath,
          false
        );
        if (outputTarget) {
          const projOutputDir = projectOutputDir(context);
          allOutputFiles.push(
            join4(
              projOutputDir,
              outputTarget.outputHref
            )
          );
          if (incremental) {
            const aliases = format14.metadata[kAliases];
            if (aliases && Array.isArray(aliases)) {
              addRedirectsToMap(
                aliases,
                join4(outputDir, outputTarget.outputHref),
                outputDir,
                false,
                redirectMap
              );
            }
          }
        }
      }
    }
  }
  for (const targetFile of Object.keys(redirectMap)) {
    const targetHrefs = redirectMap[targetFile];
    const redirects = {};
    for (const targetHref of targetHrefs) {
      const aliasHref = relative4(dirname4(targetFile), targetHref.outputFile);
      redirects[targetHref.hash || ""] = aliasHref;
    }
    if (!existsSync2(targetFile)) {
      ensureDirSync(dirname4(targetFile));
    }
    if (allOutputFiles.find((outputFile5) => outputFile5 === targetFile)) {
      for (const offendingAlias of targetHrefs.filter(
        (targetHref) => targetHref.href === relative4(dirname4(targetHref.outputFile), targetFile)
      )) {
        warn(
          `Requested alias ${targetFile} -> ${offendingAlias.outputFile} would overwrite the target. Skipping.`
        );
      }
    } else {
      writeMultipleRedirectPage(targetFile, redirects);
    }
  }
}
function addRedirectsToMap(aliases, outputFile5, outputDir, allowNewAnchors, anchorMap) {
  for (const alias of aliases) {
    const anchor = toAnchor(alias, outputFile5);
    const aliasTarget = anchor.href.startsWith("/") ? join4(outputDir, anchor.href.slice(1)) : join4(dirname4(outputFile5), anchor.href);
    if (allowNewAnchors && !anchorMap[aliasTarget]) {
      anchorMap[aliasTarget] = [];
    }
    if (anchorMap[aliasTarget]) {
      anchorMap[aliasTarget].push(anchor);
    }
  }
}
function toAnchor(url, outputFile5) {
  const fixupHref = (href) => {
    if (href.endsWith("/")) {
      return `${href}index.html`;
    } else if (extname4(href) === "") {
      return `${href}/index.html`;
    } else {
      return href;
    }
  };
  if (url.includes("#")) {
    const anchorParts = url.split("#");
    return {
      href: fixupHref(anchorParts[0]),
      outputFile: outputFile5,
      hash: anchorParts[1]
    };
  } else {
    return {
      href: fixupHref(url),
      outputFile: outputFile5
    };
  }
}
function writeMultipleRedirectPage(path3, redirects) {
  const redirectTemplate = resourcePath(
    "projects/website/templates/redirect-map.ejs"
  );
  const redirectHtml = renderEjs(redirectTemplate, {
    redirects
  });
  Deno.writeTextFileSync(path3, redirectHtml);
}

// project/types/website/website-meta.ts
init_path();
init_constants6();
init_types5();
init_config2();
init_website_constants();
init_http();

// core/image.ts
init_fs();
init_path();
init_png();
function imageSize(path3) {
  if (path3 !== void 0) {
    if (path3.endsWith(".png")) {
      if (existsSync2(path3)) {
        const imageData = Deno.readFileSync(path3);
        try {
          const png = new PngImage(imageData);
          return {
            height: png.height,
            width: png.width
          };
        } catch (error2) {
          if (!(error2 instanceof Error)) throw error2;
          throw new Error(`Error reading file ${path3}
${error2.message}`);
        }
      }
    }
  }
}
function imageContentType(path3) {
  const ext = extname4(path3);
  return kimageTypes[ext];
}
var kimageTypes = {
  ".apng": "image/apng",
  ".avif": "image/avif",
  ".gif": "image/gif",
  ".jpg": "image/jpeg",
  ".jpeg": "image/jpeg",
  ".jfif": "image/jpeg",
  ".pjpeg": "image/jpeg",
  ".pjp": "image/jpeg",
  ".png": "image/png",
  ".svg": "image/svg+xml",
  ".webp": "image/webp"
};

// project/types/website/website-meta.ts
init_format_html_shared();
init_url();
init_text2();
var kCard = "card";
function metadataHtmlDependencies(source2, project, format14, extras) {
  const pipeline2 = metaMarkdownPipeline(format14, extras);
  return {
    [kHtmlPostprocessors]: metadataHtmlPostProcessor(
      source2,
      project,
      format14,
      extras,
      pipeline2
    ),
    [kMarkdownAfterBody]: pipeline2.markdownAfterBody()
  };
}
function metadataHtmlPostProcessor(source2, project, format14, extras, pipeline2) {
  return (doc) => {
    const pageMeta = pageMetadata(format14, extras);
    const openGraphMetadataProvider = {
      key: kOpenGraph,
      prefix: "og",
      metadata: {
        ...pageMeta,
        ...opengraphMetadata(format14)
      },
      filter: (key) => {
        if ([kImageHeight, kImageWidth, kImageAlt].includes(key)) {
          return key.replace("-", ":");
        }
        if (key === kSiteName) {
          return "site_name";
        }
        return key;
      },
      resolveValue: (key, value) => {
        if ([kDescription].includes(key)) {
          return truncateText(value.trim(), 200, "punctuation");
        }
        return value;
      }
    };
    const twitterMetadataProvider = {
      key: kTwitterCard,
      prefix: "twitter",
      metadata: {
        ...pageMeta,
        ...twitterMetadata(format14)
      },
      filter: (key) => {
        if (key === kCardStyle) {
          return kCard;
        }
        if ([kImageAlt].includes(key)) {
          return key.replace("-", ":");
        }
        return key;
      },
      resolveValue: (key, value) => {
        if ([kDescription].includes(key)) {
          return truncateText(value.trim(), 200, "punctuation");
        }
        return value;
      },
      resolveDefaults: (finalMetadata) => {
        if (finalMetadata[kCardStyle] === void 0) {
          finalMetadata[kCardStyle] = finalMetadata[kImage] ? "summary_large_image" : "summary";
        }
      }
    };
    const resources = [];
    [
      openGraphMetadataProvider,
      twitterMetadataProvider
    ].forEach((provider) => {
      const metadata = provider.metadata;
      const siteMeta = format14.metadata[kWebsite];
      if (!format14.metadata[provider.key] && (!siteMeta || !siteMeta[provider.key])) {
        return;
      }
      if (metadata[kTitle] === void 0) {
        return;
      }
      if (metadata[kImage] === void 0 && format14.metadata[kImage] !== false) {
        const previewImg = findPreviewImg(doc) || websiteImage(project.config);
        metadata[kImage] = previewImg ? previewImg.src : void 0;
        metadata[kImageAlt] = previewImg ? previewImg.alt : void 0;
      }
      if (metadata[kDescription] === void 0) {
        metadata[kDescription] = findDescription(doc);
      }
      const imagePath = resolveImageMetadata(source2, project, format14, metadata);
      if (imagePath) {
        if (imagePath.startsWith("/")) {
          const absPath = join4(project.dir, imagePath);
          resources.push(relative4(dirname4(source2), absPath));
        } else {
          resources.push(imagePath);
        }
      }
      if (provider.resolveDefaults) {
        provider.resolveDefaults(metadata);
      }
      Object.keys(metadata).forEach((key) => {
        if (metadata[key] !== void 0) {
          const data3 = metadata[key];
          const value = provider.resolveValue ? provider.resolveValue(key, data3) : data3;
          if (provider.filter) {
            key = provider.filter(key);
          }
          writeMetaTag(`${provider.prefix}:${key}`, value, doc);
        }
      });
    });
    pipeline2.processRenderedMarkdown(doc);
    return Promise.resolve({
      resources,
      supporting: []
    });
  };
}
function opengraphMetadata(format14) {
  const metadata = {};
  const openGraph = mergedSiteAndDocumentData(kOpenGraph, format14);
  const siteMeta = format14.metadata[kWebsite];
  if (siteMeta && siteMeta[kTitle]) {
    metadata[kSiteName] = siteMeta[kTitle];
  }
  if (openGraph && typeof openGraph === "object") {
    [
      kTitle,
      kDescription,
      kImage,
      kImageAlt,
      kImageHeight,
      kImageWidth,
      kLocale,
      kSiteName
    ].forEach((key) => {
      if (openGraph[key] !== void 0) {
        metadata[key] = openGraph[key];
      }
    });
  }
  return metadata;
}
function twitterMetadata(format14) {
  const metadata = {};
  const twitterData = mergedSiteAndDocumentData(kTwitterCard, format14);
  if (twitterData && typeof twitterData === "object") {
    [
      kTitle,
      kDescription,
      kImage,
      kImageAlt,
      kCreator,
      kTwitterSite,
      kCardStyle
    ].forEach(
      (key) => {
        if (twitterData[key] !== void 0) {
          metadata[key] = twitterData[key];
        }
      }
    );
  }
  return metadata;
}
function pageMetadata(format14, extras) {
  const pageTitle = computePageTitle(format14, extras);
  const pageDescription = format14.metadata[kDescription];
  const pageImage = format14.metadata[kImage] ? format14.metadata[kImage] : void 0;
  return {
    [kTitle]: pageTitle,
    [kDescription]: pageDescription || format14.metadata[kAbstract] || format14.metadata[kSubtitle],
    [kImage]: pageImage
  };
}
function resolveImageMetadata(source2, project, format14, metadata) {
  const siteMeta = format14.metadata[kWebsite];
  if (metadata[kImage] && siteMeta && siteMeta[kSiteUrl] !== void 0) {
    const inputRelImg = metadata[kImage];
    const imgMeta = imageMetadata(
      metadata[kImage],
      siteMeta[kSiteUrl],
      source2,
      project
    );
    metadata[kImage] = imgMeta.href;
    metadata[kImageHeight] = imgMeta.height;
    metadata[kImageWidth] = imgMeta.width;
    const altText = format14.metadata[kImageAlt];
    if (altText && !metadata[kImageAlt]) {
      metadata[kImageAlt] = altText;
    }
    return inputRelImg;
  }
}
function mergedSiteAndDocumentData(key, format14) {
  const siteData = format14.metadata[kWebsite];
  const siteMetadata = siteData && siteData[key] !== void 0 ? siteData[key] : false;
  const docMetadata = format14.metadata[key] !== void 0 ? format14.metadata[key] : false;
  if (typeof siteMetadata === "object" && format14.metadata[kImage]) {
    const siteMeta = siteMetadata;
    siteMeta[kImage] = format14.metadata[kImage];
  }
  if (typeof siteMetadata === "object" && typeof docMetadata === "object") {
    return mergeConfigs(
      siteMetadata,
      docMetadata
    );
  } else if (docMetadata !== false) {
    return docMetadata;
  } else if (siteMetadata !== false) {
    return siteMetadata;
  } else {
    return false;
  }
}
function imageMetadata(image2, baseUrl, source2, context) {
  if (isAbsoluteRef(image2)) {
    return {
      href: image2
    };
  } else if (image2.startsWith("/")) {
    const imagePath = join4(context.dir, image2.slice(1));
    const size = imageSize(imagePath);
    return {
      path: image2,
      href: `${baseUrl}${image2}`,
      height: size?.height,
      width: size?.width
    };
  } else {
    const sourceRelative = relative4(context.dir, source2);
    const imageProjectRelative = join4(
      dirname4(sourceRelative),
      image2
    );
    const imagePath = join4(context.dir, imageProjectRelative);
    const size = imageSize(imagePath);
    return {
      path: imageProjectRelative,
      href: joinUrl(baseUrl, imageProjectRelative),
      height: size?.height,
      width: size?.width
    };
  }
}
var kMetaTitleId = "quarto-metatitle";
var kTwitterTitle = "quarto-twittercardtitle";
var kTwitterDesc = "quarto-twittercarddesc";
var kOgTitle = "quarto-ogcardtitle";
var kOgDesc = "quarto-ogcardddesc";
var kMetaSideNameId = "quarto-metasitename";
var kMetaSiteDescId = "quarto-metasitedesc";
function metaMarkdownPipeline(format14, extras) {
  const resolvedTitle = computePageTitle(format14);
  const titleMetaHandler = {
    getUnrendered() {
      const inlines = {};
      if (resolvedTitle !== void 0) {
        inlines[kMetaTitleId] = resolvedTitle;
      }
      const twitterMeta = twitterMetadata(format14);
      inlines[kTwitterTitle] = twitterMeta.title || resolvedTitle || "";
      const ogMeta = opengraphMetadata(format14);
      inlines[kOgTitle] = ogMeta.title || resolvedTitle || "";
      return { inlines };
    },
    processRendered(rendered, doc) {
      const renderedEl = rendered[kMetaTitleId];
      if (renderedEl) {
        const el = doc.querySelector(
          `head title`
        );
        if (el && el.innerText === resolvedTitle) {
          if (format14.pandoc[kNumberSections] === false) {
            const numberEl = renderedEl.querySelector("span.chapter-number");
            if (numberEl) {
              numberEl.remove();
            }
            const collapsed = renderedEl.innerText.replaceAll(/\s+/g, " ");
            el.innerHTML = collapsed;
          } else {
            el.innerHTML = renderedEl.innerText;
          }
        }
      }
      [{
        key: kOgTitle,
        sel: 'meta[property="og:title"]'
      }, {
        key: kTwitterTitle,
        sel: 'meta[name="twitter:title"]'
      }].forEach(
        (obj) => {
          const renderedObjEl = rendered[obj.key];
          if (renderedObjEl) {
            const metaEl = doc.querySelector(obj.sel);
            if (metaEl) {
              metaEl.setAttribute("content", renderedObjEl.innerText);
            }
          }
        }
      );
    }
  };
  const siteTitleMetaHandler = {
    getUnrendered() {
      const siteMeta = format14.metadata[kWebsite];
      if (siteMeta && siteMeta[kTitle]) {
        return { inlines: { [kMetaSideNameId]: siteMeta[kTitle] } };
      }
    },
    processRendered(rendered, doc) {
      const renderedEl = rendered[kMetaSideNameId];
      if (renderedEl) {
        const siteMeta = format14.metadata[kWebsite];
        if (siteMeta) {
          siteMeta[kTitle] = renderedEl.innerText;
        }
        const el = doc.querySelector(
          `meta[property="og:site_name"]`
        );
        if (el) {
          el.setAttribute("content", renderedEl.innerText);
        }
      }
    }
  };
  const descriptionMetaHandler = {
    getUnrendered() {
      const inlines = {};
      const pageMeta = pageMetadata(format14, extras);
      const siteMeta = format14.metadata[kWebsite];
      const pageDesc = pageMeta.description;
      const siteDesc = siteMeta.description;
      const description = pageDesc || siteDesc;
      const twitterMeta = twitterMetadata(format14);
      inlines[kTwitterDesc] = twitterMeta.description || description || "";
      const ogMeta = opengraphMetadata(format14);
      inlines[kOgDesc] = ogMeta.description || description || "";
      return { inlines };
    },
    processRendered(rendered, doc) {
      const metaVals = [{
        sel: 'meta[property="og:description"]',
        key: kOgDesc
      }, { sel: 'meta[name="twitter:description"]', key: kTwitterDesc }];
      metaVals.forEach((metaVal) => {
        const renderedEl = rendered[metaVal.key];
        if (renderedEl) {
          const metaEl = doc.querySelector(metaVal.sel);
          if (metaEl) {
            metaEl.setAttribute("content", renderedEl.innerText);
          }
        }
      });
    }
  };
  const siteDescriptionHandler = {
    getUnrendered() {
      const siteMeta = format14.metadata[kWebsite];
      if (siteMeta && siteMeta[kDescription]) {
        return {
          inlines: { [kMetaSiteDescId]: siteMeta[kDescription] }
        };
      }
    },
    processRendered(rendered) {
      const renderedEl = rendered[kMetaSiteDescId];
      if (renderedEl) {
        const siteMeta = format14.metadata[kWebsite];
        if (siteMeta) {
          siteMeta[kDescription] = renderedEl.innerText;
        }
      }
    }
  };
  return createMarkdownPipeline("quarto-meta-markdown", [
    titleMetaHandler,
    siteTitleMetaHandler,
    descriptionMetaHandler,
    siteDescriptionHandler
  ]);
}

// project/types/website/website-resources.ts
init_html();
init_project_resources();
await init_project_shared();
init_path();
init_path2();
function htmlResourceResolverPostprocessor(source2, project, pathResolver) {
  const sourceRelative = relative4(project.dir, source2);
  const offset3 = projectOffset(project, source2);
  const href = inputFileHref(sourceRelative);
  return (doc) => {
    const forceRoot = href === "/404.html" ? websitePath(project.config) : null;
    const resolver = pathResolver ? pathResolver : (href2, projectOffset2) => {
      return pathWithForwardSlashes(join4(projectOffset2, href2));
    };
    const refs = resolveResourceRefs(
      doc,
      offset3,
      forceRoot,
      pathResolver || resolver
    );
    return Promise.resolve({ resources: refs, supporting: [] });
  };
}
function resolveResourceRefs(doc, projectOffset2, forceRoot, resolvePath) {
  const refs = [];
  Object.keys(kHtmlResourceTags).forEach((tag) => {
    for (const attrib of kHtmlResourceTags[tag]) {
      refs.push(
        ...resolveTag(doc, projectOffset2, tag, attrib, forceRoot, resolvePath).map((ref3) => ref3.replace(/\/$/, "/index.html"))
      );
    }
  });
  const styles = doc.querySelectorAll("style");
  for (let i6 = 0; i6 < styles.length; i6++) {
    const style = styles[i6];
    if (style.innerHTML) {
      style.innerHTML = fixupCssReferences2(
        style.innerHTML,
        projectOffset2 + "/",
        (ref3) => {
          ref3 = resolvePath(ref3, projectOffset2);
          refs.push(ref3);
          return ref3;
        }
      );
    }
  }
  return refs;
}
function resolveTag(doc, projectOffset2, tag, attrib, forceRoot, resolvePath) {
  const refs = [];
  processFileResourceRefs(doc, tag, attrib, (tag2, href) => {
    if (forceRoot) {
      if (!href.startsWith("/")) {
        tag2.setAttribute(attrib, forceRoot + href);
      } else if (!href.startsWith(forceRoot)) {
        tag2.setAttribute(attrib, forceRoot + href.slice(1));
      }
    } else if (href.startsWith("/") && !href.startsWith("//")) {
      href = resolvePath(projectOffset2 + href, projectOffset2);
      tag2.setAttribute(attrib, href);
    } else {
      href = resolvePath(href, projectOffset2);
      tag2.setAttribute(attrib, href);
    }
    refs.push(href);
  });
  return refs;
}

// project/types/website/website.ts
init_project_default();

// project/types/website/listing/website-listing.ts
init_path();
init_fs();
init_types5();
init_resources2();
init_constants6();
init_sass();
init_format_html_shared();

// project/types/website/listing/website-listing-template.ts
init_lodash();
init_constants6();
init_resources2();

// config/localization.ts
function localizedString(format14, key, options) {
  if (options) {
    let formattedStr = format14.language[key];
    for (let i6 = 0; i6 < options.length; i6++) {
      const option = options[i6];
      formattedStr = formattedStr.replace(`{${i6}}`, option);
    }
    return formattedStr;
  } else {
    return format14.language[key];
  }
}

// project/types/website/listing/website-listing-template.ts
init_text2();
init_html();

// project/types/website/listing/website-listing-read.ts
init_log();
init_path();
init_lodash();
init_fs();
init_path2();
init_constants6();
init_http();
init_yaml();
await init_project_shared();
init_config2();
init_path();
init_url();
init_error2();
init_format5();
var kDefaultListingType = "default" /* Default */;
var kDefaultContentsGlobToken = "B3049D40";
var kDefaultContentsGlob = [kDefaultContentsGlobToken];
var kDefaultId = "listing";
var kDefaultTableFields = [
  kFieldDate,
  kFieldTitle,
  kFieldAuthor
];
var kDefaultGridFields = [
  kFieldTitle,
  kFieldAuthor,
  kFieldDate,
  kFieldImage,
  kFieldDescription
];
var kDefaultFields = [
  kFieldDate,
  kFieldTitle,
  kFieldAuthor,
  kFieldSubtitle,
  kFieldImage,
  kFieldDescription
];
var defaultFieldDisplayNames = (format14) => {
  return {
    [kFieldImage]: " ",
    [kFieldDate]: format14.language[kListingPageFieldDate] || "",
    [kFieldTitle]: format14.language[kListingPageFieldTitle] || "",
    [kFieldDescription]: format14.language[kListingPageFieldDescription] || "",
    [kFieldAuthor]: format14.language[kListingPageFieldAuthor] || "",
    [kFieldFileName]: format14.language[kListingPageFieldFileName] || "",
    [kFieldDateModified]: format14.language[kListingPageFieldFileModified] || "",
    [kFieldFileModified]: format14.language[kListingPageFieldFileModified] || "",
    [kFieldSubtitle]: format14.language[kListingPageFieldSubtitle] || "",
    [kFieldReadingTime]: format14.language[kListingPageFieldReadingTime] || "",
    [kFieldWordCount]: format14.language[kListingPageFieldWordCount] || "",
    [kFieldCategories]: format14.language[kListingPageFieldCategories] || ""
  };
};
var kDefaultFieldTypes = {
  [kFieldDate]: "date",
  [kFieldFileModified]: "date",
  [kFieldDateModified]: "date",
  [kFieldReadingTime]: "minutes",
  [kFieldWordCount]: "number"
};
var kDefaultFieldLinks = [kFieldTitle, kFieldFileName];
var kDefaultFieldSort = [
  kFieldTitle,
  kFieldDate,
  kFieldAuthor,
  kFieldFileName,
  kFieldFileModified
];
var kDefaultFieldRequired = [];
async function readListings(source2, project, format14) {
  const listingItems = [];
  const listings = readDehydratedListings(source2, format14);
  const firstListingValue = (key, defaultValue) => {
    for (const listing of listings) {
      const value = listing[key];
      if (value !== void 0) {
        return value;
      }
    }
    return defaultValue;
  };
  const categories = firstListingValue(kFieldCategories, false);
  const parseCategoryStyle = (categories2) => {
    if (typeof categories2 === "string") {
      switch (categories2) {
        case "unnumbered":
          return "category-unnumbered";
        case "cloud":
          return "category-cloud";
        default:
        case "default":
          return "category-default";
      }
    } else {
      return "category-default";
    }
  };
  const categoryStyle = parseCategoryStyle(categories);
  const sharedOptions = {
    [kFieldCategories]: !!categories,
    [kCategoryStyle]: categoryStyle
  };
  const feed = firstListingValue(kFeed, void 0);
  if (feed !== void 0) {
    if (typeof feed === "object") {
      sharedOptions[kFeed] = feed;
    } else if (feed) {
      sharedOptions[kFeed] = {
        type: "full"
      };
    }
  }
  for (const listing of listings) {
    const { items, sources } = await readContents(source2, project, listing);
    const listingHydrated = hydrateListing(
      format14,
      listing,
      items,
      sources,
      sharedOptions
    );
    const sortedAndFiltered = (listing2, items2) => {
      if (listing2.sort && listing2.sort.length > 0) {
        return orderBy(
          items2,
          listing2.sort.map((l6) => {
            return (item) => {
              const value = item[l6.field];
              if (value === void 0 && l6.field === kFieldOrder) {
                if (l6.direction === "asc") {
                  return Number.MAX_SAFE_INTEGER;
                } else {
                  return 0;
                }
              } else {
                return value;
              }
            };
          }),
          listing2.sort.map((l6) => l6.direction)
        );
      } else {
        return items2;
      }
    };
    const orderedItems = sortedAndFiltered(listingHydrated, items);
    listingItems.push({
      listing: listingHydrated,
      items: orderedItems
    });
  }
  return { listingDescriptors: listingItems, options: sharedOptions };
}
function completeListingItems(context, outputFiles, _incremental) {
  debug(`[listing] Completing listing items for ${outputFiles.length} files`);
  const options = {
    remove: { links: true, images: true }
  };
  debug(`[listing] Creating content reader`);
  const contentReader = renderedContentReader(context, options);
  outputFiles.forEach((outputFile5) => {
    debug(`[listing] Completing listing items ${outputFile5.input}`);
    if (outputFile5.format.metadata[kListing] && isHtmlOutput(outputFile5.format.pandoc, true)) {
      let fileContents = Deno.readTextFileSync(outputFile5.file);
      const listings = readDehydratedListings(
        outputFile5.file,
        outputFile5.format
      );
      const listingDefaultImage = {};
      listings.forEach((listing) => {
        debug(`[listing] Processing listing ${listing.id}`);
        listingDefaultImage[`${listing.id}`] = listing[kImagePlaceholder] !== void 0 ? listing[kImagePlaceholder] : void 0;
      });
      const regex = descriptionPlaceholderRegex;
      regex.lastIndex = 0;
      let match = regex.exec(fileContents);
      while (match) {
        debug(`[listing] Processing description match`);
        const maxDescLength = parseInt(match[1]);
        const relativePath = match[2];
        const absolutePath = join4(projectOutputDir(context), relativePath);
        const placeholder2 = descriptionPlaceholder(
          relativePath,
          maxDescLength
        );
        if (existsSync2(absolutePath)) {
          const options2 = maxDescLength > 0 ? { "max-length": maxDescLength } : {};
          const contents = contentReader(absolutePath, options2);
          fileContents = fileContents.replace(
            placeholder2,
            contents.firstPara || ""
          );
        } else {
          fileContents = fileContents.replace(
            placeholder2,
            ""
          );
          warn(
            `Unable to read listing item description from ${relativePath}`
          );
        }
        match = regex.exec(fileContents);
      }
      regex.lastIndex = 0;
      const imgRegex = imagePlaceholderRegex;
      imgRegex.lastIndex = 0;
      let imgMatch = imgRegex.exec(fileContents);
      while (imgMatch) {
        debug(`[listing] Processing image match`);
        const progressive = imgMatch[1] === "true";
        const imgHeight = imgMatch[2];
        const lazy = imgMatch[3] !== "false";
        const listingId = imgMatch[4];
        const docRelativePath = imgMatch[5];
        const docAbsPath = join4(projectOutputDir(context), docRelativePath);
        const imgPlaceholder = imagePlaceholder(
          listingId,
          docRelativePath,
          progressive,
          imgHeight,
          lazy
        );
        debug(`[listing] ${docAbsPath}`);
        debug(`[listing] ${imgPlaceholder}`);
        if (existsSync2(docAbsPath)) {
          debug(`[listing] exists: ${docAbsPath}`);
          const contents = contentReader(docAbsPath, {
            remove: { links: true }
          });
          if (contents.previewImage) {
            debug(`[listing] previewImage: ${docAbsPath}`);
            const resolveUrl = (path3) => {
              if (isHttpUrl(path3)) {
                return path3;
              } else {
                const imgAbsPath = isAbsolute4(path3) ? path3 : join4(dirname4(docAbsPath), path3);
                const imgRelPath = relative4(
                  dirname4(outputFile5.file),
                  imgAbsPath
                );
                return imgRelPath;
              }
            };
            const imgHtml = imageSrc(
              {
                ...contents.previewImage,
                src: resolveUrl(contents.previewImage.src)
              },
              progressive,
              imgHeight,
              lazy
            );
            debug(`[listing] replacing: ${docAbsPath}`);
            fileContents = fileContents.replace(
              imgPlaceholder,
              imgHtml
            );
          } else if (
            // Use the default image if any
            listingDefaultImage[listingId] !== void 0
          ) {
            debug(`[listing] using default image for ${docAbsPath}`);
            debug(`[listing] from listing id ${listingId}`);
            debug(`[listing] image used is ${listingDefaultImage[listingId]}`);
            const imagePreview = {
              src: listingDefaultImage[listingId]
            };
            fileContents = fileContents.replace(
              imgPlaceholder,
              imageSrc(imagePreview, progressive, imgHeight, lazy)
            );
          } else {
            debug(`[listing] using empty div: ${docAbsPath}`);
            fileContents = fileContents.replace(
              imgPlaceholder,
              emptyDiv(imgHeight)
            );
          }
        } else {
          debug(`[listing] does not exist: ${docAbsPath}`);
          fileContents = fileContents.replace(
            imgPlaceholder,
            emptyDiv(imgHeight)
          );
          warn(
            `Unable to read listing preview image from ${docRelativePath}`
          );
        }
        imgMatch = imgRegex.exec(fileContents);
      }
      imgRegex.lastIndex = 0;
      Deno.writeTextFileSync(
        outputFile5.file,
        fileContents
      );
    }
  });
}
function emptyDiv(height) {
  return `<div class="listing-item-img-placeholder card-img-top" ${height ? `style="height: ${height};"` : ""}>&nbsp;</div>`;
}
function descriptionPlaceholder(file, maxLength) {
  return file ? `<!-- desc(5A0113B34292)[max=${maxLength}]:${file} -->` : "";
}
function imagePlaceholder(id, file, progressive, height, lazy) {
  return file ? `<!-- img(9CEB782EFEE6)[progressive=${progressive ? "true" : "false"}, height=${height ? height : ""}, lazy=${lazy === false ? "false" : "true"}]:${id}:${file} -->` : "";
}
function isPlaceHolder(text) {
  return text.match(descriptionPlaceholderRegex);
}
var descriptionPlaceholderRegex = /<!-- desc\(5A0113B34292\)\[max\=(.*)\]:(.*) -->/;
var imagePlaceholderRegex = /<!-- img\(9CEB782EFEE6\)\[progressive\=(.*), height\=(.*), lazy\=(.*)\]:(.*):(.*) -->/;
function hydrateListing(format14, listing, items, sources, options) {
  const fieldsForItems = (items2) => {
    const unionedItem = items2.reduce((prev, current3) => {
      const item = { ...prev };
      for (const key of Object.keys(current3)) {
        if (current3[key] !== void 0) {
          item[key] = current3[key];
        }
      }
      return item;
    }, {});
    return Object.keys(unionedItem).filter((key) => {
      return unionedItem[key] !== void 0;
    });
  };
  const itemFields = fieldsForItems(items);
  const suggestFields = (type4, itemFields2) => {
    if (sources.size === 1 && sources.has("rawfile" /* rawfile */)) {
      return [kFieldFileName, kFieldFileModified];
    } else if (!sources.has("document" /* document */) && !sources.has("metadata-document" /* metadataDocument */)) {
      const undisplayable = ["path"];
      return itemFields2.filter((field) => {
        return !undisplayable.includes(field);
      });
    } else {
      return defaultFields(type4, itemFields2);
    }
  };
  const suggestedFields = suggestFields(listing.type, itemFields);
  const fields = suggestedFields.filter((field) => {
    if (field === kFieldImage) {
      return true;
    }
    return itemFields.includes(field);
  });
  const finalFields = fields.length > 0 ? fields : itemFields;
  const defaultSort = listing.type !== "custom" /* Custom */ && listing.type !== "table" /* Table */ ? kDefaultFieldSort : suggestedFields;
  const defaultLinks = listing.type === "table" /* Table */ ? kDefaultFieldLinks : [];
  const defaultPageSize = () => {
    switch (listing.type) {
      case "table" /* Table */:
        return 30;
      case "grid" /* Grid */:
        return 18;
      default:
      case "default" /* Default */:
        return 25;
    }
  };
  const hydratedFields = [...finalFields];
  if (options[kFieldCategories] && (listing.type === "grid" /* Grid */ || listing.type === "default" /* Default */)) {
    if (!hydratedFields.includes(kFieldCategories)) {
      hydratedFields.push(kFieldCategories);
    }
  }
  const listingHydrated = cloneDeep({
    fields: hydratedFields,
    [kFieldDisplayNames]: {},
    // default values are merged later
    [kFieldTypes]: {},
    // default values are merged later
    [kFieldLinks]: defaultLinks,
    [kFieldSort]: defaultSort,
    [kFieldFilter]: hydratedFields,
    [kFieldRequired]: kDefaultFieldRequired,
    [kPageSize]: defaultPageSize(),
    [kFilterUi]: listing[kFilterUi] !== void 0 ? listing[kFilterUi] : listing.type === "table" /* Table */,
    [kSortUi]: listing[kSortUi] !== void 0 ? listing[kSortUi] : listing.type === "table" /* Table */,
    ...listing
  });
  const sort = hydratedFields.includes(kFieldTitle) ? [
    { field: kFieldOrder, direction: "asc" },
    { field: kFieldTitle, direction: "asc" }
  ] : void 0;
  if (sort && !listingHydrated.sort && (sources.has("document" /* document */) || sources.has("metadata-document" /* metadataDocument */))) {
    listingHydrated.sort = sort;
  }
  const sortUi = listingHydrated[kSortUi];
  if (sortUi && Array.isArray(sortUi)) {
    listingHydrated[kFieldSort] = sortUi;
  }
  const filterUi = listingHydrated[kFilterUi];
  if (filterUi && Array.isArray(filterUi)) {
    listingHydrated[kFieldFilter] = filterUi;
  }
  if (listing.type === "grid" /* Grid */) {
    listingHydrated[kGridColumns] = listingHydrated[kGridColumns] || 3;
    listingHydrated[kImageHeight2] = listingHydrated[kImageHeight2] || "150px";
    listingHydrated[kMaxDescLength] = listingHydrated[kMaxDescLength] || kDefaultMaxDescLength;
  } else if (listing.type === "default" /* Default */) {
    listingHydrated[kImageAlign] = listingHydrated[kImageAlign] || "right";
  } else if (listing.type === "table" /* Table */) {
    listingHydrated[kImageHeight2] = listingHydrated[kImageHeight2] || "40px";
    listingHydrated[kTableStriped] = listingHydrated[kTableStriped] !== void 0 ? listingHydrated[kTableStriped] : false;
    listingHydrated[kTableHover] = listingHydrated[kTableHover] !== void 0 ? listingHydrated[kTableHover] : false;
  }
  listingHydrated[kFieldTypes] = {
    ...kDefaultFieldTypes,
    ...listing[kFieldTypes]
  };
  listingHydrated[kFieldDisplayNames] = {
    ...defaultFieldDisplayNames(format14),
    ...listing[kFieldDisplayNames]
  };
  return listingHydrated;
}
async function readContents(source2, project, listing) {
  debug(`[listing] Reading listing '${listing.id}' from ${source2}`);
  debug(`[listing] Contents: ${listing.contents.map((lst) => {
    return typeof lst === "string" ? lst : "<yaml>";
  }).join(",")}`);
  const listingItems = [];
  const listingItemSources = /* @__PURE__ */ new Set();
  const inputsWithoutSource = project.files.input.filter(
    (file) => file !== source2
  );
  const filterListingFiles = (globOrPaths) => {
    const hasDefaultGlob = globOrPaths.some((glob) => {
      return glob === kDefaultContentsGlobToken;
    });
    const resolvedGlobs = globOrPaths.map((glob) => {
      if (glob === kDefaultContentsGlobToken) {
        return "*";
      } else {
        return glob;
      }
    });
    const expandedGlobs = resolvedGlobs.map((resolved) => {
      return expandGlob2(source2, project, resolved);
    });
    const hasInputs = expandedGlobs.some((expanded) => {
      return !!expanded.inputs;
    });
    const finalGlobs = expandedGlobs.map((expanded) => {
      return expanded.glob;
    });
    const outDir = project.config?.project["output-dir"];
    if (outDir) {
      finalGlobs.push(`!/${outDir}/**`);
    }
    if (hasInputs || hasDefaultGlob) {
      const filtered2 = filterPaths(
        dirname4(source2),
        inputsWithoutSource,
        finalGlobs
      );
      for (const glob of finalGlobs) {
        if (safeExistsSync(glob) && Deno.statSync(glob).isFile) {
          filtered2.include.push(
            isAbsolute4(glob) ? glob : join4(Deno.cwd(), glob)
          );
        }
      }
      return filtered2;
    } else {
      return resolvePathGlobs(
        dirname4(source2),
        finalGlobs,
        ["_*", ".*", "**/_*", "**/.*", source2]
      );
    }
  };
  const contentGlobs = listing.contents.filter((content) => {
    return typeof content === "string";
  });
  const contentMetadatas = listing.contents.filter((content) => {
    return typeof content !== "string";
  });
  if (contentGlobs.length > 0) {
    const files = filterListingFiles(contentGlobs);
    debug(`[listing] matches ${files.include.length} files:`);
    const readFiles = files.include.filter((file) => {
      return !files.exclude.includes(file);
    });
    if (readFiles.length === 0) {
      const projRelativePath = relative4(project.dir, source2);
      warn(
        `The listing in '${projRelativePath}' using the following contents:
- ${contentGlobs.join("\n- ")}
doesn't match any files or folders.`
      );
    }
    for (const file of readFiles) {
      if (isYamlPath(file)) {
        debug(`[listing] Reading YAML file ${file}`);
        const yaml = readYaml(file);
        if (Array.isArray(yaml)) {
          const items = yaml;
          for (const yamlItem of items) {
            if (typeof yamlItem === "object") {
              const result2 = await listItemFromMeta(
                yamlItem,
                project,
                listing,
                dirname4(file)
              );
              if (result2) {
                const { item, source: source3 } = result2;
                validateItem(listing, item, (field) => {
                  return `An item from the file '${file}' is missing the required field '${field}'.`;
                });
                listingItemSources.add(source3);
                listingItems.push(item);
              }
            } else {
              throw new Error(
                `Unexpected listing contents in file ${file}. The array may only contain listing items, not paths or other types of data.`
              );
            }
          }
        } else if (typeof yaml === "object") {
          const result2 = await listItemFromMeta(
            yaml,
            project,
            listing,
            dirname4(file)
          );
          if (result2) {
            const { item, source: source3 } = result2;
            validateItem(listing, item, (field) => {
              return `The item defined in file '${file}' is missing the required field '${field}'.`;
            });
            listingItemSources.add(source3);
            listingItems.push(item);
          }
        } else {
          throw new Error(
            `Unexpected listing contents in file ${file}. The file should contain only one more listing items.`
          );
        }
      } else {
        const isFile = Deno.statSync(file).isFile;
        if (isFile) {
          debug(`[listing] Reading file ${file}`);
          const item = await listItemFromFile(file, project, listing);
          if (item) {
            validateItem(listing, item, (field) => {
              return `The file ${file} is missing the required field '${field}'.`;
            });
            if (item.item.title === void 0) {
              debug(`[listing] Missing Title in File ${file}`);
            }
            listingItemSources.add(item.source);
            listingItems.push(item.item);
          }
        }
      }
    }
  }
  if (contentMetadatas.length > 0) {
    for (const content of contentMetadatas) {
      const result2 = await listItemFromMeta(
        content,
        project,
        listing,
        dirname4(source2)
      );
      if (result2) {
        const { item, source: itemSource } = result2;
        validateItem(listing, item, (field) => {
          return `An item in the listing '${listing.id}' is missing the required field '${field}'.`;
        });
        listingItemSources.add(itemSource);
        listingItems.push(item);
      }
    }
  }
  const matchesField = (item, field, value) => {
    const simpleValueMatches = (itemValue, listingValue) => {
      if (typeof itemValue === "string" && typeof listingValue === "string") {
        const regex = globToRegExp4(listingValue);
        return itemValue.match(regex);
      } else {
        return itemValue === listingValue;
      }
    };
    const valueMatches = (item2, field2, value2) => {
      if (Array.isArray(item2[field2])) {
        const fieldValues = item2[field2];
        return fieldValues.some((fieldVal) => {
          return simpleValueMatches(fieldVal, value2);
        });
      } else {
        return simpleValueMatches(item2[field2], value2);
      }
    };
    if (Array.isArray(value)) {
      return value.some((val) => {
        return valueMatches(item, field, val);
      });
    } else {
      return valueMatches(item, field, value);
    }
  };
  let filtered = listingItems;
  const includes = listing[kInclude2];
  if (includes) {
    debug(
      `[listing] applying filter to include only items matching ${includes}`
    );
    const fields = Object.keys(includes);
    filtered = filtered.filter((item) => {
      return fields.every((field) => {
        return matchesField(item, field, includes[field]);
      });
    });
    debug(`[listing] afer including, ${filtered.length} item match listing`);
  }
  const excludes = listing[kExclude];
  if (excludes) {
    debug(`[listing] applying filter to exclude items matching ${includes}`);
    const fields = Object.keys(excludes);
    filtered = filtered.filter((item) => {
      return !fields.some((field) => {
        return matchesField(item, field, excludes[field]);
      });
    });
    debug(`[listing] afer excluding, ${filtered.length} item match listing`);
  }
  return {
    items: filtered,
    sources: listingItemSources
  };
}
function validateItem(listing, item, message) {
  const requiredFields = (listing2) => {
    const fields = listing2[kFieldRequired];
    if (fields) {
      if (Array.isArray(fields)) {
        return fields;
      } else {
        return [fields];
      }
    } else {
      return void 0;
    }
  };
  const validationFields = requiredFields(listing);
  if (validationFields) {
    validationFields.forEach((requiredField) => {
      if (item[requiredField] === void 0) {
        throw new Error(message(requiredField));
      }
    });
  }
}
async function listItemFromMeta(meta, project, listing, baseDir) {
  let listingItem = cloneDeep(meta);
  let source2 = "metadata" /* metadata */;
  if (typeof meta.path === "string") {
    const base3 = basename4(meta.path);
    const extension = extname4(base3).toLocaleLowerCase();
    meta[kFieldFileName] = base3;
    meta[kFieldFileModified] = fileModifiedDate(meta.path);
    const markdownExtensions = [".qmd", ".md", ".rmd"];
    if (markdownExtensions.indexOf(extension) !== -1) {
      const inputPath = isAbsolute4(meta.path) ? meta.path : join4(baseDir, meta.path);
      const fileListing = await listItemFromFile(inputPath, project, listing);
      if (fileListing === void 0) {
        return void 0;
      } else {
        listingItem = {
          ...fileListing.item || {},
          ...listingItem
        };
        if (fileListing.item.path) {
          listingItem.path = fileListing.item.path;
        }
        source2 = "metadata-document" /* metadataDocument */;
      }
    }
  }
  if (meta.author) {
    if (!Array.isArray(meta.author)) {
      meta.author = [meta.author];
    }
  }
  if (meta.date) {
    if (meta.path !== void 0) {
      listingItem.date = parsePandocDate(
        resolveDate(meta.path, meta.date)
      );
    } else {
      listingItem.date = parsePandocDate(meta.date);
    }
  }
  return {
    item: listingItem,
    source: source2
  };
}
async function listItemFromFile(input, project, listing) {
  if (!isAbsolute4(input)) {
    throw new InternalError(`input path ${input} must be absolute.`);
  }
  const projectRelativePath = relative4(project.dir, input);
  const target = await inputTargetIndex(
    project,
    pathWithForwardSlashes(projectRelativePath)
  );
  const inputTarget = await resolveInputTarget(
    project,
    pathWithForwardSlashes(projectRelativePath),
    false
  );
  const docRawMetadata = target?.markdown.yaml;
  const directoryMetadata = await directoryMetadataForInputFile(
    project,
    dirname4(input)
  );
  const documentMeta = mergeConfigs(
    project.config,
    directoryMetadata,
    docRawMetadata
  );
  const projectDraft = isProjectDraft(projectRelativePath, project);
  const draftMode = projectDraftMode(project);
  if (!isDraftVisible(draftMode) && (documentMeta?.draft || projectDraft)) {
    return void 0;
  } else {
    if (!docRawMetadata && (extname4(input) === ".qmd" || extname4(input) === ".ipynb")) {
      warn(
        `File ${input} in the listing '${listing.id}' contains no metadata.`
      );
    }
    const maxDescLength = listing[kMaxDescLength] || kDefaultMaxDescLength;
    const filename = basename4(projectRelativePath);
    const filemodified = fileModifiedDate(input);
    const description = documentMeta?.description || documentMeta?.abstract || descriptionPlaceholder(inputTarget?.outputHref, maxDescLength);
    const imageRaw = documentMeta?.image;
    const image2 = imageRaw !== void 0 && typeof imageRaw === "string" ? pathWithForwardSlashes(
      listingItemHref(imageRaw, dirname4(projectRelativePath))
    ) : void 0;
    const imageAlt = documentMeta?.[kImageAlt2];
    const imageLazyLoading = documentMeta?.[kImageLazyLoading];
    const date = documentMeta?.date ? parsePandocDate(resolveDate(input, documentMeta?.date)) : void 0;
    const datemodified = documentMeta?.date ? parsePandocDate(
      resolveDate(input, documentMeta?.[kDateModified])
    ) : void 0;
    const authors = parseAuthor(documentMeta?.author);
    let structuredAuthors;
    if (authors) {
      structuredAuthors = cslNames(
        authors?.filter((auth) => auth !== void 0).map((auth) => auth?.name)
      );
    }
    const author = structuredAuthors ? uniq(
      structuredAuthors.map(
        (auth) => auth.literal || `${auth.given} ${auth.family}`
      )
    ) : [];
    const readingContext = target?.markdown?.markdown ? estimateReadingTimeMinutes(target.markdown.markdown) : void 0;
    let readingtime = void 0;
    let wordcount = void 0;
    if (readingContext) {
      readingtime = readingContext.readingTime;
      wordcount = readingContext.wordCount;
    }
    const categories = documentMeta?.categories ? Array.isArray(documentMeta?.categories) ? documentMeta?.categories : [documentMeta?.categories] : void 0;
    const item = {
      ...documentMeta,
      path: `/${projectRelativePath}`,
      outputHref: inputTarget?.outputHref,
      [kFieldTitle]: target?.title,
      [kFieldDate]: date,
      [kFieldDateModified]: datemodified,
      [kFieldAuthor]: author,
      [kFieldCategories]: categories,
      [kFieldImage]: image2,
      [kFieldImageAlt]: imageAlt,
      [kFieldImageLazyLoading]: imageLazyLoading,
      [kFieldDescription]: description,
      [kFieldFileName]: filename,
      [kFieldFileModified]: filemodified,
      [kFieldReadingTime]: readingtime,
      [kFieldWordCount]: wordcount
    };
    return {
      item,
      source: target !== void 0 ? "document" /* document */ : "rawfile" /* rawfile */
    };
  }
}
function imageSrc(image2, progressive, height, lazy) {
  const lazyAttr = lazy === false ? "" : "loading='lazy' ";
  return `<p class="card-img-top"><img ${lazyAttr}${progressive ? "data-src" : "src"}="${image2.src}" ${image2.alt ? `alt="${image2.alt}" ` : ""}${height ? `style="height: ${height};" ` : ""}${image2.title ? `title="${image2.title}"` : ""} class="thumbnail-image card-img"/></p>`;
}
function readDehydratedListings(source2, format14) {
  const listingConfig = format14.metadata[kListing];
  const listings = [];
  if (typeof listingConfig == "string") {
    const listing = listingForType(listingType(listingConfig));
    if (listing) {
      listings.push(listing);
    }
  } else if (Array.isArray(listingConfig)) {
    const listingConfigs = listingConfig.filter(
      (listing) => typeof listing === "object"
    );
    let count = 0;
    listings.push(...listingConfigs.map((listing) => {
      return listingForMetadata(
        listing,
        () => {
          count = count + 1;
          return `${kDefaultId}-${count}`;
        },
        source2
      );
    }));
  } else if (listingConfig && typeof listingConfig === "object") {
    listings.push(
      listingForMetadata(
        listingConfig,
        () => {
          return kDefaultId;
        },
        source2
      )
    );
  } else if (listingConfig) {
    listings.push(listingForType("default" /* Default */));
  }
  return listings;
}
function listingForMetadata(meta, synthId, source2) {
  const listingType2 = meta.type || kDefaultListingType;
  const baseListing = listingForType(listingType2);
  const ensureArray = (val) => {
    if (Array.isArray(val)) {
      return val;
    } else {
      return [val];
    }
  };
  const listing = {
    ...baseListing,
    ...meta
  };
  listing.id = meta.id || synthId();
  listing.sort = computeListingSort(meta.sort);
  if (meta.contents) {
    listing.contents = ensureArray(meta.contents);
  }
  if (meta.template && typeof meta.template === "string") {
    listing.type = "custom" /* Custom */;
    listing.template = join4(dirname4(source2), meta.template);
  }
  return listing;
}
function computeListingSort(rawValue) {
  const parseValue = (sortValue) => {
    if (sortValue == void 0) {
      return void 0;
    }
    if (typeof sortValue === "string") {
      const sortStr = sortValue;
      const parts = sortStr.split(" ");
      if (parts.length === 2) {
        return {
          field: parts[0],
          direction: parts[1] === kSortAsc ? kSortAsc : kSortDesc
        };
      } else {
        return {
          field: parts[0],
          direction: kSortAsc
        };
      }
    }
  };
  if (typeof rawValue === "boolean") {
    if (rawValue) {
      return void 0;
    } else {
      return [];
    }
  } else {
    if (Array.isArray(rawValue)) {
      return rawValue.map(parseValue).filter(
        (val) => val !== void 0
      );
    } else {
      const sort = parseValue(rawValue);
      if (sort) {
        return [sort];
      }
    }
  }
}
function defaultFields(type4, itemFields) {
  switch (type4) {
    case "grid" /* Grid */:
      return kDefaultGridFields;
    case "table" /* Table */:
      return kDefaultTableFields;
    case "custom" /* Custom */:
      return itemFields;
    case "default" /* Default */:
    default:
      return kDefaultFields;
  }
}
function listingType(val) {
  switch (val) {
    case "grid" /* Grid */:
    case "default" /* Default */:
    case "table" /* Table */:
      return val;
    default:
      return "default" /* Default */;
  }
}
function listingForType(type4) {
  const listing = {
    id: kDefaultId,
    type: type4,
    contents: kDefaultContentsGlob
  };
  return listing;
}
function fileModifiedDate(input) {
  if (safeExistsSync(input)) {
    const fileInfo = Deno.statSync(input);
    return fileInfo.mtime !== null ? fileInfo.mtime : void 0;
  } else {
    return void 0;
  }
}
function listingItemHref(path3, projectRelativePath) {
  if (isAbsoluteRef(path3) || path3.startsWith("/")) {
    return path3;
  } else {
    return join4("/", projectRelativePath, path3);
  }
}
function expandGlob2(source2, project, globOrPath) {
  const getPath = () => {
    if (globOrPath.startsWith("/")) {
      return join4(project.dir, globOrPath);
    } else {
      const sourcePath = dirname4(source2);
      return join4(sourcePath, globOrPath);
    }
  };
  const globOrPathAsPath = getPath();
  try {
    if (Deno.statSync(globOrPathAsPath).isDirectory) {
      return { glob: join4(globOrPath, "**"), inputs: true };
    } else {
      return { glob: globOrPath, inputs: false };
    }
  } catch {
    return { glob: globOrPath, inputs: false };
  }
}

// core/base64.ts
function b64EncodeUnicode(str3) {
  return btoa(encodeURIComponent(str3));
}
function unicodeDecodeB64(str3) {
  return decodeURIComponent(atob(str3));
}

// project/types/website/listing/website-listing-template.ts
var kDateFormat2 = "date-format";
var kQuartoListingClass = "quarto-listing";
function templateMarkdownHandler(template2, listing, items, format14, cache3, attributes) {
  const reshapedItems = items.map(
    (item) => {
      resolveItemForTemplate(item, listing);
      const record = { ...item };
      if (item.author) {
        if (Array.isArray(item.author)) {
          record.author = item.author.join(", ");
        } else {
          record.author = item.author;
        }
      }
      const dateFormat = listing[kDateFormat2] || format14.metadata[kDateFormat2];
      const fieldLabelLangKeys = {
        "word-count": kListingPageWords
      };
      const fieldTypes = listing[kFieldTypes];
      for (const field of Object.keys(fieldTypes)) {
        if (fieldTypes[field] === kFieldDate) {
          const dateRaw = item[field];
          if (dateRaw) {
            const includeTime = field === kFieldFileModified;
            const date = typeof dateRaw === "string" ? parsePandocDate(dateRaw) : dateRaw;
            if (date) {
              record[field] = dateFormat ? formatDate(date, dateFormat) : includeTime ? formatDate(
                date,
                "short",
                "medium"
              ) : formatDate(date, "medium");
            }
          }
        } else if (fieldTypes[field] === "minutes" && item[field]) {
          const val = item[field];
          record[field] = localizedString(format14, kListingPageMinutesCompact, [
            Math.floor(val).toString()
          ]);
        } else if (fieldTypes[field] === "number" && item[field] !== void 0 && fieldLabelLangKeys[field] !== void 0) {
          const val = item[field];
          record[field] = localizedString(format14, fieldLabelLangKeys[field], [
            Math.floor(val).toLocaleString()
          ]);
        }
      }
      if (item.description !== void 0 && !isPlaceHolder(item.description)) {
        const maxDescLength = listing[kMaxDescLength] || -1;
        if (maxDescLength > 0) {
          record.description = truncateText(
            item.description,
            maxDescLength,
            "space"
          );
        }
      }
      return record;
    }
  );
  const reshapedListing = reshapeListing(listing, format14);
  const tempateItems = listing[kMaxItems] ? reshapedItems.slice(0, listing[kMaxItems]) : reshapedItems;
  const paramsForType = (type4) => {
    const ejsParams = {
      items: tempateItems
    };
    ``;
    if (type4 !== "custom" /* Custom */) {
      ejsParams.listing = reshapedListing;
    } else {
      ejsParams["metadataAttrs"] = reshapedListing.utilities.metadataAttrs;
      ejsParams["templateParams"] = reshapedListing["template-params"];
    }
    ejsParams["utils"] = {
      b64encode: b64EncodeUnicode,
      b64decode: unicodeDecodeB64
    };
    return ejsParams;
  };
  const filterRendered = renderEjs(
    resourcePath("projects/website/listing/_filter.ejs.md"),
    {
      items: tempateItems,
      listing: reshapedListing
    }
  );
  let templateRendered = renderEjs(
    template2,
    paramsForType(listing.type),
    false,
    cache3
  );
  templateRendered = templateRendered.replace(/(\r\n|\r|\n){2,}/g, "$1$1");
  const paginationRendered = renderEjs(
    resourcePath("projects/website/listing/_pagination.ejs.md"),
    {
      items: tempateItems,
      listing: reshapedListing
    }
  );
  const markdown = [filterRendered, templateRendered, paginationRendered].join(
    "\n"
  );
  const pipelineId = (id) => {
    return `pipeline-listing-${id}`;
  };
  return {
    getUnrendered() {
      return {
        blocks: {
          [pipelineId(listing.id)]: markdown
        }
      };
    },
    processRendered(rendered, doc) {
      let listingEl = doc.querySelector(`div[id='${listing.id}']`);
      if (listingEl === null) {
        const content = doc.querySelector("#quarto-content main.content");
        listingEl = doc.createElement("div");
        if (content) {
          content.appendChild(listingEl);
        } else {
          const customContent = doc.querySelector("#quarto-content");
          if (customContent) {
            customContent.appendChild(listingEl);
          } else {
            doc.body.appendChild(listingEl);
          }
        }
      }
      if (!listingEl?.classList.contains(kQuartoListingClass)) {
        listingEl?.classList.add(kQuartoListingClass);
      }
      listingEl?.classList.add(`quarto-listing-container-${listing.type}`);
      const outListingId = `listing-${listing.id}`;
      listingEl?.setAttribute("id", outListingId);
      if (attributes) {
        Object.keys(attributes).forEach((attrName) => {
          listingEl?.setAttribute(attrName, attributes[attrName]);
        });
      }
      const renderedEl = rendered[pipelineId(listing.id)];
      if (renderedEl) {
        listingEl.innerHTML = renderedEl.innerHTML;
      }
    }
  };
}
function resolveItemForTemplate(item, listing) {
  const addSortable = (item2, field, value) => {
    item2.sortableValues = item2.sortableValues || {};
    item2.sortableValues[field] = value;
  };
  for (const field of Object.keys(listing[kFieldTypes])) {
    const type4 = listing[kFieldTypes][field];
    if (item[field] !== void 0) {
      if (type4 === "date") {
        addSortable(item, field, item[field].valueOf().toString());
      } else if (type4 === "number") {
        addSortable(item, field, item[field].toString());
      } else if (type4 === "minutes") {
        addSortable(item, field, item[field].toString());
      }
    }
  }
  for (const field of listing[kFieldLinks]) {
    const val = item[field];
    if (val !== void 0) {
      addSortable(item, field, val);
    }
  }
}
function reshapeListing(listing, format14) {
  const reshaped = {
    ...listing
  };
  const utilities = {};
  utilities.sortableFieldData = () => {
    const fieldSortData = [];
    reshaped[kFieldSort].filter((field) => {
      return reshaped.fields.includes(field);
    }).forEach((field) => {
      if (reshaped[kFieldTypes][field] === "date") {
        fieldSortData.push({
          listingSort: {
            field: sortAttrValue(field),
            direction: kSortAsc
          },
          description: `${reshaped[kFieldDisplayNames][field] || field} - ${format14.language[kListingPageOrderByDateAsc]}`
        });
        fieldSortData.push({
          listingSort: {
            field: sortAttrValue(field),
            direction: kSortDesc
          },
          description: `${reshaped[kFieldDisplayNames][field] || field} - ${format14.language[kListingPageOrderByDateDesc]}`
        });
      } else if (reshaped[kFieldTypes][field] === "number" || reshaped[kFieldTypes][field] === "minutes") {
        fieldSortData.push({
          listingSort: {
            field: sortAttrValue(field),
            direction: kSortAsc
          },
          description: `${reshaped[kFieldDisplayNames][field] || field} (${format14.language[kListingPageOrderByNumberAsc]})`
        });
        fieldSortData.push({
          listingSort: {
            field: sortAttrValue(field),
            direction: kSortDesc
          },
          description: `${reshaped[kFieldDisplayNames][field] || field} (${format14.language[kListingPageOrderByNumberDesc]})`
        });
      } else {
        const sortField = useSortTarget(listing, field) ? sortAttrValue(field) : `listing-${field}`;
        fieldSortData.push({
          listingSort: {
            field: sortField,
            direction: kSortAsc
          },
          description: `${reshaped[kFieldDisplayNames][field] || field}`
        });
      }
    });
    return fieldSortData;
  };
  utilities.fieldName = (field) => {
    return reshaped[kFieldDisplayNames][field] || field;
  };
  utilities.outputLink = (item, field, val, clz) => {
    const fieldLinks = reshaped[kFieldLinks];
    const value = val || item[field] || "&nbsp;";
    const path3 = item.path;
    if (path3 && value !== void 0 && fieldLinks.includes(field)) {
      return `<a href="${path3}" class="${field}${clz ? ` ${clz}` : ""}">${value}</a>`;
    } else {
      if (clz) {
        return `<span class="${clz}">${value}</span>`;
      } else {
        return value;
      }
    }
  };
  utilities.sortTarget = (field) => {
    if (useSortTarget(listing, field)) {
      return sortAttrValue(field);
    } else {
      return `listing-${field}`;
    }
  };
  let itemNumber = 0;
  utilities.itemNumber = () => {
    return ++itemNumber;
  };
  utilities.img = (itemNumber2, src2, classes, alt, lazy) => {
    const pageSize = listing[kPageSize];
    const classAttr = classes ? `class="${classes}"` : "";
    const styleAttr = listing[kImageHeight2] ? `style="height: ${listing[kImageHeight2]};"` : "";
    const altAttr = alt ? `alt="${encodeAttributeValue(alt)}"` : "";
    const srcAttr = itemNumber2 > pageSize ? "data-src" : "src";
    const lazyAttr = lazy === false ? "" : "loading='lazy' ";
    return `<img ${lazyAttr}${srcAttr}="${src2}" ${classAttr} ${styleAttr} ${altAttr}>`;
  };
  utilities.imgPlaceholder = (listingId, itemNumber2, itemPath, lazy) => {
    const pageSize = listing[kPageSize];
    return imagePlaceholder(
      listingId,
      itemPath,
      itemNumber2 > pageSize,
      listing[kImageHeight2],
      lazy
    );
  };
  let index2 = 0;
  utilities.metadataAttrs = (item) => {
    const attr = {};
    attr["index"] = (index2++).toString();
    if (item.categories) {
      const str3 = item.categories.join(",");
      attr["categories"] = b64EncodeUnicode(str3);
    }
    item.sortableValues = item.sortableValues || {};
    for (const field of Object.keys(item.sortableValues)) {
      if (useSortTarget(listing, field)) {
        attr[sortAttrValue(field)] = escape(
          item.sortableValues[field]
        );
      }
    }
    const attrs = Object.keys(attr).map((key) => {
      const value = attr[key];
      return `data-${key}='${value}'`;
    });
    return attrs.join(" ");
  };
  utilities.localizedString = (str3) => {
    const localizedStrings = format14.language;
    return localizedStrings[str3];
  };
  reshaped.utilities = utilities;
  return reshaped;
}
function sortAttrValue(field) {
  return `listing-${field}-sort`;
}
var useSortTarget = (listing, field) => {
  const links = listing[kFieldLinks];
  if (links.includes(field)) {
    return true;
  }
  const type4 = listing[kFieldTypes][field];
  if (type4 === "date" || type4 === "number" || type4 === "minutes") {
    return true;
  } else if (listing[kFieldLinks].includes(field)) {
    return true;
  }
  return false;
};
function templateJsScript(id, listing, itemCount2) {
  const pageSize = listing[kPageSize] || 50;
  const columns = listing[kFields] || [];
  const pageOptions = itemCount2 > pageSize ? `${pageSize ? `page: ${pageSize}` : ""},
    pagination: { item: "<li class='page-item'><a class='page page-link' href='#'></a></li>" },` : "";
  const filterOptions = `searchColumns: [${listing[kFieldFilter].map((field) => {
    return `"listing-${field}"`;
  }).join(",")}],`;
  const resolvedColumns = columns.map((field) => {
    return `'listing-${field}'`;
  });
  resolvedColumns.push(
    `{ data: ['index'] }`,
    `{ data: ['categories'] }`
  );
  for (const field of listing[kFieldSort]) {
    if (useSortTarget(listing, field)) {
      resolvedColumns.push(`{ data: ['${sortAttrValue(field)}'] }`);
    }
  }
  const rowJs = `[${resolvedColumns.join(",")}]`;
  const jsScript = `
  window.document.addEventListener("DOMContentLoaded", function (_event) {
    const listingTargetEl = window.document.querySelector('#listing-${id} .list');
    if (!listingTargetEl) {
      // No listing discovered, do not attach.
      return; 
    }

    const options = {
      valueNames: ${rowJs},
      ${pageOptions}
      ${filterOptions}
    };

    window['quarto-listings'] = window['quarto-listings'] || {};
    window['quarto-listings']['listing-${id}'] = new List('listing-${id}', options);

    if (window['quarto-listing-loaded']) {
      window['quarto-listing-loaded']();
    }
  });

  window.addEventListener('hashchange',() => {
    if (window['quarto-listing-loaded']) {
      window['quarto-listing-loaded']();
    }
  })
  `;
  return jsScript;
}

// project/types/website/listing/website-listing-categories.ts
init_constants6();
function categorySidebar(doc, listingDescriptors, format14, options) {
  const categoryStyle = options[kCategoryStyle];
  const headingEl = doc.createElement("h5");
  headingEl.innerText = localizedString(format14, kListingPageFieldCategories);
  headingEl.classList.add("quarto-listing-category-title");
  const cats = accumCategories(listingDescriptors);
  const categoriesEl = categoryContainer(doc);
  const totalCategories = itemCount(listingDescriptors);
  categoriesEl.classList.add(categoryStyle);
  const defaultFormat2 = (category, count) => {
    return category + ` <span class="quarto-category-count">(${count})</span>`;
  };
  const cloudFormat = (category, count) => {
    const size = Math.ceil(count / totalCategories * 10);
    return `<span class="quarto-category-count category-cloud-${size}">${category}</span>`;
  };
  const unnumberedFormat = (category, _count) => {
    return `${category}`;
  };
  const formatFn = categoryStyle === "category-default" ? defaultFormat2 : categoryStyle === "category-cloud" ? cloudFormat : unnumberedFormat;
  if (categoryStyle === "category-default") {
    const allCategory = localizedString(format14, kListingPageCategoryAll);
    const allEl = categoryElement(
      doc,
      allCategory,
      formatFn(allCategory, totalCategories),
      ""
    );
    categoriesEl.appendChild(allEl);
  }
  for (const cat of Object.keys(cats).sort(
    (a5, b3) => a5.toLocaleLowerCase().localeCompare(b3.toLocaleLowerCase())
  )) {
    const count = cats[cat];
    const catEl = categoryElement(doc, cat, formatFn(cat, count), cat);
    categoriesEl.appendChild(catEl);
  }
  return { headingEl, categoriesEl };
}
function itemCount(listingDescriptors) {
  return listingDescriptors.reduce((previous, listingDescriptor) => {
    return previous + listingDescriptor.items.length;
  }, 0);
}
function accumCategories(listingDescriptors) {
  const items = listingDescriptors.flatMap((listingDescriptor) => {
    return listingDescriptor.items;
  });
  const categories = {};
  items.forEach((item) => {
    if (item.categories) {
      item.categories.forEach((category) => {
        const currentCount = categories[category] || 0;
        categories[category] = currentCount + 1;
      });
    }
  });
  return categories;
}
function categoryContainer(doc) {
  const container = doc.createElement("div");
  container.classList.add("quarto-listing-category");
  return container;
}
function categoryElement(doc, category, contents, value) {
  const categoryEl = doc.createElement("div");
  categoryEl.classList.add("category");
  categoryEl.setAttribute(
    "data-category",
    value !== void 0 ? b64EncodeUnicode(value) : b64EncodeUnicode(category)
  );
  categoryEl.innerHTML = contents;
  return categoryEl;
}

// project/types/website/listing/website-listing-feed.ts
init_path();
init_log();
init_lodash();
init_lodash();
init_quarto();
init_resources2();
init_website_constants();
init_path2();
await init_project_shared();
init_log2();
init_format5();
var kDefaultItems = 20;
async function createFeed(doc, source2, project, descriptors, options, format14) {
  const siteUrl2 = websiteBaseurl(project.config);
  if (!siteUrl2) {
    warn(
      "Unable to create a feed as the required `site-url` property is missing from this project."
    );
    return;
  }
  const feedTitle = options.title || websiteTitle(project.config);
  if (!feedTitle) {
    warn(
      "Unable to create a feed as the required `site > title` property is missing from this project."
    );
    return;
  }
  const feedDescription = options.description || format14.metadata[kDescription2] || websiteDescription(project.config) || "";
  const projectRelInput = relative4(project.dir, source2);
  const inputTarget = await resolveInputTarget(project, projectRelInput, false);
  const [dir, stem] = dirAndStem(source2);
  const finalRelPath = relative4(
    project.dir,
    join4(dir, `${stem}.xml`)
  );
  const link2 = absoluteUrl(siteUrl2, inputTarget?.outputHref);
  const feedLink = absoluteUrl(siteUrl2, finalRelPath);
  const items = [];
  for (const descriptor of descriptors) {
    items.push(...descriptor.items);
  }
  const filteredItems = prepareItems(items, options);
  const mostRecent = mostRecentItem(filteredItems);
  const xmlSheetHref = options[kXmlStyleSheet] ? absoluteUrl(siteUrl2, options[kXmlStyleSheet]) : void 0;
  const feed = {
    title: feedTitle,
    description: feedDescription,
    link: link2,
    feedLink,
    generator: `quarto-${quartoConfig.version()}`,
    lastBuildDate: mostRecent && mostRecent.date ? new Date(mostRecent.date).toUTCString() : (/* @__PURE__ */ new Date()).toUTCString(),
    language: options.language,
    [kXmlStyleSheet]: xmlSheetHref
  };
  const image2 = options.image || format14.metadata[kImage] || websiteImage(project.config)?.src;
  if (image2) {
    feed.image = {
      title: feedTitle,
      link: link2,
      url: absoluteUrl(siteUrl2, image2)
    };
    const size = imageSize(image2);
    if (size) {
      const [height, width] = feedImageSize(size.height, size.width);
      feed.image.height = height;
      feed.image.width = width;
    }
  }
  const stagedPath = feedPath(dir, stem, options.type);
  const feedFiles = [];
  if (options[kXmlStyleSheet]) {
    feedFiles.push(options[kXmlStyleSheet]);
  }
  const rendered = await renderFeed(
    siteUrl2,
    feed,
    filteredItems,
    project,
    stagedPath
  );
  if (rendered) {
    feedFiles.push(stagedPath);
    addLinkTagToDocument(doc, feed, `${stem}.xml`);
  }
  options[kFieldCategories] = options[kFieldCategories] || [];
  const feedCategories = Array.isArray(options[kFieldCategories]) ? options[kFieldCategories] : [options[kFieldCategories]];
  const categoriesToRender = feedCategories?.map((category) => {
    const finalRelPath2 = relative4(
      project.dir,
      join4(dir, `${stem}-${category.toLocaleLowerCase()}.xml`)
    );
    return {
      category,
      file: feedPath(
        dir,
        `${stem}-${category.toLocaleLowerCase()}`,
        options.type
      ),
      finalFile: finalRelPath2,
      feedLink: absoluteUrl(siteUrl2, finalRelPath2)
    };
  });
  if (categoriesToRender) {
    for (const categoryToRender of categoriesToRender) {
      const rendered2 = await renderCategoryFeed(
        siteUrl2,
        categoryToRender,
        feed,
        items,
        options,
        project
      );
      if (rendered2) {
        feedFiles.push(categoryToRender.file);
      }
    }
  }
  return feedFiles;
}
var kFeedOptions = {
  remove: {
    anchors: true
  },
  transform: {
    [kUrlsToAbsolute]: true,
    [kInlineCodeStyle]: true,
    math: true
  }
};
function completeStagedFeeds(context, outputFiles, _incremental) {
  const siteUrl2 = websiteBaseurl(context.config);
  if (siteUrl2 !== void 0) {
    outputFiles.forEach((outputFile5) => {
      if (outputFile5.format.metadata[kListing] && isHtmlOutput(outputFile5.format.pandoc, true)) {
        const [dir, stem] = dirAndStem(outputFile5.file);
        const files = resolvePathGlobs(dir, [`${stem}${kStagedFileGlob}`], []);
        const contentReader = renderedContentReader(
          context,
          kFeedOptions,
          siteUrl2
        );
        for (const feedFile of files.include) {
          const [feedDir, feedStem] = dirAndStem(feedFile);
          try {
            const type4 = feedFile.endsWith(kFullStagedExt) ? "full" : feedFile.endsWith(kPartialStagedExt) ? "partial" : "metadata";
            let feedContents = Deno.readTextFileSync(feedFile);
            const tagWithReplacements = [
              {
                tag: "title",
                regex: kTitleRegex,
                replaceValue: (rendered) => {
                  if (rendered.title) {
                    return escape(rendered.title);
                  } else {
                    return "";
                  }
                }
              },
              {
                tag: "description",
                regex: kDescRegex,
                replaceValue: (rendered) => {
                  if (type4 === "full") {
                    return `<![CDATA[ ${rendered.fullContents} ]]>`;
                  } else if (type4 === "partial") {
                    return `<![CDATA[ ${rendered.description || rendered.firstPara} ]]>`;
                  } else {
                    return `<![CDATA[ ${rendered.description || ""} ]]>`;
                  }
                }
              }
            ];
            tagWithReplacements.forEach((tagWithReplacement) => {
              const regex = tagWithReplacement.regex;
              const tag = tagWithReplacement.tag;
              regex.lastIndex = 0;
              let match = regex.exec(feedContents);
              while (match) {
                const relativePath = match[1];
                const absolutePath = relativePath.startsWith("/") ? join4(projectOutputDir(context), relativePath) : join4(feedDir, relativePath);
                const contents = contentReader(absolutePath);
                if (contents) {
                  const targetStr = placholderForReplace(tag, relativePath);
                  feedContents = feedContents.replace(
                    targetStr,
                    () => {
                      return `<${tag}>${tagWithReplacement.replaceValue(contents)}</${tag}>`;
                    }
                  );
                }
                match = regex.exec(feedContents);
              }
              regex.lastIndex = 0;
            });
            Deno.writeTextFileSync(
              join4(feedDir, `${feedStem}.${kFinalExt}`),
              feedContents
            );
          } catch (error2) {
            if (!(error2 instanceof Error)) {
              throw error2;
            }
            const errorMessage = error2.message;
            warnOnce(
              `Unable to generate feed '${feedStem}.xml'
${errorMessage}`
            );
          } finally {
            try {
              safeRemoveSync(feedFile);
            } catch {
            }
          }
        }
      }
    });
  }
}
async function renderCategoryFeed(siteUrl2, categoryToRender, feed, items, options, project) {
  const categoryItems = items.filter((item) => {
    const categories = item[kFieldCategories];
    if (categories) {
      return categories.includes(categoryToRender.category);
    } else {
      return false;
    }
  });
  const filteredItems = prepareItems(categoryItems, options);
  const feedMeta = { ...feed };
  feedMeta.link = feedMeta.link + "#category=" + encodeURI(categoryToRender.category);
  feedMeta.feedLink = categoryToRender.feedLink;
  if (feedMeta.image) {
    feedMeta.image.link = feedMeta.link;
    feedMeta.image.title = feedMeta.title;
  }
  const mostRecent = mostRecentItem(filteredItems);
  feedMeta.lastBuildDate = mostRecent && mostRecent.date ? new Date(mostRecent.date).toUTCString() : (/* @__PURE__ */ new Date()).toUTCString();
  return await renderFeed(
    siteUrl2,
    feedMeta,
    filteredItems,
    project,
    categoryToRender.file
  );
}
async function renderFeed(siteUrl2, feed, items, project, feedPath2) {
  const feedItems = [];
  for (const item of items) {
    const inputTarget = await resolveInputTarget(project, item.path, false);
    const title3 = inputTarget?.outputHref ? placeholder(inputTarget?.outputHref) : item.title || "";
    const link2 = absoluteUrl(siteUrl2, inputTarget?.outputHref || "");
    const description = inputTarget?.outputHref ? placeholder(inputTarget?.outputHref) : item.description || "";
    const pubDate = item.date ? new Date(item.date) : /* @__PURE__ */ new Date();
    const feedItem = {
      title: title3,
      link: link2,
      description,
      guid: link2,
      pubDate
    };
    if (Array.isArray(item[kFieldCategories])) {
      feedItem.categories = item[kFieldCategories];
    }
    if (Array.isArray(item[kFieldAuthor])) {
      feedItem.authors = item[kFieldAuthor];
    }
    if (item[kFieldImage] && typeof (item[kFieldImage] === "string")) {
      const image2 = item[kFieldImage];
      feedItem.image = absoluteUrl(siteUrl2, image2);
      const imagePath = join4(project.dir, image2);
      feedItem.imageContentType = imageContentType(imagePath);
      const size = imageSize(imagePath);
      if (size) {
        const [height, width] = feedImageSize(size.height, size.width);
        feedItem.imageHeight = height;
        feedItem.imageWidth = width;
      }
    }
    feedItems.push(feedItem);
  }
  await generateFeed(feed, feedItems, feedPath2);
  return true;
}
async function generateFeed(feed, feedItems, path3) {
  const feedFile = await Deno.open(path3, {
    write: true,
    create: true
  });
  try {
    const textEncoder = new TextEncoder();
    const preamble = renderEjs(
      resourcePath("projects/website/listing/feed/preamble.ejs.md"),
      {
        feed,
        escape
      }
    );
    await feedFile.write(textEncoder.encode(preamble));
    for (const feedItem of feedItems) {
      const item = renderEjs(
        resourcePath("projects/website/listing/feed/item.ejs.md"),
        {
          item: feedItem,
          escape
        }
      );
      await feedFile.write(textEncoder.encode(item));
    }
    const postamble = renderEjs(
      resourcePath("projects/website/listing/feed/postamble.ejs.md"),
      {
        feed,
        escape
      }
    );
    await feedFile.write(textEncoder.encode(postamble));
  } finally {
    feedFile.close();
  }
}
function prepareItems(items, options) {
  const validItems = items.filter((item) => {
    return item.title !== void 0 && item.path !== void 0;
  });
  const uniqueItems = uniqBy(validItems, (item) => {
    return item.path;
  });
  const sortedItems = uniqueItems.sort((a5, b3) => {
    const aTimestamp = a5.date ? new Date(a5.date).valueOf() : -1;
    const bTimestamp = b3.date ? new Date(b3.date).valueOf() : -1;
    return bTimestamp - aTimestamp;
  });
  const itemCount2 = options[kItems] || kDefaultItems;
  if (sortedItems.length > itemCount2) {
    return sortedItems.slice(0, itemCount2);
  } else {
    return sortedItems;
  }
}
function mostRecentItem(items) {
  const sortedItems = items.sort((a5, b3) => {
    const aTime = a5.date ? a5.date.getTime() : 0;
    const bTime = b3.date ? b3.date.getTime() : 0;
    return bTime - aTime;
  });
  const mostRecentItem2 = sortedItems.length > 0 ? sortedItems[0] : void 0;
  return mostRecentItem2;
}
function addLinkTagToDocument(doc, feed, path3) {
  const linkEl = doc.createElement("link");
  linkEl.setAttribute("rel", "alternate");
  linkEl.setAttribute("type", "application/rss+xml");
  linkEl.setAttribute("title", feed.title);
  linkEl.setAttribute("href", path3);
  linkEl.setAttribute("data-external", "1");
  doc.head.appendChild(linkEl);
}
var kFullStagedExt = "feed-full-staged";
var kPartialStagedExt = "feed-partial-staged";
var kMetadataStagedExt = "feed-metadata-staged";
var kFinalExt = "xml";
var kStagedFileGlob = "*.feed-*-staged";
function placeholder(outputHref) {
  return `{B4F502887207:${outputHref}}`;
}
function placholderForReplace(tag, outputHref) {
  return `<${tag}>{B4F502887207:${outputHref}}</${tag}>`;
}
var kTitleRegex = tagplaceholderRegex("title");
var kDescRegex = tagplaceholderRegex("description");
function tagplaceholderRegex(tag) {
  return new RegExp(`<${tag}>{B4F502887207:(.*?)}</${tag}>`, "gm");
}
function feedPath(dir, stem, type4) {
  const ext = type4 === "full" ? kFullStagedExt : type4 === "partial" ? kPartialStagedExt : kMetadataStagedExt;
  const file = `${stem}.${ext}`;
  return join4(dir, file);
}
var kMaxWidth = 144;
var kMaxHeight = 400;
var feedImageSize = (height, width) => {
  const heightScale = kMaxHeight / height;
  const widthScale = kMaxWidth / width;
  if (heightScale >= 1 && widthScale >= 1) {
    return [height, width];
  } else {
    const scaleFactor = heightScale < widthScale ? heightScale : widthScale;
    return [
      Math.round(height * scaleFactor),
      Math.round(width * scaleFactor)
    ];
  }
};

// project/types/website/listing/website-listing-project.ts
init_fs();
init_path();
init_project_scratch();
var kListingDir = "listing";
var kListingMapFile = "listing-cache.json";
function cacheListingProjectData(project, listingPath, descriptors) {
  const listingContents = descriptors.flatMap((descriptor) => {
    const contentItems = descriptor.listing.contents;
    return contentItems.filter((item) => {
      return typeof item === "string";
    });
  });
  const cache3 = readListingMap(project) || {};
  const listingMap = cache3.listingMap || {};
  listingContents.forEach((content) => {
    const globSet = new Set(listingMap[listingPath] || []);
    globSet.add(content);
    listingMap[listingPath] = [...globSet];
  });
  writeListingCache(project, {
    listingMap
  });
}
function listingProjectData(project) {
  return readListingMap(project);
}
function clearListingProjectData(project) {
  clearListingMap(project);
}
function clearListingMap(project) {
  const file = projectListingMapFile(project.dir);
  try {
    safeRemoveSync(file);
  } catch {
  }
}
function readListingMap(project) {
  const file = projectListingMapFile(project.dir);
  try {
    const mapRaw = Deno.readTextFileSync(file);
    const data3 = JSON.parse(mapRaw);
    return data3;
  } catch {
    return {};
  }
}
function writeListingCache(project, cache3) {
  const file = projectListingMapFile(project.dir);
  ensureDirSync(dirname4(file));
  const mapJson = JSON.stringify(cache3, void 0, 2);
  Deno.writeTextFileSync(file, mapJson);
}
function projectListingMapFile(dir) {
  return join4(projectScratchPath(dir, kListingDir), kListingMapFile);
}

// project/types/website/listing/website-listing.ts
init_path2();
init_lodash();
await init_project_shared();
init_file();

// project/types/website/listing/website-listing-index.ts
init_path();
init_fs();
init_path2();
init_lodash();
await init_project_shared();
init_log();
init_format5();
async function createListingIndex(source2, project, descriptors) {
  const projectRelInput = relative4(project.dir, source2);
  const inputTarget = await resolveInputTarget(project, projectRelInput, false);
  if (inputTarget) {
    const listingHref = "/" + inputTarget.outputHref;
    const items = [];
    for (const descriptor of descriptors) {
      items.push(...descriptor.items);
    }
    const filteredItems = uniqBy(items, (item) => {
      return item.path;
    });
    if (filteredItems) {
      const itemHrefs = [];
      for (const item of filteredItems) {
        if (item.path) {
          const itemTarget = await resolveInputTarget(
            project,
            item.path,
            false
          );
          if (itemTarget) {
            const itemHref = itemTarget.outputHref;
            itemHrefs.push(itemHref);
          }
        }
      }
      const listingJson = {
        listing: listingHref,
        items: itemHrefs
      };
      const listingIndexPath = listingIndex(source2);
      Deno.writeTextFileSync(
        listingIndexPath,
        JSON.stringify(listingJson, void 0, 2)
      );
      return listingIndexPath;
    } else {
      return void 0;
    }
  } else {
    return void 0;
  }
}
function updateGlobalListingIndex(context, outputFiles, incremental) {
  const outputDir = projectOutputDir(context);
  const listingJsonPath = join4(outputDir, "listings.json");
  const listingJson = existsSync2(listingJsonPath) ? Deno.readTextFileSync(listingJsonPath) : void 0;
  const listingPaths = new Array();
  let generateListings = true;
  if (incremental && listingJson) {
    try {
      const existingListingJson = JSON.parse(listingJson);
      listingPaths.push(...existingListingJson);
    } catch {
      generateListings = false;
      warn(
        "Unable to read listing index - it may be corrupt. Please re-render the entire site to create a valid listing index."
      );
    }
  }
  if (generateListings) {
    for (const outputFile5 of outputFiles) {
      const hasListing = !!outputFile5.format.metadata[kListing];
      if (hasListing && isHtmlOutput(outputFile5.format.pandoc, true)) {
        const indexPath2 = listingIndex(outputFile5.file);
        if (existsSync2(indexPath2)) {
          const json3 = Deno.readTextFileSync(indexPath2);
          const indexJson = JSON.parse(json3);
          const existingIndex = listingPaths.findIndex(
            (paths) => paths.listing === indexJson.listing
          );
          if (existingIndex > -1) {
            listingPaths[existingIndex] = indexJson;
          } else {
            listingPaths.push(indexJson);
          }
          safeRemoveSync(indexPath2);
        }
      }
    }
    if (listingPaths.length > 0) {
      Deno.writeTextFileSync(
        listingJsonPath,
        JSON.stringify(listingPaths, void 0, 2)
      );
    }
  }
}
function listingIndex(input) {
  const [dir, stem] = dirAndStem(input);
  return join4(dir, `${stem}-listing.json`);
}

// project/types/website/listing/website-listing.ts
init_format_html_info();
init_log();
function listingSupplementalFiles(project, inputs, incremental) {
  if (incremental) {
    const listingProjData = listingProjectData(project);
    const listingMap = listingProjData.listingMap || {};
    const listingFiles = Object.keys(listingMap);
    const inputPaths = inputs.map((inp) => inp.path);
    const matching = listingFiles.filter((listingFile) => {
      const listingDir = join4(project.dir, dirname4(listingFile));
      const globs = listingMap[listingFile];
      if (filterPaths(listingDir, inputPaths, globs).include.length > 0) {
        return true;
      }
    });
    if (matching.length > 0) {
      const supplementalFiles = matching.map((listingRelativePath) => {
        return join4(project.dir, listingRelativePath);
      });
      const files = uniqBy(supplementalFiles.filter((file) => {
        return !inputs.find((inp) => {
          return inp.path === file;
        }) && existsSync2(file);
      }));
      const onRenderComplete = async (project2, files2, incremental2) => {
        if (incremental2) {
          const outputDir = projectOutputDir(project2);
          for (const file of files2) {
            const filePath = join4(outputDir, file);
            await touch(filePath);
          }
        }
      };
      return {
        files: files.map((file) => {
          return { path: file, formats: ["html", "html4", "html5"] };
        }),
        onRenderComplete
      };
    } else {
      return { files: [] };
    }
  } else {
    clearListingProjectData(project);
    return { files: [] };
  }
}
async function listingHtmlDependencies(source2, project, format14, temp, _extras) {
  const { listingDescriptors, options } = await readListings(
    source2,
    project,
    format14
  );
  const pageHasListings = listingDescriptors.length > 0;
  if (pageHasListings) {
    cacheListingProjectData(
      project,
      relative4(project.dir, source2),
      listingDescriptors
    );
  }
  const markdownHandlers = [];
  listingDescriptors.forEach((listingDescriptor) => {
    markdownHandlers.push(
      markdownHandler(
        format14,
        listingDescriptor.listing,
        listingDescriptor.items
      )
    );
  });
  markdownHandlers.push({
    getUnrendered: () => {
      return {
        inlines: {
          "quarto-enable-math-inline": "$e = mC^2$"
        }
      };
    },
    processRendered: (_rendered, _doc) => {
    }
  });
  const pipeline2 = createMarkdownPipeline(
    `quarto-listing-pipeline`,
    markdownHandlers
  );
  const kListingDependency = "quarto-listing";
  const jsPaths = [
    resourcePath("projects/website/listing/list.min.js"),
    resourcePath("projects/website/listing/quarto-listing.js")
  ];
  const listingDependencies = [{
    name: kListingDependency,
    scripts: jsPaths.map((path3) => {
      return {
        name: basename4(path3),
        path: path3
      };
    })
  }];
  const generateScriptListJsScript = () => {
    return listingDescriptors.map((listingItem) => {
      return templateJsScript(
        listingItem.listing.id,
        listingItem.listing,
        listingItem.items.length
      );
    });
  };
  const listingPostProcessor = async (doc) => {
    pipeline2.processRenderedMarkdown(doc);
    listingPostProcess(
      doc,
      listingDescriptors,
      options,
      format14
    );
    const supporting = [];
    if (options[kFeed]) {
      const listingOptions = {
        type: "full",
        ...options[kFeed]
      };
      const feedAbsPaths = await createFeed(
        doc,
        source2,
        project,
        listingDescriptors,
        listingOptions,
        format14
      );
      if (feedAbsPaths) {
        feedAbsPaths.forEach((feedAbsPath) => {
          supporting.push(feedAbsPath);
        });
      }
    }
    const listingIndexPath = await createListingIndex(
      source2,
      project,
      listingDescriptors
    );
    if (listingIndexPath) {
      supporting.push(listingIndexPath);
    }
    return Promise.resolve({ resources: [], supporting });
  };
  return {
    [kSassBundles]: formatHasBootstrap(format14) ? [listingSassBundle()] : [],
    [kDependencies]: pageHasListings ? listingDependencies : [],
    [kMarkdownAfterBody]: pageHasListings ? pipeline2.markdownAfterBody() : void 0,
    [kIncludeInHeader]: pageHasListings ? [
      scriptFileForScripts(generateScriptListJsScript(), temp)
    ] : [],
    [kHtmlPostprocessors]: pageHasListings ? listingPostProcessor : void 0
  };
}
function completeListingGeneration(context, outputFiles, incremental) {
  debug(`[listing] Completing staged feeds in ${context.dir}`);
  completeStagedFeeds(context, outputFiles, incremental);
  debug(`[listing] Completing listing items in ${context.dir}`);
  completeListingItems(context, outputFiles, incremental);
  debug(`[listing] Writing global listing index for ${context.dir}`);
  updateGlobalListingIndex(context, outputFiles, incremental);
}
function markdownHandler(format14, listing, items) {
  switch (listing.type) {
    case "table" /* Table */: {
      return templateMarkdownHandler(
        resourcePath("projects/website/listing/listing-table.ejs.md"),
        listing,
        items,
        format14,
        true
      );
    }
    case "grid" /* Grid */: {
      return templateMarkdownHandler(
        resourcePath("projects/website/listing/listing-grid.ejs.md"),
        listing,
        items,
        format14,
        true
      );
    }
    case "custom" /* Custom */: {
      if (listing.template === void 0) {
        throw new Error(
          "In order to use a listing of type custom, please provide the path to a template."
        );
      } else {
        if (!existsSync2(listing.template)) {
          throw new Error(
            `The template ${listing.template} can't be found.`
          );
        }
      }
      return templateMarkdownHandler(
        listing.template,
        listing,
        items,
        format14,
        false
      );
    }
    case "default" /* Default */:
    default: {
      return templateMarkdownHandler(
        resourcePath("projects/website/listing/listing-default.ejs.md"),
        listing,
        items,
        format14,
        true
      );
    }
  }
}
function listingPostProcess(doc, listingDescriptors, options, format14) {
  debug(`[listing] Post processing ${listingDescriptors.length} listings`);
  const categories = options[kFieldCategories];
  if (categories) {
    const { headingEl, categoriesEl } = categorySidebar(
      doc,
      listingDescriptors,
      format14,
      options
    );
    const rightSidebar = doc.getElementById(kMarginSidebarId);
    const marginHeader = rightSidebar?.querySelector(".quarto-margin-header");
    if (marginHeader) {
      marginHeader.after(...[headingEl, categoriesEl]);
    } else {
      const marginFooter = rightSidebar?.querySelector(".quarto-margin-footer");
      if (marginFooter) {
        rightSidebar?.insertBefore(headingEl, marginFooter);
        rightSidebar?.insertBefore(categoriesEl, marginFooter);
      } else {
        rightSidebar?.appendChild(headingEl);
        rightSidebar?.appendChild(categoriesEl);
      }
    }
  }
  const descImgs = doc.querySelectorAll(".listing-description img");
  descImgs.forEach((descImg) => {
    descImg.remove();
  });
}
var kMarginSidebarId = "quarto-margin-sidebar";
function scriptFileForScripts(scripts, temp) {
  const scriptFile2 = temp.createFile({ suffix: "-listing.html" });
  const contents = `<script>
${scripts.join("\n")}<\/script>`;
  Deno.writeTextFileSync(scriptFile2, contents);
  return scriptFile2;
}
function listingSassBundle() {
  const scssPath = resourcePath("projects/website/listing/quarto-listing.scss");
  const layer = sassLayer(scssPath);
  return {
    dependency: kBootstrapDependencyName,
    key: scssPath,
    quarto: {
      name: "quarto-listing.css",
      ...layer
    }
  };
}

// project/types/website/website-giscus.ts
init_fs();
init_path();

// core/giscus.ts
function getDiscussionCategoryId(categoryName, metadata) {
  if (metadata.categories) {
    for (const category of metadata.categories) {
      if (category.name === categoryName) {
        return category.id;
      }
    }
  }
  return void 0;
}
async function getGithubDiscussionsMetadata(repo) {
  const url = encodeURI(
    `https://giscus.app/api/discussions/categories?repo=${repo}`
  );
  const response = await fetch(url);
  const jsonObj = await response.json();
  return jsonObj;
}
var buildGiscusThemeKeys = (darkModeDefault2, theme) => {
  if (typeof theme === "string") {
    if (theme.length > 0) {
      return { baseTheme: theme, altTheme: theme };
    } else {
      theme = { light: "light" /* light */, dark: "dark" /* dark */ };
    }
  }
  const themeRecord = theme;
  const result2 = {
    baseTheme: themeRecord.light ?? "light" /* light */,
    altTheme: themeRecord.dark ?? "dark" /* dark */
  };
  if (darkModeDefault2) {
    [result2.baseTheme, result2.altTheme] = [result2.altTheme, result2.baseTheme];
  }
  return result2;
};

// project/types/website/website-giscus.ts
init_path2();
init_format_html_shared();
init_project_scratch();
var kGiscusDir = "giscus";
async function resolveFormatForGiscus(project, format14) {
  const comments = format14.metadata[kComments];
  if (!comments) return;
  const giscusOptions = comments[kGiscus];
  if (!giscusOptions) return;
  if (giscusOptions[kGiscusRepoId] !== void 0 && giscusOptions[kGiscusCategoryId] !== void 0) return;
  const repo = giscusOptions.repo;
  const fileName = `${repo}.json`;
  let giscusMeta;
  const giscusPath = projectScratchPath(project.dir, kGiscusDir);
  ensureDirSync(giscusPath);
  const path3 = join4(
    giscusPath,
    fileName.replace("/", ".")
  );
  try {
    const giscusJson = Deno.readTextFileSync(path3);
    giscusMeta = JSON.parse(giscusJson);
  } catch {
    removeIfExists(path3);
    giscusMeta = await getGithubDiscussionsMetadata(repo);
    const jsonStr = JSON.stringify(giscusMeta, void 0, 2);
    Deno.writeTextFileSync(path3, jsonStr);
  }
  if (giscusOptions[kGiscusRepoId] === void 0) {
    giscusOptions[kGiscusRepoId] = giscusMeta.repositoryId;
  }
  if (giscusOptions[kGiscusCategoryId] === void 0) {
    giscusOptions[kGiscusCategoryId] = getDiscussionCategoryId(
      giscusOptions[kGiscusCategoryId] || "",
      giscusMeta
    );
  }
}

// project/types/website/website.ts
await init_extension();

// project/types/website/website-draft.ts
var kDraftStatus = "draft-remove";
var websiteDraftPostProcessor = (doc) => {
  const documentStatusEl = doc.querySelector("meta[name='quarto:status']");
  if (documentStatusEl !== null) {
    const status = documentStatusEl.getAttribute("content");
    if (status === kDraftStatus && doc.documentElement) {
      doc.documentElement.innerHTML = "";
    }
  }
  return Promise.resolve({
    resources: [],
    supporting: []
  });
};

// project/types/website/website-llms.ts
init_path();
init_fs();
init_path2();
init_process();
init_resources2();
init_types4();
await init_project_shared();
init_website_constants();
init_website_constants();
function computeOutputFilePath(source2, project) {
  const outputDir = projectOutputDir(project);
  const sourceRelative = relative4(project.dir, source2);
  const htmlHref = inputFileHref(sourceRelative);
  return join4(outputDir, htmlHref.slice(1));
}
function llmsHtmlFinalizer(source2, project, _format5) {
  return async (doc) => {
    if (!websiteConfigBoolean(kLlmsTxt, false, project.config)) {
      return;
    }
    const draftMode = projectDraftMode(project);
    const statusEl = doc.querySelector("meta[name='quarto:status']");
    const status = statusEl?.getAttribute("content");
    const isDraftByStatus = status === "draft" || status === "draft-remove";
    const sourceRelative = relative4(project.dir, source2);
    const isDraftByConfig = isProjectDraft(sourceRelative, project);
    const isDraft = isDraftByStatus || isDraftByConfig;
    if (isDraft && !isDraftVisible(draftMode)) {
      return;
    }
    const htmlContent = extractMainContent(doc);
    const outputFile5 = computeOutputFilePath(source2, project);
    const llmsOutputPath = outputFile5.replace(/\.html$/, ".llms.md");
    await convertHtmlToLlmsMarkdown(htmlContent, llmsOutputPath);
    cleanupConditionalContent(doc);
  };
}
function cleanupConditionalContent(doc) {
  for (const el of doc.querySelectorAll(".llms-conditional-content")) {
    el.remove();
  }
  for (const el of doc.querySelectorAll(".llms-hidden-content")) {
    const parent = el.parentElement;
    if (parent) {
      const element = el;
      while (element.firstChild) {
        parent.insertBefore(element.firstChild, element);
      }
      element.remove();
    }
  }
}
function extractMainContent(doc) {
  const clone = doc.cloneNode(true);
  const selectorsToRemove = [
    "#quarto-header",
    ".nav-footer",
    "#quarto-sidebar",
    "#quarto-margin-sidebar",
    "#quarto-search-results",
    ".sidebar",
    ".quarto-search",
    "nav.navbar",
    ".quarto-page-breadcrumbs",
    "script",
    "style",
    "link[rel='stylesheet']",
    "meta",
    "noscript"
  ];
  for (const selector of selectorsToRemove) {
    const elements = clone.querySelectorAll(selector);
    for (const el of elements) {
      el.remove();
    }
  }
  const main2 = clone.querySelector("main") || clone.querySelector("#quarto-document-content") || clone.querySelector("article") || clone.querySelector("body");
  if (!main2) {
    return "";
  }
  preprocessAnnotatedCodeBlocks(clone, main2);
  return `<!DOCTYPE html>
<html>
<head><meta charset="utf-8"></head>
<body>
${main2.innerHTML}
</body>
</html>`;
}
function preprocessAnnotatedCodeBlocks(doc, container) {
  const annotated = container.querySelectorAll("[data-llms-code-original]");
  for (const node of annotated) {
    const el = node;
    const originalText = el.getAttribute("data-llms-code-original");
    if (!originalText) continue;
    const codeEl = el.tagName === "CODE" ? el : el.querySelector("code");
    if (codeEl) {
      codeEl.textContent = originalText;
    }
    el.removeAttribute("data-llms-code-original");
  }
  const gutters = container.querySelectorAll(
    ".code-annotation-gutter, .code-annotation-gutter-bg"
  );
  for (const gutter of gutters) {
    gutter.remove();
  }
  const dls = container.querySelectorAll("dl.code-annotation-container-grid");
  for (const dlNode of dls) {
    const dl = dlNode;
    const ol = doc.createElement("ol");
    const dds = dl.querySelectorAll("dd");
    for (const ddNode of dds) {
      const dd = ddNode;
      const li = doc.createElement("li");
      li.innerHTML = dd.innerHTML;
      ol.appendChild(li);
    }
    const parent = dl.parentElement;
    if (parent && parent.classList.contains("cell-annotation")) {
      parent.parentElement?.replaceChild(ol, parent);
    } else {
      dl.parentElement?.replaceChild(ol, dl);
    }
  }
}
async function convertHtmlToLlmsMarkdown(htmlContent, outputPath) {
  const filterPath = resourcePath("filters/llms/llms.lua");
  const tempDir2 = Deno.makeTempDirSync();
  const tempHtml = join4(tempDir2, "input.html");
  Deno.writeTextFileSync(tempHtml, htmlContent);
  try {
    const cmd = [pandocBinaryPath()];
    cmd.push(tempHtml);
    cmd.push("-f", "html");
    cmd.push("-t", "gfm-raw_html");
    cmd.push("--lua-filter", filterPath);
    cmd.push("-o", outputPath);
    cmd.push("--wrap=none");
    const result2 = await execProcess({
      cmd: cmd[0],
      args: cmd.slice(1),
      stdout: "piped",
      stderr: "piped"
    });
    if (!result2.success) {
      console.error(`Error converting HTML to markdown: ${result2.stderr}`);
    }
  } finally {
    try {
      Deno.removeSync(tempDir2, { recursive: true });
    } catch {
    }
  }
}
async function updateLlmsTxt(context, outputFiles, incremental) {
  if (!websiteConfigBoolean(kLlmsTxt, false, context.config)) {
    return;
  }
  const outputDir = projectOutputDir(context);
  const llmsTxtPath = join4(outputDir, "llms.txt");
  if (incremental && existsSync2(llmsTxtPath)) {
    return;
  }
  const firstFileMeta = outputFiles.length > 0 ? outputFiles[0].format.metadata[kWebsite] : void 0;
  const siteTitle = firstFileMeta?.title || websiteTitle(context.config) || "Untitled";
  const siteDesc = firstFileMeta?.description || websiteDescription(context.config) || "";
  const baseUrl = websiteBaseurl(context.config);
  const draftMode = projectDraftMode(context);
  const isDraft = async (outputFile5) => {
    const index2 = await resolveInputTargetForOutputFile(
      context,
      relative4(outputDir, outputFile5.file)
    );
    return index2?.draft ?? false;
  };
  const doc404 = join4(outputDir, kProject404File);
  const llmsFiles = [];
  for (const file of outputFiles) {
    if (file.file === doc404) {
      continue;
    }
    const draft = await isDraft(file);
    if (draft && !isDraftVisible(draftMode)) {
      continue;
    }
    const llmsPath = file.file.replace(/\.html$/, ".llms.md");
    if (existsSync2(llmsPath)) {
      const title3 = file.format.metadata?.title || basename4(file.file, ".html");
      const relativePath = pathWithForwardSlashes(
        relative4(outputDir, llmsPath)
      );
      const filePath = baseUrl ? (baseUrl.endsWith("/") ? baseUrl : baseUrl + "/") + relativePath : relativePath;
      llmsFiles.push({
        path: filePath,
        title: title3
      });
    }
  }
  const lines2 = [];
  lines2.push(`# ${siteTitle}`);
  lines2.push("");
  if (siteDesc) {
    lines2.push(`> ${siteDesc}`);
    lines2.push("");
  }
  lines2.push("## Pages");
  lines2.push("");
  for (const f5 of llmsFiles) {
    lines2.push(`- [${f5.title}](${f5.path})`);
  }
  lines2.push("");
  Deno.writeTextFileSync(llmsTxtPath, lines2.join("\n"));
}

// project/types/website/website.ts
init_codegen();
init_array();

// format/html/format-html-title.ts
init_fs();
init_path();
init_constants6();
init_resources2();
init_sass();
var kTitleBlockStyle = "title-block-style";
var kTitleBlockBanner = "title-block-banner";
var ktitleBlockColor = "title-block-banner-color";
var kTitleBlockCategories = "title-block-categories";
function documentTitleScssLayer(format14) {
  if (format14.metadata[kTitleBlockStyle] === false || format14.metadata[kTitleBlockStyle] === "none" || format14.metadata[kTitleBlockStyle] === "plain") {
    return void 0;
  } else if (format14.metadata[kTitleBlockStyle] === "manuscript") {
    const titleBlockScss = formatResourcePath(
      "html",
      join4("templates", "title-block.scss")
    );
    return sassLayer(titleBlockScss);
  } else {
    const titleBlockScss = formatResourcePath(
      "html",
      join4("templates", "title-block.scss")
    );
    return sassLayer(titleBlockScss);
  }
}
function documentTitleMetadata(format14) {
  if (format14.metadata[kTitleBlockStyle] !== false && format14.metadata[kTitleBlockStyle] !== "none" && format14.metadata[kDateFormat] === void 0) {
    return {
      [kDateFormat]: "long"
    };
  } else {
    return void 0;
  }
}
function documentTitleIncludeInHeader(input, format14, temp) {
  const headingVars = [];
  const containerVars = [];
  const banner = format14.metadata[kTitleBlockBanner];
  if (banner) {
    const titleBlockColor = titleColor(format14.metadata[ktitleBlockColor]);
    if (titleBlockColor) {
      const color = `color: ${titleBlockColor};`;
      headingVars.push(color);
      containerVars.push(color);
    }
    if (banner === true) {
    } else if (isBannerImage(input, banner)) {
      containerVars.push(`background-image: url(${banner});`);
      containerVars.push(`background-size: cover;`);
    } else {
      containerVars.push(`background: ${banner};`);
    }
  }
  if (headingVars.length || containerVars.length) {
    const styles = ["<style>"];
    if (headingVars.length) {
      styles.push(`
      .quarto-title-block .quarto-title-banner h1,
      .quarto-title-block .quarto-title-banner h2,
      .quarto-title-block .quarto-title-banner h3,
      .quarto-title-block .quarto-title-banner h4,
      .quarto-title-block .quarto-title-banner h5,
      .quarto-title-block .quarto-title-banner h6
      {
        ${headingVars.join("\n")}
      }`);
    }
    if (containerVars.length) {
      styles.push(`
      .quarto-title-block .quarto-title-banner {
        ${containerVars.join("\n")}
      }`);
    }
    styles.push("</style>");
    const file = temp.createFile({ suffix: ".css" });
    Deno.writeTextFileSync(file, styles.join("\n"));
    return file;
  }
}
function documentTitlePartial(format14) {
  if (format14.metadata[kTitleBlockStyle] === false || format14.metadata[kTitleBlockStyle] === "none") {
    return {
      partials: [],
      templateParams: {}
    };
  } else {
    const partials = [];
    const templateParams = {};
    templateParams[kTitleBlockCategories] = format14.metadata[kTitleBlockCategories] !== false ? "true" : "";
    const banner = format14.metadata[kTitleBlockBanner];
    const manuscriptTitle = format14.metadata[kTitleBlockStyle] === "manuscript";
    partials.push("_title-meta-author.html");
    partials.push("title-metadata.html");
    if (manuscriptTitle) {
      partials.push("manuscript/title-block.html");
      partials.push("manuscript/title-metadata.html");
    } else if (banner) {
      partials.push("banner/title-block.html");
    } else {
      partials.push("title-block.html");
    }
    if (banner || manuscriptTitle) {
      const tocLeft = format14.metadata[kTocLocation] === "left";
      if (tocLeft) {
        templateParams["banner-header-class"] = "toc-left";
      }
    }
    return {
      partials: partials.map((partial) => {
        return formatResourcePath("html", join4("templates", partial));
      }),
      templateParams
    };
  }
}
async function canonicalizeTitlePostprocessor(doc, _options) {
  const titleBlock = doc.querySelector("header.quarto-title-block");
  const main2 = doc.querySelector("main");
  if (!titleBlock && main2) {
    const header = doc.createElement("header");
    header.id = "title-block-header";
    header.classList.add("quarto-title-block");
    main2.insertBefore(header, main2.firstChild);
    const h1s = Array.from(doc.querySelectorAll("h1"));
    for (const h1n of h1s) {
      const h1 = h1n;
      if (h1.classList.contains("quarto-secondary-nav-title")) {
        continue;
      }
      if (h1.parentElement?.tagName === "SECTION") {
        if (h1.parentElement?.parentElement?.firstElementChild !== h1.parentElement) {
          continue;
        }
      } else {
        if (h1.parentElement?.firstElementChild !== h1) {
          continue;
        }
      }
      const div = doc.createElement("div");
      div.classList.add("quarto-title-banner");
      h1.classList.add("title");
      header.appendChild(h1);
      break;
    }
  }
  return {
    resources: [],
    supporting: []
  };
}
function processDocumentTitle(input, format14, _flags, doc) {
  const resources = [];
  const banner = format14.metadata[kTitleBlockBanner];
  const manuscriptTitle = format14.metadata[kTitleBlockStyle] === "manuscript";
  if (banner || manuscriptTitle) {
    const headerEl = doc.getElementById("title-block-header");
    const contentEl = doc.getElementById("quarto-content");
    if (contentEl && headerEl) {
      headerEl.remove();
      contentEl.parentElement?.insertBefore(headerEl, contentEl);
    }
    const mainEl = doc.querySelector("main.content");
    mainEl?.classList.add("quarto-banner-title-block");
    if (isBannerImage(input, banner)) {
      resources.push(banner);
    }
    const quartoHeaderEl = doc.getElementById("quarto-header");
    if (quartoHeaderEl) {
      quartoHeaderEl.classList.add("quarto-banner");
    }
  }
  return resources;
}
function isBannerImage(input, banner) {
  if (typeof banner === "string") {
    let path3;
    if (isAbsolute4(banner)) {
      path3 = banner;
    } else {
      path3 = join4(dirname4(input), banner);
    }
    return existsSync2(path3);
  } else {
    return false;
  }
}
var titleColor = (block) => {
  if (block === "body" || block === "body-bg") {
    return void 0;
  } else {
    return block;
  }
};

// project/types/website/website.ts
init_brand();
var kSiteTemplateDefault = "default";
var kSiteTemplateBlog = "blog";
var websiteProjectType = {
  type: kWebsite,
  typeAliases: ["site"],
  templates: [kSiteTemplateDefault, kSiteTemplateBlog],
  create: (title3, template2) => {
    const resourceDir = resourcePath(join4("projects", "website"));
    return websiteTemplate(resourceDir, title3, template2);
  },
  libDir: "site_libs",
  outputDir: "_site",
  cleanOutputDir: true,
  formatLibDirs: () => defaultProjectType.formatLibDirs().concat(["quarto-nav", "quarto-search"]),
  config: websiteProjectConfig,
  metadataFields: websiteMetadataFields,
  resourceIgnoreFields: () => [kWebsite, "site"],
  preRender: async (context) => {
    await initWebsiteNavigation(context);
  },
  supplementRender: (project, files, incremental) => {
    const listingSupplements = listingSupplementalFiles(
      project,
      files,
      incremental
    );
    return listingSupplements;
  },
  formatExtras: async (project, source2, flags, format14, services) => {
    if (!isHtmlFileOutput(format14.pandoc)) {
      return Promise.resolve({});
    }
    const extras = formatHasBootstrap(format14) ? await websiteNavigationExtras(
      project,
      source2,
      flags,
      format14,
      services.temp
    ) : await websiteNoThemeExtras(
      project,
      source2,
      flags,
      format14,
      services.temp
    );
    extras.pandoc = extras.pandoc || {};
    extras.metadata = extras.metadata || {};
    extras.metadataOverride = extras.metadataOverride || {};
    resolveFormatForGiscus(project, format14);
    const title3 = websiteTitle(project.config);
    if (title3) {
      extras.pandoc = {
        [kTitlePrefix]: title3
      };
    }
    let favicon = websiteConfigString(kSiteFavicon, project.config);
    if (!favicon) {
      const brand = await project.resolveBrand();
      if (brand?.light) {
        favicon = getFavicon(brand.light);
      }
    }
    if (favicon) {
      const offset4 = projectOffset(project, source2);
      extras.html = extras.html || {};
      extras.html.dependencies = extras.html.dependencies || [];
      extras.html.dependencies.push({
        name: kSiteFavicon,
        links: [{
          rel: "icon",
          href: offset4 + "/" + favicon,
          type: contentType(favicon)
        }]
      });
    }
    const offset3 = projectOffset(project, source2);
    const [_dir, stem] = dirAndStem(source2);
    const home = stem === "index" && offset3 === ".";
    if (home && !format14.metadata[kTitle] && !format14.metadata[kPageTitle] && title3) {
      extras.metadata[kPageTitle] = title3;
    }
    if (format14.metadata[kFieldCategories]) {
      extras.metadataOverride[kFieldCategories] = asArray(
        format14.metadata[kFieldCategories]
      ).map(
        (category) => {
          const strCategory = typeof category === "string" ? category : category.toString();
          return pandocNativeStr(strCategory).mappedString().value;
        }
      );
    }
    extras.html = extras.html || {};
    extras.html[kHtmlPostprocessors] = extras.html[kHtmlPostprocessors] || [];
    extras.html[kHtmlFinalizers] = extras.html[kHtmlFinalizers] || [];
    extras.html[kMarkdownAfterBody] = extras.html[kMarkdownAfterBody] || [];
    extras.html[kHtmlPostprocessors].push(...[
      htmlResourceResolverPostprocessor(
        source2,
        project,
        projectExtensionPathResolver(
          project.config?.project[kProjectLibDir] || "",
          project.dir
        )
      )
    ]);
    extras.html[kHtmlPostprocessors].unshift(
      websiteDraftPostProcessor,
      // Fix H1 title inconsistency
      canonicalizeTitlePostprocessor
    );
    const hasBootstrap = formatHasBootstrap(format14);
    const htmlListingDependencies = await listingHtmlDependencies(
      source2,
      project,
      format14,
      services.temp,
      extras
    );
    if (htmlListingDependencies) {
      const listingPostProcessor = htmlListingDependencies[kHtmlPostprocessors];
      if (listingPostProcessor) {
        extras.html[kHtmlPostprocessors]?.unshift(listingPostProcessor);
      }
      const listingAfterBody = htmlListingDependencies[kMarkdownAfterBody];
      if (listingAfterBody) {
        extras.html[kMarkdownAfterBody]?.push(listingAfterBody);
      }
      extras[kIncludeInHeader] = extras[kIncludeInHeader] || [];
      extras[kIncludeInHeader].push(
        ...htmlListingDependencies[kIncludeInHeader]
      );
      extras.html[kSassBundles] = extras.html[kSassBundles] || [];
      extras.html[kSassBundles].push(
        ...htmlListingDependencies[kSassBundles]
      );
      extras.html[kDependencies] = extras.html[kDependencies] || [];
      extras.html[kDependencies]?.push(
        ...htmlListingDependencies[kDependencies]
      );
    }
    if (hasBootstrap) {
      const aboutDependencies = await aboutHtmlDependencies(
        source2,
        project,
        format14,
        services.temp,
        extras
      );
      if (aboutDependencies) {
        const aboutPostProcessor = aboutDependencies[kHtmlPostprocessors];
        if (aboutPostProcessor) {
          extras.html[kHtmlPostprocessors]?.push(aboutPostProcessor);
        }
        extras.html[kSassBundles] = extras.html[kSassBundles] || [];
        extras.html[kSassBundles].push(
          ...aboutDependencies[kSassBundles]
        );
        extras.html[kMarkdownAfterBody].push(
          ...aboutDependencies[kMarkdownAfterBody]
        );
      }
    }
    const htmlMetadataDependencies = metadataHtmlDependencies(
      source2,
      project,
      format14,
      extras
    );
    extras.html[kHtmlPostprocessors].push(
      htmlMetadataDependencies[kHtmlPostprocessors]
    );
    extras.html[kMarkdownAfterBody].push(
      htmlMetadataDependencies[kMarkdownAfterBody]
    );
    const analyticsDependency = websiteAnalyticsScriptFile(
      project,
      services.temp
    );
    if (analyticsDependency) {
      extras[kIncludeInHeader] = extras[kIncludeInHeader] || [];
      extras[kIncludeInHeader]?.push(analyticsDependency);
    }
    const cookieDep = cookieConsentDependencies(
      project,
      format14,
      services.temp
    );
    if (cookieDep) {
      extras[kIncludeInHeader] = extras[kIncludeInHeader] || [];
      extras[kIncludeInHeader]?.push(
        cookieDep.scriptFile
      );
      extras.html[kDependencies] = extras.html[kDependencies] || [];
      extras.html[kDependencies].push(cookieDep.dependency);
      extras.html[kHtmlPostprocessors].push(cookieDep.htmlPostProcessor);
    }
    if (websiteConfigBoolean(kLlmsTxt, false, project.config)) {
      extras[kFilterParams] = extras[kFilterParams] || {};
      extras[kFilterParams]["llms-txt"] = true;
      extras.html[kHtmlFinalizers]?.push(
        llmsHtmlFinalizer(source2, project, format14)
      );
    }
    return Promise.resolve(extras);
  },
  postRender: async (context, incremental, outputFiles) => {
    await websitePostRender(
      context,
      incremental,
      websiteOutputFiles(outputFiles)
    );
  },
  filterInputTarget: (inputTarget, context) => {
    const drafts = websiteConfigArray(kDrafts, context.config);
    const isDraft = drafts?.some((val) => {
      return val === inputTarget.input;
    });
    if (isDraft) {
      inputTarget.draft = true;
    }
    return inputTarget;
  },
  filterParams: async (options) => {
    if (options.project) {
      const draftMode = projectDraftMode(options.project);
      const drafts = websiteConfigArray(kDrafts, options.project.config);
      if (drafts || draftMode) {
        const draftsAbs = (drafts || []).map((path3) => {
          return join4(options.project.dir, path3);
        });
        return {
          [kDraftMode]: draftMode,
          [kDrafts]: draftsAbs
        };
      }
    }
    return void 0;
  }
};
async function websitePostRender(context, incremental, outputFiles) {
  const doc404 = join4(projectOutputDir(context), kProject404File);
  outputFiles = outputFiles.filter((file) => {
    return file.file !== doc404;
  });
  await updateSitemap(context, outputFiles, incremental);
  await updateSearchIndex(context, outputFiles, incremental);
  completeListingGeneration(context, outputFiles, incremental);
  await updateAliases(context, outputFiles, incremental);
  await updateLlmsTxt(context, outputFiles, incremental);
  await ensureIndexPage(context);
}
function websiteOutputFiles(outputFiles) {
  return outputFiles.filter((outputFile5) => {
    return isHtmlFileOutput(outputFile5.format.pandoc);
  }).map((outputFile5) => {
    const contents = Deno.readTextFileSync(outputFile5.file);
    const doctypeMatch = contents.match(/^<!DOCTYPE.*?>/);
    return {
      ...outputFile5,
      // doc,
      doctype: doctypeMatch ? doctypeMatch[0] : void 0
    };
  });
}
function websiteTemplate(resourceDir, title3, template2) {
  if (template2 === kSiteTemplateBlog) {
    const today2 = /* @__PURE__ */ new Date();
    const secondPostDateStr = formatDate(today2, "iso");
    today2.setDate(today2.getDate() - 3);
    const firstPostDateStr = formatDate(today2, "iso");
    return {
      configTemplate: join4(
        resourceDir,
        "templates",
        "blog",
        "_quarto-blog.ejs.yml"
      ),
      resourceDir,
      scaffold: () => [
        {
          name: "index",
          content: "",
          noEngineContent: true,
          title: title3,
          yaml: 'listing:\n  contents: posts\n  feed: true\n  sort: "date desc"\n  type: default\n  categories: true\n  sort-ui: false\n  filter-ui: false\npage-layout: full\ntitle-block-banner: true'
        },
        {
          name: "index",
          subdirectory: "posts/welcome",
          title: "Welcome To My Blog",
          content: "This is the first post in a Quarto blog. Welcome!\n\n![](thumbnail.jpg)\n\nSince this post doesn't specify an explicit `image`, the first image in the post will be used in the listing page of posts.",
          noEngineContent: true,
          yaml: `author: "Tristan O'Malley"
date: "${firstPostDateStr}"
categories: [news]`,
          supporting: [
            join4(resourceDir, "templates", "blog", "thumbnail.jpg")
          ]
        },
        {
          name: "index",
          subdirectory: "posts/post-with-code",
          title: "Post With Code",
          content: "This is a post with executable code.",
          yaml: `author: "Harlow Malloc"
date: "${secondPostDateStr}"
categories: [news, code, analysis]
image: "image.jpg"`,
          supporting: [
            join4(resourceDir, "templates", "blog", "image.jpg")
          ]
        },
        {
          name: "about",
          title: "About",
          content: "About this blog",
          yaml: `image: profile.jpg
about:
  template: jolla
  links:
    - icon: bluesky
      text: Bluesky
      href: https://bsky.app/
    - icon: linkedin
      text: LinkedIn
      href: https://linkedin.com
    - icon: github
      text: Github
      href: https://github.com
`,
          supporting: [
            join4(resourceDir, "templates", "blog", "profile.jpg")
          ],
          noEngineContent: true
        }
      ],
      supporting: [
        "styles.css",
        {
          from: join4("templates", "blog", "_metadata.yml"),
          to: join4("posts", "_metadata.yml")
        }
      ]
    };
  } else {
    return {
      configTemplate: join4(resourceDir, "templates", "_quarto.ejs.yml"),
      resourceDir,
      scaffold: () => [
        {
          name: "index",
          content: "This is a Quarto website.\n\nTo learn more about Quarto websites visit <https://quarto.org/docs/websites>.",
          title: title3
        },
        {
          name: "about",
          content: "About this site",
          title: "About"
        }
      ],
      supporting: [
        "styles.css"
      ]
    };
  }
}

// project/types/book/book-render.ts
init_path();
init_base64();
init_lodash();
init_pandoc_partition();
init_constants6();
init_format5();
await init_render_contexts();
await init_engine();

// project/types/book/book-extension.ts
init_path();
init_constants6();
init_formats();
await init_project_shared();

// project/types/book/book-config.ts
init_fs();
init_path();
init_lodash();
init_path2();
await init_engine();
init_formats();
init_types4();
init_website_constants();
init_book_constants();
init_book_shared();
init_constants6();
init_language();
init_format_html_shared();
init_schema_types();
init_project_types();
init_http();
init_brand();
async function bookProjectConfig(project, config2, flags) {
  const projectDir = project.dir;
  const site = config2[kWebsite] || {};
  config2[kWebsite] = site;
  const book = config2[kBook];
  if (book) {
    site[kSiteTitle] = book[kSiteTitle];
    site[kSiteFavicon] = book[kSiteFavicon];
    if (!site[kSiteFavicon]) {
      const brand = await project.resolveBrand();
      if (brand?.light) {
        site[kSiteFavicon] = getFavicon(brand.light);
      }
    }
    site[kSiteUrl] = book[kSiteUrl];
    site[kSitePath] = book[kSitePath];
    site[kSiteRepoUrl] = book[kSiteRepoUrl];
    site[kSiteRepoLinkTarget] = book[kSiteRepoLinkTarget];
    site[kSiteRepoLinkRel] = book[kSiteRepoLinkRel];
    site[kSiteRepoSubdir] = book[kSiteRepoSubdir];
    site[kSiteRepoBranch] = book[kSiteRepoBranch];
    site[kSiteRepoActions] = book[kSiteRepoActions];
    site[kSiteIssueUrl] = book[kSiteIssueUrl];
    site[kSiteNavbar] = book[kSiteNavbar];
    site[kSiteSidebar] = book[kSiteSidebar];
    site[kSitePageNavigation] = book[kSitePageNavigation] !== false;
    site[kOpenGraph] = book[kOpenGraph];
    site[kTwitterCard] = book[kTwitterCard];
    site[kImage] = book[kImage];
    site[kMarginHeader] = book[kMarginHeader];
    site[kMarginFooter] = book[kMarginFooter];
    site[kBodyHeader] = book[kBodyHeader];
    site[kBodyFooter] = book[kBodyFooter];
    site[kBookSearch] = book[kBookSearch];
    site[kSiteReaderMode] = book[kSiteReaderMode];
    site[kGoogleAnalytics] = book[kGoogleAnalytics];
    site[kCookieConsent] = book[kCookieConsent];
    site[kComments] = book[kComments];
    site[kBreadCrumbNavigation] = book[kBreadCrumbNavigation];
    site[kOtherLinks] = book[kOtherLinks];
    site[kCodeLinks] = book[kCodeLinks];
    if (book[kPageFooter]) {
      site[kPageFooter] = book[kPageFooter];
    }
  }
  const language = await formatLanguage(
    config2,
    config2[kLanguageDefaults],
    flags
  );
  site[kSiteSidebar] = site[kSiteSidebar] || {};
  const siteSidebar = site[kSiteSidebar];
  siteSidebar[kSiteTitle] = siteSidebar[kSiteTitle] || book?.[kSiteTitle];
  siteSidebar[kSidebarLogo] = siteSidebar[kSidebarLogo] ?? book?.[kSidebarLogo];
  siteSidebar[kSidebarLogoHref] = siteSidebar[kSidebarLogoHref] || book?.[kSidebarLogoHref];
  siteSidebar[kSidebarLogoAlt] = siteSidebar[kSidebarLogoAlt] || book?.[kSidebarLogoAlt];
  siteSidebar[kContents] = [];
  const bookContents = bookConfig(kBookChapters, config2);
  if (Array.isArray(bookContents)) {
    siteSidebar[kContents] = bookChaptersToSidebarItems(
      bookContents
    );
  }
  const bookReferences = bookConfig(kBookReferences, config2);
  if (bookReferences) {
    siteSidebar[kContents].push(bookReferences);
  }
  const bookAppendix = bookConfig(kBookAppendix, config2);
  if (Array.isArray(bookAppendix)) {
    siteSidebar[kContents] = siteSidebar[kContents].concat([
      chapterToSidebarItem({
        part: language[kSectionTitleAppendices],
        chapters: bookAppendix
      })
    ]);
  }
  siteSidebar[kSiteSidebarStyle] = siteSidebar[kSiteSidebarStyle] || "floating";
  const tools = [];
  if (site[kSiteRepoUrl]) {
    const repoUrl = siteRepoUrl(site);
    const icon = repoUrlIcon(repoUrl);
    const tool = {
      text: language[kCodeToolsSourceCode] || "Source Code",
      icon,
      href: repoUrl
    };
    const linkTarget = websiteConfigString(kSiteRepoLinkTarget, config2);
    if (linkTarget) {
      tool.target = linkTarget;
    }
    const linkRel = websiteConfigString(kSiteRepoLinkRel, config2);
    if (linkRel) {
      tool.rel = linkRel;
    }
    tools.push(tool);
  }
  tools.push(...downloadTools(projectDir, config2, language) || []);
  tools.push(...sharingTools(config2, language) || []);
  if (site[kSiteNavbar]) {
    site[kSiteNavbar][kBookTools] = tools;
  } else {
    siteSidebar[kBookTools] = siteSidebar[kBookTools] || [];
    siteSidebar[kBookTools].push(...tools);
  }
  const renderItems = await bookRenderItems(project, language, config2);
  book[kBookRender] = renderItems;
  config2.project[kProjectRender] = renderItems.filter((target) => !!target.file).map((target) => target.file);
  const footerFiles = [];
  const pageFooter = resolvePageFooter(config2);
  const addFooterItems = (region) => {
    if (!region || typeof region === "string") return;
    for (const item of region) {
      const navItem = Zod.NavigationItemObject.parse(item);
      if (navItem.href && !isAbsoluteRef(navItem.href)) {
        footerFiles.push(navItem.href);
      }
    }
  };
  addFooterItems(pageFooter.left);
  addFooterItems(pageFooter.right);
  addFooterItems(pageFooter.center);
  config2.project[kProjectRender].push(...footerFiles);
  const ext404 = engineValidExtensions().find(
    (ext) => existsSync2(join4(projectDir, `404${ext}`))
  );
  if (ext404) {
    config2.project[kProjectRender].push(`404${ext404}`);
  }
  return await websiteProjectConfig(project, config2);
}
function siteRepoUrl(site) {
  const repoUrl = site[kSiteRepoUrl];
  const branch = site[kSiteRepoBranch] || "main";
  if (site[kSiteRepoSubdir]) {
    const subdir = ensureTrailingSlash(site[kSiteRepoSubdir]);
    return `${ensureTrailingSlash(repoUrl)}tree/${branch}/${subdir}`;
  } else {
    return repoUrl;
  }
}
function bookConfigRenderItems(project) {
  return bookConfig(
    kBookRender,
    project
  );
}
async function bookRenderItems(project, language, config2) {
  const projectDir = project.dir;
  if (!config2) {
    return [];
  }
  let nextNumber = 1;
  const inputs = [];
  const findInputs = async (type4, items, depth = 0) => {
    const throwInputNotFound = (input) => {
      throw new Error(`Book ${type4} '${input}' not found`);
    };
    for (const item of items) {
      if (item.contents) {
        inputs.push({
          type: kBookItemPart,
          file: item.href,
          text: item.text,
          depth
        });
        await findInputs(type4, item.contents, depth + 1);
      } else if (item.href) {
        const itemPath = join4(projectDir, item.href);
        if (safeExistsSync(itemPath)) {
          const engine = await fileExecutionEngine(
            itemPath,
            void 0,
            project
          );
          if (engine) {
            let number2;
            if (type4 === kBookItemChapter && await inputIsNumbered(project, item.href)) {
              number2 = nextNumber++;
            }
            inputs.push({
              type: type4,
              file: item.href,
              number: number2,
              depth
            });
          }
        } else {
          throwInputNotFound(item.href);
        }
      } else if (item.text && !item.text.trim().match(/^-+$/)) {
        throwInputNotFound(item.text);
      }
    }
  };
  const context = sidebarContext();
  const findChapters = async (key, delimiter6) => {
    nextNumber = 1;
    const bookInputs = bookConfig(key, config2);
    if (bookInputs) {
      if (delimiter6) {
        inputs.push(delimiter6);
      }
      await findInputs(
        kBookItemChapter,
        bookChaptersToSidebarItems(bookInputs).map((item) => normalizeSidebarItem(projectDir, item, context)),
        key === "chapters" ? 0 : 1
        // next chapters under appendices, so start depth at level 1 (under appendix)
      );
    }
  };
  await findChapters(kBookChapters);
  const references = bookConfig("references", config2);
  if (references) {
    await findInputs(kBookItemChapter, [
      normalizeSidebarItem(projectDir, references, context)
    ]);
  }
  await findChapters(kBookAppendix, {
    type: kBookItemAppendix,
    text: language[kSectionTitleAppendices] + " {.unnumbered}",
    depth: 0
  });
  const missing = inputs.filter(
    (input) => input.file && !existsSync2(join4(projectDir, input.file))
  );
  if (missing.length) {
    throw new Error(
      "Book contents file(s) do not exist: " + missing.join(", ")
    );
  }
  const indexPos = inputs.findIndex((input) => isBookIndexPage(input.file));
  if (indexPos === -1) {
    throw new Error(
      "Book contents must include a home page (e.g. index.md)"
    );
  }
  const index2 = inputs.splice(indexPos, 1);
  return index2.concat(inputs);
}
var kDownloadableItems = {
  "epub": { name: "ePub", icon: "journal" },
  "pdf": { name: "PDF", icon: "file-pdf" },
  "docx": { name: "Docx", icon: "file-word" }
};
function bookChaptersToSidebarItems(chapters) {
  return chapters.map(chapterToSidebarItem);
}
function chapterToSidebarItem(chapter2) {
  const item = cloneDeep(chapter2);
  if (item.part) {
    item.section = item.part;
    delete item.part;
  }
  if (item.chapters) {
    item.contents = bookChaptersToSidebarItems(item.chapters);
    delete item.chapters;
  }
  return item;
}
function downloadTools(projectDir, config2, language) {
  const downloadActions = websiteConfigActions(kBookDownloads, kBook, config2);
  const filteredActions = downloadActions.filter((action) => {
    const format14 = defaultWriterFormat(action);
    if (format14) {
      return format14.extensions?.book && !isMultiFileBookFormat(format14);
    } else {
      return false;
    }
  });
  const outputStem = bookOutputStem(projectDir, config2);
  const projType = projectType(config2.project.type);
  const downloads = filteredActions.map((action) => {
    const format14 = defaultWriterFormat(action);
    const outputDir = projType.formatOutputDirectory ? projType.formatOutputDirectory(format14) || "" : "";
    const downloadItem = kDownloadableItems[action];
    if (downloadItem) {
      return {
        icon: downloadItem.icon,
        text: `${language[kToolsDownload] || "Download"} ${downloadItem.name}`,
        href: pathWithForwardSlashes(join4(
          "/",
          outputDir,
          `/${outputStem}.${format14.render[kOutputExt]}`
        ))
      };
    } else {
      return {
        text: `Download action}`,
        href: pathWithForwardSlashes(join4(
          "/",
          outputDir,
          `${outputStem}.${format14.render[kOutputExt]}`
        ))
      };
    }
  });
  if (downloads.length === 0) {
    return void 0;
  } else if (downloads.length === 1) {
    return [{
      icon: "download",
      ...downloads[0]
    }];
  } else {
    return [{
      icon: "download",
      text: language[kToolsDownload] || "Download",
      menu: downloads
    }];
  }
}
function sharingTools(projectConfig, language) {
  const sharingActions = websiteConfigActions("sharing", kBook, projectConfig);
  const sidebarTools = [];
  sidebarTools.push(
    ...sharingActions.filter((action) => {
      const sidebarTool = kSharingUrls[action];
      if (sidebarTool) {
        return true;
      } else {
        return false;
      }
    }).map((action) => {
      return kSharingUrls[action];
    })
  );
  if (sidebarTools.length === 0) {
    return void 0;
  } else if (sidebarTools.length === 1) {
    return sidebarTools;
  } else {
    return [{
      text: language[kToolsShare] || "Share",
      icon: kShareIcon,
      menu: sidebarTools
    }];
  }
}
var kShareIcon = "share";
var kSharingUrls = {
  linkedin: {
    icon: "linkedin",
    text: "LinkedIn",
    href: "https://www.linkedin.com/sharing/share-offsite/?url=|url|"
  },
  facebook: {
    icon: "facebook",
    text: "Facebook",
    url: "https://www.facebook.com/sharer/sharer.php?u=|url|"
  },
  twitter: {
    icon: "twitter",
    text: "Twitter",
    url: "https://twitter.com/intent/tweet?url=|url|"
  }
};
async function inputIsNumbered(project, input) {
  const partitioned = await partitionedMarkdownForInput(project, input);
  if (partitioned) {
    return isNumberedChapter(partitioned);
  } else {
    return false;
  }
}

// project/types/book/book-extension.ts
init_format5();
init_book_shared();
function onSingleFileBookPreRender(format14, config2) {
  const extension = format14.extensions?.book;
  if (extension && extension.onSingleFilePreRender) {
    extension.onSingleFilePreRender(format14, config2);
  }
  return format14;
}
function onSingleFileBookPostRender(project, file) {
  const extension = file.format.extensions?.book;
  if (extension && extension.onSingleFilePostRender) {
    extension.onSingleFilePostRender(project, file);
  }
}
async function bookMultiFileHtmlOutputs(context) {
  const renderFiles2 = bookConfigRenderItems(context.config).filter((item) => !!item.file);
  if (renderFiles2.length === 0) {
    return [];
  }
  const index2 = await inputTargetIndex(context, renderFiles2[0].file);
  if (!index2) {
    return [];
  }
  const formatName = Object.keys(index2.formats).find((name2) => {
    if (isMultiFileBookFormat(defaultWriterFormat(name2))) {
      const format14 = index2.formats[name2];
      return isHtmlOutput(format14.pandoc, true) && !!format14.pandoc[kOutputFile];
    } else {
      return false;
    }
  });
  if (!formatName) {
    return [];
  }
  const outputFiles = [];
  for (let i6 = 0; i6 < renderFiles2.length; i6++) {
    const file = renderFiles2[i6].file;
    const index3 = await inputTargetIndex(context, file);
    const outputFile5 = index3?.formats[formatName].pandoc[kOutputFile];
    if (outputFile5) {
      outputFiles.push(
        join4(projectOutputDir(context), dirname4(file), outputFile5)
      );
    }
  }
  return outputFiles;
}

// project/types/book/book-render.ts
init_book_shared();
init_book_constants();

// project/types/book/book-chapters.ts
init_lodash();
init_constants6();
init_book_constants();
init_book_shared();
function withChapterMetadata(format14, headingText, headingAttr, chapterInfo, config2) {
  format14 = cloneDeep(format14);
  if (headingText) {
    format14.metadata[kTitle] = formatChapterTitle(
      format14,
      headingText,
      headingAttr,
      chapterInfo
    );
  }
  format14.metadata[kCrossref] = format14.metadata[kCrossref] || {};
  const crossref = format14.metadata[kCrossref];
  if (headingAttr?.id) {
    crossref[kCrossrefChapterId] = headingAttr?.id;
  }
  if (chapterInfo) {
    format14.pandoc[kNumberOffset] = [chapterInfo.number];
    if (chapterInfo.appendix) {
      crossref[kCrossrefChaptersAppendix] = true;
      crossref[kCrossrefChaptersAlpha] = true;
    }
  } else {
    format14.pandoc[kNumberSections] = false;
  }
  format14.pandoc[kToc] = format14.pandoc[kToc] !== void 0 ? format14.pandoc[kToc] : isListedChapter(headingAttr);
  delete format14.metadata[kDoi];
  const description = bookConfig("description", config2);
  if (description) {
    format14.metadata[kDescription] = description;
  }
  return format14;
}
function isListedChapter(headingAttr) {
  return !headingAttr || !headingAttr.classes.includes("unlisted");
}
function chapterInfoForInput(project, chapterHref) {
  const renderItems = bookConfigRenderItems(project.config);
  const appendixPos = renderItems.findIndex(
    (item) => item.type === kBookItemAppendix
  );
  const itemPos = renderItems.findIndex((item) => item.file === chapterHref);
  if (itemPos !== -1) {
    const appendix2 = appendixPos !== -1 && itemPos > appendixPos;
    const item = renderItems[itemPos];
    if (item.number) {
      return {
        number: item.number,
        appendix: appendix2,
        labelPrefix: appendix2 ? String.fromCharCode(64 + item.number) : item.number.toString()
      };
    } else {
      return void 0;
    }
  } else {
    return void 0;
  }
}
function formatChapterTitle(format14, label, attr, info2) {
  const withIdSpan = (text) => {
    if (!attr?.id) {
      return text;
    } else {
      return `[${text}]{#${attr.id} .quarto-section-identifier}`;
    }
  };
  if (!info2) {
    return withIdSpan(label);
  }
  if (info2.appendix) {
    const crossref = format14.metadata?.crossref;
    const title3 = crossref?.[kCrossrefAppendixTitle] || format14.language[kCrossrefApxPrefix] || "Appendix";
    const delim = crossref?.[kCrossrefAppendixDelim] !== void 0 ? crossref?.[kCrossrefAppendixDelim] : " \u2014";
    return withIdSpan(`${title3} ${info2.labelPrefix}${delim} ${label}`);
  } else {
    if (format14.pandoc[kNumberSections] === false) {
      return withIdSpan(
        `[${label}]{.chapter-title}`
      );
    } else {
      return withIdSpan(
        `[${info2.labelPrefix}]{.chapter-number}\xA0 [${label}]{.chapter-title}`
      );
    }
  }
}
function numberChapterHtmlNav(label, info2) {
  if (info2) {
    return `<span class='chapter-number'>${info2.labelPrefix}</span>\xA0 <span class='chapter-title'>${label}</span>`;
  } else {
    return label;
  }
}

// project/types/book/book-render.ts
init_book_shared();

// project/types/book/book-crossrefs.ts
init_log();
init_path();
init_fs();
init_deno_dom();
init_path2();
init_constants6();
init_formats();
await init_project_shared();
init_book_shared();
async function bookCrossrefsPostRender(context, outputFiles) {
  const projOutput = projectOutputDir(context);
  const crossrefOutputFiles = outputFiles.filter(
    (file) => isMultiFileBookFormat(file.format)
  );
  if (crossrefOutputFiles.length > 0) {
    const indexes = await bookCrossrefIndexes(context);
    for (const outputFile5 of crossrefOutputFiles) {
      const fileRelative = relative4(projOutput, outputFile5.file);
      const index2 = bookCrossrefIndexForOutputFile(fileRelative, indexes);
      if (index2) {
        const doc = await parseHtml(Deno.readTextFileSync(outputFile5.file));
        resolveCrossrefs(
          context,
          fileRelative,
          outputFile5.format,
          doc,
          index2
        );
        writeDomToHtmlFile(doc, outputFile5.file, outputFile5.doctype);
      }
    }
  }
}
function resolveCrossrefs(context, file, format14, doc, index2) {
  const projOutput = projectOutputDir(context);
  const relativePathTo = (target) => {
    const currentFile = join4(projOutput, file);
    const targetFile = join4(projOutput, target);
    return pathWithForwardSlashes(
      relative4(dirname4(currentFile), targetFile)
    );
  };
  const refs = doc.querySelectorAll(".quarto-unresolved-ref");
  for (let i6 = 0; i6 < refs.length; i6++) {
    const ref3 = refs[i6];
    const id = ref3.textContent;
    const noPrefix = ref3.classList.contains("ref-noprefix");
    const type4 = refType(id);
    if (!type4) {
      continue;
    }
    const entry = index2.entries[id];
    let parentLink;
    if (ref3.parentElement?.tagName === "A" && ref3.parentElement?.getAttribute("href") === `#${id}`) {
      parentLink = ref3.parentElement;
    }
    if (entry) {
      if (parentLink && file !== entry.file) {
        const relativeFilePath = relativePathTo(entry.file);
        const hash = isChapterRef(entry) ? "" : `#${id}`;
        parentLink.setAttribute("href", `${relativeFilePath}${hash}`);
      }
      ref3.innerHTML = formatCrossref(
        type4,
        index2.files[entry.file],
        entry,
        noPrefix,
        format14,
        entry.parent ? index2.entries[entry.parent] : void 0
      );
      ref3.removeAttribute("class");
    } else {
      warn(`${file}: Unable to resolve crossref @${id}`);
      if (parentLink) {
        const parentLinkParent = parentLink.parentElement;
        if (parentLinkParent) {
          const span = doc.createElement("span");
          span.classList.add("quarto-unresolved-ref");
          span.innerHTML = `?${id}`;
          parentLinkParent.insertBefore(span, parentLink);
          parentLink.remove();
        }
      }
    }
  }
  const links = doc.querySelectorAll("a");
  for (let i6 = 0; i6 < links.length; i6++) {
    const link2 = links[i6];
    const href = link2.getAttribute("href");
    if (href && href.startsWith("#")) {
      const id = href.slice(1);
      if (index2.headings[id]) {
        if (!index2.headings[id].files.includes(file)) {
          const linkToFile = index2.headings[id].files[0];
          const hash = index2.files[linkToFile]?.[kCrossrefChapterId] === id ? "" : `#${id}`;
          const relativeFilePath = relativePathTo(index2.headings[id].files[0]);
          link2.setAttribute("href", `${relativeFilePath}${hash}`);
        }
      }
    }
  }
}
function isChapterRef(entry) {
  if (refType(entry.key) === "sec" && entry.order.section) {
    return !entry.order.section.slice(1).some((index2) => index2 > 0);
  } else {
    return false;
  }
}
function bookCrossrefIndexForOutputFile(outputFile5, indexes) {
  return indexes.find(
    (index2) => Object.keys(index2.files).find((file) => file === outputFile5)
  );
}
async function bookCrossrefIndexes(context) {
  const indexes = {};
  const renderFiles2 = bookConfigRenderItems(context.config).filter(
    (item) => !!item.file
  );
  for (const renderFile2 of renderFiles2) {
    const file = renderFile2.file;
    const index2 = await inputTargetIndex(context, file);
    if (index2) {
      for (const formatName of Object.keys(index2.formats)) {
        if (isMultiFileBookFormat(defaultWriterFormat(formatName))) {
          const format14 = index2.formats[formatName];
          if (format14.pandoc[kOutputFile]) {
            const outputFile5 = join4(dirname4(file), format14.pandoc[kOutputFile]);
            const indexFile = crossrefIndexForOutputFile(
              context.dir,
              file,
              outputFile5
            );
            if (existsSync2(indexFile)) {
              const indexJson = JSON.parse(Deno.readTextFileSync(indexFile));
              indexes[formatName] = indexes[formatName] || { files: {}, entries: {}, headings: {} };
              const index3 = indexes[formatName];
              index3.files[outputFile5] = indexJson.options || {};
              indexJson.entries.forEach((entry) => {
                index3.entries[entry.key] = {
                  ...entry,
                  file: outputFile5
                };
              });
              indexJson.headings.forEach((heading) => {
                if (!index3.headings[heading]) {
                  index3.headings[heading] = {
                    id: heading,
                    files: []
                  };
                }
                index3.headings[heading].files.push(outputFile5);
              });
            }
          }
        }
      }
    }
  }
  return Object.values(indexes);
}
function formatCrossref(type4, options, entry, noPrefix, format14, parent) {
  const { language } = format14;
  if (parent) {
    const crossref = [];
    const parentType = refType(parent.key);
    crossref.push(numberOption(parent.order, options, parentType));
    crossref.push(" (");
    crossref.push(numberOption(entry.order, options, "subref", "alpha a"));
    crossref.push(")");
    return crossref.join("");
  }
  if (format14.pandoc["number-sections"] === false && type4 === "sec") {
    return entry.caption || entry.key;
  }
  const refNumber = numberOption(entry.order, options, type4);
  if (type4 === "sec" && !noPrefix) {
    const prefix = options[kCrossrefChapters] && isChapterRef(entry) ? options[kCrossrefChaptersAppendix] ? language[kCrossrefApxPrefix] : language[kCrossrefChPrefix] : language[kCrossrefSecPrefix];
    const crossref = prefix + " " + refNumber;
    return crossref;
  } else {
    return refNumber;
  }
}
function refWithChapter(options, ref3, section) {
  if (options[kCrossrefChapters] !== false) {
    const chapter2 = section ? section[0] : void 0;
    const chapterPrefix = chapter2 ? formatChapterIndex(options, chapter2) + "." : "";
    return chapterPrefix + ref3;
  } else {
    return ref3;
  }
}
function refType(id) {
  const match = id.match(/^(\w+)-/);
  return (match ? match[1] : "fig").toLowerCase();
}
function numberOption(order, options, type4, defaultFormat2) {
  if (type4 === "sec" && order.section) {
    return sectionNumber(options, order.section);
  }
  const style = numberStyle(options, type4, defaultFormat2);
  if (Array.isArray(style)) {
    const entryCount = style.length;
    const entryIndex = (order.number - 1) % entryCount;
    const option = style[entryIndex];
    return refWithChapter(options, option, order.section);
  } else if (style.match(/^alpha /)) {
    let startIndexChar = style[style.length - 1];
    if (startIndexChar === " ") {
      startIndexChar = "a";
    }
    const startIndex = startIndexChar.charCodeAt(0);
    return refWithChapter(
      options,
      String.fromCharCode(startIndex + order.number - 1),
      order.section
    );
  } else if (style.match(/^roman/)) {
    const lower = style.endsWith("i");
    return refWithChapter(
      options,
      convertToRoman(order.number, lower),
      order.section
    );
  } else {
    return refWithChapter(options, order.number.toString(), order.section);
  }
}
function numberStyle(options, type4, defaultFormat2) {
  const opt = `${type4}-labels`;
  if (defaultFormat2 === void 0) {
    defaultFormat2 = "arabic";
  }
  const labelOpt = options[kCrossrefLabels] || defaultFormat2;
  return options[opt] || labelOpt;
}
function sectionNumber(options, section) {
  let lastIndex = 0;
  for (let i6 = section.length - 1; i6 >= 0; i6--) {
    if (section[i6] > 0) {
      lastIndex = i6;
      break;
    }
  }
  const num = [];
  for (let i6 = 0; i6 <= lastIndex; i6++) {
    if (i6 === 0) {
      const chapIndex = formatChapterIndex(options, section[i6]);
      if (chapIndex) {
        num.push(chapIndex);
      }
    } else {
      num.push(section[i6].toString());
    }
  }
  return num.join(".");
}
function formatChapterIndex(options, index2) {
  return index2 ? options[kCrossrefChaptersAlpha] ? String.fromCharCode(64 + index2) : index2.toString() : "";
}
function convertToRoman(num, lower) {
  const roman = {
    M: 1e3,
    CM: 900,
    D: 500,
    CD: 400,
    C: 100,
    XC: 90,
    L: 50,
    XL: 40,
    X: 10,
    IX: 9,
    V: 5,
    IV: 4,
    I: 1
  };
  let str3 = "";
  for (const i6 of Object.keys(roman)) {
    const q2 = Math.floor(num / roman[i6]);
    num -= q2 * roman[i6];
    str3 += lower ? i6.toLowerCase().repeat(q2) : i6.repeat(q2);
  }
  return str3;
}

// project/types/book/book-bibliography.ts
init_path();
init_fs();
init_lodash();
init_yaml();
init_log();
init_deno_dom();
init_path2();
init_process();
init_resources2();
init_constants6();
init_types4();
await init_project_shared();
init_project_types();
init_http();
async function bookBibliography(outputFiles, context) {
  const file = outputFiles[0];
  const bibliography = file.format.metadata[kBibliography];
  const nocite = typeof file.format.metadata[kNoCite] === "string" ? file.format.metadata[kNoCite] : void 0;
  const projType = projectType(context.config?.project?.[kProjectType]);
  if (!bibliography) {
    return {
      bibliographyPaths: []
    };
  }
  const fileRelativePath = relative4(
    projectFormatOutputDir(file.format, context, projType),
    file.file
  );
  const inputfile = await inputFileForOutputFile(context, fileRelativePath);
  const bibliographyPaths = [];
  let csl = file.format.metadata[kCsl];
  if (inputfile) {
    const firstFileDir = dirname4(inputfile.file);
    bibliographyPaths.push(
      ...bibliography.map(
        (file2) => (
          // we don't want to process already absolute path or url
          // (Pandoc supports fetching bibliography from the web)
          isAbsolute4(file2) || isAbsoluteRef(file2) ? file2 : join4(firstFileDir, file2)
        )
      )
    );
    if (csl) {
      const absPath = isAbsolute4(csl) ? csl : join4(firstFileDir, csl);
      const safeAbsPath = pathWithForwardSlashes(absPath);
      if (safeExistsSync(safeAbsPath)) {
        csl = safeAbsPath;
      }
    }
    return {
      csl,
      bibliographyPaths,
      nocite: nocite ? nocite.split(",").map((x3) => x3.trim().replace(/^@/, "")) : []
    };
  } else {
    throw new Error(
      `Unable to determine proper path to use when computing bibliography path for ${fileRelativePath}.`
    );
  }
}
async function bookBibliographyPostRender(context, incremental, outputFiles) {
  await initDenoDom();
  const renderFiles2 = context.config?.project[kProjectRender] || [];
  let refsHtml;
  for (const file of renderFiles2) {
    const index2 = await inputTargetIndex(context, file);
    if (index2?.markdown.containsRefs) {
      const target = await resolveInputTarget(context, file, false);
      if (target) {
        refsHtml = join4(projectOutputDir(context), target.outputHref);
      }
      break;
    }
  }
  if (refsHtml && outputFiles.length > 0) {
    const { bibliographyPaths, csl, nocite } = await bookBibliography(
      outputFiles,
      context
    );
    const citeIds = [];
    for (const file of outputFiles) {
      let changed = false;
      const refsRelative = pathWithForwardSlashes(
        relative4(dirname4(file.file), refsHtml)
      );
      const doc = await parseHtml(Deno.readTextFileSync(file.file));
      forEachCite(doc, (cite) => {
        citeIds.push(...citeIdsFromCite(cite));
        const citeLinks = cite.querySelectorAll("a[role='doc-biblioref']");
        for (let l6 = 0; l6 < citeLinks.length; l6++) {
          const link2 = citeLinks[l6];
          link2.setAttribute("href", refsRelative + link2.getAttribute("href"));
          changed = true;
        }
      });
      const refsDiv = doc.getElementById("refs");
      if (refsDiv) {
        refsDiv.setAttribute("style", "display: none");
        changed = true;
      }
      if (changed) {
        await writeDomToHtmlFile(
          doc,
          file.file,
          file.doctype
        );
      }
    }
    const refsOutputFile = outputFiles.find((file) => file.file === refsHtml);
    if (refsOutputFile) {
      if (incremental) {
        const bookHtmlOutputs = await bookMultiFileHtmlOutputs(context);
        for (const htmlOutput of bookHtmlOutputs) {
          if (outputFiles.findIndex((file) => file.file === htmlOutput) === -1) {
            if (existsSync2(htmlOutput)) {
              const doc = await parseHtml(Deno.readTextFileSync(htmlOutput));
              if (doc) {
                forEachCite(doc, (cite) => {
                  citeIds.push(...citeIdsFromCite(cite));
                });
              }
            }
          }
        }
      }
      if (nocite) {
        citeIds.push(
          ...nocite
        );
      }
      if (citeIds.length > 0) {
        const biblioHtml = await generateBibliography(
          context,
          bibliographyPaths,
          citeIds,
          "html",
          csl
        );
        const doc = await parseHtml(Deno.readTextFileSync(refsOutputFile.file));
        const newRefsDiv = doc.createElement("div");
        newRefsDiv.innerHTML = biblioHtml;
        const refsDiv = doc.getElementById("refs");
        let changed = false;
        if (refsDiv) {
          changed = true;
          refsDiv.replaceWith(newRefsDiv.firstChild);
        } else {
          const mainEl = doc.querySelector("main");
          if (mainEl) {
            changed = true;
            mainEl.appendChild(newRefsDiv.firstChild);
          }
        }
        if (changed) {
          await writeDomToHtmlFile(
            doc,
            refsOutputFile.file,
            refsOutputFile.doctype
          );
        }
      }
    }
  }
}
async function generateBibliography(context, bibliography, citeIds, to, csl) {
  const biblioPaths = bibliography.map((biblio) => {
    if (isAbsolute4(biblio)) {
      return relative4(context.dir, biblio);
    } else {
      return biblio;
    }
  });
  const yaml = {
    [kBibliography]: biblioPaths.map(pathWithForwardSlashes),
    [kNoCite]: uniq(citeIds).map((id) => "@" + id).join(", ")
  };
  if (csl) {
    yaml[kCsl] = isAbsolute4(csl) ? pathWithForwardSlashes(relative4(context.dir, csl)) : csl;
  }
  const frontMatter = `---
${stringify(yaml, { indent: 2 })}
---
`;
  const result2 = await execProcess({
    cmd: pandocBinaryPath(),
    args: [
      "--from",
      "markdown",
      "--to",
      to,
      "--citeproc"
    ],
    cwd: context.dir,
    stdout: "piped"
  }, frontMatter);
  if (result2.success) {
    return result2.stdout;
  } else {
    error(result2.stderr);
    throw new Error();
  }
}
function forEachCite(doc, f5) {
  const cites = doc.querySelectorAll(".citation");
  for (let i6 = 0; i6 < cites.length; i6++) {
    const cite = cites[i6];
    f5(cite);
  }
}
function citeIdsFromCite(cite) {
  const citeTarget = cite.getAttribute("data-cites");
  if (citeTarget) {
    return citeTarget.split(" ");
  } else {
    return [];
  }
}

// project/types/book/book-render.ts
init_yaml();
init_path2();
init_flags2();
init_resources2();
init_yaml();
init_lifetimes();
init_safe_clone_deep();
function bookPandocRenderer(options, project) {
  const renderCompletions = [];
  const renderedFiles = [];
  const executedFiles = {};
  const cleanupExecutedFiles = () => {
    for (const format14 of Object.keys(executedFiles)) {
      executedFiles[format14].forEach((executedFile) => {
        cleanupExecutedFile(
          executedFile,
          executedFile.recipe.output
        );
      });
    }
  };
  return {
    onFilterContexts: (_file, contexts, _files, _options) => {
      return contexts;
    },
    onBeforeExecute: (format14) => {
      return {
        // if we render a file at a time then resolve dependencies immediately
        resolveDependencies: isMultiFileBookFormat(format14)
      };
    },
    onRender: async (format14, file, quiet) => {
      if (isMultiFileBookFormat(file.context.format)) {
        const partitioned = partitionMarkdown(file.executeResult.markdown);
        const fileRelative = pathWithForwardSlashes(
          relative4(project.dir, file.context.target.source)
        );
        const isIndex = isBookIndexPage(fileRelative);
        if (isIndex) {
          file.recipe.format = withBookTitleMetadata(
            file.recipe.format,
            project.config
          );
          if (!isNumberedChapter(partitioned)) {
            file.recipe.format.pandoc[kNumberSections] = false;
          }
          if (!isListedChapter(partitioned.headingAttr)) {
            file.recipe.format.pandoc[kToc] = false;
          }
          const coverImage = file.recipe.format.metadata[kBookCoverImage] || bookConfig(kBookCoverImage, project.config);
          if (coverImage) {
            const coverImageAlt = file.recipe.format.metadata[kBookCoverImageAlt] || bookConfig(kBookCoverImageAlt, project.config);
            const title3 = file.recipe.format.metadata[kTitle] || "";
            const alt = coverImageAlt ? ` fig-alt="${coverImageAlt}"` : "";
            file.executeResult.markdown = `![](${coverImage} "${title3}"){.quarto-cover-image .nolightbox${alt}}

` + file.executeResult.markdown;
          }
        } else {
          const chapterInfo = isHtmlOutput(file.recipe.format.pandoc) ? chapterInfoForInput(project, fileRelative) : void 0;
          file.recipe.format.metadata[kHideDescription] = true;
          const titleInMetadata = frontMatterTitle(partitioned.yaml);
          if (titleInMetadata) {
            const parsedHeading = parsePandocTitle(titleInMetadata);
            file.recipe.format = withChapterMetadata(
              file.recipe.format,
              parsedHeading.heading,
              parsedHeading.attr,
              chapterInfo,
              project.config
            );
          } else {
            if (partitioned.headingText) {
              file.recipe.format = withChapterMetadata(
                file.recipe.format,
                partitioned.headingText,
                partitioned.headingAttr,
                chapterInfo,
                project.config
              );
            }
            const executeMarkdownPartitioned = partitionYamlFrontMatter(
              file.executeResult.markdown
            );
            if (executeMarkdownPartitioned) {
              file.executeResult.markdown = executeMarkdownPartitioned.yaml + "\n\n" + partitioned.markdown;
            } else {
              file.executeResult.markdown = partitioned.markdown;
            }
          }
        }
        if (file.recipe.format.extensions?.book) {
          const bookExtension = file.recipe.format.extensions?.book;
          if (bookExtension.onMultiFilePrePrender) {
            const result2 = await bookExtension.onMultiFilePrePrender(
              isIndex,
              file.recipe.format,
              file.executeResult.markdown,
              project
            );
            if (result2.format) {
              file.recipe.format = result2.format;
            }
            if (result2.markdown) {
              file.executeResult.markdown = result2.markdown;
            }
          }
        }
        file.recipe.format.render[kFormatLinks] = false;
        const renderCompletion = await renderPandoc(file, quiet);
        renderCompletions.push(renderCompletion);
      } else {
        executedFiles[format14] = executedFiles[format14] || [];
        executedFiles[format14].push(file);
      }
    },
    onPostProcess: async (renderedFormats) => {
      let completion = renderCompletions.pop();
      while (completion) {
        renderedFiles.push(await completion.complete(renderedFormats));
        completion = renderCompletions.pop();
      }
    },
    onComplete: async (error2, quiet) => {
      if (error2) {
        cleanupExecutedFiles();
        return {
          files: renderedFiles
        };
      }
      try {
        const renderFormats2 = Object.keys(executedFiles);
        for (const renderFormat of renderFormats2) {
          const files = executedFiles[renderFormat];
          if (files.length > 0) {
            const format14 = files[0].context.format;
            if (!isMultiFileBookFormat(format14)) {
              renderedFiles.push(
                await renderSingleFileBook(
                  project,
                  options,
                  files,
                  !!quiet
                )
              );
            }
          }
          delete executedFiles[renderFormat];
        }
        return {
          files: renderedFiles
        };
      } catch (error3) {
        if (!(error3 instanceof Error)) {
          throw error3;
        }
        cleanupExecutedFiles();
        return {
          files: renderedFiles,
          error: error3 ? typeof error3 === "string" ? new Error(error3) : error3 : new Error()
        };
      }
    }
  };
}
async function renderSingleFileBook(project, options, files, quiet) {
  const fileLifetime = await waitUntilNamedLifetime("render-file");
  try {
    const executedFile = await mergeExecutedFiles(
      project,
      options,
      files
    );
    executedFile.recipe.format = withBookTitleMetadata(
      executedFile.recipe.format,
      project.config
    );
    executedFile.recipe.format = onSingleFileBookPreRender(
      executedFile.recipe.format,
      project.config
    );
    const renderCompletion = await renderPandoc(executedFile, quiet);
    const renderedFormats = [];
    const renderedFile = await renderCompletion.complete(renderedFormats);
    files.forEach((file) => {
      file.recipe.format.render[kKeepTex] = executedFile.recipe.format.render[kKeepTex];
      cleanupExecutedFile(
        file,
        join4(project.dir, renderedFile.file)
      );
    });
    onSingleFileBookPostRender(project, renderedFile);
    return renderedFile;
  } finally {
    fileLifetime.cleanup();
  }
}
async function mergeExecutedFiles(project, options, files) {
  const context = safeCloneDeep(files[0].context);
  context.options = removePandocTo(options);
  const outputStem = bookOutputStem(project.dir, project.config);
  context.format.pandoc[kOutputFile] = `${outputStem}.${context.format.render[kOutputExt]}`;
  const recipe = await outputRecipe(context);
  if (isAbsolute4(recipe.output)) {
    recipe.output = relative4(project.dir, recipe.output);
    recipe.format.pandoc[kOutputFile] = recipe.output;
  }
  const renderItems = bookConfigRenderItems(project.config);
  const markdown = renderItems.reduce(
    (markdown2, item) => {
      let itemMarkdown = "";
      if (item.file) {
        const itemInputPath = join4(project.dir, item.file);
        const file = files.find(
          (file2) => file2.context.target.source === itemInputPath
        );
        if (file) {
          const partitioned = partitionMarkdown(file.executeResult.markdown);
          const resolveTitleMarkdown = (partitioned2) => {
            const createMarkdownTitle = (text, attr) => {
              let attrStr = "";
              if (attr) {
                const idStr = attr.id !== "" ? `#${attr.id} ` : "";
                const clzStr = attr.classes.map((clz) => {
                  return `.${clz} `;
                }).join("");
                const keyValueStr = attr.keyvalue.map((kv) => {
                  const escapedValue = kv[1].replaceAll(/"/gm, '\\"');
                  return `${kv[0]}="${escapedValue}" `;
                }).join("");
                const attrContents = `${idStr}${clzStr}${keyValueStr}`.trim();
                attrStr = `{${attrContents}}`;
              }
              return `# ${text} ${attrStr}

`;
            };
            let titleText;
            let titleAttr;
            if (partitioned2.yaml) {
              const frontTitle = frontMatterTitle(partitioned2.yaml);
              if (frontTitle) {
                titleText = frontTitle;
              } else {
                titleText = partitioned2.headingText;
                titleAttr = partitioned2.headingAttr;
              }
            } else {
              titleText = partitioned2.headingText;
              titleAttr = partitioned2.headingAttr;
            }
            if (titleText === void 0) {
              titleText = "";
            }
            return createMarkdownTitle(titleText, titleAttr);
          };
          const resolveTitleBlockMarkdown = (yaml) => {
            if (yaml) {
              const titleBlockPath = resourcePath(
                "projects/book/pandoc/title-block.md"
              );
              const titleAttr = `template='${titleBlockPath}'`;
              const frontMatter = `---
${stringify(yaml, { indent: 2 })}
---
`;
              const titleBlockMd = "```````{.quarto-title-block " + titleAttr + "}\n" + frontMatter + "\n```````\n\n";
              return titleBlockMd;
            } else {
              return "";
            }
          };
          const titleMarkdown = resolveTitleMarkdown(partitioned);
          const titleBlockMarkdown = resolveTitleBlockMarkdown(
            partitioned.yaml
          );
          const bodyMarkdown = partitioned.yaml?.title ? partitioned.srcMarkdownNoYaml : partitioned.markdown;
          itemMarkdown = bookItemMetadata(project, item, file) + titleMarkdown + titleBlockMarkdown + bodyMarkdown;
        } else {
          throw new Error(
            "Executed file not found for book item: " + item.file
          );
        }
      } else if (item.type === kBookItemPart || item.type === kBookItemAppendix) {
        itemMarkdown = bookPartMarkdown(project, item);
      }
      if ((item.type === kBookItemPart || item.type === kBookItemAppendix) && itemMarkdown.length > 0) {
        itemMarkdown = `

::: {.quarto-book-part}
${itemMarkdown}
:::

`;
      }
      return markdown2 + itemMarkdown;
    },
    ""
  );
  const supporting = files.reduce(
    (supporting2, file) => {
      return uniq(
        supporting2.concat(
          file.executeResult.supporting.map((f5) => relative4(project.dir, f5))
        )
      );
    },
    []
  );
  const filters = uniq(files.flatMap((file) => file.executeResult.filters));
  const engineDependencies = files.reduce(
    (engineDependencies2, file) => {
      const fileEngineDependencies = file.executeResult.engineDependencies;
      if (fileEngineDependencies) {
        for (const engineName of Object.keys(fileEngineDependencies)) {
          engineDependencies2[engineName] = (engineDependencies2[engineName] || []).concat(
            fileEngineDependencies[engineName]
          );
        }
      }
      return engineDependencies2;
    },
    {}
  );
  const preserve = files.reduce(
    (preserve2, file) => {
      return {
        ...preserve2,
        ...file.executeResult.preserve
      };
    },
    {}
  );
  const postProcess = files.reduce(
    (postProcess2, file) => {
      return postProcess2 || !!file.executeResult.postProcess;
    },
    false
  );
  const resourceFiles = uniq(files.flatMap((file) => file.resourceFiles));
  return Promise.resolve({
    context,
    recipe,
    executeResult: {
      markdown,
      supporting,
      filters,
      engineDependencies,
      preserve,
      postProcess
    },
    resourceFiles
  });
}
async function bookPostRender(context, incremental, outputFiles) {
  const websiteFiles = websiteOutputFiles(outputFiles);
  if (websiteFiles.length > 0) {
    await bookBibliographyPostRender(context, incremental, websiteFiles);
    await bookCrossrefsPostRender(context, websiteFiles);
    await websitePostRender(context, incremental, outputFiles);
  }
  const outputFormats = {};
  outputFiles.forEach((file) => {
    if (file.format.pandoc.to) {
      outputFormats[file.format.pandoc.to] = outputFormats[file.format.pandoc.to] || file.format;
    }
  });
  for (const outputFormat of Object.values(outputFormats)) {
    const bookExt = outputFormat.extensions?.book;
    if (bookExt.bookPostRender) {
      await bookExt.bookPostRender(
        outputFormat,
        context,
        incremental,
        outputFiles
      );
    }
  }
}
async function bookIncrementalRenderAll(context, options, files) {
  for (let i6 = 0; i6 < files.length; i6++) {
    const contexts = await renderContexts(
      { path: files[i6] },
      options,
      false,
      context.notebookContext,
      context
    );
    for (const context2 of Object.values(contexts)) {
      if (context2.active && !isMultiFileBookFormat(context2.format)) {
        return true;
      }
    }
  }
  return false;
}
function cleanupExecutedFile(file, finalOutput) {
  renderCleanup(
    file.context.target.input,
    finalOutput,
    file.recipe.format,
    file.context.project,
    file.executeResult.supporting,
    executionEngineKeepMd(file.context)
  );
}
function bookItemMetadata(project, item, file) {
  const resourceDir = file ? relative4(project.dir, dirname4(file.context.target.input)) : void 0;
  const inlineMetadata = {
    resourceDir: resourceDir || "."
  };
  const blockMetadata = {
    ...inlineMetadata,
    bookItemType: item.type,
    bookItemNumber: item.number ? item.number : null,
    bookItemFile: item.file,
    bookItemDepth: item.depth
  };
  const inlineMetadataEncoded = encodeBase64(JSON.stringify(inlineMetadata));
  const blockMetadataEncoded = encodeBase64(JSON.stringify(blockMetadata));
  return `

\`<!-- quarto-file-metadata: ${inlineMetadataEncoded} -->\`{=html}

\`\`\`{=html}
<!-- quarto-file-metadata: ${blockMetadataEncoded} -->
\`\`\`

`;
}
function bookPartMarkdown(project, item) {
  const metadata = bookItemMetadata(project, item);
  return `${metadata}# ${item.text ? item.text : ""}

`;
}
function withBookTitleMetadata(format14, config2) {
  format14 = cloneDeep(format14);
  if (config2) {
    const setMetadata = (key) => {
      const value = bookConfig(key, config2);
      if (value) {
        format14.metadata[key] = value;
      }
    };
    setMetadata(kTitle);
    setMetadata(kSubtitle);
    setMetadata(kAuthor);
    setMetadata(kDate);
    setMetadata(kDateFormat2);
    setMetadata(kAbstract);
    setMetadata(kDescription);
    setMetadata(kDoi);
  }
  return format14;
}
function frontMatterTitle(yaml) {
  if (yaml) {
    return yaml[kTitle];
  } else {
    return void 0;
  }
}

// project/types/book/book.ts
init_book_shared();
init_format_html_shared();
init_format_html_info();
var kSingleFileBook = "single-file-book";
var bookProjectType = {
  type: "book",
  inheritsType: websiteProjectType.type,
  create: (_title) => {
    const resourceDir = resourcePath(join4("projects", "book"));
    return {
      configTemplate: join4(resourceDir, "templates", "_quarto.ejs.yml"),
      resourceDir,
      scaffold: () => [
        {
          name: "index",
          content: "# Preface {.unnumbered}\n\nThis is a Quarto book.\n\nTo learn more about Quarto books visit <https://quarto.org/docs/books>."
        },
        {
          name: "intro",
          content: "# Introduction\n\nThis is a book created from markdown and executable code.\n\nSee @knuth84 for additional discussion of literate programming."
        },
        {
          name: "summary",
          content: "# Summary\n\nIn summary, this book has no content whatsoever."
        },
        {
          name: "references",
          content: "# References {.unnumbered}\n\n::: {#refs}\n:::",
          noEngineContent: true
        }
      ],
      supporting: [
        "cover.png",
        "references.bib"
      ]
    };
  },
  libDir: "site_libs",
  outputDir: "_book",
  cleanOutputDir: true,
  filterFormat: (source2, format14, project) => {
    if (format14.extensions?.book) {
      const bookExt = format14.extensions?.book;
      if (bookExt.filterFormat) {
        return bookExt.filterFormat(source2, format14, project);
      } else {
        return format14;
      }
    } else {
      return format14;
    }
  },
  formatOutputDirectory: (format14) => {
    if (format14.extensions?.book) {
      const bookExt = format14.extensions?.book;
      if (bookExt.formatOutputDirectory) {
        return bookExt.formatOutputDirectory();
      } else {
        return void 0;
      }
    } else {
      return void 0;
    }
  },
  selfContainedOutput: (format14) => {
    const bookExtension = format14.extensions?.book;
    return bookExtension?.selfContainedOutput || false;
  },
  config: bookProjectConfig,
  projectFormatsOnly: true,
  isSupportedFormat: (format14) => {
    return !!format14.extensions?.book;
  },
  filterParams: async (options) => {
    if (options.format.extensions?.book) {
      const bookExt = options.format.extensions?.book;
      const filterParams = bookExt.filterParams ? bookExt.filterParams(options) : {};
      if (isMultiFileBookFormat(options.format)) {
        return {
          ...filterParams,
          [kCrossrefResolveRefs]: false
        };
      } else {
        return {
          ...filterParams,
          [kSingleFileBook]: true
        };
      }
    }
  },
  pandocRenderer: bookPandocRenderer,
  navItemText: (context, input, text, number2) => {
    const chapterInfo = chapterInfoForInput(context, input);
    if (chapterInfo && number2) {
      return Promise.resolve({
        text,
        html: numberChapterHtmlNav(text, chapterInfo)
      });
    } else {
      return Promise.resolve({ html: text, text });
    }
  },
  incrementalRenderAll: bookIncrementalRenderAll,
  // inherit a bunch of behavior from website projects
  preRender: bookPreRender,
  postRender: bookPostRender,
  formatLibDirs: websiteProjectType.formatLibDirs,
  metadataFields: () => [...websiteProjectType.metadataFields(), "book"],
  resourceIgnoreFields: () => [
    ...websiteProjectType.resourceIgnoreFields(),
    kBook
  ],
  // format extras
  formatExtras: async (context, source2, flags, format14, services) => {
    let extras = {
      pandoc: {
        [kToc]: !isEpubOutput(format14.pandoc),
        [kNumberSections]: true
      },
      metadata: {
        [kCrossref]: {
          [kCrossrefChapters]: true
        }
      }
    };
    if (isHtmlOutput(format14.pandoc, true)) {
      if (formatHasBootstrap(format14)) {
        extras.html = {
          [kSassBundles]: [bookScssBundle()],
          [kHtmlPostprocessors]: [bookHtmlPostprocessor()]
        };
      }
      const websiteExtras = await websiteProjectType.formatExtras(
        context,
        source2,
        flags,
        format14,
        services
      );
      extras = mergeConfigs(extras, websiteExtras);
    } else if (isLatexOutput(format14.pandoc)) {
      extras = mergeConfigs(
        extras,
        {
          metadata: {
            [kDocumentClass]: "scrreprt",
            [kPaperSize]: "letter"
          },
          pandoc: {
            [kTopLevelDivision]: "chapter"
          }
        }
      );
    } else if (isTypstOutput(format14.pandoc)) {
      extras = mergeConfigs(
        extras,
        {
          pandoc: {
            [kTopLevelDivision]: "chapter",
            [kToc]: false
          }
        }
      );
    }
    return extras;
  }
};
function bookPreRender(context) {
  const date = bookConfig(kDate, context.config);
  if (context.config && isSpecialDate(date)) {
    setBookConfig(
      kDate,
      parseSpecialDate(context.files.input, date),
      context.config
    );
  }
  if (websiteProjectType.preRender) {
    return websiteProjectType.preRender(context);
  } else {
    return Promise.resolve();
  }
}
function bookHtmlPostprocessor() {
  return (doc) => {
    const coverImage = doc.querySelector(".quarto-cover-image");
    const nextEl = coverImage?.parentNode?.nextElementSibling;
    if (nextEl && nextEl.tagName === "SECTION" && coverImage?.parentNode) {
      coverImage?.parentElement?.remove();
      nextEl.firstElementChild?.after(coverImage?.parentNode);
    }
    return Promise.resolve(kHtmlEmptyPostProcessResult);
  };
}
function bookScssBundle() {
  const scssPath = resourcePath("projects/book/book.scss");
  return {
    dependency: kBootstrapDependencyName,
    key: scssPath,
    quarto: {
      name: "quarto-book.css",
      uses: "",
      defaults: "",
      functions: "",
      mixins: "",
      rules: Deno.readTextFileSync(scssPath)
    }
  };
}

// project/types/register.ts
init_project_default();
init_project_types();

// project/types/manuscript/manuscript.ts
init_resources2();
init_path();
init_types5();
init_constants6();
await init_project_shared();
init_format5();
init_github2();
await init_project_context();

// format/html/format-html-meta.ts
init_constants6();

// core/bibliography.ts
init_path();
init_constants6();
init_array();
init_process();
init_resources2();
async function bibliographyCslJson(input, metadata) {
  const bibliography = metadata[kBibliography];
  if (bibliography) {
    const references = await renderToCSLJSON(
      dirname4(input),
      asArray(bibliography)
    );
    return references;
  }
}
async function renderHtml(entry, csl) {
  const cmd = [pandocBinaryPath()];
  cmd.push("-f");
  cmd.push("csljson");
  cmd.push("-t");
  cmd.push("html5");
  cmd.push("--citeproc");
  if (csl) {
    cmd.push("--csl");
    cmd.push(csl);
  }
  const cslStr = JSON.stringify([entry], void 0, 2);
  const result2 = await execProcess(
    { cmd: cmd[0], args: cmd.slice(1), stdout: "piped", stderr: "piped" },
    cslStr
  );
  if (result2.success) {
    return result2.stdout;
  } else {
    throw new Error(
      `Failed to render citation: error code ${result2.code}
${result2.stderr}`
    );
  }
}
async function renderBibTex(entry) {
  const cmd = [pandocBinaryPath()];
  cmd.push("-f");
  cmd.push("csljson");
  cmd.push("-t");
  cmd.push("biblatex");
  cmd.push("--citeproc");
  const cslStr = JSON.stringify([entry], void 0, 2);
  const result2 = await execProcess(
    { cmd: cmd[0], args: cmd.slice(1), stdout: "piped", stderr: "piped" },
    cslStr
  );
  if (result2.success) {
    return result2.stdout;
  } else {
    throw new Error(
      `Failed to generate bibtex, rendering failed with code ${result2.code}
${result2.stderr}`
    );
  }
}
async function renderToCSLJSON(dir, biblios) {
  const bibloEntries = [];
  for (const biblio of biblios) {
    const biblioPath = join4(dir, biblio);
    const cmd = [pandocBinaryPath()];
    cmd.push(
      isAbsolute4(biblioPath) ? biblioPath : join4(Deno.cwd(), biblioPath)
    );
    cmd.push("-t");
    cmd.push("csljson");
    cmd.push("--citeproc");
    const result2 = await execProcess(
      {
        cmd: cmd[0],
        args: cmd.slice(1),
        stdout: "piped",
        stderr: "piped",
        cwd: dir
      }
    );
    if (result2.success) {
      if (result2.stdout) {
        const entries = JSON.parse(result2.stdout);
        bibloEntries.push(...entries);
      }
    } else {
      throw new Error(
        `Failed to generate bibliography, rendering failed with code ${result2.code}
${result2.stderr}`
      );
    }
  }
  return bibloEntries;
}

// format/html/format-html-meta.ts
init_html();
init_website_constants();

// quarto-core/attribution/document.ts
init_path();
init_constants6();
init_path2();
init_website_constants();
var kDOI = "DOI";
var kCitation2 = "citation";
var kURL = "URL";
var kId = "id";
var kCitationKey = "citation-key";
var kEditor = "editor";
var kType3 = "type";
var kCategories = "categories";
var kLanguage2 = "language";
var kAvailableDate = "available-date";
var kIssued = "issued";
var kDate2 = "date";
var kPublisher = "publisher";
var kContainerTitle = "container-title";
var kVolume = "volume";
var kIssue = "issue";
var kISSN = "issn";
var kISBN = "isbn";
var kPMCID = "pmcid";
var kPMID = "pmid";
var kFirstPage = "page-first";
var kLastPage = "page-last";
var kPage = "page";
var kNumber = "number";
var kCustom = "custom";
var kArchiveCollection = "archive_collection";
var kArchiveLocation = "archive_location";
var getCSLPath = (input, format14) => {
  const cslPath = format14.metadata[kCsl];
  if (cslPath) {
    if (isAbsolute4(cslPath)) {
      return cslPath;
    } else {
      return join4(dirname4(input), cslPath);
    }
  } else {
    return void 0;
  }
};
function documentCSL(input, inputMetadata, defaultType, outputFile5, offset3) {
  const citationMetadata = citationMeta(inputMetadata);
  const type4 = citationMetadata[kType3] ? cslType(citationMetadata[kType3]) : defaultType;
  const title3 = citationMetadata[kTitle] || inputMetadata[kTitle];
  const csl = {
    title: title3,
    type: type4
  };
  const key = citationMetadata[kCitationKey];
  if (key) {
    csl[kCitationKey] = key;
  }
  const authors = parseAuthor(
    citationMetadata[kAuthor] || inputMetadata[kAuthor] || inputMetadata[kAuthors]
  );
  csl.author = cslNames(
    authors?.filter((auth) => auth !== void 0).map((auth) => auth?.name)
  );
  const editors = parseAuthor(citationMetadata[kEditor]);
  csl.editor = cslNames(
    editors?.filter((editor) => editor !== void 0).map(
      (editor) => editor?.name
    )
  );
  if (csl.editor && csl.editor.length === 0) {
    delete csl.editor;
  }
  const categories = citationMetadata[kCategories] || inputMetadata[kCategories];
  if (categories) {
    csl.categories = Array.isArray(categories) ? categories : [categories];
  }
  const language = citationMetadata[kLanguage2] || inputMetadata[kLang];
  if (language) {
    csl.language = language;
  }
  const availableDate = citationMetadata[kAvailableDate] || resolveAndFormatDate(input, inputMetadata[kDate2]);
  if (availableDate) {
    csl[kAvailableDate] = cslDate(availableDate);
  }
  const issued = citationMetadata[kIssued] || resolveAndFormatDate(input, inputMetadata[kDate2]);
  if (issued) {
    csl.issued = cslDate(issued);
  }
  const abstract = citationMetadata[kAbstract] || inputMetadata[kAbstract];
  if (abstract) {
    csl.abstract = abstract;
  }
  const publisher = citationMetadata[kPublisher];
  if (publisher) {
    csl.publisher = publisher;
  }
  const containerTitle = citationMetadata[kContainerTitle];
  if (containerTitle) {
    csl[kContainerTitle] = containerTitle;
  }
  csl.id = citationMetadata[kId] || suggestId(csl.author, csl.issued);
  const findValue = (baseKey, metadata, transform) => {
    const keys = [baseKey, transform(baseKey)];
    for (const key2 of keys) {
      for (const md of metadata) {
        const value = md[key2];
        if (value) {
          return value;
        }
      }
    }
  };
  const lowercase = (key2) => {
    return key2.toLocaleLowerCase();
  };
  const kebabcase = (key2) => {
    return key2.replaceAll("_", "_");
  };
  const url = findValue(kURL, [citationMetadata], lowercase);
  if (url) {
    csl.URL = url;
  } else {
    csl.URL = synthesizeCitationUrl(input, inputMetadata, outputFile5, offset3);
  }
  const doi = findValue(kDOI, [citationMetadata, inputMetadata], lowercase);
  if (doi) {
    csl.DOI = doi;
  }
  const issue = citationMetadata[kIssue];
  if (issue) {
    csl.issue = issue;
  }
  const volume = citationMetadata[kVolume];
  if (volume) {
    csl.volume = volume;
  }
  const number2 = citationMetadata[kNumber];
  if (number2) {
    csl.number = number2;
  }
  const isbn = findValue(kISBN, [citationMetadata], lowercase);
  if (isbn) {
    csl.ISBN = isbn;
  }
  const issn = findValue(kISSN, [citationMetadata], lowercase);
  if (issn) {
    csl.ISSN = issn;
  }
  const pmcid = findValue(kPMCID, [citationMetadata], lowercase);
  if (pmcid) {
    csl.PMCID = pmcid;
  }
  const pmid = findValue(kPMID, [citationMetadata], lowercase);
  if (pmid) {
    csl.PMID = pmid;
  }
  const pageRange = pages(citationMetadata);
  if (pageRange.firstPage) {
    csl["page-first"] = pageRange.firstPage;
  }
  if (pageRange.lastPage) {
    csl["page-last"] = pageRange.lastPage;
  }
  if (pageRange.page) {
    csl.page = pageRange.page;
  }
  const archiveCollection = findValue(
    kArchiveCollection,
    [citationMetadata],
    kebabcase
  );
  if (archiveCollection) {
    csl[kArchiveCollection] = archiveCollection;
  }
  const archiveLocation = findValue(
    kArchiveLocation,
    [citationMetadata],
    kebabcase
  );
  if (archiveLocation) {
    csl[kArchiveLocation] = archiveLocation;
  }
  const forwardStringValue = (key2) => {
    if (citationMetadata[key2] !== void 0) {
      csl[key2] = citationMetadata[key2];
    }
  };
  [
    "title-short",
    "annote",
    "archive",
    "archive-place",
    "authority",
    "call-number",
    "chapter-number",
    "citation-number",
    "citation-label",
    "collection-number",
    "collection-title",
    "container-title-short",
    "dimensions",
    "division",
    "edition",
    "event-title",
    "event-place",
    "first-reference-note-number",
    "genre",
    "jurisdiction",
    "keyword",
    "locator",
    "medium",
    "note",
    "number",
    "number-of-pages",
    "number-of-volumes",
    "original-publisher",
    "original-publisher-place",
    "original-title",
    "part",
    "part-title",
    "printing",
    "publisher-place",
    "references",
    "reviewed-genre",
    "reviewed-title",
    "scale",
    "section",
    "source",
    "status",
    "supplement",
    "version",
    "volume-title",
    "volume-title-short",
    "year-suffix"
  ].forEach(forwardStringValue);
  const forwardCSLNameValue = (key2) => {
    if (citationMetadata[key2]) {
      const authors2 = parseAuthor(citationMetadata[key2]);
      csl[key2] = cslNames(
        authors2?.filter((auth) => auth !== void 0).map((auth) => auth?.name)
      );
    }
  };
  [
    "chair",
    "collection-editor",
    "compiler",
    "composer",
    "container-author",
    "contributor",
    "curator",
    "director",
    "editor",
    "editorial-director",
    "executive-producer",
    "guest",
    "host",
    "interviewer",
    "illustrator",
    "narrator",
    "organizer",
    "original-author",
    "performer",
    "producer",
    "recipient",
    "reviewed-author",
    "script-writer",
    "series-creator",
    "translator"
  ].forEach(forwardCSLNameValue);
  const forwardCSLDateValue = (key2) => {
    if (citationMetadata[key2]) {
      csl[key2] = cslDate(citationMetadata[key2]);
    }
  };
  ["accessed", "event-date", "original-date", "submitted"].forEach(
    forwardCSLDateValue
  );
  const custom2 = citationMetadata[kCustom];
  if (custom2) {
    csl[kCustom] = custom2;
  }
  const extras = {};
  const kwString = citationMetadata.keyword;
  if (kwString && typeof kwString === "string") {
    extras.keywords = kwString.split(",");
  } else if (inputMetadata.keywords) {
    const kw3 = inputMetadata.keywords;
    extras.keywords = Array.isArray(kw3) ? kw3 : [kw3];
  }
  if (citationMetadata[kPdfUrl]) {
    extras[kPdfUrl] = citationMetadata[kPdfUrl];
  }
  if (citationMetadata[kAbstractUrl]) {
    extras[kAbstractUrl] = citationMetadata[kAbstractUrl];
  }
  if (citationMetadata[kEIssn]) {
    extras[kEIssn] = citationMetadata[kEIssn];
  }
  return {
    csl,
    extras
  };
}
function citationMeta(metadata) {
  if (typeof metadata[kCitation2] === "object") {
    return metadata[kCitation2];
  } else {
    return {};
  }
}
function synthesizeCitationUrl(input, metadata, outputFile5, offset3) {
  const siteMeta = metadata[kWebsite];
  let baseUrl = siteMeta?.[kSiteUrl];
  if (baseUrl && outputFile5 && offset3) {
    baseUrl = baseUrl.replace(/\/$/, "");
    const rootDir = normalizePath(join4(dirname4(input), offset3));
    if (outputFile5 === "index.html") {
      const part = pathWithForwardSlashes(relative4(rootDir, dirname4(input)));
      if (part.length === 0) {
        return `${baseUrl}/`;
      } else {
        return `${baseUrl}/${part}/`;
      }
    } else {
      const relativePath = relative4(
        rootDir,
        join4(dirname4(input), basename4(outputFile5))
      );
      const part = pathWithForwardSlashes(relativePath);
      return `${baseUrl}/${part}`;
    }
  } else {
    return void 0;
  }
}
function pages(citationMetadata) {
  let firstPage = citationMetadata[kFirstPage];
  let lastPage = citationMetadata[kLastPage];
  let pages2 = citationMetadata[kPage] ? `${citationMetadata[kPage]}` : void 0;
  if (pages2 && pages2.includes("-")) {
    const pagesSplit = pages2.split("-");
    if (!firstPage) {
      firstPage = pagesSplit[0];
    }
    if (!lastPage) {
      lastPage = pagesSplit[1];
    }
  } else if (pages2 && !firstPage) {
    firstPage = pages2;
  } else if (!pages2) {
    if (firstPage && lastPage) {
      pages2 = `${firstPage} - ${lastPage}`;
    } else if (firstPage) {
      pages2 = `${firstPage}`;
    }
  }
  return {
    firstPage,
    lastPage,
    page: pages2
  };
}

// format/html/format-html-meta.ts
init_format_html_shared();
var kGoogleScholar = "google-scholar";
function metadataPostProcessor(input, format14, offset3) {
  return async (doc, options) => {
    if (format14.render[kCanonicalUrl]) {
      writeCanonicalUrl(
        doc,
        format14.render[kCanonicalUrl],
        input,
        options.inputMetadata,
        format14.pandoc["output-file"],
        offset3
      );
    }
    if (googleScholarEnabled(format14)) {
      const { csl, extras } = documentCSL(
        input,
        options.inputMetadata,
        "webpage",
        format14.pandoc["output-file"],
        offset3
      );
      const documentMetadata = googleScholarMeta(csl, extras);
      const referenceMetadata = await googleScholarReferences(
        input,
        options.inputMetadata
      );
      [...documentMetadata, ...referenceMetadata].forEach((meta) => {
        writeMetaTag(meta.name, meta.content, doc);
      });
    }
    return Promise.resolve(kHtmlEmptyPostProcessResult);
  };
}
function googleScholarEnabled(format14) {
  if (format14.metadata[kGoogleScholar] === true) {
    return true;
  }
  const siteMeta = format14.metadata[kWebsite];
  if (siteMeta && siteMeta[kGoogleScholar] === true) {
    return true;
  }
  return false;
}
function googleScholarMeta(csl, extras) {
  const scholarMeta = [];
  const write = metadataWriter(scholarMeta);
  if (csl.title) {
    write("citation_title", csl.title);
  }
  if (csl.abstract) {
    write("citation_abstract", csl.abstract);
  }
  if (extras.keywords) {
    write("citation_keywords", extras.keywords);
  }
  if (csl.author) {
    csl.author.forEach((author) => {
      write(
        "citation_author",
        author.literal || `${author.given} ${author.family}`
      );
    });
  }
  if (csl.editor) {
    csl.editor.forEach((editor) => {
      write(
        "citation_editor",
        editor.literal || `${editor.given} ${editor.family}`
      );
    });
  }
  if (csl.issued) {
    const edtfIssued = cslDateToEDTFDate(csl.issued);
    if (edtfIssued) {
      write("citation_publication_date", edtfIssued);
      write("citation_cover_date", edtfIssued);
    }
    const parts = csl.issued["date-parts"];
    if (parts && parts.length > 0) {
      write("citation_year", parts[0][0]);
    }
  }
  if (csl["available-date"]) {
    const edtfAvailable = cslDateToEDTFDate(csl["available-date"]);
    if (edtfAvailable) {
      write("citation_online_date", edtfAvailable);
    }
  }
  if (csl.URL) {
    write(
      "citation_fulltext_html_url",
      csl.URL
    );
  }
  if (extras[kPdfUrl]) {
    write("citation_pdf_url", extras[kPdfUrl]);
  }
  if (extras[kAbstractUrl]) {
    write("citation_abstract_html_url", extras[kAbstractUrl]);
  }
  if (csl.issue) {
    write("citation_issue", csl.issue);
  }
  if (csl.DOI) {
    write("citation_doi", csl.DOI);
  }
  if (csl.ISBN) {
    write("citation_isbn", csl.ISBN);
  }
  if (csl.ISSN) {
    write("citation_issn", csl.ISSN);
  }
  if (extras[kEIssn]) {
    write("citation_eissn", extras[kEIssn]);
  }
  if (csl.PMID) {
    write("citation_pmid", csl.PMID);
  }
  if (csl.volume) {
    write("citation_volume", csl.volume);
  }
  if (csl.language) {
    write("citation_language", csl.language);
  }
  if (csl["page-first"]) {
    write("citation_firstpage", csl["page-first"]);
  }
  if (csl["page-last"]) {
    write("citation_lastpage", csl["page-last"]);
  }
  const type4 = csl.type;
  if (type4 === "paper-conference") {
    if (csl["container-title"]) {
      write("citation_conference_title", csl["container-title"]);
    }
    if (csl.publisher) {
      write("citation_conference", csl.publisher);
    }
  } else if (type4 === "thesis") {
    if (csl.publisher) {
      write("citation_dissertation_institution", csl.publisher);
    }
  } else if (type4 === "report") {
    if (csl.publisher) {
      write(
        "citation_technical_report_institution",
        csl.publisher
      );
    }
    if (csl.number) {
      write(
        "citation_technical_report_number",
        csl.number
      );
    }
  } else if (type4 === "book") {
    if (csl["container-title"]) {
      write("citation_book_title", csl["container-title"]);
    }
  } else if (type4 === "chapter") {
    write("citation_inbook_title", csl["container-title"]);
  } else {
    if (csl["container-title"]) {
      write("citation_journal_title", csl["container-title"]);
    }
    if (csl["container-title-short"]) {
      write("citation_journal_abbrev", csl["container-title-short"]);
    }
    if (csl.publisher) {
      write("citation_publisher", csl.publisher);
    }
  }
  if (csl["collection-title"]) {
    write("citation_series_title", csl["collection-title"]);
  }
  return scholarMeta;
}
async function googleScholarReferences(input, metadata) {
  const scholarMeta = [];
  const write = metadataWriter(scholarMeta);
  const references = await bibliographyCslJson(input, metadata);
  if (references) {
    references.forEach((reference) => {
      const refMetas = googleScholarMeta(reference, {});
      const metaStrs = refMetas.map((refMeta) => {
        return `${refMeta.name}=${refMeta.content};`;
      });
      write("citation_reference", metaStrs.join());
    });
  }
  return scholarMeta;
}
function metadataWriter(metadata) {
  const write = (key, value) => {
    metadata.push({
      name: key,
      content: encodeAttributeValue(value)
    });
  };
  return write;
}
function writeCanonicalUrl(doc, url, input, inputMetadata, outputFile5, offset3) {
  if (typeof url === "string") {
    writeLinkTag("canonical", url, doc);
  } else if (url) {
    const canonicalUrl = synthesizeCitationUrl(
      input,
      inputMetadata,
      outputFile5,
      offset3
    );
    if (canonicalUrl) {
      writeLinkTag("canonical", canonicalUrl, doc);
    }
  }
}

// project/types/manuscript/manuscript.ts
init_manuscript_types();

// project/types/manuscript/manuscript-meca.ts
init_format5();
init_temp();
init_mime();
init_types4();
init_path();
init_fs();

// https://deno.land/x/xml@2.1.1/utils/types.ts
var $XML = /* @__PURE__ */ Symbol("x/xml");
var schema3 = {
  comment: "#comment",
  text: "#text",
  stylesheets: "$stylesheets",
  attribute: {
    prefix: "@"
  },
  property: {
    prefix: "@"
  },
  space: {
    name: "xml:space",
    preserve: "preserve"
  }
};
var SeekMode = Object.freeze({
  Current: Deno?.SeekMode?.Current ?? 0,
  Start: Deno?.SeekMode?.Start ?? 1,
  End: Deno?.SeekMode?.End ?? 2
});
var entities = {
  xml: {
    "&lt;": "<",
    "&gt;": ">",
    "&apos;": "'",
    "&quot;": '"',
    "&amp;": "&"
    //Keep last
  },
  char: {
    "&": "&amp;",
    //Keep first
    '"': "&quot;",
    "<": "&lt;",
    ">": "&gt;",
    "'": "&apos;"
  }
};
var tokens = {
  entity: {
    regex: {
      entities: /&#(?<hex>x?)(?<code>\d+);/g
    }
  },
  prolog: {
    start: "<?xml",
    end: "?>"
  },
  stylesheet: {
    start: "<?xml-stylesheet",
    end: "?>"
  },
  doctype: {
    start: "<!DOCTYPE",
    end: ">",
    elements: {
      start: "[",
      end: "]"
    },
    element: {
      start: "<!ELEMENT",
      end: ">",
      value: {
        start: "(",
        end: ")",
        regex: {
          end: { until: /\)/, bytes: 1 }
        }
      }
    }
  },
  comment: {
    start: "<!--",
    end: "-->",
    regex: {
      end: { until: /(?<!-)-->/, bytes: 4, length: 3 }
    }
  },
  cdata: {
    start: "<![CDATA[",
    end: "]]>",
    regex: {
      end: {
        until: /\]\]>/,
        bytes: 3
      }
    }
  },
  tag: {
    start: "<",
    end: ">",
    close: {
      start: "</",
      end: ">",
      self: "/",
      regex: {
        start: /<\//,
        end: /\/?>/
      }
    },
    attribute: {
      regex: {
        name: { until: /=/, bytes: 1 }
      }
    },
    regex: {
      name: { until: /[\s\/>]/, bytes: 1 },
      start: { until: /</, bytes: 1 }
    }
  },
  text: {
    regex: {
      end: { until: /(<\/)|(<!)/, bytes: 2 }
    }
  }
};

// https://deno.land/x/xml@2.1.1/utils/stringifier.ts
var Stringifier = class {
  /** Constructor */
  constructor(document2, options = {}) {
    this.#document = document2;
    this.#options = options;
    this.#options.replacer ??= function({ value }) {
      return value;
    };
  }
  /** Stringify document */
  stringify() {
    const document2 = this.#make.extraction(this.#document);
    if (document2.raw.xml) {
      this.#prolog(document2);
    }
    if (document2.raw[schema3.stylesheets]) {
      this.#stylesheet(document2);
    }
    if (document2.raw.doctype) {
      this.#doctype(document2);
    }
    this.#tag({ document: document2.raw, path: [], name: "", ...document2 });
    return this.#result.trim();
  }
  /** Options */
  #options;
  /** Document */
  #document;
  /** Debugger */
  #debug(path3, string2) {
    if (this.#options.debug) {
      console.debug(`${path3.join(" > ")} | ${string2}`.trim());
    }
  }
  /** Prolog stringifier */
  #prolog({ raw: node }) {
    this.#debug([], "stringifying prolog");
    const attributes = this.#attributes({ tag: "prolog", ...this.#make.extraction(node.xml) });
    this.#write(`${tokens.prolog.start}${attributes}${tokens.prolog.end}`);
  }
  /** Stylesheet stringifier */
  #stylesheet({ raw: node }) {
    this.#debug([], "stringifying stylesheets");
    for (const stylesheet of node[schema3.stylesheets]) {
      const attributes = this.#attributes({ tag: "stylesheet", ...this.#make.extraction(stylesheet) });
      this.#write(`${tokens.stylesheet.start}${attributes}${tokens.stylesheet.end}`);
    }
  }
  /** Doctype stringifier */
  #doctype({ raw: node }) {
    this.#debug([], "stringifying doctype");
    const { raw: doctype, attributes, children: elements } = this.#make.extraction(node.doctype);
    this.#write(`${tokens.doctype.start}${this.#properties({ attributes })}`, {
      newline: !!elements.length
    });
    if (elements.length) {
      this.#debug([], "stringifying doctype elements");
      this.#down();
      this.#write(tokens.doctype.elements.start);
      this.#down();
      for (const key of elements) {
        this.#debug([], `stringifying doctype elements ${key}`);
        const value = `${tokens.doctype.element.value.start}${doctype[key]}${tokens.doctype.element.value.end}`;
        this.#write(
          `${tokens.doctype.element.start} ${this.#quote(key, { optional: true })} ${value} ${tokens.doctype.element.end}`
        );
      }
      this.#up();
      this.#write(tokens.doctype.elements.end);
      this.#up();
    }
    this.#write(tokens.doctype.end);
  }
  /** Tag stringifier */
  #tag({ document: document2, path: path3, name: name2, raw: node, text: content, comments, attributes, children }) {
    if (name2) {
      this.#debug(path3, `stringifying tag ${name2}`);
    }
    if (this.#options.progress) {
      this.#options.progress(this.#result.length);
    }
    const selfclosed = content === null && !comments.length && !children.length;
    let inline = false;
    if (name2) {
      this.#write(
        `${tokens.tag.start}${name2}${this.#attributes({ raw: node, attributes, tag: name2 })}${selfclosed ? tokens.tag.close.self : ""}${tokens.tag.end}`
      );
      this.#down();
    }
    if (!selfclosed) {
      if (["string", "boolean", "number", "undefined"].includes(typeof content) || content === null) {
        let cdata = false;
        if (document2[$XML]?.cdata?.find((cpath) => cpath.join(">") === path3.join(">"))) {
          this.#debug(path3, `stringifying text content`);
          cdata = true;
        }
        this.#debug(path3, `stringifying text content`);
        inline = this.#text({
          path: path3,
          text: content,
          tag: name2,
          properties: Object.fromEntries(
            attributes.map((attribute) => [attribute.substring(schema3.attribute.prefix.length), node[attribute]])
          ),
          cdata
        });
      }
      if (comments.length) {
        this.#debug(path3, `stringifying comments`);
        const commentArr = Array.isArray(comments) ? comments : [comments];
        for (const comment of commentArr) {
          this.#write("\n", { newline: false, indent: false });
          this.#comment({ text: comment, tag: name2 });
        }
      }
      if (children.length) {
        this.#debug(path3, `stringifying children`);
        this.#write("\n", { newline: false, indent: false });
        const handle = ({ child, name: name3 }) => {
          switch (true) {
            case Array.isArray(child): {
              for (const value of child) {
                handle({ child: value, name: name3 });
              }
              break;
            }
            case (typeof child === "object" && !!child): {
              this.#tag({ document: document2, name: name3, path: [...path3, name3], ...this.#make.extraction(child) });
              break;
            }
            default: {
              this.#tag({
                document: document2,
                name: name3,
                path: [...path3, name3],
                ...this.#make.extraction({ [schema3.text]: child })
              });
              break;
            }
          }
        };
        for (const name3 of children) {
          const child = node[name3];
          handle({ child, name: name3 });
        }
        inline = false;
      }
    }
    if (name2) {
      this.#up();
      if (!selfclosed) {
        this.#write(`${tokens.tag.close.start}${name2}${tokens.tag.close.end}`, { indent: !inline });
      }
    }
  }
  /** Comment stringifier */
  #comment({ text, tag }) {
    const comment = this.#replace({ value: text, key: schema3.comment, tag, properties: null });
    this.#write(`${tokens.comment.start} ${comment} ${tokens.comment.end}`, { newline: false });
  }
  /** Text stringifier */
  #text({ path: path3, text, tag, properties, cdata }) {
    if (cdata) {
      text = `${tokens.cdata.start}${text}${tokens.cdata.end}`;
    }
    const lines2 = this.#replace({ value: text, key: schema3.text, tag, properties, escape: !cdata }).split("\n");
    let trim = true;
    if (properties[schema3.space.name] === schema3.space.preserve) {
      this.#debug(path3, `${schema3.space.name} is set to ${schema3.space.preserve}`);
      trim = false;
    }
    const inline = lines2.length <= 1;
    if (inline) {
      this.#trim();
    }
    for (const line of lines2) {
      this.#write(trim ? line.trimStart() : line, { indent: !inline, newline: !inline });
    }
    return inline;
  }
  //================================================================================
  /** Attributes stringifier */
  #attributes({ raw: node, attributes, tag }) {
    const stringified = attributes.map(
      (key) => `${key.substring(schema3.attribute.prefix.length)}=${this.#quote(this.#replace({ key, value: node[key], tag, properties: null }))}`
    ).join(" ");
    return stringified.length ? ` ${stringified}` : "";
  }
  /** Properties stringifier */
  #properties({ attributes }) {
    const stringified = attributes.map((key) => `${this.#quote(key.substring(schema3.property.prefix.length), { optional: true })}`).join(" ");
    return stringified.length ? ` ${stringified}` : "";
  }
  //================================================================================
  /** Replacer */
  #replace({ key, value, tag, properties, escape: escape2 = true }) {
    return `${this.#options.replacer.call(null, {
      key,
      tag,
      properties,
      value: (() => {
        switch (true) {
          // Convert empty values to null
          case ((this.#options.nullToEmpty ?? true) && value === null):
            return "";
          // Escape XML entities
          default: {
            if (escape2) {
              for (const [char, entity] of Object.entries(entities.char)) {
                value = `${value}`.replaceAll(char, entity);
              }
            }
          }
        }
        return `${value}`;
      })()
    })}`;
  }
  //================================================================================
  /** Result */
  #result = "";
  /** Write text */
  #write(text, { newline = true, indent = true } = {}) {
    this.#result += `${`${indent ? " ".repeat((this.#options?.indentSize ?? 2) * this.#depth) : ""}`}${text}${newline ? "\n" : ""}`;
  }
  /** Trim text */
  #trim() {
    this.#result = this.#result.trim();
  }
  /** Depth */
  #depth = 0;
  /** Go down */
  #down() {
    this.#depth++;
  }
  /** Go up */
  #up() {
    this.#depth--;
    this.#depth = Math.max(0, this.#depth);
  }
  /** Quoter */
  #quote(content, { optional = false } = {}) {
    if (optional) {
      if (/^[\w_]+$/i.test(`${content}`)) {
        return `${content}`;
      }
    }
    return `"${`${content}`.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
  }
  //================================================================================
  /** Makers */
  #make = {
    /** Extract content (text), attributes and children nodes */
    extraction(node) {
      const keys = Object.keys(node ?? {});
      return {
        raw: node,
        text: node?.[schema3.text] ?? null,
        comments: node?.[schema3.comment] ?? [],
        attributes: keys.filter(
          (key) => key.startsWith(schema3.attribute.prefix) || key.startsWith(schema3.property.prefix)
        ),
        children: keys.filter(
          (key) => ![schema3.text, schema3.comment, schema3.stylesheets, "xml", "doctype"].includes(key) && !(key.startsWith(schema3.attribute.prefix) || key.startsWith(schema3.property.prefix))
        ),
        meta: node?.[$XML] ?? {}
      };
    }
  };
};

// https://deno.land/x/xml@2.1.1/stringify.ts
function stringify4(content, options) {
  return new Stringifier(content, options).stringify();
}

// project/types/manuscript/meca.ts
var kMecaVersion = "1";
function toXml(manifest) {
  const mecaJson = {
    xml: {
      "@version": "1.0",
      "@encoding": "UTF-8"
    },
    doctype: {
      "@manifest": true,
      "@PUBLIC": true,
      "@-//MECA//DTD Manifest v1.0//en": true,
      "@MECA_manifest.dtd": true
    },
    manifest: {
      "@manifest-version": manifest.version,
      "@xmlns": "https://manuscriptexchange.org/schema/manifest",
      "@xmlns:xlink": "http://www.w3.org/1999/xlink",
      item: manifest.items.map(toMecaXMLItem)
    }
  };
  return stringify4(mecaJson);
}
function toMecaXMLItem(item) {
  const xmlItem = {};
  if (item.id) {
    xmlItem["@id"] = item.id;
  }
  if (item.type) {
    xmlItem["@item-type"] = item.type;
  }
  if (item.version) {
    xmlItem["@version"] = item.version;
  }
  if (item.metadataId) {
    xmlItem["metadata-id"] = item.metadataId;
  }
  if (item.title) {
    xmlItem["item-title"] = item.title;
  }
  if (item.description) {
    xmlItem["item-description"] = item.description;
  }
  if (item.order) {
    xmlItem["file-order"] = item.order;
  }
  if (item.metadata) {
    const metaValues = {};
    if (item.metadata) {
      for (const key of Object.keys(item.metadata)) {
        const value = item.metadata[key];
        metaValues["metadata"] = {
          ["@metadata-name"]: key,
          ["#text"]: value
        };
      }
    }
    const itemMetadata = Object.keys(metaValues).length > 0 ? {
      ["item-metadata"]: metaValues
    } : void 0;
    xmlItem["item-metadata"] = itemMetadata;
  }
  xmlItem["instance"] = {
    ["@media-type"]: item.instance.mediaType,
    ["@xlink:href"]: item.instance.href
  };
  return xmlItem;
}

// project/types/manuscript/manuscript-meca.ts
init_zip();
init_manuscript_types();
init_path2();
init_lodash();
init_project_types();
await init_engine();
init_git();
init_log();

// core/container.ts
init_fs();
init_path();
var kExecutionFiles = [
  "environment.yml",
  "requirements.txt",
  "renv.lock",
  // not supported by repo2docker
  "Pipfile",
  "Pipfile.lock",
  "setup.py",
  "Project.toml",
  "REQUIRE",
  "install.R",
  "apt.txt",
  "DESCRIPTION",
  "postBuild",
  "start",
  "runtime.txt",
  "default.nix",
  "Dockerfile"
];
function isReesEnvronmentFile(path3) {
  return kExecutionFiles.includes(basename4(path3));
}
function codeSpacesUrl(repoUrl) {
  const containerUrl = repoUrl.replace(
    /(https?\:\/\/github.com)\/([a-zA-Z0-9-_\.]+?)\/([a-zA-Z0-9-_\.]+?)\//,
    "$1/codespaces/new/$2/$3?resume=1"
  );
  return containerUrl;
}
function binderUrl(organization, repository, binderOptions) {
  const url = [`https://mybinder.org/v2/gh/${organization}/${repository}/HEAD`];
  const params = [];
  if (binderOptions && binderOptions.openFile) {
    params.push(`labpath=${binderOptions.openFile}`);
  }
  if (binderOptions?.editor) {
    switch (binderOptions.editor) {
      case "rstudio":
        params.push(`urlpath=rstudio`);
        break;
      case "vscode":
        params.push(`urlpath=vscode`);
        break;
      case "jupyterlab":
      default:
        break;
    }
  }
  if (params.length > 0) {
    url.push("?");
    url.push(params.join("&"));
  }
  return url.join("");
}
function isDevContainerFile(relPath) {
  if (relPath === join4(".devcontainer", "devcontainer.json")) {
    return true;
  }
  if (relPath === ".devcontainer.json") {
    return true;
  }
  if (relPath.match(/^\.devcontainer[\/\\][^\/\\]+?[\/\\]devcontainer.json$/)) {
    return true;
  }
  return false;
}

// project/types/manuscript/manuscript-meca.ts
var kArticleMetadata = "article-metadata";
var kArticleSupportingFile = "article-supporting-file";
var kArticleSource = "article-source";
var kArticleSourceEnvironment = "article-source-environment";
var kManuscript = "manuscript";
var kManuscriptSupportingFile = "manuscript-supporting-file";
var kSrcDirName = "source";
var kSrcDirMecaType = "article-source-directory";
var kMecaSuffix = "-meca.zip";
var shouldMakeMecaBundle = (formats2, manuConfig) => {
  if (!manuConfig || manuConfig[kMecaBundle] !== false) {
    if (manuConfig && manuConfig[kMecaBundle] === true) {
      return true;
    }
    return formats2.find((format14) => {
      if (typeof format14 === "string") {
        return isJatsOutput(format14);
      } else {
        return isJatsOutput(format14.pandoc);
      }
    });
  } else {
    return false;
  }
};
var mecaFileName = (file, config2) => {
  if (typeof config2[kMecaBundle] === "string") {
    return config2[kMecaBundle];
  } else {
    const [_3, stem] = dirAndStem(file);
    return `${stem}${kMecaSuffix}`;
  }
};
var createMecaBundle = async (mecaFile, context, outputDir, outputFiles, manuscriptConfig, otherOutputBundle) => {
  const workingDir = globalTempContext().createDir();
  const srcDir = join4(workingDir, kSrcDirName);
  ensureDirSync(srcDir);
  const srcFiles = {};
  const addSrcFile = (absPath, type4) => {
    if (srcFiles[absPath] === void 0) {
      srcFiles[absPath] = type4;
    }
  };
  let hasExplicitEnvironment = false;
  if (manuscriptConfig[kEnvironmentFiles]) {
    manuscriptConfig[kEnvironmentFiles].forEach((file) => {
      const absPath = join4(context.dir, file);
      addSrcFile(absPath, kArticleSourceEnvironment);
      hasExplicitEnvironment = true;
    });
  }
  const srcType = (path3) => {
    return !hasExplicitEnvironment && isReesEnvronmentFile(path3) || isDevContainerFile(path3) ? kArticleSourceEnvironment : kArticleSource;
  };
  const skip = [
    kSkipHidden,
    /\.DS_Store/
  ];
  const projType = projectType(context.config?.project?.[kProjectType]);
  if (projType.outputDir) {
    skip.push(RegExp(`^${join4(context.dir, projType.outputDir)}[/\\\\]`));
    skip.push(RegExp(`[/\\\\]${projType.outputDir}[/\\\\]`));
    engineIgnoreDirs().map(
      (ignore3) => skip.push(
        globToRegExp4(join4(context.dir, ignore3) + SEP)
      )
    );
  }
  let gitFiles = await lsFiles(context.dir);
  if (gitFiles) {
    const unstagedDeletes = await lsFiles(context.dir, ["--deleted"]);
    if (unstagedDeletes) {
      gitFiles = gitFiles.filter((file) => {
        return !unstagedDeletes.includes(file);
      });
    }
    for (const file of gitFiles) {
      addSrcFile(join4(context.dir, file), srcType(file));
    }
  } else {
    for (const walkEntry of walkSync(context.dir, { skip })) {
      if (walkEntry.isFile) {
        addSrcFile(walkEntry.path, srcType(walkEntry.path));
      }
    }
  }
  const sourceFiles = [];
  const sourceZipFiles = [];
  const copySrcFile = (file, type4) => {
    const relPath = join4(kSrcDirName, relative4(context.dir, file));
    const targetPath = join4(workingDir, relPath);
    ensureDirSync(dirname4(targetPath));
    Deno.copyFileSync(file, targetPath);
    const item = toMecaItem(relPath, type4);
    sourceFiles.push(item);
    sourceZipFiles.push(relPath);
  };
  const srcDirMetaItem = {
    type: kSrcDirMecaType,
    instance: {
      mediaType: "application/x-directory",
      href: kSrcDirName
    }
  };
  for (const path3 of Object.keys(srcFiles)) {
    const type4 = srcFiles[path3];
    copySrcFile(path3, type4);
  }
  const filters = [isPdfOutput, isDocxOutput];
  const articleRenderings = outputFiles.filter((outputFile5) => {
    return filters.some((filter3) => {
      return filter3(outputFile5.format.identifier["base-format"] || "html");
    });
  });
  let jatsArticle;
  for (const outputFile5 of outputFiles.reverse()) {
    if (isJatsOutput(outputFile5.format.pandoc)) {
      const input = await inputFileForOutputFile(context, outputFile5.file);
      if (input) {
        if (relative4(context.dir, input.file) === manuscriptConfig.article) {
          jatsArticle = outputFile5;
          break;
        }
      }
    }
  }
  if (jatsArticle) {
    const toWorkingDir = (input, outputRelative, move = false) => {
      const target = join4(workingDir, outputRelative);
      const targetDir = dirname4(target);
      ensureDirSync(targetDir);
      if (move) {
        moveSync(input, target);
      } else {
        copySync(input, target, { overwrite: true });
      }
      return outputRelative;
    };
    const articleRenderingPaths = articleRenderings.map((out) => {
      return toWorkingDir(out.file, relative4(outputDir, out.file), false);
    });
    const articlePath = toWorkingDir(
      jatsArticle.file,
      relative4(outputDir, jatsArticle?.file),
      false
    );
    const manuscriptResources = [];
    const manuscriptZipFiles = [];
    if (jatsArticle.supporting) {
      uniq(jatsArticle.supporting).forEach((file) => {
        const relPath = isAbsolute4(file) ? relative4(outputDir, file) : file;
        const absPath = isAbsolute4(file) ? file : join4(outputDir, file);
        const workingPath = toWorkingDir(absPath, relPath, false);
        const items = mecaItemsForPath(workingDir, workingPath, "manuscript");
        manuscriptResources.push(...items);
        manuscriptZipFiles.push(workingPath);
      });
    }
    if (otherOutputBundle) {
      if (otherOutputBundle.manuscript) {
        const relativePath = toWorkingDir(
          otherOutputBundle.manuscript,
          relative4(outputDir, otherOutputBundle.manuscript),
          false
        );
        articleRenderingPaths.push(relativePath);
      }
      for (const otherSupporting of otherOutputBundle.supporting) {
        const relativePath = toWorkingDir(
          otherSupporting,
          relative4(outputDir, otherSupporting),
          false
        );
        const isDir = Deno.statSync(otherSupporting).isDirectory;
        const otherItems = mecaItemsForPath(
          workingDir,
          relativePath,
          "manuscript",
          isDir
        );
        manuscriptResources.push(...otherItems);
        manuscriptZipFiles.push(relativePath);
      }
    }
    const msg5 = (count, nameSing, namePlur) => {
      if (count === 1) {
        info(`  ${count} ${nameSing}`);
      } else if (count > 1) {
        info(`  ${count} ${namePlur}`);
      }
    };
    msg5(
      1 + manuscriptResources.length + articleRenderingPaths.length,
      "article file",
      "article files"
    );
    msg5(Object.keys(srcFiles).length, "source file", "source files");
    const resources = [];
    resources.push(...jatsArticle.resources);
    if (context.config?.project.resources) {
      resources.push(...context.config?.project.resources);
    }
    const notebooks = manuscriptConfig.notebooks;
    notebooks.forEach((notebook) => {
      resources.push(notebook.notebook);
    });
    msg5(notebooks.length, "notebook", "notebooks");
    resources.forEach((file) => {
      const relPath = isAbsolute4(file) ? relative4(context.dir, file) : file;
      const absPath = isAbsolute4(file) ? file : join4(context.dir, file);
      const workingPath = toWorkingDir(absPath, relPath, false);
      manuscriptResources.push(
        toMecaItem(
          relPath,
          kManuscriptSupportingFile
        )
      );
      manuscriptZipFiles.push(workingPath);
    });
    msg5(resources.length, "other file", "other files");
    const articleItem = toMecaItem(articlePath, kArticleMetadata);
    const renderedItems = articleRenderingPaths.map((path3) => {
      return toMecaItem(path3, kManuscript);
    });
    const manifest = {
      version: kMecaVersion,
      items: [
        articleItem,
        ...renderedItems,
        ...manuscriptResources,
        ...sourceFiles,
        srcDirMetaItem
      ]
    };
    info("");
    const manifestFile = "manifest.xml";
    const manifestXML = toXml(manifest);
    Deno.writeTextFileSync(join4(workingDir, manifestFile), manifestXML);
    const filesToZip = uniq([
      manifestFile,
      articlePath,
      ...articleRenderingPaths,
      ...manuscriptZipFiles,
      ...sourceZipFiles
    ]);
    const zipResult = await zip(filesToZip, mecaFile, {
      cwd: workingDir
    });
    if (zipResult.success) {
      return join4(workingDir, mecaFile);
    } else {
      throw new Error(
        `An error occurred while attempting to generate MECA archive.
${zipResult.stderr}`
      );
    }
  }
};
var toMecaItem = (href, type4) => {
  const mediaType = contentType(href) || "application/octet-stream";
  return {
    type: type4,
    instance: {
      href,
      mediaType
    }
  };
};
var mecaItemsForPath = (basePath, relPath, type4, isDir) => {
  const path3 = join4(basePath, relPath);
  if (isDir === true || Deno.statSync(path3).isDirectory) {
    const items = [];
    for (const subPath of Deno.readDirSync(path3)) {
      if (subPath.isDirectory) {
        items.push(
          ...mecaItemsForPath(
            basePath,
            join4(relPath, subPath.name),
            type4,
            true
          )
        );
      } else {
        const filePath = join4(relPath, subPath.name);
        items.push(toMecaItem(filePath, mecaType(filePath, type4)));
      }
    }
    return items;
  } else {
    return [toMecaItem(relPath, mecaType(path3, type4))];
  }
};
var mecaType = (_path, type4) => {
  if (type4 === "article") {
    return kArticleSupportingFile;
  } else {
    return kManuscriptSupportingFile;
  }
};

// deno_ral/io.ts
init_read_lines2();

// project/types/manuscript/manuscript.ts
init_log();
init_log2();

// project/types/manuscript/manuscript-config.ts
init_path();
init_fs();
init_constants6();
var notebookDescriptor = (nbPath, manuscriptConfig, project) => {
  const notebooks = manuscriptConfig.notebooks;
  return notebooks.find((notebook) => {
    return notebook.notebook === relative4(project.dir, nbPath);
  });
};
var isArticle = (file, project, manuscriptConfig) => {
  const articlePath = isAbsolute4(file) ? join4(project.dir, manuscriptConfig.article) : manuscriptConfig.article;
  return file === articlePath;
};
var isArticleManuscript = (file, format14, project, manuscriptConfig) => {
  return isArticle(file, project, manuscriptConfig) && format14.render[kNotebookViewStyle] !== "notebook";
};
var computeProjectArticleFile = (projectDir, config2) => {
  let defaultRenderFile = void 0;
  if (config2.article) {
    defaultRenderFile = config2.article;
  } else {
    const defaultArticleFiles = ["index.qmd", "index.ipynb"];
    const defaultArticleFile = defaultArticleFiles.find((file) => {
      return existsSync2(join4(projectDir, file));
    });
    if (defaultArticleFile !== void 0) {
      defaultRenderFile = defaultArticleFile;
    } else {
      throw new Error(
        "Unable to determine the root input document for this manuscript. Please specify an `article` in your `_quarto.yml` file."
      );
    }
  }
  return defaultRenderFile;
};
var codeHintRegexes = [/`+{[^\.]+.*}/, /.*"cell_type"\s*:\s*"code".*/];
var hasComputations = async (file) => {
  const reader = await Deno.open(file);
  try {
    for await (const line of readLines2(reader)) {
      if (line) {
        if (codeHintRegexes.find((regex) => {
          return regex.exec(line);
        })) {
          return true;
        }
      }
    }
    return false;
  } finally {
    reader.close();
  }
};

// project/types/manuscript/manuscript.ts
init_error2();
init_format_jats_types();
init_log2();
init_language();

// project/types/manuscript/manuscript-render.ts
init_manuscript_types();
init_format5();
init_notebook_types();
init_path();
init_error2();
init_log2();
init_constants6();
init_path2();
var manuscriptRenderer = (options, context) => {
  const renderCompletions = [];
  const renderedFiles = [];
  const nbContext = options.services.notebook;
  const articleOutputFiles = {};
  const manuscriptConfig = context.config?.[kManuscriptType] || {};
  const isNotebook2 = (path3) => {
    return !isArticle(path3, context, manuscriptConfig);
  };
  const pandocRenderNb = async (input, parentOutputFiles, executedFile, project, isArticle2, quiet) => {
    const displayPath = relative4(project.dir, input);
    const progressMessage = (msg5) => {
      if (!quiet) {
        logProgress(`${msg5} [${displayPath}]`);
      }
    };
    if (isJatsOutput(executedFile.context.format.pandoc)) {
      progressMessage("Rendering JATS embedded notebook");
      const resolvedExecutedFile = nbContext.resolve(
        input,
        kJatsSubarticle2,
        executedFile
      );
      return [{
        completion: await renderPandoc(resolvedExecutedFile, true),
        cleanup: !isArticle2,
        contribute: kJatsSubarticle2
      }];
    } else if (isHtmlOutput(executedFile.context.format.pandoc, true)) {
      const result2 = [];
      const notebook = nbContext.get(input, context);
      if (isQmdFile(input) && (!notebook || !notebook[kQmdIPynb])) {
        progressMessage("Rendering qmd embeds");
        const qmdExecuted = nbContext.resolve(
          input,
          kQmdIPynb,
          executedFile
        );
        result2.push({
          completion: await renderPandoc(qmdExecuted, true),
          cleanup: true,
          contribute: kQmdIPynb
        });
      }
      let downloadHref;
      if (!notebook || !notebook[kRenderedIPynb]) {
        progressMessage("Rendering output notebook");
        const ipynbExecutedFile = nbContext.resolve(
          input,
          kRenderedIPynb,
          executedFile
        );
        downloadHref = outputFile3(input);
        result2.push({
          completion: await renderPandoc(ipynbExecutedFile, true),
          cleanup: !isArticle2,
          contribute: kRenderedIPynb
        });
      }
      progressMessage("Rendering HTML preview");
      let title3;
      const nbDescriptor = notebookDescriptor(input, manuscriptConfig, context);
      if (nbDescriptor) {
        title3 = nbDescriptor.title;
        downloadHref = nbDescriptor["download-url"];
      }
      if (!title3) {
        const inputIndex = await readBaseInputIndex(input, context);
        if (inputIndex) {
          title3 = inputIndex.title;
        }
      }
      const dirOffset = relative4(dirname4(input), context.dir);
      const index2 = join4(dirOffset, "index.html");
      const notebookMetadata = {
        title: title3 || basename4(input),
        filename: basename4(input),
        backHref: parentOutputFiles["html"] || index2,
        downloadHref: downloadHref || basename4(input),
        downloadFile: basename4(input)
      };
      const resolvedExecutedFile = nbContext.resolve(
        input,
        kHtmlPreview,
        executedFile,
        notebookMetadata
      );
      result2.push({
        completion: await renderPandoc(resolvedExecutedFile, true),
        cleanup: !isArticle2,
        contribute: kHtmlPreview
      });
      return result2;
    }
  };
  return {
    onFilterContexts: (file, contexts, _files, _options) => {
      const isValidNotebookOutput = (to) => {
        return [isJatsOutput, (format14) => {
          return isHtmlOutput(format14, true);
        }].find((fn) => {
          return fn(to);
        });
      };
      if (isNotebook2(file)) {
        const outContexts = {};
        const allowedFormats = Object.keys(contexts).filter(
          isValidNotebookOutput
        );
        for (const allowedFormat of allowedFormats || []) {
          outContexts[allowedFormat] = contexts[allowedFormat];
        }
        return outContexts;
      } else {
        Object.keys(contexts).forEach((fmt) => {
          const outputFile5 = contexts[fmt].format.pandoc[kOutputFile];
          if (outputFile5) {
            articleOutputFiles[fmt] = outputFile5;
          }
        });
      }
      return contexts;
    },
    onBeforeExecute: (_format5) => {
      return {};
    },
    onRender: async (_format5, executedFile, quiet) => {
      const target = executedFile.context.target;
      if (isArticle(target.source, context, manuscriptConfig)) {
        if (await hasComputations(target.source)) {
          const renderedNb = await pandocRenderNb(
            target.source,
            articleOutputFiles,
            executedFile,
            context,
            true,
            quiet
          );
          if (renderedNb) {
            renderCompletions.push(...renderedNb);
          }
        }
        renderCompletions.push({
          completion: await renderPandoc(executedFile, quiet)
        });
      } else {
        const renderedNb = await pandocRenderNb(
          target.source,
          articleOutputFiles,
          executedFile,
          context,
          false,
          quiet
        );
        if (renderedNb) {
          renderCompletions.push(...renderedNb);
        } else {
          throw new InternalError(
            "Manuscript asked to render a notebook to an unsupported format."
          );
        }
      }
    },
    onPostProcess: async (renderedFormats, projectContext2) => {
      if (projectContext2 === void 0) {
        throw new InternalError(
          "Manuscript pandoc rendered is being used without a project context - this is not allowed."
        );
      }
      let manuscriptCompletion = renderCompletions.shift();
      while (manuscriptCompletion) {
        const renderedFile = await manuscriptCompletion.completion.complete(
          renderedFormats,
          manuscriptCompletion.cleanup
        );
        const contributeNotebook = (renderedFile2, renderType) => {
          const nbAbsPath2 = join4(projectContext2.dir, renderedFile2.input);
          nbContext.addRendering(
            nbAbsPath2,
            renderType,
            renderedFile2,
            context
          );
        };
        if (manuscriptCompletion.contribute) {
          contributeNotebook(renderedFile, manuscriptCompletion.contribute);
          if (manuscriptCompletion.contribute !== kJatsSubarticle2) {
            renderedFiles.unshift(renderedFile);
          }
        } else {
          renderedFiles.unshift(renderedFile);
        }
        manuscriptCompletion = renderCompletions.shift();
      }
    },
    onComplete: async () => {
      const files = await Promise.resolve(renderedFiles);
      return {
        files
      };
    }
  };
};

// project/types/manuscript/manuscript.ts
init_lodash();
init_path2();
init_fs();
var kMecaIcon = "archive";
var kOutputDir = "_manuscript";
var kTexOutputBundle = "tex-bundle";
var manuscriptProjectType = {
  type: kManuscriptType,
  libDir: "site_libs",
  config: async (project, config2, flags) => {
    const projectDir = project.dir;
    const manuscriptConfig = config2[kManuscriptType] || {};
    if (manuscriptConfig[kResources]) {
      config2.project.resources = config2.project.resources || [];
      config2.project.resources = Array.isArray(config2.project.resources) ? config2.project.resources : [config2.project.resources];
      if (Array.isArray(manuscriptConfig[kResources])) {
        config2.project.resources.push(...manuscriptConfig[kResources]);
      } else {
        config2.project.resources.push(manuscriptConfig[kResources]);
      }
    }
    const language = await formatLanguage(
      config2,
      config2[kLanguageDefaults],
      flags
    );
    const inputs = await projectInputFiles(project, config2);
    const article = computeProjectArticleFile(projectDir, manuscriptConfig);
    const notebooks = [];
    const explicitNotebooks = manuscriptConfig[kNotebooks];
    if (explicitNotebooks) {
      resolveNotebookDescriptors(explicitNotebooks, true).forEach((nb) => {
        notebooks.push(nb);
      });
    } else {
      const inputNotebooks = inputs.files.map((input) => {
        return relative4(projectDir, input);
      }).filter((file) => {
        if (file === article) {
          return false;
        }
        const excludeSuffixes = [".out.ipynb", ".embed.ipynb"];
        if (excludeSuffixes.some((suffix) => {
          return file.endsWith(suffix);
        })) {
          return false;
        }
        if (file.match(/\.embed\./)) {
          return false;
        }
        return true;
      });
      if (inputNotebooks) {
        resolveNotebookDescriptors(inputNotebooks).forEach((nb) => {
          notebooks.push(nb);
        });
      }
    }
    config2.project.render = [
      ...Object.values(notebooks).map((nb) => nb.notebook),
      article
    ];
    let count = 0;
    const jatsNotebooks = Object.values(notebooks).map((notebookDesc) => {
      return {
        input: join4(projectDir, notebookDesc.notebook),
        token: `nb-${++count}`,
        render: true
      };
    });
    if (await hasComputations2(join4(projectDir, article))) {
      if (!notebooks.find((nb) => {
        return nb.notebook === article;
      })) {
        notebooks.unshift({
          notebook: article,
          title: language[kArticleNotebookLabel],
          order: 9999
        });
      }
      jatsNotebooks.unshift({
        input: join4(projectDir, article),
        token: `nb-article`,
        render: true
      });
    }
    config2[kQuartoInternal] = {
      [kSubArticles]: jatsNotebooks
    };
    const userConfig = manuscriptConfig[kEnvironmentFiles];
    const environmentFiles = userConfig !== void 0 ? Array.isArray(userConfig) ? userConfig : [userConfig] : void 0;
    const mecaFileOutput = mecaFileName(article, manuscriptConfig);
    const resolvedManuscriptOptions = {
      ...manuscriptConfig,
      article,
      notebooks,
      mecaFile: mecaFileOutput,
      [kEnvironmentFiles]: environmentFiles
    };
    config2[kManuscriptType] = resolvedManuscriptOptions;
    config2[kEcho] = false;
    config2[kWarning] = false;
    const previewOptions = { back: true };
    config2[kNotebookPreviewOptions] = previewOptions;
    config2[kTheme] = "cosmo";
    config2[kTitleBlockStyle] = "manuscript";
    config2[kLightbox] = "auto";
    return config2;
  },
  create: (title3) => {
    const resourceDir = resourcePath(join4("projects", "manuscript"));
    return {
      configTemplate: join4(resourceDir, "templates", "_quarto.ejs.yml"),
      resourceDir,
      scaffold: () => [
        {
          name: "index",
          content: [
            "---",
            `title: ${title3}`,
            `authors:`,
            `  - name: Norah Jones`,
            `    affiliation: The University`,
            `    roles: writing`,
            `    corresponding: true`,
            `bibliography: references.bib`,
            "---",
            "",
            "## Section",
            "This is a simple placeholder for the manuscript's main document [@knuth84]."
          ].join("\n")
        }
      ],
      supporting: [
        "references.bib"
      ]
    };
  },
  pandocRenderer: manuscriptRenderer,
  outputDir: kOutputDir,
  outputFile: (input, format14, project) => {
    const manuscriptConfig = project.config?.[kManuscriptType];
    if (!isArticleManuscript(input, format14, project, manuscriptConfig) && isHtmlOutput(format14.pandoc)) {
      return outputFile2(input);
    } else {
      return void 0;
    }
  },
  cleanOutputDir: true,
  incrementalFormatPreviewing: true,
  filterParams: async (options) => {
    if (options.project) {
      const filterParams = {};
      const manuscriptConfig = options.project.config?.[kManuscriptType];
      if (manuscriptConfig) {
        let baseUrl = manuscriptConfig[kManuscriptUrl];
        if (baseUrl === void 0) {
          try {
            const ghContext = await gitHubContext(options.project.dir);
            baseUrl = ghContext.siteUrl;
          } catch (e5) {
            const errorMessage = e5 instanceof Error ? e5.message : String(e5);
            if (logLevel() === "DEBUG") {
              debug(`Failed to auto-detect manuscript URL from GitHub: ${errorMessage}`);
            }
            const debugHint = logLevel() === "DEBUG" ? "" : " Run with --log-level debug for details.";
            warnOnce(
              "Unable to auto-detect manuscript URL from GitHub Pages. Set manuscript-url explicitly in your configuration if needed." + debugHint
            );
          }
        }
        if (baseUrl) {
          filterParams[kManuscriptUrl] = baseUrl;
        }
      }
      if (options.format.render[kNotebookLinks] !== void 0) {
        filterParams[kNotebookLinks] = options.format.render[kNotebookLinks];
      }
      return filterParams;
    } else {
      throw new InternalError(
        "Filters params being requested for project without providing a project."
      );
    }
  },
  filterFormat: (source2, format14, project) => {
    if (project) {
      const manuscriptConfig = project.config?.[kManuscriptType];
      const formats2 = project.config?.format ? Object.keys(project.config?.format) : [];
      if (isArticleManuscript(source2, format14, project, manuscriptConfig)) {
        if (shouldMakeMecaBundle(formats2, manuscriptConfig)) {
          if (format14.render[kFormatLinks] !== false) {
            const links = [];
            if (typeof format14.render[kFormatLinks] !== "boolean") {
              links.push(...format14.render[kFormatLinks] || []);
            }
            links.push({
              text: format14.language[kManuscriptMecaBundle] || "MECA Bundle",
              href: mecaFileName(source2, manuscriptConfig),
              icon: kMecaIcon,
              attr: { "data-meca-link": "true" },
              order: 1e3
            });
            format14.render[kFormatLinks] = links;
          }
        }
        if (format14.metadata[kGoogleScholar] !== false) {
          format14.metadata[kGoogleScholar] = true;
        }
        if (isHtmlOutput(format14.pandoc, true)) {
          if (format14.pandoc[kToc] !== false) {
            format14.pandoc[kToc] = true;
          }
          if (format14.pandoc[kOutputFile] === void 0) {
            format14.pandoc[kOutputFile] = "index.html";
          }
          if (format14.metadata[kTocLocation] === void 0) {
            format14.metadata[kTocLocation] = "left";
          }
        }
      }
      const userEcho = format14.execute.echo;
      const userWarning = format14.execute.warning;
      const clearVal = [];
      const removeVal = [];
      format14.execute.echo = false;
      format14.execute.warning = false;
      format14.render[kKeepHidden] = true;
      if (!isArticle(source2, project, manuscriptConfig) && isQmdFile(source2)) {
        format14.render[kIpynbProduceSourceNotebook] = true;
      }
      if (userEcho === true) {
        clearVal.push("code");
      } else {
        removeVal.push("code");
      }
      if (userWarning === true) {
        clearVal.push("warning");
      } else {
        removeVal.push("warning");
      }
      const resolveValue = (vals) => {
        if (vals.length === 0) {
          return "none";
        } else if (vals.length === 1) {
          return vals[0];
        } else {
          return "all";
        }
      };
      format14.metadata[kClearHiddenClasses] = resolveValue(clearVal);
      format14.metadata[kRemoveHidden] = resolveValue(removeVal);
      format14.render[kNotebookPreserveCells] = true;
      format14.metadata[kUnrollMarkdownCells] = true;
      return format14;
    } else {
      throw new InternalError(
        "Filter format being called for project without providing a project."
      );
    }
  },
  // format extras
  formatExtras: async (context, source2, _flags, format14, _services) => {
    const manuscriptConfig = context.config?.[kManuscriptType];
    const extras = {};
    extras.metadata = {};
    const isArticle2 = isArticleManuscript(
      source2,
      format14,
      context,
      manuscriptConfig
    );
    if (isArticle2 && isHtmlOutput(format14.pandoc)) {
      extras.metadata[kCodeLinks] = manuscriptConfig[kCodeLinks];
      const notebooks = manuscriptConfig.notebooks || [];
      const orderedNbs = [];
      for (const notebook of notebooks) {
        const createTitle = async () => {
          const target = await resolveInputTarget(
            context,
            relative4(context.dir, notebook.notebook),
            false
          );
          if (target) {
            return target.title;
          }
        };
        orderedNbs.push({
          ...notebook,
          title: notebook.title || await createTitle()
        });
      }
      extras[kNotebooks] = orderedNbs;
    } else if (isArticle2 && isLatexOutput(format14.pandoc)) {
      if (isLatexOutput(format14.pandoc)) {
        format14.render[kKeepTex] = true;
      }
    }
    extras.html = extras.html || {};
    extras.html[kHtmlPostprocessors] = [async (doc, _options) => {
      await resolveProjectInputLinks(source2, context, doc);
      return Promise.resolve(kHtmlEmptyPostProcessResult);
    }];
    if (!isArticle2) {
      extras.html[kDependencies] = [{
        name: "manuscript-notebook",
        scripts: [
          {
            name: "headroom.min.js",
            path: resourcePath(`projects/website/navigation/headroom.min.js`)
          }
        ]
      }];
    }
    return Promise.resolve(extras);
  },
  previewSkipUnmodified: true,
  renderResultFinalOutput: (renderResults) => {
    if (renderResults.context) {
      const manuscriptConfig = renderResults.context.config?.[kManuscriptType];
      const articleResults = renderResults.files.filter((file) => {
        return file.input === manuscriptConfig.article;
      });
      if (articleResults.length === 1) {
        return articleResults[0];
      } else if (articleResults.length > 1) {
        const preferredFormats = ["html", "pdf", "docx"];
        const sorted = orderBy(articleResults, (item) => {
          const formatStr = item.format.identifier["base-format"];
          if (formatStr) {
            const index2 = preferredFormats.indexOf(formatStr);
            if (index2 > -1) {
              if (item.format.identifier[kExtensionName]) {
                return index2 * 2;
              } else {
                return index2 * 2 + 1;
              }
            }
          }
          return Number.MAX_SAFE_INTEGER;
        }, "asc");
        return sorted[0];
      }
      return void 0;
    }
  },
  beforeMoveOutput: async (context, renderedFiles) => {
    let outBundle;
    for (const renderedFile of renderedFiles) {
      const format14 = renderedFile.format;
      if (isLatexOutput(format14.pandoc) && format14.render[kKeepTex]) {
        outBundle = createTexOutputBundle(renderedFile, context);
      }
    }
    if (outBundle) {
      return {
        [kTexOutputBundle]: outBundle
      };
    }
  },
  postRender: async (context, _incremental, outputFiles, moveOutputResult) => {
    const manuscriptConfig = context.config?.[kManuscriptType];
    if (shouldMakeMecaBundle(
      outputFiles.map((file) => file.format),
      manuscriptConfig
    ) && outputFiles.length > 0) {
      let outBundle;
      if (moveOutputResult) {
        outBundle = moveOutputResult[kTexOutputBundle];
      }
      const language = outputFiles[0].format.language;
      logProgress(`Creating ${language[kManuscriptMecaBundle]}`);
      const mecaFileName2 = manuscriptConfig.mecaFile;
      const mecaBundle = await createMecaBundle(
        mecaFileName2,
        context,
        projectOutputDir(context),
        outputFiles,
        manuscriptConfig,
        outBundle
      );
      if (mecaBundle) {
        const target = projectOutputDir(context);
        Deno.copyFileSync(
          mecaBundle,
          join4(target, mecaFileName2)
        );
      }
    }
    return Promise.resolve();
  }
};
var codeHintRegexes2 = [/`+{[^\.]+.*}/, /.*"cell_type"\s*:\s*"code".*/];
var hasComputations2 = async (file) => {
  const reader = await Deno.open(file);
  try {
    for await (const line of readLines2(reader)) {
      if (line) {
        if (codeHintRegexes2.find((regex) => {
          return regex.exec(line);
        })) {
          return true;
        }
      }
    }
    return false;
  } finally {
    reader.close();
  }
};
var resolveNotebookDescriptor = (nb, order) => {
  if (typeof nb === "string") {
    nb = { notebook: nb, order };
  }
  return nb;
};
var resolveNotebookDescriptors = (nbs, orderNotebooks = false) => {
  const resolvedNbs = [];
  let order = 0;
  for (const nb of nbs) {
    resolvedNbs.push(
      resolveNotebookDescriptor(nb, orderNotebooks ? order : void 0)
    );
    order++;
  }
  return resolvedNbs;
};
var kTexOutDir = "_tex";
var createTexOutputBundle = (outputFile5, context) => {
  const format14 = outputFile5.format;
  const outDir = projectOutputDir(context);
  const texDirAbs = join4(outDir, `${kTexOutDir}`);
  ensureDirSync(texDirAbs);
  if (format14.pandoc["output-file"]) {
    const baseDir = join4(context.dir, dirname4(outputFile5.input));
    const texInputFile = join4(baseDir, format14.pandoc["output-file"]);
    const texInputDir = dirname4(texInputFile);
    const texOutputFile = join4(texDirAbs, format14.pandoc["output-file"]);
    const textOutputDir = dirname4(texOutputFile);
    Deno.copyFileSync(
      texInputFile,
      texOutputFile
    );
    safeRemoveSync(texInputFile);
    const texBundle = {
      manuscript: texOutputFile,
      supporting: []
    };
    if (outputFile5.supporting) {
      const uniqSupporting = uniq(outputFile5.supporting);
      for (const file of uniqSupporting) {
        const supportingAbs = isAbsolute4(file) ? file : join4(texInputDir, file);
        const outPath = join4(texDirAbs, relative4(context.dir, supportingAbs));
        ensureDirSync(dirname4(outPath));
        copySync(supportingAbs, outPath, { overwrite: true });
        safeRemoveSync(supportingAbs, { recursive: true });
        texBundle.supporting.push(outPath);
      }
    }
    if (outputFile5.resourceFiles) {
      const uniqResources = uniq(outputFile5.resourceFiles);
      for (const file of uniqResources) {
        const outPath = join4(texDirAbs, relative4(context.dir, file));
        ensureDirSync(dirname4(outPath));
        copySync(file, outPath, { overwrite: true });
        texBundle.supporting.push(outPath);
      }
    }
    const docClass = format14.metadata[kDocumentClass];
    const classFile = `${docClass}.cls`;
    const classFilePath = join4(texInputDir, classFile);
    if (existsSync2(classFilePath)) {
      const outClassPath = join4(textOutputDir, classFile);
      copySync(classFilePath, outClassPath, { overwrite: true });
      texBundle.supporting.push(outClassPath);
    }
    if (format14.metadata[kBibliography]) {
      const bibliographies = Array.isArray(format14.metadata[kBibliography]) ? format14.metadata[kBibliography] : [format14.metadata[kBibliography]];
      for (const bibligography of bibliographies) {
        const bibPath = join4(context.dir, bibligography);
        const bibOutPath = join4(textOutputDir, bibligography);
        ensureDirSync(dirname4(bibOutPath));
        copySync(bibPath, bibOutPath, { overwrite: true });
        texBundle.supporting.push(bibOutPath);
      }
    }
    const formatResources = format14.render[kFormatResources];
    if (formatResources) {
      for (const formatResource of formatResources) {
        const resourcePath2 = join4(context.dir, formatResource);
        const resourceOutPath = join4(
          textOutputDir,
          basename4(formatResource)
        );
        if (!safeExistsSync(resourceOutPath)) {
          copySync(resourcePath2, resourceOutPath, { overwrite: true });
          texBundle.supporting.push(resourceOutPath);
        }
      }
    }
    return texBundle;
  } else {
    throw new InternalError(
      "Was expecting there to a Pandoc output file since we're rendering LaTeX"
    );
  }
};

// project/types/register.ts
registerProjectType(bookProjectType);
registerProjectType(defaultProjectType);
registerProjectType(websiteProjectType);
registerProjectType(manuscriptProjectType);

// command/create-project/cmd.ts
var kProjectTypes = projectTypes();
var kProjectTypeAliases = projectTypeAliases();
var kProjectTypesAndAliases = [...kProjectTypes, ...kProjectTypeAliases];
var kEditorTypes = ["source", "visual"];
var createProjectCommand = new Command().name("create-project").description("Create a project for rendering multiple documents").arguments("[dir:string]").hidden().option(
  "--title <title:string>",
  "Project title"
).option(
  "--type <type:string>",
  `Project type (${kProjectTypes.join(", ")})`
).option(
  "--template <type:string>",
  `Use a specific project template`
).option(
  "--engine <engine:string>",
  "Use execution engine (jupyter, knitr, markdown, ...)",
  {
    value: (value) => {
      value = value || kMarkdownEngine;
      const match = value.match(/(\w+)(:(.+))?$/);
      if (match) {
        return [match[1], match[3]];
      } else {
        return [value];
      }
    }
  }
).option(
  "--editor <editor:string>",
  "Default editor for project ('source' or 'visual')"
).option(
  "--with-venv [packages:string]",
  "Create a virtualenv for this project"
).option(
  "--with-condaenv [packages:string]",
  "Create a condaenv for this project"
).option(
  "--no-scaffold",
  "Don't create initial project file(s)"
).example(
  "Create a project in the current directory",
  "quarto create-project"
).example(
  "Create a project in the 'myproject' directory",
  "quarto create-project myproject"
).example(
  "Create a website project",
  "quarto create-project mysite --type website"
).example(
  "Create a blog project",
  "quarto create-project mysite --type website --template blog"
).example(
  "Create a book project",
  "quarto create-project mybook --type book"
).example(
  "Create a website project with jupyter",
  "quarto create-project mysite --type website --engine jupyter"
).example(
  "Create a website project with jupyter + kernel",
  "quarto create-project mysite --type website --engine jupyter:python3"
).example(
  "Create a book project with knitr",
  "quarto create-project mybook --type book --engine knitr"
).example(
  "Create jupyter project with virtualenv",
  "quarto create-project myproject --engine jupyter --with-venv"
).example(
  "Create jupyter project with virtualenv + packages",
  "quarto create-project myproject --engine jupyter --with-venv pandas,matplotlib"
).example(
  "Create jupyter project with condaenv ",
  "quarto create-project myproject --engine jupyter --with-condaenv"
).example(
  "Create jupyter project with condaenv + packages",
  "quarto create-project myproject --engine jupyter --with-condaenv pandas,matplotlib"
).action(async (options, dir) => {
  await initializeProjectContextAndEngines();
  if (dir === void 0 || dir === ".") {
    dir = Deno.cwd();
  }
  const engine = options.engine || [];
  if (engine[0]) {
    const engineInstance = executionEngine(engine[0]);
    if (!engineInstance) {
      throw new Error(
        `Unknown execution engine: ${engine[0]}. Available engines: ${executionEngines().map((e5) => e5.name).join(", ")}`
      );
    }
  }
  const envPackages = typeof options.withVenv === "string" ? options.withVenv.split(",").map((pkg) => pkg.trim()) : typeof options.withCondaenv === "string" ? options.withCondaenv.split(",").map((pkg) => pkg.trim()) : void 0;
  const { type: type4, template: template2 } = parseProjectType(options.type);
  const projectTemplate = options.template || template2;
  if (kProjectTypesAndAliases.indexOf(type4) === -1) {
    throw new Error(
      `Project type must be one of ${kProjectTypes.join(", ")}, but got "${type4}".`
    );
  }
  const editorType = options.editor;
  if (editorType && !kEditorTypes.includes(editorType)) {
    throw new Error(
      `Editor type must be one of ${kEditorTypes.join(", ")}, but got "${editorType}".`
    );
  }
  const projType = projectType(type4);
  if (projectTemplate && !projType.templates?.includes(projectTemplate)) {
    if (projType.templates) {
      throw new Error(
        `Project template must be one of ${projType.templates.join(", ")}, but got "${projectTemplate}".`
      );
    } else {
      throw new Error(
        `The project type ${type4} does not support any templates.`
      );
    }
  }
  await projectCreate({
    dir,
    type: type4,
    title: options.title || basename4(dir),
    scaffold: !!options.scaffold,
    engine: engine[0] || kMarkdownEngine,
    kernel: engine[1],
    editor: editorType,
    venv: !!options.withVenv,
    condaenv: !!options.withCondaenv,
    envPackages,
    template: projectTemplate
  });
});

// tools/tools-console.ts
init_colors2();

// https://deno.land/std@0.196.0/_util/os.ts
var osType3 = (() => {
  const { Deno: Deno6 } = globalThis;
  if (typeof Deno6?.build?.os === "string") {
    return Deno6.build.os;
  }
  const { navigator: navigator2 } = globalThis;
  if (navigator2?.appVersion?.includes?.("Win")) {
    return "windows";
  }
  return "linux";
})();
var isWindows8 = osType3 === "windows";

// https://deno.land/std@0.196.0/path/win32.ts
var win32_exports = {};
__export(win32_exports, {
  basename: () => basename10,
  delimiter: () => delimiter3,
  dirname: () => dirname10,
  extname: () => extname9,
  format: () => format11,
  fromFileUrl: () => fromFileUrl10,
  isAbsolute: () => isAbsolute9,
  join: () => join13,
  normalize: () => normalize10,
  parse: () => parse17,
  relative: () => relative9,
  resolve: () => resolve12,
  sep: () => sep3,
  toFileUrl: () => toFileUrl9,
  toNamespacedPath: () => toNamespacedPath7
});

// https://deno.land/std@0.196.0/path/_constants.ts
var CHAR_UPPERCASE_A4 = 65;
var CHAR_LOWERCASE_A4 = 97;
var CHAR_UPPERCASE_Z4 = 90;
var CHAR_LOWERCASE_Z4 = 122;
var CHAR_DOT4 = 46;
var CHAR_FORWARD_SLASH4 = 47;
var CHAR_BACKWARD_SLASH4 = 92;
var CHAR_COLON6 = 58;
var CHAR_QUESTION_MARK4 = 63;

// https://deno.land/std@0.196.0/path/_util.ts
function assertPath4(path3) {
  if (typeof path3 !== "string") {
    throw new TypeError(
      `Path must be a string. Received ${JSON.stringify(path3)}`
    );
  }
}
function isPosixPathSeparator7(code5) {
  return code5 === CHAR_FORWARD_SLASH4;
}
function isPathSeparator4(code5) {
  return isPosixPathSeparator7(code5) || code5 === CHAR_BACKWARD_SLASH4;
}
function isWindowsDeviceRoot4(code5) {
  return code5 >= CHAR_LOWERCASE_A4 && code5 <= CHAR_LOWERCASE_Z4 || code5 >= CHAR_UPPERCASE_A4 && code5 <= CHAR_UPPERCASE_Z4;
}
function normalizeString4(path3, allowAboveRoot, separator, isPathSeparator5) {
  let res = "";
  let lastSegmentLength = 0;
  let lastSlash = -1;
  let dots = 0;
  let code5;
  for (let i6 = 0, len = path3.length; i6 <= len; ++i6) {
    if (i6 < len) code5 = path3.charCodeAt(i6);
    else if (isPathSeparator5(code5)) break;
    else code5 = CHAR_FORWARD_SLASH4;
    if (isPathSeparator5(code5)) {
      if (lastSlash === i6 - 1 || dots === 1) {
      } else if (lastSlash !== i6 - 1 && dots === 2) {
        if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== CHAR_DOT4 || res.charCodeAt(res.length - 2) !== CHAR_DOT4) {
          if (res.length > 2) {
            const lastSlashIndex = res.lastIndexOf(separator);
            if (lastSlashIndex === -1) {
              res = "";
              lastSegmentLength = 0;
            } else {
              res = res.slice(0, lastSlashIndex);
              lastSegmentLength = res.length - 1 - res.lastIndexOf(separator);
            }
            lastSlash = i6;
            dots = 0;
            continue;
          } else if (res.length === 2 || res.length === 1) {
            res = "";
            lastSegmentLength = 0;
            lastSlash = i6;
            dots = 0;
            continue;
          }
        }
        if (allowAboveRoot) {
          if (res.length > 0) res += `${separator}..`;
          else res = "..";
          lastSegmentLength = 2;
        }
      } else {
        if (res.length > 0) res += separator + path3.slice(lastSlash + 1, i6);
        else res = path3.slice(lastSlash + 1, i6);
        lastSegmentLength = i6 - lastSlash - 1;
      }
      lastSlash = i6;
      dots = 0;
    } else if (code5 === CHAR_DOT4 && dots !== -1) {
      ++dots;
    } else {
      dots = -1;
    }
  }
  return res;
}
function _format4(sep6, pathObject) {
  const dir = pathObject.dir || pathObject.root;
  const base3 = pathObject.base || (pathObject.name || "") + (pathObject.ext || "");
  if (!dir) return base3;
  if (base3 === sep6) return dir;
  if (dir === pathObject.root) return dir + base3;
  return dir + sep6 + base3;
}
var WHITESPACE_ENCODINGS2 = {
  "	": "%09",
  "\n": "%0A",
  "\v": "%0B",
  "\f": "%0C",
  "\r": "%0D",
  " ": "%20"
};
function encodeWhitespace4(string2) {
  return string2.replaceAll(/[\s]/g, (c6) => {
    return WHITESPACE_ENCODINGS2[c6] ?? c6;
  });
}
function lastPathSegment4(path3, isSep, start = 0) {
  let matchedNonSeparator = false;
  let end = path3.length;
  for (let i6 = path3.length - 1; i6 >= start; --i6) {
    if (isSep(path3.charCodeAt(i6))) {
      if (matchedNonSeparator) {
        start = i6 + 1;
        break;
      }
    } else if (!matchedNonSeparator) {
      matchedNonSeparator = true;
      end = i6 + 1;
    }
  }
  return path3.slice(start, end);
}
function stripTrailingSeparators4(segment, isSep) {
  if (segment.length <= 1) {
    return segment;
  }
  let end = segment.length;
  for (let i6 = segment.length - 1; i6 > 0; i6--) {
    if (isSep(segment.charCodeAt(i6))) {
      end = i6;
    } else {
      break;
    }
  }
  return segment.slice(0, end);
}
function stripSuffix4(name2, suffix) {
  if (suffix.length >= name2.length) {
    return name2;
  }
  const lenDiff = name2.length - suffix.length;
  for (let i6 = suffix.length - 1; i6 >= 0; --i6) {
    if (name2.charCodeAt(lenDiff + i6) !== suffix.charCodeAt(i6)) {
      return name2;
    }
  }
  return name2.slice(0, -suffix.length);
}

// https://deno.land/std@0.196.0/assert/assertion_error.ts
var AssertionError5 = class extends Error {
  name = "AssertionError";
  constructor(message) {
    super(message);
  }
};

// https://deno.land/std@0.196.0/assert/assert.ts
function assert9(expr, msg5 = "") {
  if (!expr) {
    throw new AssertionError5(msg5);
  }
}

// https://deno.land/std@0.196.0/path/win32.ts
var sep3 = "\\";
var delimiter3 = ";";
function resolve12(...pathSegments) {
  let resolvedDevice = "";
  let resolvedTail = "";
  let resolvedAbsolute = false;
  for (let i6 = pathSegments.length - 1; i6 >= -1; i6--) {
    let path3;
    const { Deno: Deno6 } = globalThis;
    if (i6 >= 0) {
      path3 = pathSegments[i6];
    } else if (!resolvedDevice) {
      if (typeof Deno6?.cwd !== "function") {
        throw new TypeError("Resolved a drive-letter-less path without a CWD.");
      }
      path3 = Deno6.cwd();
    } else {
      if (typeof Deno6?.env?.get !== "function" || typeof Deno6?.cwd !== "function") {
        throw new TypeError("Resolved a relative path without a CWD.");
      }
      path3 = Deno6.cwd();
      if (path3 === void 0 || path3.slice(0, 3).toLowerCase() !== `${resolvedDevice.toLowerCase()}\\`) {
        path3 = `${resolvedDevice}\\`;
      }
    }
    assertPath4(path3);
    const len = path3.length;
    if (len === 0) continue;
    let rootEnd = 0;
    let device = "";
    let isAbsolute12 = false;
    const code5 = path3.charCodeAt(0);
    if (len > 1) {
      if (isPathSeparator4(code5)) {
        isAbsolute12 = true;
        if (isPathSeparator4(path3.charCodeAt(1))) {
          let j3 = 2;
          let last = j3;
          for (; j3 < len; ++j3) {
            if (isPathSeparator4(path3.charCodeAt(j3))) break;
          }
          if (j3 < len && j3 !== last) {
            const firstPart = path3.slice(last, j3);
            last = j3;
            for (; j3 < len; ++j3) {
              if (!isPathSeparator4(path3.charCodeAt(j3))) break;
            }
            if (j3 < len && j3 !== last) {
              last = j3;
              for (; j3 < len; ++j3) {
                if (isPathSeparator4(path3.charCodeAt(j3))) break;
              }
              if (j3 === len) {
                device = `\\\\${firstPart}\\${path3.slice(last)}`;
                rootEnd = j3;
              } else if (j3 !== last) {
                device = `\\\\${firstPart}\\${path3.slice(last, j3)}`;
                rootEnd = j3;
              }
            }
          }
        } else {
          rootEnd = 1;
        }
      } else if (isWindowsDeviceRoot4(code5)) {
        if (path3.charCodeAt(1) === CHAR_COLON6) {
          device = path3.slice(0, 2);
          rootEnd = 2;
          if (len > 2) {
            if (isPathSeparator4(path3.charCodeAt(2))) {
              isAbsolute12 = true;
              rootEnd = 3;
            }
          }
        }
      }
    } else if (isPathSeparator4(code5)) {
      rootEnd = 1;
      isAbsolute12 = true;
    }
    if (device.length > 0 && resolvedDevice.length > 0 && device.toLowerCase() !== resolvedDevice.toLowerCase()) {
      continue;
    }
    if (resolvedDevice.length === 0 && device.length > 0) {
      resolvedDevice = device;
    }
    if (!resolvedAbsolute) {
      resolvedTail = `${path3.slice(rootEnd)}\\${resolvedTail}`;
      resolvedAbsolute = isAbsolute12;
    }
    if (resolvedAbsolute && resolvedDevice.length > 0) break;
  }
  resolvedTail = normalizeString4(
    resolvedTail,
    !resolvedAbsolute,
    "\\",
    isPathSeparator4
  );
  return resolvedDevice + (resolvedAbsolute ? "\\" : "") + resolvedTail || ".";
}
function normalize10(path3) {
  assertPath4(path3);
  const len = path3.length;
  if (len === 0) return ".";
  let rootEnd = 0;
  let device;
  let isAbsolute12 = false;
  const code5 = path3.charCodeAt(0);
  if (len > 1) {
    if (isPathSeparator4(code5)) {
      isAbsolute12 = true;
      if (isPathSeparator4(path3.charCodeAt(1))) {
        let j3 = 2;
        let last = j3;
        for (; j3 < len; ++j3) {
          if (isPathSeparator4(path3.charCodeAt(j3))) break;
        }
        if (j3 < len && j3 !== last) {
          const firstPart = path3.slice(last, j3);
          last = j3;
          for (; j3 < len; ++j3) {
            if (!isPathSeparator4(path3.charCodeAt(j3))) break;
          }
          if (j3 < len && j3 !== last) {
            last = j3;
            for (; j3 < len; ++j3) {
              if (isPathSeparator4(path3.charCodeAt(j3))) break;
            }
            if (j3 === len) {
              return `\\\\${firstPart}\\${path3.slice(last)}\\`;
            } else if (j3 !== last) {
              device = `\\\\${firstPart}\\${path3.slice(last, j3)}`;
              rootEnd = j3;
            }
          }
        }
      } else {
        rootEnd = 1;
      }
    } else if (isWindowsDeviceRoot4(code5)) {
      if (path3.charCodeAt(1) === CHAR_COLON6) {
        device = path3.slice(0, 2);
        rootEnd = 2;
        if (len > 2) {
          if (isPathSeparator4(path3.charCodeAt(2))) {
            isAbsolute12 = true;
            rootEnd = 3;
          }
        }
      }
    }
  } else if (isPathSeparator4(code5)) {
    return "\\";
  }
  let tail;
  if (rootEnd < len) {
    tail = normalizeString4(
      path3.slice(rootEnd),
      !isAbsolute12,
      "\\",
      isPathSeparator4
    );
  } else {
    tail = "";
  }
  if (tail.length === 0 && !isAbsolute12) tail = ".";
  if (tail.length > 0 && isPathSeparator4(path3.charCodeAt(len - 1))) {
    tail += "\\";
  }
  if (device === void 0) {
    if (isAbsolute12) {
      if (tail.length > 0) return `\\${tail}`;
      else return "\\";
    } else if (tail.length > 0) {
      return tail;
    } else {
      return "";
    }
  } else if (isAbsolute12) {
    if (tail.length > 0) return `${device}\\${tail}`;
    else return `${device}\\`;
  } else if (tail.length > 0) {
    return device + tail;
  } else {
    return device;
  }
}
function isAbsolute9(path3) {
  assertPath4(path3);
  const len = path3.length;
  if (len === 0) return false;
  const code5 = path3.charCodeAt(0);
  if (isPathSeparator4(code5)) {
    return true;
  } else if (isWindowsDeviceRoot4(code5)) {
    if (len > 2 && path3.charCodeAt(1) === CHAR_COLON6) {
      if (isPathSeparator4(path3.charCodeAt(2))) return true;
    }
  }
  return false;
}
function join13(...paths) {
  const pathsCount = paths.length;
  if (pathsCount === 0) return ".";
  let joined;
  let firstPart = null;
  for (let i6 = 0; i6 < pathsCount; ++i6) {
    const path3 = paths[i6];
    assertPath4(path3);
    if (path3.length > 0) {
      if (joined === void 0) joined = firstPart = path3;
      else joined += `\\${path3}`;
    }
  }
  if (joined === void 0) return ".";
  let needsReplace = true;
  let slashCount = 0;
  assert9(firstPart != null);
  if (isPathSeparator4(firstPart.charCodeAt(0))) {
    ++slashCount;
    const firstLen = firstPart.length;
    if (firstLen > 1) {
      if (isPathSeparator4(firstPart.charCodeAt(1))) {
        ++slashCount;
        if (firstLen > 2) {
          if (isPathSeparator4(firstPart.charCodeAt(2))) ++slashCount;
          else {
            needsReplace = false;
          }
        }
      }
    }
  }
  if (needsReplace) {
    for (; slashCount < joined.length; ++slashCount) {
      if (!isPathSeparator4(joined.charCodeAt(slashCount))) break;
    }
    if (slashCount >= 2) joined = `\\${joined.slice(slashCount)}`;
  }
  return normalize10(joined);
}
function relative9(from, to) {
  assertPath4(from);
  assertPath4(to);
  if (from === to) return "";
  const fromOrig = resolve12(from);
  const toOrig = resolve12(to);
  if (fromOrig === toOrig) return "";
  from = fromOrig.toLowerCase();
  to = toOrig.toLowerCase();
  if (from === to) return "";
  let fromStart = 0;
  let fromEnd = from.length;
  for (; fromStart < fromEnd; ++fromStart) {
    if (from.charCodeAt(fromStart) !== CHAR_BACKWARD_SLASH4) break;
  }
  for (; fromEnd - 1 > fromStart; --fromEnd) {
    if (from.charCodeAt(fromEnd - 1) !== CHAR_BACKWARD_SLASH4) break;
  }
  const fromLen = fromEnd - fromStart;
  let toStart = 0;
  let toEnd = to.length;
  for (; toStart < toEnd; ++toStart) {
    if (to.charCodeAt(toStart) !== CHAR_BACKWARD_SLASH4) break;
  }
  for (; toEnd - 1 > toStart; --toEnd) {
    if (to.charCodeAt(toEnd - 1) !== CHAR_BACKWARD_SLASH4) break;
  }
  const toLen = toEnd - toStart;
  const length = fromLen < toLen ? fromLen : toLen;
  let lastCommonSep = -1;
  let i6 = 0;
  for (; i6 <= length; ++i6) {
    if (i6 === length) {
      if (toLen > length) {
        if (to.charCodeAt(toStart + i6) === CHAR_BACKWARD_SLASH4) {
          return toOrig.slice(toStart + i6 + 1);
        } else if (i6 === 2) {
          return toOrig.slice(toStart + i6);
        }
      }
      if (fromLen > length) {
        if (from.charCodeAt(fromStart + i6) === CHAR_BACKWARD_SLASH4) {
          lastCommonSep = i6;
        } else if (i6 === 2) {
          lastCommonSep = 3;
        }
      }
      break;
    }
    const fromCode = from.charCodeAt(fromStart + i6);
    const toCode = to.charCodeAt(toStart + i6);
    if (fromCode !== toCode) break;
    else if (fromCode === CHAR_BACKWARD_SLASH4) lastCommonSep = i6;
  }
  if (i6 !== length && lastCommonSep === -1) {
    return toOrig;
  }
  let out = "";
  if (lastCommonSep === -1) lastCommonSep = 0;
  for (i6 = fromStart + lastCommonSep + 1; i6 <= fromEnd; ++i6) {
    if (i6 === fromEnd || from.charCodeAt(i6) === CHAR_BACKWARD_SLASH4) {
      if (out.length === 0) out += "..";
      else out += "\\..";
    }
  }
  if (out.length > 0) {
    return out + toOrig.slice(toStart + lastCommonSep, toEnd);
  } else {
    toStart += lastCommonSep;
    if (toOrig.charCodeAt(toStart) === CHAR_BACKWARD_SLASH4) ++toStart;
    return toOrig.slice(toStart, toEnd);
  }
}
function toNamespacedPath7(path3) {
  if (typeof path3 !== "string") return path3;
  if (path3.length === 0) return "";
  const resolvedPath = resolve12(path3);
  if (resolvedPath.length >= 3) {
    if (resolvedPath.charCodeAt(0) === CHAR_BACKWARD_SLASH4) {
      if (resolvedPath.charCodeAt(1) === CHAR_BACKWARD_SLASH4) {
        const code5 = resolvedPath.charCodeAt(2);
        if (code5 !== CHAR_QUESTION_MARK4 && code5 !== CHAR_DOT4) {
          return `\\\\?\\UNC\\${resolvedPath.slice(2)}`;
        }
      }
    } else if (isWindowsDeviceRoot4(resolvedPath.charCodeAt(0))) {
      if (resolvedPath.charCodeAt(1) === CHAR_COLON6 && resolvedPath.charCodeAt(2) === CHAR_BACKWARD_SLASH4) {
        return `\\\\?\\${resolvedPath}`;
      }
    }
  }
  return path3;
}
function dirname10(path3) {
  assertPath4(path3);
  const len = path3.length;
  if (len === 0) return ".";
  let rootEnd = -1;
  let end = -1;
  let matchedSlash = true;
  let offset3 = 0;
  const code5 = path3.charCodeAt(0);
  if (len > 1) {
    if (isPathSeparator4(code5)) {
      rootEnd = offset3 = 1;
      if (isPathSeparator4(path3.charCodeAt(1))) {
        let j3 = 2;
        let last = j3;
        for (; j3 < len; ++j3) {
          if (isPathSeparator4(path3.charCodeAt(j3))) break;
        }
        if (j3 < len && j3 !== last) {
          last = j3;
          for (; j3 < len; ++j3) {
            if (!isPathSeparator4(path3.charCodeAt(j3))) break;
          }
          if (j3 < len && j3 !== last) {
            last = j3;
            for (; j3 < len; ++j3) {
              if (isPathSeparator4(path3.charCodeAt(j3))) break;
            }
            if (j3 === len) {
              return path3;
            }
            if (j3 !== last) {
              rootEnd = offset3 = j3 + 1;
            }
          }
        }
      }
    } else if (isWindowsDeviceRoot4(code5)) {
      if (path3.charCodeAt(1) === CHAR_COLON6) {
        rootEnd = offset3 = 2;
        if (len > 2) {
          if (isPathSeparator4(path3.charCodeAt(2))) rootEnd = offset3 = 3;
        }
      }
    }
  } else if (isPathSeparator4(code5)) {
    return path3;
  }
  for (let i6 = len - 1; i6 >= offset3; --i6) {
    if (isPathSeparator4(path3.charCodeAt(i6))) {
      if (!matchedSlash) {
        end = i6;
        break;
      }
    } else {
      matchedSlash = false;
    }
  }
  if (end === -1) {
    if (rootEnd === -1) return ".";
    else end = rootEnd;
  }
  return stripTrailingSeparators4(path3.slice(0, end), isPosixPathSeparator7);
}
function basename10(path3, suffix = "") {
  assertPath4(path3);
  if (path3.length === 0) return path3;
  if (typeof suffix !== "string") {
    throw new TypeError(
      `Suffix must be a string. Received ${JSON.stringify(suffix)}`
    );
  }
  let start = 0;
  if (path3.length >= 2) {
    const drive = path3.charCodeAt(0);
    if (isWindowsDeviceRoot4(drive)) {
      if (path3.charCodeAt(1) === CHAR_COLON6) start = 2;
    }
  }
  const lastSegment = lastPathSegment4(path3, isPathSeparator4, start);
  const strippedSegment = stripTrailingSeparators4(lastSegment, isPathSeparator4);
  return suffix ? stripSuffix4(strippedSegment, suffix) : strippedSegment;
}
function extname9(path3) {
  assertPath4(path3);
  let start = 0;
  let startDot = -1;
  let startPart = 0;
  let end = -1;
  let matchedSlash = true;
  let preDotState = 0;
  if (path3.length >= 2 && path3.charCodeAt(1) === CHAR_COLON6 && isWindowsDeviceRoot4(path3.charCodeAt(0))) {
    start = startPart = 2;
  }
  for (let i6 = path3.length - 1; i6 >= start; --i6) {
    const code5 = path3.charCodeAt(i6);
    if (isPathSeparator4(code5)) {
      if (!matchedSlash) {
        startPart = i6 + 1;
        break;
      }
      continue;
    }
    if (end === -1) {
      matchedSlash = false;
      end = i6 + 1;
    }
    if (code5 === CHAR_DOT4) {
      if (startDot === -1) startDot = i6;
      else if (preDotState !== 1) preDotState = 1;
    } else if (startDot !== -1) {
      preDotState = -1;
    }
  }
  if (startDot === -1 || end === -1 || // We saw a non-dot character immediately before the dot
  preDotState === 0 || // The (right-most) trimmed path component is exactly '..'
  preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
    return "";
  }
  return path3.slice(startDot, end);
}
function format11(pathObject) {
  if (pathObject === null || typeof pathObject !== "object") {
    throw new TypeError(
      `The "pathObject" argument must be of type Object. Received type ${typeof pathObject}`
    );
  }
  return _format4("\\", pathObject);
}
function parse17(path3) {
  assertPath4(path3);
  const ret = { root: "", dir: "", base: "", ext: "", name: "" };
  const len = path3.length;
  if (len === 0) return ret;
  let rootEnd = 0;
  let code5 = path3.charCodeAt(0);
  if (len > 1) {
    if (isPathSeparator4(code5)) {
      rootEnd = 1;
      if (isPathSeparator4(path3.charCodeAt(1))) {
        let j3 = 2;
        let last = j3;
        for (; j3 < len; ++j3) {
          if (isPathSeparator4(path3.charCodeAt(j3))) break;
        }
        if (j3 < len && j3 !== last) {
          last = j3;
          for (; j3 < len; ++j3) {
            if (!isPathSeparator4(path3.charCodeAt(j3))) break;
          }
          if (j3 < len && j3 !== last) {
            last = j3;
            for (; j3 < len; ++j3) {
              if (isPathSeparator4(path3.charCodeAt(j3))) break;
            }
            if (j3 === len) {
              rootEnd = j3;
            } else if (j3 !== last) {
              rootEnd = j3 + 1;
            }
          }
        }
      }
    } else if (isWindowsDeviceRoot4(code5)) {
      if (path3.charCodeAt(1) === CHAR_COLON6) {
        rootEnd = 2;
        if (len > 2) {
          if (isPathSeparator4(path3.charCodeAt(2))) {
            if (len === 3) {
              ret.root = ret.dir = path3;
              ret.base = "\\";
              return ret;
            }
            rootEnd = 3;
          }
        } else {
          ret.root = ret.dir = path3;
          return ret;
        }
      }
    }
  } else if (isPathSeparator4(code5)) {
    ret.root = ret.dir = path3;
    ret.base = "\\";
    return ret;
  }
  if (rootEnd > 0) ret.root = path3.slice(0, rootEnd);
  let startDot = -1;
  let startPart = rootEnd;
  let end = -1;
  let matchedSlash = true;
  let i6 = path3.length - 1;
  let preDotState = 0;
  for (; i6 >= rootEnd; --i6) {
    code5 = path3.charCodeAt(i6);
    if (isPathSeparator4(code5)) {
      if (!matchedSlash) {
        startPart = i6 + 1;
        break;
      }
      continue;
    }
    if (end === -1) {
      matchedSlash = false;
      end = i6 + 1;
    }
    if (code5 === CHAR_DOT4) {
      if (startDot === -1) startDot = i6;
      else if (preDotState !== 1) preDotState = 1;
    } else if (startDot !== -1) {
      preDotState = -1;
    }
  }
  if (startDot === -1 || end === -1 || // We saw a non-dot character immediately before the dot
  preDotState === 0 || // The (right-most) trimmed path component is exactly '..'
  preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
    if (end !== -1) {
      ret.base = ret.name = path3.slice(startPart, end);
    }
  } else {
    ret.name = path3.slice(startPart, startDot);
    ret.base = path3.slice(startPart, end);
    ret.ext = path3.slice(startDot, end);
  }
  ret.base = ret.base || "\\";
  if (startPart > 0 && startPart !== rootEnd) {
    ret.dir = path3.slice(0, startPart - 1);
  } else ret.dir = ret.root;
  return ret;
}
function fromFileUrl10(url) {
  url = url instanceof URL ? url : new URL(url);
  if (url.protocol != "file:") {
    throw new TypeError("Must be a file URL.");
  }
  let path3 = decodeURIComponent(
    url.pathname.replace(/\//g, "\\").replace(/%(?![0-9A-Fa-f]{2})/g, "%25")
  ).replace(/^\\*([A-Za-z]:)(\\|$)/, "$1\\");
  if (url.hostname != "") {
    path3 = `\\\\${url.hostname}${path3}`;
  }
  return path3;
}
function toFileUrl9(path3) {
  if (!isAbsolute9(path3)) {
    throw new TypeError("Must be an absolute path.");
  }
  const [, hostname, pathname] = path3.match(
    /^(?:[/\\]{2}([^/\\]+)(?=[/\\](?:[^/\\]|$)))?(.*)/
  );
  const url = new URL("file:///");
  url.pathname = encodeWhitespace4(pathname.replace(/%/g, "%25"));
  if (hostname != null && hostname != "localhost") {
    url.hostname = hostname;
    if (!url.hostname) {
      throw new TypeError("Invalid hostname.");
    }
  }
  return url;
}

// https://deno.land/std@0.196.0/path/posix.ts
var posix_exports = {};
__export(posix_exports, {
  basename: () => basename11,
  delimiter: () => delimiter4,
  dirname: () => dirname11,
  extname: () => extname10,
  format: () => format12,
  fromFileUrl: () => fromFileUrl11,
  isAbsolute: () => isAbsolute10,
  join: () => join14,
  normalize: () => normalize11,
  parse: () => parse18,
  relative: () => relative10,
  resolve: () => resolve13,
  sep: () => sep4,
  toFileUrl: () => toFileUrl10,
  toNamespacedPath: () => toNamespacedPath8
});
var sep4 = "/";
var delimiter4 = ":";
function resolve13(...pathSegments) {
  let resolvedPath = "";
  let resolvedAbsolute = false;
  for (let i6 = pathSegments.length - 1; i6 >= -1 && !resolvedAbsolute; i6--) {
    let path3;
    if (i6 >= 0) path3 = pathSegments[i6];
    else {
      const { Deno: Deno6 } = globalThis;
      if (typeof Deno6?.cwd !== "function") {
        throw new TypeError("Resolved a relative path without a CWD.");
      }
      path3 = Deno6.cwd();
    }
    assertPath4(path3);
    if (path3.length === 0) {
      continue;
    }
    resolvedPath = `${path3}/${resolvedPath}`;
    resolvedAbsolute = isPosixPathSeparator7(path3.charCodeAt(0));
  }
  resolvedPath = normalizeString4(
    resolvedPath,
    !resolvedAbsolute,
    "/",
    isPosixPathSeparator7
  );
  if (resolvedAbsolute) {
    if (resolvedPath.length > 0) return `/${resolvedPath}`;
    else return "/";
  } else if (resolvedPath.length > 0) return resolvedPath;
  else return ".";
}
function normalize11(path3) {
  assertPath4(path3);
  if (path3.length === 0) return ".";
  const isAbsolute12 = isPosixPathSeparator7(path3.charCodeAt(0));
  const trailingSeparator = isPosixPathSeparator7(
    path3.charCodeAt(path3.length - 1)
  );
  path3 = normalizeString4(path3, !isAbsolute12, "/", isPosixPathSeparator7);
  if (path3.length === 0 && !isAbsolute12) path3 = ".";
  if (path3.length > 0 && trailingSeparator) path3 += "/";
  if (isAbsolute12) return `/${path3}`;
  return path3;
}
function isAbsolute10(path3) {
  assertPath4(path3);
  return path3.length > 0 && isPosixPathSeparator7(path3.charCodeAt(0));
}
function join14(...paths) {
  if (paths.length === 0) return ".";
  let joined;
  for (let i6 = 0, len = paths.length; i6 < len; ++i6) {
    const path3 = paths[i6];
    assertPath4(path3);
    if (path3.length > 0) {
      if (!joined) joined = path3;
      else joined += `/${path3}`;
    }
  }
  if (!joined) return ".";
  return normalize11(joined);
}
function relative10(from, to) {
  assertPath4(from);
  assertPath4(to);
  if (from === to) return "";
  from = resolve13(from);
  to = resolve13(to);
  if (from === to) return "";
  let fromStart = 1;
  const fromEnd = from.length;
  for (; fromStart < fromEnd; ++fromStart) {
    if (!isPosixPathSeparator7(from.charCodeAt(fromStart))) break;
  }
  const fromLen = fromEnd - fromStart;
  let toStart = 1;
  const toEnd = to.length;
  for (; toStart < toEnd; ++toStart) {
    if (!isPosixPathSeparator7(to.charCodeAt(toStart))) break;
  }
  const toLen = toEnd - toStart;
  const length = fromLen < toLen ? fromLen : toLen;
  let lastCommonSep = -1;
  let i6 = 0;
  for (; i6 <= length; ++i6) {
    if (i6 === length) {
      if (toLen > length) {
        if (isPosixPathSeparator7(to.charCodeAt(toStart + i6))) {
          return to.slice(toStart + i6 + 1);
        } else if (i6 === 0) {
          return to.slice(toStart + i6);
        }
      } else if (fromLen > length) {
        if (isPosixPathSeparator7(from.charCodeAt(fromStart + i6))) {
          lastCommonSep = i6;
        } else if (i6 === 0) {
          lastCommonSep = 0;
        }
      }
      break;
    }
    const fromCode = from.charCodeAt(fromStart + i6);
    const toCode = to.charCodeAt(toStart + i6);
    if (fromCode !== toCode) break;
    else if (isPosixPathSeparator7(fromCode)) lastCommonSep = i6;
  }
  let out = "";
  for (i6 = fromStart + lastCommonSep + 1; i6 <= fromEnd; ++i6) {
    if (i6 === fromEnd || isPosixPathSeparator7(from.charCodeAt(i6))) {
      if (out.length === 0) out += "..";
      else out += "/..";
    }
  }
  if (out.length > 0) return out + to.slice(toStart + lastCommonSep);
  else {
    toStart += lastCommonSep;
    if (isPosixPathSeparator7(to.charCodeAt(toStart))) ++toStart;
    return to.slice(toStart);
  }
}
function toNamespacedPath8(path3) {
  return path3;
}
function dirname11(path3) {
  if (path3.length === 0) return ".";
  let end = -1;
  let matchedNonSeparator = false;
  for (let i6 = path3.length - 1; i6 >= 1; --i6) {
    if (isPosixPathSeparator7(path3.charCodeAt(i6))) {
      if (matchedNonSeparator) {
        end = i6;
        break;
      }
    } else {
      matchedNonSeparator = true;
    }
  }
  if (end === -1) {
    return isPosixPathSeparator7(path3.charCodeAt(0)) ? "/" : ".";
  }
  return stripTrailingSeparators4(
    path3.slice(0, end),
    isPosixPathSeparator7
  );
}
function basename11(path3, suffix = "") {
  assertPath4(path3);
  if (path3.length === 0) return path3;
  if (typeof suffix !== "string") {
    throw new TypeError(
      `Suffix must be a string. Received ${JSON.stringify(suffix)}`
    );
  }
  const lastSegment = lastPathSegment4(path3, isPosixPathSeparator7);
  const strippedSegment = stripTrailingSeparators4(
    lastSegment,
    isPosixPathSeparator7
  );
  return suffix ? stripSuffix4(strippedSegment, suffix) : strippedSegment;
}
function extname10(path3) {
  assertPath4(path3);
  let startDot = -1;
  let startPart = 0;
  let end = -1;
  let matchedSlash = true;
  let preDotState = 0;
  for (let i6 = path3.length - 1; i6 >= 0; --i6) {
    const code5 = path3.charCodeAt(i6);
    if (isPosixPathSeparator7(code5)) {
      if (!matchedSlash) {
        startPart = i6 + 1;
        break;
      }
      continue;
    }
    if (end === -1) {
      matchedSlash = false;
      end = i6 + 1;
    }
    if (code5 === CHAR_DOT4) {
      if (startDot === -1) startDot = i6;
      else if (preDotState !== 1) preDotState = 1;
    } else if (startDot !== -1) {
      preDotState = -1;
    }
  }
  if (startDot === -1 || end === -1 || // We saw a non-dot character immediately before the dot
  preDotState === 0 || // The (right-most) trimmed path component is exactly '..'
  preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
    return "";
  }
  return path3.slice(startDot, end);
}
function format12(pathObject) {
  if (pathObject === null || typeof pathObject !== "object") {
    throw new TypeError(
      `The "pathObject" argument must be of type Object. Received type ${typeof pathObject}`
    );
  }
  return _format4("/", pathObject);
}
function parse18(path3) {
  assertPath4(path3);
  const ret = { root: "", dir: "", base: "", ext: "", name: "" };
  if (path3.length === 0) return ret;
  const isAbsolute12 = isPosixPathSeparator7(path3.charCodeAt(0));
  let start;
  if (isAbsolute12) {
    ret.root = "/";
    start = 1;
  } else {
    start = 0;
  }
  let startDot = -1;
  let startPart = 0;
  let end = -1;
  let matchedSlash = true;
  let i6 = path3.length - 1;
  let preDotState = 0;
  for (; i6 >= start; --i6) {
    const code5 = path3.charCodeAt(i6);
    if (isPosixPathSeparator7(code5)) {
      if (!matchedSlash) {
        startPart = i6 + 1;
        break;
      }
      continue;
    }
    if (end === -1) {
      matchedSlash = false;
      end = i6 + 1;
    }
    if (code5 === CHAR_DOT4) {
      if (startDot === -1) startDot = i6;
      else if (preDotState !== 1) preDotState = 1;
    } else if (startDot !== -1) {
      preDotState = -1;
    }
  }
  if (startDot === -1 || end === -1 || // We saw a non-dot character immediately before the dot
  preDotState === 0 || // The (right-most) trimmed path component is exactly '..'
  preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
    if (end !== -1) {
      if (startPart === 0 && isAbsolute12) {
        ret.base = ret.name = path3.slice(1, end);
      } else {
        ret.base = ret.name = path3.slice(startPart, end);
      }
    }
    ret.base = ret.base || "/";
  } else {
    if (startPart === 0 && isAbsolute12) {
      ret.name = path3.slice(1, startDot);
      ret.base = path3.slice(1, end);
    } else {
      ret.name = path3.slice(startPart, startDot);
      ret.base = path3.slice(startPart, end);
    }
    ret.ext = path3.slice(startDot, end);
  }
  if (startPart > 0) {
    ret.dir = stripTrailingSeparators4(
      path3.slice(0, startPart - 1),
      isPosixPathSeparator7
    );
  } else if (isAbsolute12) ret.dir = "/";
  return ret;
}
function fromFileUrl11(url) {
  url = url instanceof URL ? url : new URL(url);
  if (url.protocol != "file:") {
    throw new TypeError("Must be a file URL.");
  }
  return decodeURIComponent(
    url.pathname.replace(/%(?![0-9A-Fa-f]{2})/g, "%25")
  );
}
function toFileUrl10(path3) {
  if (!isAbsolute10(path3)) {
    throw new TypeError("Must be an absolute path.");
  }
  const url = new URL("file:///");
  url.pathname = encodeWhitespace4(
    path3.replace(/%/g, "%25").replace(/\\/g, "%5C")
  );
  return url;
}

// https://deno.land/std@0.196.0/path/glob.ts
var path = isWindows8 ? win32_exports : posix_exports;
var { join: join15, normalize: normalize12 } = path;

// https://deno.land/std@0.196.0/path/mod.ts
var path2 = isWindows8 ? win32_exports : posix_exports;
var {
  basename: basename12,
  delimiter: delimiter5,
  dirname: dirname12,
  extname: extname11,
  format: format13,
  fromFileUrl: fromFileUrl12,
  isAbsolute: isAbsolute11,
  join: join16,
  normalize: normalize13,
  parse: parse19,
  relative: relative11,
  resolve: resolve14,
  toFileUrl: toFileUrl11,
  toNamespacedPath: toNamespacedPath9
} = path2;

// https://deno.land/x/cliffy@v1.0.0-rc.3/prompt/_figures.ts
var main = {
  ARROW_UP: "\u2191",
  ARROW_DOWN: "\u2193",
  ARROW_LEFT: "\u2190",
  ARROW_RIGHT: "\u2192",
  ARROW_UP_LEFT: "\u2196",
  ARROW_UP_RIGHT: "\u2197",
  ARROW_DOWN_RIGHT: "\u2198",
  ARROW_DOWN_LEFT: "\u2199",
  RADIO_ON: "\u25C9",
  RADIO_OFF: "\u25EF",
  TICK: "\u2714",
  CROSS: "\u2718",
  ELLIPSIS: "\u2026",
  POINTER_SMALL: "\u203A",
  POINTER_SMALL_LEFT: "\u2039",
  LINE: "\u2500",
  POINTER: "\u276F",
  POINTER_LEFT: "\u276E",
  INFO: "\u2139",
  TAB_LEFT: "\u21E4",
  TAB_RIGHT: "\u21E5",
  ESCAPE: "\u238B",
  BACKSPACE: "\u232B",
  PAGE_UP: "\u21DE",
  PAGE_DOWN: "\u21DF",
  ENTER: "\u21B5",
  SEARCH: "\u{1F50E}",
  FOLDER: "\u{1F4C1}",
  FOLDER_OPEN: "\u{1F4C2}"
};
var win = {
  ...main,
  RADIO_ON: "(*)",
  RADIO_OFF: "( )",
  TICK: "\u221A",
  CROSS: "\xD7",
  POINTER_SMALL: "\xBB"
};
var Figures = Deno.build.os === "windows" ? win : main;
var keyMap = {
  up: "ARROW_UP",
  down: "ARROW_DOWN",
  left: "ARROW_LEFT",
  right: "ARROW_RIGHT",
  pageup: "PAGE_UP",
  pagedown: "PAGE_DOWN",
  tab: "TAB_RIGHT",
  enter: "ENTER",
  return: "ENTER"
};
function getFiguresByKeys(keys) {
  const figures = [];
  for (const key of keys) {
    const figure = Figures[keyMap[key]] ?? key;
    if (!figures.includes(figure)) {
      figures.push(figure);
    }
  }
  return figures;
}

// https://deno.land/x/cliffy@v1.0.0-rc.3/keycode/_key_codes.ts
var KeyMap = {
  /* xterm/gnome ESC [ letter (with modifier) */
  "[P": "f1",
  "[Q": "f2",
  "[R": "f3",
  "[S": "f4",
  /* xterm/gnome ESC O letter (without modifier) */
  "OP": "f1",
  "OQ": "f2",
  "OR": "f3",
  "OS": "f4",
  /* xterm/rxvt ESC [ number ~ */
  "[11~": "f1",
  "[12~": "f2",
  "[13~": "f3",
  "[14~": "f4",
  /* from Cygwin and used in libuv */
  "[[A": "f1",
  "[[B": "f2",
  "[[C": "f3",
  "[[D": "f4",
  "[[E": "f5",
  /* common */
  "[15~": "f5",
  "[17~": "f6",
  "[18~": "f7",
  "[19~": "f8",
  "[20~": "f9",
  "[21~": "f10",
  "[23~": "f11",
  "[24~": "f12",
  /* xterm ESC [ letter */
  "[A": "up",
  "[B": "down",
  "[C": "right",
  "[D": "left",
  "[E": "clear",
  "[F": "end",
  "[H": "home",
  /* xterm/gnome ESC O letter */
  "OA": "up",
  "OB": "down",
  "OC": "right",
  "OD": "left",
  "OE": "clear",
  "OF": "end",
  "OH": "home",
  /* xterm/rxvt ESC [ number ~ */
  "[1~": "home",
  "[2~": "insert",
  "[3~": "delete",
  "[4~": "end",
  "[5~": "pageup",
  "[6~": "pagedown",
  /* putty */
  "[[5~": "pageup",
  "[[6~": "pagedown",
  /* rxvt */
  "[7~": "home",
  "[8~": "end"
};
var KeyMapShift = {
  /* rxvt keys with modifiers */
  "[a": "up",
  "[b": "down",
  "[c": "right",
  "[d": "left",
  "[e": "clear",
  "[2$": "insert",
  "[3$": "delete",
  "[5$": "pageup",
  "[6$": "pagedown",
  "[7$": "home",
  "[8$": "end",
  "[Z": "tab"
};
var KeyMapCtrl = {
  /* rxvt keys with modifiers */
  "Oa": "up",
  "Ob": "down",
  "Oc": "right",
  "Od": "left",
  "Oe": "clear",
  "[2^": "insert",
  "[3^": "delete",
  "[5^": "pageup",
  "[6^": "pagedown",
  "[7^": "home",
  "[8^": "end"
};
var SpecialKeyMap = {
  "\r": "return",
  "\n": "enter",
  "	": "tab",
  "\b": "backspace",
  "\x7F": "backspace",
  "\x1B": "escape",
  " ": "space"
};

// https://deno.land/x/cliffy@v1.0.0-rc.3/keycode/key_code.ts
var kUTF16SurrogateThreshold = 65536;
var kEscape = "\x1B";
function parse20(data3) {
  let index2 = -1;
  const keys = [];
  const input = data3 instanceof Uint8Array ? new TextDecoder().decode(data3) : data3;
  const hasNext = () => input.length - 1 >= index2 + 1;
  const next = () => input[++index2];
  parseNext();
  return keys;
  function parseNext() {
    let ch = next();
    let s5 = ch;
    let escaped = false;
    const key = {
      name: void 0,
      char: void 0,
      sequence: void 0,
      code: void 0,
      ctrl: false,
      meta: false,
      shift: false
    };
    if (ch === kEscape && hasNext()) {
      escaped = true;
      s5 += ch = next();
      if (ch === kEscape) {
        s5 += ch = next();
      }
    }
    if (escaped && (ch === "O" || ch === "[")) {
      let code5 = ch;
      let modifier = 0;
      if (ch === "O") {
        s5 += ch = next();
        if (ch >= "0" && ch <= "9") {
          modifier = (Number(ch) >> 0) - 1;
          s5 += ch = next();
        }
        code5 += ch;
      } else if (ch === "[") {
        s5 += ch = next();
        if (ch === "[") {
          code5 += ch;
          s5 += ch = next();
        }
        const cmdStart = s5.length - 1;
        if (ch >= "0" && ch <= "9") {
          s5 += ch = next();
          if (ch >= "0" && ch <= "9") {
            s5 += ch = next();
          }
        }
        if (ch === ";") {
          s5 += ch = next();
          if (ch >= "0" && ch <= "9") {
            s5 += next();
          }
        }
        const cmd = s5.slice(cmdStart);
        let match;
        if (match = cmd.match(/^(\d\d?)(;(\d))?([~^$])$/)) {
          code5 += match[1] + match[4];
          modifier = (Number(match[3]) || 1) - 1;
        } else if (match = cmd.match(/^((\d;)?(\d))?([A-Za-z])$/)) {
          code5 += match[4];
          modifier = (Number(match[3]) || 1) - 1;
        } else {
          code5 += cmd;
        }
      }
      key.ctrl = !!(modifier & 4);
      key.meta = !!(modifier & 10);
      key.shift = !!(modifier & 1);
      key.code = code5;
      if (code5 in KeyMap) {
        key.name = KeyMap[code5];
      } else if (code5 in KeyMapShift) {
        key.name = KeyMapShift[code5];
        key.shift = true;
      } else if (code5 in KeyMapCtrl) {
        key.name = KeyMapCtrl[code5];
        key.ctrl = true;
      } else {
        key.name = "undefined";
      }
    } else if (ch in SpecialKeyMap) {
      key.name = SpecialKeyMap[ch];
      key.meta = escaped;
      if (key.name === "space") {
        key.char = ch;
      }
    } else if (!escaped && ch <= "") {
      key.name = String.fromCharCode(
        ch.charCodeAt(0) + "a".charCodeAt(0) - 1
      );
      key.ctrl = true;
      key.char = key.name;
    } else if (/^[0-9A-Za-z]$/.test(ch)) {
      key.name = ch.toLowerCase();
      key.shift = /^[A-Z]$/.test(ch);
      key.meta = escaped;
      key.char = ch;
    } else if (escaped) {
      key.name = ch.length ? void 0 : "escape";
      key.meta = true;
    } else {
      key.name = ch;
      key.char = ch;
    }
    key.sequence = s5;
    if (s5.length !== 0 && (key.name !== void 0 || escaped) || charLengthAt(s5, 0) === s5.length) {
      keys.push(key);
    } else {
      throw new Error("Unrecognized or broken escape sequence");
    }
    if (hasNext()) {
      parseNext();
    }
  }
}
function charLengthAt(str3, i6) {
  const pos = str3.codePointAt(i6);
  if (typeof pos === "undefined") {
    return 1;
  }
  return pos >= kUTF16SurrogateThreshold ? 2 : 1;
}

// https://deno.land/x/cliffy@v1.0.0-rc.3/prompt/_generic_prompt.ts
var GenericPrompt = class _GenericPrompt {
  static injectedValue;
  cursor = {
    x: 0,
    y: 0
  };
  #value;
  #lastError;
  #isFirstRun = true;
  #encoder = new TextEncoder();
  /**
   * Inject prompt value. If called, the prompt doesn't prompt for an input and
   * returns immediately the injected value. Can be used for unit tests or pre
   * selections.
   *
   * @param value Input value.
   */
  static inject(value) {
    _GenericPrompt.injectedValue = value;
  }
  getDefaultSettings(options) {
    return {
      ...options,
      tty: tty({
        // Stdin is only used by getCursorPosition which we don't need.
        reader: Deno.stdin,
        writer: options.writer ?? Deno.stdout
      }),
      cbreak: options.cbreak ?? false,
      reader: options.reader ?? Deno.stdin,
      writer: options.writer ?? Deno.stdout,
      pointer: options.pointer ?? brightBlue(Figures.POINTER_SMALL),
      prefix: options.prefix ?? yellow2("? "),
      indent: options.indent ?? "",
      keys: {
        submit: ["enter", "return"],
        ...options.keys ?? {}
      }
    };
  }
  /** Execute the prompt. */
  async prompt() {
    try {
      return await this.#execute();
    } finally {
      this.settings.tty.cursorShow();
    }
  }
  /** Clear prompt output. */
  clear() {
    this.settings.tty.cursorLeft.eraseDown();
  }
  /** Execute the prompt. */
  #execute = async () => {
    if (typeof _GenericPrompt.injectedValue !== "undefined" && this.#lastError) {
      throw new Error(this.error());
    }
    await this.render();
    this.#lastError = void 0;
    if (!await this.read()) {
      return this.#execute();
    }
    if (typeof this.#value === "undefined") {
      throw new Error("internal error: failed to read value");
    }
    this.clear();
    const successMessage = this.success(this.#value);
    if (successMessage) {
      this.settings.writer.writeSync(
        this.#encoder.encode(successMessage + "\n")
      );
    }
    _GenericPrompt.injectedValue = void 0;
    this.settings.tty.cursorShow();
    return this.#value;
  };
  /** Render prompt. */
  async render() {
    const result2 = await Promise.all([
      this.message(),
      this.body?.(),
      this.footer()
    ]);
    const content = result2.filter(Boolean).join("\n");
    const lines2 = content.split("\n");
    const columns = getColumns();
    const linesCount = columns ? lines2.reduce((prev, next) => {
      const length = stripColor(next).length;
      return prev + (length > columns ? Math.ceil(length / columns) : 1);
    }, 0) : content.split("\n").length;
    const y4 = linesCount - this.cursor.y - 1;
    if (!this.#isFirstRun || this.#lastError) {
      this.clear();
    }
    this.#isFirstRun = false;
    this.settings.writer.writeSync(this.#encoder.encode(content));
    if (y4) {
      this.settings.tty.cursorUp(y4);
    }
    this.settings.tty.cursorTo(this.cursor.x);
  }
  /** Read user input from stdin, handle events and validate user input. */
  async read() {
    if (typeof _GenericPrompt.injectedValue !== "undefined") {
      const value = _GenericPrompt.injectedValue;
      await this.#validateValue(value);
    } else {
      const events = await this.#readKey();
      if (!events.length) {
        return false;
      }
      for (const event of events) {
        await this.handleEvent(event);
      }
    }
    return typeof this.#value !== "undefined";
  }
  submit() {
    return this.#validateValue(this.getValue());
  }
  message() {
    return `${this.settings.indent}${this.settings.prefix}` + bold2(this.settings.message) + this.defaults();
  }
  defaults() {
    let defaultMessage = "";
    if (typeof this.settings.default !== "undefined" && !this.settings.hideDefault) {
      defaultMessage += dim(` (${this.format(this.settings.default)})`);
    }
    return defaultMessage;
  }
  /** Get prompt success message. */
  success(value) {
    return `${this.settings.indent}${this.settings.prefix}` + bold2(this.settings.message) + this.defaults() + " " + this.settings.pointer + " " + green(this.format(value));
  }
  footer() {
    return this.error() ?? this.hint();
  }
  error() {
    return this.#lastError ? this.settings.indent + red2(bold2(`${Figures.CROSS} `) + this.#lastError) : void 0;
  }
  hint() {
    return this.settings.hint ? this.settings.indent + italic(brightBlue(dim(`${Figures.POINTER} `) + this.settings.hint)) : void 0;
  }
  setErrorMessage(message) {
    this.#lastError = message;
  }
  /**
   * Handle user input event.
   * @param event Key event.
   */
  async handleEvent(event) {
    switch (true) {
      case (event.name === "c" && event.ctrl):
        this.clear();
        this.settings.tty.cursorShow();
        Deno.exit(130);
        return;
      case this.isKey(this.settings.keys, "submit", event):
        await this.submit();
        break;
    }
  }
  /** Read user input from stdin and pars ansi codes. */
  #readKey = async () => {
    const data3 = await this.#readChar();
    return data3.length ? parse20(data3) : [];
  };
  /** Read user input from stdin. */
  #readChar = async () => {
    const buffer2 = new Uint8Array(8);
    const isTty = Deno.isatty(this.settings.reader.rid);
    if (isTty) {
      this.settings.reader.setRaw(
        true,
        { cbreak: this.settings.cbreak }
      );
    }
    const nread = await this.settings.reader.read(buffer2);
    if (isTty) {
      this.settings.reader.setRaw(false);
    }
    if (nread === null) {
      return buffer2;
    }
    return buffer2.subarray(0, nread);
  };
  /**
   * Map input value to output value. If a custom transform handler ist set, the
   * custom handler will be executed, otherwise the default transform handler
   * from the prompt will be executed.
   * @param value The value to transform.
   */
  #transformValue = (value) => {
    return this.settings.transform ? this.settings.transform(value) : this.transform(value);
  };
  /**
   * Validate input value. Set error message if validation fails and transform
   * output value on success.
   * If a default value is set, the default will be used as value without any
   * validation.
   * If a custom validation handler ist set, the custom handler will
   * be executed, otherwise a prompt specific default validation handler will be
   * executed.
   * @param value The value to validate.
   */
  #validateValue = async (value) => {
    if (!value && typeof this.settings.default !== "undefined") {
      this.#value = this.settings.default;
      return;
    }
    this.#value = void 0;
    this.#lastError = void 0;
    const validation = await (this.settings.validate ? this.settings.validate(value) : this.validate(value));
    if (validation === false) {
      this.#lastError = `Invalid answer.`;
    } else if (typeof validation === "string") {
      this.#lastError = validation;
    } else {
      this.#value = this.#transformValue(value);
    }
  };
  /**
   * Check if key event has given name or sequence.
   * @param keys  Key map.
   * @param name  Key name.
   * @param event Key event.
   */
  isKey(keys, name2, event) {
    const keyNames = keys?.[name2];
    return typeof keyNames !== "undefined" && (typeof event.name !== "undefined" && keyNames.indexOf(event.name) !== -1 || typeof event.sequence !== "undefined" && keyNames.indexOf(event.sequence) !== -1);
  }
};
function getColumns() {
  try {
    return Deno.consoleSize().columns ?? null;
  } catch (_error) {
    return null;
  }
}

// https://deno.land/x/cliffy@v1.0.0-rc.3/prompt/_generic_input.ts
var GenericInput = class extends GenericPrompt {
  inputValue = "";
  inputIndex = 0;
  getDefaultSettings(options) {
    const settings = super.getDefaultSettings(options);
    return {
      ...settings,
      keys: {
        moveCursorLeft: ["left"],
        moveCursorRight: ["right"],
        deleteCharLeft: ["backspace"],
        deleteCharRight: ["delete"],
        ...settings.keys ?? {}
      }
    };
  }
  getCurrentInputValue() {
    return this.inputValue;
  }
  message() {
    const message = super.message() + " " + this.settings.pointer + " ";
    this.cursor.x = stripColor(message).length + this.inputIndex + 1;
    return message + this.input();
  }
  input() {
    return underline(this.inputValue);
  }
  highlight(value, color1 = dim, color2 = brightBlue) {
    value = value.toString();
    const inputLowerCase = this.getCurrentInputValue().toLowerCase();
    const valueLowerCase = value.toLowerCase();
    const index2 = valueLowerCase.indexOf(inputLowerCase);
    const matched = value.slice(index2, index2 + inputLowerCase.length);
    return index2 >= 0 ? color1(value.slice(0, index2)) + color2(matched) + color1(value.slice(index2 + inputLowerCase.length)) : value;
  }
  /**
   * Handle user input event.
   * @param event Key event.
   */
  async handleEvent(event) {
    switch (true) {
      case this.isKey(this.settings.keys, "moveCursorLeft", event):
        this.moveCursorLeft();
        break;
      case this.isKey(this.settings.keys, "moveCursorRight", event):
        this.moveCursorRight();
        break;
      case this.isKey(this.settings.keys, "deleteCharRight", event):
        this.deleteCharRight();
        break;
      case this.isKey(this.settings.keys, "deleteCharLeft", event):
        this.deleteChar();
        break;
      case (event.char && !event.meta && !event.ctrl):
        this.addChar(event.char);
        break;
      default:
        await super.handleEvent(event);
    }
  }
  /** Add character to current input. */
  addChar(char) {
    this.inputValue = this.inputValue.slice(0, this.inputIndex) + char + this.inputValue.slice(this.inputIndex);
    this.inputIndex++;
  }
  /** Move prompt cursor left. */
  moveCursorLeft() {
    if (this.inputIndex > 0) {
      this.inputIndex--;
    }
  }
  /** Move prompt cursor right. */
  moveCursorRight() {
    if (this.inputIndex < this.inputValue.length) {
      this.inputIndex++;
    }
  }
  /** Delete char left. */
  deleteChar() {
    if (this.inputIndex > 0) {
      this.inputIndex--;
      this.deleteCharRight();
    }
  }
  /** Delete char right. */
  deleteCharRight() {
    if (this.inputIndex < this.inputValue.length) {
      this.inputValue = this.inputValue.slice(0, this.inputIndex) + this.inputValue.slice(this.inputIndex + 1);
    }
  }
};

// https://deno.land/x/cliffy@v1.0.0-rc.3/prompt/_generic_list.ts
var GenericList = class extends GenericInput {
  parentOptions = [];
  get selectedOption() {
    return this.options.at(this.listIndex);
  }
  /**
   * Create list separator.
   *
   * @param label Separator label.
   */
  static separator(label = "------------") {
    return { name: label };
  }
  getDefaultSettings({
    groupIcon = true,
    groupOpenIcon = groupIcon,
    ...options
  }) {
    const settings = super.getDefaultSettings(options);
    return {
      ...settings,
      listPointer: options.listPointer ?? brightBlue(Figures.POINTER),
      searchLabel: options.searchLabel ?? brightBlue(Figures.SEARCH),
      backPointer: options.backPointer ?? brightBlue(Figures.POINTER_LEFT),
      groupPointer: options.groupPointer ?? options.listPointer ?? brightBlue(Figures.POINTER),
      groupIcon: !groupIcon ? false : typeof groupIcon === "string" ? groupIcon : Figures.FOLDER,
      groupOpenIcon: !groupOpenIcon ? false : typeof groupOpenIcon === "string" ? groupOpenIcon : Figures.FOLDER_OPEN,
      maxBreadcrumbItems: options.maxBreadcrumbItems ?? 5,
      breadcrumbSeparator: options.breadcrumbSeparator ?? ` ${Figures.POINTER_SMALL} `,
      maxRows: options.maxRows ?? 10,
      options: this.mapOptions(options, options.options),
      keys: {
        next: options.search ? ["down"] : ["down", "d", "n", "2"],
        previous: options.search ? ["up"] : ["up", "u", "p", "8"],
        nextPage: ["pagedown", "right"],
        previousPage: ["pageup", "left"],
        open: ["right", "enter", "return"],
        back: ["left", "escape", "enter", "return"],
        ...settings.keys ?? {}
      }
    };
  }
  mapOption(options, option) {
    if (isOption2(option)) {
      return {
        value: option.value,
        name: typeof option.name === "undefined" ? options.format?.(option.value) ?? String(option.value) : option.name,
        disabled: "disabled" in option && option.disabled === true,
        indentLevel: 0
      };
    } else {
      return {
        value: null,
        name: option.name,
        disabled: true,
        indentLevel: 0
      };
    }
  }
  mapOptionGroup(options, option, recursive = true) {
    return {
      name: option.name,
      disabled: !!option.disabled,
      indentLevel: 0,
      options: recursive ? this.mapOptions(options, option.options) : []
    };
  }
  match() {
    const input = this.getCurrentInputValue().toLowerCase();
    let options = this.getCurrentOptions().slice();
    if (input.length) {
      const matches = matchOptions(
        input,
        this.getCurrentOptions()
      );
      options = flatMatchedOptions(matches);
    }
    this.setOptions(options);
  }
  setOptions(options) {
    this.options = [...options];
    const parent = this.getParentOption();
    if (parent && this.options[0] !== parent) {
      this.options.unshift(parent);
    }
    this.listIndex = Math.max(
      0,
      Math.min(this.options.length - 1, this.listIndex)
    );
    this.listOffset = Math.max(
      0,
      Math.min(
        this.options.length - this.getListHeight(),
        this.listOffset
      )
    );
  }
  getCurrentOptions() {
    return this.getParentOption()?.options ?? this.settings.options;
  }
  getParentOption(index2 = -1) {
    return this.parentOptions.at(index2);
  }
  submitBackButton() {
    const parentOption = this.parentOptions.pop();
    if (!parentOption) {
      return;
    }
    this.match();
    this.listIndex = this.options.indexOf(parentOption);
  }
  submitGroupOption(selectedOption) {
    this.parentOptions.push(selectedOption);
    this.match();
    this.listIndex = 1;
  }
  isBackButton(option) {
    return option === this.getParentOption();
  }
  hasParent() {
    return this.parentOptions.length > 0;
  }
  isSearching() {
    return this.getCurrentInputValue() !== "";
  }
  message() {
    let message = `${this.settings.indent}${this.settings.prefix}` + bold2(this.settings.message) + this.defaults();
    if (this.settings.search) {
      const input = this.isSearchSelected() ? this.input() : dim(this.input());
      message += " " + this.settings.searchLabel + " ";
      this.cursor.x = stripColor(message).length + this.inputIndex + 1;
      message += input;
    }
    return message;
  }
  /** Render options. */
  body() {
    return this.getList() + this.getInfo();
  }
  getInfo() {
    if (!this.settings.info) {
      return "";
    }
    const selected = this.listIndex + 1;
    const hasGroups = this.options.some((option) => isOptionGroup(option));
    const groupActions = hasGroups ? [
      ["Open", getFiguresByKeys(this.settings.keys.open ?? [])],
      ["Back", getFiguresByKeys(this.settings.keys.back ?? [])]
    ] : [];
    const actions = [
      ["Next", getFiguresByKeys(this.settings.keys.next ?? [])],
      ["Previous", getFiguresByKeys(this.settings.keys.previous ?? [])],
      ...groupActions,
      ["Next Page", getFiguresByKeys(this.settings.keys.nextPage ?? [])],
      [
        "Previous Page",
        getFiguresByKeys(this.settings.keys.previousPage ?? [])
      ],
      ["Submit", getFiguresByKeys(this.settings.keys.submit ?? [])]
    ];
    return "\n" + this.settings.indent + brightBlue(Figures.INFO) + bold2(` ${selected}/${this.options.length} `) + actions.map((cur) => `${cur[0]}: ${bold2(cur[1].join(", "))}`).join(", ");
  }
  /** Render options list. */
  getList() {
    const list = [];
    const height = this.getListHeight();
    for (let i6 = this.listOffset; i6 < this.listOffset + height; i6++) {
      list.push(
        this.getListItem(
          this.options[i6],
          this.listIndex === i6
        )
      );
    }
    if (!list.length) {
      list.push(
        this.settings.indent + dim("  No matches...")
      );
    }
    return list.join("\n");
  }
  /**
   * Render option.
   * @param option        Option.
   * @param isSelected  Set to true if option is selected.
   */
  getListItem(option, isSelected) {
    let line = this.getListItemIndent(option);
    line += this.getListItemPointer(option, isSelected);
    line += this.getListItemIcon(option);
    line += this.getListItemLabel(option, isSelected);
    return line;
  }
  getListItemIndent(option) {
    const indentLevel = this.isSearching() ? option.indentLevel : this.hasParent() && !this.isBackButton(option) ? 1 : 0;
    return this.settings.indent + " ".repeat(indentLevel);
  }
  getListItemPointer(option, isSelected) {
    if (!isSelected) {
      return "  ";
    }
    if (this.isBackButton(option)) {
      return this.settings.backPointer + " ";
    } else if (isOptionGroup(option)) {
      return this.settings.groupPointer + " ";
    }
    return this.settings.listPointer + " ";
  }
  getListItemIcon(option) {
    if (this.isBackButton(option)) {
      return this.settings.groupOpenIcon ? this.settings.groupOpenIcon + " " : "";
    } else if (isOptionGroup(option)) {
      return this.settings.groupIcon ? this.settings.groupIcon + " " : "";
    }
    return "";
  }
  getListItemLabel(option, isSelected) {
    let label = option.name;
    if (this.isBackButton(option)) {
      label = this.getBreadCrumb();
      label = isSelected && !option.disabled ? label : yellow2(label);
    } else {
      label = isSelected && !option.disabled ? this.highlight(label, (val) => val) : this.highlight(label);
    }
    if (this.isBackButton(option) || isOptionGroup(option)) {
      label = bold2(label);
    }
    return label;
  }
  getBreadCrumb() {
    if (!this.parentOptions.length || !this.settings.maxBreadcrumbItems) {
      return "";
    }
    const names = this.parentOptions.map((option) => option.name);
    const breadCrumb = names.length > this.settings.maxBreadcrumbItems ? [names[0], "..", ...names.slice(-this.settings.maxBreadcrumbItems + 1)] : names;
    return breadCrumb.join(this.settings.breadcrumbSeparator);
  }
  /** Get options row height. */
  getListHeight() {
    return Math.min(
      this.options.length,
      this.settings.maxRows || this.options.length
    );
  }
  getListIndex(value) {
    return Math.max(
      0,
      typeof value === "undefined" ? this.options.findIndex(
        (option) => !option.disabled
      ) || 0 : this.options.findIndex(
        (option) => isOption2(option) && option.value === value
      ) || 0
    );
  }
  getPageOffset(index2) {
    if (index2 === 0) {
      return 0;
    }
    const height = this.getListHeight();
    return Math.floor(index2 / height) * height;
  }
  /**
   * Find option by value.
   * @param value Value of the option.
   */
  getOptionByValue(value) {
    const option = this.options.find(
      (option2) => isOption2(option2) && option2.value === value
    );
    return option && isOptionGroup(option) ? void 0 : option;
  }
  /** Read user input. */
  read() {
    if (!this.settings.search) {
      this.settings.tty.cursorHide();
    }
    return super.read();
  }
  selectSearch() {
    this.listIndex = -1;
  }
  isSearchSelected() {
    return this.listIndex === -1;
  }
  /**
   * Handle user input event.
   * @param event Key event.
   */
  async handleEvent(event) {
    if (this.isKey(this.settings.keys, "open", event) && isOptionGroup(this.selectedOption) && !this.isBackButton(this.selectedOption) && !this.isSearchSelected()) {
      this.submitGroupOption(this.selectedOption);
    } else if (this.isKey(this.settings.keys, "back", event) && (this.isBackButton(this.selectedOption) || event.name === "escape") && !this.isSearchSelected()) {
      this.submitBackButton();
    } else if (this.isKey(this.settings.keys, "next", event)) {
      this.selectNext();
    } else if (this.isKey(this.settings.keys, "previous", event)) {
      this.selectPrevious();
    } else if (this.isKey(this.settings.keys, "nextPage", event) && !this.isSearchSelected()) {
      this.selectNextPage();
    } else if (this.isKey(this.settings.keys, "previousPage", event) && !this.isSearchSelected()) {
      this.selectPreviousPage();
    } else {
      await super.handleEvent(event);
    }
  }
  async submit() {
    if (this.isSearchSelected()) {
      this.selectNext();
      return;
    }
    await super.submit();
  }
  moveCursorLeft() {
    if (this.settings.search) {
      super.moveCursorLeft();
    }
  }
  moveCursorRight() {
    if (this.settings.search) {
      super.moveCursorRight();
    }
  }
  deleteChar() {
    if (this.settings.search) {
      super.deleteChar();
    }
  }
  deleteCharRight() {
    if (this.settings.search) {
      super.deleteCharRight();
      this.match();
    }
  }
  addChar(char) {
    if (this.settings.search) {
      super.addChar(char);
      this.match();
    }
  }
  /** Select previous option. */
  selectPrevious(loop = true) {
    if (this.options.length < 2 && !this.isSearchSelected()) {
      return;
    }
    if (this.listIndex > 0) {
      this.listIndex--;
      if (this.listIndex < this.listOffset) {
        this.listOffset--;
      }
      if (this.selectedOption?.disabled) {
        this.selectPrevious();
      }
    } else if (this.settings.search && this.listIndex === 0 && this.getCurrentInputValue().length) {
      this.listIndex = -1;
    } else if (loop) {
      this.listIndex = this.options.length - 1;
      this.listOffset = this.options.length - this.getListHeight();
      if (this.selectedOption?.disabled) {
        this.selectPrevious();
      }
    }
  }
  /** Select next option. */
  selectNext(loop = true) {
    if (this.options.length < 2 && !this.isSearchSelected()) {
      return;
    }
    if (this.listIndex < this.options.length - 1) {
      this.listIndex++;
      if (this.listIndex >= this.listOffset + this.getListHeight()) {
        this.listOffset++;
      }
      if (this.selectedOption?.disabled) {
        this.selectNext();
      }
    } else if (this.settings.search && this.listIndex === this.options.length - 1 && this.getCurrentInputValue().length) {
      this.listIndex = -1;
    } else if (loop) {
      this.listIndex = this.listOffset = 0;
      if (this.selectedOption?.disabled) {
        this.selectNext();
      }
    }
  }
  /** Select previous page. */
  selectPreviousPage() {
    if (this.options?.length) {
      const height = this.getListHeight();
      if (this.listOffset >= height) {
        this.listIndex -= height;
        this.listOffset -= height;
      } else if (this.listOffset > 0) {
        this.listIndex -= this.listOffset;
        this.listOffset = 0;
      } else {
        this.listIndex = 0;
      }
      if (this.selectedOption?.disabled) {
        this.selectPrevious(false);
      }
      if (this.selectedOption?.disabled) {
        this.selectNext(false);
      }
    }
  }
  /** Select next page. */
  selectNextPage() {
    if (this.options?.length) {
      const height = this.getListHeight();
      if (this.listOffset + height + height < this.options.length) {
        this.listIndex += height;
        this.listOffset += height;
      } else if (this.listOffset + height < this.options.length) {
        const offset3 = this.options.length - height;
        this.listIndex += offset3 - this.listOffset;
        this.listOffset = offset3;
      } else {
        this.listIndex = this.options.length - 1;
      }
      if (this.selectedOption?.disabled) {
        this.selectNext(false);
      }
      if (this.selectedOption?.disabled) {
        this.selectPrevious(false);
      }
    }
  }
};
function isOption2(option) {
  return !!option && typeof option === "object" && "value" in option;
}
function isOptionGroup(option) {
  return option !== null && typeof option === "object" && "options" in option && Array.isArray(option.options);
}
function matchOptions(searchInput, options) {
  const matched = [];
  for (const option of options) {
    if (isOptionGroup(option)) {
      const children = matchOptions(searchInput, option.options).sort(sortByDistance);
      if (children.length) {
        matched.push({
          option,
          distance: Math.min(...children.map((item) => item.distance)),
          children
        });
        continue;
      }
    }
    if (matchOption(searchInput, option)) {
      matched.push({
        option,
        distance: distance(option.name, searchInput),
        children: []
      });
    }
  }
  return matched.sort(sortByDistance);
  function sortByDistance(a5, b3) {
    return a5.distance - b3.distance;
  }
}
function matchOption(inputString, option) {
  return matchInput(inputString, option.name) || isOption2(option) && option.name !== option.value && matchInput(inputString, String(option.value));
}
function matchInput(inputString, value) {
  return stripColor(value).toLowerCase().includes(inputString);
}
function flatMatchedOptions(matches, indentLevel = 0, result2 = []) {
  for (const { option, children } of matches) {
    option.indentLevel = indentLevel;
    result2.push(option);
    flatMatchedOptions(children, indentLevel + 1, result2);
  }
  return result2;
}

// https://deno.land/x/cliffy@v1.0.0-rc.3/prompt/checkbox.ts
var Checkbox = class extends GenericList {
  settings;
  options;
  listIndex;
  listOffset;
  confirmSubmit = false;
  /**
   * Execute the prompt with provided options.
   *
   * @param options Checkbox options.
   */
  static prompt(options) {
    return new this(options).prompt();
  }
  /**
   * Create list separator.
   *
   * @param label Separator label.
   */
  /**
   * Inject prompt value. If called, the prompt doesn't prompt for an input and
   * returns immediately the injected value. Can be used for unit tests or pre
   * selections.
   *
   * @param value Input value.
   */
  static inject(value) {
    GenericPrompt.inject(value);
  }
  constructor(options) {
    super();
    this.settings = this.getDefaultSettings(options);
    this.options = this.settings.options.slice();
    this.listIndex = this.getListIndex();
    this.listOffset = this.getPageOffset(this.listIndex);
  }
  getDefaultSettings(options) {
    const settings = super.getDefaultSettings(options);
    return {
      confirmSubmit: true,
      ...settings,
      check: options.check ?? green(Figures.TICK),
      uncheck: options.uncheck ?? red2(Figures.CROSS),
      partialCheck: options.partialCheck ?? green(Figures.RADIO_ON),
      minOptions: options.minOptions ?? 0,
      maxOptions: options.maxOptions ?? Infinity,
      options: this.mapOptions(options, options.options),
      keys: {
        check: ["space"],
        checkAll: ["a"],
        ...settings.keys ?? {},
        open: options.keys?.open ?? ["right"],
        back: options.keys?.back ?? ["left", "escape"]
      }
    };
  }
  /** Map string option values to options and set option defaults. */
  mapOptions(promptOptions, options) {
    return options.map(
      (option) => typeof option === "string" || typeof option === "number" ? this.mapOption(
        promptOptions,
        { value: option }
      ) : isCheckboxOptionGroup(option) ? this.mapOptionGroup(promptOptions, option) : this.mapOption(promptOptions, option)
    );
  }
  mapOption(options, option) {
    if (isOption2(option)) {
      return {
        ...super.mapOption(options, option),
        checked: typeof option.checked === "undefined" && options.default && options.default.indexOf(option.value) !== -1 ? true : !!option.checked,
        icon: typeof option.icon === "undefined" ? true : option.icon
      };
    } else {
      return {
        ...super.mapOption(options, option),
        checked: false,
        icon: false
      };
    }
  }
  mapOptionGroup(promptOptions, option) {
    const options = this.mapOptions(promptOptions, option.options);
    return {
      ...super.mapOptionGroup(promptOptions, option, false),
      get checked() {
        return areAllChecked(options);
      },
      options,
      icon: typeof option.icon === "undefined" ? true : option.icon
    };
  }
  match() {
    super.match();
    if (this.isSearching()) {
      this.selectSearch();
    }
  }
  getListItemIcon(option) {
    return this.getCheckboxIcon(option) + super.getListItemIcon(option);
  }
  getCheckboxIcon(option) {
    if (!option.icon) {
      return "";
    }
    const icon = option.checked ? this.settings.check + " " : isOptionGroup(option) && areSomeChecked(option.options) ? this.settings.partialCheck + " " : this.settings.uncheck + " ";
    return option.disabled ? dim(icon) : icon;
  }
  /** Get value of checked options. */
  getValue() {
    return flatOptions(
      this.settings.options
    ).filter((option) => option.checked).map((option) => option.value);
  }
  /**
   * Handle user input event.
   * @param event Key event.
   */
  async handleEvent(event) {
    const hasConfirmed = this.confirmSubmit;
    this.confirmSubmit = false;
    switch (true) {
      case (this.isKey(this.settings.keys, "check", event) && !this.isSearchSelected()):
        this.checkValue();
        break;
      case this.isKey(this.settings.keys, "submit", event):
        await this.submit(hasConfirmed);
        break;
      case (event.ctrl && this.isKey(this.settings.keys, "checkAll", event)):
        this.checkAllOption();
        break;
      default:
        await super.handleEvent(event);
    }
  }
  hint() {
    if (this.confirmSubmit) {
      const info2 = this.isBackButton(this.selectedOption) ? ` To leave the current group press ${getFiguresByKeys(this.settings.keys.back ?? []).join(", ")}.` : isOptionGroup(this.selectedOption) ? ` To open the selected group press ${getFiguresByKeys(this.settings.keys.open ?? []).join(", ")}.` : ` To check or uncheck the selected option press ${getFiguresByKeys(this.settings.keys.check ?? []).join(", ")}.`;
      return this.settings.indent + brightBlue(
        `Press ${getFiguresByKeys(this.settings.keys.submit ?? [])} again to submit.${info2}`
      );
    }
    return super.hint();
  }
  async submit(hasConfirmed) {
    if (!hasConfirmed && this.settings.confirmSubmit && !this.isSearchSelected()) {
      this.confirmSubmit = true;
      return;
    }
    await super.submit();
  }
  /** Check selected option. */
  checkValue() {
    const option = this.options.at(this.listIndex);
    if (!option) {
      this.setErrorMessage("No option available to select.");
      return;
    } else if (option.disabled) {
      this.setErrorMessage("This option is disabled and cannot be changed.");
      return;
    }
    this.checkOption(option, !option.checked);
  }
  checkOption(option, checked) {
    if (isOption2(option)) {
      option.checked = checked;
    } else {
      for (const childOption of option.options) {
        this.checkOption(childOption, checked);
      }
    }
  }
  checkAllOption() {
    const checked = this.options.some((option) => option.checked);
    for (const option of this.options) {
      this.checkOption(option, !checked);
    }
  }
  /**
   * Validate input value.
   * @param value User input value.
   * @return True on success, false or error message on error.
   */
  validate(value) {
    const options = flatOptions(this.settings.options);
    const isValidValue2 = Array.isArray(value) && value.every(
      (val) => options.findIndex(
        (option) => option.value === val
      ) !== -1
    );
    if (!isValidValue2) {
      return false;
    }
    if (value.length < this.settings.minOptions) {
      return `The minimum number of options is ${this.settings.minOptions} but got ${value.length}.`;
    }
    if (value.length > this.settings.maxOptions) {
      return `The maximum number of options is ${this.settings.maxOptions} but got ${value.length}.`;
    }
    return true;
  }
  /**
   * Map input value to output value.
   * @param value Input value.
   * @return Output value.
   */
  transform(value) {
    return value;
  }
  /**
   * Format output value.
   * @param value Output value.
   */
  format(value) {
    return value.map(
      (val) => this.settings.format?.(val) ?? this.getOptionByValue(val)?.name ?? String(val)
    ).join(", ");
  }
};
function areSomeChecked(options) {
  return options.some(
    (option) => isOptionGroup(option) ? areSomeChecked(option.options) : option.checked
  );
}
function areAllChecked(options) {
  return options.every(
    (option) => isOptionGroup(option) ? areAllChecked(option.options) : option.checked
  );
}
function flatOptions(options) {
  return flat(options);
  function flat(options2, indentLevel = 0, opts = []) {
    for (const option of options2) {
      option.indentLevel = indentLevel;
      if (isOption2(option)) {
        opts.push(option);
      }
      if (isOptionGroup(option)) {
        flat(option.options, ++indentLevel, opts);
      }
    }
    return opts;
  }
}
function isCheckboxOptionGroup(option) {
  return isOptionGroup(option);
}

// https://deno.land/x/cliffy@v1.0.0-rc.3/prompt/_generic_suggestions.ts
var sep5 = Deno.build.os === "windows" ? "\\" : "/";
var GenericSuggestions = class extends GenericInput {
  suggestionsIndex = -1;
  suggestionsOffset = 0;
  suggestions = [];
  #hasReadPermissions;
  getDefaultSettings(options) {
    const settings = super.getDefaultSettings(options);
    return {
      ...settings,
      listPointer: options.listPointer ?? brightBlue(Figures.POINTER),
      maxRows: options.maxRows ?? 8,
      keys: {
        complete: ["tab"],
        next: ["up"],
        previous: ["down"],
        nextPage: ["pageup"],
        previousPage: ["pagedown"],
        ...settings.keys ?? {}
      }
    };
  }
  get localStorage() {
    if (this.settings.id && "localStorage" in window) {
      try {
        return window.localStorage;
      } catch (_3) {
      }
    }
    return null;
  }
  loadSuggestions() {
    if (this.settings.id) {
      const json3 = this.localStorage?.getItem(this.settings.id);
      const suggestions = json3 ? JSON.parse(json3) : [];
      if (!Array.isArray(suggestions)) {
        return [];
      }
      return suggestions;
    }
    return [];
  }
  saveSuggestions(...suggestions) {
    if (this.settings.id) {
      this.localStorage?.setItem(
        this.settings.id,
        JSON.stringify([
          ...suggestions,
          ...this.loadSuggestions()
        ].filter(uniqueSuggestions))
      );
    }
  }
  async render() {
    if (this.settings.files && this.#hasReadPermissions === void 0) {
      const status = await Deno.permissions.request({ name: "read" });
      this.#hasReadPermissions = status.state === "granted";
    }
    await this.match();
    return super.render();
  }
  async match() {
    this.suggestions = await this.getSuggestions();
    this.suggestionsIndex = Math.max(
      this.getCurrentInputValue().trim().length === 0 ? -1 : 0,
      Math.min(this.suggestions.length - 1, this.suggestionsIndex)
    );
    this.suggestionsOffset = Math.max(
      0,
      Math.min(
        this.suggestions.length - this.getListHeight(),
        this.suggestionsOffset
      )
    );
  }
  input() {
    return super.input() + dim(this.getSuggestion());
  }
  getSuggestion() {
    return this.suggestions[this.suggestionsIndex]?.toString().substr(
      this.getCurrentInputValue().length
    ) ?? "";
  }
  async getUserSuggestions(input) {
    return typeof this.settings.suggestions === "function" ? await this.settings.suggestions(input) : this.settings.suggestions ?? [];
  }
  #isFileModeEnabled() {
    return !!this.settings.files && this.#hasReadPermissions === true;
  }
  async getFileSuggestions(input) {
    if (!this.#isFileModeEnabled()) {
      return [];
    }
    const path3 = await Deno.stat(input).then((file) => file.isDirectory ? input : dirname12(input)).catch(() => dirname12(input));
    return await listDir(path3, this.settings.files);
  }
  async getSuggestions() {
    const input = this.getCurrentInputValue();
    const suggestions = [
      ...this.loadSuggestions(),
      ...await this.getUserSuggestions(input),
      ...await this.getFileSuggestions(input)
    ].filter(uniqueSuggestions);
    if (!input.length) {
      return suggestions;
    }
    return suggestions.filter(
      (value) => stripColor(value.toString()).toLowerCase().startsWith(input.toLowerCase())
    ).sort(
      (a5, b3) => distance((a5 || a5).toString(), input) - distance((b3 || b3).toString(), input)
    );
  }
  body() {
    return this.getList() + this.getInfo();
  }
  getInfo() {
    if (!this.settings.info) {
      return "";
    }
    const selected = this.suggestionsIndex + 1;
    const matched = this.suggestions.length;
    const actions = [];
    if (this.suggestions.length) {
      if (this.settings.list) {
        actions.push(
          ["Next", getFiguresByKeys(this.settings.keys?.next ?? [])],
          ["Previous", getFiguresByKeys(this.settings.keys?.previous ?? [])],
          ["Next Page", getFiguresByKeys(this.settings.keys?.nextPage ?? [])],
          [
            "Previous Page",
            getFiguresByKeys(this.settings.keys?.previousPage ?? [])
          ]
        );
      } else {
        actions.push(
          ["Next", getFiguresByKeys(this.settings.keys?.next ?? [])],
          ["Previous", getFiguresByKeys(this.settings.keys?.previous ?? [])]
        );
      }
      actions.push(
        ["Complete", getFiguresByKeys(this.settings.keys?.complete ?? [])]
      );
    }
    actions.push(
      ["Submit", getFiguresByKeys(this.settings.keys?.submit ?? [])]
    );
    let info2 = this.settings.indent;
    if (this.suggestions.length) {
      info2 += brightBlue(Figures.INFO) + bold2(` ${selected}/${matched} `);
    }
    info2 += actions.map((cur) => `${cur[0]}: ${bold2(cur[1].join(" "))}`).join(", ");
    return info2;
  }
  getList() {
    if (!this.suggestions.length || !this.settings.list) {
      return "";
    }
    const list = [];
    const height = this.getListHeight();
    for (let i6 = this.suggestionsOffset; i6 < this.suggestionsOffset + height; i6++) {
      list.push(
        this.getListItem(
          this.suggestions[i6],
          this.suggestionsIndex === i6
        )
      );
    }
    if (list.length && this.settings.info) {
      list.push("");
    }
    return list.join("\n");
  }
  /**
   * Render option.
   * @param value        Option.
   * @param isSelected  Set to true if option is selected.
   */
  getListItem(value, isSelected) {
    let line = this.settings.indent ?? "";
    line += isSelected ? `${this.settings.listPointer} ` : "  ";
    if (isSelected) {
      line += underline(this.highlight(value));
    } else {
      line += this.highlight(value);
    }
    return line;
  }
  /** Get suggestions row height. */
  getListHeight(suggestions = this.suggestions) {
    return Math.min(
      suggestions.length,
      this.settings.maxRows || suggestions.length
    );
  }
  /**
   * Handle user input event.
   * @param event Key event.
   */
  async handleEvent(event) {
    switch (true) {
      case this.isKey(this.settings.keys, "next", event):
        if (this.settings.list) {
          this.selectPreviousSuggestion();
        } else {
          this.selectNextSuggestion();
        }
        break;
      case this.isKey(this.settings.keys, "previous", event):
        if (this.settings.list) {
          this.selectNextSuggestion();
        } else {
          this.selectPreviousSuggestion();
        }
        break;
      case this.isKey(this.settings.keys, "nextPage", event):
        if (this.settings.list) {
          this.selectPreviousSuggestionsPage();
        } else {
          this.selectNextSuggestionsPage();
        }
        break;
      case this.isKey(this.settings.keys, "previousPage", event):
        if (this.settings.list) {
          this.selectNextSuggestionsPage();
        } else {
          this.selectPreviousSuggestionsPage();
        }
        break;
      case this.isKey(this.settings.keys, "complete", event):
        await this.#completeValue();
        break;
      case this.isKey(this.settings.keys, "moveCursorRight", event):
        if (this.inputIndex < this.inputValue.length) {
          this.moveCursorRight();
        } else {
          await this.#completeValue();
        }
        break;
      default:
        await super.handleEvent(event);
    }
  }
  /** Delete char right. */
  deleteCharRight() {
    if (this.inputIndex < this.inputValue.length) {
      super.deleteCharRight();
      if (!this.getCurrentInputValue().length) {
        this.suggestionsIndex = -1;
        this.suggestionsOffset = 0;
      }
    }
  }
  async #completeValue() {
    this.inputValue = await this.complete();
    this.inputIndex = this.inputValue.length;
    this.suggestionsIndex = 0;
    this.suggestionsOffset = 0;
  }
  async complete() {
    let input = this.getCurrentInputValue();
    const suggestion = this.suggestions[this.suggestionsIndex]?.toString();
    if (this.settings.complete) {
      input = await this.settings.complete(input, suggestion);
    } else if (this.#isFileModeEnabled() && input.at(-1) !== sep5 && await isDirectory(input) && (this.getCurrentInputValue().at(-1) !== "." || this.getCurrentInputValue().endsWith(".."))) {
      input += sep5;
    } else if (suggestion) {
      input = suggestion;
    }
    return this.#isFileModeEnabled() ? normalize13(input) : input;
  }
  /** Select previous suggestion. */
  selectPreviousSuggestion() {
    if (this.suggestions.length) {
      if (this.suggestionsIndex > -1) {
        this.suggestionsIndex--;
        if (this.suggestionsIndex < this.suggestionsOffset) {
          this.suggestionsOffset--;
        }
      }
    }
  }
  /** Select next suggestion. */
  selectNextSuggestion() {
    if (this.suggestions.length) {
      if (this.suggestionsIndex < this.suggestions.length - 1) {
        this.suggestionsIndex++;
        if (this.suggestionsIndex >= this.suggestionsOffset + this.getListHeight()) {
          this.suggestionsOffset++;
        }
      }
    }
  }
  /** Select previous suggestions page. */
  selectPreviousSuggestionsPage() {
    if (this.suggestions.length) {
      const height = this.getListHeight();
      if (this.suggestionsOffset >= height) {
        this.suggestionsIndex -= height;
        this.suggestionsOffset -= height;
      } else if (this.suggestionsOffset > 0) {
        this.suggestionsIndex -= this.suggestionsOffset;
        this.suggestionsOffset = 0;
      }
    }
  }
  /** Select next suggestions page. */
  selectNextSuggestionsPage() {
    if (this.suggestions.length) {
      const height = this.getListHeight();
      if (this.suggestionsOffset + height + height < this.suggestions.length) {
        this.suggestionsIndex += height;
        this.suggestionsOffset += height;
      } else if (this.suggestionsOffset + height < this.suggestions.length) {
        const offset3 = this.suggestions.length - height;
        this.suggestionsIndex += offset3 - this.suggestionsOffset;
        this.suggestionsOffset = offset3;
      }
    }
  }
};
function uniqueSuggestions(value, index2, self2) {
  return typeof value !== "undefined" && value !== "" && self2.indexOf(value) === index2;
}
function isDirectory(path3) {
  return Deno.stat(path3).then((file) => file.isDirectory).catch(() => false);
}
async function listDir(path3, mode) {
  const fileNames = [];
  for await (const file of Deno.readDir(path3 || ".")) {
    if (mode === true && (file.name.startsWith(".") || file.name.endsWith("~"))) {
      continue;
    }
    const filePath = join16(path3, file.name);
    if (mode instanceof RegExp && !mode.test(filePath)) {
      continue;
    }
    fileNames.push(filePath);
  }
  return fileNames.sort(function(a5, b3) {
    return a5.toLowerCase().localeCompare(b3.toLowerCase());
  });
}

// https://deno.land/x/cliffy@v1.0.0-rc.3/prompt/confirm.ts
var Confirm = class extends GenericSuggestions {
  settings;
  /** Execute the prompt with provided options. */
  static prompt(options) {
    return new this(options).prompt();
  }
  /**
   * Inject prompt value. If called, the prompt doesn't prompt for an input and
   * returns immediately the injected value. Can be used for unit tests or pre
   * selections.
   *
   * @param value Input value.
   */
  static inject(value) {
    GenericPrompt.inject(value);
  }
  constructor(options) {
    super();
    if (typeof options === "string") {
      options = { message: options };
    }
    this.settings = this.getDefaultSettings(options);
  }
  getDefaultSettings(options) {
    return {
      ...super.getDefaultSettings(options),
      active: options.active || "Yes",
      inactive: options.inactive || "No",
      files: false,
      complete: void 0,
      suggestions: [
        options.active || "Yes",
        options.inactive || "No"
      ],
      list: false,
      info: false
    };
  }
  defaults() {
    let defaultMessage = "";
    if (this.settings.default === true) {
      defaultMessage += this.settings.active[0].toUpperCase() + "/" + this.settings.inactive[0].toLowerCase();
    } else if (this.settings.default === false) {
      defaultMessage += this.settings.active[0].toLowerCase() + "/" + this.settings.inactive[0].toUpperCase();
    } else {
      defaultMessage += this.settings.active[0].toLowerCase() + "/" + this.settings.inactive[0].toLowerCase();
    }
    return defaultMessage ? dim(` (${defaultMessage})`) : "";
  }
  success(value) {
    this.saveSuggestions(this.format(value));
    return super.success(value);
  }
  /** Get input input. */
  getValue() {
    return this.inputValue;
  }
  /**
   * Validate input value.
   * @param value User input value.
   * @return True on success, false or error message on error.
   */
  validate(value) {
    return typeof value === "string" && [
      this.settings.active[0].toLowerCase(),
      this.settings.active.toLowerCase(),
      this.settings.inactive[0].toLowerCase(),
      this.settings.inactive.toLowerCase()
    ].indexOf(value.toLowerCase()) !== -1;
  }
  /**
   * Map input value to output value.
   * @param value Input value.
   * @return Output value.
   */
  transform(value) {
    switch (value.toLowerCase()) {
      case this.settings.active[0].toLowerCase():
      case this.settings.active.toLowerCase():
        return true;
      case this.settings.inactive[0].toLowerCase():
      case this.settings.inactive.toLowerCase():
        return false;
    }
    return;
  }
  /**
   * Format output value.
   * @param value Output value.
   */
  format(value) {
    return value ? this.settings.active : this.settings.inactive;
  }
};

// https://deno.land/x/cliffy@v1.0.0-rc.3/prompt/input.ts
var Input = class extends GenericSuggestions {
  settings;
  /** Execute the prompt with provided options. */
  static prompt(options) {
    return new this(options).prompt();
  }
  /**
   * Inject prompt value. If called, the prompt doesn't prompt for an input and
   * returns immediately the injected value. Can be used for unit tests or pre
   * selections.
   *
   * @param value Input value.
   */
  static inject(value) {
    GenericPrompt.inject(value);
  }
  constructor(options) {
    super();
    if (typeof options === "string") {
      options = { message: options };
    }
    this.settings = this.getDefaultSettings(options);
  }
  getDefaultSettings(options) {
    return {
      ...super.getDefaultSettings(options),
      minLength: options.minLength ?? 0,
      maxLength: options.maxLength ?? Infinity
    };
  }
  success(value) {
    this.saveSuggestions(value);
    return super.success(value);
  }
  /** Get input value. */
  getValue() {
    return this.settings.files ? normalize13(this.inputValue) : this.inputValue;
  }
  /**
   * Validate input value.
   * @param value User input value.
   * @return True on success, false or error message on error.
   */
  validate(value) {
    if (typeof value !== "string") {
      return false;
    }
    if (value.length < this.settings.minLength) {
      return `Value must be longer than ${this.settings.minLength} but has a length of ${value.length}.`;
    }
    if (value.length > this.settings.maxLength) {
      return `Value can't be longer than ${this.settings.maxLength} but has a length of ${value.length}.`;
    }
    return true;
  }
  /**
   * Map input value to output value.
   * @param value Input value.
   * @return Output value.
   */
  transform(value) {
    return value.trim();
  }
  /**
   * Format output value.
   * @param value Output value.
   */
  format(value) {
    return value;
  }
};

// https://deno.land/x/cliffy@v1.0.0-rc.3/prompt/secret.ts
var Secret = class extends GenericInput {
  settings;
  /** Execute the prompt with provided message or options. */
  static prompt(options) {
    return new this(options).prompt();
  }
  /**
   * Inject prompt value. If called, the prompt doesn't prompt for an input and
   * returns immediately the injected value. Can be used for unit tests or pre
   * selections.
   *
   * @param value Input value.
   */
  static inject(value) {
    GenericPrompt.inject(value);
  }
  constructor(options) {
    super();
    if (typeof options === "string") {
      options = { message: options };
    }
    this.settings = this.getDefaultSettings(options);
  }
  getDefaultSettings(options) {
    return {
      ...super.getDefaultSettings(options),
      label: options.label ?? "Secret",
      hidden: options.hidden ?? false,
      minLength: options.minLength ?? 0,
      maxLength: options.maxLength ?? Infinity
    };
  }
  input() {
    return underline(
      this.settings.hidden ? "" : "*".repeat(this.inputValue.length)
    );
  }
  /** Read user input. */
  read() {
    if (this.settings.hidden) {
      this.settings.tty.cursorHide();
    }
    return super.read();
  }
  /**
   * Validate input value.
   * @param value User input value.
   * @return True on success, false or error message on error.
   */
  validate(value) {
    if (typeof value !== "string") {
      return false;
    }
    if (value.length < this.settings.minLength) {
      return `${this.settings.label} must be longer than ${this.settings.minLength} but has a length of ${value.length}.`;
    }
    if (value.length > this.settings.maxLength) {
      return `${this.settings.label} can't be longer than ${this.settings.maxLength} but has a length of ${value.length}.`;
    }
    return true;
  }
  /**
   * Map input value to output value.
   * @param value Input value.
   * @return Output value.
   */
  transform(value) {
    return value;
  }
  /**
   * Format output value.
   * @param value Output value.
   */
  format(value) {
    return this.settings.hidden ? "*".repeat(8) : "*".repeat(value.length);
  }
  /** Get input input. */
  getValue() {
    return this.inputValue;
  }
};

// https://deno.land/x/cliffy@v1.0.0-rc.3/prompt/select.ts
var Select = class extends GenericList {
  settings;
  options;
  listIndex;
  listOffset;
  /** Execute the prompt with provided options. */
  static prompt(options) {
    return new this(options).prompt();
  }
  /**
   * Inject prompt value. If called, the prompt doesn't prompt for an input and
   * returns immediately the injected value. Can be used for unit tests or pre
   * selections.
   *
   * @param value Input value.
   */
  static inject(value) {
    GenericPrompt.inject(value);
  }
  constructor(options) {
    super();
    this.settings = this.getDefaultSettings(options);
    this.options = this.settings.options.slice();
    this.listIndex = this.getListIndex(this.settings.default);
    this.listOffset = this.getPageOffset(this.listIndex);
  }
  getDefaultSettings(options) {
    return {
      ...super.getDefaultSettings(options),
      options: this.mapOptions(options, options.options)
    };
  }
  /** Map string option values to options and set option defaults. */
  mapOptions(promptOptions, options) {
    return options.map(
      (option) => isSelectOptionGroup(option) ? this.mapOptionGroup(promptOptions, option) : typeof option === "string" || typeof option === "number" ? this.mapOption(
        promptOptions,
        { value: option }
      ) : this.mapOption(promptOptions, option)
    );
  }
  input() {
    return underline(brightBlue(this.inputValue));
  }
  async submit() {
    if (this.isBackButton(this.selectedOption) || isOptionGroup(this.selectedOption)) {
      const info2 = isOptionGroup(this.selectedOption) ? ` To select a group use ${getFiguresByKeys(this.settings.keys.open ?? []).join(", ")}.` : "";
      this.setErrorMessage(`No option selected.${info2}`);
      return;
    }
    await super.submit();
  }
  /** Get value of selected option. */
  getValue() {
    const option = this.options[this.listIndex];
    assertIsOption(option);
    return option.value;
  }
  /**
   * Validate input value.
   * @param value User input value.
   * @return True on success, false or error message on error.
   */
  validate(value) {
    return this.options.findIndex((option) => isOption2(option) && option.value === value) !== -1;
  }
  /**
   * Map input value to output value.
   * @param value Input value.
   * @return Output value.
   */
  transform(value) {
    return value;
  }
  /**
   * Format output value.
   * @param value Output value.
   */
  format(value) {
    return this.settings.format?.(value) ?? this.getOptionByValue(value)?.name ?? String(value);
  }
};
function assertIsOption(option) {
  if (!isOption2(option)) {
    throw new Error("Expected an option but got an option group.");
  }
}
function isSelectOptionGroup(option) {
  return isOptionGroup(option);
}

// https://deno.land/x/cliffy@v1.0.0-rc.3/prompt/prompt.ts
var injected = {};
function prompt(prompts, options) {
  return new PromptList(
    prompts,
    options
  ).run(options?.initial);
}
var PromptList = class {
  constructor(prompts, options) {
    this.prompts = prompts;
    this.options = options;
    this.names = this.prompts.map((prompt2) => prompt2.name);
    this.tty = tty({
      writer: options?.writer ?? Deno.stdout
    });
  }
  result = {};
  index = -1;
  names;
  isInBeforeHook = false;
  tty;
  get prompt() {
    return this.prompts[this.index];
  }
  async run(name2) {
    this.index = -1;
    this.result = {};
    this.isInBeforeHook = false;
    await this.next(name2);
    return this.result;
  }
  async next(name2) {
    if (this.updateIndex(name2)) {
      await this.runBeforeHook(async () => {
        this.isInBeforeHook = false;
        await this.runPrompt();
        await this.runAfterHook();
      });
    }
  }
  updateIndex(name2) {
    if (name2 && typeof name2 === "string") {
      this.index = this.names.indexOf(name2);
      if (this.index === -1) {
        throw new Error(
          `Invalid prompt name: ${name2}, allowed prompt names: ${this.names.join(", ")}`
        );
      }
    } else if (typeof name2 === "number") {
      if (name2 < 0 || name2 > this.names.length) {
        throw new Error(
          `Invalid prompt index: ${name2}, prompt length: ${this.names.length}`
        );
      }
      this.index = name2;
    } else if (name2 === true && !this.isInBeforeHook) {
      this.index++;
      if (this.index < this.names.length - 1) {
        this.index++;
      }
    } else {
      this.index++;
    }
    this.isInBeforeHook = false;
    if (this.index < this.names.length) {
      return true;
    } else if (this.index === this.names.length) {
      return false;
    } else {
      throw new Error("next() called multiple times");
    }
  }
  async runBeforeHook(run5) {
    this.isInBeforeHook = true;
    const next = async (name2) => {
      if (name2 || typeof name2 === "number") {
        return this.next(name2);
      }
      await run5();
    };
    if (this.options?.before) {
      await this.options.before(
        this.prompt.name,
        this.result,
        async (name2) => {
          if (name2 || typeof name2 === "number") {
            return this.next(name2);
          } else if (this.prompt.before) {
            await this.prompt.before(this.result, next);
          } else {
            await run5();
          }
        }
      );
      return;
    } else if (this.prompt.before) {
      await this.prompt.before(this.result, next);
      return;
    }
    await run5();
  }
  async runPrompt() {
    const prompt2 = this.prompt.type;
    if (typeof injected[this.prompt.name] !== "undefined") {
      if (prompt2.inject) {
        prompt2.inject(injected[this.prompt.name]);
      } else {
        GenericPrompt.inject(injected[this.prompt.name]);
      }
    }
    try {
      this.result[this.prompt.name] = await prompt2.prompt({
        reader: this.options?.reader,
        writer: this.options?.writer,
        cbreak: this.options?.cbreak,
        ...this.prompt
      });
    } finally {
      this.tty.cursorShow();
    }
  }
  async runAfterHook() {
    if (this.options?.after) {
      await this.options.after(this.prompt.name, this.result, async (name2) => {
        if (name2) {
          return this.next(name2);
        } else if (this.prompt.after) {
          await this.prompt.after(this.result, (name3) => this.next(name3));
        } else {
          await this.next();
        }
      });
    } else if (this.prompt.after) {
      await this.prompt.after(this.result, (name2) => this.next(name2));
    } else {
      await this.next();
    }
  }
};

// tools/tools-console.ts
init_log();

// tools/tools.ts
init_log();
init_log2();
init_platform();

// tools/types.ts
var kUpdatePath = "update-path";

// tools/impl/tinytex.ts
init_log();
init_fs();
init_path();
init_path2();
init_zip();
init_process();
init_github();
init_copy5();
init_path2();
init_fs();
init_platform();
var kDefaultRepos = [
  "https://mirrors.rit.edu/CTAN/systems/texlive/tlnet/",
  "https://ctan.math.illinois.edu/systems/texlive/tlnet/",
  "https://mirror.las.iastate.edu/tex-archive/systems/texlive/tlnet/"
];
var kTinyTexRepo = "rstudio/tinytex-releases";
var kPackageMaximal = "TinyTeX";
var kVersionFileName2 = "version";
var tinyTexInstallable = {
  name: "TinyTeX",
  prereqs: [{
    check: () => {
      return isWritable("/usr/local/bin");
    },
    os: ["darwin"],
    message: "The directory /usr/local/bin is not writable."
  }],
  installed,
  installDir,
  binDir,
  installedVersion,
  verifyConfiguration,
  latestRelease: remotePackageInfo,
  preparePackage,
  install: install3,
  afterInstall,
  uninstall
};
async function installed() {
  const hasTiny = hasTinyTex();
  if (hasTiny) {
    return true;
  } else {
    if (await hasTexLive()) {
      return await isTinyTex();
    } else {
      return false;
    }
  }
}
async function installDir() {
  if (await installed()) {
    return Promise.resolve(tinyTexInstallDir());
  } else {
    return Promise.resolve(void 0);
  }
}
function verifyConfiguration() {
  return Promise.resolve({ status: "ok" });
}
async function binDir() {
  if (await installed()) {
    const installDir4 = tinyTexInstallDir();
    if (installDir4) {
      return Promise.resolve(binFolder(installDir4));
    } else {
      warn(
        "Failed to resolve tinytex install directory even though it is installed."
      );
      return Promise.resolve(void 0);
    }
  } else {
    return Promise.resolve(void 0);
  }
}
async function installedVersion() {
  const installDir4 = tinyTexInstallDir();
  if (installDir4) {
    const versionFile = join4(installDir4, kVersionFileName2);
    if (existsSync2(versionFile)) {
      return await Deno.readTextFile(versionFile);
    } else {
      return void 0;
    }
  } else {
    return void 0;
  }
}
function noteInstalledVersion2(version4) {
  const installDir4 = tinyTexInstallDir();
  if (installDir4) {
    const versionFile = join4(installDir4, kVersionFileName2);
    Deno.writeTextFileSync(
      versionFile,
      version4
    );
  }
}
async function preparePackage(context) {
  const pkgInfo = await remotePackageInfo();
  const version4 = pkgInfo.version;
  const candidates = tinyTexPkgName(kPackageMaximal, version4);
  const result2 = tinyTexUrl(candidates, pkgInfo);
  if (result2) {
    const filePath = join4(context.workingDir, result2.name);
    await context.download(`TinyTex ${version4}`, result2.url, filePath);
    return { filePath, version: version4 };
  } else {
    context.error(
      `Couldn't determine what URL to use to download TinyTeX. Tried: ${candidates.join(", ")}`
    );
    return Promise.reject();
  }
}
async function install3(pkgInfo, context) {
  const installDir4 = tinyTexInstallDir();
  if (installDir4) {
    const parentDir = join4(installDir4, "..");
    const realParentDir = expandPath(parentDir);
    const tinyTexDirName = isLinux ? ".TinyTeX" : "TinyTeX";
    debug(`TinyTex Directory Information:`);
    debug(`> installDir:  ${installDir4}`);
    debug(`> parentDir:  ${parentDir}`);
    debug(`> realParentDir:  ${realParentDir}`);
    if (existsSync2(realParentDir)) {
      debug(`Unzipping file ${pkgInfo.filePath}`);
      await context.withSpinner(
        { message: `Unzipping ${basename4(pkgInfo.filePath)}` },
        async () => {
          await unzip(pkgInfo.filePath);
        }
      );
      await context.withSpinner(
        { message: `Moving files` },
        () => {
          const from = join4(context.workingDir, tinyTexDirName);
          debug(`Moving files
> from ${from}
> to   ${installDir4}`);
          copyTo(from, installDir4);
          if (isMac) {
            for (const file of walkSync(from)) {
              if (file.isFile) {
                const relativePath = relative4(from, file.path);
                const destPath = join4(installDir4, relativePath);
                const srcStat = Deno.statSync(file.path);
                const destStat = Deno.statSync(destPath);
                if (srcStat.mode !== null && srcStat.mode !== destStat.mode) {
                  Deno.chmodSync(destPath, srcStat.mode);
                }
              }
            }
          }
          safeRemoveSync(from, { recursive: true });
          noteInstalledVersion2(pkgInfo.version);
          return Promise.resolve();
        }
      );
      context.props[kTlMgrKey] = isWindows4 ? join4(binFolder(installDir4), "tlmgr.bat") : join4(binFolder(installDir4), "tlmgr");
      return Promise.resolve();
    } else {
      context.error("Installation target directory doesn't exist");
      return Promise.reject();
    }
  } else {
    context.error("Unable to determine installation directory");
    return Promise.reject();
  }
}
function binFolder(installDir4) {
  const nixBinFolder = () => {
    const oldBinFolder = join4(
      installDir4,
      "bin",
      `${Deno.build.arch}-${os}`
    );
    if (existsSync2(oldBinFolder)) {
      return oldBinFolder;
    } else {
      return join4(
        installDir4,
        "bin",
        `universal-${os}`
      );
    }
  };
  const winBinFolder = () => {
    const oldBinFolder = join4(
      installDir4,
      "bin",
      "win32"
    );
    if (existsSync2(oldBinFolder)) {
      return oldBinFolder;
    } else {
      return join4(
        installDir4,
        "bin",
        "windows"
      );
    }
  };
  return isWindows4 ? winBinFolder() : nixBinFolder();
}
async function afterInstall(context) {
  const tlmgrPath = context.props[kTlMgrKey];
  if (tlmgrPath) {
    await context.withSpinner(
      { message: "Verifying tlgpg support" },
      async () => {
        if (["darwin", "windows"].includes(os)) {
          await exec(
            tlmgrPath,
            [
              "-q",
              "--repository",
              "http://www.preining.info/tlgpg/",
              "install",
              "tlgpg"
            ]
          );
        }
      }
    );
    await context.withSpinner(
      { message: "Configuring font paths" },
      async () => {
        await exec(
          tlmgrPath,
          [
            "postaction",
            "install",
            "script",
            "xetex"
          ]
        );
      }
    );
    let restartRequired = false;
    const defaultRepo = await textLiveRepo();
    await context.withSpinner(
      {
        message: `Setting default repository`,
        doneMessage: `Default Repository: ${defaultRepo}`
      },
      async () => {
        await exec(
          tlmgrPath,
          ["-q", "option", "repository", defaultRepo]
        );
      }
    );
    if (context.flags[kUpdatePath]) {
      const message = `Unable to determine a path to use when installing TeX Live. 
To complete the installation, please run the following:

${tlmgrPath} option sys_bin <bin_dir_on_path>
${tlmgrPath} path add

This will instruct TeX Live to create symlinks that it needs in <bin_dir_on_path>.`;
      const configureBinPath = async (path3) => {
        if (!isWindows4) {
          const expandedPath = expandPath(path3);
          ensureDirSync(expandedPath);
          await exec(
            tlmgrPath,
            ["option", "sys_bin", expandedPath]
          );
          return true;
        } else {
          return true;
        }
      };
      const paths = [];
      const envPath = Deno.env.get("QUARTO_TEXLIVE_BINPATH");
      if (envPath) {
        paths.push(envPath);
      } else if (!isWindows4) {
        paths.push(...suggestUserBinPaths());
      } else {
        paths.push(tlmgrPath);
      }
      const binPathMessage = envPath ? `Setting TeXLive Binpath: ${envPath}` : !isWindows4 ? `Updating Path (inspecting ${paths.length} possible paths)` : "Updating Path";
      await context.withSpinner(
        { message: binPathMessage },
        async () => {
          let result2;
          for (const path3 of paths) {
            const pathConfigured = await configureBinPath(path3);
            if (pathConfigured) {
              result2 = await exec(
                tlmgrPath,
                ["path", "add"]
              );
              if (result2.success) {
                break;
              }
            }
          }
          if (result2 && !result2.success) {
            warn(message);
          }
        }
      );
      if (isWindows4) {
        const texLiveInstalled = await hasTexLive();
        const texLivePath = await texLiveInPath();
        restartRequired = restartRequired || !texLiveInstalled || !texLivePath;
      }
    }
    return Promise.resolve(restartRequired);
  } else {
    context.error("Couldn't locate tlmgr after installation");
    return Promise.reject();
  }
}
async function uninstall(context) {
  if (!isTinyTex()) {
    context.error("Current LateX installation does not appear to be TinyTex");
    return Promise.reject();
  }
  if (context.flags[kUpdatePath]) {
    if (await texLiveInPath()) {
      await context.withSpinner(
        { message: "Removing commands" },
        async () => {
          const texLive = await texLiveContext(true);
          const result2 = await removePath(texLive);
          if (!result2.success) {
            context.error("Failed to uninstall");
            return Promise.reject();
          }
        }
      );
    }
  }
  await context.withSpinner(
    { message: "Removing directory" },
    async () => {
      const installDir4 = tinyTexInstallDir();
      if (installDir4) {
        await Deno.remove(installDir4, { recursive: true });
      } else {
        context.error("Couldn't find install directory");
        return Promise.reject();
      }
    }
  );
}
function exec(path3, cmd) {
  return execProcess({
    cmd: path3,
    args: cmd,
    stdout: "piped",
    stderr: "piped"
  });
}
var kTlMgrKey = "tlmgr";
async function textLiveRepo() {
  let autoUrl;
  try {
    const url = "https://mirror.ctan.org/systems/texlive/tlnet";
    const response = await fetch(url, { redirect: "follow" });
    autoUrl = response.url;
  } catch (_e) {
  }
  if (!autoUrl) {
    const randomInt2 = Math.floor(Math.random() * kDefaultRepos.length);
    autoUrl = kDefaultRepos[randomInt2];
  }
  return autoUrl;
}
function tinyTexPkgName(base3, ver, options) {
  const effectiveOs = options?.os ?? (isWindows4 ? "windows" : isLinux ? "linux" : "darwin");
  const effectiveArch = options?.arch ?? arch;
  base3 = base3 || "TinyTeX";
  if (!ver) {
    const ext = effectiveOs === "windows" ? "zip" : effectiveOs === "linux" ? "tar.gz" : "tgz";
    return [`${base3}.${ext}`];
  }
  const candidates = [];
  if (effectiveOs === "windows") {
    candidates.push(`${base3}-windows-${ver}.exe`);
    candidates.push(`${base3}-${ver}.zip`);
  } else if (effectiveOs === "linux") {
    if (effectiveArch === "aarch64") {
      candidates.push(`${base3}-linux-arm64-${ver}.tar.xz`);
      candidates.push(`${base3}-arm64-${ver}.tar.gz`);
    } else {
      candidates.push(`${base3}-linux-x86_64-${ver}.tar.xz`);
      candidates.push(`${base3}-${ver}.tar.gz`);
    }
  } else {
    candidates.push(`${base3}-darwin-${ver}.tar.xz`);
    candidates.push(`${base3}-${ver}.tgz`);
  }
  return candidates;
}
function tinyTexUrl(candidates, remotePkgInfo) {
  for (const pkg of candidates) {
    const asset = remotePkgInfo.assets.find((asset2) => asset2.name === pkg);
    if (asset) {
      return { url: asset.url, name: pkg };
    }
  }
  return void 0;
}
async function remotePackageInfo() {
  const githubRelease = await getLatestRelease(kTinyTexRepo);
  return {
    url: githubRelease.html_url,
    version: githubRelease.tag_name,
    assets: githubRelease.assets.map((asset) => {
      return { name: asset.name, url: asset.browser_download_url };
    })
  };
}
async function isWritable(path3) {
  const desc = { name: "write", path: path3 };
  const status = await Deno.permissions.query(desc);
  return status.state === "granted";
}
async function isTinyTex() {
  const root = await texLiveRoot();
  if (root) {
    if (root.match(/[/\\][Tt]iny[Tt]e[Xx][/\\]?/)) {
      return true;
    }
    const cnfFile = join4(root, "texmf-dist/web2c/fmtutil.cnf");
    if (existsSync2(cnfFile)) {
      const cnfText = Deno.readTextFileSync(cnfFile);
      const match = cnfText.match(/\W[.]?TinyTeX\W/);
      if (match) {
        return true;
      }
    }
    return false;
  }
  return false;
}
async function texLiveRoot() {
  const texLivePath = await which("tlmgr");
  if (texLivePath) {
    const realPath = await Deno.realPath(texLivePath);
    if (isWindows4) {
      return join4(realPath, "..", "..", "..");
    } else {
      const root = join4(realPath, "..", "..", "..", "..");
      const tlBin = join4(root, "bin");
      if (existsSync2(tlBin)) {
        return root;
      } else {
        return void 0;
      }
    }
  } else {
    const installDir4 = tinyTexInstallDir();
    if (installDir4 && existsSync2(installDir4)) {
      return installDir4;
    } else {
      return void 0;
    }
  }
}

// tools/impl/chromium.ts
await init_puppeteer();
async function installDir2() {
  if (await installed2()) {
    return Promise.resolve(chromiumInstallDir());
  } else {
    return Promise.resolve(void 0);
  }
}
var chromiumInstallable = {
  name: "Chromium (deprecated)",
  prereqs: [],
  installed: installed2,
  installedVersion: installedVersion2,
  latestRelease,
  preparePackage: preparePackage2,
  install: install4,
  afterInstall: afterInstall2,
  uninstall: uninstall2,
  installDir: installDir2
};
async function installed2() {
  const fetcherObj = await fetcher();
  const version4 = await supportedRevision();
  const localRevisions = await fetcherObj.localRevisions();
  return localRevisions.includes(version4);
}
async function installedVersion2() {
  const fetcherObj = await fetcher();
  const localRevisions = await fetcherObj.localRevisions();
  if (localRevisions.length) {
    return localRevisions[localRevisions.length - 1];
  }
}
async function latestRelease() {
  const fetcherObj = await fetcher();
  const version4 = await supportedRevision();
  const revisionInfo = await fetcherObj.revisionInfo(version4);
  return Promise.resolve({
    url: revisionInfo.url,
    version: version4,
    assets: [{ name: "", url: "" }]
  });
}
async function preparePackage2(_ctx) {
  const revision = await supportedRevision();
  const progress = progressBar(
    100,
    `Downloading Chromium ${revision}`
  );
  let spinnerStatus;
  const fetcherObj = await fetcher();
  const revisionInfo = await fetcherObj.download(
    revision,
    (x3, total) => {
      const percent = x3 / total * 100;
      if (percent < 100) {
        progress.update(percent);
      } else {
        progress.complete(true);
        clearLine();
        spinnerStatus = spinner(`Installing Chromium ${revision}`);
      }
    }
  );
  if (spinnerStatus !== void 0) {
    spinnerStatus();
  }
  return {
    filePath: revisionInfo.folderPath,
    version: revisionInfo.revision
  };
}
function install4(_pkg, _ctx) {
  return Promise.resolve();
}
function afterInstall2(_ctx) {
  return Promise.resolve(false);
}
async function uninstall2(_ctx) {
  await withSpinner({
    message: "Removing Chromium..."
  }, async () => {
    const fetcherObj = await fetcher();
    const version4 = await supportedRevision();
    return fetcherObj.remove(version4);
  });
  return Promise.resolve();
}
async function supportedRevision() {
  return (await getPuppeteer())._preferredRevision;
}

// tools/impl/chrome-headless-shell.ts
init_path();
init_fs();
init_chrome_for_testing();
init_chrome_headless_shell_paths();
async function installed3() {
  return isInstalled(chromeHeadlessShellInstallDir());
}
function installDirIfInstalled() {
  const dir = chromeHeadlessShellInstallDir();
  if (isInstalled(dir)) {
    return Promise.resolve(dir);
  }
  return Promise.resolve(void 0);
}
async function installedVersion3() {
  return readInstalledVersion(chromeHeadlessShellInstallDir());
}
async function latestRelease2() {
  const platformInfo = detectChromePlatform();
  if (isPlaywrightCdnPlatform(platformInfo)) {
    const entry = await fetchPlaywrightBrowsersJson();
    const url = playwrightCdnDownloadUrl(entry.revision);
    return {
      url,
      version: entry.browserVersion,
      assets: [{ name: "chrome-headless-shell", url }]
    };
  }
  const release2 = await fetchLatestCftRelease();
  const { platform: platform2 } = platformInfo;
  const downloads = release2.downloads["chrome-headless-shell"];
  if (!downloads) {
    throw new Error("Chrome for Testing API has no chrome-headless-shell downloads");
  }
  const dl = downloads.find((d4) => d4.platform === platform2);
  if (!dl) {
    throw new Error(
      `No chrome-headless-shell download for platform ${platform2}`
    );
  }
  return {
    url: dl.url,
    version: release2.version,
    assets: [{ name: "chrome-headless-shell", url: dl.url }]
  };
}
async function preparePackage3(ctx) {
  const release2 = await latestRelease2();
  const workingDir = Deno.makeTempDirSync({ prefix: "quarto-chrome-hs-" });
  const binaryName = chromeHeadlessShellBinaryName();
  try {
    await downloadAndExtractChrome(
      "Chrome Headless Shell",
      release2.url,
      workingDir,
      ctx,
      binaryName
    );
  } catch (e5) {
    safeRemoveSync(workingDir, { recursive: true });
    throw e5;
  }
  return {
    filePath: workingDir,
    version: release2.version
  };
}
async function install5(pkg, _ctx) {
  const installDir4 = chromeHeadlessShellInstallDir();
  if (existsSync2(installDir4)) {
    for (const entry of Deno.readDirSync(installDir4)) {
      safeRemoveSync(join4(installDir4, entry.name), { recursive: true });
    }
  }
  for (const entry of Deno.readDirSync(pkg.filePath)) {
    safeMoveSync(join4(pkg.filePath, entry.name), join4(installDir4, entry.name));
  }
  noteInstalledVersion(installDir4, pkg.version);
}
async function afterInstall3(ctx) {
  try {
    if (await chromiumInstallable.installed()) {
      ctx.info("Removing legacy Chromium installation...");
      await chromiumInstallable.uninstall(ctx);
    }
  } catch {
    ctx.info(
      "Note: Could not remove legacy Chromium. You can remove it manually with 'quarto uninstall chromium'."
    );
  }
  return false;
}
async function uninstall3(ctx) {
  await ctx.withSpinner(
    { message: "Removing Chrome Headless Shell..." },
    async () => {
      safeRemoveSync(chromeHeadlessShellInstallDir(), { recursive: true });
    }
  );
}
var chromeHeadlessShellInstallable = {
  name: "Chrome Headless Shell",
  prereqs: [],
  installed: installed3,
  installDir: installDirIfInstalled,
  installedVersion: installedVersion3,
  latestRelease: latestRelease2,
  preparePackage: preparePackage3,
  install: install5,
  afterInstall: afterInstall3,
  uninstall: uninstall3
};

// tools/impl/verapdf.ts
init_fs();
init_path();
init_log();
init_zip();
init_process();
init_appdirs();
init_platform();
var kDownloadBaseUrl = "https://quarto.org/download";
var kDefaultVersion = "1.28.2";
var kMinJavaVersion = 8;
var kMaxSupportedLtsVersion = 21;
var kVersionFileName3 = "version";
function isLtsJavaVersion(version4) {
  if (version4 === 8 || version4 === 11) return true;
  if (version4 >= 17 && (version4 - 17) % 4 === 0) return true;
  return false;
}
var verapdfInstallable = {
  name: "VeraPDF",
  prereqs: [{
    check: async (context) => {
      const javaVersion = await getJavaVersion();
      context.props.javaVersion = javaVersion;
      if (javaVersion === void 0 || javaVersion < kMinJavaVersion) {
        return false;
      }
      if (!isLtsJavaVersion(javaVersion)) {
        const supportedVersions = Array.from(
          { length: kMaxSupportedLtsVersion - 8 + 1 },
          (_3, i6) => i6 + 8
        ).filter(isLtsJavaVersion).join(", ");
        warn(
          `Java ${javaVersion} is not a Long-Term Support (LTS) version. veraPDF ${kDefaultVersion} officially supports Java ${supportedVersions}. Installation will proceed, but you may encounter issues.`
        );
      } else if (javaVersion > kMaxSupportedLtsVersion) {
        warn(
          `Java ${javaVersion} is newer than veraPDF ${kDefaultVersion} officially supports. Installation will proceed, but you may encounter issues.`
        );
      }
      return true;
    },
    os: ["darwin", "linux", "windows"],
    message: (context) => {
      const javaVersion = context.props.javaVersion;
      if (javaVersion === void 0) {
        return `Java is not installed. veraPDF requires Java ${kMinJavaVersion} or later.`;
      } else {
        return `Java ${javaVersion} is too old. veraPDF requires Java ${kMinJavaVersion} or later.`;
      }
    }
  }],
  installed: installed4,
  installDir: installDir3,
  binDir: binDir2,
  installedVersion: installedVersion4,
  latestRelease: latestRelease3,
  preparePackage: preparePackage4,
  install: install6,
  afterInstall: afterInstall4,
  uninstall: uninstall4
};
async function getJavaVersion() {
  try {
    const result2 = await execProcess({
      cmd: "java",
      args: ["-version"],
      stderr: "piped"
    });
    if (!result2.success) {
      return void 0;
    }
    const match = result2.stderr?.match(/version "(\d+)(?:\.(\d+))?/);
    if (match) {
      const major = parseInt(match[1]);
      return major === 1 ? parseInt(match[2]) : major;
    }
  } catch {
    return void 0;
  }
  return void 0;
}
function verapdfInstallDir() {
  return quartoDataDir("verapdf");
}
async function installed4() {
  const dir = verapdfInstallDir();
  const verapdfBin = isWindows4 ? join4(dir, "verapdf.bat") : join4(dir, "verapdf");
  return existsSync2(verapdfBin);
}
async function installDir3() {
  if (await installed4()) {
    return verapdfInstallDir();
  }
  return void 0;
}
async function binDir2() {
  if (await installed4()) {
    return verapdfInstallDir();
  }
  return void 0;
}
async function installedVersion4() {
  const dir = verapdfInstallDir();
  const versionFile = join4(dir, kVersionFileName3);
  if (existsSync2(versionFile)) {
    return await Deno.readTextFile(versionFile);
  }
  return void 0;
}
function noteInstalledVersion3(version4) {
  const dir = verapdfInstallDir();
  const versionFile = join4(dir, kVersionFileName3);
  Deno.writeTextFileSync(versionFile, version4);
}
async function latestRelease3() {
  const version4 = Deno.env.get("VERAPDF") || kDefaultVersion;
  const filename = `verapdf-greenfield-${version4}-installer.zip`;
  const downloadUrl = `${kDownloadBaseUrl}/verapdf/${version4}/${filename}`;
  return {
    url: downloadUrl,
    version: version4,
    assets: [{ name: filename, url: downloadUrl }]
  };
}
async function preparePackage4(context) {
  const pkgInfo = await latestRelease3();
  const version4 = pkgInfo.version;
  const asset = pkgInfo.assets[0];
  const filePath = join4(context.workingDir, asset.name);
  await context.download(`VeraPDF ${version4}`, asset.url, filePath);
  return { filePath, version: version4 };
}
async function install6(pkgInfo, context) {
  const targetDir = verapdfInstallDir();
  await context.withSpinner(
    { message: `Extracting ${basename4(pkgInfo.filePath)}` },
    async () => {
      await unzip(pkgInfo.filePath);
    }
  );
  const extractedDir = context.workingDir;
  let installerJar;
  for await (const entry of Deno.readDir(extractedDir)) {
    if (entry.isDirectory && entry.name.startsWith("verapdf-")) {
      const subDir = join4(extractedDir, entry.name);
      for await (const subEntry of Deno.readDir(subDir)) {
        if (subEntry.isFile && subEntry.name.endsWith(".jar")) {
          installerJar = join4(subDir, subEntry.name);
          break;
        }
      }
      if (installerJar) break;
    } else if (entry.isFile && entry.name.endsWith(".jar")) {
      installerJar = join4(extractedDir, entry.name);
      break;
    }
  }
  if (!installerJar) {
    context.error(
      "Could not find veraPDF installer JAR in the downloaded package"
    );
    return Promise.reject();
  }
  const autoInstallXml = `<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<AutomatedInstallation langpack="eng">
  <com.izforge.izpack.panels.htmlhello.HTMLHelloPanel id="welcome"/>
  <com.izforge.izpack.panels.target.TargetPanel id="install_dir">
    <installpath>${targetDir}</installpath>
  </com.izforge.izpack.panels.target.TargetPanel>
  <com.izforge.izpack.panels.packs.PacksPanel id="sdk_pack_select">
    <pack index="0" name="veraPDF GUI" selected="false"/>
    <pack index="1" name="veraPDF Mac and *nix Scripts" selected="true"/>
    <pack index="2" name="veraPDF Batch files" selected="true"/>
    <pack index="3" name="veraPDF Validation model" selected="true"/>
    <pack index="4" name="veraPDF Documentation" selected="false"/>
    <pack index="5" name="veraPDF Sample Plugins" selected="false"/>
  </com.izforge.izpack.panels.packs.PacksPanel>
  <com.izforge.izpack.panels.install.InstallPanel id="install"/>
  <com.izforge.izpack.panels.finish.FinishPanel id="finish"/>
</AutomatedInstallation>`;
  const autoInstallPath = join4(extractedDir, "auto-install.xml");
  await Deno.writeTextFile(autoInstallPath, autoInstallXml);
  await context.withSpinner(
    { message: "Installing veraPDF" },
    async () => {
      const result2 = await execProcess({
        cmd: "java",
        args: ["-jar", installerJar, autoInstallPath],
        stdout: "piped",
        stderr: "piped"
      });
      if (!result2.success) {
        const errorMsg = result2.stderr || "Unknown error";
        throw new Error(`veraPDF installation failed: ${errorMsg}`);
      }
    }
  );
  noteInstalledVersion3(pkgInfo.version);
}
async function afterInstall4(context) {
  if (context.flags[kUpdatePath]) {
    const dir = verapdfInstallDir();
    const verapdfBin = isWindows4 ? join4(dir, "verapdf.bat") : join4(dir, "verapdf");
    await context.withSpinner(
      { message: "Updating PATH" },
      async () => {
        await createToolSymlink(verapdfBin, "verapdf", context);
      }
    );
    return isWindows4;
  }
  return false;
}
async function uninstall4(context) {
  if (context.flags[kUpdatePath]) {
    await removeToolSymlink("verapdf");
  }
  await context.withSpinner(
    { message: "Removing veraPDF" },
    async () => {
      const dir = verapdfInstallDir();
      if (existsSync2(dir)) {
        safeRemoveSync(dir, { recursive: true });
      }
    }
  );
}

// core/download.ts
init_write_all();
async function downloadWithProgress(url, msg5, toFile) {
  const response = await (typeof url === "string" ? fetch(
    url,
    {
      redirect: "follow"
    }
  ) : url);
  if (response.status === 200 && response.body) {
    const pkgFile = await Deno.open(toFile, { create: true, write: true });
    const contentLength = response.headers.get("content-length") || 0;
    const contentLengthMb = contentLength / 1024 / 1024;
    const prog = progressBar(contentLengthMb, msg5);
    let totalLength = 0;
    for await (const chunk of response.body) {
      await writeAll(pkgFile, chunk);
      totalLength = totalLength + chunk.length;
      if (contentLength > 0) {
        prog.update(
          totalLength / 1024 / 1024,
          `${(totalLength / 1024 / 1024).toFixed(1)}MB`
        );
      }
    }
    prog.complete();
    pkgFile.close();
  } else {
    throw new Error(
      `download failed (HTTP status ${response.status} - ${response.statusText})`
    );
  }
}

// tools/tools.ts
init_fs();
init_path();
init_path2();
init_platform();
var kInstallableTools = {
  tinytex: tinyTexInstallable,
  // temporarily disabled until deno 1.28.* gets puppeteer support
  chromium: chromiumInstallable,
  "chrome-headless-shell": chromeHeadlessShellInstallable,
  verapdf: verapdfInstallable
};
var kDeprecatedTools = /* @__PURE__ */ new Set(["chromium"]);
function isDeprecatedTool(key) {
  return kDeprecatedTools.has(key);
}
async function allTools() {
  const installed5 = [];
  const notInstalled = [];
  const tools = installableTools();
  for (const name2 of tools) {
    const tool = installableTool(name2);
    const isInstalled2 = await tool.installed();
    if (isInstalled2) {
      installed5.push(tool);
    } else if (!isDeprecatedTool(name2)) {
      notInstalled.push(tool);
    }
  }
  return {
    installed: installed5,
    notInstalled
  };
}
function installableTools() {
  return Object.keys(kInstallableTools);
}
function installableToolNames() {
  return Object.values(kInstallableTools).map((tool) => tool.name);
}
async function printToolInfo(name2) {
  name2 = name2 || "";
  const tool = installableTool(name2);
  if (tool) {
    const response = {
      name: tool.name,
      installed: await tool.installed(),
      version: await tool.installedVersion(),
      directory: await tool.installDir()
    };
    if (tool.binDir) {
      response["bin-directory"] = await tool.binDir();
    }
    if (response.installed && tool.verifyConfiguration) {
      response["configuration"] = await tool.verifyConfiguration();
    }
    Deno.stdout.writeSync(
      new TextEncoder().encode(JSON.stringify(response, null, 2) + "\n")
    );
  }
}
function checkToolRequirement(name2) {
  if (name2.toLowerCase() === "chromium" && isWSL()) {
    const troubleshootUrl = "https://pptr.dev/next/troubleshooting#running-puppeteer-on-wsl-windows-subsystem-for-linux.";
    warn([
      `${name2} can't be installed fully on WSL with Quarto as system requirements could be missing.`,
      `- Please do a manual installation following recommandations at ${troubleshootUrl}`,
      "- See https://github.com/quarto-dev/quarto-cli/issues/1822 for more context."
    ].join("\n"));
    return false;
  } else if (name2.toLowerCase() === "chrome-headless-shell" && isWSL()) {
    info(
      "Note: chrome-headless-shell is a headless-only binary and should work on WSL without additional system dependencies."
    );
    return true;
  } else {
    return true;
  }
}
async function installTool(name2, updatePath) {
  name2 = name2 || "";
  if (name2.toLowerCase() === "chromium") {
    warn(
      "'chromium' is deprecated. Installing 'chrome-headless-shell' instead.\nPlease update your scripts to use 'quarto install chrome-headless-shell'."
    );
    return installTool("chrome-headless-shell", updatePath);
  }
  const tool = installableTool(name2);
  if (tool) {
    if (checkToolRequirement(name2)) {
      const workingDir = Deno.makeTempDirSync();
      try {
        const context = installContext(workingDir, updatePath);
        context.info(`Installing ${name2}`);
        const alreadyInstalled = await tool.installed();
        if (alreadyInstalled) {
          context.error(`Install canceled - ${name2} is already installed.`);
          Deno.exit(1);
        } else {
          const platformPrereqs = tool.prereqs.filter(
            (prereq) => prereq.os.includes(os)
          );
          for (const prereq of platformPrereqs) {
            const met = await prereq.check(context);
            if (!met) {
              const message = typeof prereq.message === "function" ? await prereq.message(context) : prereq.message;
              context.error(message);
              Deno.exit(1);
            }
          }
          const pkgInfo = await tool.preparePackage(context);
          await tool.install(pkgInfo, context);
          const restartRequired = await tool.afterInstall(context);
          context.info("Installation successful");
          if (restartRequired) {
            context.info(
              "To complete this installation, please restart your system."
            );
          }
        }
      } finally {
        safeRemoveSync(workingDir, { recursive: true });
      }
    }
  } else {
    info(
      `Could not install '${name2}'- try again with one of the following:`
    );
    installableTools().forEach(
      (name3) => info("quarto install " + name3, { indent: 2 })
    );
  }
}
async function uninstallTool(name2, updatePath) {
  const tool = installableTool(name2);
  if (tool) {
    const installed5 = await tool.installed();
    if (installed5) {
      const workingDir = Deno.makeTempDirSync();
      const context = installContext(workingDir, updatePath);
      context.info(`Uninstalling ${name2}`);
      try {
        await tool.uninstall(context);
        info(`Uninstallation successful`);
      } catch (e5) {
        logError(e5);
      } finally {
        safeRemoveSync(workingDir, { recursive: true });
      }
    } else {
      info(
        `${name2} is not installed use 'quarto install ${name2} to install it.`
      );
    }
  }
}
async function updateTool(name2) {
  const summary = await toolSummary(name2);
  const tool = installableTool(name2);
  if (tool && summary && summary.installed) {
    const workingDir = Deno.makeTempDirSync();
    const context = installContext(workingDir);
    try {
      context.info(
        `Updating ${tool.name} from ${summary.installedVersion} to ${summary.latestRelease.version}`
      );
      const pkgInfo = await tool.preparePackage(context);
      context.info(`Removing ${summary.installedVersion}`);
      await tool.uninstall(context);
      context.info(`Installing ${summary.latestRelease.version}`);
      await tool.install(pkgInfo, context);
      context.info("Finishing update");
      const restartRequired = await tool.afterInstall(context);
      context.info("Update successful");
      if (restartRequired) {
        context.info(
          "To complete this update, please restart your system."
        );
      }
    } catch (e5) {
      logError(e5);
    } finally {
      safeRemoveSync(workingDir, { recursive: true });
    }
  } else {
    info(
      `${name2} is not installed use 'quarto install ${name2.toLowerCase()} to install it.`
    );
  }
}
async function toolSummary(name2) {
  const tool = installableTool(name2);
  if (tool) {
    const installed5 = await tool.installed();
    const installedVersion5 = await tool.installedVersion();
    const latestRelease4 = await tool.latestRelease();
    const configuration = tool.verifyConfiguration && installed5 ? await tool.verifyConfiguration() : { status: "ok" };
    return { installed: installed5, installedVersion: installedVersion5, latestRelease: latestRelease4, configuration };
  } else {
    return void 0;
  }
}
function installableTool(name2) {
  return kInstallableTools[name2.toLowerCase()];
}
var installContext = (workingDir, updatePath) => {
  const installMessaging = {
    info: (msg5) => {
      info(msg5);
    },
    error: (msg5) => {
      info(msg5);
    },
    confirm: (msg5, def) => {
      if (def !== void 0) {
        return Confirm.prompt({ message: msg5, default: def });
      } else {
        return Confirm.prompt(msg5);
      }
    },
    withSpinner
  };
  return {
    download: async (name2, url, target) => {
      try {
        await downloadWithProgress(url, `Downloading ${name2}`, target);
      } catch (error2) {
        if (!(error2 instanceof Error)) {
          throw error2;
        }
        installMessaging.error(
          error2.message
        );
        Deno.exit(1);
      }
    },
    workingDir,
    ...installMessaging,
    props: {},
    flags: {
      [kUpdatePath]: updatePath
    }
  };
};
async function createToolSymlink(binaryPath, symlinkName, context) {
  if (isWindows4) {
    context.info(
      `Add the tool's directory to your PATH to use ${symlinkName} from anywhere.`
    );
    return false;
  }
  const binPaths = suggestUserBinPaths();
  if (binPaths.length === 0) {
    context.info(
      `No suitable bin directory found in PATH. Add the tool's directory to your PATH manually.`
    );
    return false;
  }
  for (const binPath of binPaths) {
    const expandedBinPath = expandPath(binPath);
    ensureDirSync(expandedBinPath);
    const symlinkPath = join4(expandedBinPath, symlinkName);
    try {
      if (existsSync2(symlinkPath)) {
        await Deno.remove(symlinkPath);
      }
      await Deno.symlink(binaryPath, symlinkPath);
      return true;
    } catch {
      continue;
    }
  }
  context.info(
    `Could not create symlink. Add the tool's directory to your PATH manually.`
  );
  return false;
}
async function removeToolSymlink(symlinkName) {
  if (isWindows4) {
    return;
  }
  const binPaths = suggestUserBinPaths();
  for (const binPath of binPaths) {
    const symlinkPath = join4(expandPath(binPath), symlinkName);
    try {
      const stat = await Deno.lstat(symlinkPath);
      if (stat.isSymlink) {
        await Deno.remove(symlinkPath);
      }
    } catch {
    }
  }
}

// tools/tools-console.ts
async function outputTools() {
  const toolRows = [];
  const statusMsgs = [];
  const installStatus = (summary) => {
    if (summary.installed) {
      if (summary.installedVersion) {
        if (summary.installedVersion === summary.latestRelease.version) {
          return "Up to date";
        } else {
          return "Update available";
        }
      } else {
        return "External Installation";
      }
    } else {
      return "Not installed";
    }
  };
  const tools = await loadTools();
  for (const tool of tools) {
    const summary = await toolSummary(tool.key);
    if (summary) {
      toolRows.push([
        tool.key,
        installStatus(summary),
        summary.installedVersion || "---",
        summary.latestRelease.version
      ]);
      if (summary.configuration.status !== "ok") {
        statusMsgs.push(
          `${summary.configuration.message}`
        );
      }
    }
  }
  info("");
  const table = new Table().header([
    bold3("Tool"),
    bold3("Status"),
    bold3("Installed"),
    bold3("Latest")
  ]).body(
    toolRows
  ).padding(5);
  info(table.toString());
  statusMsgs.forEach((msg5) => {
    warn(msg5);
  });
}
async function loadTools() {
  let sorted = [];
  await withSpinner({ message: "Inspecting tools" }, async () => {
    const toolInfos = [];
    for (const key of installableTools()) {
      const tool = installableTool(key);
      const installed5 = await tool.installed();
      if (!installed5 && isDeprecatedTool(key)) continue;
      const version4 = await tool.installedVersion();
      const latest = await tool.latestRelease();
      toolInfos.push({ key, tool, version: version4, installed: installed5, latest });
    }
    sorted = toolInfos.sort((tool1, tool2) => {
      return tool1.tool.name.localeCompare(tool2.tool.name);
    });
  });
  return sorted;
}
async function afterConfirm(message, action, prompt2) {
  if (prompt2 !== false) {
    const confirmed = await Confirm.prompt(
      {
        message,
        default: true
      }
    );
    if (confirmed) {
      info("");
      return action();
    } else {
      return Promise.resolve();
    }
  } else {
    return action();
  }
}
var removeTool = (toolname, prompt2, updatePath) => {
  return afterConfirm(
    `Are you sure you'd like to remove ${toolname}?`,
    () => {
      return uninstallTool(toolname, updatePath);
    },
    prompt2
  );
};
async function updateOrInstallTool(tool, action, prompt2, updatePath) {
  if (tool.toLowerCase() === "chromium") {
    warn(
      "'chromium' is deprecated. Installing 'chrome-headless-shell' instead.\nPlease update your scripts to use 'quarto install chrome-headless-shell'."
    );
    if (action === "update") {
      const chsSummary = await toolSummary("chrome-headless-shell");
      const redirectAction = chsSummary?.installed ? "update" : "install";
      const legacyTool = installableTool("chromium");
      if (legacyTool && await legacyTool.installed()) {
        await uninstallTool("chromium");
      }
      return updateOrInstallTool("chrome-headless-shell", redirectAction, prompt2, updatePath);
    }
    return updateOrInstallTool("chrome-headless-shell", "install", prompt2, updatePath);
  }
  const summary = await toolSummary(tool);
  if (action === "update") {
    if (!summary?.installed) {
      return afterConfirm(
        `${tool} is not installed. Do you want to install it now?`,
        () => {
          return installTool(tool, updatePath);
        },
        prompt2
      );
    } else {
      if (summary.installedVersion === void 0) {
        info(
          `${tool} was not installed using Quarto. Please use the tool that you used to install ${tool} instead.`
        );
      } else if (summary.installedVersion === summary.latestRelease.version) {
        info(`${tool} is already up to date.`);
      } else {
        return afterConfirm(
          `Do you want to update ${tool} from ${summary.installedVersion} to ${summary.latestRelease.version}?`,
          () => {
            return updateTool(tool);
          },
          prompt2
        );
      }
    }
  } else {
    if (summary && summary.installed) {
      if (summary.installedVersion === summary.latestRelease.version) {
        info(`${tool} is already installed and up to date.`);
      } else {
        return afterConfirm(
          `${tool} is already installed. Do you want to update to ${summary.latestRelease.version}?`,
          () => {
            return updateTool(tool);
          },
          prompt2
        );
      }
    } else {
      return installTool(tool, updatePath);
    }
  }
}
async function selectTool(toolsInfo, action) {
  const name2 = (toolInfo) => {
    if (action === "install" || action == "update") {
      if (toolInfo.installed) {
        return `${toolInfo.tool.name}${toolInfo.version ? " (" + toolInfo.version + " installed)" : ""}`;
      } else {
        return `${toolInfo.tool.name}${toolInfo.latest.version ? " (" + toolInfo.latest.version + ")" : ""}`;
      }
    } else {
      if (!toolInfo.installed) {
        return `${toolInfo.tool.name} (not installed)`;
      } else {
        return `${toolInfo.tool.name}${toolInfo.version ? " (" + toolInfo.version + " installed)" : ""}`;
      }
    }
  };
  const result2 = await prompt([{
    name: "tool",
    message: `Select a tool to ${action}`,
    options: toolsInfo.map((toolInfo) => {
      return {
        name: name2(toolInfo),
        value: toolInfo.key,
        disabled: action === "install" ? toolInfo.installed : !toolInfo.installed
      };
    }),
    type: Select
  }]);
  return result2.tool;
}

// command/tools/cmd.ts
init_log();
var toolsCommand = new Command().name("tools").description(
  `Display the status of Quarto installed dependencies`
).example(
  "Show tool status",
  "quarto tools"
).action(async (_options) => {
  await outputTools();
}).command("install <tool:string>").hidden().action(
  async (_options, tool) => {
    info(
      "This command has been superseded. Please use `quarto install` instead.\n"
    );
    await updateOrInstallTool(
      tool,
      "install"
    );
  }
).command("info <tool:string>").hidden().action(
  async (_options, tool) => {
    await printToolInfo(tool);
  }
).command("uninstall <tool:string>").hidden().action(
  async (_options, tool) => {
    info(
      "This command has been superseded. Please use `quarto uninstall` instead.\n"
    );
    await removeTool(tool);
  }
).command("update <tool:string>").hidden().action(
  async (_options, tool) => {
    info(
      "This command has been superseded. Please use `quarto update` instead.\n"
    );
    await updateOrInstallTool(
      tool,
      "update"
    );
  }
).command("list").hidden().action(async () => {
  info(
    "This command has been superseded. Please use `quarto tools` with no arguments to list tools and status.\n"
  );
  await outputTools();
});

// command/preview/cmd.ts
init_fs();
init_path();
init_colors2();
init_port_consts();
init_port();
init_flags2();

// project/serve/serve.ts
init_log();
init_fs();
init_path();
init_colors2();
init_lodash();
init_deno_dom();
init_mime();
init_path2();
init_log2();
init_types4();
await init_project_shared();
await init_project_context();
init_http();

// project/serve/watch.ts
init_path();
init_fs();
init_lodash();
init_path2();
init_hash2();
init_log2();
init_format5();
init_types4();
await init_project_shared();
await init_project_context();
await init_render_services();
init_mime();
init_file();
await init_extension();
function watchProject(project, extensionDirs, resourceFiles, renderOptions, pandocArgs, options, renderingOnReload, renderManager, stopServer) {
  const nbContext = notebookContext();
  const flags = renderOptions.flags;
  const refreshProjectConfig = async () => {
    project.cleanup();
    project = await projectContext(project.dir, nbContext, renderOptions, false);
  };
  const projDir = normalizePath(project.dir);
  const projDirHidden = projDir + "/.";
  const outputDir = projectOutputDir(project);
  const libDirConfig = project.config?.project[kProjectLibDir];
  const libDirSource = libDirConfig ? join4(project.dir, libDirConfig) : void 0;
  const isResourceFile = (path3) => {
    if (libDirSource && path3.startsWith(libDirSource)) {
      return false;
    } else {
      return project.files.resources?.includes(path3) || resourceFiles.includes(path3);
    }
  };
  const extensionFiles = extensionFilesFromDirs(extensionDirs);
  const isExtensionFile = (path3) => {
    return extensionFiles.includes(path3);
  };
  const isInputFile = (path3) => {
    return project.files.input.includes(path3);
  };
  const rendered = /* @__PURE__ */ new Map();
  const handleWatchEvent = async (event) => {
    try {
      const paths = uniq(
        event.paths.filter((path3) => !path3.startsWith(projDirHidden)).filter(
          (path3) => outputDir === project.dir || !path3.startsWith(outputDir)
        )
      );
      if (paths.length === 0) {
        return;
      }
      if (["modify", "create"].includes(event.kind)) {
        if (options[kProjectWatchInputs]) {
          const inputs = paths.filter(isInputFile).filter(existsSync1).filter(
            (input) => {
              return !rendered.has(input) || rendered.get(input) !== md5HashSync(Deno.readTextFileSync(input));
            }
          );
          if (inputs.length) {
            const services = renderServices(nbContext);
            try {
              const result2 = await renderManager.submitRender(() => {
                if (inputs.length > 1) {
                  return renderProject(
                    project,
                    {
                      services,
                      progress: true,
                      flags,
                      pandocArgs,
                      previewServer: true
                    },
                    inputs
                  );
                } else {
                  return render(inputs[0], {
                    services,
                    flags,
                    pandocArgs,
                    previewServer: true
                  });
                }
              });
              if (result2.error) {
                result2.context.cleanup();
                renderManager.onRenderError(result2.error);
                return void 0;
              }
              for (const input of inputs.filter(existsSync1)) {
                rendered.set(
                  input,
                  await md5HashAsync(Deno.readTextFileSync(input))
                );
              }
              renderManager.onRenderResult(
                result2,
                extensionDirs,
                resourceFiles,
                project
              );
              const nonSupplementalFiles = result2.files.filter(
                (renderResultFile) => {
                  return !renderResultFile.supplemental;
                }
              );
              result2.context.cleanup();
              return {
                config: false,
                output: true,
                reloadTarget: nonSupplementalFiles.length && !isPdfContent(nonSupplementalFiles[0].file) ? join4(outputDir, nonSupplementalFiles[0].file) : void 0
              };
            } finally {
              services.cleanup();
            }
          }
        }
        const configFile = paths.some(
          (path3) => (project.files.config || []).includes(path3)
        );
        const inputFileRemoved = project.files.input.some(
          (file) => !existsSync2(file)
        );
        const configResourceFile = paths.some(
          (path3) => (project.files.configResources || []).includes(path3) && !project.files.input.includes(path3)
        );
        const resourceFile = paths.some(isResourceFile);
        const extensionFile2 = paths.some(isExtensionFile);
        const reload = configFile || configResourceFile || resourceFile || extensionFile2 || inputFileRemoved;
        if (reload) {
          return {
            config: configFile || configResourceFile || inputFileRemoved,
            output: false
          };
        } else {
          return;
        }
      } else {
        return;
      }
    } catch (e5) {
      logError(e5);
      return;
    }
  };
  const devServer = httpDevServer(
    options.timeout,
    () => renderManager.isRendering(),
    stopServer
  );
  const reloadClients = debounce(async (changes) => {
    const services = renderServices(nbContext);
    try {
      if (!changes.output && !renderingOnReload) {
        await refreshProjectConfig();
        const result2 = await renderManager.submitRender(
          () => renderProject(
            project,
            {
              services,
              useFreezer: true,
              devServerReload: true,
              flags,
              pandocArgs,
              previewServer: true
            }
          )
        );
        if (result2.error) {
          renderManager.onRenderError(result2.error);
        } else {
          renderManager.onRenderResult(
            result2,
            extensionDirs,
            resourceFiles,
            project
          );
        }
      }
      if (changes.config) {
        await refreshProjectConfig();
      }
      let reloadTarget = changes.reloadTarget || "";
      if (reloadTarget && await preventReload(project, reloadTarget, options)) {
        return;
      }
      if (reloadTarget && options.navigate) {
        if (reloadTarget.startsWith(outputDir)) {
          reloadTarget = relative4(outputDir, reloadTarget);
        } else {
          reloadTarget = relative4(projDir, reloadTarget);
        }
        if (existsSync2(join4(outputDir, reloadTarget))) {
          reloadTarget = "/" + pathWithForwardSlashes(reloadTarget);
        } else {
          reloadTarget = "";
        }
      } else {
        reloadTarget = "";
      }
      devServer.reloadClients(reloadTarget);
    } catch (e5) {
      logError(e5);
    } finally {
      services.cleanup();
    }
  }, 100);
  const watcher = watchForFileChanges(() => {
    return uniq([
      ...project.files.input,
      ...project.files.resources || [],
      ...project.files.config || [],
      ...project.files.configResources || [],
      ...resourceFiles,
      // statically computed at project startup
      ...extensionFiles
      // statically computed at project startup
    ]);
  });
  const watchForChanges = async () => {
    for await (const event of watcher) {
      const result2 = await handleWatchEvent(event);
      if (result2) {
        await reloadClients(result2);
      }
    }
  };
  watchForChanges();
  return Promise.resolve({
    handle: (req) => {
      return devServer.handle(req);
    },
    request: devServer.request,
    injectClient: (req, file, inputFile, contentType2) => {
      return devServer.injectClient(req, file, inputFile, contentType2);
    },
    clientHtml: (req, inputFile) => {
      return devServer.clientHtml(req, inputFile);
    },
    hasClients: () => devServer.hasClients(),
    reloadClients: async (output, reloadTarget) => {
      await reloadClients({
        config: false,
        output,
        reloadTarget
      });
    },
    project: () => project,
    refreshProject: async () => {
      await refreshProjectConfig();
      return project;
    }
  });
}
async function preventReload(project, lastHtmlFile, options) {
  if (isRStudio() && !options[kProjectWatchInputs]) {
    const index2 = await inputTargetIndexForOutputFile(
      project,
      relative4(projectOutputDir(project), lastHtmlFile)
    );
    if (index2) {
      return isRevealjsOutput(Object.keys(index2.formats)[0]);
    }
  }
  return false;
}

// project/serve/serve.ts
await init_render_services();
init_project_types();
init_render();
init_constants6();
init_format5();
init_book_shared();
init_flags2();

// project/serve/render.ts
init_path();
init_hash2();
init_jupyter();
init_log2();
init_mime();
await init_extension();
await init_project_shared();
init_types4();
init_project_types();
var ServeRenderManager = class {
  fileRequiresReRender(file, inputFile, extensionDirs, resourceFiles, project) {
    const lastRenderHash = this.fileRenders_.get(file);
    if (lastRenderHash) {
      return lastRenderHash !== this.fileRenderHash(
        file,
        inputFile,
        extensionDirs,
        resourceFiles,
        project
      );
    } else {
      return true;
    }
  }
  submitRender(render2) {
    HttpDevServerRenderMonitor.onRenderStart();
    return this.renderQueue_.enqueue(render2);
  }
  isRendering() {
    return this.renderQueue_.isRunning();
  }
  onRenderError(error2) {
    HttpDevServerRenderMonitor.onRenderStop(false);
    if (error2.message) {
      logError(error2);
    }
  }
  onRenderResult(result2, extensionDirs, resourceFiles, project) {
    HttpDevServerRenderMonitor.onRenderStop(true);
    const fileOutputDir = (file) => {
      const format14 = file.format;
      return projectFormatOutputDir(
        format14,
        project,
        projectType(project.config?.project?.[kProjectType])
      );
    };
    result2.files.forEach((resultFile) => {
      const file = isAbsolute4(resultFile.file) ? resultFile.file : join4(fileOutputDir(resultFile), resultFile.file);
      const inputFile = isAbsolute4(resultFile.input) ? resultFile.input : join4(project.dir, resultFile.input);
      this.fileRenders_.set(
        file,
        this.fileRenderHash(
          file,
          inputFile,
          extensionDirs,
          resourceFiles,
          project
        )
      );
    });
  }
  fileRenderHash(file, inputFile, extensionDirs, resourceFiles, project) {
    const resourceHash = [
      file,
      inputFile,
      ...resourceFiles,
      ...extensionFilesFromDirs(extensionDirs),
      ...project.files.config || [],
      ...project.files.configResources || [],
      ...project.files.resources || []
    ].reduce((hash, file2) => {
      try {
        return hash + Deno.statSync(file2).mtime?.toUTCString();
      } catch {
        return hash;
      }
    }, "");
    if (isJupyterNotebook(inputFile) || !isHtmlContent(file)) {
      return String(Deno.statSync(file).mtime) + String(Deno.statSync(inputFile).mtime) + resourceHash;
    } else {
      return md5HashSync(Deno.readTextFileSync(file)) + md5HashSync(Deno.readTextFileSync(inputFile)) + resourceHash;
    }
  }
  fileRenders_ = /* @__PURE__ */ new Map();
  renderQueue_ = new PromiseQueue();
};

// project/serve/serve.ts
init_project_scratch();
init_quarto();
init_cleanup();
await init_extension();
init_port();
init_port_consts();

// core/http-server.ts
function handleHttpRequests(options) {
  const abortController = new AbortController();
  const server = Deno.serve({ ...options, signal: abortController.signal });
  return {
    server,
    stop: () => {
      abortController.abort();
    }
  };
}

// project/serve/serve.ts
init_file();
init_manuscript_types();

// preview/preview-server.ts
init_mod4();
init_platform();
function noPreviewServer() {
  return Promise.resolve({
    start: () => Promise.resolve(void 0),
    serve: () => {
      return new Promise(() => {
      });
    },
    stop: () => {
      return Promise.resolve();
    }
  });
}
function runExternalPreviewServer(options) {
  const { cmd } = options;
  const denoCommand = new Deno.Command(cmd[0], {
    args: cmd.slice(1),
    ...options,
    stdout: "piped",
    stderr: "piped"
  });
  const process4 = denoCommand.spawn();
  const multiplexIterator = new MuxAsyncIterator();
  multiplexIterator.add(process4.stdout);
  multiplexIterator.add(process4.stderr);
  const decoder3 = new TextDecoder();
  return {
    start: async () => {
      for await (const chunk of multiplexIterator) {
        const text = decoder3.decode(chunk);
        if (options.readyPattern.test(text)) {
          break;
        }
        Deno.stderr.writeSync(chunk);
      }
      return "";
    },
    serve: async () => {
      for await (const chunk of multiplexIterator) {
        Deno.stderr.writeSync(chunk);
      }
      await process4.output();
    },
    stop: () => {
      if (!isWindows4) {
        Deno.kill(-process4.pid, "SIGTERM");
      } else {
        process4.kill();
      }
      return Promise.resolve();
    }
  };
}

// project/serve/serve.ts
init_platform();
var kRenderNone = "none";
var kRenderDefault = "default";
async function serveProject(target, renderOptions, pandocArgs, options, noServe) {
  let project;
  let flags = renderOptions.flags;
  const nbContext = renderOptions.services.notebook;
  if (typeof target === "string") {
    if (target === ".") {
      target = Deno.cwd();
    }
    project = await projectContext(
      target,
      nbContext,
      renderOptions
    );
    if (!project || !project?.config) {
      throw new Error(`${target} is not a project`);
    }
    const isMdFormat = (mdFormat, format14) => {
      if (!format14) {
        return false;
      }
      if (typeof format14 === "string") {
        return format14 === mdFormat;
      } else if (typeof format14 === "object") {
        const formats2 = Object.keys(format14);
        if (formats2.length > 0) {
          const firstFormat = Object.keys(format14)[0];
          return firstFormat === mdFormat;
        } else {
          return false;
        }
      } else {
        return false;
      }
    };
    const projType = projectType(project?.config?.project?.[kProjectType]);
    if (projType.type === "default" && !isMdFormat("docusaurus-md", project?.config?.format) && !isMdFormat("hugo-md", project?.config?.format)) {
      const hasIndex = project.files.input.some((file) => {
        let relPath = file;
        if (project) {
          relPath = relative4(project.dir, file);
        }
        const [dir, stem] = dirAndStem(relPath);
        return dir === "." && stem === "index";
      });
      if (!hasIndex && options.browser !== false) {
        throw new Error(
          `The project '${project.config.project.title || ""}' is a default type project which doesn't support project wide previewing unless there is an 'index' file present.

Please preview an individual file within this project instead.`
        );
      }
    }
  } else {
    project = target;
  }
  acquirePreviewLock(project);
  previewMonitorResources();
  clearProjectIndex(project.dir);
  Deno.env.set("QUARTO_PROJECT_DIR", project.dir);
  options = {
    ...options,
    ...await resolvePreviewOptions(options, project)
  };
  const renderBefore = options.render !== kRenderNone;
  if (renderBefore) {
    renderProgress("Rendering:");
  } else {
    renderProgress("Preparing to preview");
  }
  flags = {
    ...flags,
    ...renderBefore && options.render !== kRenderDefault ? { to: options.render } : {}
  };
  if (flags.to === void 0) {
    flags.to = kRenderDefault;
  }
  const pdfOutput = isPdfOutput(flags.to || "");
  const services = renderServices(nbContext);
  let files;
  let resourceFiles = [];
  if (!renderBefore) {
    if (pdfOutput) {
      files = project.files.input;
    } else {
      const srvFiles = await serveFiles(project);
      files = srvFiles.files;
      resourceFiles = srvFiles.resourceFiles;
    }
  }
  let renderResult;
  try {
    renderResult = await renderProject(
      project,
      {
        services,
        progress: true,
        useFreezer: !renderBefore,
        flags,
        pandocArgs,
        previewServer: true
      },
      files
    );
  } finally {
    services.cleanup();
  }
  if (renderResult.error) {
    throw renderResult.error;
  }
  resourceFiles.push(...uniq(
    renderResult.files.flatMap((file) => file.resourceFiles)
  ));
  const extensionDirs = projectExtensionDirs(project);
  const renderManager = new ServeRenderManager();
  renderManager.onRenderResult(
    renderResult,
    extensionDirs,
    resourceFiles,
    project
  );
  let stopServer = () => {
  };
  const watcher = await watchProject(
    project,
    extensionDirs,
    resourceFiles,
    { ...renderOptions, flags },
    pandocArgs,
    options,
    !pdfOutput,
    // we don't render on reload for pdf output
    renderManager,
    stopServer
  );
  printWatchingForChangesMessage();
  const serve2 = noServe ? false : projectPreviewServe(project) || true;
  const previewServer = serve2 === false ? await noPreviewServer() : serve2 === true ? await internalPreviewServer(
    project,
    renderResult,
    renderManager,
    pdfOutput,
    watcher,
    extensionDirs,
    resourceFiles,
    flags,
    pandocArgs,
    options
  ) : await externalPreviewServer(
    project,
    serve2,
    options,
    renderManager,
    watcher,
    extensionDirs,
    resourceFiles,
    flags,
    pandocArgs
  );
  stopServer = previewServer.stop;
  const path3 = await previewServer.start();
  if (path3 !== void 0) {
    printBrowsePreviewMessage(
      options.host,
      options.port,
      path3
    );
    if (options.browser && !isServerSession()) {
      await openUrl(previewURL(options.host, options.port, path3));
    }
  }
  onCleanup(stopServer);
  if (options.touchPath) {
    await touch(options.touchPath);
  }
  await previewServer.serve();
}
function externalPreviewServer(project, serve2, options, renderManager, watcher, extensionDirs, resourceFiles, flags, pandocArgs) {
  let stop;
  if (renderToken()) {
    const outputDir = projectOutputDir(project);
    const handlerOptions = {
      //  base dir
      baseDir: outputDir,
      // handle websocket upgrade and render requests
      onRequest: previewControlChannelRequestHandler(
        project,
        renderManager,
        watcher,
        extensionDirs,
        resourceFiles,
        flags,
        pandocArgs,
        false
      )
    };
    const handler = httpFileRequestHandler(handlerOptions);
    const port = findOpenPort();
    ({ stop } = handleHttpRequests({
      port,
      hostname: kLocalhost,
      handler
    }));
    info(`Preview service running (${port})`);
  }
  const cmd = serve2.cmd.split(/[\t ]/).map((arg, index2) => {
    if (isWindows4 && index2 === 0 && arg === "npm") {
      return "npm.cmd";
    } else if (arg === "{host}") {
      return options.host || kLocalhost;
    } else if (arg === "{port}") {
      return String(options.port);
    } else {
      return arg;
    }
  });
  if (serve2.args) {
    cmd.push(...serve2.args);
  }
  const readyPattern = new RegExp(serve2.ready);
  const server = runExternalPreviewServer({
    cmd,
    readyPattern,
    env: serve2.env,
    cwd: projectOutputDir(project)
  });
  return Promise.resolve({
    start: async () => {
      return server.start();
    },
    serve: async () => {
      return server.serve();
    },
    stop: () => {
      stop?.();
      return server.stop();
    }
  });
}
async function internalPreviewServer(project, renderResult, renderManager, pdfOutput, watcher, extensionDirs, resourceFiles, flags, pandocArgs, options) {
  const projType = projectType(project?.config?.project?.[kProjectType]);
  const outputDir = projectOutputDir(project);
  const finalOutput = renderResultFinalOutput(renderResult);
  const pdfOutputFile = finalOutput && pdfOutput ? () => {
    const project2 = watcher.project();
    if (projType.type == kManuscriptType) {
      return finalOutput;
    } else {
      const outputFile5 = join4(
        dirname4(finalOutput),
        bookOutputStem(project2.dir, project2.config) + ".pdf"
      );
      return outputFile5;
    }
  } : void 0;
  const handlerOptions = {
    //  base dir
    baseDir: outputDir,
    // print all urls
    printUrls: "all",
    // handle websocket upgrade and render requests
    onRequest: previewControlChannelRequestHandler(
      project,
      renderManager,
      watcher,
      extensionDirs,
      resourceFiles,
      flags,
      pandocArgs,
      isBrowserPreviewable(finalOutput)
    ),
    // handle html file requests w/ re-renders
    onFile: async (file, req) => {
      const baseDir = projectOutputDir(project);
      const staticResponse = await staticResource(baseDir, file);
      if (staticResponse) {
        const resolveBody = () => {
          if (staticResponse.injectClient) {
            const contents = new TextDecoder().decode(staticResponse.contents);
            return staticResponse.injectClient(
              contents,
              watcher.clientHtml(req)
            );
          } else {
            return staticResponse.contents;
          }
        };
        const body = resolveBody();
        const response = {
          body,
          contentType: staticResponse.contentType
        };
        return response;
      } else if (isHtmlContent(file) || isPdfContent(file) || isDocxContent(file) || isTextContent(file)) {
        const serveDir = projectOutputDir(watcher.project());
        const filePathRelative = relative4(serveDir, file);
        let inputFile = await inputFileForOutputFile(
          watcher.project(),
          filePathRelative
        );
        if (!inputFile) {
          const fileSourcePath = join4(watcher.project().dir, filePathRelative);
          const projectResourceFiles2 = watcher.project().files.resources;
          if (projectResourceFiles2?.includes(fileSourcePath)) {
            return void 0;
          }
        }
        if (!inputFile || !existsSync2(inputFile.file)) {
          inputFile = await inputFileForOutputFile(
            await watcher.refreshProject(),
            filePathRelative
          );
        }
        let result2;
        let renderError;
        if (inputFile) {
          if (renderManager.fileRequiresReRender(
            file,
            inputFile.file,
            extensionDirs,
            resourceFiles,
            watcher.project()
          )) {
            const renderFlags = { ...flags, quiet: true };
            const renderPandocArgs = projType.projectFormatsOnly ? pandocArgs : removePandocToArg(pandocArgs);
            if (!projType.projectFormatsOnly) {
              delete renderFlags?.to;
            }
            if (renderFlags?.to == "all") {
              renderFlags.to = isHtmlContent(file) ? "html" : "pdf";
            }
            if (projType.incrementalFormatPreviewing) {
              renderFlags.to = inputFile.format.identifier[kTargetFormat];
              delete renderFlags?.clean;
            }
            const services = renderServices(notebookContext());
            try {
              result2 = await renderManager.submitRender(
                () => renderProject(
                  watcher.project(),
                  {
                    services,
                    useFreezer: true,
                    devServerReload: true,
                    previewServer: true,
                    flags: renderFlags,
                    pandocArgs: renderPandocArgs
                  },
                  [inputFile.file]
                )
              );
              if (result2.error) {
                renderManager.onRenderError(result2.error);
                renderError = result2.error;
              } else {
                renderManager.onRenderResult(
                  result2,
                  extensionDirs,
                  resourceFiles,
                  project
                );
              }
            } catch (e5) {
              if (!(e5 instanceof Error)) throw e5;
              logError(e5);
              renderError = e5;
            } finally {
              services.cleanup();
            }
          }
        }
        const fileContents = renderError ? renderErrorPage(renderError) : Deno.readFileSync(file);
        if (isHtmlContent(file) && inputFile) {
          const projInputFile = join4(
            project.dir,
            relative4(watcher.project().dir, inputFile.file)
          );
          return watcher.injectClient(
            req,
            fileContents,
            projInputFile
          );
        } else if (isTextContent(file) && inputFile) {
          return previewTextContent(
            file,
            inputFile.file,
            inputFile.format,
            req,
            watcher.injectClient
          );
        } else {
          return { contentType: contentType(file), body: fileContents };
        }
      } else {
        return void 0;
      }
    },
    // handle 404 by returing site custom 404 page
    on404: (url, req) => {
      const print = !basename4(url).startsWith("jupyter-");
      let body = new TextEncoder().encode("Not Found");
      const custom404 = join4(outputDir, kProject404File);
      if (existsSync2(custom404)) {
        let content404 = Deno.readTextFileSync(custom404);
        const sitePath = websitePath(project?.config);
        if (sitePath !== "/" || isRStudioServer()) {
          let replacePath = "/";
          const referer = req.headers.get("referer");
          if (isRStudioServer() && referer) {
            const match = referer.match(/\/p\/.*?\//);
            if (match) {
              replacePath = match[0];
            }
          }
          content404 = content404.replaceAll(
            new RegExp('((?:content|ref|src)=")(' + sitePath + ")", "g"),
            "$1" + replacePath
          );
        }
        body = new TextEncoder().encode(content404);
      }
      return {
        print,
        response: watcher.injectClient(req, body)
      };
    }
  };
  if (finalOutput && pdfOutput) {
    handlerOptions.baseDir = pdfJsBaseDir();
    handlerOptions.onFile = pdfJsFileHandler(
      pdfOutputFile,
      async (file, req) => {
        if (isHtmlContent(file)) {
          const fileContents = await Deno.readFile(file);
          return watcher.injectClient(req, fileContents);
        } else {
          return void 0;
        }
      }
    );
  }
  const handler = httpFileRequestHandler(handlerOptions);
  let browserPath = options.browserPath ? options.browserPath.replace(/^\//, "") : void 0;
  if (browserPath) {
    const browserPathTarget = await resolveInputTarget(
      project,
      browserPath,
      false
    );
    if (browserPathTarget) {
      browserPath = browserPathTarget.outputHref;
    }
  }
  const targetPath = browserPath ? browserPath : pdfOutput ? kPdfJsInitialPath : renderResultUrlPath(renderResult);
  const path3 = targetPath && targetPath !== "index.html" ? targetPath : "";
  let stop;
  return {
    start: () => Promise.resolve(path3),
    serve: async () => {
      const { server, stop: stopServer } = handleHttpRequests({
        port: options.port,
        hostname: options.host,
        handler
      });
      stop = stopServer;
      await server.finished;
    },
    stop: () => {
      stop?.();
      return Promise.resolve();
    }
  };
}
function previewControlChannelRequestHandler(project, renderManager, watcher, extensionDirs, resourceFiles, flags, pandocArgs, requireActiveClient) {
  return async (req) => {
    if (watcher.handle(req)) {
      return await watcher.request(req);
    } else if (isPreviewTerminateRequest(req)) {
      exitWithCleanup(0);
    } else if (isPreviewRenderRequest(req)) {
      const prevReq = previewRenderRequest(
        req,
        requireActiveClient ? watcher.hasClients() : true,
        project.dir
      );
      if (prevReq && await previewRenderRequestIsCompatible(prevReq, project, flags.to)) {
        if (isProjectInputFile(prevReq.path, project)) {
          const services = renderServices(notebookContext());
          const to = flags.to === "all" ? prevReq.format || "html" : flags.to;
          renderManager.submitRender(
            () => render(prevReq.path, {
              services,
              flags: { ...flags, to },
              pandocArgs,
              previewServer: true
            })
          ).then((result2) => {
            if (result2.error) {
              result2.context.cleanup();
              renderManager.onRenderError(result2.error);
            } else {
              const finalOutput = renderResultFinalOutput(
                result2,
                dirname4(prevReq.path)
              );
              if (!finalOutput) {
                throw new Error(
                  "No output created by quarto render " + basename4(prevReq.path)
                );
              }
              renderManager.onRenderResult(
                result2,
                extensionDirs,
                resourceFiles,
                watcher.project()
              );
              result2.context.cleanup();
              info("Output created: " + finalOutput + "\n");
              printWatchingForChangesMessage();
              watcher.reloadClients(
                true,
                !isPdfContent(finalOutput) ? join4(dirname4(prevReq.path), finalOutput) : void 0
              );
            }
          }).finally(() => {
            services.cleanup();
          });
          return httpContentResponse("rendered");
        } else if (extname4(prevReq.path) === ".md" && projectPreviewServe(project)) {
          return httpContentResponse("rendered");
        } else {
          return previewUnableToRenderResponse();
        }
      } else {
        return previewUnableToRenderResponse();
      }
    } else {
      return void 0;
    }
  };
}
function sleepSync(timeout) {
  const sab = new SharedArrayBuffer(1024);
  const int32 = new Int32Array(sab);
  Atomics.wait(int32, 0, 0, timeout);
}
function acquirePreviewLock(project) {
  const lockfile = previewLockFile(project);
  if (existsSync2(lockfile)) {
    const pid2 = parseInt(Deno.readTextFileSync(lockfile)) || void 0;
    if (pid2) {
      info(
        bold3(blue3("Terminating existing preview server....")),
        { newline: false }
      );
      try {
        Deno.kill(pid2, "SIGTERM");
        sleepSync(3e3);
      } catch {
      } finally {
        info(bold3(blue3("DONE\n")));
      }
    }
  }
  Deno.writeTextFileSync(lockfile, String(Deno.pid));
  onCleanup(() => releasePreviewLock(project));
}
function releasePreviewLock(project) {
  try {
    safeRemoveSync(previewLockFile(project));
  } catch {
  }
}
function previewLockFile(project) {
  return projectScratchPath(project.dir, join4("preview", "lock"));
}
function renderErrorPage(e5) {
  const content = `
<!doctype html>
<html lang=en>
<head>
<meta charset=utf-8>
<title>Quarto Render Error</title>
<script id="quarto-render-error" type="text/plain">${e5.message}<\/script>
</head>
<body>
</body>
</html>
`;
  return new TextEncoder().encode(content);
}
async function serveFiles(project) {
  const projType = projectType(project.config?.project?.[kProjectType]);
  await initDenoDom();
  const files = [];
  const resourceFiles = [];
  for (let i6 = 0; i6 < project.files.input.length; i6++) {
    const inputFile = project.files.input[i6];
    const projRelative = relative4(project.dir, inputFile);
    const target = await resolveInputTarget(project, projRelative, false);
    if (target) {
      const outputFile5 = join4(projectOutputDir(project), target?.outputHref);
      if (isModifiedAfter(inputFile, outputFile5) || projType.previewSkipUnmodified === false) {
        files.push(inputFile);
      } else {
        const outputResources = [];
        if (isHtmlContent(outputFile5)) {
          const htmlInput = Deno.readTextFileSync(outputFile5);
          const doc = new DOMParser().parseFromString(htmlInput, "text/html");
          const resolver = htmlResourceResolverPostprocessor(
            inputFile,
            project
          );
          outputResources.push(...(await resolver(doc)).resources);
        }
        const partitioned = await partitionedMarkdownForInput(
          project,
          projRelative
        );
        const globs = [];
        if (partitioned?.yaml) {
          const metadata = partitioned.yaml;
          globs.push(...resourcesFromMetadata(metadata[kResources]));
        }
        resourceFiles.push(
          ...await resourceFilesFromFile(
            project.dir,
            projectExcludeDirs(project),
            projRelative,
            { files: outputResources, globs },
            false,
            // selfContained,
            [join4(dirname4(projRelative), inputFilesDir(projRelative))],
            partitioned
          )
        );
      }
    } else {
      warn("Unabled to resolve output target for " + inputFile);
    }
  }
  return { files, resourceFiles: uniq(resourceFiles) };
}

// command/preview/cmd.ts
init_types4();
await init_project_context();
await init_project_shared();
init_format5();
await init_render_services();
init_pandoc_formats();
init_path2();
init_constants6();
init_log();
await init_render_contexts();
init_render();

// command/preview/preview-shiny.ts
init_log();
init_path();
init_cleanup();
init_http();
init_port();
init_path2();
init_quarto();
await init_render_services();
async function previewShiny(options) {
  previewMonitorResources();
  let rendering = false;
  const renderingFile = isAbsolute4(options.input) ? options.input : join4(Deno.cwd(), options.input);
  const render2 = async (to) => {
    to = to || options.format;
    const renderFlags = { to, execute: true };
    const services = renderServices(notebookContext());
    try {
      rendering = true;
      const result3 = await renderForPreview(
        options.input,
        services,
        renderFlags,
        options.pandocArgs,
        options.project
      );
      return result3;
    } finally {
      services.cleanup();
      rendering = false;
    }
  };
  const result2 = await render2();
  const changeHandler = createChangeHandler(
    // result to kick off change handling
    result2,
    // render for reload, but provide a reload filter that prevents
    // rendering for files that shiny will auto-reload on and on
    // the .html file that we generate
    {
      reloadClients: async () => {
        await render2();
      }
    },
    // delegate to render
    render2,
    // watch .qmd if requested
    options.watchInputs,
    // filter files that shiny will reload on
    (file) => {
      const ext = extname4(file);
      return ![".py", ".html", ".htm"].includes(ext);
    },
    (files) => {
      if (files.length === 1 && files[0] === renderingFile && extname4(files[0]) === ".ipynb") {
        return rendering;
      }
      return false;
    }
  );
  if (renderToken()) {
    runPreviewControlService(options, changeHandler.render);
  }
  return await serve({ ...options, render: false, reload: true });
}
function runPreviewControlService(options, renderHandler) {
  const isCompatibleRequest = async (prevReq) => {
    return normalizePath(options.input) === normalizePath(prevReq.path) && await previewRenderRequestIsCompatible(
      prevReq,
      options.project,
      options.format
    );
  };
  const baseDir = dirname4(options.input);
  const handlerOptions = {
    baseDir,
    onRequest: async (req) => {
      if (isPreviewTerminateRequest(req)) {
        exitWithCleanup(0);
      } else if (isPreviewRenderRequest(req)) {
        const prevReq = previewRenderRequest(req, true, baseDir);
        if (prevReq && await isCompatibleRequest(prevReq)) {
          renderHandler();
          return httpContentResponse("rendered");
        } else {
          return previewUnableToRenderResponse();
        }
      } else {
        return void 0;
      }
    }
  };
  const handler = httpFileRequestHandler(handlerOptions);
  const port = findOpenPort();
  onCleanup(handleHttpRequests({ ...handlerOptions, handler }).stop);
  info(`Preview service running (${port})`);
}

// command/preview/cmd.ts
await init_engine();
init_cleanup();
var previewCommand = new Command().name("preview").stopEarly().option(
  "--port [port:number]",
  "Suggested port to listen on (defaults to random value between 3000 and 8000).\nIf the port is not available then a random port between 3000 and 8000 will be selected."
).option(
  "--host [host:string]",
  "Hostname to bind to (defaults to 127.0.0.1)"
).option(
  "--render [format:string]",
  "Render to the specified format(s) before previewing",
  {
    default: kRenderNone
  }
).option(
  "--no-serve",
  "Don't run a local preview web server (just monitor and re-render input files)"
).option(
  "--no-navigate",
  "Don't navigate the browser automatically when outputs are updated."
).option(
  "--no-browser",
  "Don't open a browser to preview the site."
).option(
  "--no-watch-inputs",
  "Do not re-render input files when they change."
).option(
  "--timeout",
  "Time (in seconds) after which to exit if there are no active clients."
).arguments("[file:string] [...args:string]").description(
  'Render and preview a document or website project.\n\nAutomatically reloads the browser when input files or document resources (e.g. CSS) change.\n\nFor website preview, the most recent execution results of computational documents are used to render\nthe site (this is to optimize startup time). If you want to perform a full render prior to\npreviewing pass the --render option with "all" or a comma-separated list of formats to render.\n\nFor document preview, input file changes will result in a re-render (pass --no-watch to prevent).\n\nYou can also include arbitrary command line arguments to be forwarded to ' + bold3("quarto render") + "."
).example(
  "Preview document",
  "quarto preview doc.qmd"
).example(
  "Preview document with render command line args",
  "quarto preview doc.qmd --toc"
).example(
  "Preview document (don't watch for input changes)",
  "quarto preview doc.qmd --no-watch-inputs"
).example(
  "Preview website with most recent execution results",
  "quarto preview"
).example(
  "Previewing website using a specific port",
  "quarto preview --port 4444"
).example(
  "Preview website (don't open a browser)",
  "quarto preview --no-browser"
).example(
  "Fully render all website/book formats then preview",
  "quarto preview --render all"
).example(
  "Fully render the html format then preview",
  "quarto preview --render html"
).action(async (options, file, ...args) => {
  setInitializer(initYamlIntelligenceResourcesFromFilesystem);
  await initState();
  if (!file || file === kCliffyImplicitCwd) {
    file = Deno.cwd();
    const firstArg = args.find(
      (arg) => arg.endsWith(".qmd") || arg.endsWith(".ipynb")
    );
    if (firstArg) {
      warn(
        `\`quarto preview\` invoked with no input file specified (the parameter order matters).
Quarto will preview the current directory by default.
Did you mean to run \`quarto preview ${firstArg} ${args.filter((arg) => arg !== firstArg).join(" ")}\`?
Use \`quarto preview --help\` for more information.`
      );
    }
  }
  file = file || Deno.cwd();
  if (!existsSync2(file)) {
    throw new Error(`${file} not found`);
  }
  if (args.length > 0 && args[0] === "--help") {
    previewCommand.showHelp();
    return;
  }
  const portPos = args.indexOf("--port");
  if (portPos !== -1) {
    options.port = parseInt(args[portPos + 1]);
    args.splice(portPos, 2);
  }
  const hostPos = args.indexOf("--host");
  if (hostPos !== -1) {
    options.host = String(args[hostPos + 1]);
    args.splice(hostPos, 2);
  }
  const renderPos = args.indexOf("--render");
  if (renderPos !== -1) {
    options.render = String(args[renderPos + 1]);
    args.splice(renderPos, 2);
  }
  const presentationPos = args.indexOf("--presentation");
  if (presentationPos !== -1) {
    options.presentation = true;
    args.splice(presentationPos, 1);
  } else {
    options.presentation = false;
  }
  const browserPathPos = args.indexOf("--browser-path");
  if (browserPathPos !== -1) {
    options.browserPath = String(args[browserPathPos + 1]);
    args.splice(browserPathPos, 2);
  }
  const noServePos = args.indexOf("--no-serve");
  if (noServePos !== -1) {
    options.noServe = true;
    args.splice(noServePos, 1);
  }
  const noBrowsePos = args.indexOf("--no-browse");
  if (noBrowsePos !== -1) {
    options.browse = false;
    args.splice(noBrowsePos, 1);
  }
  const noBrowserPos = args.indexOf("--no-browser");
  if (noBrowserPos !== -1) {
    options.browser = false;
    args.splice(noBrowserPos, 1);
  }
  const navigatePos = args.indexOf("--navigate");
  if (navigatePos !== -1) {
    options.navigate = true;
    args.splice(navigatePos, 1);
  }
  const noNavigatePos = args.indexOf("--no-navigate");
  if (noNavigatePos !== -1) {
    options.navigate = false;
    args.splice(noNavigatePos, 1);
  }
  const watchInputsPos = args.indexOf("--watch-inputs");
  if (watchInputsPos !== -1) {
    options.watchInputs = true;
    args.splice(watchInputsPos, 1);
  }
  const noWatchInputsPos = args.indexOf("--no-watch-inputs");
  if (noWatchInputsPos !== -1) {
    options.watchInputs = false;
    args.splice(noWatchInputsPos, 1);
  }
  const timeoutPos = args.indexOf("--timeout");
  if (timeoutPos !== -1) {
    options.timeout = parseInt(args[timeoutPos + 1]);
    args.splice(timeoutPos, 2);
  }
  const noWatchPos = args.indexOf("--no-watch");
  if (noWatchPos !== -1) {
    options.watchInputs = false;
    args.splice(noWatchPos, 1);
  }
  const noRenderPos = args.indexOf("--no-render");
  if (noRenderPos !== -1) {
    options.watchInputs = false;
    args.splice(noRenderPos, 1);
  }
  if (options.port) {
    const port = parseInt(options.port);
    if (await waitForPort({ port, hostname: kLocalhost })) {
      options.port = port;
    } else {
      throw new Error(`Requested port ${options.port} is already in use.`);
    }
  }
  const flags = await parseRenderFlags(args);
  args = fixupPandocArgs(args, flags);
  let touchPath;
  let projectTarget = file;
  let project;
  if (Deno.statSync(file).isFile) {
    const nbContext = notebookContext();
    project = await projectContext(dirname4(file), nbContext) || await singleFileProjectContext(file, nbContext);
    const formats2 = await (async () => {
      const services = renderServices(nbContext);
      try {
        return await renderFormats(
          file,
          services,
          void 0,
          project
        );
      } finally {
        services.cleanup();
      }
    })();
    const format14 = await previewFormat(file, project, flags.to, formats2);
    if (isHtmlOutput(parseFormatString(format14).baseFormat)) {
      const renderFormat = formats2[format14];
      if (renderFormat && isServerShiny(renderFormat)) {
        const engine = await fileExecutionEngine(file, flags, project);
        setPreviewFormat(format14, flags, args);
        if (isServerShinyPython(renderFormat, engine?.name)) {
          const result2 = await previewShiny({
            input: file,
            render: !!options.render,
            port: typeof options.port === "string" ? parseInt(options.port) : options.port,
            host: options.host,
            browser: options.browser,
            projectDir: project?.dir,
            tempDir: Deno.makeTempDirSync(),
            format: format14,
            pandocArgs: args,
            watchInputs: options.watchInputs,
            project
          });
          exitWithCleanup(result2.code);
          throw new Error();
        } else {
          const result2 = await serve({
            input: file,
            render: !!options.render,
            port: typeof options.port === "string" ? parseInt(options.port) : options.port,
            host: options.host,
            format: format14,
            browser: options.browser,
            projectDir: project?.dir,
            tempDir: Deno.makeTempDirSync()
          });
          exitWithCleanup(result2.code);
          throw new Error();
        }
      }
    }
    if (project && projectIsServeable(project)) {
      const filePath = normalizePath(file);
      if (!project.files.input.includes(filePath)) {
        if (extname4(file) === ".md" && projectPreviewServe(project)) {
          setPreviewFormat(format14, flags, args);
          touchPath = filePath;
          options.browserPath = "";
          file = project.dir;
          projectTarget = project;
        }
      } else {
        if (isHtmlOutput(parseFormatString(format14).baseFormat, true) || projectPreviewServe(project)) {
          setPreviewFormat(format14, flags, args);
          const services = renderServices(notebookContext());
          try {
            const renderResult = await renderProject(project, {
              services,
              progress: false,
              useFreezer: false,
              flags,
              pandocArgs: args,
              previewServer: true
            }, [file]);
            if (renderResult.error) {
              throw renderResult.error;
            }
            handleRenderResult(file, renderResult);
            if (projectPreviewServe(project) && renderResult.baseDir) {
              touchPath = join4(
                renderResult.baseDir,
                renderResult.files[0].file
              );
            }
          } finally {
            services.cleanup();
          }
          if (projectPreviewServe(project)) {
            options.browserPath = "";
          } else {
            options.browserPath = relative4(project.dir, file);
          }
          file = project.dir;
          projectTarget = project;
        }
      }
    }
  }
  if (Deno.statSync(file).isDirectory) {
    const renderOptions = {
      services: renderServices(notebookContext()),
      flags
    };
    await serveProject(projectTarget, renderOptions, args, {
      port: options.port,
      host: options.host,
      browser: options.browser === false || options.browse === false ? false : void 0,
      [kProjectWatchInputs]: options.watchInputs,
      timeout: options.timeout,
      render: options.render,
      touchPath,
      browserPath: options.browserPath,
      navigate: options.navigate
    }, options.noServe === true);
  } else {
    if (options.render !== kRenderNone && options.render !== kRenderDefault && args.indexOf("--to") === -1) {
      args.push("--to", options.render);
    }
    await preview(relative4(Deno.cwd(), file), flags, args, {
      port: options.port,
      host: options.host,
      browser: options.browser === false || options.browse === false ? false : void 0,
      [kProjectWatchInputs]: options.watchInputs,
      timeout: options.timeout,
      presentation: options.presentation
    }, project);
  }
});

// command/convert/cmd.ts
init_fs();
init_path();
init_log();
init_jupyter();
init_path2();

// command/convert/jupyter.ts
init_yaml();
init_yaml();
init_constants6();
init_jupyter();
init_partition_cell_options();
init_kernels();
init_jupyter_fixups();
init_jupyter_shared();
init_asserts();
init_text();
async function markdownToJupyterNotebook(file, includeIds) {
  const markdown = Deno.readTextFileSync(file);
  const notebook = await quartoMdToJupyter(markdown, includeIds);
  return JSON.stringify(notebook, null, 2);
}
async function jupyterNotebookToMarkdown(file, includeIds) {
  const notebook = fixupFrontMatter(jupyterFromFile(file));
  let kernelspec = notebook.metadata.kernelspec;
  if (kernelspec.language === void 0 && notebook.metadata.language_info?.name) {
    kernelspec = {
      ...kernelspec,
      language: notebook.metadata.language_info?.name
    };
  }
  if (kernelspec.language === void 0) {
    throw new Error(
      "No language found in kernelspec for notebook " + file
    );
  }
  const md = [];
  let frontMatter;
  for (let i6 = 0; i6 < notebook.cells.length; i6++) {
    {
      const cell = notebook.cells[i6];
      const cellWithOptions = jupyterCellWithOptions(
        i6,
        kernelspec.language,
        cell
      );
      const endingNewLineCount = getEndingNewlineCount(md);
      if (i6 > 0 && endingNewLineCount < 2) {
        md.push("\n\n");
      }
      switch (cell.cell_type) {
        case "markdown":
          md.push(...mdFromContentCell(cellWithOptions));
          break;
        case "raw":
          if (frontMatter === void 0) {
            const { yaml: cellYaml, markdown: cellMarkdown } = partitionYamlFrontMatter(
              jupyterCellSrcAsStr(cell)
            ) || {};
            if (cellYaml) {
              frontMatter = cellYaml;
            }
            if (cellMarkdown) {
              md.push(cellMarkdown);
            }
          } else {
            md.push(...mdFromRawCell(cellWithOptions));
          }
          break;
        case "code":
          md.push(
            ...await mdFromCodeCell2(
              kernelspec.language.toLowerCase(),
              cell,
              includeIds
            )
          );
          break;
        default:
          throw new Error("Unexpected cell type " + cell.cell_type);
      }
      if (i6 > 0 || !frontMatter) {
        md.push("\n");
      }
    }
  }
  const mdSource = md.join("");
  const yaml = frontMatter ? readYamlFromMarkdown(frontMatter) : {};
  yaml.jupyter = notebook.metadata.jupytext ? {
    jupytext: notebook.metadata.jupytext,
    kernelspec: notebook.metadata.kernelspec
  } : notebook.metadata.kernelspec.name;
  if (typeof yaml.jupyter === "string") {
    if (!await jupyterKernelspec(yaml.jupyter)) {
      yaml.jupyter = {
        kernelspec: notebook.metadata.kernelspec
      };
    }
  }
  assert7(frontMatter || !mdSource.match(/^\n\n/));
  const maybeYamlMdBreak = frontMatter ? "" : "\n\n";
  const yamlText = stringify(yaml, {
    indent: 2,
    lineWidth: -1,
    sortKeys: false,
    skipInvalid: true
  });
  return `---
${yamlText}---${maybeYamlMdBreak}${mdSource}`;
}
async function mdFromCodeCell2(language, cell, includeIds) {
  if (!cell.source.length) {
    return [];
  }
  const maxBackticks = Math.max(
    ...jupyterCellSrcAsLines(cell).map(
      (line) => line.match(/^`+/g)?.[0].length || 0
    ),
    2
  );
  const backticks = "`".repeat(maxBackticks + 1);
  const md = [backticks + "{" + language + "}\n"];
  const { yaml, source: source2 } = await partitionCellOptions(
    language,
    jupyterCellSrcAsLines(cell)
  );
  const options = yaml ? yaml : {};
  if (!includeIds) {
    delete cell.id;
    delete cell.metadata["id"];
    delete cell.metadata["outputId"];
  } else {
    if (cell.id) {
      if (options[kCellLabel]) {
        const label = String(options[kCellLabel]);
        if (jupyterAutoIdentifier(label) === cell.id) {
          cell.id = void 0;
        }
      }
    }
  }
  let yamlOptions = {};
  if (cell.id) {
    yamlOptions[kCellId] = cell.id;
  }
  yamlOptions = {
    ...cell.metadata,
    ...yaml,
    ...yamlOptions
  };
  if (yamlOptions[kCellId]) {
    md.push(
      ...jupyterCellOptionsAsComment(language, { id: yamlOptions[kCellId] })
    );
    delete yamlOptions[kCellId];
  }
  if (yaml) {
    const yamlOutput = {};
    for (const key in yaml) {
      const value = yamlOptions[key];
      if (value !== void 0) {
        yamlOutput[key] = value;
        delete yamlOptions[key];
      }
    }
    md.push(...jupyterCellOptionsAsComment(language, yamlOutput));
  }
  const metadataOutput = {};
  for (const key in cell.metadata) {
    const value = cell.metadata[key];
    if (value !== void 0) {
      metadataOutput[key] = value;
      delete yamlOptions[key];
    }
  }
  md.push(
    ...jupyterCellOptionsAsComment(language, metadataOutput, { flowLevel: 1 })
  );
  md.push(...mdEnsureTrailingNewline(source2));
  md.push(backticks + "\n");
  return md;
}

// command/convert/cmd.ts
var kNotebookFormat = "notebook";
var kMarkdownFormat = "markdown";
var convertCommand = new Command().name("convert").arguments("<input:string>").description(
  "Convert documents to alternate representations."
).option(
  "-o, --output [path:string]",
  "Write output to PATH."
).option(
  "--with-ids",
  "Include ids in conversion"
).example(
  "Convert notebook to markdown",
  "quarto convert mydocument.ipynb "
).example(
  "Convert markdown to notebook",
  "quarto convert mydocument.qmd"
).example(
  "Convert notebook to markdown, writing to file",
  "quarto convert mydocument.ipynb --output mydoc.qmd"
).action(async (options, input) => {
  await initYamlIntelligenceResourcesFromFilesystem();
  if (!existsSync2(input)) {
    throw new Error(`File not found: '${input}'`);
  }
  const srcFormat = isJupyterNotebook(input) ? kNotebookFormat : kMarkdownFormat;
  const withIds = options.withIds === void 0 ? false : !!options.withIds;
  const converted = srcFormat === kNotebookFormat ? await jupyterNotebookToMarkdown(input, withIds) : await markdownToJupyterNotebook(input, withIds);
  const [dir, stem] = dirAndStem(input);
  let output = options.output;
  if (!output) {
    output = join4(
      dir,
      stem + (srcFormat === kMarkdownFormat ? ".ipynb" : ".qmd")
    );
  }
  Deno.writeTextFileSync(output, converted);
  info(`Converted to ${output}`);
});

// command/run/run.ts
init_fs();
init_log();
init_cleanup();
async function runScript(args, env2) {
  let dev = false;
  let scriptArgs = args;
  if (args[0] === "--dev") {
    dev = true;
    scriptArgs = args.slice(1);
  }
  const script = scriptArgs[0];
  if (!script) {
    error("quarto run: no script specified");
    exitWithCleanup(1);
    throw new Error();
  }
  if (!existsSync2(script)) {
    error("quarto run: script '" + script + "' not found");
    exitWithCleanup(1);
    throw new Error();
  }
  const handler = await handlerForScript(script);
  if (!handler) {
    error("quarto run: no handler found for script '" + script + "'");
    exitWithCleanup(1);
    throw new Error();
  }
  return await handler.run(script, scriptArgs.slice(1), void 0, {
    env: env2,
    dev
  });
}
var runCommand = new Command().name("run").stopEarly().arguments("[script:string] [...args]").description(
  "Run a TypeScript, R, Python, or Lua script.\n\nRun a utility script written in a variety of languages. For details, see:\nhttps://quarto.org/docs/projects/scripts.html#periodic-scripts"
).option("--dev", "Use development import map (when running from source)", {
  hidden: true
});

// command/pandoc/cmd.ts
var pandocCommand = new Command().name("pandoc").stopEarly().arguments("[...args]").description(
  "Run the version of Pandoc embedded within Quarto.\n\nYou can pass arbitrary command line arguments to quarto pandoc (they will\nbe passed through unmodified to Pandoc)"
).example(
  "Render markdown to HTML",
  "quarto pandoc document.md --to html --output document.html"
).example(
  "List Pandoc output formats",
  "quarto pandoc --list-output-formats"
);

// command/typst/cmd.ts
var typstCommand = new Command().name("typst").stopEarly().arguments("[...args]").description(
  "Run the version of Typst embedded within Quarto.\n\nYou can pass arbitrary command line arguments to quarto typst (they will\nbe passed through unmodified to Typst)"
).example(
  "Compile Typst to PDF",
  "quarto typst compile document.typ"
).example(
  "List all discovered fonts in system and custom font paths",
  "quarto typst fonts"
);

// command/capabilities/cmd.ts
init_write_all();

// command/capabilities/capabilities.ts
init_path();
init_lodash();
init_resources2();
init_pandoc_formats();
init_capabilities();
init_kernels();
async function capabilities() {
  const caps = {
    formats: await formats(),
    themes: await themes(),
    python: await jupyterCapabilities()
  };
  if (caps.python) {
    const pythonEx = caps.python;
    if (pythonEx.jupyter_core) {
      pythonEx.kernels = Array.from((await jupyterKernelspecs()).values());
    }
    pythonEx.venv = !pythonEx.conda;
  }
  return caps;
}
async function formats() {
  const formats2 = await pandocListFormats();
  const commonFormats = [
    "html",
    "pdf",
    "docx",
    "odt",
    "pptx",
    "beamer",
    "revealjs",
    "gfm",
    "epub",
    "dashboard",
    "email"
  ];
  const excludedFormats = [
    "bibtex",
    "biblatex",
    "csljson"
  ];
  return difference(
    commonFormats.concat(difference(formats2, commonFormats)),
    excludedFormats
  );
}
async function themes() {
  const themesPath = formatResourcePath("html", join4("bootstrap", "themes"));
  const themes2 = ["default"];
  const kScss = ".scss";
  for await (const dirEntry of Deno.readDir(themesPath)) {
    if (dirEntry.isFile && dirEntry.name.endsWith(kScss)) {
      themes2.push(basename4(dirEntry.name, kScss));
    }
  }
  return themes2;
}

// command/capabilities/cmd.ts
var capabilitiesCommand = new Command().name("capabilities").description(
  "Query for current capabilities (formats, engines, kernels etc.)"
).hidden().action(async () => {
  const capsJSON = JSON.stringify(await capabilities(), void 0, 2);
  writeAllSync(
    Deno.stdout,
    new TextEncoder().encode(capsJSON)
  );
});

// command/check/check.ts
init_log();
await init_render_services();
init_quarto();
init_windows();
init_process();
init_resources2();
init_text2();
init_mod6();
init_dart_sass();
init_path2();
init_path();
init_appdirs();
init_platform();

// typing/dynamic.ts
init_error2();
var makeStringEnumTypeFunctions = (...values) => {
  const valueSet = new Set(values);
  const predicate = (value) => {
    return typeof value === "string" && valueSet.has(value);
  };
  const enforce = (value) => {
    if (predicate(value)) {
      return value;
    }
    throw new DynamicTypeCheckError(
      "Invalid value '" + value + "' (valid values are " + values.join(", ") + ")."
    );
  };
  return { predicate, enforce };
};
var makeStringEnumTypeEnforcer = (...values) => {
  return makeStringEnumTypeFunctions(...values).enforce;
};

// command/check/check.ts
await init_puppeteer();
await init_engine();
function getTargets() {
  const checkableEngineNames = executionEngines().filter((engine) => engine.checkInstallation).map((engine) => engine.name);
  return ["install", "info", ...checkableEngineNames, "versions", "all"];
}
function enforceTargetType(value) {
  const targets = getTargets();
  return makeStringEnumTypeEnforcer(...targets)(value);
}
var kIndent = "      ";
function checkCompleteMessage(conf, message) {
  if (!conf.jsonResult) {
    completeMessage(message);
  }
}
function checkInfoMsg(conf, message) {
  if (!conf.jsonResult) {
    info(message);
  }
}
async function check(target, strict, output) {
  const services = renderServices(notebookContext());
  const conf = {
    strict: !!strict,
    target,
    output,
    services,
    jsonResult: void 0
  };
  if (conf.output) {
    conf.jsonResult = {
      strict
    };
  }
  try {
    if (conf.jsonResult) {
      conf.jsonResult.version = quartoConfig.version();
    }
    checkInfoMsg(conf, `Quarto ${quartoConfig.version()}`);
    for (const [name2, checker] of [
      ["info", checkInfo],
      ["versions", checkVersions],
      ["install", checkInstall]
    ]) {
      if (target === name2 || target === "all") {
        await checker(conf);
      }
    }
    for (const engine of executionEngines()) {
      if (engine.checkInstallation && (target === engine.name || target === "all")) {
        await engine.checkInstallation(conf);
      }
    }
    if (conf.jsonResult && conf.output) {
      await Deno.writeTextFile(
        conf.output,
        JSON.stringify(conf.jsonResult, null, 2)
      );
    }
  } finally {
    services.cleanup();
  }
}
async function checkInfo(conf) {
  const cacheDir = quartoCacheDir();
  if (conf.jsonResult) {
    conf.jsonResult.info = { cacheDir };
  }
  checkCompleteMessage(conf, "Checking environment information...");
  checkInfoMsg(conf, kIndent + "Quarto cache location: " + cacheDir);
}
async function checkVersions(conf) {
  const {
    strict
  } = conf;
  const checkVersion3 = (version4, constraint, name2) => {
    if (typeof version4 !== "string") {
      throw new Error(`Unable to determine ${name2} version`);
    }
    const good = satisfies(version4, constraint);
    if (conf.jsonResult) {
      if (conf.jsonResult.dependencies === void 0) {
        conf.jsonResult.dependencies = {};
      }
      conf.jsonResult.dependencies[name2] = {
        version: version4,
        constraint,
        satisfies: good
      };
    }
    if (!good) {
      checkInfoMsg(
        conf,
        `      NOTE: ${name2} version ${version4} is too old. Please upgrade to ${constraint.slice(2)} or later.`
      );
    } else {
      checkInfoMsg(conf, `      ${name2} version ${version4}: OK`);
    }
  };
  const strictCheckVersion = (version4, constraint, name2) => {
    const good = version4 === constraint;
    if (conf.jsonResult) {
      if (conf.jsonResult.dependencies === void 0) {
        conf.jsonResult.dependencies = {};
      }
      conf.jsonResult.dependencies[name2] = {
        version: version4,
        constraint,
        satisfies: good
      };
    }
    if (!good) {
      checkInfoMsg(
        conf,
        `      NOTE: ${name2} version ${version4} does not strictly match ${constraint} and strict checking is enabled. Please use ${constraint}.`
      );
    } else {
      checkInfoMsg(conf, `      ${name2} version ${version4}: OK`);
    }
  };
  checkCompleteMessage(
    conf,
    "Checking versions of quarto binary dependencies..."
  );
  let pandocVersion = lines(
    (await execProcess({
      cmd: pandocBinaryPath(),
      args: ["--version"],
      stdout: "piped"
    })).stdout
  )[0]?.split(" ")[1];
  const sassVersion = (await dartCommand(["--version"]))?.trim();
  const denoVersion = Deno.version.deno;
  const typstVersion2 = lines(
    (await execProcess({
      cmd: typstBinaryPath(),
      args: ["--version"],
      stdout: "piped"
    })).stdout
  )[0].split(" ")[1];
  if (pandocVersion) {
    const versionParts = pandocVersion.split(".");
    if (versionParts.length > 3) {
      pandocVersion = versionParts.slice(0, 3).join(".");
    } else if (versionParts.length < 3) {
      pandocVersion = versionParts.concat(
        Array(3 - versionParts.length).fill("0")
      ).join(".");
    }
  }
  const versionConstraints = [
    [pandocVersion, "3.8.3", "Pandoc"],
    [sassVersion, "1.87.0", "Dart Sass"],
    [denoVersion, "2.4.5", "Deno"],
    [typstVersion2, "0.14.2", "Typst"]
  ];
  const checkData = versionConstraints.map(([version4, ver, name2]) => [
    version4,
    strict ? ver : `>=${ver}`,
    name2
  ]);
  const fun = strict ? strictCheckVersion : checkVersion3;
  for (const [version4, constraint, name2] of checkData) {
    if (version4 === void 0) {
      if (conf.jsonResult) {
        if (conf.jsonResult.dependencies === void 0) {
          conf.jsonResult.dependencies = {};
        }
        conf.jsonResult.dependencies[name2] = {
          version: version4,
          constraint,
          found: false
        };
      }
      checkInfoMsg(conf, `      ${name2} version: (not detected)`);
    } else {
      fun(version4, constraint, name2);
    }
  }
  checkCompleteMessage(
    conf,
    "Checking versions of quarto dependencies......OK"
  );
}
async function checkInstall(conf) {
  const {
    services
  } = conf;
  checkCompleteMessage(conf, "Checking Quarto installation......OK");
  checkInfoMsg(conf, `${kIndent}Version: ${quartoConfig.version()}`);
  if (quartoConfig.version() === "99.9.9") {
    const quartoRoot = Deno.env.get("QUARTO_ROOT");
    if (quartoRoot) {
      const gitHead = await execProcess({
        cmd: "git",
        args: ["-C", quartoRoot, "rev-parse", "HEAD"],
        stdout: "piped",
        stderr: "piped"
        // to not show error if not in a git repo
      });
      if (gitHead.success && gitHead.stdout) {
        checkInfoMsg(conf, `${kIndent}commit: ${gitHead.stdout.trim()}`);
        if (conf.jsonResult) {
          conf.jsonResult["quarto-dev-version"] = gitHead.stdout.trim();
        }
      }
    }
  }
  checkInfoMsg(conf, `${kIndent}Path: ${quartoConfig.binPath()}`);
  if (conf.jsonResult) {
    conf.jsonResult["quarto-path"] = quartoConfig.binPath();
  }
  if (isWindows4) {
    const json3 = {};
    if (conf.jsonResult) {
      conf.jsonResult.windows = json3;
    }
    try {
      const codePage = readCodePage();
      clearCodePageCache();
      await cacheCodePage();
      const codePage2 = readCodePage();
      checkInfoMsg(conf, `${kIndent}CodePage: ${codePage2 || "unknown"}`);
      json3["code-page"] = codePage2 || "unknown";
      if (codePage && codePage !== codePage2) {
        checkInfoMsg(
          conf,
          `${kIndent}NOTE: Code page updated from ${codePage} to ${codePage2}. Previous rendering may have been affected.`
        );
        json3["code-page-updated-from"] = codePage;
      }
      const nonAscii = /[^\x00-\x7F]+/;
      if (nonAscii.test(quartoConfig.binPath())) {
        checkInfoMsg(
          conf,
          `${kIndent}ERROR: Non-ASCII characters in Quarto path causes rendering problems.`
        );
        json3["non-ascii-in-path"] = true;
      }
    } catch {
      checkInfoMsg(conf, `${kIndent}CodePage: Unable to read code page`);
      json3["error"] = "Unable to read code page";
    }
  }
  checkInfoMsg(conf, "");
  const toolsMessage = "Checking tools....................";
  const toolsOutput = [];
  let tools;
  const toolsJson = {};
  if (conf.jsonResult) {
    conf.jsonResult.tools = toolsJson;
  }
  const toolsCb = async () => {
    tools = await allTools();
    for (const tool of tools.installed) {
      const version4 = await tool.installedVersion() || "(external install)";
      toolsOutput.push(`${kIndent}${tool.name}: ${version4}`);
      toolsJson[tool.name] = {
        version: version4
      };
      if (tool.name === "Chromium (deprecated)") {
        toolsOutput.push(
          `${kIndent}      (Run "quarto install chrome-headless-shell" to replace)`
        );
      }
    }
    for (const tool of tools.notInstalled) {
      toolsOutput.push(`${kIndent}${tool.name}: (not installed)`);
      toolsJson[tool.name] = {
        installed: false
      };
    }
  };
  if (conf.jsonResult) {
    await toolsCb();
  } else {
    await withSpinner({
      message: toolsMessage,
      doneMessage: toolsMessage + "OK"
    }, toolsCb);
  }
  toolsOutput.forEach((out) => checkInfoMsg(conf, out));
  checkInfoMsg(conf, "");
  const latexMessage = "Checking LaTeX....................";
  const latexOutput = [];
  const latexJson = {};
  if (conf.jsonResult) {
    conf.jsonResult.latex = latexJson;
  }
  const latexCb = async () => {
    const tlContext = await texLiveContext(true);
    if (tlContext.hasTexLive) {
      const version4 = await tlVersion(tlContext);
      if (tlContext.usingGlobal) {
        const tlMgrPath = await which("tlmgr");
        latexOutput.push(`${kIndent}Using: Installation From Path`);
        if (tlMgrPath) {
          latexOutput.push(`${kIndent}Path: ${dirname4(tlMgrPath)}`);
          latexJson["path"] = dirname4(tlMgrPath);
          latexJson["source"] = "global";
        }
      } else {
        latexOutput.push(`${kIndent}Using: TinyTex`);
        if (tlContext.binDir) {
          latexOutput.push(`${kIndent}Path: ${tlContext.binDir}`);
          latexJson["path"] = tlContext.binDir;
          latexJson["source"] = "tinytex";
        }
      }
      latexOutput.push(`${kIndent}Version: ${version4}`);
      latexJson["version"] = version4;
    } else {
      latexOutput.push(`${kIndent}Tex:  (not detected)`);
      latexJson["installed"] = false;
    }
  };
  if (conf.jsonResult) {
    await latexCb();
  } else {
    await withSpinner({
      message: latexMessage,
      doneMessage: latexMessage + "OK"
    }, latexCb);
  }
  latexOutput.forEach((out) => checkInfoMsg(conf, out));
  checkInfoMsg(conf, "");
  const chromeHeadlessMessage = "Checking Chrome Headless....................";
  const chromeHeadlessOutput = [];
  const chromeJson = {};
  if (conf.jsonResult) {
    conf.jsonResult.chrome = chromeJson;
  }
  const chromeCb = async () => {
    const check2 = await detectChromeForCheck();
    if (check2.warning) {
      chromeHeadlessOutput.push(`${kIndent}NOTE: ${check2.warning}`);
      chromeJson["warning"] = check2.warning;
    }
    if (check2.detected) {
      const { label, path: path3, source: source2, displaySource, version: version4 } = check2.detected;
      chromeHeadlessOutput.push(`${kIndent}Using: ${label}`);
      if (path3) {
        chromeHeadlessOutput.push(`${kIndent}Path: ${path3}`);
        chromeJson["path"] = path3;
      }
      chromeJson["source"] = source2;
      if (displaySource) {
        chromeHeadlessOutput.push(`${kIndent}Source: ${displaySource}`);
      }
      if (version4) {
        chromeHeadlessOutput.push(`${kIndent}Version: ${version4}`);
        chromeJson["version"] = version4;
      }
    } else {
      chromeHeadlessOutput.push(`${kIndent}Chrome:  (not detected)`);
      chromeJson["installed"] = false;
    }
  };
  if (conf.jsonResult) {
    await chromeCb();
  } else {
    await withSpinner({
      message: chromeHeadlessMessage,
      doneMessage: chromeHeadlessMessage + "OK"
    }, chromeCb);
  }
  chromeHeadlessOutput.forEach((out) => checkInfoMsg(conf, out));
  checkInfoMsg(conf, "");
  const kMessage = "Checking basic markdown render....";
  const markdownRenderJson = {};
  if (conf.jsonResult) {
    conf.jsonResult.render = {
      markdown: markdownRenderJson
    };
  }
  const markdownRenderCb = async () => {
    const mdPath = services.temp.createFile({ suffix: "check.md" });
    Deno.writeTextFileSync(
      mdPath,
      `
---
title: "Title"
---

## Header
`
    );
    const result2 = await render(mdPath, {
      services,
      flags: { quiet: true }
    });
    if (result2.error) {
      if (!conf.jsonResult) {
        throw result2.error;
      } else {
        markdownRenderJson["error"] = result2.error;
      }
    } else {
      markdownRenderJson["ok"] = true;
    }
  };
  if (conf.jsonResult) {
    await markdownRenderCb();
  } else {
    await withSpinner({
      message: kMessage,
      doneMessage: kMessage + "OK\n"
    }, markdownRenderCb);
  }
}
async function detectChromeForCheck() {
  const detection = await detectBrowser();
  if (detection.detected) {
    return { detected: detection.detected };
  }
  const result2 = {};
  if (detection.warning) {
    result2.warning = detection.warning;
  }
  const chromiumTool = installableTool("chromium");
  if (chromiumTool && await chromiumTool.installed()) {
    let path3;
    if (chromiumTool.binDir) {
      path3 = await chromiumTool.binDir();
    }
    const version4 = await chromiumTool.installedVersion();
    result2.detected = {
      label: "Chromium installed by Quarto",
      path: path3,
      source: "quarto",
      version: version4
    };
  }
  return result2;
}

// command/check/cmd.ts
var checkCommand = new Command().name("check").option("--output <path>", "Output as JSON to a file").option(
  "--no-strict",
  "When set, will not fail if dependency versions don't match precisely"
).arguments("[target:string]").description(
  "Verify correct functioning of Quarto installation.\n\nCheck specific functionality with argument install, jupyter, knitr, or all."
).example("Check Quarto installation", "quarto check install").example("Check Jupyter engine", "quarto check jupyter").example("Check Knitr engine", "quarto check knitr").example("Check installation and all engines", "quarto check all").action(async (options, targetStr) => {
  targetStr = targetStr || "all";
  await initializeProjectContextAndEngines();
  const target = enforceTargetType(targetStr);
  await check(
    target,
    options.strict,
    options.output
  );
});

// inspect/inspect.ts
init_fs();
init_path();
init_lodash();
init_constants6();
await init_project_context();
await init_engine();
await init_render_contexts();
init_quarto();
init_css();
await init_project_shared();
init_path2();
init_constants12();
await init_extension();
await init_render_services();
init_log();
function isDocumentConfig(config2) {
  return config2.formats !== void 0;
}
async function inspectConfig(path3) {
  path3 = path3 || Deno.cwd();
  if (!existsSync2(path3)) {
    throw new Error(`${path3} not found`);
  }
  const stat = Deno.statSync(path3);
  if (stat.isDirectory) {
    const nbContext = notebookContext();
    const ctx = await projectContext(path3, nbContext);
    if (!ctx) {
      throw new Error(`${path3} is not a Quarto project.`);
    }
    const config2 = await withProjectCleanup(ctx, inspectProjectConfig);
    if (!config2) {
      throw new Error(`${path3} is not a Quarto project.`);
    }
    return config2;
  } else {
    return await inspectDocumentConfig(path3);
  }
}
var inspectProjectConfig = async (context) => {
  if (!context.config) {
    return void 0;
  }
  const fileInformation = {};
  for (const file of context.files.input) {
    await populateFileInformation(context, fileInformation, file);
  }
  const extensions2 = await populateExtensionInformation(context);
  const config2 = {
    quarto: {
      version: quartoConfig.version()
    },
    dir: context.dir,
    engines: context.engines,
    config: context.config,
    files: context.files,
    fileInformation,
    extensions: extensions2
  };
  return config2;
};
var populateExtensionInformation = async (context) => {
  const extensionContext = createExtensionContext();
  return await extensionContext.extensions(
    context.dir,
    context.config,
    context.dir,
    { builtIn: false }
  );
};
var populateFileInformation = async (context, fileInformation, file) => {
  const engine = await fileExecutionEngine(file, void 0, context);
  const src2 = await context.resolveFullMarkdownForFile(engine, file);
  if (engine) {
    const errors2 = await validateDocumentFromSource(
      src2,
      engine.name,
      error
    );
    if (errors2.length) {
      throw new Error(`${file} is not a valid Quarto input document`);
    }
  }
  await projectResolveCodeCellsForFile(context, engine, file);
  await projectFileMetadata(context, file);
  const cacheEntry = context.fileInformationCache.get(file);
  const outputKey = relative4(context.dir, normalizePath(file));
  fileInformation[outputKey] = {
    includeMap: cacheEntry?.includeMap ?? [],
    codeCells: cacheEntry?.codeCells ?? [],
    metadata: cacheEntry?.metadata ?? {}
  };
};
var inspectDocumentConfig = async (path3) => {
  const nbContext = notebookContext();
  const project = await projectContext(path3, nbContext) || await singleFileProjectContext(path3, nbContext);
  return withProjectCleanup(project, async (project2) => {
    const engine = await fileExecutionEngine(path3, void 0, project2);
    if (!engine) {
      throw new Error(`${path3} is not a valid Quarto input document`);
    }
    const partitioned = await engine.partitionedMarkdown(path3);
    const context = project2;
    const src2 = await context.resolveFullMarkdownForFile(engine, path3);
    if (engine) {
      const errors2 = await validateDocumentFromSource(
        src2,
        engine.name,
        error
      );
      if (errors2.length) {
        throw new Error(`${path3} is not a valid Quarto input document`);
      }
    }
    const formats2 = await withRenderServices(
      nbContext,
      (services) => renderFormats(path3, services, "all", context)
    );
    const resourceConfig = Object.values(formats2).reduce(
      (resources2, format14) => {
        resources2 = uniq(resources2.concat(
          resourcesFromMetadata(format14.metadata[kResources])
        ));
        if (format14.pandoc[kCss]) {
          return uniq(resources2.concat(
            resourcesFromMetadata(format14.pandoc[kCss])
          ));
        } else {
          return resources2;
        }
      },
      []
    );
    const fileDir = normalizePath(dirname4(path3));
    const excludeDirs = context ? projectExcludeDirs(context) : [];
    const resources = await resolveResources(
      context ? context.dir : fileDir,
      fileDir,
      excludeDirs,
      partitioned.markdown,
      resourceConfig
    );
    const extensions2 = join4(fileDir, kExtensionDir);
    if (safeExistsSync(extensions2)) {
      resources.push(
        ...extensionFilesFromDirs([extensions2]).map(
          (file) => relative4(fileDir, file)
        )
      );
    }
    await context.resolveFullMarkdownForFile(engine, path3);
    await projectResolveCodeCellsForFile(context, engine, path3);
    await projectFileMetadata(context, path3);
    const fileInformation = context.fileInformationCache.get(path3);
    const config2 = {
      quarto: {
        version: quartoConfig.version()
      },
      engines: [engine.name],
      formats: formats2,
      resources,
      fileInformation: {
        [path3]: {
          includeMap: fileInformation?.includeMap ?? [],
          codeCells: fileInformation?.codeCells ?? [],
          metadata: fileInformation?.metadata ?? {}
        }
      }
    };
    if (context?.config && !(context.isSingleFile && isRStudio())) {
      config2.project = await inspectProjectConfig(context);
    }
    return config2;
  });
};
async function resolveResources(rootDir, fileDir, excludeDirs, markdown, globs) {
  const resolved = await resolveFileResources(
    rootDir,
    fileDir,
    excludeDirs,
    markdown,
    globs
  );
  const resources = difference(
    resolved.include,
    resolved.exclude
  );
  const allResources = resources.concat(cssFileResourceReferences(resources));
  return allResources.map((file) => relative4(rootDir, file));
}

// command/inspect/cmd.ts
var inspectCommand = new Command().name("inspect").arguments("[path] [output]").description(
  "Inspect a Quarto project or input path.\n\nInspecting a project returns its config and engines.\nInspecting an input path return its formats, engine, and dependent resources.\n\nEmits results of inspection as JSON to output (or stdout if not provided)."
).hidden().example(
  "Inspect project in current directory",
  "quarto inspect"
).example(
  "Inspect project in directory",
  "quarto inspect myproject"
).example(
  "Inspect input path",
  "quarto inspect document.md"
).example(
  "Inspect input path and write to file",
  "quarto inspect document.md output.json"
).action(
  async (_options, path3, output) => {
    setInitializer(initYamlIntelligenceResourcesFromFilesystem);
    await initState();
    path3 = path3 || Deno.cwd();
    const config2 = await inspectConfig(path3);
    const outputJson = JSON.stringify(config2, void 0, 2);
    if (!output) {
      Deno.stdout.writeSync(
        new TextEncoder().encode(outputJson + "\n")
      );
    } else {
      Deno.writeTextFileSync(output, outputJson + "\n");
    }
  }
);

// command/install/cmd.ts
init_temp();

// extension/install.ts
init_fs();
init_path();
await init_project_context();
init_zip();
init_copy5();
init_constants12();
await init_extension();
init_log();

// extension/extension-host.ts
init_fs();
init_platform();
async function extensionSource(target) {
  if (!target.match(/^https?:\/\/.*$/) && existsSync2(target)) {
    return { type: "local", resolvedTarget: target };
  }
  for (const resolver of extensionHostResolvers) {
    const resolved = resolver(target);
    if (!resolved) {
      continue;
    }
    try {
      const response = await resolved.response;
      if (response.status === 200) {
        return {
          type: "remote",
          resolvedTarget: response,
          resolvedFile: resolved?.urlFile,
          owner: resolved?.owner,
          targetSubdir: resolved?.subdirectory,
          learnMoreUrl: resolved?.learnMoreUrl
        };
      }
    } catch (err2) {
      if (!(err2 instanceof Error)) {
        throw err2;
      }
      err2.message = `A network error occurred when attempting to inspect the extension '${target}'. Please try again.

` + err2.message;
      throw err2;
    }
  }
  return void 0;
}
var archiveExt = isWindows4 ? ".zip" : ".tar.gz";
var githubLatestUrlProvider = {
  extensionUrl: (host) => {
    if (host.modifier === void 0 || host.modifier === "latest") {
      return `https://github.com/${host.organization}/${host.repo}/archive/refs/heads/main${archiveExt}`;
    }
  },
  archiveSubdir: (host) => {
    const baseDir = `${host.repo}-main`;
    if (host.subdirectory) {
      return baseDir + "/" + host.subdirectory;
    } else {
      return baseDir;
    }
  },
  learnMoreUrl: (host) => {
    return `https://www.github.com/${host.organization}/${host.repo}#readme`;
  }
};
var githubTagUrlProvider = {
  extensionUrl: (host) => {
    if (host.modifier) {
      return `https://github.com/${host.organization}/${host.repo}/archive/refs/tags/${host.modifier}${archiveExt}`;
    }
  },
  archiveSubdir: (host) => {
    const baseDir = `${host.repo}-${tagSubDirectory(host.modifier)}`;
    if (host.subdirectory) {
      return baseDir + "/" + host.subdirectory;
    } else {
      return baseDir;
    }
  },
  learnMoreUrl: (host) => {
    return `https://github.com/${host.organization}/${host.repo}/tree/${host.modifier}#readme`;
  }
};
var githubBranchUrlProvider = {
  extensionUrl: (host) => {
    if (host.modifier) {
      return `https://github.com/${host.organization}/${host.repo}/archive/refs/heads/${host.modifier}${archiveExt}`;
    }
  },
  archiveSubdir: (host) => {
    const baseDir = `${host.repo}-${host.modifier}`;
    if (host.subdirectory) {
      return baseDir + "/" + host.subdirectory;
    } else {
      return baseDir;
    }
  },
  learnMoreUrl: (host) => {
    return `https://github.com/${host.organization}/${host.repo}/tree/${host.modifier}#readme`;
  }
};
var kGithubExtensionSource = {
  parse: (name2) => {
    const match = name2.match(kGithubExtensionNameRegex);
    if (match) {
      return {
        name: name2,
        organization: match[1],
        repo: match[2],
        subdirectory: match[3],
        modifier: match[4]
      };
    } else {
      return void 0;
    }
  },
  urlProviders: [
    githubLatestUrlProvider,
    githubTagUrlProvider,
    githubBranchUrlProvider
  ]
};
var kGithubExtensionNameRegex = /^([a-zA-Z0-9-_\.]*?)\/([a-zA-Z0-9-_\.]*?)(?:\/(.*?)\/?)?(?:@([a-zA-Z0-9-_\.\/]*))?$/;
var kGithubArchiveUrlSource = {
  parse: (name2) => {
    const match = name2.match(kGithubArchiveUrlRegex);
    if (match) {
      return {
        name: name2,
        organization: match[1],
        repo: match[2],
        subdirectory: void 0,
        // Subdirectories aren't support for archive urls
        modifier: match[3]
      };
    } else {
      return void 0;
    }
  },
  urlProviders: [
    {
      extensionUrl: (host) => host.name,
      archiveSubdir: (host) => {
        return `${host.repo}-${tagSubDirectory(host.modifier)}`;
      },
      learnMoreUrl: (host) => `https://www.github.com/${host.organization}/${host.repo}`
    }
  ]
};
var kGithubArchiveUrlRegex = /https?\:\/\/github.com\/([a-zA-Z0-9-_\.]+?)\/([a-zA-Z0-9-_\.]+?)\/archive\/refs\/(?:tags|heads)\/(.+)(?:\.tar\.gz|\.zip)$/;
function tagSubDirectory(tag) {
  if (tag) {
    return tag.startsWith("v") ? tag.slice(1) : tag;
  } else {
    return tag;
  }
}
function makeResolvers(source2) {
  return source2.urlProviders.map((urlProvider) => {
    return (name2) => {
      const host = source2.parse(name2);
      if (!host) {
        return void 0;
      }
      const url = urlProvider.extensionUrl(host);
      if (url) {
        return {
          url,
          urlFile: url.split("/").pop(),
          response: fetch(url),
          owner: host.organization,
          subdirectory: urlProvider.archiveSubdir(host),
          learnMoreUrl: urlProvider.learnMoreUrl(host)
        };
      } else {
        return void 0;
      }
    };
  });
}
var kGithubResolvers = [
  ...makeResolvers(kGithubExtensionSource),
  ...makeResolvers(kGithubArchiveUrlSource)
];
var unknownUrlResolver = (name2) => {
  try {
    new URL(name2);
  } catch {
    return void 0;
  }
  return {
    url: name2,
    response: fetch(name2)
  };
};
var extensionHostResolvers = [
  ...kGithubResolvers,
  unknownUrlResolver
];

// extension/install.ts
init_path2();
init_error2();
var kUnversionedFrom = "  (?)";
var kUnversionedTo = "(?)  ";
async function installExtension(target, temp, allowPrompt, embed) {
  const source2 = await extensionSource(target);
  if (!source2) {
    info(
      `Extension not found in local or remote sources`
    );
    return false;
  }
  const trusted = await isTrusted(source2, allowPrompt);
  if (!trusted) {
    cancelInstallation();
    return false;
  }
  const currentDir = Deno.cwd();
  const installDir4 = await determineInstallDir(
    currentDir,
    allowPrompt,
    embed
  );
  const extensionDir2 = await stageExtension(source2, temp.createDir());
  const stagedExtensions = await validateExtension2(extensionDir2);
  const confirmed = await confirmInstallation(
    stagedExtensions,
    installDir4,
    { allowPrompt }
  );
  if (!confirmed) {
    cancelInstallation();
    return false;
  }
  await completeInstallation(extensionDir2, installDir4);
  await withSpinner(
    { message: "Extension installation complete" },
    () => {
      return Promise.resolve();
    }
  );
  if (source2.learnMoreUrl) {
    info("");
    if (allowPrompt) {
      const open = await Confirm.prompt({
        message: "View documentation using default browser?",
        default: true
      });
      if (open) {
        await openUrl(source2.learnMoreUrl);
      }
    } else {
      info(
        `
Learn more about this extension at:
${source2.learnMoreUrl}
`
      );
    }
  }
  return true;
}
function cancelInstallation() {
  info("Installation canceled\n");
}
async function isTrusted(source2, allowPrompt) {
  if (allowPrompt && source2.type === "remote") {
    const preamble = `
Quarto extensions may execute code when documents are rendered. If you do not 
trust the authors of the extension, we recommend that you do not install or 
use the extension.`;
    info(preamble);
    const question = "Do you trust the authors of this extension";
    const confirmed = await Confirm.prompt({
      message: question,
      default: true
    });
    return confirmed;
  } else {
    return true;
  }
}
async function determineInstallDir(dir, allowPrompt, embed) {
  if (embed) {
    const extensionName = embed;
    const context = createExtensionContext();
    const extension = await context.extension(extensionName, dir);
    if (extension) {
      if (Object.keys(extension?.contributes.formats || {}).length > 0) {
        return extension?.path;
      } else {
        throw new Error(
          `The extension ${embed} does not contribute a format.
You can only embed extensions within an extension which itself contributes a format.`
        );
      }
    } else {
      throw new Error(
        `Unable to locate the extension '${embed}' that you'd like to embed this within.`
      );
    }
  } else {
    const nbContext = notebookContext();
    const project = await projectContext(dir, nbContext);
    if (project && project.dir !== dir) {
      const question = "Install extension into project?";
      if (allowPrompt) {
        const useProject = await Confirm.prompt(question);
        if (useProject) {
          return project.dir;
        } else {
          return dir;
        }
      } else {
        return dir;
      }
    } else {
      return dir;
    }
  }
}
async function stageExtension(source2, workingDir) {
  if (source2.type === "remote") {
    const archiveDir = join4(workingDir, "archive");
    ensureDirSync(archiveDir);
    const filename = (typeof source2.resolvedTarget === "string" ? source2.resolvedTarget : source2.resolvedFile) || "extension.zip";
    const toFile = join4(archiveDir, filename);
    await downloadWithProgress(source2.resolvedTarget, `Downloading`, toFile);
    return unzipAndStage(toFile, source2);
  } else {
    if (typeof source2.resolvedTarget !== "string") {
      throw new InternalError(
        "local resolved extension should always have a string target."
      );
    }
    if (Deno.statSync(source2.resolvedTarget).isDirectory) {
      const srcDir = extensionDir(source2.resolvedTarget);
      if (srcDir) {
        const destDir = join4(workingDir, kExtensionDir);
        await readAndCopyExtensions(srcDir, destDir);
      }
      return workingDir;
    } else {
      const filename = basename4(source2.resolvedTarget);
      const toFile = join4(workingDir, filename);
      copyTo(source2.resolvedTarget, toFile);
      return unzipAndStage(toFile, source2);
    }
  }
}
async function unzipAndStage(zipFile, source2) {
  await withSpinner(
    { message: "Unzipping" },
    async () => {
      const result2 = await unzip(zipFile);
      if (!result2.success) {
        throw new Error("Failed to unzip extension.\n" + result2.stderr);
      }
      await Deno.remove(zipFile);
      return Promise.resolve();
    }
  );
  const archiveDir = dirname4(zipFile);
  const findExtensionDir2 = () => {
    if (source2.targetSubdir) {
      const subDirPath = join4(archiveDir, source2.targetSubdir);
      if (existsSync2(subDirPath)) {
        return subDirPath;
      }
    }
    if (safeExistsSync(join4(archiveDir, kExtensionDir))) {
      return archiveDir;
    } else {
      const dirEntries = Deno.readDirSync(archiveDir);
      let count = 0;
      let name2;
      for (const dirEntry of dirEntries) {
        if (dirEntry.isDirectory) {
          name2 = dirEntry.name;
          count++;
        }
      }
      if (count === 1 && name2 && name2 !== kExtensionDir) {
        if (safeExistsSync(join4(archiveDir, name2, kExtensionDir))) {
          return join4(archiveDir, name2);
        } else {
          return archiveDir;
        }
      } else {
        return archiveDir;
      }
    }
  };
  const extensionsDir = join4(findExtensionDir2(), kExtensionDir);
  const finalDir = join4(archiveDir, "staged");
  await copyExtensions(source2, extensionsDir, finalDir);
  return finalDir;
}
async function copyExtensions(source2, srcDir, targetDir) {
  const finalExtensionsDir = join4(targetDir, kExtensionDir);
  const finalExtensionTargetDir = source2.owner ? join4(finalExtensionsDir, source2.owner) : finalExtensionsDir;
  ensureDirSync(finalExtensionTargetDir);
  await readAndCopyExtensions(srcDir, finalExtensionTargetDir);
}
async function readAndCopyExtensions(extensionsDir, targetDir) {
  const extensions2 = await readExtensions(extensionsDir);
  info(
    `    Found ${extensions2.length} ${extensions2.length === 1 ? "extension" : "extensions"}.`
  );
  for (const extension of extensions2) {
    copyTo(
      extension.path,
      join4(targetDir, extension.id.name)
    );
  }
}
async function validateExtension2(path3) {
  const extensionsFolder = extensionDir(path3);
  if (!extensionsFolder) {
    throw new Error(
      `Invalid extension
The extension staged at ${path3} is missing an '_extensions' folder.`
    );
  }
  const extensions2 = await readExtensions(extensionsFolder);
  if (extensions2.length === 0) {
    throw new Error(
      `Invalid extension
The extension staged at ${path3} does not provide any valid extensions.`
    );
  }
  return extensions2;
}
async function confirmInstallation(extensions2, installDir4, options) {
  const readExisting = async () => {
    try {
      const existingExtensions2 = await readExtensions(
        join4(installDir4, kExtensionDir)
      );
      return existingExtensions2;
    } catch {
      return [];
    }
  };
  const name2 = (extension) => {
    const idStr = extension.id.organization ? `${extension.id.organization}/${extension.id.name}` : extension.id.name;
    return extension.title || idStr;
  };
  const existingExtensions = await readExisting();
  const existing = (extension) => {
    return existingExtensions.find((existing2) => {
      return existing2.id.name === extension.id.name && existing2.id.organization === extension.id.organization;
    });
  };
  if (existingExtensions.length > 0 && !options.allowPrompt && options.throw) {
    throw new Error(
      `There are extensions installed which would be overwritten. Aborting installation.
${existingExtensions.map((ext) => {
        return ext.title;
      }).join("\n - ")}`
    );
  }
  const typeStr = (to) => {
    const contributes = to.contributes;
    const extTypes = [];
    if (contributes.formats && Object.keys(contributes.formats).length > 0) {
      Object.keys(contributes.formats).length === 1 ? extTypes.push("format") : extTypes.push("formats");
    }
    if (contributes.shortcodes && contributes.shortcodes.length > 0) {
      contributes.shortcodes.length === 1 ? extTypes.push("shortcode") : extTypes.push("shortcodes");
    }
    if (contributes.filters && contributes.filters.length > 0) {
      contributes.filters.length === 1 ? extTypes.push("filter") : extTypes.push("filters");
    }
    if (extTypes.length > 0) {
      return `(${extTypes.join(",")})`;
    } else {
      return "";
    }
  };
  const versionMessage = (to, from) => {
    if (to && !from) {
      const versionStr = to.version?.format();
      return {
        action: "Install",
        from: "",
        to: versionStr
      };
    } else {
      if (to.version && from?.version) {
        const comparison = to.version.compare(from.version);
        if (comparison === 0) {
          return {
            action: "No Change",
            from: "",
            to: ""
          };
        } else if (comparison > 0) {
          return {
            action: "Update",
            from: from.version.format(),
            to: to.version.format()
          };
        } else {
          return {
            action: "Revert",
            from: from.version.format(),
            to: to.version.format()
          };
        }
      } else if (to.version && !from?.version) {
        return {
          action: "Update",
          from: kUnversionedFrom,
          to: to.version.format()
        };
      } else if (!to.version && from?.version) {
        return {
          action: "Update",
          from: from.version.format(),
          to: kUnversionedTo
        };
      } else {
        return {
          action: "Update",
          from: kUnversionedFrom,
          to: kUnversionedTo
        };
      }
    }
  };
  const extensionRows = [];
  for (const stagedExtension of extensions2) {
    const installedExtension = existing(stagedExtension);
    const message = versionMessage(
      stagedExtension,
      installedExtension
    );
    const types8 = typeStr(stagedExtension);
    if (message) {
      extensionRows.push([
        name2(stagedExtension) + "  ",
        `[${message.action}]`,
        message.from || "",
        message.to && message.from ? "->" : "",
        message.to || "",
        types8
      ]);
    }
  }
  if (extensionRows.length > 0) {
    const table = new Table(...extensionRows);
    info(
      `
${options.message || "The following changes will be made:"}
${table.toString()}`
    );
    const question = "Would you like to continue";
    return !options.allowPrompt || await Confirm.prompt({
      message: question,
      default: true
    });
  } else {
    info(`
No changes required - extensions already installed.`);
    return true;
  }
}
async function completeInstallation(downloadDir, installDir4) {
  info("");
  await withSpinner({
    message: `Copying`
  }, async () => {
    const stagingDir = join4(installDir4, "._extensions.staging");
    try {
      const downloadedExtDir = join4(downloadDir, kExtensionDir);
      const stagingExtDir = join4(stagingDir, kExtensionDir);
      ensureDirSync(stagingExtDir);
      const installExtDir = join4(installDir4, kExtensionDir);
      ensureDirSync(installExtDir);
      const extensions2 = await readExtensions(downloadedExtDir);
      extensions2.forEach((extension) => {
        const extensionRelativeDir = relative4(downloadedExtDir, extension.path);
        const stagingPath = join4(stagingExtDir, extensionRelativeDir);
        copyTo(extension.path, stagingPath);
        const installPath = join4(installExtDir, extensionRelativeDir);
        if (existsSync2(installPath)) {
          safeRemoveSync(installPath, { recursive: true });
        }
        ensureDirSync(dirname4(installPath));
        Deno.renameSync(stagingPath, installPath);
      });
    } finally {
      safeRemoveSync(stagingDir, { recursive: true });
    }
    return Promise.resolve();
  });
}
var extensionDir = (path3) => {
  if (basename4(path3) === kExtensionDir) {
    return path3;
  } else {
    const extDir = join4(path3, kExtensionDir);
    if (existsSync2(extDir) && Deno.statSync(extDir).isDirectory) {
      return extDir;
    } else {
      return path3;
    }
  }
};

// command/install/cmd.ts
init_log();

// command/remove/cmd.ts
init_temp();
init_log();

// extension/remove.ts
init_path();
init_path2();
init_constants12();
async function removeExtension(extension) {
  if (extension.id.organization === kBuiltInExtOrg) {
    throw new Error(
      `The extension ${extension.title} can't be removed since it is a built in extension.`
    );
  }
  await Deno.remove(extension.path, { recursive: true });
  const extensionDir2 = dirname4(extension.path);
  removeIfEmptyDir(extensionDir2);
  const parentDir = dirname4(extensionDir2);
  if (parentDir && basename4(parentDir) === kExtensionDir) {
    removeIfEmptyDir(parentDir);
  }
}

// command/remove/cmd.ts
await init_extension();
init_extension_shared();
await init_project_context();

// command/utils.ts
var someCommandFailed = false;
var signalCommandFailure = () => {
  someCommandFailed = true;
};
var commandFailed = () => {
  return someCommandFailed;
};

// command/remove/cmd.ts
var removeCommand = new Command().name("remove").arguments("[target...]").option(
  "--no-prompt",
  "Do not prompt to confirm actions"
).option(
  "--embed <extensionId>",
  "Remove this extension from within another extension (used when authoring extensions)."
).option(
  "--update-path",
  "Update system path when a tool is installed",
  {
    hidden: true
  }
).description(
  "Removes an extension."
).example(
  "Remove extension using name",
  "quarto remove <extension-name>"
).action(
  async (options, ...target) => {
    await initYamlIntelligenceResourcesFromFilesystem();
    const temp = createTempContext();
    const extensionContext = createExtensionContext();
    try {
      const resolved = resolveCompatibleArgs(target || [], "extension");
      if (resolved.action === "tool") {
        if (resolved.name) {
          await removeTool(resolved.name, options.prompt, options.updatePath);
        } else {
          const allTools2 = await loadTools();
          if (allTools2.filter((tool) => tool.installed).length === 0) {
            info("No tools are installed.");
            signalCommandFailure();
          } else {
            const toolTarget = await selectTool(allTools2, "remove");
            if (toolTarget) {
              info("");
              await removeTool(toolTarget);
            }
          }
        }
      } else {
        const workingDir = Deno.cwd();
        const resolveTargetDir = async () => {
          if (options.embed) {
            const context = createExtensionContext();
            const extension = await context.extension(
              options.embed,
              workingDir
            );
            if (extension) {
              return extension?.path;
            } else {
              throw new Error(`Unable to find extension '${options.embed}.`);
            }
          } else {
            return workingDir;
          }
        };
        const targetDir = await resolveTargetDir();
        if (resolved.name) {
          const extensions2 = await extensionContext.find(
            resolved.name,
            targetDir,
            void 0,
            void 0,
            void 0,
            { builtIn: false }
          );
          if (extensions2.length > 0) {
            await removeExtensions(extensions2.slice(), options.prompt);
          } else {
            info("No matching extension found.");
            signalCommandFailure();
          }
        } else {
          const nbContext = notebookContext();
          const project = await projectContext(targetDir, nbContext);
          const extensions2 = await extensionContext.extensions(
            targetDir,
            project?.config,
            project?.dir,
            { builtIn: false }
          );
          if (extensions2.length > 0) {
            const extensionsToRemove = await selectExtensions(extensions2);
            if (extensionsToRemove.length > 0) {
              await removeExtensions(extensionsToRemove);
            }
          } else {
            info("No extensions installed.");
            signalCommandFailure();
          }
        }
      }
    } finally {
      temp.cleanup();
    }
  }
);
var resolveCompatibleArgs = (args, defaultAction) => {
  if (args.length === 1) {
    const extname12 = args[0];
    if (extname12 === "tool") {
      return {
        action: "tool"
      };
    } else if (extname12 === "extension") {
      return {
        action: "extension"
      };
    } else if (installableTools().includes(extname12.toLowerCase())) {
      return {
        action: "tool",
        name: args[0]
      };
    } else {
      return {
        action: defaultAction,
        name: args[0]
      };
    }
  } else if (args.length > 1) {
    const action = args[0];
    const name2 = args[1];
    if (action === "tool") {
      return {
        action,
        name: name2
      };
    } else if (action === "extension") {
      return {
        action: "extension",
        name: name2
      };
    } else {
      return {
        action: defaultAction,
        name: name2
      };
    }
  } else {
    return {
      action: defaultAction
    };
  }
};
function removeExtensions(extensions2, prompt2) {
  const removeOneExtension = async (extension) => {
    return await afterConfirm(
      `Are you sure you'd like to remove ${extension.title}?`,
      async () => {
        await removeExtension(extension);
        info("Extension removed.");
      },
      prompt2
    );
  };
  const removeMultipleExtensions = async (extensions3) => {
    return await afterConfirm(
      `Are you sure you'd like to remove ${extensions3.length} ${extensions3.length === 1 ? "extension" : "extensions"}?`,
      async () => {
        for (const extensionToRemove of extensions3) {
          await removeExtension(extensionToRemove);
        }
        info(
          `${extensions3.length} ${extensions3.length === 1 ? "extension" : "extensions"} removed.`
        );
      },
      prompt2
    );
  };
  info("");
  if (extensions2.length === 1) {
    return removeOneExtension(extensions2[0]);
  } else {
    return removeMultipleExtensions(extensions2);
  }
}
async function selectExtensions(extensions2) {
  const sorted = extensions2.sort((ext1, ext2) => {
    const orgSort = (ext1.id.organization || "").localeCompare(
      ext2.id.organization || ""
    );
    if (orgSort !== 0) {
      return orgSort;
    } else {
      return ext1.title.localeCompare(ext2.title);
    }
  });
  const extsToKeep = (await Checkbox.prompt({
    message: "Select extension(s) to keep",
    options: sorted.map((ext) => {
      return {
        name: `${ext.title}${ext.id.organization ? " (" + ext.id.organization + ")" : ""}`,
        value: extensionIdString(ext.id),
        checked: true
      };
    }),
    hint: `Use the arrow keys and spacebar to specify extensions you'd like to remove.
   Press Enter to confirm the list of accounts you wish to remain available.`
  })).map((x3) => x3.value);
  return extensions2.filter((extension) => {
    return !extsToKeep.includes(extensionIdString(extension.id));
  });
}

// command/install/cmd.ts
var installCommand = new Command().name("install").arguments("[target...]").option(
  "--no-prompt",
  "Do not prompt to confirm actions"
).option(
  "--embed <extensionId>",
  "Embed this extension within another extension (used when authoring extensions).",
  {
    hidden: true
  }
).option(
  "--update-path",
  "Update system path when a tool is installed"
).description(
  `Installs a global dependency (${installableToolNames().join(", ")}).`
).example(
  "Install TinyTeX",
  "quarto install tinytex"
).example(
  "Install Chrome Headless Shell",
  "quarto install chrome-headless-shell"
).example(
  "Choose tool to install",
  "quarto install"
).action(
  async (options, ...target) => {
    await initYamlIntelligenceResourcesFromFilesystem();
    const temp = createTempContext();
    const resolved = resolveCompatibleArgs(target || [], "tool");
    try {
      if (resolved.action === "extension") {
        if (resolved.name) {
          await installExtension(
            resolved.name,
            temp,
            options.prompt !== false,
            options.embed
          );
        } else {
          info("Please provide an extension name, url, or path.");
        }
      } else if (resolved.action === "tool") {
        if (resolved.name) {
          await updateOrInstallTool(
            resolved.name,
            "install",
            options.prompt,
            options.updatePath
          );
        } else {
          const allTools2 = await loadTools();
          if (allTools2.filter((tool) => !tool.installed).length === 0) {
            info("All tools are already installed.");
          } else {
            const toolTarget = await selectTool(allTools2, "install");
            if (toolTarget) {
              info("");
              await installTool(toolTarget, options.updatePath);
            }
          }
        }
      } else {
        info(
          `Unrecognized option '${resolved.action}' - please choose 'tool' or 'extension'.`
        );
      }
    } finally {
      temp.cleanup();
    }
  }
);

// command/update/cmd.ts
init_temp();
init_log();
var updateCommand = new Command().name("update").arguments("[target...]").option(
  "--no-prompt",
  "Do not prompt to confirm actions"
).option(
  "--embed <extensionId>",
  "Embed this extension within another extension (used when authoring extensions)."
).description(
  `Updates an extension or global dependency (${installableToolNames().join(", ")}).`
).example(
  "Update extension (Github)",
  "quarto update extension <gh-org>/<gh-repo>"
).example(
  "Update extension (file)",
  "quarto update extension <path-to-zip>"
).example(
  "Update extension (url)",
  "quarto update extension <url>"
).example(
  "Update TinyTeX",
  "quarto update tool tinytex"
).example(
  "Update Chrome Headless Shell",
  "quarto update tool chrome-headless-shell"
).example(
  "Choose tool to update",
  "quarto update tool"
).action(
  async (options, ...target) => {
    await initYamlIntelligenceResourcesFromFilesystem();
    const temp = createTempContext();
    try {
      const resolved = resolveCompatibleArgs(target, "extension");
      if (resolved.action === "extension") {
        if (resolved.name) {
          await installExtension(
            resolved.name,
            temp,
            options.prompt !== false,
            options.embed
          );
        } else {
          info("Please provide an extension name, url, or path.");
        }
      } else if (resolved.action === "tool") {
        if (resolved.name) {
          await updateOrInstallTool(resolved.name, "update", options.prompt);
        } else {
          const allTools2 = await loadTools();
          if (allTools2.filter((tool) => !tool.installed).length === 0) {
            info("All tools are already installed.");
          } else {
            const toolTarget = await selectTool(allTools2, "update");
            if (toolTarget) {
              info("");
              await updateOrInstallTool(toolTarget, "update");
            }
          }
        }
      } else {
        info(
          `Unrecognized option '${resolved.action}' - please choose 'tool' or 'extension'.`
        );
      }
    } finally {
      temp.cleanup();
    }
  }
);

// command/publish/cmd.ts
init_fs();

// publish/netlify/api/core/BaseHttpRequest.ts
var BaseHttpRequest = class {
  constructor(config2) {
    this.config = config2;
  }
};

// publish/netlify/api/core/ApiError.ts
var ApiError = class extends Error {
  url;
  status;
  statusText;
  body;
  constructor(response, message) {
    super(message);
    this.name = "ApiError";
    this.url = response.url;
    this.status = response.status;
    this.statusText = response.statusText;
    this.body = response.body;
  }
};

// publish/netlify/api/core/CancelablePromise.ts
var CancelError = class extends Error {
  constructor(message) {
    super(message);
    this.name = "CancelError";
  }
  get isCancelled() {
    return true;
  }
};
var CancelablePromise = class {
  [Symbol.toStringTag] = "";
  _isResolved;
  _isRejected;
  _isCancelled;
  _cancelHandlers;
  _promise;
  _resolve;
  _reject;
  constructor(executor) {
    this._isResolved = false;
    this._isRejected = false;
    this._isCancelled = false;
    this._cancelHandlers = [];
    this._promise = new Promise((resolve16, reject2) => {
      this._resolve = resolve16;
      this._reject = reject2;
      const onResolve = (value) => {
        if (this._isResolved || this._isRejected || this._isCancelled) {
          return;
        }
        this._isResolved = true;
        this._resolve?.(value);
      };
      const onReject = (reason) => {
        if (this._isResolved || this._isRejected || this._isCancelled) {
          return;
        }
        this._isRejected = true;
        this._reject?.(reason);
      };
      const onCancel = (cancelHandler) => {
        if (this._isResolved || this._isRejected || this._isCancelled) {
          return;
        }
        this._cancelHandlers.push(cancelHandler);
      };
      Object.defineProperty(onCancel, "isResolved", {
        get: () => this._isResolved
      });
      Object.defineProperty(onCancel, "isRejected", {
        get: () => this._isRejected
      });
      Object.defineProperty(onCancel, "isCancelled", {
        get: () => this._isCancelled
      });
      return executor(onResolve, onReject, onCancel);
    });
  }
  then(onFulfilled, onRejected) {
    return this._promise.then(onFulfilled, onRejected);
  }
  catch(onRejected) {
    return this._promise.catch(onRejected);
  }
  finally(onFinally) {
    return this._promise.finally(onFinally);
  }
  cancel() {
    if (this._isResolved || this._isRejected || this._isCancelled) {
      return;
    }
    this._isCancelled = true;
    if (this._cancelHandlers.length) {
      try {
        for (const cancelHandler of this._cancelHandlers) {
          cancelHandler();
        }
      } catch (error2) {
        console.warn("Cancellation threw an error", error2);
        return;
      }
    }
    this._cancelHandlers.length = 0;
    this._reject?.(new CancelError("Request aborted"));
  }
  get isCancelled() {
    return this._isCancelled;
  }
};

// publish/netlify/api/core/request.ts
var isDefined = (value) => {
  return value !== void 0 && value !== null;
};
var isString4 = (value) => {
  return typeof value === "string";
};
var isStringWithValue = (value) => {
  return isString4(value) && value !== "";
};
var isBlob = (value) => {
  return typeof value === "object" && typeof value.type === "string" && typeof value.stream === "function" && typeof value.arrayBuffer === "function" && typeof value.constructor === "function" && typeof value.constructor.name === "string" && /^(Blob|File)$/.test(value.constructor.name) && /^(Blob|File)$/.test(value[Symbol.toStringTag]);
};
var isFormData = (value) => {
  return value instanceof FormData;
};
var base64 = (str3) => {
  try {
    return btoa(str3);
  } catch (err2) {
    return Buffer.from(str3).toString("base64");
  }
};
var getQueryString = (params) => {
  const qs = [];
  const append = (key, value) => {
    qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
  };
  const process4 = (key, value) => {
    if (isDefined(value)) {
      if (Array.isArray(value)) {
        value.forEach((v4) => {
          process4(key, v4);
        });
      } else if (typeof value === "object") {
        Object.entries(value).forEach(([k3, v4]) => {
          process4(`${key}[${k3}]`, v4);
        });
      } else {
        append(key, value);
      }
    }
  };
  Object.entries(params).forEach(([key, value]) => {
    process4(key, value);
  });
  if (qs.length > 0) {
    return `?${qs.join("&")}`;
  }
  return "";
};
var getUrl = (config2, options) => {
  const encoder4 = config2.ENCODE_PATH || encodeURI;
  const path3 = options.url.replace("{api-version}", config2.VERSION).replace(/{(.*?)}/g, (substring, group) => {
    if (options.path?.hasOwnProperty(group)) {
      return encoder4(String(options.path[group]));
    }
    return substring;
  });
  const url = `${config2.BASE}${path3}`;
  if (options.query) {
    return `${url}${getQueryString(options.query)}`;
  }
  return url;
};
var getFormData = (options) => {
  if (options.formData) {
    const formData = new FormData();
    const process4 = (key, value) => {
      if (isString4(value) || isBlob(value)) {
        formData.append(key, value);
      } else {
        formData.append(key, JSON.stringify(value));
      }
    };
    Object.entries(options.formData).filter(([_3, value]) => isDefined(value)).forEach(([key, value]) => {
      if (Array.isArray(value)) {
        value.forEach((v4) => process4(key, v4));
      } else {
        process4(key, value);
      }
    });
    return formData;
  }
  return void 0;
};
var resolve15 = async (options, resolver) => {
  if (typeof resolver === "function") {
    return resolver(options);
  }
  return resolver;
};
var getHeaders = async (config2, options) => {
  const token = await resolve15(options, config2.TOKEN);
  const username = await resolve15(options, config2.USERNAME);
  const password = await resolve15(options, config2.PASSWORD);
  const additionalHeaders = await resolve15(options, config2.HEADERS);
  const headers = Object.entries({
    Accept: "application/json",
    ...additionalHeaders,
    ...options.headers
  }).filter(([_3, value]) => isDefined(value)).reduce((headers2, [key, value]) => ({
    ...headers2,
    [key]: String(value)
  }), {});
  if (isStringWithValue(token)) {
    headers["Authorization"] = `Bearer ${token}`;
  }
  if (isStringWithValue(username) && isStringWithValue(password)) {
    const credentials = base64(`${username}:${password}`);
    headers["Authorization"] = `Basic ${credentials}`;
  }
  if (options.body) {
    if (options.mediaType) {
      headers["Content-Type"] = options.mediaType;
    } else if (isBlob(options.body)) {
      headers["Content-Type"] = options.body.type || "application/octet-stream";
    } else if (isString4(options.body)) {
      headers["Content-Type"] = "text/plain";
    } else if (!isFormData(options.body)) {
      headers["Content-Type"] = "application/json";
    }
  }
  return new Headers(headers);
};
var getRequestBody = (options) => {
  if (options.body) {
    if (options.mediaType?.includes("/json")) {
      return JSON.stringify(options.body);
    } else if (isString4(options.body) || isBlob(options.body) || isFormData(options.body)) {
      return options.body;
    } else {
      return JSON.stringify(options.body);
    }
  }
  return void 0;
};
var sendRequest = async (config2, options, url, body, formData, headers, onCancel) => {
  const controller = new AbortController();
  const request2 = {
    headers,
    body: body ?? formData,
    method: options.method,
    signal: controller.signal
  };
  if (config2.WITH_CREDENTIALS) {
    request2.credentials = config2.CREDENTIALS;
  }
  onCancel(() => controller.abort());
  return await fetch(url, request2);
};
var getResponseHeader = (response, responseHeader) => {
  if (responseHeader) {
    const content = response.headers.get(responseHeader);
    if (isString4(content)) {
      return content;
    }
  }
  return void 0;
};
var getResponseBody = async (response) => {
  if (response.status !== 204) {
    try {
      const contentType2 = response.headers.get("Content-Type");
      if (contentType2) {
        const isJSON = contentType2.toLowerCase().startsWith("application/json");
        if (isJSON) {
          return await response.json();
        } else {
          return await response.text();
        }
      }
    } catch (error2) {
      console.error(error2);
    }
  }
  return void 0;
};
var catchErrorCodes = (options, result2) => {
  const errors2 = {
    400: "Bad Request",
    401: "Unauthorized",
    403: "Forbidden",
    404: "Not Found",
    500: "Internal Server Error",
    502: "Bad Gateway",
    503: "Service Unavailable",
    ...options.errors
  };
  const error2 = errors2[result2.status];
  if (error2) {
    throw new ApiError(result2, error2);
  }
  if (!result2.ok) {
    throw new ApiError(result2, "Generic Error");
  }
};
var request = (config2, options) => {
  return new CancelablePromise(async (resolve16, reject2, onCancel) => {
    try {
      const url = getUrl(config2, options);
      const formData = getFormData(options);
      const body = getRequestBody(options);
      const headers = await getHeaders(config2, options);
      if (!onCancel.isCancelled) {
        const response = await sendRequest(
          config2,
          options,
          url,
          body,
          formData,
          headers,
          onCancel
        );
        const responseBody = await getResponseBody(response);
        const responseHeader = getResponseHeader(
          response,
          options.responseHeader
        );
        const result2 = {
          url,
          ok: response.ok,
          status: response.status,
          statusText: response.statusText,
          body: responseHeader ?? responseBody
        };
        catchErrorCodes(options, result2);
        resolve16(result2.body);
      }
    } catch (error2) {
      reject2(error2);
    }
  });
};

// publish/netlify/api/core/FetchHttpRequest.ts
var FetchHttpRequest = class extends BaseHttpRequest {
  constructor(config2) {
    super(config2);
  }
  /**
   * Request method
   * @param options The request options from the service
   * @returns CancelablePromise<T>
   * @throws ApiError
   */
  request(options) {
    return request(this.config, options);
  }
};

// publish/netlify/api/services/AccessTokenService.ts
var AccessTokenService = class {
  constructor(httpRequest) {
    this.httpRequest = httpRequest;
  }
  /**
   * @returns any error
   * @throws ApiError
   */
  exchangeTicket({
    ticketId
  }) {
    return this.httpRequest.request({
      method: "POST",
      url: "/oauth/tickets/{ticket_id}/exchange",
      path: {
        "ticket_id": ticketId
      }
    });
  }
};

// publish/netlify/api/services/AccountMembershipService.ts
var AccountMembershipService = class {
  constructor(httpRequest) {
    this.httpRequest = httpRequest;
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  listAccountsForUser() {
    return this.httpRequest.request({
      method: "GET",
      url: "/accounts"
    });
  }
  /**
   * @returns any error
   * @throws ApiError
   */
  createAccount({
    accountSetup: accountSetup2
  }) {
    return this.httpRequest.request({
      method: "POST",
      url: "/accounts",
      body: accountSetup2
    });
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  getAccount({
    accountId
  }) {
    return this.httpRequest.request({
      method: "GET",
      url: "/accounts/{account_id}",
      path: {
        "account_id": accountId
      }
    });
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  updateAccount({
    accountId,
    accountUpdateSetup
  }) {
    return this.httpRequest.request({
      method: "PUT",
      url: "/accounts/{account_id}",
      path: {
        "account_id": accountId
      },
      body: accountUpdateSetup
    });
  }
  /**
   * @returns any error
   * @throws ApiError
   */
  cancelAccount({
    accountId
  }) {
    return this.httpRequest.request({
      method: "DELETE",
      url: "/accounts/{account_id}",
      path: {
        "account_id": accountId
      }
    });
  }
};

// publish/netlify/api/services/AccountTypeService.ts
var AccountTypeService = class {
  constructor(httpRequest) {
    this.httpRequest = httpRequest;
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  listAccountTypesForUser() {
    return this.httpRequest.request({
      method: "GET",
      url: "/accounts/types"
    });
  }
};

// publish/netlify/api/services/AssetService.ts
var AssetService = class {
  constructor(httpRequest) {
    this.httpRequest = httpRequest;
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  listSiteAssets({
    siteId
  }) {
    return this.httpRequest.request({
      method: "GET",
      url: "/sites/{site_id}/assets",
      path: {
        "site_id": siteId
      }
    });
  }
  /**
   * @returns any error
   * @throws ApiError
   */
  createSiteAsset({
    siteId,
    name: name2,
    size,
    contentType: contentType2,
    visibility
  }) {
    return this.httpRequest.request({
      method: "POST",
      url: "/sites/{site_id}/assets",
      path: {
        "site_id": siteId
      },
      query: {
        "name": name2,
        "size": size,
        "content_type": contentType2,
        "visibility": visibility
      }
    });
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  getSiteAssetInfo({
    siteId,
    assetId
  }) {
    return this.httpRequest.request({
      method: "GET",
      url: "/sites/{site_id}/assets/{asset_id}",
      path: {
        "site_id": siteId,
        "asset_id": assetId
      }
    });
  }
  /**
   * @returns any Updated
   * @throws ApiError
   */
  updateSiteAsset({
    siteId,
    assetId,
    state: state2
  }) {
    return this.httpRequest.request({
      method: "PUT",
      url: "/sites/{site_id}/assets/{asset_id}",
      path: {
        "site_id": siteId,
        "asset_id": assetId
      },
      query: {
        "state": state2
      }
    });
  }
  /**
   * @returns any error
   * @throws ApiError
   */
  deleteSiteAsset({
    siteId,
    assetId
  }) {
    return this.httpRequest.request({
      method: "DELETE",
      url: "/sites/{site_id}/assets/{asset_id}",
      path: {
        "site_id": siteId,
        "asset_id": assetId
      }
    });
  }
};

// publish/netlify/api/services/AssetPublicSignatureService.ts
var AssetPublicSignatureService = class {
  constructor(httpRequest) {
    this.httpRequest = httpRequest;
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  getSiteAssetPublicSignature({
    siteId,
    assetId
  }) {
    return this.httpRequest.request({
      method: "GET",
      url: "/sites/{site_id}/assets/{asset_id}/public_signature",
      path: {
        "site_id": siteId,
        "asset_id": assetId
      }
    });
  }
};

// publish/netlify/api/services/AuditLogService.ts
var AuditLogService = class {
  constructor(httpRequest) {
    this.httpRequest = httpRequest;
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  listAccountAuditEvents({
    accountId,
    query,
    logType,
    page,
    perPage
  }) {
    return this.httpRequest.request({
      method: "GET",
      url: "/accounts/{account_id}/audit",
      path: {
        "account_id": accountId
      },
      query: {
        "query": query,
        "log_type": logType,
        "page": page,
        "per_page": perPage
      }
    });
  }
};

// publish/netlify/api/services/BuildService.ts
var BuildService = class {
  constructor(httpRequest) {
    this.httpRequest = httpRequest;
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  listSiteBuilds({
    siteId,
    page,
    perPage
  }) {
    return this.httpRequest.request({
      method: "GET",
      url: "/sites/{site_id}/builds",
      path: {
        "site_id": siteId
      },
      query: {
        "page": page,
        "per_page": perPage
      }
    });
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  createSiteBuild({
    siteId,
    build
  }) {
    return this.httpRequest.request({
      method: "POST",
      url: "/sites/{site_id}/builds",
      path: {
        "site_id": siteId
      },
      body: build
    });
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  getSiteBuild({
    buildId
  }) {
    return this.httpRequest.request({
      method: "GET",
      url: "/builds/{build_id}",
      path: {
        "build_id": buildId
      }
    });
  }
  /**
   * @returns any error
   * @throws ApiError
   */
  notifyBuildStart({
    buildId
  }) {
    return this.httpRequest.request({
      method: "POST",
      url: "/builds/{build_id}/start",
      path: {
        "build_id": buildId
      }
    });
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  getAccountBuildStatus({
    accountId
  }) {
    return this.httpRequest.request({
      method: "GET",
      url: "/{account_id}/builds/status",
      path: {
        "account_id": accountId
      }
    });
  }
};

// publish/netlify/api/services/BuildHookService.ts
var BuildHookService = class {
  constructor(httpRequest) {
    this.httpRequest = httpRequest;
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  listSiteBuildHooks({
    siteId
  }) {
    return this.httpRequest.request({
      method: "GET",
      url: "/sites/{site_id}/build_hooks",
      path: {
        "site_id": siteId
      }
    });
  }
  /**
   * @returns any error
   * @throws ApiError
   */
  createSiteBuildHook({
    siteId,
    buildHook
  }) {
    return this.httpRequest.request({
      method: "POST",
      url: "/sites/{site_id}/build_hooks",
      path: {
        "site_id": siteId
      },
      body: buildHook
    });
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  getSiteBuildHook({
    siteId,
    id
  }) {
    return this.httpRequest.request({
      method: "GET",
      url: "/sites/{site_id}/build_hooks/{id}",
      path: {
        "site_id": siteId,
        "id": id
      }
    });
  }
  /**
   * @returns any error
   * @throws ApiError
   */
  updateSiteBuildHook({
    siteId,
    id,
    buildHook
  }) {
    return this.httpRequest.request({
      method: "PUT",
      url: "/sites/{site_id}/build_hooks/{id}",
      path: {
        "site_id": siteId,
        "id": id
      },
      body: buildHook
    });
  }
  /**
   * @returns any error
   * @throws ApiError
   */
  deleteSiteBuildHook({
    siteId,
    id
  }) {
    return this.httpRequest.request({
      method: "DELETE",
      url: "/sites/{site_id}/build_hooks/{id}",
      path: {
        "site_id": siteId,
        "id": id
      }
    });
  }
};

// publish/netlify/api/services/BuildLogMsgService.ts
var BuildLogMsgService = class {
  constructor(httpRequest) {
    this.httpRequest = httpRequest;
  }
  /**
   * @returns any error
   * @throws ApiError
   */
  updateSiteBuildLog({
    buildId,
    msg: msg5
  }) {
    return this.httpRequest.request({
      method: "POST",
      url: "/builds/{build_id}/log",
      path: {
        "build_id": buildId
      },
      body: msg5
    });
  }
};

// publish/netlify/api/services/DeployService.ts
var DeployService = class {
  constructor(httpRequest) {
    this.httpRequest = httpRequest;
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  listSiteDeploys({
    siteId,
    page,
    perPage
  }) {
    return this.httpRequest.request({
      method: "GET",
      url: "/sites/{site_id}/deploys",
      path: {
        "site_id": siteId
      },
      query: {
        "page": page,
        "per_page": perPage
      }
    });
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  createSiteDeploy({
    siteId,
    deploy,
    title: title3
  }) {
    return this.httpRequest.request({
      method: "POST",
      url: "/sites/{site_id}/deploys",
      path: {
        "site_id": siteId
      },
      query: {
        "title": title3
      },
      body: deploy
    });
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  getSiteDeploy({
    siteId,
    deployId
  }) {
    return this.httpRequest.request({
      method: "GET",
      url: "/sites/{site_id}/deploys/{deploy_id}",
      path: {
        "site_id": siteId,
        "deploy_id": deployId
      }
    });
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  updateSiteDeploy({
    siteId,
    deployId,
    deploy
  }) {
    return this.httpRequest.request({
      method: "PUT",
      url: "/sites/{site_id}/deploys/{deploy_id}",
      path: {
        "site_id": siteId,
        "deploy_id": deployId
      },
      body: deploy
    });
  }
  /**
   * @returns any error
   * @throws ApiError
   */
  cancelSiteDeploy({
    deployId
  }) {
    return this.httpRequest.request({
      method: "POST",
      url: "/deploys/{deploy_id}/cancel",
      path: {
        "deploy_id": deployId
      }
    });
  }
  /**
   * @returns any error
   * @throws ApiError
   */
  restoreSiteDeploy({
    siteId,
    deployId
  }) {
    return this.httpRequest.request({
      method: "POST",
      url: "/sites/{site_id}/deploys/{deploy_id}/restore",
      path: {
        "site_id": siteId,
        "deploy_id": deployId
      }
    });
  }
  /**
   * @returns any error
   * @throws ApiError
   */
  rollbackSiteDeploy({
    siteId
  }) {
    return this.httpRequest.request({
      method: "PUT",
      url: "/sites/{site_id}/rollback",
      path: {
        "site_id": siteId
      }
    });
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  getDeploy({
    deployId
  }) {
    return this.httpRequest.request({
      method: "GET",
      url: "/deploys/{deploy_id}",
      path: {
        "deploy_id": deployId
      }
    });
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  lockDeploy({
    deployId
  }) {
    return this.httpRequest.request({
      method: "POST",
      url: "/deploys/{deploy_id}/lock",
      path: {
        "deploy_id": deployId
      }
    });
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  unlockDeploy({
    deployId
  }) {
    return this.httpRequest.request({
      method: "POST",
      url: "/deploys/{deploy_id}/unlock",
      path: {
        "deploy_id": deployId
      }
    });
  }
};

// publish/netlify/api/services/DeployedBranchService.ts
var DeployedBranchService = class {
  constructor(httpRequest) {
    this.httpRequest = httpRequest;
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  listSiteDeployedBranches({
    siteId
  }) {
    return this.httpRequest.request({
      method: "GET",
      url: "/sites/{site_id}/deployed-branches",
      path: {
        "site_id": siteId
      }
    });
  }
};

// publish/netlify/api/services/DeployKeyService.ts
var DeployKeyService = class {
  constructor(httpRequest) {
    this.httpRequest = httpRequest;
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  listDeployKeys() {
    return this.httpRequest.request({
      method: "GET",
      url: "/deploy_keys"
    });
  }
  /**
   * @returns any error
   * @throws ApiError
   */
  createDeployKey() {
    return this.httpRequest.request({
      method: "POST",
      url: "/deploy_keys"
    });
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  getDeployKey({
    keyId
  }) {
    return this.httpRequest.request({
      method: "GET",
      url: "/deploy_keys/{key_id}",
      path: {
        "key_id": keyId
      }
    });
  }
  /**
   * @returns any error
   * @throws ApiError
   */
  deleteDeployKey({
    keyId
  }) {
    return this.httpRequest.request({
      method: "DELETE",
      url: "/deploy_keys/{key_id}",
      path: {
        "key_id": keyId
      }
    });
  }
};

// publish/netlify/api/services/DnsZoneService.ts
var DnsZoneService = class {
  constructor(httpRequest) {
    this.httpRequest = httpRequest;
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  getDnsForSite({
    siteId
  }) {
    return this.httpRequest.request({
      method: "GET",
      url: "/sites/{site_id}/dns",
      path: {
        "site_id": siteId
      }
    });
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  configureDnsForSite({
    siteId
  }) {
    return this.httpRequest.request({
      method: "PUT",
      url: "/sites/{site_id}/dns",
      path: {
        "site_id": siteId
      }
    });
  }
  /**
   * @returns any error
   * @throws ApiError
   */
  createDnsZone({
    dnsZoneParams
  }) {
    return this.httpRequest.request({
      method: "POST",
      url: "/dns_zones",
      body: dnsZoneParams
    });
  }
  /**
   * @returns any get all DNS zones the user has access to
   * @throws ApiError
   */
  getDnsZones({
    accountSlug
  }) {
    return this.httpRequest.request({
      method: "GET",
      url: "/dns_zones",
      query: {
        "account_slug": accountSlug
      }
    });
  }
  /**
   * @returns any get a single DNS zone
   * @throws ApiError
   */
  getDnsZone({
    zoneId
  }) {
    return this.httpRequest.request({
      method: "GET",
      url: "/dns_zones/{zone_id}",
      path: {
        "zone_id": zoneId
      }
    });
  }
  /**
   * @returns any error
   * @throws ApiError
   */
  deleteDnsZone({
    zoneId
  }) {
    return this.httpRequest.request({
      method: "DELETE",
      url: "/dns_zones/{zone_id}",
      path: {
        "zone_id": zoneId
      }
    });
  }
  /**
   * @returns any transfer a DNS zone to another account
   * @throws ApiError
   */
  transferDnsZone({
    zoneId,
    accountId,
    transferAccountId,
    transferUserId
  }) {
    return this.httpRequest.request({
      method: "PUT",
      url: "/dns_zones/{zone_id}/transfer",
      path: {
        "zone_id": zoneId
      },
      query: {
        "account_id": accountId,
        "transfer_account_id": transferAccountId,
        "transfer_user_id": transferUserId
      }
    });
  }
  /**
   * @returns any get all DNS records for a single DNS zone
   * @throws ApiError
   */
  getDnsRecords({
    zoneId
  }) {
    return this.httpRequest.request({
      method: "GET",
      url: "/dns_zones/{zone_id}/dns_records",
      path: {
        "zone_id": zoneId
      }
    });
  }
  /**
   * @returns any error
   * @throws ApiError
   */
  createDnsRecord({
    zoneId,
    dnsRecord
  }) {
    return this.httpRequest.request({
      method: "POST",
      url: "/dns_zones/{zone_id}/dns_records",
      path: {
        "zone_id": zoneId
      },
      body: dnsRecord
    });
  }
  /**
   * @returns any get a single DNS record
   * @throws ApiError
   */
  getIndividualDnsRecord({
    zoneId,
    dnsRecordId
  }) {
    return this.httpRequest.request({
      method: "GET",
      url: "/dns_zones/{zone_id}/dns_records/{dns_record_id}",
      path: {
        "zone_id": zoneId,
        "dns_record_id": dnsRecordId
      }
    });
  }
  /**
   * @returns any error
   * @throws ApiError
   */
  deleteDnsRecord({
    zoneId,
    dnsRecordId
  }) {
    return this.httpRequest.request({
      method: "DELETE",
      url: "/dns_zones/{zone_id}/dns_records/{dns_record_id}",
      path: {
        "zone_id": zoneId,
        "dns_record_id": dnsRecordId
      }
    });
  }
};

// publish/netlify/api/services/FileService.ts
var FileService = class {
  constructor(httpRequest) {
    this.httpRequest = httpRequest;
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  listSiteFiles({
    siteId
  }) {
    return this.httpRequest.request({
      method: "GET",
      url: "/sites/{site_id}/files",
      path: {
        "site_id": siteId
      }
    });
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  getSiteFileByPathName({
    siteId,
    filePath
  }) {
    return this.httpRequest.request({
      method: "GET",
      url: "/sites/{site_id}/files/{file_path}",
      path: {
        "site_id": siteId,
        "file_path": filePath
      }
    });
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  uploadDeployFile({
    deployId,
    path: path3,
    fileBody,
    size
  }) {
    return this.httpRequest.request({
      method: "PUT",
      url: "/deploys/{deploy_id}/files/{path}",
      path: {
        "deploy_id": deployId,
        "path": path3
      },
      query: {
        "size": size
      },
      body: fileBody
    });
  }
};

// publish/netlify/api/services/FormService.ts
var FormService = class {
  constructor(httpRequest) {
    this.httpRequest = httpRequest;
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  listSiteForms({
    siteId
  }) {
    return this.httpRequest.request({
      method: "GET",
      url: "/sites/{site_id}/forms",
      path: {
        "site_id": siteId
      }
    });
  }
  /**
   * @returns any error
   * @throws ApiError
   */
  deleteSiteForm({
    siteId,
    formId
  }) {
    return this.httpRequest.request({
      method: "DELETE",
      url: "/sites/{site_id}/forms/{form_id}",
      path: {
        "site_id": siteId,
        "form_id": formId
      }
    });
  }
};

// publish/netlify/api/services/FunctionService.ts
var FunctionService = class {
  constructor(httpRequest) {
    this.httpRequest = httpRequest;
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  uploadDeployFunction({
    deployId,
    name: name2,
    fileBody,
    runtime,
    size
  }) {
    return this.httpRequest.request({
      method: "PUT",
      url: "/deploys/{deploy_id}/functions/{name}",
      path: {
        "deploy_id": deployId,
        "name": name2
      },
      query: {
        "runtime": runtime,
        "size": size
      },
      body: fileBody
    });
  }
};

// publish/netlify/api/services/HookService.ts
var HookService = class {
  constructor(httpRequest) {
    this.httpRequest = httpRequest;
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  listHooksBySiteId({
    siteId
  }) {
    return this.httpRequest.request({
      method: "GET",
      url: "/hooks",
      query: {
        "site_id": siteId
      }
    });
  }
  /**
   * @returns any error
   * @throws ApiError
   */
  createHookBySiteId({
    siteId,
    hook
  }) {
    return this.httpRequest.request({
      method: "POST",
      url: "/hooks",
      query: {
        "site_id": siteId
      },
      body: hook
    });
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  getHook({
    hookId
  }) {
    return this.httpRequest.request({
      method: "GET",
      url: "/hooks/{hook_id}",
      path: {
        "hook_id": hookId
      }
    });
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  updateHook({
    hookId,
    hook
  }) {
    return this.httpRequest.request({
      method: "PUT",
      url: "/hooks/{hook_id}",
      path: {
        "hook_id": hookId
      },
      body: hook
    });
  }
  /**
   * @returns void
   * @throws ApiError
   */
  deleteHook({
    hookId
  }) {
    return this.httpRequest.request({
      method: "DELETE",
      url: "/hooks/{hook_id}",
      path: {
        "hook_id": hookId
      }
    });
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  enableHook({
    hookId
  }) {
    return this.httpRequest.request({
      method: "POST",
      url: "/hooks/{hook_id}/enable",
      path: {
        "hook_id": hookId
      }
    });
  }
};

// publish/netlify/api/services/HookTypeService.ts
var HookTypeService = class {
  constructor(httpRequest) {
    this.httpRequest = httpRequest;
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  listHookTypes() {
    return this.httpRequest.request({
      method: "GET",
      url: "/hooks/types"
    });
  }
};

// publish/netlify/api/services/MemberService.ts
var MemberService = class {
  constructor(httpRequest) {
    this.httpRequest = httpRequest;
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  listMembersForAccount({
    accountSlug
  }) {
    return this.httpRequest.request({
      method: "GET",
      url: "/{account_slug}/members",
      path: {
        "account_slug": accountSlug
      }
    });
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  addMemberToAccount({
    accountSlug,
    email,
    role
  }) {
    return this.httpRequest.request({
      method: "POST",
      url: "/{account_slug}/members",
      path: {
        "account_slug": accountSlug
      },
      query: {
        "role": role,
        "email": email
      }
    });
  }
};

// publish/netlify/api/services/MetadataService.ts
var MetadataService = class {
  constructor(httpRequest) {
    this.httpRequest = httpRequest;
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  getSiteMetadata({
    siteId
  }) {
    return this.httpRequest.request({
      method: "GET",
      url: "/sites/{site_id}/metadata",
      path: {
        "site_id": siteId
      }
    });
  }
  /**
   * @returns any error
   * @throws ApiError
   */
  updateSiteMetadata({
    siteId,
    metadata
  }) {
    return this.httpRequest.request({
      method: "PUT",
      url: "/sites/{site_id}/metadata",
      path: {
        "site_id": siteId
      },
      body: metadata
    });
  }
};

// publish/netlify/api/services/PaymentMethodService.ts
var PaymentMethodService = class {
  constructor(httpRequest) {
    this.httpRequest = httpRequest;
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  listPaymentMethodsForUser() {
    return this.httpRequest.request({
      method: "GET",
      url: "/billing/payment_methods"
    });
  }
};

// publish/netlify/api/services/ServiceService.ts
var ServiceService = class {
  constructor(httpRequest) {
    this.httpRequest = httpRequest;
  }
  /**
   * @returns any services
   * @throws ApiError
   */
  getServices({
    search
  }) {
    return this.httpRequest.request({
      method: "GET",
      url: "/services/",
      query: {
        "search": search
      }
    });
  }
  /**
   * @returns any services
   * @throws ApiError
   */
  showService({
    addonName
  }) {
    return this.httpRequest.request({
      method: "GET",
      url: "/services/{addonName}",
      path: {
        "addonName": addonName
      }
    });
  }
  /**
   * @returns any error
   * @throws ApiError
   */
  showServiceManifest({
    addonName
  }) {
    return this.httpRequest.request({
      method: "GET",
      url: "/services/{addonName}/manifest",
      path: {
        "addonName": addonName
      }
    });
  }
};

// publish/netlify/api/services/ServiceInstanceService.ts
var ServiceInstanceService = class {
  constructor(httpRequest) {
    this.httpRequest = httpRequest;
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  listServiceInstancesForSite({
    siteId
  }) {
    return this.httpRequest.request({
      method: "GET",
      url: "/sites/{site_id}/service-instances",
      path: {
        "site_id": siteId
      }
    });
  }
  /**
   * @returns any error
   * @throws ApiError
   */
  createServiceInstance({
    siteId,
    addon,
    config: config2
  }) {
    return this.httpRequest.request({
      method: "POST",
      url: "/sites/{site_id}/services/{addon}/instances",
      path: {
        "site_id": siteId,
        "addon": addon
      },
      body: config2
    });
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  showServiceInstance({
    siteId,
    addon,
    instanceId
  }) {
    return this.httpRequest.request({
      method: "GET",
      url: "/sites/{site_id}/services/{addon}/instances/{instance_id}",
      path: {
        "site_id": siteId,
        "addon": addon,
        "instance_id": instanceId
      }
    });
  }
  /**
   * @returns any error
   * @throws ApiError
   */
  updateServiceInstance({
    siteId,
    addon,
    instanceId,
    config: config2
  }) {
    return this.httpRequest.request({
      method: "PUT",
      url: "/sites/{site_id}/services/{addon}/instances/{instance_id}",
      path: {
        "site_id": siteId,
        "addon": addon,
        "instance_id": instanceId
      },
      body: config2
    });
  }
  /**
   * @returns any error
   * @throws ApiError
   */
  deleteServiceInstance({
    siteId,
    addon,
    instanceId
  }) {
    return this.httpRequest.request({
      method: "DELETE",
      url: "/sites/{site_id}/services/{addon}/instances/{instance_id}",
      path: {
        "site_id": siteId,
        "addon": addon,
        "instance_id": instanceId
      }
    });
  }
};

// publish/netlify/api/services/SiteService.ts
var SiteService = class {
  constructor(httpRequest) {
    this.httpRequest = httpRequest;
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  listSites({
    name: name2,
    filter: filter3,
    page,
    perPage
  }) {
    return this.httpRequest.request({
      method: "GET",
      url: "/sites",
      query: {
        "name": name2,
        "filter": filter3,
        "page": page,
        "per_page": perPage
      }
    });
  }
  /**
   * @returns any error
   * @throws ApiError
   */
  createSite({
    site,
    configureDns
  }) {
    return this.httpRequest.request({
      method: "POST",
      url: "/sites",
      query: {
        "configure_dns": configureDns
      },
      body: site
    });
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  getSite({
    siteId
  }) {
    return this.httpRequest.request({
      method: "GET",
      url: "/sites/{site_id}",
      path: {
        "site_id": siteId
      }
    });
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  updateSite({
    siteId,
    site
  }) {
    return this.httpRequest.request({
      method: "PATCH",
      url: "/sites/{site_id}",
      path: {
        "site_id": siteId
      },
      body: site
    });
  }
  /**
   * @returns any error
   * @throws ApiError
   */
  deleteSite({
    siteId
  }) {
    return this.httpRequest.request({
      method: "DELETE",
      url: "/sites/{site_id}",
      path: {
        "site_id": siteId
      }
    });
  }
  /**
   * [Beta] Unlinks the repo from the site.
   *
   * This action will also:
   * - Delete associated deploy keys
   * - Delete outgoing webhooks for the repo
   * - Delete the site's build hooks
   * @returns any OK
   * @throws ApiError
   */
  unlinkSiteRepo({
    siteId
  }) {
    return this.httpRequest.request({
      method: "PUT",
      url: "/sites/{site_id}/unlink_repo",
      path: {
        "site_id": siteId
      },
      errors: {
        404: `Site not found`
      }
    });
  }
  /**
   * @returns any error
   * @throws ApiError
   */
  createSiteInTeam({
    accountSlug,
    site,
    configureDns
  }) {
    return this.httpRequest.request({
      method: "POST",
      url: "/{account_slug}/sites",
      path: {
        "account_slug": accountSlug
      },
      query: {
        "configure_dns": configureDns
      },
      body: site
    });
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  listSitesForAccount({
    accountSlug,
    name: name2,
    page,
    perPage
  }) {
    return this.httpRequest.request({
      method: "GET",
      url: "/{account_slug}/sites",
      path: {
        "account_slug": accountSlug
      },
      query: {
        "name": name2,
        "page": page,
        "per_page": perPage
      }
    });
  }
};

// publish/netlify/api/services/SniCertificateService.ts
var SniCertificateService = class {
  constructor(httpRequest) {
    this.httpRequest = httpRequest;
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  provisionSiteTlsCertificate({
    siteId,
    certificate,
    key,
    caCertificates
  }) {
    return this.httpRequest.request({
      method: "POST",
      url: "/sites/{site_id}/ssl",
      path: {
        "site_id": siteId
      },
      query: {
        "certificate": certificate,
        "key": key,
        "ca_certificates": caCertificates
      }
    });
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  showSiteTlsCertificate({
    siteId
  }) {
    return this.httpRequest.request({
      method: "GET",
      url: "/sites/{site_id}/ssl",
      path: {
        "site_id": siteId
      }
    });
  }
};

// publish/netlify/api/services/SnippetService.ts
var SnippetService = class {
  constructor(httpRequest) {
    this.httpRequest = httpRequest;
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  listSiteSnippets({
    siteId
  }) {
    return this.httpRequest.request({
      method: "GET",
      url: "/sites/{site_id}/snippets",
      path: {
        "site_id": siteId
      }
    });
  }
  /**
   * @returns any error
   * @throws ApiError
   */
  createSiteSnippet({
    siteId,
    snippet: snippet3
  }) {
    return this.httpRequest.request({
      method: "POST",
      url: "/sites/{site_id}/snippets",
      path: {
        "site_id": siteId
      },
      body: snippet3
    });
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  getSiteSnippet({
    siteId,
    snippetId
  }) {
    return this.httpRequest.request({
      method: "GET",
      url: "/sites/{site_id}/snippets/{snippet_id}",
      path: {
        "site_id": siteId,
        "snippet_id": snippetId
      }
    });
  }
  /**
   * @returns any error
   * @throws ApiError
   */
  updateSiteSnippet({
    siteId,
    snippetId,
    snippet: snippet3
  }) {
    return this.httpRequest.request({
      method: "PUT",
      url: "/sites/{site_id}/snippets/{snippet_id}",
      path: {
        "site_id": siteId,
        "snippet_id": snippetId
      },
      body: snippet3
    });
  }
  /**
   * @returns any error
   * @throws ApiError
   */
  deleteSiteSnippet({
    siteId,
    snippetId
  }) {
    return this.httpRequest.request({
      method: "DELETE",
      url: "/sites/{site_id}/snippets/{snippet_id}",
      path: {
        "site_id": siteId,
        "snippet_id": snippetId
      }
    });
  }
};

// publish/netlify/api/services/SplitTestService.ts
var SplitTestService = class {
  constructor(httpRequest) {
    this.httpRequest = httpRequest;
  }
  /**
   * @returns any error
   * @throws ApiError
   */
  createSplitTest({
    siteId,
    branchTests
  }) {
    return this.httpRequest.request({
      method: "POST",
      url: "/sites/{site_id}/traffic_splits",
      path: {
        "site_id": siteId
      },
      body: branchTests
    });
  }
  /**
   * @returns any split_tests
   * @throws ApiError
   */
  getSplitTests({
    siteId
  }) {
    return this.httpRequest.request({
      method: "GET",
      url: "/sites/{site_id}/traffic_splits",
      path: {
        "site_id": siteId
      }
    });
  }
  /**
   * @returns any error
   * @throws ApiError
   */
  updateSplitTest({
    siteId,
    splitTestId,
    branchTests
  }) {
    return this.httpRequest.request({
      method: "PUT",
      url: "/sites/{site_id}/traffic_splits/{split_test_id}",
      path: {
        "site_id": siteId,
        "split_test_id": splitTestId
      },
      body: branchTests
    });
  }
  /**
   * @returns any split_test
   * @throws ApiError
   */
  getSplitTest({
    siteId,
    splitTestId
  }) {
    return this.httpRequest.request({
      method: "GET",
      url: "/sites/{site_id}/traffic_splits/{split_test_id}",
      path: {
        "site_id": siteId,
        "split_test_id": splitTestId
      }
    });
  }
  /**
   * @returns any error
   * @throws ApiError
   */
  enableSplitTest({
    siteId,
    splitTestId
  }) {
    return this.httpRequest.request({
      method: "POST",
      url: "/sites/{site_id}/traffic_splits/{split_test_id}/publish",
      path: {
        "site_id": siteId,
        "split_test_id": splitTestId
      }
    });
  }
  /**
   * @returns any error
   * @throws ApiError
   */
  disableSplitTest({
    siteId,
    splitTestId
  }) {
    return this.httpRequest.request({
      method: "POST",
      url: "/sites/{site_id}/traffic_splits/{split_test_id}/unpublish",
      path: {
        "site_id": siteId,
        "split_test_id": splitTestId
      }
    });
  }
};

// publish/netlify/api/services/SubmissionService.ts
var SubmissionService = class {
  constructor(httpRequest) {
    this.httpRequest = httpRequest;
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  listSiteSubmissions({
    siteId,
    page,
    perPage
  }) {
    return this.httpRequest.request({
      method: "GET",
      url: "/sites/{site_id}/submissions",
      path: {
        "site_id": siteId
      },
      query: {
        "page": page,
        "per_page": perPage
      }
    });
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  listFormSubmissions({
    formId,
    page,
    perPage
  }) {
    return this.httpRequest.request({
      method: "GET",
      url: "/forms/{form_id}/submissions",
      path: {
        "form_id": formId
      },
      query: {
        "page": page,
        "per_page": perPage
      }
    });
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  listFormSubmission({
    submissionId,
    query,
    page,
    perPage
  }) {
    return this.httpRequest.request({
      method: "GET",
      url: "/submissions/{submission_id}",
      path: {
        "submission_id": submissionId
      },
      query: {
        "query": query,
        "page": page,
        "per_page": perPage
      }
    });
  }
  /**
   * @returns any error
   * @throws ApiError
   */
  deleteSubmission({
    submissionId
  }) {
    return this.httpRequest.request({
      method: "DELETE",
      url: "/submissions/{submission_id}",
      path: {
        "submission_id": submissionId
      }
    });
  }
};

// publish/netlify/api/services/TicketService.ts
var TicketService = class {
  constructor(httpRequest) {
    this.httpRequest = httpRequest;
  }
  /**
   * @returns any error
   * @throws ApiError
   */
  createTicket({
    clientId
  }) {
    return this.httpRequest.request({
      method: "POST",
      url: "/oauth/tickets",
      query: {
        "client_id": clientId
      }
    });
  }
  /**
   * @returns any ok
   * @throws ApiError
   */
  showTicket({
    ticketId
  }) {
    return this.httpRequest.request({
      method: "GET",
      url: "/oauth/tickets/{ticket_id}",
      path: {
        "ticket_id": ticketId
      }
    });
  }
};

// publish/netlify/api/services/UserService.ts
var UserService = class {
  constructor(httpRequest) {
    this.httpRequest = httpRequest;
  }
  /**
   * @returns any OK
   * @throws ApiError
   */
  getCurrentUser() {
    return this.httpRequest.request({
      method: "GET",
      url: "/user"
    });
  }
};

// publish/netlify/api/services/XInternalService.ts
var XInternalService = class {
  constructor(httpRequest) {
    this.httpRequest = httpRequest;
  }
  /**
   * This is an internal-only endpoint.
   * @returns any OK
   * @throws ApiError
   */
  updatePlugin({
    siteId,
    _package,
    pluginParams
  }) {
    return this.httpRequest.request({
      method: "PUT",
      url: "/sites/{site_id}/plugins/{package}",
      path: {
        "site_id": siteId,
        "package": _package
      },
      body: pluginParams
    });
  }
  /**
   * This is an internal-only endpoint.
   * @returns any OK
   * @throws ApiError
   */
  getLatestPluginRuns({
    siteId,
    packages,
    state: state2
  }) {
    return this.httpRequest.request({
      method: "GET",
      url: "/sites/{site_id}/plugin_runs/latest",
      path: {
        "site_id": siteId
      },
      query: {
        "packages": packages,
        "state": state2
      }
    });
  }
  /**
   * This is an internal-only endpoint.
   * @returns any error
   * @throws ApiError
   */
  createPluginRun({
    deployId,
    pluginRun
  }) {
    return this.httpRequest.request({
      method: "POST",
      url: "/deploys/{deploy_id}/plugin_runs",
      path: {
        "deploy_id": deployId
      },
      body: pluginRun
    });
  }
};

// publish/netlify/api/NetlifyClient.ts
var NetlifyClient = class {
  accessToken;
  accountMembership;
  accountType;
  asset;
  assetPublicSignature;
  auditLog;
  build;
  buildHook;
  buildLogMsg;
  deploy;
  deployedBranch;
  deployKey;
  dnsZone;
  file;
  form;
  function;
  hook;
  hookType;
  member;
  metadata;
  paymentMethod;
  service;
  serviceInstance;
  site;
  sniCertificate;
  snippet;
  splitTest;
  submission;
  ticket;
  user;
  xInternal;
  request;
  constructor(config2, HttpRequest = FetchHttpRequest) {
    this.request = new HttpRequest({
      BASE: config2?.BASE ?? "https://api.netlify.com/api/v1",
      VERSION: config2?.VERSION ?? "2.9.0",
      WITH_CREDENTIALS: config2?.WITH_CREDENTIALS ?? false,
      CREDENTIALS: config2?.CREDENTIALS ?? "include",
      TOKEN: config2?.TOKEN,
      USERNAME: config2?.USERNAME,
      PASSWORD: config2?.PASSWORD,
      HEADERS: config2?.HEADERS,
      ENCODE_PATH: config2?.ENCODE_PATH
    });
    this.accessToken = new AccessTokenService(this.request);
    this.accountMembership = new AccountMembershipService(this.request);
    this.accountType = new AccountTypeService(this.request);
    this.asset = new AssetService(this.request);
    this.assetPublicSignature = new AssetPublicSignatureService(this.request);
    this.auditLog = new AuditLogService(this.request);
    this.build = new BuildService(this.request);
    this.buildHook = new BuildHookService(this.request);
    this.buildLogMsg = new BuildLogMsgService(this.request);
    this.deploy = new DeployService(this.request);
    this.deployedBranch = new DeployedBranchService(this.request);
    this.deployKey = new DeployKeyService(this.request);
    this.dnsZone = new DnsZoneService(this.request);
    this.file = new FileService(this.request);
    this.form = new FormService(this.request);
    this.function = new FunctionService(this.request);
    this.hook = new HookService(this.request);
    this.hookType = new HookTypeService(this.request);
    this.member = new MemberService(this.request);
    this.metadata = new MetadataService(this.request);
    this.paymentMethod = new PaymentMethodService(this.request);
    this.service = new ServiceService(this.request);
    this.serviceInstance = new ServiceInstanceService(this.request);
    this.site = new SiteService(this.request);
    this.sniCertificate = new SniCertificateService(this.request);
    this.snippet = new SnippetService(this.request);
    this.splitTest = new SplitTestService(this.request);
    this.submission = new SubmissionService(this.request);
    this.ticket = new TicketService(this.request);
    this.user = new UserService(this.request);
    this.xInternal = new XInternalService(this.request);
  }
};

// publish/netlify/api/models/accountSetup.ts
var accountSetup;
((accountSetup2) => {
  let period;
  ((period2) => {
    period2["MONTHLY"] = "monthly";
    period2["YEARLY"] = "yearly";
  })(period = accountSetup2.period || (accountSetup2.period = {}));
})(accountSetup || (accountSetup = {}));

// publish/common/account.ts
init_fs();
init_path();
init_log();
init_colors2();
init_platform();
init_wait();

// publish/common/data.ts
init_fs();
init_path();
init_appdirs();
init_path2();
function publishDataDir() {
  return quartoDataDir("publish");
}
function publishRecordsPath() {
  return join4(publishDataDir(), "records.json");
}
function accountsDataDir() {
  const accountsDir = join4(publishDataDir(), "accounts");
  ensureDirSync(accountsDir);
  return accountsDir;
}
async function readAccountsPublishedTo(input, provider, record) {
  const source2 = normalizePath(
    typeof input === "string" ? input : input.dir
  );
  const tokens2 = [];
  const publishRecordsFile = publishRecordsPath();
  if (existsSync2(publishRecordsFile)) {
    const records = JSON.parse(
      Deno.readTextFileSync(publishRecordsFile)
    );
    if (records[source2] && records[source2][provider.name]) {
      const publishIdentifiers = records[source2][provider.name];
      const accounts = await provider.accountTokens();
      for (const publishIdentifier of publishIdentifiers) {
        const account = accounts.find(
          (account2) => publishIdentifier === publishRecordIdentifier(record, account2)
        );
        if (account) {
          tokens2.push(account);
        }
      }
    }
  }
  return tokens2;
}
function writePublishRecord(source2, provider, account, record) {
  source2 = normalizePath(source2);
  const publishRecordsFile = publishRecordsPath();
  const publishRecords = existsSync2(publishRecordsFile) ? JSON.parse(Deno.readTextFileSync(publishRecordsFile)) : {};
  if (!publishRecords[source2]) {
    publishRecords[source2] = {
      [provider]: []
    };
  }
  if (!publishRecords[source2][provider]) {
    publishRecords[source2][provider] = [];
  }
  const publishedTo = publishRecordIdentifier(record, account);
  if (!publishRecords[source2][provider].includes(publishedTo)) {
    publishRecords[source2][provider].push(publishedTo);
  }
  Deno.writeTextFileSync(
    publishRecordsFile,
    JSON.stringify(publishRecords, void 0, 2)
  );
}
function publishRecordIdentifier(record, account) {
  return `${record.id}/${account?.server ? account.server + "/" : ""}${account?.name || ""}`;
}

// publish/common/account.ts
async function authorizeAccessToken(handler) {
  const ticket = await handler.createTicket();
  const ticketUrl = handler.authorizationUrl(ticket);
  if (isServerSession()) {
    info(
      "Please authorize by opening this url: " + underline2(ticketUrl)
    );
  } else {
    await openUrl(handler.authorizationUrl(ticket));
  }
  let authorizedTicket;
  const checkTicket = async () => {
    const t5 = await handler.checkTicket(ticket);
    if (t5.authorized) {
      authorizedTicket = t5;
    }
    return Boolean(t5.authorized);
  };
  const pollingStart = Date.now();
  const kPollingTimeout = 60 * 1e3;
  const kPollingInterval = 500;
  while (Date.now() - pollingStart < kPollingTimeout) {
    if (await checkTicket()) {
      break;
    }
    await sleep2(kPollingInterval);
  }
  if (authorizedTicket) {
    const accessToken = await handler.exchangeTicket(authorizedTicket);
    writeAccessToken(handler.name, accessToken, handler.compareTokens);
    return accessToken;
  } else {
    return void 0;
  }
}
function readAccessTokens(provider) {
  const tokenPath2 = accessTokensPath(provider);
  if (existsSync2(tokenPath2)) {
    const tokens2 = JSON.parse(Deno.readTextFileSync(tokenPath2));
    return tokens2;
  } else {
    return void 0;
  }
}
function writeAccessTokens(provider, tokens2) {
  const tokensPath = accessTokensPath(provider);
  Deno.writeTextFileSync(
    tokensPath,
    JSON.stringify(tokens2, void 0, 2)
  );
  if (!isWindows4) {
    Deno.chmod(tokensPath, 384);
  }
}
function writeAccessToken(provider, token, compareTokens) {
  let writeTokens;
  writeTokens = readAccessTokens(provider) || [];
  if (compareTokens) {
    const updateIdx = writeTokens.findIndex((t5) => compareTokens(t5, token));
    if (updateIdx !== -1) {
      writeTokens[updateIdx] = token;
    } else {
      writeTokens.push(token);
    }
  } else {
    writeTokens = [token];
  }
  writeAccessTokens(provider, writeTokens);
}
function accessTokensPath(provider) {
  const dir = join4(accountsDataDir(), provider);
  ensureDirSync(dir);
  return join4(dir, "accounts.json");
}

// publish/netlify/netlify.ts
init_quarto();

// core/retry.ts
init_wait();
async function withRetry(fn, options) {
  const {
    attempts = 10,
    minWait = 1e3,
    maxWait = 4e3,
    retry = () => true
  } = options || {};
  let attempt = 0;
  while (true) {
    try {
      return fn();
    } catch (err2) {
      if (!(err2 instanceof Error)) throw err2;
      if (attempt++ >= attempts || retry && !retry(err2)) {
        throw err2;
      }
      const delay = minWait + Math.floor(Math.random() * (maxWait - minWait));
      await sleep2(delay);
    }
  }
}

// publish/common/publish.ts
init_log();
init_colors2();
init_fs();
init_path();
init_crypto();

// https://jsr.io/@std/encoding/1.0.9/_common16.ts
var alphabet3 = new TextEncoder().encode("0123456789abcdef");
var rAlphabet3 = new Uint8Array(128).fill(16);
alphabet3.forEach((byte, i6) => rAlphabet3[byte] = i6);
new TextEncoder().encode("ABCDEF").forEach((byte, i6) => rAlphabet3[byte] = i6 + 10);
function calcSizeHex(originalSize) {
  return originalSize * 2;
}
function encode4(buffer2, i6, o5, alphabet5) {
  for (; i6 < buffer2.length; ++i6) {
    const x3 = buffer2[i6];
    buffer2[o5++] = alphabet5[x3 >> 4];
    buffer2[o5++] = alphabet5[x3 & 15];
  }
  return o5;
}

// https://jsr.io/@std/encoding/1.0.9/hex.ts
init_common_detach();
var alphabet4 = new TextEncoder().encode("0123456789abcdef");
var rAlphabet4 = new Uint8Array(128).fill(16);
alphabet4.forEach((byte, i6) => rAlphabet4[byte] = i6);
new TextEncoder().encode("ABCDEF").forEach((byte, i6) => rAlphabet4[byte] = i6 + 10);
function encodeHex3(src2) {
  if (typeof src2 === "string") {
    src2 = new TextEncoder().encode(src2);
  } else if (src2 instanceof ArrayBuffer) src2 = new Uint8Array(src2).slice();
  else src2 = src2.slice();
  const [output, i6] = detach(
    src2,
    calcSizeHex(src2.length)
  );
  encode4(output, i6, 0, alphabet4);
  return new TextDecoder().decode(output);
}

// publish/common/publish.ts
init_wait();
init_path2();

// core/progress.ts
function fileProgress(files) {
  const numWidth = String(files.length).length;
  let i6 = 0;
  return {
    status: () => {
      return `[${String(i6 + 1).padStart(numWidth)}/${files.length}] ${files[i6]}`;
    },
    next: () => {
      i6++;
    }
  };
}

// publish/common/publish.ts
init_pandoc_id();
init_random();
init_copy5();
init_mime();
init_temp();
init_resources2();
init_html();
init_text2();
async function handlePublish(handler, type4, title3, slug, render2, target) {
  if (!target?.id) {
    if (handler.slugAvailable) {
      slug = await promptForSlug(type4, handler.slugAvailable, slug);
    }
    info("");
    await withSpinner({
      message: `Creating ${handler.name} ${type4}`
    }, async () => {
      const site = await handler.createSite(type4, title3, slug);
      target = {
        id: site.id,
        url: site.url,
        code: !!site.code
      };
    });
    info("");
  }
  target = target;
  const publishFiles = await renderForPublish(
    render2,
    handler.name,
    type4,
    title3,
    type4 === "site" ? target.url : void 0
  );
  const publishFilePath = (file) => {
    return join4(publishFiles.baseDir, file);
  };
  let siteDeploy;
  const files = [];
  await withSpinner({
    message: `Preparing to publish ${type4}`
  }, async () => {
    let size = 0;
    for (const file of publishFiles.files) {
      const filePath = publishFilePath(file);
      const fileBuffer = Deno.readFileSync(filePath);
      size = size + fileBuffer.byteLength;
      const sha1 = await stdCrypto.subtle.digest("SHA-1", fileBuffer);
      const encodedSha1 = encodeHex3(new Uint8Array(sha1));
      files.push([file, encodedSha1]);
    }
    const deploy = {
      files: {}
    };
    for (const file of files) {
      deploy.files[`/${pathWithForwardSlashes(file[0])}`] = file[1];
    }
    siteDeploy = await handler.createDeploy(
      target.id,
      deploy.files,
      size
    );
    while (true) {
      siteDeploy = await handler.getDeploy(siteDeploy.id);
      if (siteDeploy.state === "prepared" || siteDeploy.state === "ready") {
        break;
      }
      await sleep2(250);
    }
  });
  const required = siteDeploy?.required.map((sha1) => {
    const file = files.find((file2) => file2[1] === sha1);
    return file ? file[0] : null;
  }).filter((file) => file);
  const progress = fileProgress(required);
  await withSpinner({
    message: () => `Uploading files ${progress.status()}`,
    doneMessage: false
  }, async () => {
    for (const requiredFile of required) {
      const filePath = publishFilePath(requiredFile);
      const fileArray = Deno.readFileSync(filePath);
      await handler.uploadDeployFile(
        siteDeploy?.id,
        requiredFile,
        new Blob([fileArray.buffer])
      );
      progress.next();
    }
  });
  completeMessage(`Uploading files (complete)`);
  let targetUrl = target.url;
  let adminUrl = target.url;
  let launchUrl = target.url;
  await withSpinner({
    message: `Deploying published ${type4}`
  }, async () => {
    while (true) {
      const deployReady = await handler.getDeploy(siteDeploy?.id);
      if (deployReady.state === "ready") {
        targetUrl = deployReady.url || targetUrl;
        adminUrl = deployReady.admin_url || targetUrl;
        launchUrl = deployReady.launch_url || adminUrl;
        break;
      }
      await sleep2(500);
    }
  });
  completeMessage(`Published ${type4}: ${targetUrl}`);
  if (handler.updateAccountSite) {
    let accountSite;
    await withSpinner({
      message: `Updating account site`,
      doneMessage: false
    }, async () => {
      accountSite = await handler.updateAccountSite();
    });
    completeMessage(`Account site updated: ${accountSite.url}`);
  }
  info("");
  return [
    { ...target, url: targetUrl },
    launchUrl ? new URL(launchUrl) : void 0
  ];
}
async function renderForPublish(render2, providerName, type4, title3, siteUrl2) {
  let publishFiles = await render2({ siteUrl: siteUrl2 });
  if (type4 === "document" && !isHtmlContent(publishFiles.rootFile) && !isPdfContent(publishFiles.rootFile)) {
    throw new Error(
      `Documents published to ${providerName} must be either HTML or PDF.`
    );
  }
  if (type4 === "document") {
    publishFiles = stageDocumentPublish(title3, publishFiles);
  }
  return publishFiles;
}
function stageDocumentPublish(title3, publishFiles) {
  const publishDir = globalTempContext().createDir();
  const stagedFiles = globalThis.structuredClone(publishFiles);
  stagedFiles.baseDir = publishDir;
  for (const file of publishFiles.files) {
    const src2 = join4(publishFiles.baseDir, file);
    const target = join4(stagedFiles.baseDir, file);
    ensureDirSync(dirname4(target));
    copyTo(src2, target);
  }
  const kIndex = "index.html";
  if (isHtmlContent(publishFiles.rootFile)) {
    if (stagedFiles.rootFile !== "index.html") {
      copyTo(
        join4(stagedFiles.baseDir, stagedFiles.rootFile),
        join4(stagedFiles.baseDir, kIndex)
      );
    }
  } else if (isPdfContent(publishFiles.rootFile)) {
    const src2 = formatResourcePath("pdf", "pdfjs");
    const dest = join4(stagedFiles.baseDir, "pdfjs");
    for (const walk5 of walkSync(src2)) {
      if (walk5.isFile) {
        const destFile = join4(dest, relative4(src2, walk5.path));
        ensureDirSync(dirname4(destFile));
        copyTo(walk5.path, destFile);
        stagedFiles.files.push(relative4(stagedFiles.baseDir, destFile));
      }
    }
    const indexHtml = `<!DOCTYPE html>
<html>
<head>
<title>${encodeAttributeValue(title3)}</title>
<style type="text/css">
  body, html {
    margin: 0; padding: 0; height: 100%; overflow: hidden;
  }
</style>
</head>
<body>
<iframe id="pdf-js-viewer" src="pdfjs/web/viewer.html?file=../../${encodeAttributeValue(stagedFiles.rootFile)}" title="${encodeAttributeValue(title3)}" frameborder="0" width="100%" height="100%"></iframe>

</body>
</html>
`;
    Deno.writeTextFileSync(join4(stagedFiles.baseDir, kIndex), indexHtml);
  }
  if (!stagedFiles.files.includes(kIndex)) {
    stagedFiles.files.push(kIndex);
  }
  stagedFiles.rootFile = kIndex;
  return stagedFiles;
}
async function promptForSlug(type4, slugAvailable, slug) {
  const available = await slugAvailable(slug);
  if (!available && type4 === "document") {
    slug = slug + "-" + randomHex(4);
  }
  if (await slugAvailable(slug)) {
    const kConfirmed = "confirmed";
    const input = await Select.prompt({
      indent: "",
      message: `${typeName(type4)} name:`,
      options: [
        {
          name: slug,
          value: kConfirmed
        },
        {
          name: "Use another name...",
          value: "another"
        }
      ]
    });
    if (input === kConfirmed) {
      return slug;
    }
  }
  let hint = `The ${typeName(type4).toLowerCase()} name is included within your published URL
  (e.g. https://username.quarto.pub/${slug}/)`;
  while (true) {
    const input = await Input.prompt({
      indent: "",
      message: `Publish with name:`,
      hint,
      transform: (slug2) => gfmAutoIdentifier(slug2, false),
      validate: (slug2) => {
        if (slug2.length === 0) {
          return true;
        } else if (slug2.length < 2) {
          return `${typeName(type4)} name must be at least 2 characters.`;
        } else {
          return true;
        }
      }
    });
    hint = void 0;
    if (input.length === 0) {
      throw new Error();
    }
    if (await slugAvailable(input)) {
      return input;
    } else {
      info(
        red3(
          `  The specified name is already in use within your account.`
        )
      );
    }
  }
}
function typeName(type4) {
  return capitalizeWord(type4);
}

// publish/account.ts
init_log();
async function authorizePrompt(provider) {
  const result2 = await prompt([{
    indent: "",
    name: "confirmed",
    message: "Authorize",
    default: true,
    hint: `In order to publish to ${provider.description} you need to authorize your account.
  Please be sure you are logged into the correct ${provider.description} account in your
  default web browser, then press Enter or 'Y' to authorize.`,
    type: Confirm
  }]);
  return !!result2.confirmed;
}
async function reauthorizePrompt(provider) {
  const result2 = await prompt([{
    indent: "",
    name: "confirmed",
    message: "Re-authorize account",
    default: true,
    hint: `The authorization saved for ${provider.description} is no longer valid.
  Please be sure you are logged into the correct ${provider.description} account in your
  default web browser, then press Enter to re-authorize.`,
    type: Confirm
  }]);
  return !!result2.confirmed;
}
async function handleUnauthorized(provider, account) {
  if (account.type === 0 /* Environment */) {
    error(
      `Unable to authenticate with the provided ${account.name}. Please be sure this token is valid.`
    );
    return false;
  } else if (account.type === 1 /* Authorized */) {
    return await reauthorizePrompt(
      provider
    );
  }
}

// publish/netlify/netlify.ts
var kNetlify = "netlify";
var kNetlifyDescription = "Netlify";
var kNetlifyAuthTokenVar = "NETLIFY_AUTH_TOKEN";
var netlifyProvider = {
  name: kNetlify,
  description: kNetlifyDescription,
  requiresServer: false,
  listOriginOnly: false,
  accountTokens,
  authorizeToken,
  removeToken,
  resolveTarget,
  publish,
  isUnauthorized,
  isNotFound
};
function accountTokens() {
  const envTk = environmentAuthToken();
  const accessTkns = accessTokens();
  const accounts = [];
  if (envTk) {
    accounts.push({
      type: 0 /* Environment */,
      name: kNetlifyAuthTokenVar,
      server: null,
      token: envTk
    });
  }
  if (accessTkns) {
    for (const accessTk of accessTkns) {
      if (accessTk?.access_token) {
        accounts.push({
          type: 1 /* Authorized */,
          name: accessTk.email,
          server: null,
          token: accessTk?.access_token
        });
      }
    }
  }
  return Promise.resolve(accounts);
}
async function authorizeToken(_options) {
  if (await authorizePrompt(netlifyProvider)) {
    const token = await authorizeNetlifyAccessToken();
    if (token) {
      return {
        type: 1 /* Authorized */,
        name: token.email,
        server: null,
        token: token.access_token
      };
    }
  } else {
    return void 0;
  }
}
function removeToken(token) {
  writeAccessTokens(
    netlifyProvider.name,
    readAccessTokens(netlifyProvider.name)?.filter(
      (accessToken) => {
        return accessToken.email !== token.name;
      }
    ) || []
  );
}
function environmentAuthToken() {
  return Deno.env.get(kNetlifyAuthTokenVar);
}
function accessTokens() {
  return readAccessTokens(kNetlify);
}
async function authorizeNetlifyAccessToken() {
  const client = new NetlifyClient({});
  const clientId = (await quartoConfig.dotenv())["NETLIFY_APP_CLIENT_ID"];
  const handler = {
    name: kNetlifyDescription,
    createTicket: function() {
      return client.ticket.createTicket({
        clientId
      });
    },
    authorizationUrl: function(ticket) {
      return `https://app.netlify.com/authorize?response_type=ticket&ticket=${ticket.id}`;
    },
    checkTicket: function(ticket) {
      return client.ticket.showTicket({ ticketId: ticket.id });
    },
    exchangeTicket: function(ticket) {
      return client.accessToken.exchangeTicket({
        ticketId: ticket.id
      });
    },
    compareTokens: (a5, b3) => a5.email === b3.email
  };
  return authorizeAccessToken(handler);
}
async function resolveTarget(account, target) {
  const client = new NetlifyClient({
    TOKEN: account.token
  });
  const site = await client.site.getSite({ siteId: target.id });
  if (updateProcessingSettings(site)) {
    await client.site.updateSite({
      siteId: target.id,
      site: {
        processing_settings: {
          css: {
            bundle: false,
            minify: false
          },
          html: {
            pretty_urls: false
          },
          js: {
            bundle: false,
            minify: false
          }
        }
      }
    });
  }
  target.url = site?.ssl_url || site?.url || target.url;
  return target;
}
function updateProcessingSettings(site) {
  return site.processing_settings?.skip !== true && (site.processing_settings?.css?.bundle || site.processing_settings?.css?.minify || site.processing_settings?.html?.pretty_urls || site.processing_settings?.js?.bundle || site.processing_settings?.js?.minify);
}
function publish(account, type4, _input, title3, slug, render2, _options, target) {
  const client = new NetlifyClient({
    TOKEN: account.token
  });
  const handler = {
    name: kNetlify,
    createSite: async (_type, _title, _slug) => {
      return withSslUrl(
        await client.site.createSite({
          site: {
            force_ssl: true,
            processing_settings: {
              skip: true
            }
          }
        })
      );
    },
    createDeploy: async (siteId, files) => {
      return withSslUrl(
        await client.deploy.createSiteDeploy({
          siteId,
          deploy: {
            files,
            async: true
          }
        })
      );
    },
    getDeploy: async (deployId) => {
      return withSslUrl(
        await client.deploy.getDeploy({
          deployId
        })
      );
    },
    uploadDeployFile: async (deployId, path3, fileBody) => {
      await withRetry(async () => {
        await client.file.uploadDeployFile({
          deployId,
          path: path3,
          fileBody
        });
      });
    }
  };
  return handlePublish(
    handler,
    type4,
    title3,
    slug,
    render2,
    target
  );
}
function withSslUrl(obj) {
  return {
    ...obj,
    url: obj.ssl_url || obj.url
  };
}
function isUnauthorized(err2) {
  return err2 instanceof ApiError && err2.status === 401;
}
function isNotFound(err2) {
  return err2 instanceof ApiError && err2.status === 404;
}

// publish/gh-pages/gh-pages.ts
init_log();
init_path();
init_fs();
init_colors2();
init_path2();
init_process();
init_uuid();
init_wait();
init_url();
init_git();

// publish/common/git.ts
init_github2();
init_path();

// publish/common/errors.ts
var throwUnableToPublish = (reason, provider) => {
  throw new Error(
    `Unable to publish to ${provider} (${reason})`
  );
};

// publish/common/git.ts
async function gitHubContextForPublish(input) {
  const dir = typeof input === "string" ? dirname4(input) : input.dir;
  const context = await gitHubContext(dir);
  if (typeof input !== "string") {
    const configSiteUrl = websiteBaseurl(input?.config);
    if (configSiteUrl) {
      context.siteUrl = configSiteUrl;
    }
  }
  return context;
}
function anonymousAccount() {
  return {
    type: 2 /* Anonymous */,
    name: "anonymous",
    server: null,
    token: "anonymous"
  };
}
function verifyContext(ghContext, provider) {
  if (!ghContext.git) {
    throwUnableToPublish(
      "git does not appear to be installed on this system",
      provider
    );
  }
  if (!ghContext.repo) {
    throwUnableToPublish(
      "the target directory is not a git repository",
      provider
    );
  }
  if (!ghContext.originUrl) {
    throwUnableToPublish(
      "the git repository does not have a remote origin",
      provider
    );
  }
}

// publish/gh-pages/gh-pages.ts
init_temp();
init_project_scratch();
var kGhpages = "gh-pages";
var kGhpagesDescription = "GitHub Pages";
var ghpagesProvider = {
  name: kGhpages,
  description: kGhpagesDescription,
  requiresServer: false,
  listOriginOnly: false,
  accountTokens: accountTokens2,
  authorizeToken: authorizeToken2,
  removeToken: removeToken2,
  publishRecord,
  resolveTarget: resolveTarget2,
  publish: publish2,
  isUnauthorized: isUnauthorized2,
  isNotFound: isNotFound2
};
function accountTokens2() {
  return Promise.resolve([anonymousAccount()]);
}
async function authorizeToken2(options) {
  const ghContext = await gitHubContextForPublish(options.input);
  verifyContext(ghContext, "GitHub Pages");
  return Promise.resolve(anonymousAccount());
}
function removeToken2(_token) {
}
async function publishRecord(input) {
  const ghContext = await gitHubContextForPublish(input);
  if (ghContext.ghPagesRemote) {
    return {
      id: "gh-pages",
      url: ghContext.siteUrl || ghContext.originUrl
    };
  }
}
function resolveTarget2(_account, target) {
  return Promise.resolve(target);
}
async function publish2(_account, type4, input, title3, _slug, render2, options, target) {
  input = Deno.statSync(input).isDirectory ? input : dirname4(input);
  const version4 = await gitVersion();
  if (version4.compare("2.17.0") < 0) {
    throw new Error(
      "git version 2.17.0 or higher is required to publish to GitHub Pages"
    );
  }
  const ghContext = await gitHubContextForPublish(options.input);
  verifyContext(ghContext, "GitHub Pages");
  if (!await gitUserIdentityConfigured(input)) {
    throwUnableToPublish(
      `git user.name and/or user.email is not configured
(run 'git config user.name "Your Name"' and 'git config user.email "you@example.com"' to set them)`,
      "GitHub Pages"
    );
  }
  const createGhPagesBranchRemote = !ghContext.ghPagesRemote;
  const createGhPagesBranchLocal = !ghContext.ghPagesLocal;
  if (createGhPagesBranchRemote) {
    let confirmed = await Confirm.prompt({
      indent: "",
      message: `Publish site to ${ghContext.siteUrl || ghContext.originUrl} using gh-pages?`,
      default: true
    });
    if (confirmed && !createGhPagesBranchLocal) {
      confirmed = await Confirm.prompt({
        indent: "",
        message: `A local gh-pages branch already exists. Should it be pushed to remote 'origin'?`,
        default: true
      });
    }
    if (!confirmed) {
      throw new Error();
    }
    const stash = !await gitDirIsClean(input);
    if (stash) {
      await gitStash(input);
    }
    const oldBranch = await gitCurrentBranch(input);
    try {
      if (createGhPagesBranchLocal) {
        await gitCreateGhPages(input);
      } else {
        await gitPushGhPages(input);
      }
    } catch {
      if (createGhPagesBranchLocal && await gitBranchExists("gh-pages")) {
        await gitCmds(input, [
          ["checkout", oldBranch],
          ["branch", "-D", "gh-pages"]
        ]);
      }
      throw new Error(
        "Publishing to gh-pages with `quarto publish gh-pages` failed."
      );
    } finally {
      if (await gitCurrentBranch(input) !== oldBranch) {
        await gitCmds(input, [["checkout", oldBranch]]);
      }
      if (stash) {
        await gitStashApply(input);
      }
    }
  }
  await gitCmds(input, [
    ["remote", "set-branches", "--add", "origin", "gh-pages"],
    ["fetch", "origin", "gh-pages"]
  ]);
  const renderResult = await renderForPublish(
    render2,
    "gh-pages",
    type4,
    title3,
    type4 === "site" ? target?.url : void 0
  );
  const kPublishWorktreeDir = "quarto-publish-worktree-";
  const temp = createTempContext(
    { prefix: kPublishWorktreeDir, dir: projectScratchPath(input) }
  );
  const tempDir2 = temp.baseDir;
  removeIfExists(tempDir2);
  const worktreeDir = Deno.readDirSync(projectScratchPath(input));
  for (const entry of worktreeDir) {
    if (entry.isDirectory && entry.name.startsWith(kPublishWorktreeDir)) {
      debug(
        `Cleaning up leftover worktree folder ${entry.name} from past deploys`
      );
      const worktreePath = join4(projectScratchPath(input), entry.name);
      await execProcess({
        cmd: "git",
        args: ["worktree", "remove", "--force", worktreePath],
        cwd: projectScratchPath(input)
      });
      removeIfExists(worktreePath);
    }
  }
  const deployId = shortUuid();
  debug(`Deploying from worktree ${tempDir2} with deployId ${deployId}`);
  await withWorktree(input, relative4(input, tempDir2), async () => {
    await copy(renderResult.baseDir, tempDir2, { overwrite: true });
    Deno.writeTextFileSync(join4(tempDir2, ".nojekyll"), deployId);
    await gitCmds(tempDir2, [
      ["add", "-Af", "."],
      ["commit", "--allow-empty", "-m", "Built site for gh-pages"],
      ["remote", "-v"],
      ["push", "--force", "origin", "HEAD:gh-pages"]
    ]);
  });
  temp.cleanup();
  info("");
  let notifyGhPagesBranch = false;
  let defaultSiteMatch;
  if (ghContext.siteUrl) {
    defaultSiteMatch = ghContext.siteUrl.match(
      /^https:\/\/(.+?)\.github\.io\/$/
    );
    if (defaultSiteMatch) {
      if (createGhPagesBranchRemote) {
        notifyGhPagesBranch = true;
      } else {
        try {
          const response = await fetch(ghContext.siteUrl);
          if (response.status === 404) {
            notifyGhPagesBranch = true;
          }
        } catch {
        }
      }
    }
  }
  if (!createGhPagesBranchRemote && !notifyGhPagesBranch) {
    info(yellow3(
      "NOTE: GitHub Pages sites use caching so you might need to click the refresh\nbutton within your web browser to see changes after deployment.\n"
    ));
  }
  let verified = false;
  const start = /* @__PURE__ */ new Date();
  if (options.browser && ghContext.siteUrl && !notifyGhPagesBranch) {
    await withSpinner({
      message: "Deploying gh-pages branch to website (this may take a few minutes)"
    }, async () => {
      const noJekyllUrl = joinUrl(ghContext.siteUrl, ".nojekyll");
      while (true) {
        const now = /* @__PURE__ */ new Date();
        const elapsed = now.getTime() - start.getTime();
        if (elapsed > 1e3 * 60 * 5) {
          info(yellow3(
            "Deployment took longer than 5 minutes, giving up waiting for deployment to complete"
          ));
          break;
        }
        await sleep2(2e3);
        const response = await fetch(noJekyllUrl);
        if (response.status === 200) {
          if ((await response.text()).trim() === deployId) {
            verified = true;
            await sleep2(2e3);
            break;
          }
        } else if (response.status !== 404) {
          break;
        }
      }
    });
  }
  completeMessage(`Published to ${ghContext.siteUrl || ghContext.originUrl}`);
  info("");
  if (notifyGhPagesBranch) {
    info(
      yellow3(
        "To complete publishing, change the source branch for this site to " + bold3("gh-pages") + `.

Set the source branch at: ` + underline2(
          `https://github.com/${defaultSiteMatch[1]}/${defaultSiteMatch[1]}.github.io/settings/pages`
        ) + "\n"
      )
    );
  } else if (!verified) {
    info(yellow3(
      "NOTE: GitHub Pages deployments normally take a few minutes (your site updates\nwill be visible once the deploy completes)\n"
    ));
  }
  return Promise.resolve([
    void 0,
    verified ? new URL(ghContext.siteUrl) : void 0
  ]);
}
function isUnauthorized2(_err) {
  return false;
}
function isNotFound2(_err) {
  return false;
}
async function gitStash(dir) {
  const result2 = await execProcess({
    cmd: "git",
    args: ["stash"],
    cwd: dir
  });
  if (!result2.success) {
    throw new Error();
  }
}
async function gitStashApply(dir) {
  const result2 = await execProcess({
    cmd: "git",
    args: ["stash", "apply"],
    cwd: dir
  });
  if (!result2.success) {
    throw new Error();
  }
}
async function gitDirIsClean(dir) {
  const result2 = await execProcess({
    cmd: "git",
    args: ["diff", "HEAD"],
    cwd: dir,
    stdout: "piped"
  });
  if (result2.success) {
    return result2.stdout.trim().length === 0;
  } else {
    throw new Error();
  }
}
async function gitCurrentBranch(dir) {
  const result2 = await execProcess({
    cmd: "git",
    args: ["rev-parse", "--abbrev-ref", "HEAD"],
    cwd: dir,
    stdout: "piped"
  });
  if (result2.success) {
    return result2.stdout.trim();
  } else {
    throw new Error();
  }
}
async function withWorktree(dir, siteDir, f5) {
  await execProcess({
    cmd: "git",
    args: [
      "worktree",
      "add",
      "--track",
      "-B",
      "gh-pages",
      siteDir,
      "origin/gh-pages"
    ],
    cwd: dir
  });
  await execProcess({
    cmd: "git",
    args: ["rm", "-r", "--quiet", "."],
    cwd: join4(dir, siteDir)
  });
  try {
    await f5();
  } finally {
    await execProcess({
      cmd: "git",
      args: ["worktree", "remove", "--force", siteDir],
      cwd: dir
    });
  }
}
async function gitCreateGhPages(dir) {
  await gitCmds(dir, [
    ["checkout", "--orphan", "gh-pages"],
    ["rm", "-rf", "--quiet", "."],
    ["commit", "--allow-empty", "-m", "Initializing gh-pages branch"]
  ]);
  await gitPushGhPages(dir);
}
async function gitPushGhPages(dir) {
  if (await gitCurrentBranch(dir) !== "gh-pages") {
    await gitCmds(dir, [["checkout", "gh-pages"]]);
  }
  await gitCmds(dir, [["push", "origin", "HEAD:gh-pages"]]);
}

// publish/types.ts
var ApiError2 = class extends Error {
  constructor(status, statusText, description = void 0) {
    let message = `API Error: ${status} - ${statusText}`;
    if (description) {
      message = `${message} (${description})`;
    }
    super(message);
    this.status = status;
    this.statusText = statusText;
    this.description = description;
  }
};

// publish/quarto-pub/api/index.ts
var acceptApplicationJsonHeader = {
  Accept: "application/json"
};
var contentTypeApplicationJsonHeader = {
  "Content-Type": "application/json"
};
var kUrlResolveRegex = /https:\/\/quartopub\.com\/sites\/([^\/]+)\/(.*)/;
var authorizationHeader = (token) => !token ? {} : { Authorization: `Bearer ${token}` };
var QuartoPubClient = class {
  constructor(environment, token_) {
    this.token_ = token_;
    switch (environment) {
      case "LOCAL":
        this.baseURL_ = "http://localhost:3000/api/v1";
        break;
      case "PRODUCTION":
      default:
        this.baseURL_ = "https://quartopub.com/api/v1";
        break;
    }
  }
  baseURL_;
  // Creates a ticket.
  createTicket = async (client_id) => {
    const response = await fetch(
      this.createURL(
        `tickets?${new URLSearchParams({ application_id: client_id })}`
      ),
      {
        method: "POST",
        headers: {
          ...authorizationHeader(this.token_),
          ...acceptApplicationJsonHeader
        }
      }
    );
    if (!response.ok) {
      throw new ApiError2(response.status, response.statusText);
    }
    return await response.json();
  };
  // Shows a ticket.
  showTicket = async (id) => {
    const response = await fetch(this.createURL(`tickets/${id}`), {
      method: "GET",
      headers: {
        ...authorizationHeader(this.token_),
        ...acceptApplicationJsonHeader
      }
    });
    if (!response.ok) {
      throw new ApiError2(response.status, response.statusText);
    }
    return await response.json();
  };
  // Exchanges a ticket for an access token.
  exchangeTicket = async (id) => {
    const response = await fetch(this.createURL(`tickets/${id}/exchange`), {
      method: "POST",
      headers: {
        ...authorizationHeader(this.token_),
        ...acceptApplicationJsonHeader
      }
    });
    if (!response.ok) {
      throw new ApiError2(response.status, response.statusText);
    }
    return await response.json();
  };
  // Checks if a slug is available.
  slugAvailable = async (slug) => {
    const response = await fetch(this.createURL(`slugs/${slug}`), {
      method: "HEAD",
      headers: {
        ...authorizationHeader(this.token_)
      }
    });
    if (response.ok) {
      return false;
    }
    if (response.status == 404) {
      return true;
    }
    throw new ApiError2(response.status, response.statusText);
  };
  // Creates a site.
  createSite = async (type4, title3, slug) => {
    const response = await fetch(this.createURL("sites"), {
      method: "POST",
      headers: {
        ...authorizationHeader(this.token_),
        ...acceptApplicationJsonHeader
      },
      body: new URLSearchParams({ type: type4, title: title3, slug })
    });
    if (!response.ok) {
      throw new ApiError2(response.status, response.statusText);
    }
    const site = await response.json();
    site.url = this.resolveUrl(site.url);
    return site;
  };
  // Creates a site deploy.
  createDeploy = async (siteId, files, size) => {
    const response = await fetch(
      this.createURL(`sites/${siteId}/deploys`),
      {
        method: "POST",
        headers: {
          ...authorizationHeader(this.token_),
          ...acceptApplicationJsonHeader,
          ...contentTypeApplicationJsonHeader
        },
        body: JSON.stringify({
          size,
          files
        })
        // body: JSON.stringify(files),
      }
    );
    if (!response.ok) {
      const description = await descriptionFromErrorResponse(response);
      throw new ApiError2(response.status, description || response.statusText);
    }
    const deploy = await response.json();
    deploy.url = this.resolveUrl(deploy.url);
    return deploy;
  };
  // Gets a deploy.
  getDeploy = async (deployId) => {
    const response = await fetch(this.createURL(`deploys/${deployId}`), {
      method: "GET",
      headers: {
        ...authorizationHeader(this.token_),
        ...acceptApplicationJsonHeader
      }
    });
    if (!response.ok) {
      throw new ApiError2(response.status, response.statusText);
    }
    const deploy = await response.json();
    deploy.url = this.resolveUrl(deploy.url);
    return deploy;
  };
  // Uploads a deploy file.
  uploadDeployFile = async (deployId, path3, fileBody) => {
    const response = await fetch(
      this.createURL(`deploys/${deployId}/files/${path3}`),
      {
        method: "PUT",
        headers: {
          ...authorizationHeader(this.token_)
        },
        body: fileBody
      }
    );
    if (!response.ok) {
      throw new ApiError2(response.status, response.statusText);
    }
  };
  // Updates the account site.
  updateAccountSite = async () => {
    const response = await fetch(this.createURL("update-account-site"), {
      method: "PUT",
      headers: {
        ...authorizationHeader(this.token_),
        ...acceptApplicationJsonHeader
      }
    });
    if (!response.ok) {
      throw new ApiError2(response.status, response.statusText);
    }
    return await response.json();
  };
  // Creates a URL.
  createURL = (path3) => `${this.baseURL_}/${path3}`;
  // Resolve the URL into a form that can be used to address resources
  // (not just the root redirect). For example this form allows
  // social metadata cards to properly form links to images, and so on.
  resolveUrl = (url) => {
    const match = url.match(kUrlResolveRegex);
    if (match) {
      return `https://${match[1]}.quarto.pub/${match[2]}`;
    } else {
      return url;
    }
  };
};
async function descriptionFromErrorResponse(response) {
  if (response.body) {
    try {
      const result2 = await response.json();
      if (typeof result2.description === "string") {
        return result2.description;
      }
    } catch {
    }
  }
}

// publish/quarto-pub/quarto-pub.ts
init_quarto();
var kQuartoPub = "quarto-pub";
var kQuartoPubAuthTokenVar = "QUARTO_PUB_AUTH_TOKEN";
var quartoPubProvider = {
  name: kQuartoPub,
  description: "Quarto Pub",
  requiresServer: false,
  listOriginOnly: false,
  accountTokens: accountTokens3,
  authorizeToken: authorizeToken3,
  removeToken: removeToken3,
  resolveTarget: resolveTarget3,
  publish: publish3,
  isUnauthorized: isUnauthorized3,
  isNotFound: isNotFound3
};
function accountTokens3() {
  const envTk = environmentAuthToken2();
  const accessTks = readAccessTokens(quartoPubProvider.name);
  const accounts = [];
  if (envTk) {
    accounts.push({
      type: 0 /* Environment */,
      name: kQuartoPubAuthTokenVar,
      server: null,
      token: envTk
    });
  }
  if (accessTks) {
    for (const accessTk of accessTks) {
      accounts.push({
        type: 1 /* Authorized */,
        name: accessTk.email,
        server: null,
        token: accessTk.application_token
      });
    }
  }
  return Promise.resolve(accounts);
}
async function authorizeToken3(_options) {
  if (await authorizePrompt(quartoPubProvider)) {
    const token = await authorizeQuartoPubAccessToken();
    if (token) {
      return {
        type: 1 /* Authorized */,
        name: token.email,
        server: null,
        token: token.application_token
      };
    } else {
      return void 0;
    }
  }
}
function removeToken3(token) {
  writeAccessTokens(
    quartoPubProvider.name,
    readAccessTokens(quartoPubProvider.name)?.filter(
      (accessToken) => {
        return accessToken.email !== token.name;
      }
    ) || []
  );
}
var dotenvConfig2 = await quartoConfig.dotenv();
var quartoPubEnvironment = dotenvConfig2["QUARTO_PUB_ENVIRONMENT"];
function environmentAuthToken2() {
  return Deno.env.get(kQuartoPubAuthTokenVar);
}
function authorizeQuartoPubAccessToken() {
  const client = new QuartoPubClient(quartoPubEnvironment);
  const provider = {
    name: kQuartoPub,
    createTicket: () => client.createTicket(dotenvConfig2["QUARTO_PUB_APP_CLIENT_ID"]),
    authorizationUrl: (ticket) => ticket.authorization_url,
    checkTicket: (ticket) => client.showTicket(ticket.id),
    exchangeTicket: (ticket) => client.exchangeTicket(ticket.id),
    compareTokens: (a5, b3) => a5.account_identifier === b3.account_identifier
  };
  return authorizeAccessToken(provider);
}
function resolveTarget3(_account, target) {
  return Promise.resolve(target);
}
function publish3(accountToken, type4, _input, title3, slug, render2, _options, target) {
  const client = new QuartoPubClient(quartoPubEnvironment, accountToken.token);
  const handler = {
    name: kQuartoPub,
    slugAvailable: (slug2) => client.slugAvailable(slug2),
    createSite: (type5, title4, slug2) => client.createSite(type5, title4, slug2),
    createDeploy: (siteId, files, size) => client.createDeploy(siteId, files, size),
    getDeploy: (deployId) => client.getDeploy(deployId),
    uploadDeployFile: (deployId, path3, fileBody) => client.uploadDeployFile(deployId, path3, fileBody),
    updateAccountSite: () => client.updateAccountSite()
  };
  return handlePublish(handler, type4, title3, slug, render2, target);
}
function isUnauthorized3(err2) {
  return err2 instanceof ApiError2 && err2.status === 401;
}
function isNotFound3(err2) {
  return err2 instanceof ApiError2 && err2.status === 404;
}

// publish/rsconnect/rsconnect.ts
init_log();
init_colors2();

// https://deno.land/x/another_cookiejar@v5.0.3/cookie.ts
var CONTROL_CHARS = /[\x00-\x1F\x7F]/;
var COOKIE_NAME_BLOCKED = /[()<>@,;:\\"/[\]?={}]/;
var COOKIE_OCTET_BLOCKED = /[\s",;\\]/;
var COOKIE_OCTET = /^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]+$/;
var TERMINATORS = ["\n", "\r", "\0"];
function isSameDomainOrSubdomain(domainA, domainB) {
  if (!domainA || !domainB) {
    return false;
  }
  let longerDomain;
  let shorterDomain;
  if (domainB.length > domainA.length) {
    longerDomain = domainB;
    shorterDomain = domainA;
  } else {
    longerDomain = domainA;
    shorterDomain = domainB;
  }
  const indexOfDomain = longerDomain.indexOf(shorterDomain);
  if (indexOfDomain === -1) {
    return false;
  } else if (indexOfDomain > 0) {
    if (longerDomain.charAt(indexOfDomain - 1) !== ".") {
      return false;
    }
  }
  return true;
}
function trimTerminator(str3) {
  if (str3 === void 0 || str3 === "") return str3;
  for (let t5 = 0; t5 < TERMINATORS.length; t5++) {
    const terminatorIdx = str3.indexOf(TERMINATORS[t5]);
    if (terminatorIdx !== -1) {
      str3 = str3.substr(0, terminatorIdx);
    }
  }
  return str3;
}
function isValidName(name2) {
  if (!name2) {
    return false;
  }
  if (CONTROL_CHARS.test(name2) || COOKIE_NAME_BLOCKED.test(name2)) {
    return false;
  }
  return true;
}
function trimWrappingDoubleQuotes(val) {
  if (val.length >= 2 && val.at(0) === '"' && val.at(-1) === '"') {
    return val.slice(1, -1);
  }
  return val;
}
function isValidValue(val) {
  if (val === "") {
    return true;
  }
  if (!val) {
    return false;
  }
  if (CONTROL_CHARS.test(val) || COOKIE_OCTET_BLOCKED.test(val) || !COOKIE_OCTET.test(val)) {
    return false;
  }
  return true;
}
function parseURL(input) {
  let copyUrl;
  if (input instanceof Request) {
    copyUrl = input.url;
  } else if (input instanceof URL) {
    copyUrl = input.toString();
  } else {
    copyUrl = input;
  }
  copyUrl = copyUrl.replace(/^\./, "");
  if (!copyUrl.includes("://")) {
    copyUrl = "http://" + copyUrl;
  }
  return new URL(copyUrl);
}
var Cookie = class _Cookie {
  // important
  name;
  value;
  path;
  domain;
  // expire
  /** in milliseconds */
  expires;
  /** in seconds */
  maxAge;
  // other
  secure;
  httpOnly;
  sameSite;
  creationDate = Date.now();
  // deno-lint-ignore ban-ts-comment
  // @ts-ignore
  creationIndex;
  static cookiesCreated = 0;
  constructor(options) {
    if (options) {
      this.name = options.name;
      this.value = options.value;
      this.path = options.path;
      this.domain = options.domain;
      this.expires = options.expires;
      this.maxAge = options.maxAge;
      this.secure = options.secure;
      this.httpOnly = options.httpOnly;
      this.sameSite = options.sameSite;
      if (options.creationDate) {
        this.creationDate = options.creationDate;
      }
    }
    Object.defineProperty(this, "creationIndex", {
      configurable: false,
      enumerable: false,
      // important for assertStrictEquals checks
      writable: true,
      value: ++_Cookie.cookiesCreated
    });
  }
  static from(cookieStr) {
    const options = {
      name: void 0,
      value: void 0,
      path: void 0,
      domain: void 0,
      expires: void 0,
      maxAge: void 0,
      secure: void 0,
      httpOnly: void 0,
      sameSite: void 0,
      creationDate: Date.now()
    };
    const unparsed = cookieStr.slice().trim();
    const attrAndValueList = unparsed.split(";");
    const keyValuePairString = trimTerminator(attrAndValueList.shift() || "").trim();
    const keyValuePairEqualsIndex = keyValuePairString.indexOf("=");
    if (keyValuePairEqualsIndex < 0) {
      return new _Cookie();
    }
    const name2 = keyValuePairString.slice(0, keyValuePairEqualsIndex);
    const value = trimWrappingDoubleQuotes(
      keyValuePairString.slice(keyValuePairEqualsIndex + 1)
    );
    if (!(isValidName(name2) && isValidValue(value))) {
      return new _Cookie();
    }
    options.name = name2;
    options.value = value;
    while (attrAndValueList.length) {
      const cookieAV = attrAndValueList.shift()?.trim();
      if (!cookieAV) {
        continue;
      }
      const avSeperatorIndex = cookieAV.indexOf("=");
      let attrKey, attrValue;
      if (avSeperatorIndex === -1) {
        attrKey = cookieAV;
        attrValue = "";
      } else {
        attrKey = cookieAV.substr(0, avSeperatorIndex);
        attrValue = cookieAV.substr(avSeperatorIndex + 1);
      }
      attrKey = attrKey.trim().toLowerCase();
      if (attrValue) {
        attrValue = attrValue.trim();
      }
      switch (attrKey) {
        case "expires":
          if (attrValue) {
            const expires = new Date(attrValue).getTime();
            if (expires && !isNaN(expires)) {
              options.expires = expires;
            }
          }
          break;
        case "max-age":
          if (attrValue) {
            const maxAge = parseInt(attrValue, 10);
            if (!isNaN(maxAge)) {
              options.maxAge = maxAge;
            }
          }
          break;
        case "domain":
          if (attrValue) {
            const domain2 = parseURL(attrValue).hostname;
            if (domain2) {
              options.domain = domain2;
            }
          }
          break;
        case "path":
          if (attrValue) {
            options.path = attrValue.startsWith("/") ? attrValue : "/" + attrValue;
          }
          break;
        case "secure":
          options.secure = true;
          break;
        case "httponly":
          options.httpOnly = true;
          break;
        case "samesite": {
          const lowerCasedSameSite = attrValue.toLowerCase();
          switch (lowerCasedSameSite) {
            case "strict":
              options.sameSite = "Strict";
              break;
            case "lax":
              options.sameSite = "Lax";
              break;
            case "none":
              options.sameSite = "None";
              break;
            default:
              break;
          }
          break;
        }
        // unknown attribute
        default:
          break;
      }
    }
    return new _Cookie(options);
  }
  isValid() {
    return isValidName(this.name) && isValidValue(this.value);
  }
  /**
   * @param url - the url that we are checking against
   */
  canSendTo(url) {
    const urlObj = parseURL(url);
    if (this.secure && urlObj.protocol !== "https:") {
      return false;
    }
    if (this.sameSite === "None" && !this.secure) return false;
    if (this.path) {
      if (this.path === urlObj.pathname) {
        return true;
      }
      if (urlObj.pathname.startsWith(this.path) && this.path[this.path.length - 1] === "/") {
        return true;
      }
      if (this.path.length < urlObj.pathname.length && urlObj.pathname.startsWith(this.path) && urlObj.pathname[this.path.length] === "/") {
        return true;
      }
      return false;
    }
    if (this.domain) {
      const hostname = urlObj.hostname;
      if (isSameDomainOrSubdomain(this.domain, hostname)) {
        return true;
      }
    }
    return false;
  }
  getCookieString() {
    return `${this.name || ""}=${this.value || ""}`;
  }
  setDomain(url) {
    this.domain = parseURL(url).hostname;
  }
  setPath(url) {
    const uriPath = parseURL(url).pathname;
    if (!uriPath || uriPath[0] !== "/") {
      this.path = "/";
    } else {
      const rightmostSlashIdx = uriPath.lastIndexOf("/");
      if (rightmostSlashIdx <= 0) {
        this.path = "/";
      } else {
        this.path = uriPath.slice(0, rightmostSlashIdx);
      }
    }
  }
  setExpires(exp) {
    if (exp instanceof Date) {
      this.expires = exp.getTime();
    } else if (typeof exp === "number" && exp >= 0) {
      this.expires = exp;
    }
  }
  isExpired() {
    if (this.maxAge !== void 0) {
      if (Date.now() - this.creationDate >= this.maxAge * 1e3) {
        return true;
      }
    }
    if (this.expires !== void 0) {
      if (Date.now() - this.expires >= 0) {
        return true;
      }
    }
    return false;
  }
  toString() {
    let str3 = this.getCookieString();
    if (this.expires && this.expires !== Infinity) {
      str3 += "; Expires=" + new Date(this.expires).toUTCString();
    }
    if (this.maxAge && this.maxAge !== Infinity) {
      str3 += `; Max-Age=${this.maxAge}`;
    }
    if (this.domain) {
      str3 += `; Domain=${this.domain}`;
    }
    if (this.path) {
      str3 += `; Path=${this.path}`;
    }
    if (this.secure) {
      str3 += "; Secure";
    }
    if (this.httpOnly) {
      str3 += "; HttpOnly";
    }
    if (this.sameSite) {
      str3 += `; SameSite=${this.sameSite}`;
    }
    return str3;
  }
  clone() {
    return new _Cookie(JSON.parse(JSON.stringify(this)));
  }
};

// https://deno.land/x/another_cookiejar@v5.0.3/cookie_jar.ts
var strictMatchProps = [
  "value",
  "secure",
  "httpOnly",
  "maxAge",
  "expires",
  "sameSite"
];
function cookieMatches(options, comparedWith, strictMatch = false) {
  if (options.path !== void 0 && !comparedWith.path?.startsWith(options.path)) {
    return false;
  }
  if (options.domain) {
    if (!isSameDomainOrSubdomain(options.domain, comparedWith.domain)) {
      return false;
    }
  }
  if (options.name !== void 0 && options.name !== comparedWith.name) {
    return false;
  }
  if (strictMatch && strictMatchProps.some(
    (propKey) => (
      // deno-lint-ignore ban-ts-comment
      // @ts-ignore
      options[propKey] !== void 0 && // deno-lint-ignore ban-ts-comment
      // @ts-ignore
      options[propKey] !== comparedWith[propKey]
    )
  )) {
    return false;
  }
  return true;
}
var MAX_TIME = 2147483647e3;
function cookieCompare(a5, b3) {
  let cmp2 = 0;
  const aPathLen = a5.path?.length || 0;
  const bPathLen = b3.path?.length || 0;
  cmp2 = bPathLen - aPathLen;
  if (cmp2 !== 0) {
    return cmp2;
  }
  const aTime = a5.creationDate || MAX_TIME;
  const bTime = b3.creationDate || MAX_TIME;
  cmp2 = aTime - bTime;
  if (cmp2 !== 0) {
    return cmp2;
  }
  cmp2 = a5.creationIndex - b3.creationIndex;
  return cmp2;
}
var CookieJar = class {
  cookies = Array();
  /**
   * @param cookies - the cookies array to initialize with
   */
  constructor(cookies) {
    this.replaceCookies(cookies);
  }
  /**
   * Sets or replaces a cookie inside the jar.
   * Only sets new cookies if cookie is valid and not expired.
   * Validation and expiration checks are not run when replacing a cookie.
   * @param url - the url that this cookie from received from. mainly used by the fetch wrapper.
   *              will automatically set domain and path if provided and it was not found inside Cookie/cookiestring.
   */
  setCookie(cookie, url) {
    let cookieObj;
    if (typeof cookie === "string") {
      cookieObj = Cookie.from(cookie);
    } else {
      cookieObj = cookie;
    }
    if (url) {
      if (!cookieObj.domain) {
        cookieObj.setDomain(url);
      }
      if (!cookieObj.path) {
        cookieObj.setPath(url);
      }
    }
    if (!cookieObj.isValid()) {
      return;
    }
    const foundCookie = this.getCookie(cookieObj);
    if (foundCookie) {
      const indexOfCookie = this.cookies.indexOf(foundCookie);
      if (!cookieObj.isExpired()) {
        this.cookies.splice(indexOfCookie, 1, cookieObj);
      } else {
        this.cookies.splice(indexOfCookie, 1);
      }
    } else if (!cookieObj.isExpired()) {
      this.cookies.push(cookieObj);
    }
    this.cookies.sort(cookieCompare);
  }
  /**
   * Gets the first cooking matching the defined properties of a given Cookie or CookieOptions.
   * returns undefined if not found or expired. `creationDate` prop is not checked.
   * Also removes the cookie and returns undefined if cookie is expired.
   */
  getCookie(options) {
    const strictMatch = typeof options.isValid !== "function";
    for (const [index2, cookie] of this.cookies.entries()) {
      if (cookieMatches(options, cookie, strictMatch)) {
        if (!cookie.isExpired()) {
          return cookie;
        } else {
          this.cookies.splice(index2, 1);
          return void 0;
        }
      }
    }
  }
  /**
   * Returns cookies that match the options excluding expired ones, also removes expired cookies before returning.
   * @param options - the options to filter cookies with, and if not provided, returnes all cookies.
   *  if no cookie is found with given options, an empty array is returned.
   */
  getCookies(options) {
    if (options) {
      const matchedCookies = [];
      const removeCookies = [];
      for (const cookie of this.cookies) {
        if (cookieMatches(options, cookie)) {
          if (!cookie.isExpired()) {
            matchedCookies.push(cookie);
          } else {
            removeCookies.push(cookie);
          }
        }
      }
      if (removeCookies.length) {
        this.cookies = this.cookies.filter(
          (cookie) => !removeCookies.includes(cookie)
        );
      }
      return matchedCookies;
    } else {
      return this.cookies;
    }
  }
  /**
   * Converts the cookies to a string that can be used in a request.
   * @param url - the url to get the cookies for. if provided, will only return cookies that match the domain and path of the url.
   * @returns string of all cookies that match the url, in the from of `<cookie-name>=<cookie-value>` seperated by `; `
   */
  getCookieString(url) {
    const searchCookie = new Cookie();
    searchCookie.setDomain(url);
    const cookiesToSend = this.getCookies(searchCookie).filter((cookie) => {
      return cookie.canSendTo(parseURL(url));
    }).map((c6) => c6.getCookieString()).join("; ");
    return cookiesToSend;
  }
  toJSON() {
    return this.cookies;
  }
  /**
   * Removes first cookie that matches the given option.
   *
   * Returns the deleted cookie if found or undefined otherwise.
   */
  removeCookie(options) {
    for (const [index2, cookie] of this.cookies.entries()) {
      if (cookieMatches(options, cookie)) {
        return this.cookies.splice(index2, 1)[0];
      }
    }
  }
  /**
   * Removes all cookies that matches the given option.
   * If options is not given, all cookies will be deleted.
   *
   * Returns the deleted cookies if found or undefined otherwise.
   */
  removeCookies(options) {
    if (options) {
      const deletedCookies = [];
      this.cookies = this.cookies.filter((cookie) => {
        if (cookieMatches(options, cookie)) {
          deletedCookies.push(cookie);
          return false;
        }
        return true;
      });
      return deletedCookies.length ? deletedCookies : void 0;
    } else {
      this.cookies = [];
    }
  }
  replaceCookies(cookies) {
    if (cookies?.length) {
      if (typeof cookies[0].isValid === "function") {
        this.cookies = cookies;
      } else {
        this.cookies = [];
        for (const option of cookies) {
          this.cookies.push(new Cookie(option));
        }
      }
    } else {
      this.cookies = [];
    }
  }
};

// https://deno.land/x/another_cookiejar@v5.0.3/fetch_wrapper.ts
var MAX_REDIRECT = 20;
var redirectStatus = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
function isRedirect(status) {
  return redirectStatus.has(status);
}
function isDomainOrSubdomain(destination, original) {
  const orig = new URL(original).hostname;
  const dest = new URL(destination).hostname;
  return orig === dest || orig.endsWith(`.${dest}`);
}
function wrapFetch(options) {
  const { cookieJar = new CookieJar(), fetch: fetch3 = globalThis.fetch } = options || {};
  async function wrappedFetch(input, init5) {
    if (!input) {
      return await fetch3(input);
    }
    const cookieString = cookieJar.getCookieString(input);
    let originalRedirectOption;
    const originalRequestUrl = input.url || input.toString();
    if (input instanceof Request) {
      originalRedirectOption = input.redirect;
    }
    if (init5?.redirect) {
      originalRedirectOption = init5?.redirect;
    }
    const interceptedInit = {
      ...init5,
      redirect: "manual"
    };
    const reqHeaders = new Headers(input.headers || {});
    if (init5?.headers) {
      new Headers(init5.headers).forEach((value, key) => {
        reqHeaders.set(key, value);
      });
    }
    reqHeaders.set("cookie", cookieString);
    reqHeaders.delete("cookie2");
    interceptedInit.headers = reqHeaders;
    const response = await fetch3(input, interceptedInit);
    response.headers.forEach((value, key) => {
      if (key.toLowerCase() === "set-cookie") {
        cookieJar.setCookie(value, response.url);
      }
    });
    const redirectCount = interceptedInit.redirectCount ?? 0;
    const redirectUrl = response.headers.has("location") ? new URL(
      response.headers.get("location").toString(),
      originalRequestUrl
    ).toString() : void 0;
    if (redirectCount > 0) {
      Object.defineProperty(response, "redirected", { value: true });
    }
    if (
      // Return if response is not redirect
      !isRedirect(response.status) || //  or location is not set
      !redirectUrl || // or if it's the first request and request.redirect is set to 'manual'
      redirectCount === 0 && originalRedirectOption === "manual"
    ) {
      return response;
    }
    if (originalRedirectOption === "error") {
      await response.body?.cancel();
      throw new TypeError(
        `URI requested responded with a redirect and redirect mode is set to error: ${response.url}`
      );
    }
    if (redirectCount >= MAX_REDIRECT) {
      await response.body?.cancel();
      throw new TypeError(
        `Reached maximum redirect of ${MAX_REDIRECT} for URL: ${response.url}`
      );
    }
    await response.body?.cancel();
    interceptedInit.redirectCount = redirectCount + 1;
    const filteredHeaders = new Headers(interceptedInit.headers);
    if (!isDomainOrSubdomain(originalRequestUrl, redirectUrl)) {
      for (const name2 of ["authorization", "www-authenticate"]) {
        filteredHeaders.delete(name2);
      }
    }
    if (interceptedInit.method === "POST") {
      filteredHeaders.delete("content-length");
      interceptedInit.method = "GET";
      interceptedInit.body = void 0;
    }
    interceptedInit.headers = filteredHeaders;
    return await wrappedFetch(redirectUrl, interceptedInit);
  }
  return wrappedFetch;
}

// publish/rsconnect/api/index.ts
init_url();
var fetch2 = wrapFetch();
var RSConnectClient = class {
  constructor(server_, key_) {
    this.server_ = server_;
    this.key_ = key_;
    this.server_ = ensureProtocolAndTrailingSlash(this.server_);
  }
  getUser() {
    return this.get("user");
  }
  createContent(name2, title3) {
    return this.post("content", JSON.stringify({ name: name2, title: title3 }));
  }
  getContent(guid) {
    return this.get(`content/${guid}`);
  }
  uploadBundle(guid, fileBody) {
    return this.post(`content/${guid}/bundles`, fileBody);
  }
  deployBundle(bundle2) {
    return this.post(
      `content/${bundle2.content_guid}/deploy`,
      JSON.stringify({ bundle_id: bundle2.id })
    );
  }
  getTaskStatus(task) {
    return this.get(
      `tasks/${task.task_id}?${new URLSearchParams({ wait: "1" })}`
    );
  }
  get = (path3) => this.fetch("GET", path3);
  post = (path3, body) => this.fetch("POST", path3, body);
  fetch = async (method, path3, body) => {
    return this.handleResponse(
      await fetch2(this.apiUrl(path3), {
        method,
        //     credentials: "include",
        headers: {
          Accept: "application/json",
          ...authorizationHeader2(this.key_)
        },
        body
      })
    );
  };
  apiUrl = (path3) => `${this.server_}__api__/v1/${path3}`;
  handleResponse(response) {
    if (response.ok) {
      return response.json();
    } else if (response.status !== 200) {
      throw new ApiError2(response.status, response.statusText);
    } else {
      throw new Error(`${response.status} - ${response.statusText}`);
    }
  }
  cookies_ = /* @__PURE__ */ new Map();
};
var authorizationHeader2 = (key) => !key ? {} : { Authorization: `Key ${key}` };

// publish/rsconnect/rsconnect.ts
init_url();
init_temp();
init_random();

// publish/common/bundle.ts
init_path();
init_fs();
init_hash2();

// https://jsr.io/@std/tar/0.1.6/tar_stream.ts
var SLASH_CODE_POINT = "/".charCodeAt(0);
var TarStream = class {
  #readable;
  #writable;
  constructor() {
    const { readable, writable } = new TransformStream({
      transform(chunk, controller) {
        if (chunk.options) {
          try {
            assertValidTarStreamOptions(chunk.options);
          } catch (e5) {
            return controller.error(e5);
          }
        }
        if ("size" in chunk && (chunk.size < 0 || 8 ** 12 < chunk.size || chunk.size.toString() === "NaN")) {
          return controller.error(
            new RangeError(
              "Cannot add to the tar archive: The size cannot exceed 64 Gibs"
            )
          );
        }
        const path3 = parsePath(chunk.path);
        controller.enqueue({ ...chunk, path: path3 });
      }
    });
    this.#writable = writable;
    const gen = (async function* () {
      const encoder4 = new TextEncoder();
      for await (const chunk of readable) {
        const [prefix, name2] = chunk.path;
        const typeflag = "size" in chunk ? "0" : "5";
        const header = new Uint8Array(512);
        const size = "size" in chunk ? chunk.size : 0;
        const options = {
          mode: typeflag === "5" ? 493 : 420,
          uid: 0,
          gid: 0,
          mtime: Math.floor(Date.now() / 1e3),
          uname: "",
          gname: "",
          devmajor: "",
          devminor: "",
          ...chunk.options
        };
        header.set(name2);
        header.set(
          encoder4.encode(
            options.mode.toString(8).padStart(6, "0") + " \0" + // mode
            options.uid.toString(8).padStart(6, "0") + " \0" + //uid
            options.gid.toString(8).padStart(6, "0") + " \0" + // gid
            size.toString(8).padStart(size < 8 ** 11 ? 11 : 12, "0") + (size < 8 ** 11 ? " " : "") + // size
            options.mtime.toString(8).padStart(11, "0") + " " + // mtime
            " ".repeat(8) + // checksum | To be updated later
            typeflag + // typeflag
            "\0".repeat(100) + // linkname
            "ustar\x0000" + // version
            options.uname.padEnd(32, "\0") + // uname
            options.gname.padEnd(32, "\0") + // gname
            options.devmajor.padStart(8, "\0") + // devmajor
            options.devminor.padStart(8, "\0")
            // devminor
          ),
          100
        );
        header.set(prefix, 345);
        header.set(
          encoder4.encode(
            header.reduce((x3, y4) => x3 + y4).toString(8).padStart(6, "0") + "\0"
          ),
          148
        );
        yield header;
        if ("size" in chunk) {
          let size2 = 0;
          for await (const value of chunk.readable) {
            size2 += value.length;
            yield value;
          }
          if (chunk.size !== size2) {
            throw new RangeError(
              `Cannot add to the tar archive: The provided size (${chunk.size}) did not match bytes read from provided readable (${size2})`
            );
          }
          if (chunk.size % 512) {
            yield new Uint8Array(512 - size2 % 512);
          }
        }
      }
      yield new Uint8Array(1024);
    })();
    this.#readable = new ReadableStream({
      type: "bytes",
      async pull(controller) {
        const { done, value } = await gen.next();
        if (done) {
          controller.close();
          return controller.byobRequest?.respond(0);
        }
        if (controller.byobRequest?.view) {
          const buffer2 = new Uint8Array(controller.byobRequest.view.buffer);
          const size = buffer2.length;
          if (size < value.length) {
            buffer2.set(value.slice(0, size));
            controller.byobRequest.respond(size);
            controller.enqueue(value.slice(size));
          } else {
            buffer2.set(value);
            controller.byobRequest.respond(value.length);
          }
        } else {
          controller.enqueue(value);
        }
      }
    });
  }
  /**
   * The ReadableStream
   *
   * @return ReadableStream<Uint8Array>
   *
   * @example Usage
   * ```ts ignore
   * import { TarStream } from "@std/tar/tar-stream";
   *
   * await ReadableStream.from([
   *   {
   *     type: "directory",
   *     path: 'potato/'
   *   },
   *   {
   *     type: "file",
   *     path: 'deno.json',
   *     size: (await Deno.stat('deno.json')).size,
   *     readable: (await Deno.open('deno.json')).readable
   *   },
   *   {
   *     type: "file",
   *     path: '.vscode/settings.json',
   *     size: (await Deno.stat('.vscode/settings.json')).size,
   *     readable: (await Deno.open('.vscode/settings.json')).readable
   *   }
   * ])
   *   .pipeThrough(new TarStream())
   *   .pipeThrough(new CompressionStream('gzip'))
   *   .pipeTo((await Deno.create('./out.tar.gz')).writable)
   * ```
   */
  get readable() {
    return this.#readable;
  }
  /**
   * The WritableStream
   *
   * @return WritableStream<TarStreamInput>
   *
   * @example Usage
   * ```ts ignore
   * import { TarStream } from "@std/tar/tar-stream";
   *
   * await ReadableStream.from([
   *   {
   *     type: "directory",
   *     path: 'potato/'
   *   },
   *   {
   *     type: "file",
   *     path: 'deno.json',
   *     size: (await Deno.stat('deno.json')).size,
   *     readable: (await Deno.open('deno.json')).readable
   *   },
   *   {
   *     type: "file",
   *     path: '.vscode/settings.json',
   *     size: (await Deno.stat('.vscode/settings.json')).size,
   *     readable: (await Deno.open('.vscode/settings.json')).readable
   *   }
   * ])
   *   .pipeThrough(new TarStream())
   *   .pipeThrough(new CompressionStream('gzip'))
   *   .pipeTo((await Deno.create('./out.tar.gz')).writable)
   * ```
   */
  get writable() {
    return this.#writable;
  }
};
function parsePath(path3) {
  const name2 = new TextEncoder().encode(path3);
  if (name2.length <= 100) {
    return [new Uint8Array(0), name2];
  }
  if (name2.length > 256) {
    throw new RangeError(
      `Cannot parse the path as the path length cannot exceed 256 bytes: The path length is ${name2.length}`
    );
  }
  let suitableSlashPos = Math.max(0, name2.lastIndexOf(SLASH_CODE_POINT));
  if (name2.length - suitableSlashPos > 100) {
    throw new RangeError(
      `Cannot parse the path as the filename cannot exceed 100 bytes: The filename length is ${name2.length - suitableSlashPos}`
    );
  }
  for (let nextPos = suitableSlashPos; nextPos > 0; suitableSlashPos = nextPos) {
    nextPos = name2.lastIndexOf(SLASH_CODE_POINT, suitableSlashPos - 1);
    if (name2.length - nextPos > 100) {
      break;
    }
  }
  const prefix = name2.slice(0, suitableSlashPos);
  if (prefix.length > 155) {
    throw new TypeError(
      "Cannot parse the path as the path needs to be split-able on a forward slash separator into [155, 100] bytes respectively"
    );
  }
  return [prefix, name2.slice(suitableSlashPos + 1)];
}
function assertValidTarStreamOptions(options) {
  if (options.mode && options.mode.toString(8).length > 6) {
    throw new TypeError("Cannot add to the tar archive: Invalid Mode provided");
  }
  if (options.uid && options.uid.toString(8).length > 6) {
    throw new TypeError("Cannot add to the tar archive: Invalid UID provided");
  }
  if (options.gid && options.gid.toString(8).length > 6) {
    throw new TypeError("Cannot add to the tar archive: Invalid GID provided");
  }
  if (options.mtime != void 0 && (options.mtime.toString(8).length > 11 || options.mtime.toString() === "NaN")) {
    throw new TypeError(
      "Cannot add to the tar archive: Invalid MTime provided"
    );
  }
  if (options.uname && // deno-lint-ignore no-control-regex
  (options.uname.length > 32 - 1 || !/^[\x00-\x7F]*$/.test(options.uname))) {
    throw new TypeError(
      "Cannot add to the tar archive: Invalid UName provided"
    );
  }
  if (options.gname && // deno-lint-ignore no-control-regex
  (options.gname.length > 32 - 1 || !/^[\x00-\x7F]*$/.test(options.gname))) {
    throw new TypeError(
      "Cannot add to the tar archive: Invalid GName provided"
    );
  }
  if (options.devmajor && options.devmajor.length > 8) {
    throw new TypeError(
      "Cannot add to the tar archive: Invalid DevMajor provided"
    );
  }
  if (options.devminor && options.devminor.length > 8) {
    throw new TypeError(
      "Cannot add to the tar archive: Invalid DevMinor provided"
    );
  }
}

// deno_ral/tar.ts
init_path();
init_path2();
async function createTarFromFiles(outputPath, filePaths, options) {
  const baseDir = options?.baseDir;
  const inputs = await Promise.all(
    filePaths.map(async (path3) => {
      const fullPath = baseDir ? join4(baseDir, path3) : path3;
      const stat = await Deno.stat(fullPath);
      const archivePath = pathWithForwardSlashes(path3);
      if (stat.isDirectory) {
        return {
          type: "directory",
          path: archivePath + (archivePath.endsWith("/") ? "" : "/")
        };
      } else {
        return {
          type: "file",
          path: archivePath,
          size: stat.size,
          readable: (await Deno.open(fullPath)).readable
        };
      }
    })
  );
  await ReadableStream.from(inputs).pipeThrough(new TarStream()).pipeTo((await Deno.create(outputPath)).writable);
}

// publish/common/bundle.ts
async function createBundle(type4, files, tempContext2) {
  const manifestFiles = {};
  for (const file of files.files) {
    const filePath = join4(files.baseDir, file);
    if (Deno.statSync(filePath).isFile) {
      const fileBytes = Deno.readFileSync(filePath);
      const checksum = await md5HashBytes(fileBytes);
      manifestFiles[file] = { checksum };
    }
  }
  const manifest = {
    version: 1,
    locale: "en_US",
    platform: "4.2.0",
    metadata: {
      appmode: "static",
      primary_rmd: null,
      primary_html: files.rootFile,
      content_category: type4 === "site" ? "site" : null,
      has_parameters: false
    },
    packages: null,
    files: manifestFiles,
    users: null
  };
  const stageDir = tempContext2.createDir();
  files.files.forEach((file) => {
    const filePath = join4(files.baseDir, file);
    if (Deno.statSync(filePath).isFile) {
      const targetDir = join4(stageDir, dirname4(file));
      ensureDirSync(targetDir);
      Deno.copyFileSync(filePath, join4(stageDir, file));
    }
  });
  Deno.writeTextFileSync(
    join4(stageDir, "manifest.json"),
    JSON.stringify(manifest, void 0, 2)
  );
  const tarFiles = [...files.files, "manifest.json"];
  const tarFile = tempContext2.createFile({ suffix: ".tar" });
  await createTarFromFiles(tarFile, tarFiles, { baseDir: stageDir });
  const targzFile = `${tarFile}.gz`;
  const src2 = await Deno.open(tarFile);
  const dest = await Deno.open(targzFile, {
    create: true,
    write: true
  });
  await src2.readable.pipeThrough(new CompressionStream("gzip")).pipeTo(dest.writable);
  return {
    bundlePath: targzFile,
    manifest
  };
}

// publish/rsconnect/rsconnect.ts
var kRSConnect = "connect";
var kRSConnectDescription = "Posit Connect";
var kRSConnectServerVar = "CONNECT_SERVER";
var kRSConnectAuthTokenVar = "CONNECT_API_KEY";
var rsconnectProvider = {
  name: kRSConnect,
  description: kRSConnectDescription,
  requiresServer: true,
  listOriginOnly: true,
  accountTokens: accountTokens4,
  authorizeToken: authorizeToken4,
  removeToken: removeToken4,
  resolveTarget: resolveTarget4,
  publish: publish4,
  isUnauthorized: isUnauthorized4,
  isNotFound: isNotFound4
};
function accountTokens4() {
  const accounts = [];
  const server = Deno.env.get(kRSConnectServerVar);
  const apiKey = Deno.env.get(kRSConnectAuthTokenVar);
  if (server && apiKey) {
    accounts.push({
      type: 0 /* Environment */,
      name: kRSConnectAuthTokenVar,
      server,
      token: apiKey
    });
  }
  const tokens2 = readAccessTokens(kRSConnect);
  if (tokens2) {
    accounts.push(...tokens2.map((token) => ({
      type: 1 /* Authorized */,
      name: token.username,
      server: token.server,
      token: token.key
    })));
  }
  return Promise.resolve(accounts);
}
function removeToken4(token) {
  writeAccessTokens(
    rsconnectProvider.name,
    readAccessTokens(rsconnectProvider.name)?.filter(
      (accessToken) => {
        return accessToken.server !== token.server && accessToken.username !== token.name;
      }
    ) || []
  );
}
async function authorizeToken4(options, target) {
  let server = target?.url ? new URL(target.url).origin : options.server || void 0;
  if (server) {
    server = ensureProtocolAndTrailingSlash(server);
  }
  while (server === void 0) {
    server = await Input.prompt({
      message: "Server URL:",
      hint: "e.g. https://connect.example.com/",
      validate: (value) => {
        if (value.length === 0) {
          throw new Error();
        }
        try {
          const url = new URL(ensureProtocolAndTrailingSlash(value));
          if (!["http:", "https:"].includes(url.protocol)) {
            return `${value} is not an HTTP URL`;
          } else {
            return true;
          }
        } catch {
          return `${value} is not a valid URL`;
        }
      },
      transform: ensureProtocolAndTrailingSlash
    });
    const client = new RSConnectClient(server);
    try {
      await client.getUser();
    } catch (err2) {
      if (!(err2 instanceof Error)) {
        throw err2;
      }
      if (isUnauthorized4(err2)) {
        break;
      } else {
        info(
          red3(
            "   Unable to connect to server (is this a valid Posit Connect Server?)"
          )
        );
        server = void 0;
      }
    }
  }
  while (true) {
    const apiKey = await Secret.prompt({
      message: "API Key:",
      hint: "Learn more at https://docs.rstudio.com/connect/user/api-keys/"
    });
    if (apiKey.length === 0) {
      throw new Error();
    }
    try {
      const client = new RSConnectClient(server, apiKey);
      const user = await client.getUser();
      if (user.user_role !== "viewer") {
        const account = {
          username: user.username,
          server,
          key: apiKey
        };
        writeAccessToken(
          kRSConnect,
          account,
          (a5, b3) => a5.server === b3.server && a5.username === b3.username
        );
        return {
          type: 1 /* Authorized */,
          name: user.username,
          server,
          token: apiKey
        };
      } else {
        promptError(
          "API key is for an Posit Connect viewer rather than a publisher."
        );
      }
    } catch (err2) {
      if (!(err2 instanceof Error)) {
        throw err2;
      }
      if (isUnauthorized4(err2)) {
        promptError(
          "API key is not authorized for this Posit Connect server."
        );
      } else {
        throw err2;
      }
    }
  }
}
async function resolveTarget4(account, target) {
  const client = new RSConnectClient(account.server, account.token);
  const content = await client.getContent(target.id);
  return contentAsTarget(content);
}
async function publish4(account, type4, _input, title3, slug, render2, _options, target) {
  const client = new RSConnectClient(account.server, account.token);
  let content;
  await withSpinner({
    message: `Preparing to publish ${type4}`
  }, async () => {
    if (!target) {
      content = await createContent(client, title3, slug);
      if (content) {
        target = contentAsTarget(content);
      } else {
        throw new Error();
      }
    } else {
      content = await client.getContent(target.id);
    }
  });
  info("");
  const publishFiles = await render2();
  const tempContext2 = createTempContext();
  try {
    let task;
    await withSpinner({
      message: () => `Uploading files`
    }, async () => {
      const { bundlePath } = await createBundle(
        type4,
        publishFiles,
        tempContext2
      );
      const bundleBytes = Deno.readFileSync(bundlePath);
      const bundleBlob = new Blob([bundleBytes.buffer]);
      const bundle2 = await client.uploadBundle(target.id, bundleBlob);
      task = await client.deployBundle(bundle2);
    });
    await withSpinner({
      message: `Publishing ${type4}`
    }, async () => {
      while (true) {
        const status = await client.getTaskStatus(task);
        if (status.finished) {
          if (status.code === 0) {
            break;
          } else {
            throw new Error(
              `Error attempting to publish content: ${status.code} - ${status.error}`
            );
          }
        }
      }
    });
    completeMessage(`Published: ${content.content_url}
`);
    return Promise.resolve([target, new URL(content.dashboard_url)]);
  } finally {
    tempContext2.cleanup();
  }
}
function isUnauthorized4(err2) {
  return err2 instanceof ApiError2 && err2.status === 401;
}
function isConflict(err2) {
  return err2 instanceof ApiError2 && err2.status === 409;
}
function isNotFound4(err2) {
  return err2 instanceof ApiError2 && err2.status === 404;
}
function contentAsTarget(content) {
  return { id: content.guid, url: content.content_url, code: false };
}
async function createContent(client, title3, slug) {
  while (true) {
    const name2 = slug + "-" + randomHex(4);
    try {
      return await client.createContent(name2, title3);
    } catch (err2) {
      if (!(err2 instanceof Error)) {
        throw err2;
      }
      if (!isConflict(err2)) {
        throw err2;
      }
    }
  }
}
function promptError(msg5) {
  info(red3(`  ${msg5}`));
}

// publish/confluence/confluence.ts
init_path();
init_path2();

// publish/confluence/api/index.ts
init_base64();
init_path2();

// publish/confluence/api/types.ts
var PAGE_TYPE = "page";
var EMPTY_PARENT = {
  space: "",
  parent: ""
};

// publish/confluence/constants.ts
var DELETE_DISABLED = false;
var EXIT_ON_ERROR = false;
var DESCENDANT_PAGE_SIZE = 200;
var MAX_PAGES_TO_LOAD = 100;
var V2EDITOR_METADATA = {
  metadata: {
    properties: {
      editor: {
        value: "v2"
      }
    }
  }
};
var DELETE_SLEEP_MILLIS = 1e3;
var ATTACHMENT_UPLOAD_DELAY_MS = 800;
var CAN_SET_PERMISSIONS_DISABLED = "CONFLUENCE_LOCAL_STORAGE_CAN_SET_PERMISSIONS_DISABLED";
var CAN_SET_PERMISSIONS_ENABLED_CACHED = "CONFLUENCE_LOCAL_STORAGE_CAN_SET_PERMISSIONS_ENABLED_CACHED";

// publish/confluence/confluence-logger.ts
init_log();
var trace2 = (message, value = "", prefix = "[General]" /* GENERAL */, level = "DEBUG" /* DEBUG */) => {
  const logger = {
    ["DEBUG" /* DEBUG */]: debug,
    ["INFO" /* INFO */]: info,
    ["WARN" /* WARN */]: warn,
    ["ERROR" /* ERROR */]: error
  };
  const prefixedMessage = `
[Confluence] ${prefix} ${message}`;
  logger[level](`${prefixedMessage} ${Deno.inspect(value)}`);
};
var logError2 = (message, value, prefix = "[General]" /* GENERAL */) => trace2(message, value, prefix, "ERROR" /* ERROR */);

// publish/confluence/confluence-helper.ts
init_path2();
init_path();
init_url();
init_text2();
var LINK_FINDER = /(\S*.qmd'|\S*.qmd#\S*')/g;
var FILE_FINDER = /(?<=href=\')(.*)(?=\.qmd)/;
var ATTACHMENT_FINDER = /(?<=ri:attachment ri:filename=["\'])[^"\']+?\.(?:jpe?g|png|gif|m4a|mp3|txt|svg|ai|pdf)(?=["\'])/g;
var capitalizeFirstLetter = (value = "") => {
  if (!value || value.length === 0) {
    return "";
  }
  return value[0].toUpperCase() + value.slice(1);
};
var transformAtlassianDomain = (domain2) => {
  return ensureTrailingSlash(
    isHttpUrl(domain2) ? domain2 : `https://${domain2}.atlassian.net`
  );
};
var isUnauthorized5 = (error2) => {
  return error2 instanceof ApiError2 && (error2.status === 401 || error2.status === 403);
};
var isNotFound5 = (error2) => {
  return error2 instanceof ApiError2 && error2.status === 404;
};
var exitIfNoValue = (value) => {
  if (value?.length === 0) {
    throw new Error("");
  }
};
var validateServer = (value) => {
  exitIfNoValue(value);
  try {
    new URL(transformAtlassianDomain(value));
    return true;
  } catch {
    return `Not a valid URL`;
  }
};
var validateEmail = (value) => {
  exitIfNoValue(value);
  const expression = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i;
  const isValid2 = expression.test(value);
  if (!isValid2) {
    return "Invalid email address";
  }
  return true;
};
var validateToken = (value) => {
  exitIfNoValue(value);
  return true;
};
var validateParentURL = (value) => {
  exitIfNoValue(value);
  return true;
};
var getMessageFromAPIError = (error2) => {
  if (error2 instanceof ApiError2) {
    return `${error2.status} - ${error2.statusText}`;
  }
  if (error2?.message) {
    return error2.message;
  }
  return "Unknown error";
};
var tokenFilterOut = (accessToken, token) => {
  return accessToken.server !== token.server && accessToken.name !== token.name;
};
var confluenceParentFromString = (url) => {
  let toMatch = url;
  const urlNoParamsList = url?.split("?");
  if (urlNoParamsList.length === 2) {
    toMatch = urlNoParamsList[0] ?? url;
  }
  const match = toMatch.match(
    /^https.*?wiki\/spaces\/(?:(~?\w+)|(~?\w+)\/overview|(~?.+)\/pages\/(\d+).*)$/
  );
  if (match) {
    return {
      space: match[1] || match[2] || match[3],
      parent: match[4]
    };
  }
  return EMPTY_PARENT;
};
var wrapBodyForConfluence = (value) => {
  const body = {
    storage: {
      value,
      representation: "storage" /* storage */
    }
  };
  return body;
};
var buildPublishRecordForContent = (server, content) => {
  if (!content?.id || !content?.space || !(server.length > 0)) {
    throw new Error("Invalid Content");
  }
  const url = `${ensureTrailingSlash(server)}wiki/spaces/${content.space.key}/pages/${content.id}`;
  const newPublishRecord = {
    id: content.id,
    url
  };
  return [newPublishRecord, new URL(url)];
};
var doWithSpinner = async (message, toDo) => {
  return await withSpinner(
    {
      message
    },
    toDo
  );
};
var getNextVersion = (previousPage) => {
  const previousNumber = previousPage.version?.number ?? 0;
  return {
    number: previousNumber + 1
  };
};
var writeTokenComparator = (a5, b3) => a5.server === b3.server && a5.name === b3.name;
var filterFilesForUpdate = (allFiles) => {
  const fileFilter = (fileName) => {
    if (!fileName.endsWith(".xml")) {
      return false;
    }
    return true;
  };
  const result2 = allFiles.filter(fileFilter);
  return result2;
};
var isContentCreate = (content) => {
  return content.contentChangeType === "create" /* create */;
};
var isContentUpdate = (content) => {
  return content.contentChangeType === "update" /* update */;
};
var isContentDelete = (content) => {
  return content.contentChangeType === "delete" /* delete */;
};
var buildContentCreate = (title3, space, body, fileName, parent, status = "current" /* current */, id = null, type4 = PAGE_TYPE) => {
  return {
    contentChangeType: "create" /* create */,
    title: title3,
    type: type4,
    space,
    status,
    ancestors: parent ? [{ id: parent }] : null,
    body,
    fileName
  };
};
var buildContentUpdate = (id, title3, body, fileName, parent, status = "current" /* current */, type4 = PAGE_TYPE, version4 = null, ancestors = null) => {
  return {
    contentChangeType: "update" /* update */,
    id,
    version: version4,
    title: title3,
    type: type4,
    status,
    ancestors: parent ? [{ id: parent }] : ancestors,
    body,
    fileName
  };
};
var findPagesToDelete = (fileMetadataList, existingSite = []) => {
  const activeParents = existingSite.reduce(
    (accumulator, page) => {
      return [...accumulator, ...page.ancestors ?? []];
    },
    []
  );
  const isActiveParent = (id) => !!activeParents.find((parent) => parent.id === id);
  return existingSite.reduce((accumulator, page) => {
    if (!fileMetadataList.find(
      (file) => pathWithForwardSlashes(file.fileName) === (page?.metadata?.fileName ?? "")
    ) && !isActiveParent(page.id)) {
      return [...accumulator, page];
    }
    return accumulator;
  }, []);
};
var buildSpaceChanges = (fileMetadataList, parent, space, existingSite = []) => {
  const spaceChangesCallback = (accumulatedChanges, fileMetadata) => {
    const findPageInExistingSite = (fileName) => existingSite.find(
      (page) => page?.metadata?.fileName === fileName
    );
    const universalFileName = pathWithForwardSlashes(fileMetadata.fileName);
    const existingPage = findPageInExistingSite(universalFileName);
    let spaceChangeList = [];
    const pathList = universalFileName.split("/");
    let pageParent = pathList.length > 1 ? pathList.slice(0, pathList.length - 1).join("/") : parent?.parent;
    const checkCreateParents = () => {
      if (pathList.length < 2) {
        return null;
      }
      let existingSiteParent = null;
      const parentsList = pathList.slice(0, pathList.length - 1);
      parentsList.forEach((parentFileName, index2) => {
        const ancestorFilePath = parentsList.slice(0, index2).join("/");
        const ancestor2 = index2 > 0 ? ancestorFilePath : parent?.parent;
        let fileName = `${ancestorFilePath}/${parentFileName}`;
        if (fileName.startsWith("/")) {
          fileName = parentFileName;
        }
        const existingParentCreateChange = accumulatedChanges.find(
          (spaceChange) => {
            if (spaceChange.fileName) {
              return spaceChange?.fileName === fileName;
            }
            return false;
          }
        );
        existingSiteParent = existingSite.find((page) => {
          if (page?.metadata?.fileName) {
            return page.metadata.fileName === fileName;
          }
          return false;
        });
        if (!existingParentCreateChange && !existingSiteParent) {
          const existingAncestor = findPageInExistingSite(ancestor2 ?? "");
          spaceChangeList = [
            ...spaceChangeList,
            buildContentCreate(
              capitalizeFirstLetter(parentFileName),
              space,
              {
                storage: {
                  value: "",
                  representation: "storage"
                }
              },
              fileName,
              existingAncestor ? existingAncestor.id : ancestor2,
              "current" /* current */
            )
          ];
        }
      });
      return existingSiteParent;
    };
    const existingParent = checkCreateParents();
    pageParent = existingParent ? existingParent.id : pageParent;
    if (existingPage) {
      spaceChangeList = [
        buildContentUpdate(
          existingPage.id,
          fileMetadata.title,
          fileMetadata.contentBody,
          universalFileName,
          pageParent
        )
      ];
    } else {
      spaceChangeList = [
        ...spaceChangeList,
        buildContentCreate(
          fileMetadata.title,
          space,
          fileMetadata.contentBody,
          universalFileName,
          pageParent,
          "current" /* current */
        )
      ];
    }
    return [...accumulatedChanges, ...spaceChangeList];
  };
  const pagesToDelete = findPagesToDelete(
    fileMetadataList,
    existingSite
  );
  const deleteChanges = pagesToDelete.map(
    (toDelete) => {
      return { contentChangeType: "delete" /* delete */, id: toDelete.id };
    }
  );
  let spaceChanges = fileMetadataList.reduce(
    spaceChangesCallback,
    deleteChanges
  );
  const activeAncestorIds = spaceChanges.reduce(
    (accumulator, change) => {
      if (change?.ancestors?.length) {
        const idList = change.ancestors.map(
          (ancestor2) => ancestor2?.id ?? ""
        );
        return [...accumulator, ...idList];
      }
      return accumulator;
    },
    []
  );
  spaceChanges = spaceChanges.filter((change) => {
    if (isContentDelete(change) && activeAncestorIds.includes(change.id)) {
      return false;
    }
    return true;
  });
  return spaceChanges;
};
var flattenIndexes = (changes, metadataByFileName, siteParentId) => {
  const getFileNameForChange = (change) => {
    if (isContentDelete(change)) {
      return "";
    }
    return pathWithForwardSlashes(change?.fileName ?? "");
  };
  const isIndexFile = (change) => {
    return getFileNameForChange(change)?.endsWith("/index.xml");
  };
  const toIndexPageLookup = (accumulator, change) => {
    if (isContentDelete(change)) {
      return accumulator;
    }
    const fileName = getFileNameForChange(change);
    const isIndex = isIndexFile(change);
    if (isIndex) {
      const folderFileName = fileName.replace("/index.xml", "");
      return {
        ...accumulator,
        [folderFileName]: change
      };
    }
    return accumulator;
  };
  const indexLookup = changes.reduce(
    toIndexPageLookup,
    {}
  );
  const toFlattenedIndexes = (accumulator, change) => {
    if (isContentDelete(change)) {
      return [...accumulator, change];
    }
    const fileName = getFileNameForChange(change);
    if (fileName === "index.xml") {
      const rootUpdate = buildContentUpdate(
        siteParentId,
        change.title,
        change.body,
        "index.xml"
      );
      return [...accumulator, rootUpdate];
    }
    const parentFileName = fileName.replace("/index.xml", "");
    const parentSitePage = metadataByFileName[parentFileName];
    if (isIndexFile(change)) {
      if (parentSitePage) {
        const parentUpdate = buildContentUpdate(
          parentSitePage.id,
          change.title,
          change.body,
          parentSitePage.metadata.fileName ?? "",
          "",
          "current" /* current */,
          PAGE_TYPE,
          null,
          parentSitePage.ancestors
        );
        return [...accumulator, parentUpdate];
      } else {
        return [...accumulator];
      }
    }
    const indexCreateChange = indexLookup[fileName];
    if (indexCreateChange && !isContentDelete(indexCreateChange)) {
      change.title = indexCreateChange.title ?? change.title;
      change.body = indexCreateChange.body ?? change.body;
    }
    return [...accumulator, change];
  };
  const flattenedIndexes = changes.reduce(toFlattenedIndexes, []);
  return flattenedIndexes;
};
var replaceExtension = (fileName, oldExtension, newExtension) => {
  return fileName.replace(oldExtension, newExtension);
};
var getTitle = (fileName, metadataByInput) => {
  const qmdFileName = replaceExtension(fileName, ".xml", ".qmd");
  const metadataTitle = metadataByInput[qmdFileName]?.title;
  const titleFromFilename = capitalizeWord(fileName.split(".")[0] ?? fileName);
  const title3 = metadataTitle ?? titleFromFilename;
  return title3;
};
var flattenMetadata = (list = []) => {
  const result2 = list.reduce(
    (accumulator, currentValue) => {
      const updated = accumulator;
      updated[currentValue.key] = currentValue.value;
      return updated;
    },
    {}
  );
  return result2;
};
var mergeSitePages = (shallowPages = [], contentProperties = []) => {
  const result2 = shallowPages.map(
    (contentSummary, index2) => {
      const sitePage = {
        title: contentSummary.title,
        id: contentSummary.id ?? "",
        metadata: flattenMetadata(contentProperties[index2]),
        ancestors: contentSummary.ancestors ?? []
      };
      return sitePage;
    }
  );
  return result2;
};
var buildFileToMetaTable = (fileMetadata) => {
  return fileMetadata.reduce(
    (accumulator, page) => {
      const fileName = page?.metadata?.fileName ?? "";
      const fileNameQMD = fileName.replace("xml", "qmd");
      if (fileName.length === 0) {
        return accumulator;
      }
      accumulator[fileNameQMD] = page;
      return accumulator;
    },
    {}
  );
};
var updateLinks = (fileMetadataTable, spaceChanges, server, parent) => {
  const root = `${server}`;
  const url = `${ensureTrailingSlash(server)}wiki/spaces/${parent.space}/pages/`;
  let collectedPass2Changes = [];
  const changeMapper = (changeToProcess) => {
    const replacer = (match) => {
      let documentFileName = "";
      if (isContentUpdate(changeToProcess) || isContentCreate(changeToProcess)) {
        documentFileName = changeToProcess.fileName ?? "";
      }
      const docFileNamePathList = documentFileName.split("/");
      let updated = match;
      const linkFileNameMatch = FILE_FINDER.exec(match);
      const linkFileName = linkFileNameMatch ? linkFileNameMatch[0] ?? "" : "";
      const fileNamePathList = linkFileName.split("/");
      const linkFullFileName = `${linkFileName}.qmd`;
      let siteFilePath = linkFullFileName;
      const isAbsolute12 = siteFilePath.startsWith("/");
      if (!isAbsolute12 && docFileNamePathList.length > 1) {
        const relativePath = docFileNamePathList.slice(0, docFileNamePathList.length - 1).join("/");
        if (siteFilePath.startsWith("./")) {
          siteFilePath = siteFilePath.replace("./", `${relativePath}/`);
        } else {
          siteFilePath = `${relativePath}/${linkFullFileName}`;
        }
      }
      if (isAbsolute12) {
        siteFilePath = siteFilePath.slice(1);
      }
      if (siteFilePath.endsWith("/index.qmd")) {
        const siteFilePathParent = siteFilePath.replace("/index.qmd", "");
        if (fileMetadataTable[siteFilePathParent]) {
          siteFilePath = siteFilePathParent;
        }
      }
      if (!documentFileName.endsWith(".xml")) {
        const siteFilePathParent = `${documentFileName}/${linkFullFileName}`;
        if (fileMetadataTable[siteFilePathParent]) {
          siteFilePath = siteFilePathParent;
        }
      }
      const sitePage = fileMetadataTable[siteFilePath] ?? null;
      if (sitePage) {
        updated = match.replace('href="', `href="${url}`);
        const pagePath = `${url}${sitePage.id}`;
        updated = updated.replace(linkFullFileName, pagePath);
      } else {
        if (!collectedPass2Changes.includes(changeToProcess)) {
          collectedPass2Changes = [...collectedPass2Changes, changeToProcess];
        }
      }
      return updated;
    };
    if (isContentUpdate(changeToProcess) || isContentCreate(changeToProcess)) {
      const valueToProcess = changeToProcess?.body?.storage?.value;
      if (valueToProcess) {
        const replacedLinks = valueToProcess.replaceAll(
          LINK_FINDER,
          replacer
        );
        changeToProcess.body.storage.value = replacedLinks;
      }
    }
    return changeToProcess;
  };
  const updatedChanges = spaceChanges.map(
    changeMapper
  );
  return { pass1Changes: updatedChanges, pass2Changes: collectedPass2Changes };
};
var convertForSecondPass = (fileMetadataTable, spaceChanges, server, parent) => {
  const toUpdatesReducer = (accumulator, change) => {
    if (isContentUpdate(change)) {
      accumulator = [...accumulator, change];
    }
    if (isContentCreate(change)) {
      const qmdFileName = replaceExtension(
        change.fileName ?? "",
        ".xml",
        ".qmd"
      );
      const updateId = fileMetadataTable[qmdFileName]?.id;
      if (updateId) {
        const convertedUpdate = buildContentUpdate(
          updateId,
          change.title,
          change.body,
          change.fileName ?? "",
          "",
          "current" /* current */,
          PAGE_TYPE,
          null,
          change.ancestors
        );
        accumulator = [...accumulator, convertedUpdate];
      } else {
        trace2("update ID not found for", change.fileName);
      }
    }
    return accumulator;
  };
  const changesAsUpdates = spaceChanges.reduce(toUpdatesReducer, []);
  const updateLinkResults = updateLinks(
    fileMetadataTable,
    changesAsUpdates,
    server,
    parent
  );
  return updateLinkResults.pass1Changes;
};
var updateImagePaths = (body) => {
  const replacer = (match) => {
    let updated = match.replace(/^.*[\\\/]/, "");
    return updated;
  };
  const bodyValue = body?.storage?.value;
  if (!bodyValue) {
    return body;
  }
  const attachments = findAttachments(bodyValue);
  const withReplacedImages = bodyValue.replaceAll(
    ATTACHMENT_FINDER,
    replacer
  );
  body.storage.value = withReplacedImages;
  return body;
};
var findAttachments = (bodyValue, publishFiles = [], filePathParam = "") => {
  const filePath = pathWithForwardSlashes(filePathParam);
  const pathList = filePath.split("/");
  const parentPath = pathList.slice(0, pathList.length - 1).join("/");
  const imageFinderMatches = bodyValue.match(
    ATTACHMENT_FINDER
  );
  let uniqueFoundImages = [...new Set(imageFinderMatches)];
  if (publishFiles.length > 0) {
    uniqueFoundImages = uniqueFoundImages.map((assetFileName) => {
      const assetInPublishFiles = publishFiles.find((assetPathParam) => {
        const assetPath = pathWithForwardSlashes(assetPathParam);
        const toCheck = pathWithForwardSlashes(join4(parentPath, assetFileName));
        return assetPath === toCheck;
      });
      return assetInPublishFiles ?? assetFileName;
    });
  }
  return uniqueFoundImages ?? [];
};
var buildConfluenceAnchor = (id) => `<ac:structured-macro ac:name="anchor" ac:schema-version="1" ac:local-id="a6aa6f25-0bee-4a7f-929b-71fcb7eba592" ac:macro-id="d2cb5be1217ae6e086bc60005e9d27b7"><ac:parameter ac:name="">${id}</ac:parameter></ac:structured-macro>`;
var footnoteTransform = (bodyValue) => {
  const BACK_ANCHOR_FINDER = /<a href="#fn(\d)"/g;
  const ANCHOR_FINDER = /<a href="#fnref(\d)"/g;
  const CONFLUENCE_ANCHOR_FINDER = /ac:macro-id="d2cb5be1217ae6e086bc60005e9d27b7"><ac:parameter ac:name="">fn/g;
  if (bodyValue.search(CONFLUENCE_ANCHOR_FINDER) !== -1) {
    return bodyValue;
  }
  const replacer = (prefix) => (match, p1) => `${buildConfluenceAnchor(`${prefix}${p1}`)}${match}`;
  let replacedBody = bodyValue.replaceAll(
    BACK_ANCHOR_FINDER,
    replacer("fnref")
  );
  replacedBody = replacedBody.replaceAll(ANCHOR_FINDER, replacer("fn"));
  return replacedBody;
};

// publish/confluence/api/index.ts
var ConfluenceClient = class {
  constructor(token_) {
    this.token_ = token_;
  }
  getUser(expand2 = ["operations"]) {
    return this.get(`user/current?expand=${expand2}`);
  }
  getSpace(spaceId, expand2 = ["homepage"]) {
    return this.get(`space/${spaceId}?expand=${expand2}`);
  }
  getContent(id) {
    return this.get(`content/${id}`);
  }
  async getContentProperty(id) {
    const result2 = await this.get(`content/${id}/property`);
    return result2.results;
  }
  getDescendantsPage(id, start = 0, expand2 = ["metadata.properties", "ancestors"]) {
    const url = `content/${id}/descendant/page?limit=${DESCENDANT_PAGE_SIZE}&start=${start}&expand=${expand2}`;
    return this.get(url);
  }
  async isTitleUniqueInSpace(title3, space, idToIgnore = "") {
    const result2 = await this.fetchMatchingTitlePages(title3, space);
    if (result2.length === 1 && result2[0].id === idToIgnore) {
      return true;
    }
    return result2.length === 0;
  }
  async fetchMatchingTitlePages(title3, space, isFuzzy = false) {
    const encodedTitle = encodeURIComponent(title3);
    let cql = `title="${encodedTitle}"`;
    const CQL_CONTEXT = "%7B%22contentStatuses%22%3A%5B%22archived%22%2C%20%22current%22%2C%20%22draft%22%5D%7D";
    cql = `${cql}&spaces=${space.key}&cqlcontext=${CQL_CONTEXT}`;
    const result2 = await this.get(`content/search?cql=${cql}`);
    return result2?.results ?? [];
  }
  /**
   * Perform a test to see if the user can manage permissions.  In the space create a simple test page, attempt to set
   * permissions on it, then delete it.
   */
  async canSetPermissions(parent, space, user) {
    let result2 = true;
    trace2("canSetPermissions check");
    trace2(
      "localStorage.getItem(CAN_SET_PERMISSIONS_DISABLED)",
      localStorage.getItem(CAN_SET_PERMISSIONS_DISABLED)
    );
    trace2(
      "localStorage.getItem(CAN_SET_PERMISSIONS_ENABLED_CACHED)",
      localStorage.getItem(CAN_SET_PERMISSIONS_ENABLED_CACHED)
    );
    const permissionsTestDisabled = localStorage.getItem(CAN_SET_PERMISSIONS_DISABLED) === "true" || localStorage.getItem(CAN_SET_PERMISSIONS_ENABLED_CACHED) === "true";
    trace2("permissionsTestDisabled", permissionsTestDisabled);
    if (permissionsTestDisabled) {
      return Promise.resolve(true);
    }
    const testContent = buildContentCreate(
      `quarto-permission-test-${globalThis.crypto.randomUUID()}`,
      space,
      {
        storage: {
          value: "",
          representation: "storage"
        }
      },
      "permisson-test"
    );
    const testContentCreated = await this.createContent(user, testContent);
    const testContentId = testContentCreated.id ?? "";
    try {
      await this.put(
        `content/${testContentId}/restriction/byOperation/update/user?accountId=${user.accountId}`
      );
    } catch (error2) {
      if (!(error2 instanceof ApiError2)) {
        throw error2;
      }
      trace2("lockDownResult Error", error2);
      if (error2?.status === 403) {
        result2 = false;
      }
    }
    const contentDelete = {
      id: testContentId,
      contentChangeType: "delete" /* delete */
    };
    let attemptArchive = false;
    try {
      await this.deleteContent(contentDelete);
    } catch (error2) {
      if (!(error2 instanceof ApiError2)) {
        throw error2;
      }
      trace2("delete canSetPermissions Test Error", error2);
      if (error2?.status === 403) {
        attemptArchive = true;
      }
    }
    try {
      await this.archiveContent(contentDelete);
    } catch (error2) {
      trace2("archive canSetPermissions Test Error", error2);
    }
    if (attemptArchive) {
      trace2(
        "Disabling Permissions Test: confluenceCanSetPermissionsDisabled",
        "true"
      );
      localStorage.setItem(CAN_SET_PERMISSIONS_DISABLED, "true");
    }
    return result2;
  }
  async lockDownPermissions(contentId, user) {
    try {
      return await this.put(
        `content/${contentId}/restriction/byOperation/update/user?accountId=${user.accountId}`
      );
    } catch (error2) {
      trace2("lockDownResult Error", error2);
    }
  }
  async createContent(user, content, metadata = V2EDITOR_METADATA) {
    const toCreate = {
      ...content,
      ...metadata
    };
    trace2("to create", toCreate);
    trace2("createContent body", content.body.storage.value);
    const createBody = JSON.stringify(toCreate);
    const result2 = await this.post("content", createBody);
    await this.lockDownPermissions(result2.id ?? "", user);
    return result2;
  }
  async updateContent(user, content, metadata = V2EDITOR_METADATA) {
    const toUpdate = {
      ...content,
      ...metadata
    };
    const result2 = await this.put(
      `content/${content.id}`,
      JSON.stringify(toUpdate)
    );
    await this.lockDownPermissions(content.id ?? "", user);
    return result2;
  }
  createContentProperty(id, content) {
    return this.post(
      `content/${id}/property`,
      JSON.stringify(content)
    );
  }
  deleteContent(content) {
    trace2("deleteContent", content);
    return this.delete(`content/${content.id}`);
  }
  archiveContent(content) {
    trace2("archiveContent", content);
    const toArchive = {
      pages: [
        {
          id: content.id
        }
      ]
    };
    return this.post(`content/archive`, JSON.stringify(toArchive));
  }
  async getAttachments(id) {
    const wrappedResult = await this.get(`content/${id}/child/attachment`);
    const result2 = wrappedResult?.results ?? [];
    return result2;
  }
  async createOrUpdateAttachment(parentId, file, comment = "") {
    trace2("createOrUpdateAttachment", { file, parentId }, "[Attach]" /* ATTACHMENT */);
    const wrappedResult = await this.putAttachment(
      `content/${parentId}/child/attachment`,
      file,
      comment
    );
    trace2("createOrUpdateAttachment", wrappedResult, "[Attach]" /* ATTACHMENT */);
    const result2 = wrappedResult.results[0] ?? null;
    return result2;
  }
  get = (path3) => this.fetch("GET", path3);
  delete = (path3) => this.fetch("DELETE", path3);
  post = (path3, body) => this.fetch("POST", path3, body);
  put = (path3, body) => this.fetch("PUT", path3, body);
  putAttachment = (path3, file, comment = "") => this.fetchWithAttachment("PUT", path3, file, comment);
  fetch = async (method, path3, body) => {
    const headers = {
      Accept: "application/json",
      ...["POST", "PUT"].includes(method) ? { "Content-Type": "application/json" } : {},
      ...this.authorizationHeader()
    };
    const request2 = {
      method,
      headers,
      body
    };
    return this.handleResponse(await fetch(this.apiUrl(path3), request2));
  };
  fetchWithAttachment = async (method, path3, file, comment = "") => {
    const formData = new FormData();
    formData.append("file", file);
    formData.append("minorEdit", "true");
    formData.append("comment", comment);
    const headers = {
      ["X-Atlassian-Token"]: "nocheck",
      ...this.authorizationHeader()
    };
    const request2 = {
      method,
      headers,
      body: formData
    };
    return this.handleResponse(await fetch(this.apiUrl(path3), request2));
  };
  apiUrl = (path3) => `${ensureTrailingSlash(this.token_.server)}wiki/rest/api/${path3}`;
  authorizationHeader() {
    const auth = encodeBase64(this.token_.name + ":" + this.token_.token);
    return {
      Authorization: `Basic ${auth}`
    };
  }
  async handleResponse(response) {
    if (response.ok) {
      if (response.body) {
        let data3 = await response.text();
        if (data3 === "") {
          return null;
        } else {
          return JSON.parse(data3);
        }
      } else {
        return response;
      }
    } else if (response.status === 403) {
      throw new ApiError2(response.status, response.statusText);
    } else if (response.status !== 200) {
      logError2("response.status !== 200", response);
      throw new ApiError2(response.status, response.statusText);
    } else {
      logError2("handleResponse", response);
      throw new Error(`${response.status} - ${response.statusText}`);
    }
  }
};

// publish/confluence/confluence-verify.ts
var verifyWithSpinner = async (verifyCommand, message = "Verifying...") => {
  return await withSpinner({ message }, verifyCommand);
};
var verifyAccountToken = async (accountToken) => {
  try {
    const client = new ConfluenceClient(accountToken);
    await client.getUser();
  } catch (error2) {
    throw new Error(
      `Unable to sign into Confluence account: ${getMessageFromAPIError(error2)}`
    );
  }
};
var verifyLocation = async (locationURL) => {
  return await verifyWithSpinner(() => verifyLocationExists(locationURL));
};
var verifyLocationExists = async (server) => {
  try {
    const result2 = await fetch(server);
    if (!result2.ok) {
      throw new Error("");
    }
  } catch (error2) {
    trace2("server doesnt exist", error2);
    throw new Error(`${server} doesn't exist`);
  }
};
var verifyConfluenceParent = async (parentUrl, parent) => {
  if (parent.space.length === 0) {
    throw new Error("Invalid Confluence parent URL: " + parentUrl);
  }
  await verifyLocation(parentUrl);
};
var verifyOrWarnManagePermissions = async (client, space, parent, user) => {
  const canManagePermissions = await client.canSetPermissions(
    parent,
    space,
    user
  );
  if (canManagePermissions) {
    localStorage.setItem(CAN_SET_PERMISSIONS_ENABLED_CACHED, "true");
    trace2("Caching permission check success");
  } else {
    const confirmed = await Confirm.prompt(
      "We've detected that your account is not able to manage the permissions for this destination.\n\nPublished pages will be directly editable within the Confluence web editor.\n\nThis means that if you republish the page from Quarto, you may be overwriting the web edits.\nWe recommend that you establish a clear policy about how this published page will be revised.\n\nAre you sure you want to continue?"
    );
    if (!confirmed) {
      throw new Error("");
    }
  }
};

// publish/confluence/confluence.ts
init_hash2();
init_async();
init_log();
var CONFLUENCE_ID = "confluence";
var getAccountTokens = () => {
  const getConfluenceEnvironmentAccount = () => {
    const server = Deno.env.get("CONFLUENCE_DOMAIN");
    const name2 = Deno.env.get("CONFLUENCE_USER_EMAIL");
    const token = Deno.env.get("CONFLUENCE_AUTH_TOKEN");
    if (server && name2 && token) {
      return {
        type: 0 /* Environment */,
        name: name2,
        server: transformAtlassianDomain(server),
        token
      };
    }
  };
  const readConfluenceAccessTokens = () => {
    const result2 = readAccessTokens(CONFLUENCE_ID) ?? [];
    return result2;
  };
  let accounts = [];
  const envAccount = getConfluenceEnvironmentAccount();
  if (envAccount) {
    accounts = [...accounts, envAccount];
  }
  const tempStoredAccessTokens = readConfluenceAccessTokens();
  accounts = [...accounts, ...tempStoredAccessTokens];
  return Promise.resolve(accounts);
};
var removeToken5 = (token) => {
  const existingTokens = readAccessTokens(CONFLUENCE_ID) ?? [];
  const toWrite = existingTokens.filter(
    (accessToken) => tokenFilterOut(accessToken, token)
  );
  writeAccessTokens(CONFLUENCE_ID, toWrite);
};
var promptAndAuthorizeToken = async () => {
  const server = await Input.prompt({
    indent: "",
    message: "Confluence Domain:",
    hint: "e.g. https://mydomain.atlassian.net/",
    validate: validateServer,
    transform: transformAtlassianDomain
  });
  await verifyLocation(server);
  const name2 = await Input.prompt({
    indent: "",
    message: `Confluence Account Email:`,
    validate: validateEmail
  });
  const token = await Secret.prompt({
    indent: "",
    message: "Confluence API Token:",
    hint: "Create an API token at https://id.atlassian.com/manage/api-tokens",
    validate: validateToken
  });
  const accountToken = {
    type: 1 /* Authorized */,
    name: name2,
    server,
    token
  };
  await withSpinner(
    { message: "Verifying account..." },
    () => verifyAccountToken(accountToken)
  );
  writeAccessToken(
    CONFLUENCE_ID,
    accountToken,
    writeTokenComparator
  );
  return Promise.resolve(accountToken);
};
var promptForParentURL = async () => {
  return await Input.prompt({
    indent: "",
    message: `Space or Parent Page URL:`,
    hint: "Browse in Confluence to the space or parent, then copy the URL",
    validate: validateParentURL
  });
};
var resolveTarget5 = async (accountToken, target) => {
  return Promise.resolve(target);
};
var loadDocument = (baseDirectory, rootFile) => {
  const documentValue = Deno.readTextFileSync(join4(baseDirectory, rootFile));
  const body = wrapBodyForConfluence(documentValue);
  return body;
};
var renderDocument = async (render2) => {
  const flags = {
    to: "confluence-publish"
  };
  return await render2(flags);
};
var renderSite = async (render2) => {
  const flags = {
    to: "confluence-publish"
  };
  const renderResult = await render2(flags);
  return renderResult;
};
async function publish5(account, type4, _input, title3, _slug, render2, _options, publishRecord3) {
  trace2("publish", {
    account,
    type: type4,
    _input,
    title: title3,
    _slug,
    _options,
    publishRecord: publishRecord3
  });
  const client = new ConfluenceClient(account);
  const user = await client.getUser();
  let parentUrl = publishRecord3?.url ?? await promptForParentURL();
  const parent = confluenceParentFromString(parentUrl);
  const server = account?.server ?? "";
  await verifyConfluenceParent(parentUrl, parent);
  const space = await client.getSpace(parent.space);
  trace2("publish", { parent, server, id: space.id, key: space.key });
  await verifyOrWarnManagePermissions(client, space, parent, user);
  const uniquifyTitle = async (title4, idToIgnore = "") => {
    trace2("uniquifyTitle", title4);
    const titleIsUnique = await client.isTitleUniqueInSpace(
      title4,
      space,
      idToIgnore
    );
    if (titleIsUnique) {
      return title4;
    }
    const uuid = globalThis.crypto.randomUUID();
    const shortUUID = uuid.split("-")[0] ?? uuid;
    const uuidTitle = `${title4} ${shortUUID}`;
    return uuidTitle;
  };
  const fetchExistingSite = async (parentId) => {
    let descendants = [];
    let start = 0;
    for (let i6 = 0; i6 < MAX_PAGES_TO_LOAD; i6++) {
      const result2 = await client.getDescendantsPage(parentId, start);
      if (result2.results.length === 0) {
        break;
      }
      descendants = [...descendants, ...result2.results];
      start = start + DESCENDANT_PAGE_SIZE;
    }
    trace2("descendants.length", descendants);
    const contentProperties = await Promise.all(
      descendants.map(
        (page) => client.getContentProperty(page.id ?? "")
      )
    );
    const sitePageList = mergeSitePages(
      descendants,
      contentProperties
    );
    return sitePageList;
  };
  const uploadAttachments = (baseDirectory, attachmentsToUpload, parentId, filePath, existingAttachments = []) => {
    const uploadAttachment = async (attachmentPath) => {
      let fileBuffer;
      let fileHash;
      const path3 = join4(baseDirectory, attachmentPath);
      trace2(
        "uploadAttachment",
        {
          baseDirectory,
          attachmentPath,
          attachmentsToUpload,
          parentId,
          existingAttachments,
          path: path3
        },
        "[Attach]" /* ATTACHMENT */
      );
      try {
        fileBuffer = await Deno.readFile(path3);
        fileHash = await md5HashBytes(fileBuffer);
      } catch (error2) {
        logError2(`${path3} not found`, error2);
        return null;
      }
      const fileName = pathWithForwardSlashes(attachmentPath);
      const existingDuplicateAttachment = existingAttachments.find(
        (attachment2) => {
          return attachment2?.metadata?.comment === fileHash;
        }
      );
      if (existingDuplicateAttachment) {
        trace2(
          "existing duplicate attachment found",
          existingDuplicateAttachment.title,
          "[Attach]" /* ATTACHMENT */
        );
        return existingDuplicateAttachment;
      }
      const file = new File([fileBuffer], fileName);
      const attachment = await client.createOrUpdateAttachment(parentId, file, fileHash);
      trace2("attachment", attachment, "[Attach]" /* ATTACHMENT */);
      return attachment;
    };
    return attachmentsToUpload.map(uploadAttachment);
  };
  const updateContent = async (user2, publishFiles, id, body, titleToUpdate = title3, fileName = "", uploadFileAttachments = true) => {
    const previousPage = await client.getContent(id);
    const attachmentsToUpload = findAttachments(
      body.storage.value,
      publishFiles.files,
      fileName
    );
    let uniqueTitle = titleToUpdate;
    if (previousPage.title !== titleToUpdate) {
      uniqueTitle = await uniquifyTitle(titleToUpdate, id);
    }
    trace2("attachmentsToUpload", attachmentsToUpload, "[Attach]" /* ATTACHMENT */);
    const updatedBody = updateImagePaths(body);
    updatedBody.storage.value = footnoteTransform(updatedBody.storage.value);
    const toUpdate = {
      contentChangeType: "update" /* update */,
      id,
      version: getNextVersion(previousPage),
      title: uniqueTitle,
      type: PAGE_TYPE,
      status: "current" /* current */,
      ancestors: null,
      body: updatedBody
    };
    trace2("updateContent", toUpdate);
    trace2("updateContent body", toUpdate?.body?.storage?.value);
    const updatedContent = await client.updateContent(user2, toUpdate);
    if (toUpdate.id && uploadFileAttachments) {
      const existingAttachments = await client.getAttachments(toUpdate.id);
      trace2(
        "attachments",
        { existingAttachments, attachmentsToUpload },
        "[Attach]" /* ATTACHMENT */
      );
      const uploadAttachmentsResult = [];
      for (let i6 = 0; i6 < attachmentsToUpload.length; i6++) {
        const tasks = uploadAttachments(
          publishFiles.baseDir,
          [attachmentsToUpload[i6]],
          // <-- one at a time
          toUpdate.id,
          fileName,
          existingAttachments
        );
        const res = await tasks[0];
        uploadAttachmentsResult.push(res);
        if (i6 < attachmentsToUpload.length - 1) {
          await sleep(ATTACHMENT_UPLOAD_DELAY_MS);
        }
      }
      trace2(
        "uploadAttachmentsResult",
        uploadAttachmentsResult,
        "[Attach]" /* ATTACHMENT */
      );
    }
    return {
      content: updatedContent,
      hasAttachments: attachmentsToUpload.length > 0
    };
  };
  const createSiteParent = async (title4, body) => {
    let ancestors = [];
    if (parent?.parent) {
      ancestors = [{ id: parent.parent }];
    } else if (space.homepage?.id) {
      ancestors = [{ id: space.homepage?.id }];
    }
    const toCreate = {
      contentChangeType: "create" /* create */,
      title: title4,
      type: PAGE_TYPE,
      space,
      status: "current" /* current */,
      ancestors,
      body
    };
    const createdContent = await client.createContent(user, toCreate);
    return createdContent;
  };
  const checkToCreateSiteParent = async (parentId = "") => {
    let isQuartoSiteParent = false;
    const existingSiteParent = await client.getContent(parentId);
    if (existingSiteParent?.id) {
      const siteParentContentProperties = await client.getContentProperty(existingSiteParent.id ?? "");
      isQuartoSiteParent = siteParentContentProperties.find(
        (property) => property.key === "isQuartoSiteParent" /* isQuartoSiteParent */
      ) !== void 0;
    }
    if (!isQuartoSiteParent) {
      const body = {
        storage: {
          value: "",
          representation: "storage" /* storage */
        }
      };
      const siteParentTitle = await uniquifyTitle(title3);
      const siteParent = await createSiteParent(
        siteParentTitle,
        body
      );
      const newSiteParentId = siteParent.id ?? "";
      const contentProperty = await client.createContentProperty(
        newSiteParentId,
        { key: "isQuartoSiteParent" /* isQuartoSiteParent */, value: true }
      );
      parentId = newSiteParentId;
    }
    return parentId;
  };
  const createContent2 = async (publishFiles, body, titleToCreate = title3, createParent = parent, fileNameParam = "") => {
    const createTitle = await uniquifyTitle(titleToCreate);
    const fileName = pathWithForwardSlashes(fileNameParam);
    const attachmentsToUpload = findAttachments(
      body.storage.value,
      publishFiles.files,
      fileName
    );
    trace2("attachmentsToUpload", attachmentsToUpload, "[Attach]" /* ATTACHMENT */);
    const updatedBody = updateImagePaths(body);
    updatedBody.storage.value = footnoteTransform(updatedBody.storage.value);
    const toCreate = {
      contentChangeType: "create" /* create */,
      title: createTitle,
      type: PAGE_TYPE,
      space,
      status: "current" /* current */,
      ancestors: createParent?.parent ? [{ id: createParent.parent }] : null,
      body: updatedBody
    };
    trace2("createContent", { publishFiles, toCreate });
    const createdContent = await client.createContent(user, toCreate);
    if (createdContent.id) {
      const uploadAttachmentsResult = await Promise.all(
        uploadAttachments(
          publishFiles.baseDir,
          attachmentsToUpload,
          createdContent.id,
          fileName
        )
      );
      trace2(
        "uploadAttachmentsResult",
        uploadAttachmentsResult,
        "[Attach]" /* ATTACHMENT */
      );
    }
    return {
      content: createdContent,
      hasAttachments: attachmentsToUpload.length > 0
    };
  };
  const publishDocument2 = async () => {
    const publishFiles = await renderDocument(render2);
    const body = loadDocument(
      publishFiles.baseDir,
      publishFiles.rootFile
    );
    trace2("publishDocument", { publishFiles, body }, "[Render]" /* RENDER */);
    let publishResult;
    let message = "";
    let doOperation;
    if (publishRecord3) {
      message = `Updating content at ${publishRecord3.url}...`;
      doOperation = async () => {
        const result2 = await updateContent(
          user,
          publishFiles,
          publishRecord3.id,
          body
        );
        publishResult = result2;
      };
    } else {
      message = `Creating content in space ${parent.space}...`;
      doOperation = async () => {
        const result2 = await createContent2(publishFiles, body);
        publishResult = result2;
      };
    }
    try {
      await doWithSpinner(message, doOperation);
      return [
        buildPublishRecordForContent(server, publishResult?.content),
        !!publishResult?.hasAttachments
      ];
    } catch (error2) {
      trace2("Error Performing Operation", error2);
      trace2("Value to Update", body?.storage?.value);
      throw error2;
    }
  };
  const publishSite2 = async () => {
    let parentId = parent?.parent ?? space.homepage.id ?? "";
    parentId = await checkToCreateSiteParent(parentId);
    const siteParent = {
      space: parent.space,
      parent: parentId
    };
    let existingSite = await fetchExistingSite(parentId);
    trace2("existingSite", existingSite);
    const publishFiles = await renderSite(render2);
    const metadataByInput = publishFiles.metadataByInput ?? {};
    trace2("metadataByInput", metadataByInput);
    trace2("publishSite", {
      parentId,
      publishFiles
    });
    const filteredFiles = filterFilesForUpdate(publishFiles.files);
    trace2("filteredFiles", filteredFiles);
    const assembleSiteFileMetadata = async (fileName) => {
      const fileToContentBody = async (fileName2) => {
        return loadDocument(publishFiles.baseDir, fileName2);
      };
      const originalTitle = getTitle(fileName, metadataByInput);
      const title4 = originalTitle;
      return await {
        fileName,
        title: title4,
        originalTitle,
        contentBody: await fileToContentBody(fileName)
      };
    };
    const fileMetadata = await Promise.all(
      filteredFiles.map(assembleSiteFileMetadata)
    );
    trace2("fileMetadata", fileMetadata);
    let metadataByFilename = buildFileToMetaTable(existingSite);
    trace2("metadataByFilename", metadataByFilename);
    let changeList = buildSpaceChanges(
      fileMetadata,
      siteParent,
      space,
      existingSite
    );
    changeList = flattenIndexes(changeList, metadataByFilename, parentId);
    const { pass1Changes, pass2Changes } = updateLinks(
      metadataByFilename,
      changeList,
      server,
      siteParent
    );
    changeList = pass1Changes;
    trace2("changelist Pass 1", changeList);
    let pathsToId = {};
    const handleChangeError = (label, currentChange, error2) => {
      if (isContentUpdate(currentChange) || isContentCreate(currentChange)) {
        trace2("currentChange.fileName", currentChange.fileName);
        trace2("Value to Update", currentChange.body.storage.value);
      }
      if (EXIT_ON_ERROR) {
        throw error2;
      }
    };
    let hasAttachments = false;
    const doChange = async (change, uploadFileAttachments = true) => {
      if (isContentCreate(change)) {
        if (change.fileName === "sitemap.xml") {
          trace2("sitemap.xml skipped", change);
          return;
        }
        let ancestorId = (change?.ancestors && change?.ancestors[0]?.id) ?? null;
        if (ancestorId && pathsToId[ancestorId]) {
          ancestorId = pathsToId[ancestorId];
        }
        const ancestorParent = {
          space: parent.space,
          parent: ancestorId ?? siteParent.parent
        };
        const universalPath = pathWithForwardSlashes(change.fileName ?? "");
        const result2 = await createContent2(
          publishFiles,
          change.body,
          change.title ?? "",
          ancestorParent,
          universalPath
        );
        if (universalPath) {
          pathsToId[universalPath] = result2.content.id ?? "";
        }
        const contentPropertyResult = await client.createContentProperty(result2.content.id ?? "", {
          key: "fileName" /* fileName */,
          value: change.fileName
        });
        hasAttachments = hasAttachments || result2.hasAttachments;
        return result2;
      } else if (isContentUpdate(change)) {
        const update = change;
        const result2 = await updateContent(
          user,
          publishFiles,
          update.id ?? "",
          update.body,
          update.title ?? "",
          update.fileName ?? "",
          uploadFileAttachments
        );
        hasAttachments = hasAttachments || result2.hasAttachments;
        return result2;
      } else if (isContentDelete(change)) {
        if (DELETE_DISABLED) {
          console.warn("DELETE DISABELD");
          return null;
        }
        const result2 = await client.deleteContent(change);
        await sleep(DELETE_SLEEP_MILLIS);
        return { content: result2, hasAttachments: false };
      } else {
        console.error("Space Change not defined");
        return null;
      }
    };
    let pass1Count = 0;
    for (let currentChange of changeList) {
      try {
        pass1Count = pass1Count + 1;
        const doOperation = async () => await doChange(currentChange);
        await doWithSpinner(
          `Site Updates [${pass1Count}/${changeList.length}]`,
          doOperation
        );
      } catch (error2) {
        handleChangeError(
          "Error Performing Change Pass 1",
          currentChange,
          error2
        );
      }
    }
    if (pass2Changes.length) {
      trace2("changelist Pass 2", pass2Changes);
      existingSite = await fetchExistingSite(parentId);
      metadataByFilename = buildFileToMetaTable(existingSite);
      const linkUpdateChanges = convertForSecondPass(
        metadataByFilename,
        pass2Changes,
        server,
        parent
      );
      let pass2Count = 0;
      for (let currentChange of linkUpdateChanges) {
        try {
          pass2Count = pass2Count + 1;
          const doOperation = async () => await doChange(currentChange, false);
          await doWithSpinner(
            `Updating Links [${pass2Count}/${linkUpdateChanges.length}]`,
            doOperation
          );
        } catch (error2) {
          handleChangeError(
            "Error Performing Change Pass 2",
            currentChange,
            error2
          );
        }
      }
    }
    const parentPage = await client.getContent(parentId);
    return [buildPublishRecordForContent(server, parentPage), hasAttachments];
  };
  if (type4 === "document" /* document */) {
    const [publishResult, hasAttachments] = await publishDocument2();
    if (hasAttachments) {
      info(
        "\nNote: The published content includes attachments or images. You may see a placeholder for a few moments while Confluence processes the image or attachment.\n"
      );
    }
    return publishResult;
  } else {
    const [publishResult, hasAttachments] = await publishSite2();
    if (hasAttachments) {
      info(
        "\nNote: The published content includes attachments or images. You may see a placeholder for a few moments while Confluence processes the image or attachment.\n"
      );
    }
    return publishResult;
  }
}
var confluenceProvider = {
  name: CONFLUENCE_ID,
  description: "Confluence",
  hidden: false,
  requiresServer: true,
  requiresRender: true,
  accountTokens: getAccountTokens,
  authorizeToken: promptAndAuthorizeToken,
  removeToken: removeToken5,
  resolveTarget: resolveTarget5,
  publish: publish5,
  isUnauthorized: isUnauthorized5,
  isNotFound: isNotFound5
};

// publish/huggingface/huggingface.ts
init_log();
init_path();
init_colors2();
init_git();
init_asserts();
var kHuggingFace = "huggingface";
var kHuggingFaceDescription = "Hugging Face Spaces";
var huggingfaceProvider = {
  name: kHuggingFace,
  description: kHuggingFaceDescription,
  requiresServer: false,
  listOriginOnly: false,
  accountTokens: () => Promise.resolve([anonymousAccount()]),
  authorizeToken: authorizeToken5,
  removeToken: () => {
  },
  publishRecord: publishRecord2,
  resolveTarget: (_account, target) => Promise.resolve(target),
  publish: publish6,
  isUnauthorized: () => false,
  isNotFound: () => false,
  resolveProjectPath: (path3) => join4(path3, "src")
};
async function authorizeToken5(options) {
  const ghContext = await gitHubContextForPublish(options.input);
  const provider = "Hugging Face Spaces";
  verifyContext(ghContext, provider);
  if (!ghContext.originUrl.match(/^https:\/\/(.*:.*@)?huggingface.co\/spaces\//)) {
    throwUnableToPublish(
      "the git repository does not appear to have a Hugging Face Space origin",
      provider
    );
  }
  return Promise.resolve(anonymousAccount());
}
async function publishRecord2(input) {
  const ghContext = await gitHubContextForPublish(input);
  if (ghContext.ghPagesRemote) {
    return {
      id: kHuggingFace,
      url: ghContext.siteUrl || ghContext.originUrl
    };
  }
}
async function publish6(_account, _type, input, _title, _slug, _render, options, _target) {
  input = Deno.statSync(input).isDirectory ? input : dirname4(input);
  const version4 = await gitVersion();
  if (version4.compare("2.17.0") < 0) {
    throw new Error(
      "git version 2.17.0 or higher is required to publish to GitHub Pages"
    );
  }
  const ghContext = await gitHubContextForPublish(options.input);
  verifyContext(ghContext, "Hugging Face Spaces");
  if (!ghContext.originUrl.match(/^https:\/\/.*:.*@huggingface.co\/spaces\//)) {
    const previousRemotePath = ghContext.originUrl.match(
      /.*huggingface.co(\/spaces\/.*)/
    );
    assert7(previousRemotePath);
    info(yellow3([
      "The current git repository needs to be reconfigured to allow `quarto publish`",
      "to publish to Hugging Face Spaces. Please enter your username and authentication token.",
      "Refer to https://huggingface.co/blog/password-git-deprecation#switching-to-personal-access-token",
      "for more information on how to obtain a personal access token."
    ].join("\n")));
    const username = await Input.prompt({
      indent: "",
      message: "Hugging Face username"
    });
    const token = await Secret.prompt({
      indent: "",
      message: "Hugging Face authentication token:",
      hint: "Create a token at https://huggingface.co/settings/tokens"
    });
    await gitCmds(input, [
      [
        "remote",
        "set-url",
        "origin",
        `https://${username}:${token}@huggingface.co${previousRemotePath[1]}`
      ]
    ]);
  }
  await gitCmds(input, [
    ["stash"],
    ["fetch", "origin", "main"]
  ]);
  try {
    await gitCmds(input, [
      ["merge", "origin/main"]
    ]);
  } catch (_e) {
    info(yellow3([
      "Could not merge origin/main. This is likely because of git conflicts.",
      "Please resolve those manually and run `quarto publish` again."
    ].join("\n")));
    return Promise.resolve([
      void 0,
      void 0
    ]);
  }
  try {
    await gitCmds(input, [
      ["stash", "pop"]
    ]);
  } catch (_e) {
    info(yellow3([
      "Could not pop git stash.",
      "This is likely because there are no changes to push to the repository."
    ].join("\n")));
    return Promise.resolve([
      void 0,
      void 0
    ]);
  }
  await gitCmds(input, [
    ["add", "-Af", "."],
    ["commit", "--allow-empty", "-m", "commit from `quarto publish`"],
    ["push", "origin", "main"]
  ]);
  info(yellow3(
    "NOTE: Hugging Face Space sites build the content remotely and use caching.\nYou will need to wait a moment for Hugging Face to rebuild your site, and\nthen click the refresh button within your web browser to see changes after deployment.\n\nSpecifically, you need to:\n- wait for your space's status to go from 'Building' to 'Running'\n  (this is visible in the status bar above the space)\n- force-reload the web page by holding Shift and hitting the reload button in your browser.\n"
  ));
  await new Promise((resolve16) => setTimeout(resolve16, 3e3));
  return Promise.resolve([
    void 0,
    new URL(ghContext.originUrl)
  ]);
}

// publish/posit-connect-cloud/posit-connect-cloud.ts
init_log();
init_colors2();
init_temp();
init_wait();

// publish/posit-connect-cloud/api/index.ts
init_log();
init_wait();
init_quarto();
var kProviderName = "posit-connect-cloud";
var kOAuthScope = "vivid";
var publishDebug = (msg5) => debug(`[publish][posit-connect-cloud] ${msg5}`);
var kEnvironments = {
  production: {
    authHost: "login.posit.cloud",
    apiHost: "api.connect.posit.cloud",
    uiHost: "connect.posit.cloud",
    clientId: "quarto-cli"
  },
  staging: {
    authHost: "login.staging.posit.cloud",
    apiHost: "api.staging.connect.posit.cloud",
    uiHost: "staging.connect.posit.cloud",
    clientId: "quarto-cli-staging"
  },
  development: {
    authHost: "login.staging.posit.cloud",
    apiHost: "api.dev.connect.posit.cloud",
    uiHost: "dev.connect.posit.cloud",
    clientId: "quarto-cli-staging"
  }
};
function getEnvironment() {
  const env2 = Deno.env.get("POSIT_CONNECT_CLOUD_ENVIRONMENT");
  if (env2 === "staging" || env2 === "development" || env2 === "production") {
    return env2;
  }
  return "production";
}
function getEnvironmentConfig() {
  return kEnvironments[getEnvironment()];
}
var kRefreshThresholdMs = 5 * 60 * 1e3;
var PositConnectCloudClient = class {
  env_;
  accessToken_;
  storedToken_;
  constructor(accessToken, storedToken) {
    this.env_ = getEnvironmentConfig();
    this.accessToken_ = accessToken;
    this.storedToken_ = storedToken;
    publishDebug(
      `Client created for ${this.env_.apiHost}`
    );
  }
  // --- API Methods ---
  async getUser() {
    return await this.apiGet("users/me");
  }
  // Single-page fetch is sufficient: Connect Cloud limits accounts per user
  // (typically 1-3), and has_user_role=true further restricts the result set.
  async listAccounts() {
    const response = await this.apiGet(
      "accounts?has_user_role=true"
    );
    return response.data;
  }
  async createContent(accountId, title3, primaryFile) {
    const body = {
      account_id: accountId,
      title: title3,
      next_revision: {
        source_type: "bundle",
        content_type: "static",
        app_mode: "static",
        primary_file: primaryFile
      },
      secrets: []
    };
    publishDebug(
      `POST /contents (title: ${title3}, account: ${accountId})`
    );
    return await this.apiPost("contents", body);
  }
  async getContent(contentId) {
    return await this.apiGet(`contents/${contentId}`);
  }
  async updateContent(contentId, primaryFile) {
    const body = {
      secrets: [],
      revision_overrides: {
        primary_file: primaryFile,
        app_mode: "static"
      }
    };
    publishDebug(
      `PATCH /contents/${contentId}?new_bundle=true`
    );
    return await this.apiFetch(
      "PATCH",
      `contents/${contentId}?new_bundle=true`,
      body
    );
  }
  async uploadBundle(uploadUrl, bundleData) {
    publishDebug(
      `Uploading bundle (${bundleData.length} bytes)`
    );
    const response = await fetch(uploadUrl, {
      method: "POST",
      headers: {
        "Content-Type": "application/gzip"
      },
      body: bundleData
    });
    if (!response.ok) {
      const text = await response.text().catch(() => "");
      throw new ApiError2(
        response.status,
        response.statusText,
        text || void 0
      );
    }
    publishDebug("Bundle uploaded successfully");
  }
  async publishContent(contentId) {
    publishDebug(`POST /contents/${contentId}/publish`);
    const url = this.buildUrl_(`contents/${contentId}/publish`);
    const response = await this.fetchWithRetry_("POST", url, {
      "Accept": "application/json"
    }, void 0);
    await response.arrayBuffer();
  }
  async getRevision(revisionId) {
    return await this.apiGet(`revisions/${revisionId}`);
  }
  buildUrl_(path3) {
    return `https://${this.env_.apiHost}/v1/${path3}`;
  }
  contentUrl(accountName, contentId) {
    return `https://${this.env_.uiHost}/${accountName}/content/${contentId}`;
  }
  accountCreationUrl() {
    return `https://${this.env_.uiHost}/account/done?utm_source=quarto-cli`;
  }
  // --- Token Refresh ---
  async ensureValidToken_() {
    if (!this.storedToken_) return;
    if (this.storedToken_.expiresAt === 0) return;
    const now = Date.now();
    if (now >= this.storedToken_.expiresAt - kRefreshThresholdMs) {
      publishDebug(
        "Token refresh: proactive (expires soon)"
      );
      await this.tryRefreshToken_();
    }
  }
  async tryRefreshToken_() {
    if (!this.storedToken_?.refreshToken) return false;
    try {
      const tokenResponse = await refreshAccessToken(
        this.env_,
        this.storedToken_.refreshToken
      );
      this.accessToken_ = tokenResponse.access_token;
      this.storedToken_ = {
        ...this.storedToken_,
        accessToken: tokenResponse.access_token,
        refreshToken: tokenResponse.refresh_token,
        expiresAt: Date.now() + tokenResponse.expires_in * 1e3
      };
      if (this.storedToken_.accountId) {
        writeAccessToken(
          kProviderName,
          this.storedToken_,
          (a5, b3) => a5.accountId === b3.accountId && a5.environment === b3.environment
        );
        publishDebug("Token refreshed and persisted");
      } else {
        publishDebug("Token refreshed (in-memory only, env token)");
      }
      return true;
    } catch (err2) {
      publishDebug(
        `Token refresh failed: ${err2}`
      );
      return false;
    }
  }
  // --- HTTP primitives with token refresh ---
  async apiGet(path3) {
    return await this.apiFetch("GET", path3);
  }
  async apiPost(path3, body) {
    return await this.apiFetch("POST", path3, body);
  }
  async apiFetch(method, path3, body) {
    const url = this.buildUrl_(path3);
    const headers = {
      "Accept": "application/json"
    };
    if (body) {
      headers["Content-Type"] = "application/json";
    }
    const response = await this.fetchWithRetry_(
      method,
      url,
      headers,
      body ? JSON.stringify(body) : void 0
    );
    return await response.json();
  }
  async fetchWithRetry_(method, url, headers, body) {
    await this.ensureValidToken_();
    const buildHeaders = () => ({
      ...headers,
      "Authorization": `Bearer ${this.accessToken_}`,
      "User-Agent": `quarto-cli/${quartoConfig.version()}`
    });
    const response = await fetch(url, {
      method,
      headers: buildHeaders(),
      body
    });
    if (response.ok) {
      return response;
    }
    if (response.status === 401 && await this.tryRefreshToken_()) {
      await response.arrayBuffer();
      publishDebug("Retrying after token refresh");
      const retryResponse = await fetch(url, {
        method,
        headers: buildHeaders(),
        body
      });
      if (retryResponse.ok) {
        return retryResponse;
      }
      const text = await retryResponse.text().catch(() => "");
      throw new ApiError2(
        retryResponse.status,
        retryResponse.statusText,
        text || void 0
      );
    }
    const description = await response.text().catch(() => void 0);
    throw new ApiError2(response.status, response.statusText, description);
  }
};
function postFormUrlEncoded(url, params) {
  return fetch(url, {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: params.toString()
  });
}
async function initiateDeviceAuth(env2) {
  const params = new URLSearchParams({
    scope: kOAuthScope,
    client_id: env2.clientId
  });
  publishDebug(
    `OAuth: initiating device authorization (client_id: ${env2.clientId})`
  );
  const response = await postFormUrlEncoded(
    `https://${env2.authHost}/oauth/device/authorize`,
    params
  );
  if (!response.ok) {
    const text = await response.text().catch(() => "");
    throw new ApiError2(
      response.status,
      response.statusText,
      text || void 0
    );
  }
  return await response.json();
}
async function pollForToken(env2, deviceCode, initialInterval, expiresIn) {
  let interval = Math.max(initialInterval, 5);
  const params = new URLSearchParams({
    scope: kOAuthScope,
    client_id: env2.clientId,
    grant_type: "urn:ietf:params:oauth:grant-type:device_code",
    device_code: deviceCode
  });
  const url = `https://${env2.authHost}/oauth/token`;
  const startTime = Date.now();
  const timeoutMs = expiresIn * 1e3;
  while (true) {
    if (Date.now() - startTime > timeoutMs) {
      throw new Error(
        "Authorization timed out. The verification code has expired. Please try again."
      );
    }
    publishDebug(
      `OAuth: polling for token (interval: ${interval}s)`
    );
    await sleep2(interval * 1e3);
    const response = await postFormUrlEncoded(url, params);
    if (response.ok) {
      publishDebug("OAuth: token received");
      return await response.json();
    }
    const body = await response.text();
    let errorCode;
    try {
      const parsed = JSON.parse(body);
      errorCode = parsed.error || body;
    } catch {
      errorCode = body.trim();
    }
    switch (errorCode) {
      case "authorization_pending":
        break;
      case "slow_down":
        interval += 5;
        publishDebug(
          `OAuth: slow_down, new interval: ${interval}s`
        );
        break;
      case "expired_token":
        throw new Error(
          "Authorization timed out. The verification code has expired. Please try again."
        );
      case "access_denied":
        throw new Error(
          "Authorization was denied. Please try again and approve the request."
        );
      default:
        throw new ApiError2(
          response.status,
          response.statusText,
          `Unexpected OAuth error: ${errorCode}`
        );
    }
  }
}
async function refreshAccessToken(env2, refreshToken) {
  const params = new URLSearchParams({
    scope: kOAuthScope,
    client_id: env2.clientId,
    grant_type: "refresh_token",
    refresh_token: refreshToken
  });
  publishDebug("Refreshing access token");
  const response = await postFormUrlEncoded(
    `https://${env2.authHost}/oauth/token`,
    params
  );
  if (!response.ok) {
    const text = await response.text().catch(() => "");
    throw new ApiError2(
      response.status,
      response.statusText,
      text || void 0
    );
  }
  return await response.json();
}
function readStoredTokens() {
  return readAccessTokens(kProviderName) || [];
}
function writeStoredTokens(tokens2) {
  writeAccessTokens(kProviderName, tokens2);
}
function writeStoredToken(token) {
  writeAccessToken(
    kProviderName,
    token,
    (a5, b3) => a5.accountId === b3.accountId && a5.environment === b3.environment
  );
}

// publish/posit-connect-cloud/posit-connect-cloud.ts
var kPositConnectCloud = "posit-connect-cloud";
var kPositConnectCloudDescription = "Posit Connect Cloud";
var kPositConnectCloudAccessTokenVar = "POSIT_CONNECT_CLOUD_ACCESS_TOKEN";
var kPositConnectCloudRefreshTokenVar = "POSIT_CONNECT_CLOUD_REFRESH_TOKEN";
var kPositConnectCloudAccountIdVar = "POSIT_CONNECT_CLOUD_ACCOUNT_ID";
var kRevisionPollTimeoutMs = 30 * 60 * 1e3;
var positConnectCloudProvider = {
  name: kPositConnectCloud,
  description: kPositConnectCloudDescription,
  requiresServer: false,
  listOriginOnly: false,
  accountTokens: accountTokens5,
  authorizeToken: authorizeToken6,
  removeToken: removeToken6,
  resolveTarget: resolveTarget6,
  publish: publish7,
  isUnauthorized: isUnauthorized6,
  isNotFound: isNotFound6
};
function accountTokens5() {
  const accounts = [];
  const env2 = getEnvironmentConfig();
  const serverUrl = `https://${env2.uiHost}`;
  const envToken = Deno.env.get(kPositConnectCloudAccessTokenVar);
  if (envToken) {
    accounts.push({
      type: 0 /* Environment */,
      name: kPositConnectCloudAccessTokenVar,
      server: serverUrl,
      token: envToken
    });
  }
  const storedTokens = readStoredTokens();
  const currentEnv = getEnvironment();
  for (const stored of storedTokens) {
    if (stored.environment === currentEnv) {
      accounts.push({
        type: 1 /* Authorized */,
        name: stored.accountName,
        server: serverUrl,
        token: stored.accessToken
      });
    }
  }
  return Promise.resolve(accounts);
}
async function authorizeToken6(_options) {
  if (!await authorizePrompt(positConnectCloudProvider)) {
    return void 0;
  }
  const env2 = getEnvironmentConfig();
  publishDebug(
    `Starting authorization (env: ${getEnvironment()}, client_id: ${env2.clientId})`
  );
  const deviceAuth = await initiateDeviceAuth(env2);
  info("");
  info(
    `  Your authorization code is: ${bold3(green2(deviceAuth.user_code))}`
  );
  info("");
  const authUrlObj = new URL(deviceAuth.verification_uri_complete);
  authUrlObj.searchParams.set("utm_source", "quarto-cli");
  const authUrl = authUrlObj.toString();
  if (isServerSession()) {
    info(
      "  Please open this URL to authorize: " + underline2(authUrl)
    );
  } else {
    info("  Opening browser to authorize...");
    await openUrl(authUrl);
  }
  info("");
  const tokenResponse = await pollForToken(
    env2,
    deviceAuth.device_code,
    deviceAuth.interval,
    deviceAuth.expires_in
  );
  const client = new PositConnectCloudClient(tokenResponse.access_token);
  try {
    const user = await client.getUser();
    publishDebug(
      `Authenticated as: ${user.display_name} (${user.email})`
    );
  } catch (err2) {
    if (!isUnauthorized6(err2)) {
      throw err2;
    }
    publishDebug("getUser returned 401 \u2014 signup may be incomplete");
  }
  let accounts;
  try {
    accounts = await client.listAccounts();
  } catch (err2) {
    if (isUnauthorized6(err2)) {
      accounts = [];
    } else {
      throw err2;
    }
  }
  const publishableAccounts = accounts.filter(
    (a5) => a5.permissions?.includes("content:create")
  );
  let publishable = publishableAccounts;
  if (publishable.length === 0) {
    info("  No publishable accounts found. Opening account setup...");
    const accountUrl = client.accountCreationUrl();
    if (isServerSession()) {
      info(
        "  Please open this URL to create an account: " + underline2(accountUrl)
      );
    } else {
      await openUrl(accountUrl);
    }
    const kMaxAttempts = 300;
    const kPollInterval = 2e3;
    let found = [];
    await withSpinner({
      message: "Waiting for account setup"
    }, async () => {
      for (let i6 = 0; i6 < kMaxAttempts; i6++) {
        await sleep2(kPollInterval);
        try {
          const refreshed = await client.listAccounts();
          found = refreshed.filter(
            (a5) => a5.permissions?.includes("content:create")
          );
          if (found.length > 0) break;
        } catch (err2) {
          if (err2 instanceof ApiError2 || err2 instanceof TypeError) {
            publishDebug(
              `Account polling error (will retry): ${err2}`
            );
          } else {
            throw err2;
          }
        }
      }
    });
    if (found.length === 0) {
      throw new Error(
        "Timed out waiting for account setup. Please complete account setup and try again."
      );
    }
    publishable = found;
  }
  let selectedAccount;
  if (publishable.length === 1) {
    selectedAccount = publishable[0];
    publishDebug(
      `Auto-selected account: ${selectedAccount.name}`
    );
  } else {
    const selectedIdx = await Select.prompt({
      indent: "",
      message: "Select account:",
      options: publishable.map((a5, i6) => ({
        name: a5.display_name ? `${a5.display_name} (${a5.name})` : a5.name,
        value: String(i6)
      }))
    });
    selectedAccount = publishable[Number(selectedIdx)];
  }
  info(
    `  Authorized to publish as ${bold3(selectedAccount.display_name || selectedAccount.name)}`
  );
  const storedToken = {
    username: selectedAccount.display_name || selectedAccount.name,
    accountId: selectedAccount.id,
    accountName: selectedAccount.name,
    accessToken: tokenResponse.access_token,
    refreshToken: tokenResponse.refresh_token,
    expiresAt: Date.now() + tokenResponse.expires_in * 1e3,
    environment: getEnvironment()
  };
  writeStoredToken(storedToken);
  publishDebug("Token stored");
  return {
    type: 1 /* Authorized */,
    name: selectedAccount.name,
    server: `https://${env2.uiHost}`,
    token: tokenResponse.access_token
  };
}
function removeToken6(token) {
  const currentEnv = getEnvironment();
  const tokens2 = readStoredTokens().filter(
    (stored) => !(stored.accountName === token.name && stored.environment === currentEnv)
  );
  writeStoredTokens(tokens2);
}
async function resolveTarget6(account, target) {
  const storedToken = findStoredToken(account);
  const client = clientForAccount(account, storedToken);
  try {
    const content = await client.getContent(target.id);
    if (content.state === "deleted") {
      publishDebug(
        `Content ${target.id} is deleted, treating as not found`
      );
      return void 0;
    }
    return {
      id: content.id,
      url: target.url,
      code: false
    };
  } catch (err2) {
    if (isNotFound6(err2)) {
      publishDebug(
        `Content ${target.id} not found (404), treating as not found`
      );
      return void 0;
    }
    throw err2;
  }
}
async function publish7(account, type4, _input, title3, _slug, render2, options, target) {
  if (options.token) {
    throw new Error(
      "Posit Connect Cloud does not support --token. For CI/CD, use environment variables: POSIT_CONNECT_CLOUD_ACCESS_TOKEN, POSIT_CONNECT_CLOUD_REFRESH_TOKEN, and POSIT_CONNECT_CLOUD_ACCOUNT_ID."
    );
  }
  const storedToken = findStoredToken(account);
  const client = clientForAccount(account, storedToken);
  let accountName = storedToken?.accountName || account.name;
  let accountId = storedToken?.accountId || "";
  if (!storedToken && account.type === 0 /* Environment */) {
    publishDebug(
      "Resolving account for environment token"
    );
    const accounts = await client.listAccounts();
    const publishable = accounts.filter(
      (a5) => a5.permissions?.includes("content:create")
    );
    if (publishable.length === 0) {
      throw new Error(
        "No publishable accounts found for the provided access token."
      );
    }
    const envAccountId = Deno.env.get(kPositConnectCloudAccountIdVar)?.trim();
    if (envAccountId) {
      const match = publishable.find((a5) => a5.id === envAccountId);
      if (!match) {
        throw new Error(
          `Account ${envAccountId} not found or lacks content:create permission.`
        );
      }
      accountName = match.name;
      accountId = match.id;
    } else {
      if (publishable.length > 1 && !options.prompt) {
        throw new Error(
          `Multiple publishable accounts found. Set ${kPositConnectCloudAccountIdVar} to select a specific account.`
        );
      }
      accountName = publishable[0].name;
      accountId = publishable[0].id;
      if (publishable.length > 1) {
        warn(
          `Multiple publishable accounts found. Using "${accountName}". Set ${kPositConnectCloudAccountIdVar} to select a specific account.`
        );
      }
    }
    publishDebug(
      `Resolved account: ${accountName} (${accountId})`
    );
  }
  const { contentId, revisionId, uploadUrl } = await withSpinner({
    message: `Preparing to publish ${type4}`
  }, async () => {
    if (!target) {
      if (!accountId?.trim()) {
        throw new Error(
          "Account ID not found. Please re-authorize with 'quarto publish posit-connect-cloud --authorize'."
        );
      }
      publishDebug("Creating new content");
      const content = await client.createContent(
        accountId,
        title3,
        "index.html"
      );
      if (!content.next_revision?.source_bundle_upload_url) {
        throw new Error(
          "Content creation did not return an upload URL"
        );
      }
      publishDebug(
        `Content created: ${content.id}`
      );
      return {
        contentId: content.id,
        revisionId: content.next_revision.id,
        uploadUrl: content.next_revision.source_bundle_upload_url
      };
    } else {
      const content = await client.getContent(target.id);
      if (content.state === "deleted") {
        throw new Error(
          "Content has been deleted on Connect Cloud. Remove the publish record from _publish.yml and try again."
        );
      }
      if (content.current_revision === null) {
        publishDebug(
          "First publish (no current_revision), using existing next_revision"
        );
        if (!content.next_revision?.source_bundle_upload_url) {
          throw new Error(
            "Content has no upload URL in next_revision"
          );
        }
        return {
          contentId: content.id,
          revisionId: content.next_revision.id,
          uploadUrl: content.next_revision.source_bundle_upload_url
        };
      } else {
        publishDebug("Updating existing content");
        const updated = await client.updateContent(
          content.id,
          "index.html"
        );
        if (!updated.next_revision?.source_bundle_upload_url) {
          throw new Error(
            "Content update did not return an upload URL"
          );
        }
        return {
          contentId: content.id,
          revisionId: updated.next_revision.id,
          uploadUrl: updated.next_revision.source_bundle_upload_url
        };
      }
    }
  });
  info("");
  const publishFiles = await renderForPublish(
    render2,
    kPositConnectCloud,
    type4,
    title3
  );
  const tempContext2 = createTempContext();
  try {
    await withSpinner({
      message: () => "Uploading files"
    }, async () => {
      const { bundlePath } = await createBundle(
        type4,
        publishFiles,
        tempContext2
      );
      const bundleBytes = await Deno.readFile(bundlePath);
      publishDebug(
        `Bundle: ${publishFiles.files.length} files, ${bundleBytes.length} bytes compressed`
      );
      await client.uploadBundle(uploadUrl, bundleBytes);
    });
    await withSpinner({
      message: `Publishing ${type4}`
    }, async () => {
      await client.publishContent(contentId);
      const pollStartTime = Date.now();
      let lastStatus = "";
      let consecutiveErrors = 0;
      const kMaxConsecutiveErrors = 5;
      while (true) {
        if (Date.now() - pollStartTime > kRevisionPollTimeoutMs) {
          throw new Error(
            "Timed out waiting for publish to complete. Check the Connect Cloud dashboard for status."
          );
        }
        let revision;
        try {
          revision = await client.getRevision(revisionId);
          consecutiveErrors = 0;
        } catch (err2) {
          if (err2 instanceof ApiError2 || err2 instanceof TypeError) {
            consecutiveErrors++;
            publishDebug(
              `Revision poll error (${consecutiveErrors}/${kMaxConsecutiveErrors}): ${err2}`
            );
            if (consecutiveErrors >= kMaxConsecutiveErrors) {
              throw new Error(
                "Lost connection to Connect Cloud while monitoring deployment. The deployment may still succeed \u2014 check the dashboard for status."
              );
            }
            await sleep2(2e3);
            continue;
          }
          throw err2;
        }
        if (revision.status && revision.status !== lastStatus) {
          publishDebug(
            `Revision status: ${revision.status}`
          );
          lastStatus = revision.status;
        }
        if (revision.publish_result === "success") {
          break;
        } else if (revision.publish_result === "failure") {
          const errorMsg = revision.publish_error_details || revision.publish_error || "Unknown publish error";
          throw new Error(`Publish failed: ${errorMsg}`);
        } else if (revision.publish_result !== null) {
          throw new Error(
            `Unexpected publish result: ${revision.publish_result}`
          );
        }
        await sleep2(1e3);
      }
    });
    const contentUrl = client.contentUrl(accountName, contentId);
    completeMessage(`Published: ${contentUrl}
`);
    const publishRecord3 = {
      id: contentId,
      url: contentUrl,
      code: false
    };
    return [publishRecord3, new URL(contentUrl)];
  } finally {
    tempContext2.cleanup();
  }
}
function isUnauthorized6(err2) {
  return err2 instanceof ApiError2 && err2.status === 401;
}
function isNotFound6(err2) {
  return err2 instanceof ApiError2 && err2.status === 404;
}
function clientForAccount(account, storedToken) {
  if (account.type === 0 /* Environment */) {
    const refreshToken = Deno.env.get(kPositConnectCloudRefreshTokenVar);
    if (refreshToken) {
      const pseudoToken = {
        username: account.name,
        accountId: "",
        accountName: account.name,
        accessToken: account.token,
        refreshToken,
        expiresAt: 0,
        // Unknown for env tokens; rely on reactive refresh
        environment: getEnvironment()
      };
      return new PositConnectCloudClient(account.token, pseudoToken);
    }
    return new PositConnectCloudClient(account.token);
  }
  return new PositConnectCloudClient(account.token, storedToken);
}
function findStoredToken(account) {
  const currentEnv = getEnvironment();
  return readStoredTokens().find(
    (t5) => t5.accountName === account.name && t5.environment === currentEnv
  );
}

// publish/provider.ts
init_log();
function accountTokenText(token) {
  return token.name + (token.server ? ` (${token.server})` : "");
}
var kPublishProviders = [
  quartoPubProvider,
  ghpagesProvider,
  rsconnectProvider,
  netlifyProvider,
  positConnectCloudProvider,
  confluenceProvider,
  huggingfaceProvider
];
function publishProviders() {
  return kPublishProviders.slice();
}
function findProvider(name2) {
  if (name2 === "posit-cloud") {
    warn(
      `The Posit Cloud publishing destination is no longer supported. Consider publishing to Posit Connect Cloud instead using \`quarto publish posit-connect-cloud\`. See https://docs.posit.co/cloud/whats_new/#october-2024 for details.`
    );
  }
  return kPublishProviders.find((provider) => provider.name === name2);
}

// command/publish/cmd.ts
await init_project_context();
await init_project_shared();

// command/publish/deployment.ts
init_log();

// publish/config.ts
init_log();
init_yaml();
init_path();
init_yaml();
init_file();
function readPublishDeployments(source2) {
  const [deployDir, deploySource] = resolveDeploymentSource(source2);
  const deplomentsFile = publishDeploymentsFile(deployDir);
  if (deplomentsFile) {
    const deployments = readYaml(deplomentsFile);
    if (deployments) {
      if (isDeploymentsArray(deployments)) {
        const sourceDeployments = deployments.find(
          (deployment) => deployment.source === basename4(deploySource)
        );
        if (sourceDeployments) {
          delete sourceDeployments.source;
          Object.values(sourceDeployments).forEach((deployment) => {
            if (Array.isArray(deployment)) {
              deployment = deployment.map((d4) => {
                d4.code = !!d4.code;
                return d4;
              });
            }
          });
          return {
            dir: deployDir,
            source: deploySource,
            records: sourceDeployments
          };
        }
      } else {
        warn(
          "Unexpcted format for _publish.yml file (not reading publish history)"
        );
      }
    }
  }
  return {
    dir: deployDir,
    source: deploySource,
    records: {}
  };
}
function writePublishDeployment(source2, provider, account, publish9) {
  publish9 = {
    ...publish9
  };
  if (publish9.code === false) {
    delete publish9.code;
  }
  let indent = 2;
  const [deployDir, deploySource] = resolveDeploymentSource(source2);
  const deploymentsFile = publishDeploymentsFile(deployDir);
  if (deploymentsFile) {
    const deploymentsFileYaml = Deno.readTextFileSync(deploymentsFile);
    indent = detectIndentLevel(deploymentsFileYaml);
    const deployments = readYamlFromString(deploymentsFileYaml);
    if (isDeploymentsArray(deployments)) {
      const docDeploymentsIdx = deployments.findIndex(
        (deployment) => deployment.source === basename4(deploySource)
      );
      if (docDeploymentsIdx !== -1) {
        const docDeployments = deployments[docDeploymentsIdx];
        if (docDeployments[provider]) {
          const deploymentIdx = docDeployments[provider].findIndex(
            (published) => published.id === publish9.id
          );
          if (deploymentIdx !== -1) {
            docDeployments[provider][deploymentIdx] = publish9;
          } else {
            docDeployments[provider].push(publish9);
          }
        } else {
          docDeployments[provider] = [publish9];
        }
      } else {
        const deployment = {
          source: deploySource,
          [provider]: [publish9]
        };
        deployments.push(deployment);
      }
      Deno.writeTextFileSync(
        deploymentsFile,
        stringifyPublishConfig(deployments, indent)
      );
    } else {
      warn(
        "Unexpcted format for _publish.yml file (not writing to publish history)"
      );
    }
  } else {
    Deno.writeTextFileSync(
      join4(deployDir, kDefaultPublishDeploymentsFile),
      stringifyPublishConfig([{
        source: deploySource,
        [provider]: [publish9]
      }], indent)
    );
  }
  writePublishRecord(source2, provider, account, publish9);
}
function resolveDeploymentSource(source2) {
  const deployDir = Deno.statSync(source2).isDirectory ? source2 : dirname4(source2);
  const deploySource = Deno.statSync(source2).isDirectory ? "project" : basename4(source2);
  return [deployDir, deploySource];
}
function readProjectPublishDeployments(project) {
  return readPublishDeployments(project.dir);
}
function writeProjectPublishDeployment(project, provider, account, publish9) {
  writePublishDeployment(project.dir, provider, account, publish9);
}
function isDeploymentsArray(obj) {
  return Array.isArray(obj) && typeof obj[0].source === "string";
}
function stringifyPublishConfig(config2, indent) {
  return stringify(
    config2,
    {
      indent,
      lineWidth: -1,
      sortKeys: false,
      skipInvalid: true
    }
  );
}
function detectIndentLevel(yaml) {
  const spaceMatch = yaml.match(/\n(\s+)/);
  return spaceMatch ? spaceMatch[1].length : 2;
}
var kDefaultPublishDeploymentsFile = "_publish.yml";
function publishDeploymentsFile(dir) {
  return [kDefaultPublishDeploymentsFile, "_publish.yaml"].map((file) => join4(dir, file)).find(existsSync1);
}

// command/publish/deployment.ts
async function resolveDeployment(options, providerFilter) {
  const deployments = await publishDeployments(
    options,
    providerFilter
  );
  if (deployments && deployments.length > 0) {
    const siteId = options.id;
    if (siteId) {
      const deployment = deployments.find((deployment2) => {
        return deployment2.target.id === siteId;
      });
      if (deployment) {
        if (options.prompt) {
          const confirmed = await Confirm.prompt({
            indent: "",
            message: `Update site at ${deployment.target.url}?`,
            default: true
          });
          if (!confirmed) {
            throw new Error();
          }
        }
        return deployment;
      } else {
        throw new Error(
          `No previous publish with site-id ${siteId} was found`
        );
      }
    } else if (options.prompt) {
      const confirmPrompt = async (hint) => {
        return await Confirm.prompt({
          indent: "",
          message: `Update site at ${deployments[0].target.url}?`,
          default: true,
          hint
        });
      };
      if (deployments.length === 1 && deployments[0].provider.publishRecord && providerFilter === deployments[0].provider.name) {
        const confirmed = await confirmPrompt();
        if (confirmed) {
          return deployments[0];
        } else {
          throw new Error();
        }
      } else {
        return await chooseDeployment(deployments);
      }
    } else if (deployments.length === 1) {
      return deployments[0];
    } else {
      throw new Error(
        `Multiple previous publishes exist (specify one with --id when using --no-prompt)`
      );
    }
  } else if (!options.prompt) {
    if (providerFilter === kGhpages) {
      throw new Error(
        `Unable to publish to GitHub Pages (the remote origin does not have a branch named "gh-pages". Use first \`quarto publish gh-pages\` locally to initialize the remote repository for publishing.)`
      );
    } else {
      throw new Error(
        `No _publish.yml file available (_publish.yml specifying a destination required for non-interactive publish)`
      );
    }
  }
}
async function publishDeployments(options, providerFilter) {
  const deployments = [];
  for (const provider of publishProviders()) {
    if ((!providerFilter || providerFilter === provider.name) && provider.publishRecord) {
      const record = await provider.publishRecord(options.input);
      if (record) {
        deployments.push({
          provider,
          target: record
        });
      }
    }
  }
  const config2 = typeof options.input === "string" ? readPublishDeployments(options.input) : readProjectPublishDeployments(options.input);
  for (const providerName of Object.keys(config2.records)) {
    if (providerFilter && providerName !== providerFilter) {
      continue;
    }
    const provider = findProvider(providerName);
    if (provider) {
      for (const record of config2.records[providerName]) {
        let account;
        const publishedToAccounts = await readAccountsPublishedTo(
          options.input,
          provider,
          record
        );
        if (publishedToAccounts.length === 1) {
          account = publishedToAccounts[0];
        }
        if (account) {
          const target = await resolveDeploymentTarget(
            provider,
            account,
            record
          );
          if (target) {
            deployments.push({
              provider,
              target,
              account
            });
          }
        } else {
          deployments.push({ provider, target: record });
        }
      }
    } else {
      warn(`Unkonwn provider ${providerName}`);
    }
  }
  return deployments;
}
async function chooseDeployment(depoyments) {
  depoyments = depoyments.filter((deployment) => !!deployment.target.url);
  const originCounts = depoyments.reduce((origins, deployment) => {
    try {
      const originUrl = new URL(deployment.target.url).origin;
      const count = origins.get(originUrl) || 0;
      origins.set(originUrl, count + 1);
    } catch {
    }
    return origins;
  }, /* @__PURE__ */ new Map());
  const kOther = "other";
  const options = depoyments.map((deployment) => {
    let url = deployment.target.url;
    try {
      const targetOrigin = new URL(deployment.target.url).origin;
      if (originCounts.get(targetOrigin) === 1 && (deployment.provider?.listOriginOnly ?? false)) {
        url = targetOrigin;
      }
    } catch {
    }
    return {
      name: `${url} (${deployment.provider.description}${deployment.account ? " - " + deployment.account.name : ""})`,
      value: publishRecordIdentifier(deployment.target, deployment.account)
    };
  });
  options.push({
    name: "Add a new destination...",
    value: kOther
  });
  const confirm = await prompt([{
    name: "destination",
    indent: "",
    message: "Publish update to:",
    options,
    type: Select
  }]);
  if (confirm.destination !== kOther) {
    return depoyments.find(
      (deployment) => publishRecordIdentifier(deployment.target, deployment.account) === confirm.destination
    );
  } else {
    return void 0;
  }
}
async function resolveDeploymentTarget(provider, account, record) {
  try {
    return await provider.resolveTarget(account, record);
  } catch (err2) {
    if (!(err2 instanceof Error)) {
      throw err2;
    }
    if (provider.isNotFound(err2)) {
      warn(
        `${record.url} not found (you may need to remove it from the publish configuration)`
      );
      return void 0;
    } else if (!provider.isUnauthorized(err2)) {
      throw err2;
    }
  }
  return record;
}

// command/publish/account.ts
init_log();
async function resolveAccount(provider, prompt2, options, hintAccount, target) {
  if (options.token) {
    if (provider.requiresServer && !options.server) {
      throw new Error(
        `You must provide the --server argument along with --token for ${provider.description}`
      );
    }
    return {
      type: 1 /* Authorized */,
      name: provider.name,
      server: options.server ? options.server : null,
      token: options.token
    };
  }
  let token;
  let accounts = (await provider.accountTokens()).filter((account) => {
    if (account.server && target?.url) {
      return target.url.startsWith(account.server);
    } else {
      return true;
    }
  });
  if (prompt2 === "never") {
    return accounts.length === 1 ? accounts[0] : void 0;
  } else if (prompt2 === "multiple" && accounts.length === 1) {
    return accounts[0];
  } else if (accounts.length === 1 && accounts[0].type === 2 /* Anonymous */) {
    return accounts[0];
  } else {
    if (accounts.length > 0) {
      if (hintAccount) {
        const hintIdx = accounts.findIndex(
          (account) => account.token === hintAccount.token
        );
        if (hintIdx !== -1) {
          const newAccounts = [accounts[hintIdx]];
          if (hintIdx > 0) {
            newAccounts.push(...accounts.slice(0, hintIdx));
          }
          if (hintIdx < accounts.length - 1) {
            newAccounts.push(...accounts.slice(hintIdx + 1));
          }
          accounts = newAccounts;
        }
      }
      token = await accountPrompt(provider, accounts);
    }
    if (!token) {
      token = await provider.authorizeToken(options, target);
    }
    return token;
  }
}
async function accountPrompt(_provider, accounts) {
  const options = accounts.filter((account) => account.type !== 2 /* Anonymous */).map((account) => ({
    name: accountTokenText(account),
    value: account.token
  }));
  const kAuthorize = "authorize";
  const accountDescriptor = _provider.accountDescriptor || "account";
  options.push({
    name: `Use another ${accountDescriptor}...`,
    value: kAuthorize
  });
  const result2 = await prompt([{
    indent: "",
    name: "token",
    message: `Publish with ${accountDescriptor}:`,
    options,
    type: Select
  }]);
  if (result2.token !== kAuthorize) {
    return accounts.find((account) => account.token === result2.token);
  }
}
async function manageAccounts() {
  const accounts = [];
  for (const provider of publishProviders()) {
    for (const account of await provider.accountTokens()) {
      if (account.type === 1 /* Authorized */) {
        accounts.push({ provider: provider.name, ...account });
      }
    }
  }
  if (accounts.length === 0) {
    info("No publishing accounts currently authorized.");
    throw new Error();
  }
  const keepAccounts = await prompt([{
    name: "accounts",
    message: "Manage Publishing Accounts",
    type: Checkbox,
    indent: "",
    options: accounts.map((account) => ({
      name: `${findProvider(account.provider)?.description}: ${account.name}${account.server ? " (" + account.server + ")" : ""}`,
      value: JSON.stringify(account),
      checked: true
    })),
    hint: `Use the arrow keys and spacebar to specify accounts you would like to remove.
   Press Enter to confirm the list of accounts you wish to remain available.`
  }]);
  const removeAccounts = [];
  for (const account of accounts) {
    if (!keepAccounts.accounts?.find((keepAccountJson) => {
      const keepAccount = JSON.parse(
        keepAccountJson
      );
      return account.provider == keepAccount.provider && account.name == keepAccount.name && account.server == keepAccount.server;
    })) {
      info(
        `Removing ${findProvider(account.provider)?.description} account ${account.name}`
      );
      removeAccounts.push(account);
    }
  }
  for (const account of removeAccounts) {
    const provider = findProvider(account.provider);
    provider?.removeToken(account);
  }
}

// publish/publish.ts
init_lodash();
init_fs();
init_path();
await init_render_services();
await init_project_shared();
init_constants6();
init_render();
init_pandoc_id();
init_mime();
init_path2();
var kSiteContent = "site";
var kDocumentContent = "document";
async function publishSite(project, provider, account, options, target) {
  const renderForPublish2 = async (flags) => {
    let metadataByInput = {};
    if (options.render) {
      renderProgress("Rendering for publish:\n");
      const services = renderServices(notebookContext());
      try {
        const result2 = await render(project.dir, {
          services,
          flags,
          setProjectDir: true
        });
        metadataByInput = result2.files.reduce(
          // deno-lint-ignore no-explicit-any
          (accumulatedResult, currentInput) => {
            const key = currentInput.input;
            accumulatedResult[key] = {
              title: currentInput.format.metadata.title,
              author: currentInput.format.metadata.author,
              date: currentInput.format.metadata.date
            };
            return accumulatedResult;
          },
          {}
        );
        result2.context.cleanup();
        if (result2.error) {
          throw result2.error;
        }
      } finally {
        services.cleanup();
      }
    }
    const outputDir = projectOutputDir(project);
    const files = [];
    for (const walk5 of walkSync(outputDir)) {
      if (walk5.isFile) {
        files.push(relative4(outputDir, walk5.path));
      }
    }
    return normalizePublishFiles({
      baseDir: outputDir,
      rootFile: "index.html",
      files,
      metadataByInput
    });
  };
  const siteTitle = websiteTitle(project.config) || basename4(project.dir);
  const siteSlug = gfmAutoIdentifier(siteTitle, false);
  const [publishRecord3, siteUrl2] = await provider.publish(
    account,
    kSiteContent,
    project.dir,
    siteTitle,
    siteSlug,
    renderForPublish2,
    options,
    target
  );
  if (publishRecord3) {
    if (options.id === void 0) {
      writeProjectPublishDeployment(
        project,
        provider.name,
        account,
        publishRecord3
      );
    }
  }
  return siteUrl2;
}
async function publishDocument(document2, provider, account, options, target) {
  let title3 = basename4(document2, extname4(document2));
  const fileConfig = await inspectConfig(document2);
  if (isDocumentConfig(fileConfig)) {
    title3 = Object.values(fileConfig.formats)[0].metadata[kTitle] || title3;
  }
  const renderForPublish2 = async (flags) => {
    const files = [];
    if (options.render) {
      renderProgress("Rendering for publish:\n");
      const services = renderServices(notebookContext());
      try {
        const result2 = await render(document2, {
          services,
          flags
        });
        if (result2.error) {
          result2.context.cleanup();
          throw result2.error;
        }
        if (result2.baseDir) {
          result2.baseDir = normalizePath(result2.baseDir);
          const docDir = normalizePath(dirname4(document2));
          if (result2.baseDir !== docDir) {
            const docRelative = (file) => {
              if (!isAbsolute4(file)) {
                file = join4(result2.baseDir, file);
              }
              return relative4(docDir, file);
            };
            result2.files = result2.files.map((resultFile) => {
              return {
                ...resultFile,
                file: docRelative(resultFile.file),
                supporting: resultFile.supporting ? resultFile.supporting.map(docRelative) : void 0,
                resourceFiles: resultFile.resourceFiles.map(docRelative)
              };
            });
            result2.baseDir = docDir;
          }
        }
        const baseDir = result2.baseDir || dirname4(document2);
        const asRelative = (file) => {
          if (isAbsolute4(file)) {
            return relative4(baseDir, file);
          } else {
            return file;
          }
        };
        const findRootFile = (files2) => {
          const rootFile2 = files2.find((renderResult) => {
            return isHtmlContent(renderResult.file);
          }) || files2.find((renderResult) => {
            return isPdfContent(renderResult.file);
          }) || files2[0];
          if (rootFile2) {
            return asRelative(rootFile2.file);
          } else {
            return void 0;
          }
        };
        const rootFile = findRootFile(result2.files);
        for (const resultFile of result2.files) {
          const file = asRelative(resultFile.file);
          files.push(file);
          if (resultFile.supporting) {
            files.push(
              ...resultFile.supporting.map((sf) => {
                if (isAbsolute4(sf)) {
                  return relative4(baseDir, sf);
                } else {
                  return sf;
                }
              }).map(asRelative)
            );
          }
          files.push(...resultFile.resourceFiles.map(asRelative));
        }
        let finalBaseDir = baseDir;
        if (result2.outputDir && result2.context) {
          const relBasePath = relative4(result2.context.dir, baseDir);
          finalBaseDir = join4(
            result2.context.dir,
            result2.outputDir,
            relBasePath
          );
        }
        result2.context.cleanup();
        return normalizePublishFiles({
          baseDir: finalBaseDir,
          rootFile,
          files
        });
      } finally {
        services.cleanup();
      }
    } else {
      const baseDir = dirname4(document2);
      if (isDocumentConfig(fileConfig)) {
        let rootFile;
        for (const format14 of Object.values(fileConfig.formats)) {
          title3 = format14.metadata[kTitle] || title3;
          const outputFile5 = format14.pandoc[kOutputFile];
          if (outputFile5 && existsSync2(join4(baseDir, outputFile5))) {
            files.push(outputFile5);
            if (!rootFile) {
              rootFile = outputFile5;
            }
          } else {
            throw new Error(`Output file ${outputFile5} does not exist.`);
          }
        }
        const filesDir = inputFilesDir(document2);
        if (existsSync2(filesDir)) {
          files.push(filesDir);
        }
        files.push(...fileConfig.resources);
        return normalizePublishFiles({
          baseDir,
          rootFile,
          files
        });
      } else {
        throw new Error(
          `The specifed document (${document2}) is not a valid quarto input file`
        );
      }
    }
  };
  const [publishRecord3, siteUrl2] = await provider.publish(
    account,
    kDocumentContent,
    document2,
    title3,
    gfmAutoIdentifier(title3, false),
    renderForPublish2,
    options,
    target
  );
  if (publishRecord3) {
    if (options.id === void 0) {
      writePublishDeployment(document2, provider.name, account, publishRecord3);
    }
  }
  return siteUrl2;
}
function normalizePublishFiles(publishFiles) {
  publishFiles.files = publishFiles.files.reduce((files, file) => {
    const filePath = join4(publishFiles.baseDir, file);
    if (Deno.statSync(filePath).isDirectory) {
      for (const walk5 of walkSync(filePath)) {
        if (walk5.isFile) {
          files.push(relative4(publishFiles.baseDir, walk5.path));
        }
      }
    } else {
      files.push(file);
    }
    return files;
  }, new Array());
  publishFiles.files = uniq(publishFiles.files);
  return publishFiles;
}

// command/publish/cmd.ts
var publishCommand = (
  // deno-lint-ignore no-explicit-any
  new Command().name("publish").description(
    "Publish a document or project to a provider.\n\nAvailable providers include:\n\n - Quarto Pub (quarto-pub)\n - GitHub Pages (gh-pages)\n - Posit Connect (connect)\n - Posit Connect Cloud (posit-connect-cloud)\n - Netlify (netlify)\n - Confluence (confluence)\n - Hugging Face Spaces (huggingface)\n\nAccounts are configured interactively during publishing.\nManage/remove accounts with: quarto publish accounts"
  ).arguments("[provider] [path]").option(
    "--id <id:string>",
    "Identifier of content to publish"
  ).option(
    "--server <server:string>",
    "Server to publish to"
  ).option(
    "--token <token:string>",
    "Access token for publising provider"
  ).option(
    "--no-render",
    "Do not render before publishing."
  ).option(
    "--no-prompt",
    "Do not prompt to confirm publishing destination"
  ).option(
    "--no-browser",
    "Do not open a browser to the site after publishing"
  ).example(
    "Publish project (prompt for provider)",
    "quarto publish"
  ).example(
    "Publish document (prompt for provider)",
    "quarto publish document.qmd"
  ).example(
    "Publish project to Hugging Face Spaces",
    "quarto publish huggingface"
  ).example(
    "Publish project to Netlify",
    "quarto publish netlify"
  ).example(
    "Publish with explicit target",
    "quarto publish netlify --id DA36416-F950-4647-815C-01A24233E294"
  ).example(
    "Publish project to GitHub Pages",
    "quarto publish gh-pages"
  ).example(
    "Publish project to Posit Connect",
    "quarto publish connect"
  ).example(
    "Publish with explicit credentials",
    "quarto publish connect --server example.com --token 01A24233E294"
  ).example(
    "Publish project to Posit Connect Cloud",
    "quarto publish posit-connect-cloud"
  ).example(
    "Publish without confirmation prompt",
    "quarto publish --no-prompt"
  ).example(
    "Publish without rendering",
    "quarto publish --no-render"
  ).example(
    "Publish without opening browser",
    "quarto publish --no-browser"
  ).example(
    "Manage/remove publishing accounts",
    "quarto publish accounts"
  ).action(
    async (options, provider, path3) => {
      if (provider && !path3 && existsSync2(provider)) {
        path3 = provider;
        provider = void 0;
      }
      if (provider === "accounts") {
        await manageAccounts();
      } else {
        let providerInterface;
        if (provider) {
          providerInterface = findProvider(provider);
          if (!providerInterface) {
            throw new Error(`Publishing source '${provider}' not found`);
          }
        }
        await publishAction(options, providerInterface, path3);
      }
    }
  )
);
async function publishAction(options, provider, path3) {
  await initYamlIntelligence2();
  const publishOptions = await createPublishOptions(options, provider, path3);
  const doPublish = async (publishProvider, accountPrompt2, publishTarget, account) => {
    if (publishProvider.requiresRender && publishOptions.render === false) {
      throw new Error(
        `${publishProvider.description} requires rendering before publish.`
      );
    }
    account = account && !publishOptions.prompt ? account : await resolveAccount(
      publishProvider,
      publishOptions.prompt ? accountPrompt2 : "never",
      publishOptions,
      account,
      publishTarget
    );
    if (account) {
      await publish8(
        publishProvider,
        account,
        publishOptions,
        publishTarget
      );
    }
  };
  const deployment = provider && publishOptions.id ? {
    provider,
    target: {
      id: publishOptions.id
    }
  } : await resolveDeployment(
    publishOptions,
    provider?.name
  );
  provider = deployment?.provider || provider;
  if (deployment) {
    await doPublish(
      deployment.provider,
      deployment.account ? "multiple" : "always",
      deployment.target,
      deployment.account
    );
  } else if (publishOptions.prompt) {
    const providers = publishProviders();
    if (!provider) {
      const result2 = await prompt([{
        indent: "",
        name: "provider",
        message: "Provider:",
        options: providers.filter((provider2) => !provider2.hidden).map((provider2) => ({
          name: provider2.description,
          value: provider2.name
        })),
        type: Select
      }]);
      if (result2.provider) {
        provider = findProvider(result2.provider);
      }
    }
    if (provider) {
      await doPublish(provider, "always");
    }
  } else {
    throw new Error(
      "No re-publishing target found (--no-prompt requires an existing 'publish' config to update)"
    );
  }
}
async function publish8(provider, account, options, target) {
  try {
    const siteUrl2 = typeof options.input !== "string" ? await publishSite(
      options.input,
      provider,
      account,
      options,
      target
    ) : await publishDocument(
      options.input,
      provider,
      account,
      options,
      target
    );
    if (siteUrl2 && options.browser) {
      await openUrl(siteUrl2.toString());
    }
  } catch (err2) {
    if (!(err2 instanceof Error)) {
      throw err2;
    }
    if (!(provider.isUnauthorized(err2) && options.prompt)) {
      throw err2;
    }
    if (await handleUnauthorized(provider, account)) {
      const authorizedAccount = await provider.authorizeToken(
        options,
        target
      );
      if (authorizedAccount) {
        return await publish8(provider, authorizedAccount, options, target);
      }
    }
  }
}
async function createPublishOptions(options, provider, path3) {
  const nbContext = notebookContext();
  path3 = path3 || Deno.cwd();
  if (!existsSync2(path3)) {
    throw new Error(
      `The specified path (${path3}) does not exist so cannot be published.`
    );
  }
  let input;
  if (provider && provider.resolveProjectPath) {
    const resolvedPath = provider.resolveProjectPath(path3);
    try {
      if (Deno.statSync(resolvedPath).isDirectory) {
        path3 = resolvedPath;
      }
    } catch (_e) {
    }
  }
  const project = await projectContext(path3, nbContext) || await singleFileProjectContext(path3, nbContext);
  if (Deno.statSync(path3).isDirectory) {
    if (projectIsWebsite(project)) {
      input = project;
    } else if (projectIsManuscript(project) && project.files.input.length > 0) {
      input = project;
    } else if (project.files.input.length === 1) {
      input = project.files.input[0];
    } else {
      throw new Error(
        `The specified path (${path3}) is not a website, manuscript or book project so cannot be published.`
      );
    }
  } else {
    if (project && projectIsWebsite(project)) {
      throw new Error(
        `The specified path (${path3}) is within a website or book project so cannot be published individually`
      );
    }
    input = path3;
  }
  const interactive = isInteractiveTerminal() && !runningInCI() && !options.id;
  return {
    input,
    server: options.server || null,
    token: options.token,
    id: options.id,
    render: !!options.render,
    prompt: !!options.prompt && interactive,
    browser: !!options.browser && interactive && !isServerSession()
  };
}
async function initYamlIntelligence2() {
  setInitializer(initYamlIntelligenceResourcesFromFilesystem);
  await initState();
}

// command/list/cmd.ts
init_temp();
init_log();
await init_extension();
init_extension_shared();
await init_project_context();
var listCommand = new Command().name("list").arguments("<type:string>").description(
  "Lists an extension or global dependency."
).example(
  "List installed extensions",
  "quarto list extensions"
).example(
  "List global tools",
  "quarto list tools"
).action(
  async (_options, type4) => {
    await initYamlIntelligenceResourcesFromFilesystem();
    const temp = createTempContext();
    const extensionContext = createExtensionContext();
    try {
      if (type4.toLowerCase() === "extensions") {
        await outputExtensions(Deno.cwd(), extensionContext);
      } else if (type4.toLowerCase() === "tools") {
        await outputTools();
      } else {
        info(
          `Unrecognized option '${type4}' - please choose 'tools' or 'extensions'.`
        );
      }
    } finally {
      temp.cleanup();
    }
  }
);
async function outputExtensions(path3, extensionContext) {
  const nbContext = notebookContext();
  const project = await projectContext(path3, nbContext);
  const extensions2 = await extensionContext.extensions(
    path3,
    project?.config,
    project?.dir,
    { builtIn: false }
  );
  if (extensions2.length === 0) {
    info(
      `No extensions are installed in this ${project ? "project" : "directory"}.`
    );
  } else {
    const extensionEntries = [];
    const provides = (extension) => {
      const contribs = [];
      if (extension.contributes.filters && extension.contributes.filters?.length > 0) {
        contribs.push("filters");
      }
      if (extension.contributes.shortcodes && extension.contributes.shortcodes?.length > 0) {
        contribs.push("shortcodes");
      }
      if (extension.contributes.formats && Object.keys(extension.contributes.formats).length > 0) {
        contribs.push("formats");
      }
      return contribs.join(", ");
    };
    extensions2.forEach((ext) => {
      const row = [
        extensionIdString(ext.id),
        ext.version?.toString() || "(none)",
        `${provides(ext)}`
      ];
      extensionEntries.push(row);
    });
    const table = new Table().header(["Id", "Version", "Contributes"]).body(
      extensionEntries
    ).padding(4);
    info(table.toString());
  }
}

// command/use/commands/template.ts
init_log();
init_path();
init_fs();
init_zip();

// extension/template.ts
init_path();
init_fs();
init_path2();
init_text2();
init_log();
var kQuartoIgnore2 = ".quartoignore";
function templateFiles(dir) {
  const excludes = [];
  const includes = [];
  const ignoreFile = join4(dir, kQuartoIgnore2);
  if (existsSync2(ignoreFile)) {
    const ignoreFileContents = Deno.readTextFileSync(ignoreFile);
    const ignoreLines = lines(ignoreFileContents.trim());
    ignoreLines.forEach((line) => {
      const splitOnComment = line.split("#");
      const exclude = splitOnComment[0];
      if (exclude && exclude.startsWith("!")) {
        if (exclude.length > 1) {
          includes.push(exclude.substring(1));
        } else {
          warn(`Unknown ignore pattern '${exclude}'`);
        }
      } else if (exclude) {
        excludes.push(exclude);
      }
    });
  }
  excludes.push(...kBuiltInExcludes);
  const filtered = excludes.filter((ex) => {
    return !includes.includes(ex);
  });
  const resolved = resolvePathGlobs(
    dir,
    ["**/*"],
    filtered
  );
  return resolved.include;
}
var kBuiltInExcludes = [
  ".*",
  "COPYING.md",
  "COPYRIGHT",
  "README.md",
  "CHANGELOG.md",
  "COPYRIGHT",
  "LICENSE",
  "_extensions",
  "CLAUDE.md",
  "CLAUDE.local.md",
  "AGENTS.md",
  "AGENTS.local.md"
];

// command/use/commands/template.ts
init_temp();
init_constants12();
init_error2();
await init_extension();
var kRootTemplateName = "template.qmd";
var useTemplateCommand = new Command().name("template").arguments("<target:string>").description(
  "Use a Quarto template for this directory or project."
).option(
  "--no-prompt",
  "Do not prompt to confirm actions"
).example(
  "Use a template from Github",
  "quarto use template <gh-org>/<gh-repo>"
).action(async (options, target) => {
  await initYamlIntelligenceResourcesFromFilesystem();
  const temp = createTempContext();
  try {
    await useTemplate(options, target, temp);
  } finally {
    temp.cleanup();
  }
});
async function useTemplate(options, target, tempContext2) {
  const source2 = await extensionSource(target);
  if (!source2) {
    info(
      `Extension not found in local or remote sources`
    );
    return;
  }
  const trusted = await isTrusted2(source2, options.prompt !== false);
  if (trusted) {
    const outputDirectory = await determineDirectory(options.prompt !== false);
    const stagedDir = await stageTemplate2(source2, tempContext2);
    const filesToCopy = templateFiles(stagedDir);
    const extDir = join4(stagedDir, kExtensionDir);
    const templateExtensions = await readExtensions(extDir);
    const installedExtensions = [];
    let installExtensions = false;
    if (templateExtensions.length > 0) {
      installExtensions = await confirmInstallation(
        templateExtensions,
        outputDirectory,
        {
          allowPrompt: options.prompt !== false,
          throw: true,
          message: "The template requires the following changes to extensions:"
        }
      );
      if (!installExtensions) {
        return;
      }
    }
    info(
      `
Preparing template files...`
    );
    const copyActions = [];
    for (const fileToCopy of filesToCopy) {
      const isDir = Deno.statSync(fileToCopy).isDirectory;
      const rel = relative4(stagedDir, fileToCopy);
      if (!isDir) {
        let target2 = join4(outputDirectory, rel);
        let displayName = rel;
        const targetDir = dirname4(target2);
        if (rel === kRootTemplateName) {
          displayName = `${basename4(targetDir)}.qmd`;
          target2 = join4(targetDir, displayName);
        }
        const copyAction = {
          file: displayName,
          copy: async () => {
            await ensureDir(targetDir);
            await Deno.copyFile(fileToCopy, target2);
          }
        };
        if (existsSync2(target2)) {
          if (options.prompt) {
            const proceed = await Confirm.prompt({
              message: `Overwrite file ${displayName}?`
            });
            if (proceed) {
              copyActions.push(copyAction);
            }
          } else {
            throw new Error(
              `The file ${displayName} already exists and would be overwritten by this action.`
            );
          }
        } else {
          copyActions.push(copyAction);
        }
      }
    }
    if (installExtensions) {
      installedExtensions.push(...templateExtensions);
      await withSpinner({ message: "Installing extensions..." }, async () => {
        const subStagedDir = tempContext2.createDir();
        await copyExtensions(source2, stagedDir, subStagedDir);
        await completeInstallation(subStagedDir, outputDirectory);
      });
    }
    if (copyActions.length > 0) {
      await withSpinner({ message: "Copying files..." }, async () => {
        for (const copyAction of copyActions) {
          await copyAction.copy();
        }
      });
    }
    if (installedExtensions.length > 0) {
      info(
        `
Extensions installed:`
      );
      for (const extension of installedExtensions) {
        info(` - ${extension.title}`);
      }
    }
    if (copyActions.length > 0) {
      info(
        `
Files created:`
      );
      for (const copyAction of copyActions) {
        info(` - ${copyAction.file}`);
      }
    }
  } else {
    return Promise.resolve();
  }
}
async function stageTemplate2(source2, tempContext2) {
  if (source2.type === "remote") {
    const workingDir = tempContext2.createDir();
    const archiveDir = join4(workingDir, "archive");
    ensureDirSync(archiveDir);
    const filename = (typeof source2.resolvedTarget === "string" ? source2.resolvedTarget : source2.resolvedFile) || "extension.zip";
    const toFile = join4(archiveDir, filename);
    await downloadWithProgress(source2.resolvedTarget, `Downloading`, toFile);
    await unzipInPlace(toFile);
    if (source2.targetSubdir) {
      const sourceSubDir = join4(archiveDir, source2.targetSubdir);
      if (existsSync2(sourceSubDir)) {
        return sourceSubDir;
      }
    }
    const dirEntries = Deno.readDirSync(archiveDir);
    let count = 0;
    let name2;
    let hasFiles = false;
    for (const dirEntry of dirEntries) {
      if (dirEntry.isDirectory) {
        name2 = dirEntry.name;
        count++;
      } else {
        hasFiles = true;
      }
    }
    if (!hasFiles && count === 1 && name2) {
      return join4(archiveDir, name2);
    }
    return archiveDir;
  } else {
    if (typeof source2.resolvedTarget !== "string") {
      throw new InternalError(
        "Local resolved extension should always have a string target."
      );
    }
    if (Deno.statSync(source2.resolvedTarget).isDirectory) {
      return source2.resolvedTarget;
    } else {
      const workingDir = tempContext2.createDir();
      const targetFile = join4(workingDir, basename4(source2.resolvedTarget));
      Deno.copyFileSync(
        source2.resolvedTarget,
        targetFile
      );
      await unzipInPlace(targetFile);
      return workingDir;
    }
  }
}
async function isTrusted2(source2, allowPrompt) {
  if (allowPrompt && source2.type === "remote") {
    const preamble = `
Quarto templates may execute code when documents are rendered. If you do not 
trust the authors of the template, we recommend that you do not install or 
use the template.`;
    info(preamble);
    const question = "Do you trust the authors of this template";
    const confirmed = await Confirm.prompt({
      message: question,
      default: true
    });
    return confirmed;
  } else {
    return true;
  }
}
async function determineDirectory(allowPrompt) {
  const currentDir = Deno.cwd();
  if (!allowPrompt) {
    if (!directoryEmpty(currentDir)) {
      throw new Error(
        `Unable to install in ${currentDir} as the directory isn't empty.`
      );
    } else {
      return currentDir;
    }
  } else {
    return promptForDirectory(currentDir, directoryEmpty(currentDir));
  }
}
async function promptForDirectory(root, isEmpty) {
  const useSubDir = await Confirm.prompt({
    message: "Create a subdirectory for template?",
    default: !isEmpty,
    hint: "Use a subdirectory for the template rather than the current directory."
  });
  if (!useSubDir) {
    return root;
  }
  const dirName = await Input.prompt({
    message: "Directory name:",
    validate: (input) => {
      if (input.length === 0 || input === ".") {
        return true;
      }
      const dir = join4(root, input);
      if (!existsSync2(dir)) {
        ensureDirSync(dir);
      }
      return true;
    }
  });
  if (dirName.length === 0 || dirName === ".") {
    return root;
  } else {
    return join4(root, dirName);
  }
}
async function unzipInPlace(zipFile) {
  await withSpinner(
    { message: "Unzipping" },
    async () => {
      const result2 = await unzip(zipFile);
      if (!result2.success) {
        throw new Error("Failed to unzip template.\n" + result2.stderr);
      }
      await Deno.remove(zipFile);
      return Promise.resolve();
    }
  );
}
function directoryEmpty(path3) {
  const dirContents = Deno.readDirSync(path3);
  for (const _content of dirContents) {
    return false;
  }
  return true;
}

// command/use/commands/binder/binder.ts
init_temp();
init_resources2();
init_mod6();
init_path();
init_log();
init_fs();
init_process();

// command/use/commands/binder/binder-utils.ts
init_hash2();
init_project_scratch();
init_log();
init_fs();
init_path();
var safeFileWriter = (projectDir, prompt2 = true) => {
  const idxPath = join4(projectScratchPath(projectDir), "use", "binder.json");
  ensureDirSync(dirname4(idxPath));
  let fileIndex = {};
  if (existsSync2(idxPath)) {
    fileIndex = JSON.parse(Deno.readTextFileSync(idxPath));
  }
  return async (projRelativePath, contents) => {
    const absPath = join4(projectDir, projRelativePath);
    const write = () => {
      fileIndex[projRelativePath] = hash;
      Deno.writeTextFileSync(absPath, contents);
      Deno.writeTextFileSync(idxPath, JSON.stringify(fileIndex, null, 2));
      info(`[\u2713] ${projRelativePath}`);
    };
    const hash = await md5HashAsync(contents);
    if (existsSync2(absPath)) {
      const lastHash = fileIndex[projRelativePath];
      const currentContents = Deno.readTextFileSync(absPath);
      const currentHash = await md5HashAsync(currentContents);
      let writeFile = true;
      if (!lastHash || lastHash !== currentHash) {
        if (prompt2) {
          const question = lastHash ? `File ${projRelativePath} was modified since last generated. Overwrite?` : `File ${projRelativePath} wasn't created by the this command. Overwrite?`;
          writeFile = await Confirm.prompt({
            message: question
          });
        } else {
          writeFile = false;
          lastHash ? warn(
            `Skipped ${projRelativePath} - modified since last generated.`
          ) : warn(
            `Skipped ${projRelativePath} - wasn't created by the this command.`
          );
        }
      }
      if (writeFile) {
        write();
      }
    } else {
      write();
    }
  };
};

// command/use/commands/binder/binder.ts
await init_project_context();
init_log2();
init_types4();
init_array();
var useBinderCommand = new Command().name("binder").description(
  "Configure the current project with Binder support."
).option(
  "--no-prompt",
  "Do not prompt to confirm actions"
).example(
  "Configure project to use Binder",
  "quarto use binder"
).action(async (options) => {
  await initYamlIntelligenceResourcesFromFilesystem();
  const temp = createTempContext();
  try {
    logProgress("Determining configuration");
    const nbContext = notebookContext();
    const context = await projectContext(Deno.cwd(), nbContext);
    if (!context) {
      throw new Error(
        "You must be in a Quarto project in order to configure Binder support."
      );
    }
    const projEnv = await withSpinner(
      {
        message: "Inspecting project configuration:",
        doneMessage: "Detected Project configuration:\n"
      },
      () => {
        return context.environment();
      }
    );
    const jupyterLab4 = jupyterLabVersion(context, projEnv);
    const rConfig = {};
    if (projectHasR(context, projEnv)) {
      const result2 = await execProcess(
        {
          cmd: await rBinaryPath("R"),
          args: [
            "--version"
          ],
          stdout: "piped",
          stderr: "piped"
        }
      );
      if (result2.success) {
        const output = result2.stdout;
        const verMatch = output?.match(
          /R version (\d+\.\d+\.\d+) \((\d\d\d\d-\d\d-\d\d)\)/m
        );
        if (verMatch) {
          const version4 = verMatch[1];
          rConfig.version = new mod_default(version4);
          rConfig.date = verMatch[2];
        }
      } else {
        warn("Unable to detect R version, ommitting R configuration");
      }
    }
    const quartoVersion = typeof projEnv.quarto === "string" ? projEnv.quarto === "prerelease" ? "most recent prerelease" : "most recent release" : projEnv.quarto.toString();
    const table = new Table();
    table.push(["Quarto", quartoVersion]);
    table.push([
      "JupyterLab",
      jupyterLab4 ? "4.x" : "default"
    ]);
    if (projEnv.engines.length > 0) {
      table.push([
        projEnv.engines.length === 1 ? "Engine" : "Engines",
        projEnv.engines.join("\n")
      ]);
    }
    if (rConfig.version || rConfig.date) {
      const verStr = [];
      if (rConfig.version) {
        verStr.push(`${rConfig.version?.toString()}`);
      }
      if (rConfig.date) {
        verStr.push(`(${rConfig.date})`);
      }
      table.push([
        "R",
        verStr.join(" ")
      ]);
    }
    if (projEnv.tools.length > 0) {
      table.push(["Tools", projEnv.tools.join("\n")]);
    }
    table.push(["Editor", projEnv.codeEnvironment]);
    if (projEnv.environments.length > 0) {
      table.push(["Environments", projEnv.environments.join("\n")]);
    }
    table.indent(4).minColWidth(12).render();
    const isMarkdownEngineOnly = (engines) => {
      return engines.length === 1 && engines.includes("markdown");
    };
    if (projEnv.environments.length === 0 && !isMarkdownEngineOnly(projEnv.engines)) {
      info(
        "\nNo files which provide dependencies were discovered. If you continue, no dependencies will be restored when running this project with Binder.\n\nLearn more at:\nhttps://www.quarto.org/docs/prerelease/1.4/binder.html#dependencies\n"
      );
      const proceed = !options.prompt || await Confirm.prompt({
        message: "Do you want to continue?",
        default: true
      });
      if (!proceed) {
        return;
      }
    }
    const fileOperations = await binderFileOperations(
      projEnv,
      jupyterLab4,
      context,
      options,
      rConfig
    );
    info(
      "\nThe following files will be written:"
    );
    const changeTable = new Table();
    fileOperations.forEach((op) => {
      changeTable.push([op.file, op.desc]);
    });
    changeTable.border(true).render();
    info("");
    const writeFiles = !options.prompt || await Confirm.prompt({
      message: "Continue?",
      default: true
    });
    if (writeFiles) {
      logProgress("\nWriting configuration files");
      for (const fileOperation of fileOperations) {
        await fileOperation.performOp();
      }
    }
  } finally {
    temp.cleanup();
  }
});
var createPostBuild = (quartoConfig2, vscodeConfig, pythonConfig) => {
  const postBuildScript = [];
  postBuildScript.push("#!/usr/bin/env -S bash -v");
  postBuildScript.push("");
  postBuildScript.push(`# determine which version of Quarto to install`);
  postBuildScript.push(`QUARTO_VERSION=${quartoConfig2.version}`);
  postBuildScript.push(kLookupQuartoVersion);
  postBuildScript.push(msg4("Installing Quarto $QUARTO_VERSION"));
  postBuildScript.push(kInstallQuarto);
  postBuildScript.push(msg4("Installed Quarto"));
  if (quartoConfig2.tinytex) {
    postBuildScript.push(msg4("Installing TinyTex"));
    postBuildScript.push("# install tinytex");
    postBuildScript.push("quarto install tinytex --no-prompt");
    postBuildScript.push(msg4("Installed TinyTex"));
  }
  if (quartoConfig2.chromium) {
    postBuildScript.push(msg4("Installing Chrome Headless Shell"));
    postBuildScript.push("# install chrome-headless-shell");
    postBuildScript.push("quarto install chrome-headless-shell --no-prompt");
    postBuildScript.push(msg4("Installed Chrome Headless Shell"));
  }
  if (vscodeConfig.version) {
    const version4 = typeof vscodeConfig.version === "boolean" ? new mod_default("4.16.1") : vscodeConfig.version;
    postBuildScript.push(msg4("Configuring VSCode"));
    postBuildScript.push("# download and install VS Code server");
    postBuildScript.push(`CODE_VERSION=${version4}`);
    postBuildScript.push(kInstallVSCode);
    if (vscodeConfig.extensions) {
      postBuildScript.push("# install vscode extensions");
      for (const extension of vscodeConfig.extensions) {
        postBuildScript.push(
          `code-server --install-extension ${extension}`
        );
      }
    }
    postBuildScript.push(msg4("Configured VSCode"));
  }
  if (pythonConfig.pip) {
    postBuildScript.push("# install required python packages");
    for (const lib2 of pythonConfig.pip) {
      postBuildScript.push(`python3 -m pip install ${lib2}`);
    }
  }
  postBuildScript.push(msg4("Completed"));
  return postBuildScript.join("\n");
};
var jupyterLabVersion = (context, env2) => {
  const envs = env2.environments;
  const envMatchers = {};
  envMatchers["requirements.txt"] = /jupyterlab>*=*4.*./g;
  envMatchers["environment.yml"] = /jupyterlab *>*=*4.*./g;
  envMatchers["pipfile"] = /jupyterlab = "*>*=*4.*."/g;
  const hasJL4 = envs.some((env3) => {
    const matcher = envMatchers[env3];
    if (!matcher) {
      return false;
    }
    const contents = Deno.readTextFileSync(join4(context.dir, env3));
    return contents.match(matcher);
  });
  return hasJL4;
};
var msg4 = (text) => {
  return `
echo
echo ${text}
echo`;
};
var kInstallQuarto = `
# download and install the deb file
curl -LO https://github.com/quarto-dev/quarto-cli/releases/download/v$QUARTO_VERSION/quarto-$QUARTO_VERSION-linux-amd64.deb
dpkg -x quarto-$QUARTO_VERSION-linux-amd64.deb .quarto
rm -rf quarto-$QUARTO_VERSION-linux-amd64.deb

# get quarto in the path
mkdir -p ~/.local/bin
ln -s ~/.quarto/opt/quarto/bin/quarto ~/.local/bin/quarto

# create the proper pandoc symlink to enable visual editor in Quarto extension
ln -s ~/.quarto/opt/quarto/bin/tools/x86_64/pandoc ~/.quarto/opt/quarto/bin/tools/pandoc
`;
var kInstallVSCode = `
# download and extract
wget -q -O code-server.tar.gz https://github.com/coder/code-server/releases/download/v$CODE_VERSION/code-server-$CODE_VERSION-linux-amd64.tar.gz
tar xzf code-server.tar.gz
rm -rf code-server.tar.gz

# place in hidden folder
mv "code-server-$CODE_VERSION-linux-amd64" .code-server

# get code-server in path
mkdir -p ./.local/bin
ln -s ~/.code-server/bin/code-server ~/.local/bin/code-server
`;
var kLookupQuartoVersion = `
# See whether we need to lookup a Quarto version
if [ $QUARTO_VERSION = "prerelease" ]; then
	QUARTO_JSON="_prerelease.json"
elif [ $QUARTO_VERSION = "release" ]; then
	QUARTO_JSON="_download.json"
fi

if [ $QUARTO_JSON != "" ]; then

# create a python script and run it
PYTHON_SCRIPT=_quarto_version.py
if [ -e $PYTHON_SCRIPT ]; then
	rm -rf $PYTHON_SCRIPT
fi

cat > $PYTHON_SCRIPT <<EOF
import urllib, json

import urllib.request, json
with urllib.request.urlopen("https://quarto.org/docs/download/\${QUARTO_JSON}") as url:
	data = json.load(url)
	print(data['version'])

EOF

QUARTO_VERSION=$(python $PYTHON_SCRIPT)
rm -rf $PYTHON_SCRIPT

fi
`;
async function binderFileOperations(projEnv, jupyterLab4, context, options, rConfig) {
  const operations = [];
  const quartoConfig2 = {
    version: projEnv.quarto,
    tinytex: projEnv.tools.includes("tinytex"),
    chromium: projEnv.tools.includes("chromium")
  };
  const vsCodeConfig = {
    version: projEnv.codeEnvironment === "vscode" ? new mod_default("4.16.1") : void 0,
    extensions: [
      "ms-python.python",
      "sumneko.lua",
      "quarto.quarto"
    ]
  };
  const pythonConfig = {
    pip: []
  };
  if (jupyterLab4) {
    if (projEnv.codeEnvironment === "vscode") {
      pythonConfig.pip?.push(
        "git+https://github.com/trungleduc/jupyter-server-proxy@lab4"
      );
    }
    pythonConfig.pip?.push("jupyterlab-quarto");
  } else {
    if (projEnv.codeEnvironment === "vscode") {
      pythonConfig.pip?.push("jupyter-server-proxy");
    }
    pythonConfig.pip?.push("jupyterlab-quarto==0.1.45");
  }
  const environmentConfig = {
    apt: ["zip"]
  };
  const writeFile = safeFileWriter(context.dir, options.prompt);
  const renvPath = join4(context.dir, "renv.lock");
  if (existsSync2(renvPath)) {
    const installRText = "install.packages('renv')\nrenv::restore()";
    operations.push({
      file: "install.R",
      desc: "Activates the R environment described in renv.lock",
      performOp: async () => {
        await writeFile(
          "install.R",
          installRText
        );
      }
    });
  }
  const postBuildScriptText = createPostBuild(
    quartoConfig2,
    vsCodeConfig,
    pythonConfig
  );
  operations.push({
    file: "postBuild",
    desc: "Configures Quarto and supporting tools",
    performOp: async () => {
      await writeFile(
        "postBuild",
        postBuildScriptText
      );
    }
  });
  if (vsCodeConfig.version) {
    operations.push({
      file: ".jupyter",
      desc: "Configures JupyterLab with necessary extensions",
      performOp: async () => {
        const traitletsDir = ".jupyter";
        ensureDirSync(join4(context.dir, traitletsDir));
        const resDir = resourcePath("use/binder/");
        for (const file of ["vscode.svg", "jupyter_notebook_config.py"]) {
          const textContents = Deno.readTextFileSync(join4(resDir, file));
          await writeFile(join4(traitletsDir, file), textContents);
        }
      }
    });
  }
  if (environmentConfig.apt && environmentConfig.apt.length) {
    const aptText = environmentConfig.apt.join("\n");
    operations.push({
      file: "apt.txt",
      desc: "Installs Quarto required packages",
      performOp: async () => {
        await writeFile(
          "apt.txt",
          aptText
        );
      }
    });
  }
  if (rConfig.version || rConfig.date) {
    const runtime = ["r"];
    if (rConfig.version) {
      runtime.push(`-${rConfig.version}`);
    }
    if (rConfig.date) {
      runtime.push(`-${rConfig.date}`);
    }
    operations.push({
      file: "runtime.txt",
      desc: "Installs R and configures RStudio",
      performOp: async () => {
        await writeFile(
          "runtime.txt",
          runtime.join("")
        );
      }
    });
  }
  return operations;
}
var projectHasR = (context, projEnv) => {
  if (projEnv.engines.includes("knitr")) {
    return true;
  }
  if (existsSync2(join4(context.dir, "renv.lock"))) {
    return true;
  }
  if (existsSync2(join4(context.dir, "install.R"))) {
    return true;
  }
  if (context.config?.project?.[kProjectPreRender]) {
    if (asArray(context.config.project[kProjectPreRender]).some((file) => {
      return extname4(file).toLowerCase() === ".r";
    })) {
      return true;
    }
  }
  if (context.config?.project?.[kProjectPostRender]) {
    if (asArray(context.config.project[kProjectPostRender]).some((file) => {
      return extname4(file).toLowerCase() === ".r";
    })) {
      return true;
    }
  }
  return false;
};

// command/use/commands/brand.ts
init_log();
init_path();
init_fs();
init_zip();
init_temp();
init_error2();
await init_project_context();
init_yaml();
function checkForBrandExtension(dir) {
  const extensionFiles = ["_extension.yml", "_extension.yaml"];
  for (const file of extensionFiles) {
    const path3 = join4(dir, file);
    if (existsSync2(path3)) {
      try {
        const yaml = readYaml(path3);
        const contributes = yaml?.contributes;
        const metadata = contributes?.metadata;
        const project = metadata?.project;
        const brandFile = project?.brand;
        if (brandFile && typeof brandFile === "string") {
          return {
            isBrandExtension: true,
            extensionDir: dir,
            brandFileName: brandFile
          };
        }
      } catch {
      }
    }
  }
  return { isBrandExtension: false };
}
function findBrandExtension(stagedDir) {
  const rootCheck = checkForBrandExtension(stagedDir);
  if (rootCheck.isBrandExtension) {
    return rootCheck;
  }
  const extensionsDir = join4(stagedDir, "_extensions");
  if (!existsSync2(extensionsDir)) {
    return { isBrandExtension: false };
  }
  try {
    for (const entry of Deno.readDirSync(extensionsDir)) {
      if (!entry.isDirectory) continue;
      const extPath = join4(extensionsDir, entry.name);
      const check2 = checkForBrandExtension(extPath);
      if (check2.isBrandExtension) {
        return check2;
      }
      for (const nested of Deno.readDirSync(extPath)) {
        if (!nested.isDirectory) continue;
        const nestedPath = join4(extPath, nested.name);
        const nestedCheck = checkForBrandExtension(nestedPath);
        if (nestedCheck.isBrandExtension) {
          return nestedCheck;
        }
      }
    }
  } catch {
  }
  return { isBrandExtension: false };
}
function extractPath(value) {
  if (typeof value === "string") {
    return value;
  }
  if (value && typeof value === "object" && "path" in value) {
    const pathValue = value.path;
    if (typeof pathValue === "string") {
      return pathValue;
    }
  }
  return void 0;
}
function isLocalPath(path3) {
  return !path3.startsWith("http://") && !path3.startsWith("https://");
}
function extractBrandFilePaths(brandYamlPath) {
  const paths = [];
  try {
    const yaml = readYaml(brandYamlPath);
    if (!yaml) return paths;
    const logo = yaml.logo;
    if (logo) {
      const images = logo.images;
      if (images && typeof images === "object") {
        for (const value of Object.values(images)) {
          const path3 = extractPath(value);
          if (path3 && isLocalPath(path3)) {
            paths.push(path3);
          }
        }
      }
      for (const size of ["small", "medium", "large"]) {
        const sizeValue = logo[size];
        if (!sizeValue) continue;
        if (typeof sizeValue === "string") {
          if (isLocalPath(sizeValue)) {
            paths.push(sizeValue);
          }
        } else if (typeof sizeValue === "object") {
          const lightDark = sizeValue;
          if (typeof lightDark.light === "string" && isLocalPath(lightDark.light)) {
            paths.push(lightDark.light);
          }
          if (typeof lightDark.dark === "string" && isLocalPath(lightDark.dark)) {
            paths.push(lightDark.dark);
          }
        }
      }
    }
    const typography = yaml.typography;
    if (typography) {
      const fonts = typography.fonts;
      if (Array.isArray(fonts)) {
        for (const font of fonts) {
          if (!font || typeof font !== "object") continue;
          const fontObj = font;
          if (fontObj.source !== "file") continue;
          const files = fontObj.files;
          if (Array.isArray(files)) {
            for (const file of files) {
              const path3 = extractPath(file);
              if (path3 && isLocalPath(path3)) {
                paths.push(path3);
              }
            }
          }
        }
      }
    }
  } catch {
  }
  return paths;
}
var useBrandCommand = new Command().name("brand").arguments("<target:string>").description(
  "Use a brand for this project."
).option(
  "--force",
  "Skip all prompts and confirmations"
).option(
  "--dry-run",
  "Show what would happen without making changes"
).example(
  "Use a brand from Github",
  "quarto use brand <gh-org>/<gh-repo>"
).action(
  async (options, target) => {
    if (options.force && options.dryRun) {
      throw new Error("Cannot use --force and --dry-run together");
    }
    await initYamlIntelligenceResourcesFromFilesystem();
    const temp = createTempContext();
    try {
      await useBrand(options, target, temp);
    } finally {
      temp.cleanup();
    }
  }
);
async function useBrand(options, target, tempContext2) {
  if (options.dryRun) {
    info("\nDry run - no changes will be made.");
  }
  const source2 = await extensionSource(target);
  if (!source2) {
    info(
      `Brand not found in local or remote sources`
    );
    return;
  }
  if (!options.dryRun && !options.force) {
    const trusted = await isTrusted3(source2);
    if (!trusted) {
      return;
    }
  }
  const brandDir = await ensureBrandDirectory(
    options.force === true,
    options.dryRun === true
  );
  const stagedDir = await stageBrand(source2, tempContext2);
  const brandExtInfo = findBrandExtension(stagedDir);
  const sourceDir = brandExtInfo.isBrandExtension ? brandExtInfo.extensionDir : stagedDir;
  const brandFileName = brandExtInfo.isBrandExtension ? brandExtInfo.brandFileName : existsSync2(join4(sourceDir, "_brand.yml")) ? "_brand.yml" : existsSync2(join4(sourceDir, "_brand.yaml")) ? "_brand.yaml" : void 0;
  if (!brandFileName) {
    info("No brand file (_brand.yml or _brand.yaml) found in source");
    return;
  }
  const brandFilePath = join4(sourceDir, brandFileName);
  const brandFileDir = dirname4(brandFilePath);
  const referencedPaths = extractBrandFilePaths(brandFilePath);
  const filesToCopy = [brandFilePath];
  for (const refPath of referencedPaths) {
    const fullPath = join4(brandFileDir, refPath);
    if (existsSync2(fullPath)) {
      filesToCopy.push(fullPath);
    }
  }
  if (!options.dryRun && !options.force) {
    const filename = (typeof source2.resolvedTarget === "string" ? source2.resolvedTarget : source2.resolvedFile) || "brand.zip";
    const allowUse = await Confirm.prompt({
      message: `Proceed with using brand ${filename}?`,
      default: true
    });
    if (!allowUse) {
      return;
    }
  }
  if (!options.dryRun) {
    info(
      `
Preparing brand files...`
    );
  }
  const sourceFiles = new Set(
    filesToCopy.filter((f5) => !Deno.statSync(f5).isDirectory).map((f5) => {
      if (f5 === brandFilePath) {
        return "_brand.yml";
      }
      return relative4(brandFileDir, f5);
    })
  );
  const extraFiles = findExtraFiles(brandDir, sourceFiles);
  const wouldOverwrite = [];
  const wouldCreate = [];
  const wouldRemove = [];
  const copyActions = [];
  let removed = [];
  for (const fileToCopy of filesToCopy) {
    const isDir = Deno.statSync(fileToCopy).isDirectory;
    if (isDir) {
      continue;
    }
    let targetRel;
    if (fileToCopy === brandFilePath) {
      targetRel = "_brand.yml";
    } else {
      targetRel = relative4(brandFileDir, fileToCopy);
    }
    const targetPath = join4(brandDir, targetRel);
    const displayName = targetRel;
    const targetDir = dirname4(targetPath);
    const copyAction = {
      file: displayName,
      copy: async () => {
        await ensureDir(targetDir);
        await Deno.copyFile(fileToCopy, targetPath);
      }
    };
    if (existsSync2(targetPath)) {
      if (options.dryRun) {
        wouldOverwrite.push(displayName);
      } else if (!options.force) {
        const proceed = await Confirm.prompt({
          message: `Overwrite file ${displayName}?`,
          default: true
        });
        if (proceed) {
          copyActions.push({ ...copyAction, action: "overwrite" });
        } else {
          throw new Error(
            `The file ${displayName} already exists and would be overwritten by this action.`
          );
        }
      } else {
        copyActions.push({ ...copyAction, action: "overwrite" });
      }
    } else {
      if (options.dryRun) {
        wouldCreate.push(displayName);
      } else {
        copyActions.push({ ...copyAction, action: "create" });
      }
    }
  }
  if (options.dryRun) {
    if (wouldOverwrite.length > 0) {
      info(`
Would overwrite:`);
      for (const file of wouldOverwrite) {
        info(` - ${file}`);
      }
    }
    if (wouldCreate.length > 0) {
      info(`
Would create:`);
      for (const file of wouldCreate) {
        info(` - ${file}`);
      }
    }
    if (extraFiles.length > 0) {
      info(`
Would remove:`);
      for (const file of extraFiles) {
        info(` - ${file}`);
      }
    }
    return;
  }
  if (copyActions.length > 0) {
    await withSpinner({ message: "Copying files..." }, async () => {
      for (const copyAction of copyActions) {
        await copyAction.copy();
      }
    });
  }
  if (extraFiles.length > 0) {
    const removeExtras = async () => {
      for (const file of extraFiles) {
        await Deno.remove(join4(brandDir, file));
      }
      cleanupEmptyDirs(brandDir);
      removed = extraFiles;
    };
    if (options.force) {
      await removeExtras();
    } else {
      info(`
Extra files not in source brand:`);
      for (const file of extraFiles) {
        info(` - ${file}`);
      }
      await afterConfirm(
        `Remove these ${extraFiles.length} file(s)?`,
        removeExtras
      );
    }
  }
  const overwritten = copyActions.filter((a5) => a5.action === "overwrite");
  const created = copyActions.filter((a5) => a5.action === "create");
  if (overwritten.length > 0) {
    info(`
Overwritten:`);
    for (const a5 of overwritten) {
      info(` - ${a5.file}`);
    }
  }
  if (created.length > 0) {
    info(`
Created:`);
    for (const a5 of created) {
      info(` - ${a5.file}`);
    }
  }
  if (removed.length > 0) {
    info(`
Removed:`);
    for (const file of removed) {
      info(` - ${file}`);
    }
  }
}
async function stageBrand(source2, tempContext2) {
  if (source2.type === "remote") {
    const workingDir = tempContext2.createDir();
    const archiveDir = join4(workingDir, "archive");
    ensureDirSync(archiveDir);
    const filename = (typeof source2.resolvedTarget === "string" ? source2.resolvedTarget : source2.resolvedFile) || "brand.zip";
    const toFile = join4(archiveDir, filename);
    await downloadWithProgress(source2.resolvedTarget, `Downloading`, toFile);
    await unzipInPlace2(toFile);
    if (source2.targetSubdir) {
      const sourceSubDir = join4(archiveDir, source2.targetSubdir);
      if (existsSync2(sourceSubDir)) {
        return sourceSubDir;
      }
    }
    const dirEntries = Deno.readDirSync(archiveDir);
    let count = 0;
    let name2;
    let hasFiles = false;
    for (const dirEntry of dirEntries) {
      if (dirEntry.isDirectory) {
        name2 = dirEntry.name;
        count++;
      } else {
        hasFiles = true;
      }
    }
    if (!hasFiles && count === 1 && name2) {
      return join4(archiveDir, name2);
    }
    return archiveDir;
  } else {
    if (typeof source2.resolvedTarget !== "string") {
      throw new InternalError(
        "Local resolved extension should always have a string target."
      );
    }
    if (Deno.statSync(source2.resolvedTarget).isDirectory) {
      return source2.resolvedTarget;
    } else {
      const workingDir = tempContext2.createDir();
      const targetFile = join4(workingDir, basename4(source2.resolvedTarget));
      Deno.copyFileSync(
        source2.resolvedTarget,
        targetFile
      );
      await unzipInPlace2(targetFile);
      return workingDir;
    }
  }
}
async function isTrusted3(source2) {
  if (source2.type === "remote") {
    const preamble = `
If you do not trust the authors of the brand, we recommend that you do not install or use the brand.`;
    info(preamble);
    const question = "Do you trust the authors of this brand";
    const confirmed = await Confirm.prompt({
      message: question,
      default: true
    });
    return confirmed;
  } else {
    return true;
  }
}
async function ensureBrandDirectory(force, dryRun) {
  const currentDir = Deno.cwd();
  const nbContext = notebookContext();
  const project = await projectContext(currentDir, nbContext);
  const baseDir = project?.dir ?? currentDir;
  const brandDir = join4(baseDir, "_brand");
  if (!existsSync2(brandDir)) {
    if (dryRun) {
      info(`  Would create directory: _brand/`);
    } else if (!force) {
      if (!await Confirm.prompt({
        message: `Create brand directory ${brandDir}?`,
        default: true
      })) {
        throw new Error(`Could not create brand directory ${brandDir}`);
      }
      ensureDirSync(brandDir);
    } else {
      ensureDirSync(brandDir);
    }
  }
  return brandDir;
}
async function unzipInPlace2(zipFile) {
  await withSpinner(
    { message: "Unzipping" },
    async () => {
      const result2 = await unzip(zipFile);
      if (!result2.success) {
        throw new Error("Failed to unzip brand.\n" + result2.stderr);
      }
      await Deno.remove(zipFile);
      return Promise.resolve();
    }
  );
}
function findExtraFiles(targetDir, sourceFiles) {
  const extraFiles = [];
  function walkDir(dir, baseRel = "") {
    if (!existsSync2(dir)) return;
    for (const entry of Deno.readDirSync(dir)) {
      const rel = baseRel ? join4(baseRel, entry.name) : entry.name;
      if (entry.isDirectory) {
        walkDir(join4(dir, entry.name), rel);
      } else if (!sourceFiles.has(rel)) {
        extraFiles.push(rel);
      }
    }
  }
  walkDir(targetDir);
  return extraFiles;
}
function cleanupEmptyDirs(dir) {
  if (!existsSync2(dir)) return;
  for (const entry of Deno.readDirSync(dir)) {
    if (entry.isDirectory) {
      const subdir = join4(dir, entry.name);
      cleanupEmptyDirs(subdir);
      const contents = [...Deno.readDirSync(subdir)];
      if (contents.length === 0) {
        Deno.removeSync(subdir);
      }
    }
  }
}

// command/use/cmd.ts
var kUseCommands = [useTemplateCommand, useBinderCommand, useBrandCommand];
var makeUseCommand = () => {
  const theCommand = new Command().name("use").arguments("<type:string> [target:string]").option(
    "--no-prompt",
    "Do not prompt to confirm actions"
  ).description(
    "Automate document or project setup tasks."
  ).action((_options, type4, _target) => {
    const useCommand = kUseCommands.find((command) => {
      return command.getName() === type4;
    });
    if (!useCommand) {
      throw new ValidationError2(
        `Unknown type '${type4}'- did you mean 'template'?`
      );
    }
  });
  kUseCommands.forEach((command) => {
    theCommand.command(command.getName(), command);
  });
  return theCommand;
};

// command/add/cmd.ts
init_temp();
init_log();
var addCommand2 = new Command().name("add").arguments("<extension:string>").option(
  "--no-prompt",
  "Do not prompt to confirm actions"
).option(
  "--embed <extensionId>",
  "Embed this extension within another extension (used when authoring extensions)."
).description(
  "Add an extension to this folder or project"
).example(
  "Install extension (Github)",
  "quarto add <gh-org>/<gh-repo>"
).example(
  "Install extension (file)",
  "quarto add <path-to-zip>"
).example(
  "Install extension (url)",
  "quarto add <url>"
).action(
  async (options, extension) => {
    await initYamlIntelligenceResourcesFromFilesystem();
    const temp = createTempContext();
    try {
      if (!extension) {
        info("Please provide an extension name, url, or path.");
        signalCommandFailure();
      }
      const result2 = await installExtension(
        extension,
        temp,
        options.prompt !== false,
        options.embed
      );
      if (!result2) {
        signalCommandFailure();
      }
    } finally {
      temp.cleanup();
    }
  }
);

// command/uninstall/cmd.ts
init_log();
var uninstallCommand = new Command().name("uninstall").arguments("[tool]").option(
  "--no-prompt",
  "Do not prompt to confirm actions"
).option(
  "--update-path",
  "Update system path when a tool is installed"
).description(
  `Uninstalls a global dependency (${installableToolNames().join(", ")}).`
).example(
  "Uninstall TinyTeX",
  "quarto uninstall tinytex"
).example(
  "Uninstall Chrome Headless Shell",
  "quarto uninstall chrome-headless-shell"
).action(
  async (options, tool) => {
    await initYamlIntelligenceResourcesFromFilesystem();
    if (tool) {
      await removeTool(tool, options.prompt, options.updatePath);
    } else {
      const allTools2 = await loadTools();
      if (allTools2.filter((tool2) => tool2.installed).length === 0) {
        info("No tools are installed.");
      } else {
        const toolTarget = await selectTool(allTools2, "remove");
        if (toolTarget) {
          info("");
          await removeTool(toolTarget);
        }
      }
    }
  }
);

// command/create/artifacts/artifact-shared.ts
init_text2();
init_quarto();
init_process();
init_pandoc_id();
init_mod6();
init_log();
init_path();
init_fs();
init_path2();
var keyRegExp = /(.*)qstart-(.*)-qend(.*)/;
function renderAndCopyArtifacts(target, artifactSrcDir, createDirective, data3, quiet) {
  ensureDirSync(target);
  const copiedFiles = [];
  for (const artifact of walkSync(artifactSrcDir)) {
    if (artifact.isFile) {
      keyRegExp.lastIndex = 0;
      let match = keyRegExp.exec(artifact.path);
      let resolvedPath = artifact.path;
      while (match) {
        const prefix = match[1];
        const key = match[2];
        const suffix = match[3];
        if (data3[key]) {
          resolvedPath = `${prefix}${data3[key]}${suffix}`;
        } else {
          resolvedPath = `${prefix}${key}${suffix}`;
        }
        match = keyRegExp.exec(resolvedPath);
      }
      keyRegExp.lastIndex = 0;
      const targetRelativePath = relative4(artifactSrcDir, resolvedPath);
      const targetAbsolutePath = join4(
        createDirective.directory,
        targetRelativePath
      );
      copiedFiles.push(renderArtifact(
        artifact.path,
        targetAbsolutePath,
        data3
      ));
    }
  }
  if (!quiet) {
    info(`Creating ${createDirective.displayType} at `, { newline: false });
    info(`${createDirective.directory}`, { bold: true, newline: false });
    info(":");
    for (const copiedFile of copiedFiles) {
      const relPath = relative4(createDirective.directory, copiedFile);
      info(
        `  - Created ${relPath}`
      );
    }
  }
  return copiedFiles;
}
var renderArtifact = (src2, target, data3) => {
  const srcFileName = basename4(src2);
  if (srcFileName.includes(".ejs.")) {
    const renderTarget = target.replace(/\.ejs\./, ".");
    if (safeExistsSync(renderTarget)) {
      throw new Error(`The file ${renderTarget} already exists.`);
    }
    const rendered = renderEjs(src2, data3, false);
    ensureDirSync(dirname4(renderTarget));
    Deno.writeTextFileSync(renderTarget, rendered);
    return renderTarget;
  } else {
    if (safeExistsSync(target)) {
      throw new Error(`The file ${target} already exists.`);
    }
    ensureDirSync(dirname4(target));
    Deno.copyFileSync(src2, target);
    ensureUserWritable(target);
    return target;
  }
};
async function ejsData(createDirective) {
  const title3 = capitalizeTitle(createDirective.name);
  const classname = title3.replaceAll(/[^\w]/gm, "");
  const filesafename = gfmAutoIdentifier(createDirective.name, true);
  const version4 = "1.0.0";
  const author = await gitAuthor() || "First Last";
  const qVer = coerce(quartoConfig.version());
  const quartoversion = `${qVer?.major}.${qVer?.minor}.0`;
  return {
    name: createDirective.name,
    filesafename,
    title: title3,
    classname,
    author: author.trim(),
    version: version4,
    quartoversion,
    cellLanguage: createDirective.options?.cellLanguage || filesafename
  };
}
async function gitAuthor() {
  const result2 = await execProcess({
    cmd: "git",
    args: ["config", "--global", "user.name"],
    stdout: "piped",
    stderr: "piped"
  });
  if (result2.success) {
    return result2.stdout;
  } else {
    return void 0;
  }
}

// command/create/artifacts/extension.ts
init_resources2();
init_path();
init_fs();
var kType4 = "type";
var kSubType = "subtype";
var kName2 = "name";
var kCellLanguage2 = "cellLanguage";
var kTypeExtension = "extension";
var kExtensionTypes = [
  { name: "shortcode", value: "shortcode", openfiles: ["example.qmd"] },
  { name: "filter", value: "filter", openfiles: ["example.qmd"] },
  {
    name: "revealjs plugin",
    value: "revealjs-plugin",
    openfiles: ["example.qmd"]
  },
  { name: "journal format", value: "journal", openfiles: ["template.qmd"] },
  { name: "custom format", value: "format", openfiles: ["template.qmd"] },
  { name: "metadata", value: "metadata", openfiles: [] },
  { name: "brand", value: "brand", openfiles: [] },
  { name: "engine", value: "engine", openfiles: ["example.qmd"] }
];
var kExtensionSubtypes = {
  "format": ["html", "pdf", "docx", "revealjs", "typst"]
};
var kExtensionValues = kExtensionTypes.filter((t5) => typeof t5 === "object").map((t5) => t5.value);
var extensionArtifactCreator = {
  displayName: "Extension",
  type: kTypeExtension,
  resolveOptions,
  finalizeOptions,
  nextPrompt,
  createArtifact
};
function resolveOptions(args) {
  const typeRaw = args.length > 0 ? args[0] : void 0;
  const nameRaw = args.length > 1 ? args[1] : void 0;
  const cellLanguageRaw = args.length > 2 ? args[2] : void 0;
  const options = {};
  if (typeRaw) {
    const [type4, template2] = typeRaw.split(":");
    options[kType4] = type4;
    options[kSubType] = template2;
  }
  if (nameRaw) {
    options[kName2] = nameRaw;
  }
  if (cellLanguageRaw && options[kType4] === "engine") {
    options[kCellLanguage2] = cellLanguageRaw;
  }
  return options;
}
function finalizeOptions(createOptions) {
  if (!createOptions.options.name) {
    throw new Error("Required property 'name' is missing.");
  }
  const type4 = createOptions.options[kType4];
  if (!kExtensionValues.includes(type4)) {
    throw new Error(
      `The type ${type4} isn't valid. Expected one of ${kExtensionValues.join(", ")}`
    );
  }
  const subType = createOptions.options[kSubType];
  const subTypes = kExtensionSubtypes[type4];
  if (subTypes && !subTypes.includes(subType)) {
    throw new Error(
      `The sub type ${subType} isn't valid. Expected one of ${subTypes.join(", ")}`
    );
  }
  const template2 = createOptions.options[kSubType] ? `${createOptions.options[kType4]}:${createOptions.options[kSubType]}` : createOptions.options[kType4];
  return {
    displayType: "extension",
    name: createOptions.options[kName2],
    directory: join4(
      createOptions.cwd,
      createOptions.options[kName2]
    ),
    template: template2,
    options: createOptions.options
  };
}
function nextPrompt(createOptions) {
  if (!createOptions.options[kType4]) {
    return {
      name: kType4,
      message: "Type",
      type: Select,
      options: kExtensionTypes.map((t5) => {
        if (t5 === "---") {
          return Select.separator("--------");
        } else {
          return t5;
        }
      })
    };
  }
  const subTypes = kExtensionSubtypes[createOptions.options[kType4]];
  if (!createOptions.options[kSubType] && subTypes && subTypes.length > 0) {
    return {
      name: kSubType,
      message: "Base Format",
      type: Select,
      options: subTypes.map((t5) => {
        return {
          name: t5,
          value: t5
        };
      })
    };
  }
  if (!createOptions.options[kName2]) {
    return {
      name: kName2,
      message: "Extension Name",
      type: Input
    };
  }
  if (createOptions.options[kType4] === "engine" && !createOptions.options[kCellLanguage2]) {
    return {
      name: kCellLanguage2,
      message: "Default cell language name",
      type: Input,
      default: createOptions.options[kName2]
    };
  }
}
function typeFromTemplate(template2) {
  return template2.split(":")[0];
}
async function createArtifact(createDirective, quiet) {
  const createType = typeFromTemplate(createDirective.template);
  const extType = kExtensionTypes.find((type4) => {
    if (typeof type4 === "object") {
      return type4.value === createType;
    } else {
      return false;
    }
  });
  if (!extType) {
    throw new Error(`Unrecognized extension type ${createType}`);
  }
  const openfiles = extType ? extType.openfiles : [];
  await createExtension(createDirective, quiet);
  return {
    path: createDirective.directory,
    openfiles
  };
}
async function createExtension(createDirective, quiet) {
  const artifact = templateFolder(createDirective);
  const target = createDirective.directory;
  if (existsSync2(target)) {
    throw new Error(
      `The directory ${target} already exists. Quarto extensions must have unique names - please modify the existing extension or use a unique name.`
    );
  }
  const data3 = await ejsData(createDirective);
  const filesCreated = renderAndCopyArtifacts(
    target,
    artifact,
    createDirective,
    data3,
    quiet
  );
  return filesCreated[0];
}
function templateFolder(createDirective) {
  const basePath = resourcePath(join4("create", "extensions"));
  const artifactFolderName = createDirective.template.replace(":", "-");
  return join4(basePath, artifactFolderName);
}

// command/create/artifacts/project.ts
init_types3();
init_project_types();
init_path();
init_log();
var kProjectTypes2 = projectTypes();
var kProjectTypeAliases2 = projectTypeAliases();
var kProjectTypesAndAliases2 = [
  ...kProjectTypes2,
  ...kProjectTypeAliases2
];
var kType5 = "type";
var kSubdirectory = "subdirectory";
var kBlogTypeAlias = "blog";
var kConfluenceAlias = "confluence";
var kTypeProj = "project";
var kProjectCreateTypes = [
  ...kProjectTypes2,
  kBlogTypeAlias,
  kConfluenceAlias
];
var kProjectTypeOrder = [
  "default",
  "website",
  kBlogTypeAlias,
  "manuscript",
  "book",
  kConfluenceAlias
];
var projectArtifactCreator = {
  displayName: "Project",
  type: kTypeProj,
  resolveOptions: resolveOptions2,
  finalizeOptions: finalizeOptions2,
  nextPrompt: nextPrompt2,
  createArtifact: createArtifact2
};
function resolveOptions2(args) {
  const typeRaw = args.length > 0 ? args[0] : void 0;
  const directoryRaw = args.length > 1 ? args[1] : void 0;
  const titleRaw = args.length > 2 ? args[2] : void 0;
  const options = {};
  if (typeRaw) {
    if (kProjectCreateTypes.includes(typeRaw)) {
      options[kType5] = typeRaw;
    }
  }
  if (directoryRaw) {
    options[kSubdirectory] = directoryRaw;
  }
  if (titleRaw) {
    options.name = titleRaw;
  }
  return options;
}
function resolveTemplate(type4) {
  if (type4 === "website") {
    return {
      type: type4,
      template: "default"
    };
  } else if (type4 === kBlogTypeAlias) {
    return {
      type: "website",
      template: "blog"
    };
  } else if (type4 === "confluence") {
    return {
      type: "default",
      template: kConfluenceAlias
    };
  } else {
    return {
      type: type4
    };
  }
}
function finalizeOptions2(createContext) {
  const typeStr = createContext.options[kType5] || "default";
  const resolved = resolveTemplate(typeStr);
  const subdirectory = createContext.options[kSubdirectory];
  if (!subdirectory) {
    throw new Error(
      "A directory is required for project creation with `quarto create project`"
    );
  }
  const directory = join4(createContext.cwd, subdirectory);
  let name2 = createContext.options.name;
  if (!name2) {
    name2 = defaultName(subdirectory, typeStr);
    warn(
      `No 'title' for project provided in \`quarto create project\`. Using '${name2}' as default.`
    );
  }
  const template2 = resolved.template ? `${resolved.type}:${resolved.template}` : resolved.type;
  return {
    displayType: "project",
    name: name2,
    directory,
    template: template2
  };
}
function nextPrompt2(createOptions) {
  if (!createOptions.options[kType5]) {
    const orderedTypes = kProjectCreateTypes.sort((t1, t22) => {
      if (t1 === t22) {
        return 0;
      } else if (kProjectTypeOrder.indexOf(t1) === -1) {
        return 1;
      } else {
        return kProjectTypeOrder.indexOf(t1) - kProjectTypeOrder.indexOf(t22);
      }
    });
    return {
      name: kType5,
      message: "Type",
      type: Select,
      options: orderedTypes.map((t5) => {
        return {
          name: t5,
          value: t5
        };
      })
    };
  }
  if (!createOptions.options[kSubdirectory]) {
    return {
      name: kSubdirectory,
      message: "Directory",
      type: Input
    };
  }
  if (!createOptions.options.name) {
    return {
      name: "name",
      message: "Title",
      type: Input,
      default: defaultName(
        createOptions.options[kSubdirectory],
        createOptions.options[kType5]
      )
    };
  }
}
async function createArtifact2(createDirective, quiet) {
  const dir = createDirective.directory;
  const projectTitle = createDirective.name;
  const directiveType = createDirective.template;
  const { type: type4, template: template2 } = parseProjectType(directiveType);
  if (kProjectTypesAndAliases2.indexOf(type4) === -1) {
    throw new Error(
      `Project type must be one of ${kProjectTypes2.join(", ")}, but got "${type4}".`
    );
  }
  const projType = projectType(type4);
  if (template2 && !projType.templates?.includes(template2)) {
    if (projType.templates) {
      throw new Error(
        `Project template must be one of ${projType.templates.join(", ")}, but got "${template2}".`
      );
    } else {
      throw new Error(
        `The project type ${type4} does not support any templates.`
      );
    }
  }
  await projectCreate({
    dir,
    type: type4,
    title: projectTitle,
    scaffold: true,
    engine: kMarkdownEngine,
    template: template2,
    quiet
  });
  return {
    path: dir,
    openfiles: type4 !== "default" ? ["index.qmd", "_quarto.yml"] : ["_quarto.yml"]
  };
}
function defaultName(subdirectory, type4) {
  return subdirectory !== "." ? subdirectory : type4;
}

// command/create/editor.ts
init_path2();
init_path();
init_fs();
init_platform();
var kEditorInfos = [
  positronEditorInfo(),
  vscodeEditorInfo(),
  rstudioEditorInfo()
];
async function scanForEditors(editorInfos, createResult) {
  const editors = [];
  for (const editorInfo of editorInfos) {
    const editorPath = await findEditorPath(editorInfo.actions);
    if (editorPath) {
      editors.push({
        id: editorInfo.id,
        name: editorInfo.name,
        open: editorInfo.open(editorPath, createResult),
        inEditor: editorInfo.inEditor
      });
    }
  }
  return editors;
}
function vscodeEditorInfo() {
  const editorInfo = {
    id: "vscode",
    name: "vscode",
    open: (path3, createResult) => {
      const artifactPath = createResult.path;
      const cwd2 = Deno.statSync(artifactPath).isDirectory ? artifactPath : dirname4(artifactPath);
      return async () => {
        await call(path3, { args: [artifactPath], cwd: cwd2 });
      };
    },
    inEditor: isVSCodeTerminal(),
    actions: []
  };
  if (isWindows4) {
    editorInfo.actions.push({
      action: "which",
      arg: "code.exe"
    });
    const pathActions = windowsAppPaths(
      "Microsoft VS Code",
      "code.exe"
    ).map((path3) => ({
      action: "path",
      arg: path3
    }));
    editorInfo.actions.push(...pathActions);
  } else if (isMac) {
    editorInfo.actions.push({
      action: "which",
      arg: "code"
    });
    const pathActions = macosAppPaths(
      "Visual Studio Code.app/Contents/Resources/app/bin/code"
    ).map((path3) => ({
      action: "path",
      arg: path3
    }));
    editorInfo.actions.push(...pathActions);
  } else {
    editorInfo.actions.push({
      action: "which",
      arg: "code"
    });
    editorInfo.actions.push({
      action: "path",
      arg: "/snap/bin/code"
    });
  }
  return editorInfo;
}
function positronEditorInfo() {
  const editorInfo = {
    id: "positron",
    name: "positron",
    open: (path3, createResult) => {
      const artifactPath = createResult.path;
      const cwd2 = Deno.statSync(artifactPath).isDirectory ? artifactPath : dirname4(artifactPath);
      return async () => {
        await call(path3, { args: [artifactPath], cwd: cwd2 });
      };
    },
    inEditor: isPositronTerminal(),
    actions: []
  };
  if (isWindows4) {
    editorInfo.actions.push({
      action: "which",
      arg: "Positron.exe"
    });
    const pathActions = windowsAppPaths(
      "Positron",
      "Positron.exe"
    ).map(
      (path3) => ({
        action: "path",
        arg: path3
      })
    );
    editorInfo.actions.push(...pathActions);
  } else if (isMac) {
    editorInfo.actions.push({
      action: "which",
      arg: "positron"
    });
    const pathActions = macosAppPaths(
      "Positron.app/Contents/Resources/app/bin/code"
    ).map((path3) => {
      return {
        action: "path",
        arg: path3
      };
    });
    editorInfo.actions.push(...pathActions);
  } else {
    editorInfo.actions.push({
      action: "which",
      arg: "positron"
    });
  }
  return editorInfo;
}
function rstudioEditorInfo() {
  const editorInfo = {
    id: "rstudio",
    name: "RStudio",
    open: (path3, createResult) => {
      return async () => {
        const artifactPath = createResult.path;
        const cwd2 = Deno.statSync(artifactPath).isDirectory ? artifactPath : dirname4(artifactPath);
        const artifactName = basename4(artifactPath);
        const rProjPath = join4(cwd2, `${artifactName}.Rproj`);
        Deno.writeTextFileSync(rProjPath, kRProjContents);
        const callCmd = path3.endsWith(".app") && isMac ? ["open", "-na", path3, "--args", rProjPath] : [path3, rProjPath];
        const callPath = callCmd[0];
        const args = callCmd.slice(1);
        await call(callPath, { args, cwd: cwd2 });
      };
    },
    inEditor: isRStudioTerminal(),
    actions: []
  };
  const rstudioExe = "rstudio.exe";
  if (isWindows4) {
    editorInfo.actions.push({
      action: "env",
      arg: "RS_RPOSTBACK_PATH",
      filter: (path3) => {
        return join4(dirname4(path3), rstudioExe);
      }
    });
    const paths = windowsAppPaths(
      join4("RStudio", "bin"),
      rstudioExe
    ).map((path3) => ({
      action: "path",
      arg: path3
    }));
    editorInfo.actions.push(...paths);
  } else if (isMac) {
    const paths = macosAppPaths("RStudio.app").map((path3) => ({
      action: "path",
      arg: path3
    }));
    editorInfo.actions.push(...paths);
  } else {
    editorInfo.actions.push({
      action: "env",
      arg: "RS_RPOSTBACK_PATH",
      filter: (path3) => {
        return join4(dirname4(path3), rstudioExe);
      }
    });
    editorInfo.actions.push({
      action: "path",
      arg: "/usr/lib/rstudio/bin/rstudio"
    });
    editorInfo.actions.push({
      action: "which",
      arg: "rstudio"
    });
  }
  return editorInfo;
}
var kRProjContents = `Version: 1.0

RestoreWorkspace: Default
SaveWorkspace: Default
AlwaysSaveHistory: Default

EnableCodeIndexing: Yes
UseSpacesForTab: Yes
NumSpacesForTab: 2
Encoding: UTF-8

RnwWeave: Knitr
LaTeX: pdfLaTeX`;
async function findEditorPath(actions) {
  for (const action of actions) {
    const filter3 = action.filter || ((path3) => {
      return path3;
    });
    switch (action.action) {
      case "which": {
        const path3 = await which(action.arg);
        if (path3) {
          return filter3(path3);
        }
        break;
      }
      case "path":
        if (existsSync2(action.arg)) {
          return filter3(action.arg);
        }
        break;
      case "env": {
        const envValue = Deno.env.get(action.arg);
        if (envValue) {
          return filter3(envValue);
        }
      }
    }
  }
  return void 0;
}
function windowsAppPaths(folderName, command) {
  const paths = [];
  const localAppData = Deno.env.get("LOCALAPPDATA");
  if (localAppData) {
    paths.push(join4(localAppData, "Programs", folderName, command));
  }
  const programFiles = Deno.env.get("PROGRAMFILES");
  if (programFiles) {
    paths.push(join4(programFiles, folderName, command));
  }
  const programFilesx86 = Deno.env.get("PROGRAMFILES(X86)");
  if (programFilesx86) {
    paths.push(join4(programFilesx86, folderName, command));
  }
  return paths;
}
function macosAppPaths(appName) {
  const paths = [];
  paths.push(join4("/Applications", appName));
  const home = Deno.env.get("HOME");
  if (home) {
    paths.push(join4(home, "Applications", appName));
  }
  return paths;
}

// command/create/cmd.ts
init_log();
var kArtifactCreators = [
  projectArtifactCreator,
  extensionArtifactCreator
  // documentArtifactCreator, CT: Disabled for 1.2 as it arrived too late on the scene
];
var createCommand = new Command().name("create").description("Create a Quarto project or extension").option(
  "--open [editor:string]",
  `Open new artifact in this editor (${kEditorInfos.map((info2) => info2.id).join(", ")})`
).option("--no-open", "Do not open in an editor").option("--no-prompt", "Do not prompt to confirm actions").option("--json", "Pass serialized creation options via stdin", {
  hidden: true
}).arguments("[type] [commands...]").action(
  async (options, type4, ...commands2) => {
    await initializeProjectContextAndEngines();
    if (options.json) {
      await createFromStdin();
    } else {
      const isInteractive = isInteractiveTerminal() && !runningInCI();
      const allowPrompt = isInteractive && !!options.prompt && !options.json;
      if (options.open !== false && isPositWorkbench()) {
        if (options.open !== void 0) {
          info(
            `The --open option is not supported in Posit Workbench - ignoring`
          );
        }
        options.open = false;
      }
      const resolved = await resolveArtifact(
        type4,
        options.prompt
      );
      const resolvedArtifact = resolved.artifact;
      if (resolvedArtifact) {
        const args = commands2;
        const commandOpts = resolvedArtifact.resolveOptions(args);
        const createOptions = {
          cwd: Deno.cwd(),
          options: commandOpts
        };
        if (allowPrompt) {
          let nextPrompt3 = resolvedArtifact.nextPrompt(createOptions);
          while (nextPrompt3 !== void 0) {
            if (nextPrompt3) {
              const result2 = await prompt([nextPrompt3]);
              createOptions.options = {
                ...createOptions.options,
                ...result2
              };
            }
            nextPrompt3 = resolvedArtifact.nextPrompt(createOptions);
          }
        }
        const createDirective = resolvedArtifact.finalizeOptions(
          createOptions
        );
        const createResult = await resolvedArtifact.createArtifact(
          createDirective
        );
        if (allowPrompt && options.open !== false) {
          const resolvedEditor = await resolveEditor(
            createResult,
            typeof options.open === "string" ? options.open : void 0
          );
          if (resolvedEditor) {
            resolvedEditor.open();
          }
        }
      }
    }
  }
);
var resolveArtifact = async (type4, prompt2) => {
  const findArtifact = (type5) => {
    return kArtifactCreators.find(
      (artifact2) => artifact2.type === type5 && artifact2.enabled !== false
    );
  };
  let artifact = type4 ? findArtifact(type4) : void 0;
  while (artifact === void 0) {
    if (!prompt2) {
      if (type4) {
        throw new Error(`Failed to create ${type4} - the type isn't recognized`);
      } else {
        throw new Error(
          `Creation failed - you must provide a type to create when using '--no-prompt'`
        );
      }
    }
    if (type4) {
      info(`Unknown type ${type4} - please select from the following:`);
    }
    type4 = await promptForType();
    artifact = findArtifact(type4);
  }
  return {
    artifact
  };
};
async function promptSelect(message, options) {
  return await Select.prompt({
    message,
    options
  });
}
var promptForType = async () => {
  return await promptSelect(
    "Create",
    kArtifactCreators.map((artifact) => {
      return {
        name: artifact.displayName.toLowerCase(),
        value: artifact.type
      };
    })
  );
};
var resolveEditor = async (createResult, editor) => {
  const editors = await scanForEditors(kEditorInfos, createResult);
  const defaultEditor = editors.find((ed) => {
    return ed.id === editor;
  });
  if (defaultEditor) {
    return defaultEditor;
  } else {
    const inEditor = editors.find((ed) => ed.inEditor);
    if (inEditor) {
      return inEditor;
    } else if (editors.length > 0) {
      const editorOptions = editors.map((editor2) => {
        return {
          name: editor2.name.toLowerCase(),
          value: editor2.name
        };
      });
      const options = [...editorOptions, {
        name: "(don't open)",
        value: "do not open"
      }];
      const name2 = await promptSelect("Open With", options);
      const selectedEditor = editors.find((edit) => edit.name === name2);
      return selectedEditor;
    } else {
      return void 0;
    }
  }
};
async function createFromStdin() {
  const { value: input } = await readLines2(Deno.stdin).next();
  Deno.stdin.close();
  const jsonOptions = JSON.parse(input);
  const type4 = jsonOptions.type;
  if (!type4) {
    throw new Error(
      "The provided json for create artifacts must include a valid type"
    );
  }
  if (!jsonOptions.directive || !jsonOptions.directive.name || !jsonOptions.directive.directory || !jsonOptions.directive.template) {
    throw new Error(
      "The provided json for create artifacts must include a directive with a name, directory, and template."
    );
  }
  const resolved = await resolveArtifact(
    type4,
    false
  );
  const createDirective = jsonOptions.directive;
  const createResult = await resolved.artifact.createArtifact(
    createDirective,
    true
  );
  const resultJSON = JSON.stringify(createResult, void 0);
  Deno.stdout.writeSync(new TextEncoder().encode(resultJSON));
}

// command/editor-support/crossref.ts
init_path();
init_log();

// deno_ral/encoding.ts
init_base64();

// command/editor-support/crossref.ts
init_process();
init_resources2();
init_temp();
function parseCrossrefFlags(options, args) {
  let input, output;
  if (options.input && args[0]) {
    input = args.shift();
  } else if (options.output && args[0]) {
    output = args.shift();
  }
  const argsStack = [...args];
  let arg = argsStack.shift();
  while (arg !== void 0) {
    switch (arg) {
      case "-i":
      case "--input":
        arg = argsStack.shift();
        if (arg) {
          input = arg;
        }
        break;
      case "-o":
      case "--output":
        arg = argsStack.shift();
        if (arg) {
          output = arg;
        }
        break;
      default:
        arg = argsStack.shift();
        break;
    }
  }
  return { input, output };
}
var makeCrossrefCommand = () => {
  return new Command().description("Index cross references for content").stopEarly().arguments("[...args]").option(
    "-i, --input",
    "Use FILE as input (default: stdin)."
  ).option(
    "-o, --output",
    "Write output to FILE (default: stdout)."
  ).action(async (options, ...args) => {
    const flags = parseCrossrefFlags(options, args);
    const getInput = async () => {
      if (flags.input) {
        return Deno.readTextFileSync(flags.input);
      } else {
        const stdinContent = await readAll(Deno.stdin);
        return new TextDecoder().decode(stdinContent);
      }
    };
    const getOutputFile = () => flags.output || "stdout";
    const input = await getInput();
    const indexingDir = globalTempContext().createDir();
    const indexFile = join4(indexingDir, "index.json");
    Deno.env.set("QUARTO_CROSSREF_INDEX_PATH", indexFile);
    Deno.env.set("QUARTO_CROSSREF_INPUT_TYPE", "qmd");
    const cmd = pandocBinaryPath();
    const cmdArgs = ["+RTS", "-K512m", "-RTS"];
    cmdArgs.push(...[
      "--from",
      resourcePath("filters/qmd-reader.lua"),
      "--to",
      "native",
      "--data-dir",
      resourcePath("pandoc/datadir"),
      "--lua-filter",
      resourcePath("filters/quarto-init/quarto-init.lua"),
      "--lua-filter",
      resourcePath("filters/crossref/crossref.lua")
    ]);
    const filterParams = encodeBase64(
      JSON.stringify({
        ["crossref-index-file"]: "index.json",
        ["crossref-input-type"]: "qmd"
      })
    );
    const result2 = await execProcess(
      {
        cmd,
        args: cmdArgs,
        cwd: indexingDir,
        env: {
          "QUARTO_FILTER_PARAMS": filterParams,
          "QUARTO_SHARE_PATH": resourcePath()
        },
        stdout: "piped"
      },
      input,
      void 0,
      // mergeOutput?: "stderr>stdout" | "stdout>stderr",
      void 0,
      // stderrFilter?: (output: string) => string,
      void 0,
      // respectStreams?: boolean,
      5e3
    );
    if (!result2.success) {
      error("Error running Pandoc: " + result2.stderr);
      throw new Error(result2.stderr);
    }
    const outputFile5 = getOutputFile();
    if (outputFile5 === "stdout") {
      Deno.stdout.writeSync(Deno.readFileSync(indexFile));
    } else {
      Deno.writeTextFileSync(outputFile5, Deno.readTextFileSync(indexFile));
    }
  });
};
var crossrefCommand = makeCrossrefCommand();

// command/editor-support/cmd.ts
var editorSupportCommand = new Command().name("editor-support").description(
  "Miscellaneous tools to support Quarto editor modes"
).hidden().command("crossref", crossrefCommand);

// command/call/engine-cmd.ts
await init_engine();
var engineCommand = new Command().name("engine").description(
  `Access functionality specific to quarto's different rendering engines.`
).stopEarly().arguments("<engine-name:string> [args...:string]").action(async (options, engineName, ...args) => {
  await initializeProjectContextAndEngines();
  const engine = executionEngine(engineName);
  if (!engine) {
    console.error(`Unknown engine: ${engineName}`);
    console.error(
      `Available engines: ${executionEngines().map((e5) => e5.name).join(", ")}`
    );
    Deno.exit(1);
  }
  if (!engine.populateCommand) {
    console.error(`Engine ${engineName} does not support subcommands`);
    Deno.exit(1);
  }
  const engineSubcommand = new Command().description(
    `Access functionality specific to the ${engineName} rendering engine.`
  );
  engine.populateCommand(engineSubcommand);
  await engineSubcommand.parse(args);
});

// command/call/build-ts-extension/cmd.ts
init_log();
init_resources2();
init_process();
init_path();
init_fs();
init_expand_glob2();
init_yaml();
init_log();
async function resolveConfig() {
  const cwd2 = Deno.cwd();
  const userConfigPath = join4(cwd2, "deno.json");
  if (existsSync2(userConfigPath)) {
    info(`Using config: ${userConfigPath}`);
    const content2 = Deno.readTextFileSync(userConfigPath);
    const config3 = JSON.parse(content2);
    if (config3.importMap && config3.imports) {
      error('deno.json contains both "importMap" and "imports"\n');
      error(
        'deno.json can use either "importMap" (path to file) OR "imports" (inline mappings), but not both.\n'
      );
      error("Please remove one of these fields from your deno.json.");
      Deno.exit(1);
    }
    return { config: config3, configPath: userConfigPath };
  }
  const defaultConfigPath = resourcePath("extension-build/deno.json");
  if (!existsSync2(defaultConfigPath)) {
    error("Could not find default extension-build configuration.\n");
    error("This may indicate that Quarto was not built correctly.");
    error("Expected config at: " + defaultConfigPath);
    Deno.exit(1);
  }
  info(`Using default config: ${defaultConfigPath}`);
  const content = Deno.readTextFileSync(defaultConfigPath);
  const config2 = JSON.parse(content);
  return { config: config2, configPath: defaultConfigPath };
}
async function autoDetectEntryPoint(configEntryPoint) {
  if (configEntryPoint) {
    if (!existsSync2(configEntryPoint)) {
      error(
        `Entry point specified in deno.json does not exist: ${configEntryPoint}`
      );
      Deno.exit(1);
    }
    return configEntryPoint;
  }
  const srcDir = "src";
  if (!existsSync2(srcDir)) {
    error("No src/ directory found.\n");
    error("Create a TypeScript file in src/:");
    error("  mkdir -p src");
    error("  touch src/my-engine.ts\n");
    error("Or specify entry point as argument:");
    error("  quarto call build-ts-extension src/my-engine.ts\n");
    if (existsSync2("deno.json")) {
      error("Or configure in deno.json:");
      error("  {");
      error('    "bundle": {');
      error('      "entryPoint": "path/to/file.ts"');
      error("    }");
      error("  }");
    }
    Deno.exit(1);
  }
  const tsFiles = [];
  for await (const entry of Deno.readDir(srcDir)) {
    if (entry.isFile && entry.name.endsWith(".ts")) {
      tsFiles.push(entry.name);
    }
  }
  if (tsFiles.length === 0) {
    error("No .ts files found in src/\n");
    error("Create a TypeScript file:");
    error("  touch src/my-engine.ts");
    Deno.exit(1);
  }
  if (tsFiles.length === 1) {
    return join4(srcDir, tsFiles[0]);
  }
  if (tsFiles.includes("mod.ts")) {
    return join4(srcDir, "mod.ts");
  }
  error(`Multiple .ts files found in src/: ${tsFiles.join(", ")}
`);
  error("Specify entry point as argument:");
  error("  quarto call build-ts-extension src/my-engine.ts\n");
  error("Or rename one file to mod.ts:");
  error(`  mv src/${tsFiles[0]} src/mod.ts
`);
  if (existsSync2("deno.json")) {
    error("Or configure in deno.json:");
    error("  {");
    error('    "bundle": {');
    error('      "entryPoint": "src/my-engine.ts"');
    error("    }");
    error("  }");
  }
  Deno.exit(1);
}
function inferFilename(entryPoint) {
  const fileName = basename4(entryPoint, extname4(entryPoint));
  return `${fileName}.js`;
}
function inferOutputPath(outputFilename, userSpecifiedFilename) {
  const extensionName = basename4(outputFilename, extname4(outputFilename));
  const extensionsDir = "_extensions";
  if (!existsSync2(extensionsDir)) {
    error("No _extensions/ directory found.\n");
    if (userSpecifiedFilename) {
      error(
        `You specified outputFile: "${userSpecifiedFilename}" in deno.json.`
      );
      error("To write to the current directory, use a path prefix:");
      error(`  "outputFile": "./${userSpecifiedFilename}"
`);
      error("Or create an extension structure:");
    } else {
      error(
        "Extension projects must have an _extensions/ directory with _extension.yml."
      );
      error("Create the extension structure:");
    }
    error(`  mkdir -p _extensions/${extensionName}`);
    error(`  touch _extensions/${extensionName}/_extension.yml`);
    Deno.exit(1);
  }
  const extensionYmlFiles = [];
  for (const entry of expandGlobSync2("_extensions/**/_extension.yml")) {
    extensionYmlFiles.push(dirname4(entry.path));
  }
  if (extensionYmlFiles.length === 0) {
    error("No _extension.yml found in _extensions/ subdirectories.\n");
    error(
      "Extension projects must have _extension.yml in a subdirectory of _extensions/."
    );
    error("Create the extension metadata:");
    error(`  touch _extensions/${extensionName}/_extension.yml`);
    Deno.exit(1);
  }
  if (extensionYmlFiles.length > 1) {
    const extensionNames = extensionYmlFiles.map(
      (path3) => path3.replace("_extensions/", "")
    );
    error(
      `Multiple extension directories found: ${extensionNames.join(", ")}
`
    );
    if (existsSync2("deno.json")) {
      const relativeExtPath = extensionYmlFiles[0].replace(
        /^.*\/_extensions\//,
        "_extensions/"
      );
      error("Specify the output path in deno.json:");
      error("  {");
      error('    "bundle": {');
      error(`      "outputFile": "${relativeExtPath}/${outputFilename}"`);
      error("    }");
      error("  }");
    } else {
      error("This tool doesn't currently support multi-extension projects.");
      error(
        "Use `quarto call build-ts-extension --init-config` to create a deno.json if this is intentional."
      );
    }
    Deno.exit(1);
  }
  return join4(extensionYmlFiles[0], outputFilename);
}
async function bundle(entryPoint, config2, configPath) {
  info("Bundling...");
  const denoBinary = Deno.env.get("QUARTO_DENO") || architectureToolsPath("deno");
  let outputPath;
  if (config2.bundle?.outputFile) {
    const specifiedOutput = config2.bundle.outputFile;
    if (!specifiedOutput.includes("/") && !specifiedOutput.includes("\\")) {
      outputPath = inferOutputPath(specifiedOutput, specifiedOutput);
    } else {
      outputPath = specifiedOutput;
    }
  } else {
    const filename = inferFilename(entryPoint);
    outputPath = inferOutputPath(filename);
  }
  const outputDir = dirname4(outputPath);
  if (!existsSync2(outputDir)) {
    Deno.mkdirSync(outputDir, { recursive: true });
  }
  const args = [
    "bundle",
    `--config=${configPath}`,
    `--output=${outputPath}`,
    entryPoint
  ];
  if (config2.bundle?.minify) {
    args.push("--minify");
  }
  if (config2.bundle?.sourcemap) {
    const sourcemapValue = config2.bundle.sourcemap;
    if (typeof sourcemapValue === "string") {
      args.push(`--sourcemap=${sourcemapValue}`);
    } else {
      args.push("--sourcemap");
    }
  }
  const result2 = await execProcess({
    cmd: denoBinary,
    args,
    cwd: Deno.cwd()
  });
  if (!result2.success) {
    error("deno bundle failed");
    if (result2.stderr) {
      error(result2.stderr);
    }
    Deno.exit(1);
  }
  validateExtensionYml(outputPath);
  info(`\u2713 Built ${entryPoint} \u2192 ${outputPath}`);
}
function validateExtensionYml(outputPath) {
  const extensionDir2 = dirname4(outputPath);
  const extensionYmlPath = join4(extensionDir2, "_extension.yml");
  if (!existsSync2(extensionYmlPath)) {
    return;
  }
  try {
    const yml = readYaml(extensionYmlPath);
    const engines = yml?.contributes?.engines;
    if (Array.isArray(engines)) {
      const outputFilename = basename4(outputPath);
      for (const engine of engines) {
        const enginePath = typeof engine === "string" ? engine : engine?.path;
        if (enginePath && enginePath !== outputFilename) {
          warn(
            `_extension.yml specifies engine path "${enginePath}" but built file is "${outputFilename}"`
          );
          warn(`  Update _extension.yml to: path: ${outputFilename}`);
        }
      }
    }
  } catch {
  }
}
async function initializeConfig() {
  const configPath = "deno.json";
  if (existsSync2(configPath)) {
    const importMapPath2 = resourcePath("extension-build/import-map.json");
    error("deno.json already exists\n");
    error("To use Quarto's default config, remove the existing deno.json.");
    error("Or manually add the importMap to your existing config:");
    info(`  "importMap": "${importMapPath2}"`);
    Deno.exit(1);
  }
  const importMapPath = resourcePath("extension-build/import-map.json");
  const config2 = {
    compilerOptions: {
      strict: true,
      lib: ["deno.ns", "DOM", "ES2021"]
    },
    importMap: importMapPath
  };
  Deno.writeTextFileSync(
    configPath,
    JSON.stringify(config2, null, 2) + "\n"
  );
  info("\u2713 Created deno.json");
  info(`  Import map: ${importMapPath}`);
  info("");
  info("Customize as needed:");
  info('  - Add "bundle" section for build options:');
  info('      "entryPoint": "src/my-engine.ts"');
  info('      "outputFile": "_extensions/my-engine/my-engine.js"');
  info('      "minify": true');
  info('      "sourcemap": true');
  info('  - Modify "compilerOptions" for type-checking behavior');
}
var buildTsExtensionCommand = new Command().name("build-ts-extension").arguments("[entry-point:string]").description(
  "Build TypeScript execution engine extensions.\n\nThis command type-checks and bundles TypeScript extensions into single JavaScript files using Quarto's bundled deno bundle.\n\nThe entry point is determined by:\n  1. [entry-point] command-line argument (if specified)\n  2. bundle.entryPoint in deno.json (if specified)\n  3. Single .ts file in src/ directory\n  4. src/mod.ts (if multiple .ts files exist)"
).option("--check", "Type-check only (skip bundling)").option(
  "--init-config",
  "Generate deno.json with absolute importMap path"
).action(async (options, entryPointArg) => {
  try {
    if (options.initConfig) {
      await initializeConfig();
      return;
    }
    const { config: config2, configPath } = await resolveConfig();
    const entryPoint = entryPointArg || await autoDetectEntryPoint(
      config2.bundle?.entryPoint
    );
    info(`Entry point: ${entryPoint}`);
    if (options.check) {
      info("Type-checking...");
      const denoBinary = Deno.env.get("QUARTO_DENO") || architectureToolsPath("deno");
      const result2 = await execProcess({
        cmd: denoBinary,
        args: ["check", `--config=${configPath}`, entryPoint],
        cwd: Deno.cwd()
      });
      if (!result2.success) {
        error("Type check failed\n");
        error(
          "See errors above. Fix type errors in your code or adjust compilerOptions in deno.json."
        );
        Deno.exit(1);
      }
      info("\u2713 Type check passed");
    } else {
      await bundle(entryPoint, config2, configPath);
    }
  } catch (e5) {
    if (e5 instanceof Error) {
      error(e5.message);
    } else {
      error(String(e5));
    }
    Deno.exit(1);
  }
});

// command/call/typst-gather/cmd.ts
init_log();
init_process();
init_path();
init_fs();
init_expand_glob2();
init_yaml();
async function findExtensionDir() {
  const cwd2 = Deno.cwd();
  if (existsSync2(join4(cwd2, "_extension.yml"))) {
    return cwd2;
  }
  const extensionsDir = join4(cwd2, "_extensions");
  if (existsSync2(extensionsDir)) {
    const extensionDirs = [];
    for (const entry of expandGlobSync2("_extensions/**/_extension.yml")) {
      extensionDirs.push(dirname4(entry.path));
    }
    if (extensionDirs.length === 1) {
      return extensionDirs[0];
    } else if (extensionDirs.length > 1) {
      console.error("Multiple extension directories found.\n");
      console.error(
        "Run this command from within a specific extension directory,"
      );
      console.error(
        "or create a typst-gather.toml to specify the configuration."
      );
      return null;
    }
  }
  return null;
}
function extractTypstFiles(extensionDir2) {
  const extensionYmlPath = join4(extensionDir2, "_extension.yml");
  if (!existsSync2(extensionYmlPath)) {
    return [];
  }
  try {
    const yml = readYaml(extensionYmlPath);
    const typstConfig = yml?.contributes?.formats?.typst;
    if (!typstConfig) {
      return [];
    }
    const files = [];
    if (typstConfig.template) {
      files.push(join4(extensionDir2, typstConfig.template));
    }
    if (typstConfig["template-partials"]) {
      for (const partial of typstConfig["template-partials"]) {
        files.push(join4(extensionDir2, partial));
      }
    }
    return files;
  } catch {
    return [];
  }
}
async function resolveConfig2(extensionDir2) {
  const cwd2 = Deno.cwd();
  const configPath = join4(cwd2, "typst-gather.toml");
  if (existsSync2(configPath)) {
    info(`Using config: ${configPath}`);
    return {
      configFile: configPath,
      destination: "",
      discover: []
    };
  }
  if (!extensionDir2) {
    console.error(
      "No typst-gather.toml found and no extension directory detected.\n"
    );
    console.error("Either:");
    console.error("  1. Create a typst-gather.toml file, or");
    console.error(
      "  2. Run from within an extension directory with _extension.yml"
    );
    return null;
  }
  const typstFiles = extractTypstFiles(extensionDir2);
  if (typstFiles.length === 0) {
    console.error("No Typst files found in _extension.yml.\n");
    console.error(
      "The extension must define 'template' or 'template-partials' under contributes.formats.typst"
    );
    return null;
  }
  const destination = join4(extensionDir2, "typst/packages");
  const relDest = relative4(cwd2, destination);
  const relFiles = typstFiles.map((f5) => relative4(cwd2, f5));
  info(`Auto-detected from _extension.yml:`);
  info(`  Destination: ${relDest}`);
  info(`  Files to scan: ${relFiles.join(", ")}`);
  return {
    destination,
    discover: typstFiles
  };
}
function generateConfigFromAnalysis(result2, rootdir) {
  const lines2 = [];
  lines2.push("# typst-gather configuration");
  lines2.push("# Run: quarto call typst-gather");
  lines2.push("");
  if (rootdir) {
    lines2.push(`rootdir = "${toTomlPath(rootdir)}"`);
  }
  lines2.push('destination = "typst/packages"');
  lines2.push("");
  if (result2.files.length === 1) {
    lines2.push(`discover = "${toTomlPath(result2.files[0])}"`);
  } else if (result2.files.length > 1) {
    const files = result2.files.map((f5) => `"${toTomlPath(f5)}"`).join(", ");
    lines2.push(`discover = [${files}]`);
  } else {
    lines2.push('# discover = "template.typ"  # Add your .typ files here');
  }
  lines2.push("");
  const previewImports = result2.imports.filter(
    (i6) => i6.namespace === "preview"
  );
  lines2.push("# Preview packages are auto-discovered from imports.");
  lines2.push("# Uncomment to pin specific versions:");
  lines2.push("# [preview]");
  if (previewImports.length > 0) {
    const seen = /* @__PURE__ */ new Set();
    for (const { name: name2, version: version4, direct, source: source2 } of previewImports) {
      if (!seen.has(name2)) {
        seen.add(name2);
        const suffix = direct ? "" : `  # via ${source2}`;
        lines2.push(`# ${name2} = "${version4}"${suffix}`);
      }
    }
  } else {
    lines2.push('# cetz = "0.4.1"');
  }
  lines2.push("");
  const localImports2 = result2.imports.filter(
    (i6) => i6.namespace === "local" && i6.direct
  );
  lines2.push(
    "# Local packages (@local namespace) must be configured manually."
  );
  if (localImports2.length > 0) {
    lines2.push("# Found @local imports:");
    const seen = /* @__PURE__ */ new Set();
    for (const { name: name2, version: version4, source: source2 } of localImports2) {
      if (!seen.has(name2)) {
        seen.add(name2);
        lines2.push(`#   @local/${name2}:${version4} (in ${source2})`);
      }
    }
    lines2.push("[local]");
    seen.clear();
    for (const { name: name2 } of localImports2) {
      if (!seen.has(name2)) {
        seen.add(name2);
        lines2.push(`${name2} = "/path/to/${name2}"  # TODO: set correct path`);
      }
    }
  } else {
    lines2.push("# [local]");
    lines2.push('# my-pkg = "/path/to/my-pkg"');
  }
  lines2.push("");
  return lines2.join("\n");
}
async function initConfig() {
  const configFile = join4(Deno.cwd(), "typst-gather.toml");
  if (existsSync2(configFile)) {
    console.error("typst-gather.toml already exists");
    console.error("Remove it first or edit it manually.");
    Deno.exit(1);
  }
  const extensionDir2 = await findExtensionDir();
  if (!extensionDir2) {
    console.error("No extension directory found.");
    console.error(
      "Run this command from a directory containing _extension.yml or _extensions/"
    );
    Deno.exit(1);
  }
  const typFiles = extractTypstFiles(extensionDir2);
  if (typFiles.length === 0) {
    info("Warning: No .typ files found in _extension.yml.");
    info(
      "Edit the generated typst-gather.toml to configure local or pinned dependencies."
    );
  } else {
    info(`Found extension: ${extensionDir2}`);
  }
  const discoverArray = typFiles.map((f5) => `"${toTomlPath(f5)}"`).join(", ");
  const analyzeConfig = `discover = [${discoverArray}]
`;
  const analysis = await runAnalyze(analyzeConfig);
  const rootdir = relative4(Deno.cwd(), extensionDir2);
  const configContent = generateConfigFromAnalysis(analysis, rootdir);
  try {
    Deno.writeTextFileSync(configFile, configContent);
  } catch (e5) {
    console.error(`Error writing typst-gather.toml: ${e5}`);
    Deno.exit(1);
  }
  const previewImports = analysis.imports.filter(
    (i6) => i6.namespace === "preview"
  );
  const localImports2 = analysis.imports.filter(
    (i6) => i6.namespace === "local" && i6.direct
  );
  info("Created typst-gather.toml");
  if (analysis.files.length > 0) {
    info(`  Scanned: ${analysis.files.join(", ")}`);
  }
  if (previewImports.length > 0) {
    info(`  Found ${previewImports.length} @preview import(s)`);
  }
  if (localImports2.length > 0) {
    info(
      `  Found ${localImports2.length} @local import(s) - configure paths in [local] section`
    );
  }
  info("");
  info("Next steps:");
  info("  1. Review and edit typst-gather.toml");
  if (localImports2.length > 0) {
    info("  2. Add paths for @local packages in [local] section");
  }
  info("  3. Run: quarto call typst-gather");
}
var typstGatherCommand = new Command().name("typst-gather").description(
  "Gather Typst packages for a format extension.\n\nThis command scans Typst files for @preview imports and downloads the packages to a local directory for offline use.\n\nConfiguration is determined by:\n  1. typst-gather.toml in current directory (if present)\n  2. Auto-detection from _extension.yml (template and template-partials)"
).option(
  "--init-config",
  "Generate a starter typst-gather.toml in current directory"
).action(async (options) => {
  if (options.initConfig) {
    await initConfig();
    return;
  }
  try {
    const extensionDir2 = await findExtensionDir();
    const config2 = await resolveConfig2(extensionDir2);
    if (!config2) {
      Deno.exit(1);
    }
    const typstGatherBinary = typstGatherBinaryPath();
    info(`Running typst-gather...`);
    let result2;
    if (config2.configFile) {
      result2 = await execProcess({
        cmd: typstGatherBinary,
        args: ["gather", config2.configFile],
        cwd: Deno.cwd()
      });
    } else {
      const discoverArray = config2.discover.map((p5) => `"${toTomlPath(p5)}"`).join(", ");
      let tomlContent = "";
      if (config2.rootdir) {
        tomlContent += `rootdir = "${toTomlPath(config2.rootdir)}"
`;
      }
      tomlContent += `destination = "${toTomlPath(config2.destination)}"
`;
      tomlContent += `discover = [${discoverArray}]
`;
      result2 = await execProcess(
        {
          cmd: typstGatherBinary,
          args: ["gather", "-"],
          cwd: Deno.cwd()
        },
        tomlContent
      );
    }
    if (!result2.success) {
      if (result2.stdout) {
        console.log(result2.stdout);
      }
      if (result2.stderr) {
        console.error(result2.stderr);
      }
      const output = (result2.stdout || "") + (result2.stderr || "");
      if (output.includes("@local imports not configured") && !config2.configFile) {
        console.error("");
        console.error(
          "Tip: Run 'quarto call typst-gather --init-config' to generate a config file"
        );
        console.error(
          "     with placeholders for your @local package paths."
        );
      }
      Deno.exit(1);
    }
    info("Done!");
  } catch (e5) {
    if (e5 instanceof Error) {
      console.error(e5.message);
    } else {
      console.error(String(e5));
    }
    Deno.exit(1);
  }
});

// command/call/cmd.ts
var callCommand = new Command().name("call").description(
  "Access functions of Quarto subsystems such as its rendering engines."
).action(() => {
  callCommand.showHelp();
  Deno.exit(1);
}).command("engine", engineCommand).command("build-ts-extension", buildTsExtensionCommand).command("typst-gather", typstGatherCommand);

// command/dev-call/cmd.ts
init_quarto();

// core/schema/build-schema-file.ts
init_resources2();
init_schema();

// core/schema/yaml-schema.ts
init_definitions();
init_expand_glob2();
init_resources2();
init_yaml();
init_resources();
init_pandoc_formats();
var schemaResourcesLoaded = false;
async function ensureSchemaResources() {
  if (!schemaResourcesLoaded) {
    schemaResourcesLoaded = true;
    const resources = {};
    for (const walk5 of expandGlobSync2(resourcePath("schema/*.yml"))) {
      resources[`schema/${walk5.name}`] = readYaml(walk5.path);
    }
    resources[`pandoc/formats.yml`] = await pandocListFormats();
    setYamlIntelligenceResources(resources);
    await loadDefaultSchemaDefinitions();
  }
}

// format/reveal/schemas.ts
init_common4();
init_constants5();
init_constants6();
var scriptSchema = anyOfSchema(
  stringSchema,
  objectSchema({
    properties: {
      path: stringSchema,
      "async": booleanSchema
    },
    required: ["path"]
    // FIXME is this an exhaustive schema?
  })
);
var revealPluginSchema = idSchema(
  objectSchema({
    properties: {
      path: stringSchema,
      name: stringSchema,
      register: booleanSchema,
      script: anyOfSchema(scriptSchema, arraySchema(scriptSchema)),
      stylesheet: anyOfSchema(stringSchema, arraySchema(stringSchema)),
      // FIXME what's the schema for metadata?
      [kSelfContained]: booleanSchema
    },
    required: ["name"]
    // FIXME is this an exhaustive schema?
  }),
  "plugin-reveal"
);

// core/schema/build-schema-file.ts
init_deno_dom();
init_resources2();
init_process();
init_schema_utils();
init_resources();
init_format_aliases();
init_front_matter();
init_project_config();
init_chunk_metadata();
await init_base();
init_common4();
init_partition_cell_options();

// core/schema/types-from-schema.ts
init_yaml();
init_text();
init_text2();
init_path();
function typeNameFromSchemaName(schemaName) {
  return capitalizeWord(toCapitalizationCase(schemaName.replaceAll("/", "-")));
}
function fmtSource(source2) {
  return new Deno.Command(Deno.execPath(), {
    args: ["fmt", source2]
  }).output();
}
var generatedSrcMessage = `// This file is automatically generated by \`quarto dev-call build-artifacts\`! Do not edit.",
//
// If you find yourself trying to rebuild types and \`quarto dev-call build-artifacts\` won't run because
// of bad type definitions, run the following:
// $ cd $QUARTO_ROOT
// $ ./package/dist/bin/tools/deno run --importmap=./src/import_map.json --allow-all ./package/src/common/create-schema-types.ts ./src/resources

export type MaybeArrayOf<T> = (T | T[]);
export type JsonObject = { [key: string]: unknown };
// export type SchemaObject = { [key: string]: string };

`;
function schemaDefinitions(resourcePath2) {
  const definitionsSchema = parse3(
    Deno.readTextFileSync(join4(resourcePath2, "/schema/definitions.yml"))
    // deno-lint-ignore no-explicit-any
  );
  const projectSchema = parse3(
    Deno.readTextFileSync(join4(resourcePath2, "/schema/project.yml"))
    // deno-lint-ignore no-explicit-any
  );
  const schemas = [];
  for (const definition of definitionsSchema) {
    schemas.push({
      name: typeNameFromSchemaName(definition.id),
      schema: definition
    });
  }
  schemas.push(
    {
      name: "ProjectConfig",
      schema: projectSchema[0]
    },
    {
      name: "BookProject",
      schema: projectSchema[2]
    }
  );
  return schemas;
}
async function generateTypesFromSchemas(resourcePath2) {
  const schemas = schemaDefinitions(resourcePath2);
  const autoGeneratedTypes = [
    generatedSrcMessage
  ];
  for (const { name: name2, schema: schema4 } of schemas) {
    try {
      autoGeneratedTypes.push(`export type ${name2} = ${schemaToType(schema4)}`);
    } catch (e5) {
      console.error(JSON.stringify(schema4, null, 2));
      throw e5;
    }
  }
  Deno.mkdirSync(join4(resourcePath2, "/types"), { recursive: true });
  Deno.writeTextFileSync(
    join4(resourcePath2, "/types/schema-types.ts"),
    autoGeneratedTypes.join("\n\n")
  );
  await fmtSource(join4(resourcePath2, "/types/schema-types.ts"));
}
function yamlToTypeScriptKey(key) {
  if (!/^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(key)) {
    return JSON.stringify(key);
  }
  return key;
}
function schemaToType(schema4) {
  if ([true, false, null].indexOf(schema4) !== -1) {
    return String(schema4);
  }
  if (typeof schema4 === "string") {
    switch (schema4) {
      case "any":
        return "unknown";
      case "number":
      case "boolean":
      case "string":
      case "null":
        return schema4;
      case "path":
        return "string";
      case "object":
        return "JsonObject";
    }
    throw new Error(`Unimplemented: ${schema4}`);
  }
  const document2 = (schemaStr, entry) => {
    if (typeof entry.description === "string") {
      return `${schemaStr} /* ${entry.description.trim()} */`;
    } else if (typeof schema4.description === "string") {
      return `${schemaStr} /* ${schema4.description.trim()} */`;
    } else if (typeof entry.description === "object") {
      return `${schemaStr} /* ${entry.description.long.trim()} */`;
    } else if (typeof schema4.description === "object") {
      return `${schemaStr} /* ${schema4.description.long.trim()} */`;
    } else {
      return schemaStr;
    }
  };
  if (typeof schema4 === "object") {
    if (schema4.schema) return schemaToType(schema4.schema);
    if (schema4.string) {
      return document2("string", schema4.string);
    }
    if (schema4.number) {
      return document2("number", schema4.number);
    }
    if (schema4.boolean) {
      return document2("boolean", schema4.boolean);
    }
    if (schema4.path) {
      return document2("string", schema4.path);
    }
    if (schema4.arrayOf) {
      return document2(`(${schemaToType(schema4.arrayOf)})[]`, schema4.arrayOf);
    }
    if (schema4.maybeArrayOf) {
      const t5 = schemaToType(schema4.maybeArrayOf);
      return document2(`MaybeArrayOf<${t5}>`, schema4.maybeArrayOf);
    }
    if (schema4.record) {
      return document2(
        "{" + Object.entries(schema4.record).map(([key, value]) => {
          return `${yamlToTypeScriptKey(key)}: ${schemaToType(value)}`;
        }).join("; ") + "}",
        {}
      );
    }
    if (schema4.enum) {
      const doIt = (v4) => {
        if (v4.length === 1) {
          return JSON.stringify(v4[0]);
        }
        return document2(
          "(" + v4.map((x3) => JSON.stringify(x3)).join(" | ") + ")",
          schema4.enum
        );
      };
      if (Array.isArray(schema4.enum.values)) {
        return doIt(schema4.enum.values);
      }
      if (!Array.isArray(schema4.enum)) {
        throw new Error(`Unimplemented: ${JSON.stringify(schema4)}`);
      }
      return doIt(schema4.enum);
    }
    if (schema4.ref) {
      return typeNameFromSchemaName(schema4.ref);
    }
    if (schema4.allOf) {
      if (!Array.isArray(schema4.allOf)) {
        throw new Error(`Unimplemented: ${JSON.stringify(schema4)}`);
      }
      return document2(
        "(" + schema4.allOf.map(schemaToType).join(" & ") + ")",
        schema4.allOf
      );
    }
    if (schema4.anyOf) {
      if (!Array.isArray(schema4.anyOf)) {
        throw new Error(`Unimplemented: ${JSON.stringify(schema4)}`);
      }
      return document2(
        "(" + schema4.anyOf.map(schemaToType).join(" | ") + ")",
        schema4.anyOf
      );
    }
    if (schema4.object) {
      let mainType = "";
      if (schema4.object.properties) {
        mainType = "{" + Object.entries(schema4.object.properties).map(([key, value]) => {
          const optionalFlag = schema4.object.required === "all" ? false : schema4.object.required === void 0 ? true : schema4.object.required.indexOf(key) === -1;
          return `${yamlToTypeScriptKey(key)}${optionalFlag ? "?" : ""}: ${schemaToType(value)}`;
        }).sort(([k1, _v1], [k22, _v2]) => k1.localeCompare(k22)).join("; ") + "}";
      } else if (schema4.object.additionalProperties) {
        mainType = "{ [key: string]: " + schemaToType(schema4.object.additionalProperties) + " }";
      } else {
        mainType = "JsonObject";
      }
      if (schema4.object?.super?.resolveRef) {
        return document2(
          "(" + mainType + " & " + typeNameFromSchemaName(schema4.object?.super?.resolveRef) + ")",
          schema4.object
        );
      } else {
        return document2(mainType, schema4.object);
      }
    }
  }
  throw new Error(`Unimplemented: ${JSON.stringify(schema4)}`);
}

// core/schema/json-schema-from-schema.ts
var convertSchemaToJSONSchema = (_schema) => {
  const schema4 = _schema;
  if (schema4) {
    if (typeof schema4 === "string") {
      const dispatch = {
        number: { type: "number" },
        boolean: { type: "boolean" },
        string: { type: "string" },
        path: { type: "string" },
        object: { type: "object" },
        any: {}
      };
      const result2 = dispatch[schema4];
      if (!result2) {
        throw new Error(`Unknown schema type: ${schema4}`);
      }
      return result2;
    } else if (typeof schema4 === "object") {
      if (schema4.schema) {
        return convertSchemaToJSONSchema(schema4.schema);
      }
      if (schema4.enum) {
        return {
          enum: schema4.enum
        };
      }
      if (schema4.anyOf) {
        return {
          anyOf: schema4.anyOf.map(convertSchemaToJSONSchema)
        };
      }
      if (schema4.allOf) {
        return {
          allOf: schema4.allOf.map(convertSchemaToJSONSchema)
        };
      }
      if (schema4.arrayOf) {
        return {
          type: "array",
          items: convertSchemaToJSONSchema(schema4.arrayOf)
        };
      }
      if (schema4.record) {
        return {
          object: {
            properties: Object.fromEntries(
              Object.entries(schema4.record).map(([key, value]) => [
                key,
                convertSchemaToJSONSchema(value)
              ])
            ),
            required: Object.keys(schema4.record),
            additionalProperties: false
          }
        };
      }
      if (schema4.object) {
        return {
          object: {
            properties: Object.fromEntries(
              Object.entries(schema4.object.properties ?? {}).map(([key, value]) => [
                key,
                convertSchemaToJSONSchema(value)
              ])
            ),
            required: schema4.required
          }
        };
      }
      if (schema4.ref) {
        return {
          "$ref": "#/$defs/" + typeNameFromSchemaName(schema4.ref)
        };
      }
      if (schema4.maybeArrayOf) {
        const items = convertSchemaToJSONSchema(schema4.maybeArrayOf);
        return {
          anyOf: [
            {
              type: "array",
              items
            },
            items
          ]
        };
      }
      if (schema4.string) {
        return {
          type: "string"
        };
      }
      if (schema4.boolean) {
        return {
          type: "boolean"
        };
      }
      if (schema4.number) {
        return {
          type: "number"
        };
      }
      if (schema4.path) {
        return {
          type: "string"
        };
      }
    } else {
      console.log({ schema: schema4 });
      console.log(typeof schema4);
      throw new Error(`fallthrough?`);
    }
  } else {
    if (schema4 === null) {
      return {
        enum: [null]
      };
    }
  }
  console.log(JSON.stringify(schema4, null, 2));
  throw new Error("Not implemented");
};
var generateJsonSchemasFromSchemas = async (resourcePath2) => {
  const quartoSchemas = schemaDefinitions(resourcePath2);
  const defs = quartoSchemas.reduce((acc, { name: name2, schema: schema5 }) => {
    try {
      acc[name2] = convertSchemaToJSONSchema(schema5);
    } catch (e5) {
      console.log("Outermost failing schema:");
      console.log(JSON.stringify(schema5));
      throw e5;
    }
    return acc;
  }, {});
  const schema4 = {
    "$schema": "https://json-schema.org/draft/2020-12/schema",
    "$defs": defs
  };
  Deno.writeTextFileSync(
    `${resourcePath2}/schema/json-schemas.json`,
    JSON.stringify(schema4, null, 2)
  );
};

// core/schema/build-schema-file.ts
init_error2();

// core/schema/zod-types-from-schema.ts
init_fs();
init_path();
var ZodDeclarationFileBuilder = class {
  constructor() {
    this.declarations = [];
    this.inferredTypes = [];
  }
  declarations = [];
  inferredTypes = [];
  // we keep track of the schemas we've seen so we can
  // process resolve-ref schemas
  // deno-lint-ignore no-explicit-any
  schemas = {};
  // deno-lint-ignore no-explicit-any
  addSchema(obj, inComments = false) {
    this.schemas[obj.name] = obj.schema;
    const schemaName = typeNameFromSchemaName(obj.name);
    const schema4 = obj.schema;
    const zodType = this.convertToZodJsSource(schema4);
    const startComment = inComments ? "/* " : "";
    const endComment = inComments ? " */" : "";
    this.declarations.push(
      `${startComment}export const Zod${schemaName} = ${zodType};${endComment}
`
    );
    this.inferredTypes.push(
      `${startComment}export type ${schemaName} = z.infer<typeof Zod${schemaName}>;${endComment}
`
    );
  }
  fileSource() {
    const zodDeclarations = this.declarations.join("\n");
    const zodInferredTypes = this.inferredTypes.join("\n");
    const zodObject = (() => {
      const lines2 = [
        "export const Zod = {"
      ];
      Object.keys(this.schemas).forEach((name2) => {
        const typeName2 = typeNameFromSchemaName(name2);
        lines2.push(
          `  ${typeName2}: Zod${typeName2},`
        );
      });
      lines2.push("};");
      return lines2.join("\n");
    })();
    return `import { z } from "zod";

import { ZodSidebarContents, ZodNavigationItem, ZodNavigationItemObject } from "./handwritten-schema-types.ts";
export { ZodSidebarContents, ZodNavigationItem, ZodNavigationItemObject } from "./handwritten-schema-types.ts";

${generatedSrcMessage}

${zodDeclarations}
${zodInferredTypes}

${zodObject}
`;
  }
  // deno-lint-ignore no-explicit-any
  convertToZodJsSource(schema4) {
    const result2 = this.convertSchemaNull(schema4) || this.convertSchemaEnum(schema4) || this.convertExplicitSchema(schema4) || this.convertStringSchema(schema4) || this.convertNumberSchema(schema4) || this.convertBooleanSchema(schema4) || this.convertResolveRefSchema(schema4) || this.convertRefSchema(schema4) || this.convertMaybeArrayOfSchema(schema4) || this.convertArrayOfSchema(schema4) || this.convertAllOfSchema(schema4) || this.convertAnyOfSchema(schema4) || this.convertRecordSchema(schema4) || this.convertObjectSchema(schema4);
    if (result2) {
      return result2;
    }
    throw new Error(
      `Unsupported schema: ${JSON.stringify(schema4, null, 2)}`
    );
  }
  // deno-lint-ignore no-explicit-any
  convertSchemaEnum(schema4) {
    const zodEnumDeclaration = (values) => {
      const zodEnumStrings = values.filter((value) => {
        return typeof value === "string";
      }).map((value) => {
        return JSON.stringify(value);
      });
      const zodLiterals = values.filter((x3) => {
        return typeof x3 !== "string";
      });
      const zodTypes = [];
      if (zodEnumStrings.length) {
        zodTypes.push(
          `z.enum([${zodEnumStrings.join(", ")}] as const)`
        );
      }
      if (zodLiterals.length) {
        zodTypes.push(
          ...zodLiterals.map((x3) => {
            return `z.literal(${JSON.stringify(x3)})`;
          })
        );
      }
      if (zodTypes.length === 0) {
        throw new Error(
          `Unimplemented: ${JSON.stringify(schema4, null, 2)}`
        );
      } else if (zodTypes.length === 1) {
        return zodTypes[0];
      } else {
        return `z.union([${zodTypes.join(", ")}])`;
      }
    };
    if (schema4.enum) {
      if (Array.isArray(schema4.enum)) {
        return zodEnumDeclaration(schema4.enum);
      }
      return this.convertSchemaEnum(schema4.enum);
    }
    if (schema4.values) {
      return zodEnumDeclaration(schema4.values);
    }
    return void 0;
  }
  // deno-lint-ignore no-explicit-any
  convertSchemaNull(schema4) {
    if (schema4 === "null" || schema4 === null || schema4.null) {
      return `z.null()`;
    }
    return void 0;
  }
  // deno-lint-ignore no-explicit-any
  convertExplicitSchema(schema4) {
    if (schema4.schema) {
      return this.convertToZodJsSource(schema4.schema);
    }
    return void 0;
  }
  // deno-lint-ignore no-explicit-any
  convertStringSchema(schema4) {
    if (schema4 === "string") {
      return `z.string()`;
    }
    if (schema4 === "path") {
      return `z.string()`;
    }
    const zodDeclStringWithMaybePattern = (innerSchema) => {
      if (innerSchema.pattern) {
        return `z.string().regex(new RegExp(${JSON.stringify(
          innerSchema.pattern
        )}))`;
      } else {
        return `z.string()`;
      }
    };
    if (schema4.path) {
      return zodDeclStringWithMaybePattern(schema4.path);
    }
    if (schema4.string) {
      return zodDeclStringWithMaybePattern(schema4.string);
    }
    if (schema4.pattern) {
      return zodDeclStringWithMaybePattern(schema4);
    }
    return void 0;
  }
  // deno-lint-ignore no-explicit-any
  convertNumberSchema(schema4) {
    if (schema4 === "number") {
      return `z.number()`;
    }
    if (schema4.number) {
      return `z.number()`;
    }
    return void 0;
  }
  // deno-lint-ignore no-explicit-any
  convertBooleanSchema(schema4) {
    if (schema4 === "boolean") {
      return `z.boolean()`;
    }
    if (schema4.boolean) {
      return `z.boolean()`;
    }
    return void 0;
  }
  // deno-lint-ignore no-explicit-any
  convertResolveRefSchema(schema4) {
    if (schema4.resolveRef) {
      throw new Error("Unimplemented: convertResolveRefSchema");
    }
    return void 0;
  }
  // TODO: if this is a recursive schema, we need to know about that
  // and change the top-level schema to have an explicit type annotation
  // cf https://zod.dev/?id=recursive-types
  // deno-lint-ignore no-explicit-any
  convertRefSchema(schema4) {
    if (schema4.ref) {
      const refName = typeNameFromSchemaName(schema4.ref);
      return `z.lazy(() => Zod${refName})`;
    }
    return void 0;
  }
  // deno-lint-ignore no-explicit-any
  convertMaybeArrayOfSchema(schema4) {
    if (schema4.maybeArrayOf) {
      const innerSchema = schema4.maybeArrayOf;
      const innerZodType = this.convertToZodJsSource(innerSchema);
      return `z.union([${innerZodType}, z.array(${innerZodType})])`;
    }
    return void 0;
  }
  // deno-lint-ignore no-explicit-any
  convertArrayOfSchema(schema4) {
    if (schema4.arrayOf) {
      const innerSchema = schema4.arrayOf;
      const innerZodType = this.convertToZodJsSource(innerSchema);
      return `z.array(${innerZodType})`;
    }
    return void 0;
  }
  // deno-lint-ignore no-explicit-any
  convertAllOfSchema(schema4) {
    if (!schema4.allOf) {
      return void 0;
    }
    const innerSchemas = schema4.allOf;
    const innerZodTypes = innerSchemas.map((s5) => {
      return this.convertToZodJsSource(s5);
    });
    let first = innerZodTypes.shift();
    while (innerZodTypes.length > 0) {
      const innerZodType = innerZodTypes.shift();
      first = `${first}.and(${innerZodType})`;
    }
    return first;
  }
  // deno-lint-ignore no-explicit-any
  convertAnyOfSchema(schema4) {
    if (!schema4.anyOf) {
      return void 0;
    }
    const innerSchemas = schema4.anyOf;
    const innerZodTypes = innerSchemas.map((s5) => {
      return this.convertToZodJsSource(s5);
    });
    return `z.union([${innerZodTypes.join(", ")}])`;
  }
  // deno-lint-ignore no-explicit-any
  convertRecordSchema(schema4) {
    if (!schema4.record) {
      return void 0;
    }
    const properties = schema4.record.properties || schema4.record;
    return `z.object({ ${Object.entries(properties).map(([key, value]) => {
      return `${yamlToTypeScriptKey(key)}: ${this.convertToZodJsSource(value)}`;
    })}}).strict()`;
  }
  // deno-lint-ignore no-explicit-any
  convertObjectSchema(schema4) {
    const getProperties = (s5) => {
      if (s5.properties) {
        return s5.properties;
      }
      if (s5.schema) {
        return getProperties(s5.schema);
      }
      if (s5.object) {
        return getProperties(s5.object);
      }
      return {};
    };
    const resolveSuper = (s5) => {
      if (!s5.super) {
        return s5;
      }
      let superSchemas;
      if (Array.isArray(s5.super)) {
        superSchemas = s5.super.map(resolveSuper);
      } else if (s5.super.resolveRef) {
        superSchemas = [
          this.schemas[typeNameFromSchemaName(s5.super.resolveRef)]
        ];
      } else {
        throw new Error(
          `Unimplemented: ${JSON.stringify(s5.super, null, 2)}`
        );
      }
      const properties = {};
      for (const superSchema of superSchemas) {
        const superProperties = getProperties(superSchema);
        for (const key in superProperties) {
          properties[key] = superProperties[key];
        }
      }
      return {
        ...s5,
        properties: {
          ...properties,
          ...getProperties(s5)
        }
      };
    };
    if (schema4 === "object") {
      return `z.object({}).passthrough()`;
    }
    if (!schema4.object) {
      return void 0;
    }
    let obj = schema4.object;
    if (obj.namingConvention) {
      console.warn(
        "namingConvention enforcement is not supported. Ignoring."
      );
      console.warn(JSON.stringify(obj, null, 2));
    }
    const closed = obj.closed || false;
    const required = obj.required;
    obj = resolveSuper(obj);
    let baseObj = `z.object({${Object.entries(obj.properties || {}).map(([key, value]) => {
      return `${yamlToTypeScriptKey(key)}: ${this.convertToZodJsSource(value)}`;
    }).join(", ")}})`;
    if (closed) {
      baseObj = `${baseObj}.strict()`;
    } else {
      baseObj = `${baseObj}.passthrough()`;
    }
    if (Array.isArray(required)) {
      baseObj = `${baseObj}.partial().required({${required.map((key) => {
        return `${key}: true`;
      }).join(", ")}})`;
    } else if (required === void 0) {
      baseObj = `${baseObj}.partial()`;
    } else if (required === "all") {
      baseObj = `${baseObj}.required()`;
    }
    if (obj.additionalProperties) {
      baseObj = `z.record(${this.convertToZodJsSource(
        obj.additionalProperties
      )}).and(${baseObj})`;
    }
    return baseObj;
  }
};
async function generateZodTypesFromSchemas(resourcePath2) {
  const builder = new ZodDeclarationFileBuilder();
  const schemas = schemaDefinitions(resourcePath2);
  const schemasToSkip = [
    "SidebarContents",
    "NavigationItem",
    "NavigationItemObject"
  ];
  for (const schema4 of schemas) {
    builder.addSchema(schema4, schemasToSkip.includes(schema4.name));
  }
  const zodTypes = builder.fileSource();
  const schemaSchemaSourcePath = join4(
    resourcePath2,
    "types",
    "zod",
    "schema-types.ts"
  );
  ensureDirSync(join4(
    resourcePath2,
    "types",
    "zod"
  ));
  Deno.writeTextFileSync(
    schemaSchemaSourcePath,
    zodTypes
  );
  await fmtSource(schemaSchemaSourcePath);
}

// core/schema/build-schema-file.ts
async function buildIntelligenceResources() {
  await ensureSchemaResources();
  getFormatAliases();
  await getFrontMatterSchema();
  await getProjectConfigSchema();
  await getEngineOptionsSchema();
  const externalSchemas = [revealPluginSchema];
  for (const schema4 of externalSchemas) {
    setSchemaDefinition(schema4);
  }
  const htmlDescriptions = await createHtmlDescriptions();
  setYamlIntelligenceResources({
    "schema/html-descriptions.yml": htmlDescriptions,
    "schema/external-schemas.yml": externalSchemas,
    "handlers/languages.yml": languages(),
    "handlers/lang-comment-chars.yml": kLangCommentChars
  });
  for (const language of languages()) {
    let schema4 = await languageSchema(language);
    if (schema4) {
      schema4 = idSchema(schema4, `handlers/${language}`);
      setYamlIntelligenceResources({
        [`handlers/${language}/schema.yml`]: schema4
      });
    }
  }
  const yamlResources = exportYamlIntelligenceResources(true);
  const yamlResourcesPath = resourcePath(
    "/editor/tools/yaml/yaml-intelligence-resources.json"
  );
  Deno.writeTextFileSync(yamlResourcesPath, yamlResources);
  const definitions = getSchemaDefinitionsObject();
  const definitionsPath = resourcePath(
    "editor/tools/yaml/all-schema-definitions.json"
  );
  Deno.writeTextFileSync(
    definitionsPath,
    JSON.stringify(definitions)
  );
  const path3 = resourcePath();
  await Promise.all([
    generateTypesFromSchemas(path3),
    generateJsonSchemasFromSchemas(path3),
    generateZodTypesFromSchemas(path3)
  ]);
}
function getMarkdownDescriptions() {
  const result2 = [];
  const schemaList = Object.values(getSchemaDefinitionsObject());
  for (const schema4 of schemaList) {
    walkSchema(schema4, (s5) => {
      if (s5 === false || s5 === true) {
        return;
      }
      const description = s5?.tags?.description;
      if (description === void 0) {
        return;
      }
      result2.push(`## annotation
`);
      if (typeof description === "string") {
        result2.push(`### string
`);
        result2.push(description);
        result2.push("");
      } else {
        result2.push(`### short
`);
        result2.push(description?.short || "");
        result2.push("");
        result2.push(`### long
`);
        result2.push(description?.long || "");
        result2.push("");
      }
      return;
    });
  }
  return result2.join("\n");
}
async function createHtmlDescriptions() {
  const markdownDescriptions = getMarkdownDescriptions();
  const descriptionList = [];
  const cmd = [pandocBinaryPath(), "--to", "html"];
  const pandocResult = await execProcess(
    { stdout: "piped", cmd: cmd[0], args: cmd.slice(1) },
    markdownDescriptions
  );
  if (!pandocResult.success) {
    throw new InternalError("Couldn't run pandoc");
  }
  await initDenoDom();
  const doc = await parseHtml(pandocResult.stdout);
  for (const entryNode of doc.querySelectorAll("h2")) {
    const entry = entryNode;
    const values = {};
    for (const value of filter2(
      stopWhen(
        siblings(entry),
        (e5) => e5.tagName === "H2"
      ),
      (e5) => e5.tagName === "H3"
    )) {
      const name2 = value.textContent;
      const html = [];
      for (const p5 of stopWhen(siblings(value), (e5) => e5.tagName !== "P")) {
        html.push(p5.innerHTML);
      }
      values[name2] = html.join("\n");
    }
    if (values["string"]) {
      descriptionList.push(values["string"]);
    } else if (values["short"] || values["long"]) {
      descriptionList.push({
        short: values["short"],
        long: values["long"]
      });
    }
  }
  return descriptionList;
}
function* siblings(entry) {
  do {
    if (entry.nextElementSibling === null) {
      return;
    }
    entry = entry.nextElementSibling;
    yield entry;
  } while (true);
}
function* stopWhen(gen, when) {
  for (const v4 of gen) {
    if (when(v4)) {
      break;
    }
    yield v4;
  }
}
function* filter2(gen, f5) {
  for (const v4 of gen) {
    if (f5(v4)) {
      yield v4;
    }
  }
}

// command/dev-call/build-artifacts/cmd.ts
init_resources2();
var import_acorn_class_fields = __toESM(require_acorn_class_fields());
init_path();
function ensureAllowableIDESyntax(src2, filename) {
  const ast = Parser3.extend(import_acorn_class_fields.default).parse(src2, {
    ecmaVersion: "2020",
    sourceType: "module"
  });
  let failed = false;
  simple2(ast, {
    // deno-lint-ignore no-explicit-any
    ChainExpression(_node) {
      console.error(
        `Failure: Chain expression \`?.\` not allowed in ${filename}`
      );
      failed = true;
    },
    // deno-lint-ignore no-explicit-any
    LogicalExpression(node) {
      if (node.operator === "??") {
        console.error(
          `Failure: Nullish coalescing operator \`??\` not allows in ${filename}`
        );
        failed = true;
      }
    }
  });
  if (failed) {
    throw new Error("Found syntax that is not allowed");
  }
}
async function buildYAMLJS() {
  const treeSitterYamlJson = {
    "data": Array.from(Deno.readFileSync(
      resourcePath("editor/tools/yaml/tree-sitter-yaml.wasm")
    ))
  };
  Deno.writeTextFileSync(
    resourcePath("editor/tools/yaml/tree-sitter-yaml.json"),
    JSON.stringify(treeSitterYamlJson)
  );
  const esbuild = async (cwd2, filename, outputType = "iife", checkIde = true) => {
    const result2 = await esbuildCompile(
      "",
      cwd2,
      [filename],
      outputType
    );
    if (checkIde) {
      ensureAllowableIDESyntax(result2, filename);
    }
    return result2;
  };
  Deno.writeTextFileSync(
    resourcePath("editor/tools/yaml/yaml-intelligence.js"),
    await esbuild(
      resourcePath("../core/lib/yaml-intelligence"),
      "ide-main.ts",
      "esm"
    )
  );
  Deno.writeTextFileSync(
    resourcePath("editor/tools/yaml/yaml.js"),
    await esbuild(
      resourcePath("editor/tools/yaml"),
      "automation.js"
    )
  );
  const webWorkerSrc = await esbuild(
    resourcePath("../core/lib/yaml-intelligence"),
    "web-worker.ts"
  );
  const vsCodeSrc = await esbuild(
    resourcePath("../core/lib/yaml-intelligence"),
    "vs-code.ts",
    "esm",
    false
  );
  const treeSitter = Deno.readTextFileSync(
    resourcePath("editor/tools/yaml/tree-sitter.js")
  );
  ensureAllowableIDESyntax(treeSitter, "tree-sitter.js");
  Deno.writeTextFileSync(
    resourcePath("editor/tools/vs-code.mjs"),
    [treeSitter, vsCodeSrc].join("")
  );
  Deno.writeTextFileSync(
    resourcePath("editor/tools/yaml/web-worker.js"),
    [treeSitter, webWorkerSrc].join("")
  );
}
async function buildEsbuildAnalysisCache() {
  const inputFiles = [
    "quarto.js"
  ];
  const analysisCache = {};
  for (const file of inputFiles) {
    analysisCache[file] = await esbuildAnalyze(
      formatResourcePath("html", file),
      resourcePath(join4("formats", "html"))
    );
  }
  Deno.writeTextFileSync(
    formatResourcePath("html", "esbuild-analysis-cache.json"),
    JSON.stringify(analysisCache, null, 2)
  );
}
async function buildAssets() {
  await buildIntelligenceResources();
  await buildYAMLJS();
  await buildEsbuildAnalysisCache();
}
var buildJsCommand = new Command().name("build-artifacts").hidden().description(
  "Builds all the javascript assets necessary for IDE support.\n\n"
).action(async () => {
  await initYamlIntelligenceResourcesFromFilesystem();
  await buildAssets();
});

// command/dev-call/validate-yaml/cmd.ts
init_validated_yaml();
init_mapped_text2();
init_schema();
init_log();
init_errors();
init_from_yaml();
var getSchema = async (schemaNameOrFile) => {
  if (schemaNameOrFile.endsWith(".yml")) {
    getSchemaSchemas();
    const file = mappedStringFromFile(schemaNameOrFile);
    const schema4 = getSchemaDefinition("schema/schema");
    const result2 = await readAndValidateYamlFromMappedString(
      file,
      schema4
    );
    if (result2.yamlValidationErrors.length) {
      error("Schema file is not valid");
      for (const err2 of result2.yamlValidationErrors) {
        error(tidyverseFormatError(err2.niceError), { colorize: false });
      }
      Deno.exit(1);
    }
    const schemaName = `user-schema-${schemaNameOrFile}`;
    const newSchema = convertFromYaml(result2.yaml);
    newSchema.$id = schemaName;
    setSchemaDefinition(newSchema);
    return getSchemaDefinition(schemaName);
  } else {
    return getSchemaDefinition(schemaNameOrFile);
  }
};
var validateYamlCommand = new Command().name("validate-yaml").hidden().arguments("<input:string>").option(
  "-s, --schema [schema:string]",
  "Name of schema in Quarto's definitions.yml. If string ends with .yml, it is treated as a file name for a new schema, which is validated, loaded, and then used."
).option(
  "--json",
  "If set, output error messages in JSON format."
).description(
  "Validates a YAML file against Quarto's schemas.\n\n"
).action(async (options, input) => {
  await initYamlIntelligenceResourcesFromFilesystem();
  if (!options.schema) {
    throw new Error("Schema name or file is required");
  }
  const file = mappedStringFromFile(input);
  const schema4 = await getSchema(options.schema);
  const result2 = await readAndValidateYamlFromMappedString(
    file,
    schema4
  );
  if (options.json) {
    console.log(JSON.stringify(result2.yamlValidationErrors, null, 2));
  } else {
    for (const err2 of result2.yamlValidationErrors) {
      error(tidyverseFormatError(err2.niceError), { colorize: false });
    }
  }
  if (result2.yamlValidationErrors.length) {
    Deno.exit(1);
  }
});

// command/dev-call/show-ast-trace/cmd.ts
init_appdirs();
init_quarto();
init_fs();
init_path();
init_copy();
init_resources2();
init_process();
var ensureTracingToolsCopied = async () => {
  const cacheDir = quartoCacheDir();
  const tracingDir = `${cacheDir}/ast-tracing`;
  await ensureDir(tracingDir);
  safeRemoveDirSync(join4(tracingDir, "qmd"), cacheDir);
  await copy(
    resourcePath(join4("tools", "ast-tracing")),
    join4(tracingDir, "qmd")
  );
  return join4(tracingDir, "qmd");
};
var showAstTraceCommand = new Command().name("show-ast-trace").hidden().arguments("<arguments...>").description(
  "Renders the document with AST tracing enabled and then shows the debugging output.\n\n"
).action(async (_options, input, ...args) => {
  const toolsPath2 = await ensureTracingToolsCopied();
  const dir = dirname4(input);
  const base3 = basename4(input, ".qmd");
  const traceName = join4(dir, `${base3}-quarto-ast-trace.json`);
  const renderOpts = {
    cmd: quartoConfig.cliPath(),
    env: {
      "QUARTO_TRACE_FILTERS": traceName
    },
    args: [
      "render",
      input,
      ...args,
      "--quiet"
    ]
  };
  const _renderResult = await execProcess(renderOpts);
  moveSync(traceName, join4(toolsPath2, basename4(traceName)));
  const _previewResult = await execProcess({
    cmd: quartoConfig.cliPath(),
    cwd: toolsPath2,
    args: [
      "preview",
      "trace-viewer.qmd",
      "-M",
      `trace_1:${basename4(traceName)}`
    ]
  });
});

// command/dev-call/make-ast-diagram/cmd.ts
init_path();
init_resources2();
init_process();
var makeAstDiagramCommand = new Command().name("make-ast-diagram").hidden().option("-m, --mode <mode:string>", "Diagram mode (default: full)").arguments("<arguments...>").description(
  "Creates a diagram of the Pandoc AST.\n\n"
).action(async (options, ...args) => {
  const renderOpts = {
    cmd: Deno.execPath(),
    args: [
      "run",
      "--allow-read",
      "--allow-write",
      "--allow-run",
      resourcePath(join4("tools", "ast-diagram", "main.ts")),
      ...args,
      "--mode",
      options.mode || "full"
    ]
  };
  await execProcess(renderOpts);
});

// command/dev-call/pull-git-subtree/cmd.ts
init_git();
init_log();
init_log2();
var SUBTREES = [
  {
    name: "julia-engine",
    prefix: "src/resources/extension-subtrees/julia-engine",
    remoteUrl: "https://github.com/PumasAI/quarto-julia-engine.git",
    remoteBranch: "main"
  },
  {
    name: "orange-book",
    prefix: "src/resources/extension-subtrees/orange-book",
    remoteUrl: "https://github.com/quarto-ext/orange-book.git",
    remoteBranch: "main"
  }
];
async function findLastSplit(quartoRoot, prefix) {
  try {
    debug(
      `Searching for last split with grep pattern: git-subtree-dir: ${prefix}$`
    );
    const log3 = await gitCmdOutput(quartoRoot, [
      "log",
      `--grep=git-subtree-dir: ${prefix}$`,
      "-1",
      "--pretty=%b"
    ]);
    debug(`Git log output: ${log3}`);
    const splitLine = log3.split("\n").find(
      (line) => line.startsWith("git-subtree-split:")
    );
    if (!splitLine) {
      debug("No split line found in log output");
      return null;
    }
    const splitCommit = splitLine.split(/\s+/)[1];
    debug(`Found last split commit: ${splitCommit}`);
    return splitCommit;
  } catch (e5) {
    debug(`Error finding last split: ${e5}`);
    return null;
  }
}
async function pullSubtree(quartoRoot, config2) {
  info(`
=== Pulling subtree: ${config2.name} ===`);
  info(`Prefix: ${config2.prefix}`);
  info(`Remote: ${config2.remoteUrl}`);
  info(`Branch: ${config2.remoteBranch}`);
  info("Fetching...");
  await gitCmds(quartoRoot, [
    ["fetch", config2.remoteUrl, config2.remoteBranch]
  ]);
  const fetchHead = await gitCmdOutput(quartoRoot, ["rev-parse", "FETCH_HEAD"]);
  debug(`FETCH_HEAD resolves to: ${fetchHead.trim()}`);
  const prefixPath = `${quartoRoot}/${config2.prefix}`;
  let prefixExists = false;
  try {
    const stat = await Deno.stat(prefixPath);
    prefixExists = stat.isDirectory;
    debug(`Prefix directory exists: ${prefixExists} (${prefixPath})`);
  } catch {
    debug(`Prefix directory does not exist: ${prefixPath}`);
  }
  let lastSplit = await findLastSplit(quartoRoot, config2.prefix);
  if (!lastSplit) {
    info("No previous subtree found - using 'git subtree add'");
    await gitCmds(quartoRoot, [
      [
        "subtree",
        "add",
        "--squash",
        `--prefix=${config2.prefix}`,
        config2.remoteUrl,
        config2.remoteBranch
      ]
    ]);
    lastSplit = await gitCmdOutput(quartoRoot, ["rev-parse", "FETCH_HEAD^"]);
    debug(`After subtree add, lastSplit set to: ${lastSplit.trim()}`);
  }
  const commitRange = `${lastSplit}..FETCH_HEAD`;
  debug(`Checking commit range: ${commitRange}`);
  const hasNewCommits = await gitCmdOutput(quartoRoot, [
    "log",
    "--oneline",
    commitRange,
    "-1"
  ]);
  if (!hasNewCommits.trim()) {
    info("No new commits to merge");
    debug(`Commit range ${commitRange} has no commits`);
    if (!prefixExists) {
      info("WARNING: Prefix directory doesn't exist but no new commits found!");
      debug("This may indicate lastSplit was found on a different branch");
    }
    return;
  }
  debug(`Found new commits in range ${commitRange}`);
  info("Running git subtree pull --squash...");
  await gitCmds(quartoRoot, [
    [
      "subtree",
      "pull",
      "--squash",
      `--prefix=${config2.prefix}`,
      config2.remoteUrl,
      config2.remoteBranch
    ]
  ]);
  info("\u2713 Done!");
}
var pullGitSubtreeCommand = new Command().name("pull-git-subtree").hidden().arguments("[name:string]").description(
  "Pull configured git subtrees.\n\nThis command pulls from configured subtree repositories using --squash, which creates two commits: a squash commit containing the subtree changes and a merge commit that integrates it into your branch.\n\nArguments:\n  [name]  Name of subtree to pull (use 'all' or omit to pull all)"
).action(async (_options, nameArg) => {
  const quartoRoot = Deno.env.get("QUARTO_ROOT");
  if (!quartoRoot) {
    error(
      "QUARTO_ROOT environment variable not set. This command requires a development version of Quarto."
    );
    Deno.exit(1);
  }
  if (logLevel() === "DEBUG") {
    try {
      const currentBranch = await gitCmdOutput(quartoRoot, [
        "branch",
        "--show-current"
      ]);
      debug(`Current branch: ${currentBranch.trim()}`);
    } catch (e5) {
      debug(`Unable to determine current branch: ${e5}`);
    }
  }
  let subtreesToPull;
  if (!nameArg || nameArg === "all") {
    subtreesToPull = SUBTREES;
    info(`Quarto root: ${quartoRoot}`);
    info(`Processing all ${SUBTREES.length} subtree(s)...`);
  } else {
    const config2 = SUBTREES.find((s5) => s5.name === nameArg);
    if (!config2) {
      error(`Unknown subtree name: ${nameArg}`);
      error(`Available subtrees: ${SUBTREES.map((s5) => s5.name).join(", ")}`);
      Deno.exit(1);
    }
    subtreesToPull = [config2];
    info(`Quarto root: ${quartoRoot}`);
    info(`Processing subtree: ${nameArg}`);
  }
  let successCount = 0;
  let errorCount = 0;
  for (const config2 of subtreesToPull) {
    try {
      await pullSubtree(quartoRoot, config2);
      successCount++;
    } catch (err2) {
      const message = err2 instanceof Error ? err2.message : String(err2);
      error(`Failed to pull subtree ${config2.name}: ${message}`);
      errorCount++;
    }
  }
  info(`
=== Summary ===`);
  info(`Success: ${successCount}`);
  info(`Failed: ${errorCount}`);
  if (errorCount > 0) {
    Deno.exit(1);
  }
});

// command/dev-call/typst-gather/cmd.ts
init_fs();
init_log();
init_path();
init_platform();
init_resources2();
var typstGatherCommand2 = new Command().name("typst-gather").hidden().description(
  "Gather Typst packages for offline/hermetic builds.\n\nThis command runs the typst-gather tool to download @preview packages and copy @local packages to a local directory for use during Quarto builds."
).action(async () => {
  const quartoRoot = Deno.env.get("QUARTO_ROOT");
  if (!quartoRoot) {
    error(
      "QUARTO_ROOT environment variable not set. This command requires a development version of Quarto."
    );
    Deno.exit(1);
  }
  const tomlPath = join4(
    quartoRoot,
    "src/command/dev-call/typst-gather/typst-gather.toml"
  );
  const binaryName = isWindows4 ? "typst-gather.exe" : "typst-gather";
  const typstGatherBinary = Deno.env.get("QUARTO_TYPST_GATHER") || architectureToolsPath(binaryName);
  if (!existsSync2(typstGatherBinary)) {
    error(
      `typst-gather binary not found.
Run ./configure.sh to build and install it.`
    );
    Deno.exit(1);
  }
  info(`Quarto root: ${quartoRoot}`);
  info(`Config: ${tomlPath}`);
  info(`Running typst-gather...`);
  const command = new Deno.Command(typstGatherBinary, {
    args: ["gather", tomlPath],
    cwd: quartoRoot,
    stdout: "inherit",
    stderr: "inherit"
  });
  const result2 = await command.output();
  if (!result2.success) {
    error(`typst-gather failed with exit code ${result2.code}`);
    Deno.exit(result2.code);
  }
  info("Done!");
});

// command/dev-call/cmd.ts
var generateCliInfoCommand = new Command().name("cli-info").description("Generate JSON information about the Quarto CLI.").action(async () => {
  const output = {};
  output["version"] = quartoConfig.version();
  const commandsInfo = [];
  output["commands"] = commandsInfo;
  const hiddenCommands = [
    "dev-call",
    "editor-support",
    "create-project"
  ];
  const cmdAsJson = (cmd) => {
    return {
      name: cmd.getName(),
      hidden: hiddenCommands.includes(cmd.getName()),
      description: cmd.getDescription(),
      options: cmd.getOptions(),
      usage: cmd.getUsage(),
      examples: cmd.getExamples(),
      commands: cmd.getCommands().map(cmdAsJson)
    };
  };
  output["commands"] = commands().map(cmdAsJson);
  console.log(JSON.stringify(output, null, 2));
});
var devCallCommand = new Command().name("dev-call").hidden().description(
  "Access internals of Quarto - this command is not intended for general use."
).action(() => {
  devCallCommand.showHelp();
  Deno.exit(1);
}).command("cli-info", generateCliInfoCommand).command("validate-yaml", validateYamlCommand).command("build-artifacts", buildJsCommand).command("show-ast-trace", showAstTraceCommand).command("make-ast-diagram", makeAstDiagramCommand).command("pull-git-subtree", pullGitSubtreeCommand).command("typst-gather", typstGatherCommand2);

// command/command.ts
function commands() {
  return [
    // deno-lint-ignore no-explicit-any
    renderCommand,
    previewCommand,
    serveCommand,
    createCommand,
    makeUseCommand(),
    addCommand2,
    updateCommand,
    removeCommand,
    createProjectCommand,
    convertCommand,
    pandocCommand,
    typstCommand,
    runCommand,
    listCommand,
    installCommand,
    uninstallCommand,
    toolsCommand,
    publishCommand,
    capabilitiesCommand,
    inspectCommand,
    checkCommand,
    editorSupportCommand,
    callCommand,
    devCallCommand
  ];
}

// quarto.ts
init_log2();
init_log();
init_temp();
init_flags();
init_quarto();
init_process();
init_resources2();
init_profile();
init_log2();
init_mod6();

// core/devconfig.ts
init_log();
init_path();
init_fs();
init_hash2();
init_quarto();
init_path2();
init_platform();
var kDevConfig = "dev-config";
function createDevConfig(deno, deno_dom, pandoc2, dartsass, esbuild, typst, scriptDir) {
  const scriptPath = join4(scriptDir, "quarto" + (isWindows4 ? ".cmd" : ""));
  const srcDir = Deno.env.get("QUARTO_SRC_PATH") || join4(quartoConfig.sharePath(), "../../src");
  return {
    deno,
    deno_dom,
    pandoc: pandoc2,
    dartsass,
    esbuild,
    typst,
    script: md5HashSync(Deno.readTextFileSync(scriptPath)),
    importMap: md5HashSync(
      Deno.readTextFileSync(
        join4(srcDir, "import_map.json")
      )
    )
  };
}
function readInstalledDevConfig() {
  const binPath = quartoConfig.binPath();
  const configPath = join4(binPath, "..", "config", kDevConfig);
  if (existsSync2(configPath)) {
    return JSON.parse(Deno.readTextFileSync(configPath));
  } else {
    return null;
  }
}
function readSourceDevConfig() {
  const rootDir = Deno.env.get("QUARTO_ROOT") || join4(quartoConfig.sharePath(), "../..");
  const configurationScript = join4(
    rootDir,
    "configuration"
  );
  const configurationScriptSrc = Deno.readTextFileSync(configurationScript);
  const readConfig = (key) => {
    const regex = new RegExp(`${key}=(\\S+)`);
    const match = configurationScriptSrc.match(regex);
    if (match) {
      return match[1];
    } else {
      return "";
    }
  };
  return createDevConfig(
    readConfig("DENO"),
    readConfig("DENO_DOM"),
    readConfig("PANDOC"),
    readConfig("DARTSASS"),
    readConfig("ESBUILD"),
    readConfig("TYPST"),
    quartoConfig.binPath()
  );
}
function devConfigsEqual(a5, b3) {
  return a5.deno === b3.deno && a5.deno_dom === b3.deno_dom && a5.pandoc === b3.pandoc && a5.dartsass == b3.dartsass && a5.esbuild == b3.esbuild && a5.typst === b3.typst && a5.script == b3.script && a5.importMap === b3.importMap;
}
async function reconfigureQuarto(installed5, source2) {
  if (isWindows4) {
    error(
      `Quarto requires reconfiguration to ${reconfigureReason(installed5, source2)}. Please run \`./configure.cmd\` command.
`
    );
    return;
  }
  const configureScript = isWindows4 ? ["cmd", "/c", ".\\configure.cmd"] : ["./configure.sh"];
  const quartoDir2 = normalizePath(
    join4(quartoConfig.sharePath(), "..", "..")
  );
  const process4 = new Deno.Command(configureScript[0], {
    args: configureScript.slice(1),
    cwd: quartoDir2
  });
  await process4.output();
  info("");
  error(
    `Quarto required reconfiguration to ${reconfigureReason(installed5, source2)}. Please try command again.
`
  );
}
function reconfigureReason(installed5, source2) {
  const versionMessage = (dep, version4) => {
    return `install ${dep} version ${version4}`;
  };
  if (installed5 === null || installed5.deno !== source2.deno) {
    return versionMessage("Deno", source2.deno);
  } else if (installed5.deno_dom !== source2.deno_dom) {
    return versionMessage("Deno Dom", source2.deno_dom);
  } else if (installed5.pandoc !== source2.pandoc) {
    return versionMessage("Pandoc", source2.pandoc);
  } else if (installed5.dartsass !== source2.dartsass) {
    return versionMessage("Dart Sass", source2.dartsass);
  } else if (installed5.esbuild !== source2.esbuild) {
    return versionMessage("Esbuild", source2.esbuild);
  } else if (installed5.typst !== source2.typst) {
    return versionMessage("Typst", source2.typst);
  } else if (installed5.script !== source2.script) {
    return "update Quarto wrapper script";
  } else if (installed5.importMap !== source2.importMap) {
    return "update dev import map";
  }
}

// quarto.ts
init_cleanup();

// core/run/deno.ts
init_fs();
init_path();
init_appdirs();
init_process();
init_resources2();
init_path2();
init_copy5();
init_quarto();
var denoRunHandler = {
  canHandle: (script) => {
    return [".js", ".ts"].includes(extname4(script).toLowerCase());
  },
  run: async (script, args, stdin2, options) => {
    const denoDir = initDenoCache();
    options = {
      ...options,
      env: {
        ...options?.env,
        DENO_DIR: denoDir
      }
    };
    let importMap;
    if (options?.dev) {
      const srcDir = Deno.env.get("QUARTO_SRC_PATH") || join4(quartoConfig.sharePath(), "../../src");
      importMap = normalize4(join4(srcDir, "import_map.json"));
    } else {
      importMap = normalize4(join4(denoDir, "../run_import_map.json"));
    }
    const noNet = Deno.env.get("QUARTO_RUN_NO_NETWORK") === "true";
    const cachedOnly = noNet;
    return await execProcess(
      {
        cmd: architectureToolsPath("deno"),
        args: [
          "run",
          "--import-map",
          importMap,
          ...cachedOnly ? ["--cached-only"] : [],
          "--allow-all",
          "--unstable-kv",
          "--unstable-ffi",
          script,
          ...args
        ],
        ...options
      },
      stdin2,
      void 0,
      void 0,
      true
    );
  }
};
function directoryListing(path3) {
  return new Set(
    [...expandGlobSync(path3 + "/**")].map((x3) => x3.path.slice(path3.length))
  );
}
function directoryListingsMatch(path1, path22) {
  const listing1 = directoryListing(path1), listing2 = directoryListing(path22);
  for (const path3 of listing1) {
    if (!listing2.has(path3)) {
      return false;
    }
  }
  return true;
}
function initDenoCache() {
  const distDenoStd = resourcePath("deno_std");
  const cacheDenoStd = quartoCacheDir("deno_std");
  const filesDiffer = (file) => {
    const file1 = join4(distDenoStd, file);
    const file2 = join4(cacheDenoStd, file);
    if (!existsSync2(file2)) {
      return true;
    }
    return Deno.readTextFileSync(file1) !== Deno.readTextFileSync(file2);
  };
  const fileList = ["deno_std.lock", "import_map.json", "run_import_map.json"];
  if (fileList.some(filesDiffer) || // perf: don't check contents; instead only look at filenames, since they're all hashed anyway
  !directoryListingsMatch(distDenoStd, cacheDenoStd)) {
    removeIfExists(cacheDenoStd);
    copyTo(distDenoStd, cacheDenoStd);
  }
  return join4(cacheDenoStd, "cache");
}

// core/run/lua.ts
init_log();
init_path();
init_path2();
init_process();
init_resources2();
var luaRunHandler = {
  canHandle: (script) => {
    return [".lua"].includes(extname4(script).toLowerCase());
  },
  run: async (script, args, stdin2, options) => {
    if (typeof stdin2 === "string") {
      throw new Error("Lua run handlers cannot be passed stdin");
    }
    const cmd = [
      pandocBinaryPath(),
      "--from",
      "markdown",
      "--to",
      "plain"
    ];
    cmd.push(
      "--lua-filter",
      script
    );
    cmd.push(...args);
    return await execProcess(
      {
        cmd: cmd[0],
        args: cmd.slice(1),
        ...options
      },
      "",
      void 0,
      void 0,
      true
    );
  }
};

// core/run/python.ts
init_path();
init_exec();
init_process();
var pythonRunHandler = {
  canHandle: (script) => {
    return [".py"].includes(extname4(script).toLowerCase());
  },
  run: async (script, args, stdin2, options) => {
    const pythonCmd = await pythonExec();
    return await execProcess(
      {
        cmd: pythonCmd[0],
        args: [
          ...pythonCmd.slice(1),
          script,
          ...args
        ],
        ...options
      },
      stdin2,
      void 0,
      void 0,
      true
    );
  }
};

// core/run/r.ts
init_path();
init_process();
init_resources2();
var rRunHandler = {
  canHandle: (script) => {
    return [".r"].includes(extname4(script).toLowerCase());
  },
  run: async (script, args, stdin2, options) => {
    return await execProcess(
      {
        cmd: await rBinaryPath("Rscript"),
        args: [
          script,
          ...args
        ],
        ...options
      },
      stdin2,
      void 0,
      void 0,
      true
    );
  }
};

// core/run/register.ts
installRunHandler(denoRunHandler);
installRunHandler(luaRunHandler);
installRunHandler(pythonRunHandler);
installRunHandler(rRunHandler);

// format/html/format-html.ts
init_path();
init_log();
init_lodash();
init_config2();
init_resources2();
init_css();
init_constants6();
init_types5();
init_formats_shared();
init_format_html_info();

// format/html/format-html-bootstrap.ts
init_path();
init_resources2();
init_html();
init_constants6();
init_types5();

// format/html/format-html-scss.ts
init_fs();
init_path();
init_resources2();
init_css();
init_sass();
init_sass();
init_constants6();
init_website_constants();
init_format_html_shared();
init_mod();
function layerQuartoScss(key, dependency, sassLayer2, format14, darkLayer, darkDefault, loadPaths) {
  const uses = quartoUses();
  const defaults = [
    quartoDefaults(format14),
    quartoBootstrapDefaults(format14.metadata),
    quartoCopyCodeDefaults()
  ].join("\n");
  const mixins = [quartoBootstrapMixins()].join("\n");
  const functions = [quartoFunctions(), quartoBootstrapFunctions()].join("\n");
  const rules = [
    quartoRules(),
    quartoCopyCodeRules(),
    quartoBootstrapRules(),
    quartoGlobalCssVariableRules(),
    quartoLinkExternalRules(),
    quartoCodeFilenameRules()
  ].join("\n");
  const quartoScss = {
    uses,
    defaults,
    functions,
    mixins,
    rules
  };
  const frameworkFunctions = [
    bootstrapFunctions(),
    sassUtilFunctions("color-contrast.scss")
  ].join(
    "\n"
  );
  const frameworkVariables = [
    bootstrapVariables(),
    pandocVariablesToThemeScss(format14.metadata)
  ].join("\n");
  const frameworkMixins = [bootstrapMixins(), bslibComponentMixins()].join(
    "\n"
  );
  const frameworkRules = [
    bootstrapRules(),
    bslibComponentRules(),
    htmlToolsRules()
  ].join("\n");
  const bootstrapScss = {
    uses: "",
    defaults: frameworkVariables,
    functions: frameworkFunctions,
    mixins: frameworkMixins,
    rules: frameworkRules
  };
  const resolvedLoadPaths = [
    ...loadPaths || [],
    bootstrapResourceDir(),
    bslibResourceDir()
  ];
  return {
    dependency,
    key,
    user: sassLayer2,
    quarto: quartoScss,
    framework: bootstrapScss,
    loadPaths: resolvedLoadPaths,
    dark: darkLayer ? {
      user: darkLayer,
      default: darkDefault
    } : void 0,
    attribs: { id: "quarto-bootstrap" }
  };
}
function resolveBootstrapScss(input, format14, sassLayers) {
  const quartoThemesDir = formatResourcePath(
    "html",
    join4("bootstrap", "themes")
  );
  const theme = format14.metadata[kTheme] || [];
  const [themeSassLayers, defaultDark, loadPaths] = resolveThemeLayer(
    format14,
    input,
    theme,
    quartoThemesDir,
    sassLayers
  );
  const sassBundles = [];
  sassBundles.push(
    layerQuartoScss(
      "quarto-theme",
      kBootstrapDependencyName,
      themeSassLayers.light,
      format14,
      themeSassLayers.dark,
      defaultDark,
      loadPaths
    )
  );
  return sassBundles;
}
function layerTheme(input, themes2, quartoThemesDir) {
  let injectedCustomization = false;
  const loadPaths = [];
  const layers = themes2.flatMap((theme) => {
    const isAbs = isAbsolute4(theme);
    const isScssFile = [".scss", ".css"].includes(extname4(theme));
    if (theme === "brand") {
      return "brand";
    } else if (isAbs && isScssFile) {
      if (existsSync2(theme)) {
        const themeDir = dirname4(theme);
        loadPaths.push(themeDir);
        return sassLayer(theme);
      } else {
        warn(`Theme file not found: ${theme}`);
      }
    } else if (isScssFile) {
      const themePath = join4(dirname4(input), theme);
      if (existsSync2(themePath)) {
        const themeDir = dirname4(themePath);
        loadPaths.push(themeDir);
        return sassLayer(themePath);
      } else {
        warn(`Theme file not found: ${themePath}`);
      }
    } else {
      const resolvedThemePath = join4(quartoThemesDir, `${theme}.scss`);
      if (existsSync2(resolvedThemePath)) {
        const themeLayer2 = sassLayer(resolvedThemePath);
        injectedCustomization = true;
        return [themeLayer2, quartoBootstrapCustomizationLayer()];
      }
    }
    return {
      uses: "",
      defaults: "",
      functions: "",
      mixins: "",
      rules: ""
    };
  });
  if (!injectedCustomization) {
    layers.unshift(quartoBootstrapCustomizationLayer());
  }
  return { layers, loadPaths };
}
function resolveTextHighlightingLayer(input, format14, style) {
  const layer = {
    uses: "",
    defaults: "",
    functions: "",
    mixins: "",
    rules: ""
  };
  const themeDescriptor = readHighlightingTheme(
    dirname4(input),
    format14.pandoc,
    style
  );
  if (format14.metadata[kCodeBlockBackground] === void 0) {
    if (themeDescriptor && !themeDescriptor.isAdaptive) {
      const backgroundColor = () => {
        if (themeDescriptor.json["background-color"]) {
          return themeDescriptor.json["background-color"];
        } else {
          const editorColors = themeDescriptor.json["editor-colors"];
          if (editorColors && editorColors["BackgroundColor"]) {
            return editorColors["BackgroundColor"];
          } else {
            return void 0;
          }
        }
      };
      const background = backgroundColor();
      if (background) {
        layer.defaults = outputVariable(
          sassVariable(
            "code-block-bg",
            asCssColor(background)
          ),
          true
        );
      }
      const textColor = themeDescriptor.json["text-color"];
      if (textColor) {
        layer.defaults = layer.defaults + "\n" + outputVariable(
          sassVariable(
            "code-block-color",
            asCssColor(textColor)
          ),
          true
        );
      }
    }
  }
  if (themeDescriptor) {
    const readTextColor = (name2) => {
      const textStyles = themeDescriptor.json["text-styles"];
      if (textStyles && typeof textStyles === "object") {
        const commentColor2 = textStyles[name2];
        if (commentColor2 && typeof commentColor2 === "object") {
          const textColor = commentColor2["text-color"];
          return textColor;
        } else {
          return void 0;
        }
      } else {
        return void 0;
      }
    };
    const commentColor = readTextColor("Comment");
    if (commentColor) {
      layer.defaults = layer.defaults + "\n" + outputVariable(
        sassVariable(
          "btn-code-copy-color",
          asCssColor(commentColor)
        ),
        true
      );
    }
    const functionColor = readTextColor("Function");
    if (functionColor) {
      layer.defaults = layer.defaults + "\n" + outputVariable(
        sassVariable(
          "btn-code-copy-color-active",
          asCssColor(functionColor)
        ),
        true
      );
    }
  }
  return layer;
}
function resolveThemeLayer(format14, input, themes2, quartoThemesDir, sassLayers) {
  let theme = void 0;
  let defaultDark = false;
  if (typeof themes2 === "string") {
    theme = { light: [themes2] };
  } else if (Array.isArray(themes2)) {
    theme = { light: themes2 };
  } else if (typeof themes2 === "object") {
    const themeArr = (theme2) => {
      const themes3 = [];
      if (theme2) {
        if (typeof theme2 === "string") {
          themes3.push(theme2);
        } else if (Array.isArray(theme2)) {
          themes3.push(...theme2);
        }
      }
      return themes3;
    };
    const themeObj = themes2;
    const keyList = Object.keys(themeObj);
    defaultDark = keyList.length > 1 && keyList[0] === "dark";
    theme = {
      light: themeArr(themeObj.light),
      dark: themeObj.dark ? themeArr(themeObj.dark) : void 0
    };
  } else {
    theme = { light: [] };
  }
  const lightLayerContext = layerTheme(input, theme.light, quartoThemesDir);
  lightLayerContext.layers.unshift(...sassLayers);
  const highlightingLayer = resolveTextHighlightingLayer(
    input,
    format14,
    "light"
  );
  if (highlightingLayer) {
    lightLayerContext.layers.unshift(highlightingLayer);
  }
  const darkLayerContext = theme.dark ? layerTheme(input, theme.dark, quartoThemesDir) : void 0;
  if (darkLayerContext) {
    darkLayerContext.layers.unshift(...sassLayers);
    const darkHighlightingLayer = resolveTextHighlightingLayer(
      input,
      format14,
      "dark"
    );
    if (darkHighlightingLayer) {
      darkLayerContext.layers.unshift(darkHighlightingLayer);
    }
  }
  const themeSassLayer = {
    light: lightLayerContext.layers,
    dark: darkLayerContext?.layers
  };
  const loadPaths = [
    ...lightLayerContext.loadPaths,
    ...darkLayerContext?.loadPaths || []
  ];
  return [themeSassLayer, defaultDark, loadPaths];
}
function pandocVariablesToThemeDefaults(metadata) {
  const explicitVars = [];
  const add = (defaults, name2, value, formatter) => {
    if (value) {
      const sassVar = sassVariable(name2, value, formatter);
      defaults.push(sassVar);
    }
  };
  add(explicitVars, "line-height-base", metadata["linestretch"], asCssNumber);
  add(explicitVars, "font-size-root", metadata["fontsize"]);
  add(explicitVars, "body-bg", metadata["backgroundcolor"]);
  add(explicitVars, "body-color", metadata["fontcolor"]);
  add(explicitVars, "link-color", metadata["linkcolor"]);
  add(explicitVars, "font-family-base", metadata["mainfont"], asCssFont);
  add(explicitVars, "font-family-code", metadata["monofont"], asCssFont);
  add(explicitVars, "mono-background-color", metadata["monobackgroundcolor"]);
  const explicitSizes = [
    "max-width",
    "margin-top",
    "margin-bottom",
    "margin-left",
    "margin-right"
  ];
  explicitSizes.forEach((attrib) => {
    add(explicitVars, attrib, metadata[attrib], asCssSize);
  });
  const gridObj = metadata[kGrid];
  if (gridObj) {
    add(explicitVars, "grid-sidebar-width", gridObj["sidebar-width"]);
    add(explicitVars, "grid-margin-width", gridObj["margin-width"]);
    add(explicitVars, "grid-body-width", gridObj["body-width"]);
    add(explicitVars, "grid-column-gutter-width", gridObj["gutter-width"]);
  }
  return explicitVars;
}
function pandocVariablesToThemeScss(metadata, asDefaults = false) {
  return pandocVariablesToThemeDefaults(metadata).map(
    (variable) => {
      return outputVariable(variable, asDefaults);
    }
  ).join("\n");
}
var kCodeBorderLeft = "code-block-border-left";
var kCodeBlockBackground = "code-block-bg";
var kBackground = "background";
var kForeground = "foreground";
var kTogglePosition = "toggle-position";
var kColor = "color";
var kBorder = "border";
var quartoBootstrapDefaults = (metadata) => {
  const varFilePath = formatResourcePath(
    "html",
    join4("bootstrap", "_bootstrap-variables.scss")
  );
  const variables = [Deno.readTextFileSync(varFilePath)];
  const colorDefaults = [];
  const navbar = metadata[kWebsite]?.[kSiteNavbar];
  if (navbar && typeof navbar === "object") {
    const navbarBackground = navbar[kBackground];
    if (navbarBackground !== void 0) {
      resolveBootstrapColorDefault(navbarBackground, colorDefaults);
      variables.push(
        outputVariable(
          sassVariable(
            "navbar-bg",
            navbarBackground,
            typeof navbarBackground === "string" ? asBootstrapColor : void 0
          )
        )
      );
    }
    const navbarForeground = navbar[kForeground];
    if (navbarForeground !== void 0) {
      resolveBootstrapColorDefault(navbarForeground, colorDefaults);
      variables.push(
        outputVariable(
          sassVariable(
            "navbar-fg",
            navbarForeground,
            typeof navbarForeground === "string" ? asBootstrapColor : void 0
          )
        )
      );
    }
    const navbarTogglePosition = navbar[kTogglePosition];
    if (navbarTogglePosition !== void 0) {
      variables.push(
        outputVariable(
          sassVariable(
            "navbar-toggle-position",
            navbarTogglePosition
          )
        )
      );
    }
  }
  const sidebars = metadata[kWebsite]?.[kSiteSidebar];
  const sidebar = Array.isArray(sidebars) ? sidebars[0] : typeof sidebars === "object" ? sidebars : void 0;
  if (sidebar) {
    const sidebarBackground = sidebar[kBackground];
    if (sidebarBackground !== void 0) {
      resolveBootstrapColorDefault(sidebarBackground, colorDefaults);
      variables.push(
        outputVariable(
          sassVariable(
            "sidebar-bg",
            sidebarBackground,
            typeof sidebarBackground === "string" ? asBootstrapColor : void 0
          )
        )
      );
    } else if (sidebar.style === "floating" || navbar) {
      variables.push(
        `$sidebar-bg: if(variable-exists(body-bg), $body-bg, #fff) !default;`
      );
    }
    const sidebarForeground = sidebar[kForeground];
    if (sidebarForeground !== void 0) {
      resolveBootstrapColorDefault(sidebarForeground, colorDefaults);
      variables.push(
        outputVariable(
          sassVariable(
            "sidebar-fg",
            sidebarForeground,
            typeof sidebarForeground === "string" ? asBootstrapColor : void 0
          )
        )
      );
    }
    const sidebarBorder = sidebar[kBorder];
    variables.push(
      outputVariable(
        sassVariable(
          "sidebar-border",
          sidebarBorder !== void 0 ? sidebarBorder : sidebar.style === "docked"
        )
      )
    );
  } else {
    variables.push(
      `$sidebar-bg: if(variable-exists(body-bg), $body-bg, #fff) !default;`
    );
  }
  const footer = metadata[kWebsite]?.[kPageFooter];
  if (footer !== void 0 && typeof footer === "object") {
    const footerBg = footer[kBackground];
    if (footerBg !== void 0) {
      resolveBootstrapColorDefault(footerBg, colorDefaults);
      variables.push(
        outputVariable(
          sassVariable(
            "footer-bg",
            footerBg,
            typeof footerBg === "string" ? asBootstrapColor : void 0
          )
        )
      );
    }
    const footerFg = footer[kForeground];
    if (footerFg !== void 0) {
      resolveBootstrapColorDefault(footerFg, colorDefaults);
      variables.push(
        outputVariable(
          sassVariable(
            "footer-fg",
            footerFg,
            typeof footerFg === "string" ? asBootstrapColor : void 0
          )
        )
      );
    }
    const footerBorder = footer[kBorder];
    const showBorder = footerBorder !== void 0 ? footerBorder : sidebar?.style === "docked";
    if (showBorder) {
      variables.push(
        outputVariable(
          sassVariable(
            "footer-border",
            true
          )
        )
      );
    }
    if (footerBorder !== void 0 && typeof footerBorder === "string") {
      resolveBootstrapColorDefault(footerBorder, colorDefaults);
      variables.push(
        outputVariable(
          sassVariable(
            "footer-border-color",
            footerBorder,
            asBootstrapColor
          )
        )
      );
    }
    const footerColor = footer[kColor];
    if (footerColor && typeof footerColor === "string") {
      resolveBootstrapColorDefault(footerColor, colorDefaults);
      variables.push(
        outputVariable(
          sassVariable(
            "footer-color",
            footerColor,
            asBootstrapColor
          )
        )
      );
    }
  }
  const codeblockLeftBorder = metadata[kCodeBorderLeft];
  const codeblockBackground = metadata[kCodeBlockBackground];
  if (codeblockLeftBorder !== void 0) {
    resolveBootstrapColorDefault(codeblockLeftBorder, colorDefaults);
    variables.push(
      outputVariable(
        sassVariable(
          kCodeBorderLeft,
          codeblockLeftBorder,
          typeof codeblockLeftBorder === "string" ? asBootstrapColor : void 0
        )
      )
    );
    if (codeblockBackground === void 0 && codeblockLeftBorder !== false) {
      variables.push(outputVariable(sassVariable(kCodeBlockBackground, false)));
    }
  }
  if (codeblockBackground !== void 0) {
    variables.push(outputVariable(sassVariable(
      kCodeBlockBackground,
      codeblockBackground,
      typeof codeblockBackground === "string" ? asBootstrapColor : void 0
    )));
  }
  colorDefaults.forEach((colorDefault) => {
    variables.push(colorDefault);
  });
  return variables.reverse().join("\n");
};
function resolveBootstrapColorDefault(value, variables) {
  if (value) {
    const variable = bootstrapColorDefault(value);
    if (variable && !variables.find((existingVar) => {
      return existingVar === variable;
    })) {
      variables.unshift(variable);
    }
  }
}
function bootstrapColorDefault(value) {
  if (typeof value === "string") {
    return bootstrapColorVars[value];
  }
}
var bootstrapColorVars = {
  primary: "$primary: #0d6efd !default;",
  secondary: "$secondary: #6c757d !default;",
  success: "$success: #198754 !default;",
  info: "$info: #0dcaf0 !default;",
  warning: "$warning: #ffc107 !default;",
  danger: "$danger: #dc3545 !default;",
  light: "$light: #f8f9fa !default;",
  dark: "$dark: #212529 !default;"
};

// format/html/format-html-bootstrap.ts
init_format_html_shared();

// format/html/format-html-appendix.ts
init_constants6();
init_format_html_shared();
var kAppendixCreativeCommonsLic = [
  "CC BY",
  "CC BY-SA",
  "CC BY-ND",
  "CC BY-NC",
  "CC BY-NC-SA",
  "CC BY-NC-ND"
];
var kAppendixCCZero = "CC0";
var kStylePlain = "plain";
var kStyleDefault = "default";
var kAppendixHeadingClass = "quarto-appendix-heading";
var kAppendixContentsClass = "quarto-appendix-contents";
var kQuartoSecondaryLabelClass = "quarto-appendix-secondary-label";
var kQuartoCiteAsClass = "quarto-appendix-citeas";
var kQuartoCiteBibtexClass = "quarto-appendix-bibtex";
var kAppendixId = "quarto-appendix";
async function processDocumentAppendix(input, inputTraits, format14, flags, doc, offset3) {
  if (format14.metadata.book || // It never makes sense to process the appendix when we're in a book
  format14.metadata[kAppendixStyle] === false || format14.metadata[kAppendixStyle] === "none") {
    return;
  }
  const appendixStyle = parseStyle(
    format14.metadata[kAppendixStyle]
  );
  let mainEl = doc.querySelector("main.content");
  if (mainEl === null) {
    mainEl = doc.querySelector("#quarto-content");
  }
  if (mainEl === null) {
    mainEl = doc.querySelector(".page-layout-custom");
  }
  if (mainEl) {
    const appendixEl = doc.createElement("DIV");
    appendixEl.setAttribute("id", kAppendixId);
    if (appendixStyle !== kStylePlain) {
      appendixEl.classList.add(appendixStyle);
    }
    const headingClasses = ["anchored", kAppendixHeadingClass];
    const appendixSections = [];
    const addSection = (fn, title3) => {
      const containerEl = doc.createElement("SECTION");
      containerEl.classList.add(
        kAppendixContentsClass
      );
      fn(containerEl);
      if (title3) {
        insertTitle(
          doc,
          containerEl,
          title3,
          2,
          headingClasses
        );
      }
      appendixSections.push(containerEl);
    };
    if (!hasMarginCites(format14) && !inputTraits[kPositionedRefs]) {
      const refsEl = doc.getElementById("refs");
      if (refsEl) {
        const findRefTitle = (refsEl2) => {
          const parentEl = refsEl2.parentElement;
          if (parentEl && parentEl.tagName === "SECTION" && parentEl.childElementCount === 2) {
            const headingEl = parentEl.querySelector("h1, h2, h3, h4, h5, h6");
            if (headingEl) {
              headingEl.remove();
              return headingEl.innerText;
            }
          }
        };
        const existingTitle = findRefTitle(refsEl);
        addSection((sectionEl) => {
          sectionEl.setAttribute("role", "doc-bibliography");
          sectionEl.id = "quarto-bibliography";
          sectionEl.appendChild(refsEl);
          if (existingTitle) {
            insertTitle(doc, sectionEl, existingTitle, 2, headingClasses);
          } else {
            insertReferencesTitle(
              doc,
              sectionEl,
              format14.language,
              2,
              headingClasses
            );
          }
        });
      }
    }
    if (!hasMarginRefs(format14, flags)) {
      const footnoteEls = doc.querySelectorAll('section[role="doc-endnotes"]');
      if (footnoteEls && footnoteEls.length === 1) {
        const footnotesEl = footnoteEls.item(0);
        footnotesEl.tagName = "SECTION";
        insertFootnotesTitle(
          doc,
          footnotesEl,
          format14.language,
          2,
          headingClasses
        );
        appendixSections.push(footnotesEl);
      }
    }
    if (format14.metadata[kLicense]) {
      addSection((sectionEl) => {
        const contentsDiv = doc.createElement("DIV");
        sectionEl.id = "quarto-reuse";
        contentsDiv.classList.add(
          kAppendixContentsClass
        );
        const normalizedLicense = (license2) => {
          if (typeof license2 === "string") {
            const creativeCommons = creativeCommonsLicense(license2);
            if (creativeCommons) {
              const licenseUrlInfo = creativeCommonsUrl(
                creativeCommons.base,
                format14.metadata[kLang],
                creativeCommons.version
              );
              return licenseUrlInfo;
            } else {
              return { text: license2 };
            }
          } else {
            const licenseObj = license2;
            return {
              text: licenseObj.text,
              url: licenseObj.url,
              type: licenseObj.type,
              inlineLink: false
            };
          }
        };
        const normalizedLicenses = (licenses) => {
          if (Array.isArray(licenses)) {
            return licenses.map((license2) => {
              return normalizedLicense(license2);
            });
          } else {
            return [normalizedLicense(licenses)];
          }
        };
        const license = format14.metadata[kLicense];
        const normalized = normalizedLicenses(license);
        for (const normalLicense of normalized) {
          const licenseEl = doc.createElement("DIV");
          if (normalLicense.url && normalLicense.inlineLink) {
            const linkEl = doc.createElement("A");
            linkEl.innerText = normalLicense.text;
            linkEl.setAttribute("rel", "license");
            linkEl.setAttribute("href", normalLicense.url);
            licenseEl.appendChild(linkEl);
          } else {
            licenseEl.innerText = normalLicense.text;
            if (normalLicense.url) {
              const linkEl = doc.createElement("A");
              linkEl.innerText = `(${format14.language[kAppendixViewLicense] || "View License"})`;
              linkEl.setAttribute("rel", "license");
              linkEl.setAttribute("href", normalLicense.url);
              licenseEl.appendChild(linkEl);
            }
          }
          contentsDiv.appendChild(licenseEl);
        }
        sectionEl.appendChild(contentsDiv);
      }, format14.language[kSectionTitleReuse] || "Reuse");
    }
    if (format14.metadata[kCopyright]) {
      const normalizedCopyright = (copyright2) => {
        if (typeof copyright2 === "string") {
          return copyright2;
        } else if (copyright2) {
          return copyright2.statement;
        }
      };
      const copyrightRaw = format14.metadata[kCopyright];
      const copyright = normalizedCopyright(copyrightRaw);
      if (copyright) {
        addSection((sectionEl) => {
          const contentsDiv = doc.createElement("DIV");
          sectionEl.id = "quarto-copyright";
          contentsDiv.classList.add(
            kAppendixContentsClass
          );
          const licenseEl = doc.createElement("DIV");
          licenseEl.innerText = copyright;
          contentsDiv.appendChild(licenseEl);
          sectionEl.appendChild(contentsDiv);
        }, format14.language[kSectionTitleCopyright] || "Copyright");
      }
    }
    if (format14.metadata[kCitation]) {
      const cite = await generateCite(input, format14, offset3);
      if (cite?.bibtex || cite?.html) {
        addSection((sectionEl) => {
          const contentsDiv = doc.createElement("DIV");
          sectionEl.appendChild(contentsDiv);
          sectionEl.id = "quarto-citation";
          if (cite?.bibtex) {
            const bibTexLabelEl = doc.createElement("DIV");
            bibTexLabelEl.classList.add(kQuartoSecondaryLabelClass);
            bibTexLabelEl.innerText = format14.language[kAppendixAttributionBibTex] || "BibLaTeX citation";
            contentsDiv.appendChild(bibTexLabelEl);
            const bibTexDiv = createCodeBlock(doc, cite.bibtex, "bibtex");
            bibTexDiv.classList.add(kQuartoCiteBibtexClass);
            contentsDiv.appendChild(bibTexDiv);
            const copyButton = createCodeCopyButton(doc, format14);
            bibTexDiv.appendChild(copyButton);
          }
          if (cite?.html) {
            const citeLabelEl = doc.createElement("DIV");
            citeLabelEl.classList.add(kQuartoSecondaryLabelClass);
            citeLabelEl.innerText = format14.language[kAppendixAttributionCiteAs] || "For attribution, please cite this work as:";
            contentsDiv.appendChild(citeLabelEl);
            const entry = extractCiteEl(cite.html, doc);
            if (entry) {
              entry.classList.add(kQuartoCiteAsClass);
              contentsDiv.appendChild(entry);
            }
          }
        }, format14.language[kSectionTitleCitation] || "Citation");
      }
    }
    const appendixSectionNodes = doc.querySelectorAll("section.appendix");
    const appendixSectionEls = [];
    for (const appendixSectionNode of appendixSectionNodes) {
      const appendSectionEl = appendixSectionNode;
      if (appendSectionEl) {
        if (appendSectionEl.id) {
          const selector = `#TOC a[href="#${appendSectionEl.id}"]`;
          const tocEl = doc.querySelector(selector);
          if (tocEl && tocEl.parentElement) {
            tocEl.parentElement.remove();
          }
        }
        const extractHeaderEl = () => {
          const headerEl2 = appendSectionEl.querySelector(
            "h1, h2, h3, h4, h5, h6"
          );
          if (headerEl2) {
            headerEl2.remove();
            const h22 = doc.createElement("h2");
            h22.innerHTML = headerEl2.innerHTML;
            if (appendSectionEl.id) {
              h22.classList.add("anchored");
            }
            return h22;
          } else {
            const h22 = doc.createElement("h2");
            return h22;
          }
        };
        const headerEl = extractHeaderEl();
        headerEl.classList.add(kAppendixHeadingClass);
        const containerDivEl = doc.createElement("DIV");
        containerDivEl.classList.add(
          kAppendixContentsClass
        );
        while (appendSectionEl.childNodes.length > 0) {
          containerDivEl.appendChild(appendSectionEl.childNodes[0]);
        }
        appendSectionEl.appendChild(headerEl);
        appendSectionEl.appendChild(containerDivEl);
        appendixSectionEls.push(appendSectionEl);
      }
    }
    if (appendixSectionEls.length > 0) {
      appendixSections.unshift(...appendixSectionEls);
    }
    appendixSections.forEach((el) => {
      appendixEl.appendChild(el);
    });
    if (appendixEl.childElementCount > 0) {
      mainEl.appendChild(appendixEl);
    }
  }
}
var kCiteAsStyleBibtex = "bibtex";
var kCiteAsStyleDisplay = "display";
function citeStyleTester(format14) {
  const citeStyle = format14.metadata[kAppendixCiteAs];
  const resolvedStyles = [];
  if (citeStyle === void 0 || citeStyle === true) {
    resolvedStyles.push(...[kCiteAsStyleDisplay, kCiteAsStyleBibtex]);
  } else {
    if (Array.isArray(citeStyle)) {
      resolvedStyles.push(...citeStyle);
    } else {
      resolvedStyles.push(citeStyle);
    }
  }
  return {
    hasCiteAs: () => {
      return resolvedStyles.length > 0;
    },
    hasCiteAsStyle: (style) => {
      return resolvedStyles.includes(style);
    }
  };
}
function parseStyle(style) {
  switch (style) {
    case "plain":
      return "plain";
    default:
      return kStyleDefault;
  }
}
var kCcPattern = /(CC BY[^\s]*)\s*(\S*)/;
function creativeCommonsLicense(license) {
  if (license) {
    const match = license.toUpperCase().match(kCcPattern);
    if (match) {
      const base3 = match[1];
      const version4 = match[2];
      if (kAppendixCreativeCommonsLic.includes(base3)) {
        return {
          base: base3,
          version: version4 || "4.0"
        };
      }
    } else if (license === kAppendixCCZero) {
      return {
        base: kAppendixCCZero,
        version: "1.0"
      };
    } else {
      return void 0;
    }
  } else {
    return void 0;
  }
}
function creativeCommonsUrl(license, lang, version4) {
  if (license === kAppendixCCZero) {
    return {
      url: `https://creativecommons.org/publicdomain/zero/${version4}/`,
      text: `CC0 ${version4}`,
      inlineLink: true
    };
  }
  const licenseType = license.substring(3);
  if (lang && lang !== "en") {
    return {
      url: `https://creativecommons.org/licenses/${licenseType.toLowerCase()}/${version4}/deed.${lang.toLowerCase().replace("-", "_")}`,
      text: `CC ${licenseType} ${version4}`,
      inlineLink: true
    };
  } else {
    return {
      url: `https://creativecommons.org/licenses/${licenseType.toLowerCase()}/${version4}/`,
      text: `CC ${licenseType} ${version4}`,
      inlineLink: true
    };
  }
}
async function generateCite(input, format14, offset3) {
  const citeStyle = citeStyleTester(format14);
  if (citeStyle.hasCiteAs()) {
    const { csl } = documentCSL(
      input,
      format14.metadata,
      "webpage",
      format14.pandoc["output-file"],
      offset3
    );
    if (csl) {
      const cslPath = getCSLPath(input, format14);
      return {
        html: citeStyle.hasCiteAsStyle(kCiteAsStyleDisplay) ? await renderHtml(csl, cslPath) : void 0,
        bibtex: citeStyle.hasCiteAsStyle(kCiteAsStyleBibtex) ? await renderBibTex(csl) : void 0
      };
    } else {
      return void 0;
    }
  } else {
    return {};
  }
}
function extractCiteEl(html, doc) {
  const htmlDiv = doc.createElement("DIV");
  htmlDiv.innerHTML = html;
  const entry = htmlDiv.querySelector(".csl-entry");
  if (entry) {
    const leftMarginEl = entry.querySelector(".csl-left-margin");
    if (leftMarginEl) {
      leftMarginEl.remove();
      const rightEl = entry.querySelector(".csl-right-inline");
      if (rightEl) {
        rightEl.classList.remove("csl-right-inline");
      }
    }
    return entry;
  } else {
    return void 0;
  }
}

// format/html/format-html-bootstrap.ts
init_format_html_info();
init_template();
init_format5();

// format/html/format-html-notebook.ts
init_lodash();
init_constants6();
init_path();

// format/html/format-html-notebook-preview.ts
init_array();
init_lodash();
init_constants6();
init_path();
init_path2();
await init_project_shared();
init_notebook_types();
init_notebook_types();
init_error2();
init_log2();
var notebookPreviewer = (nbView, format14, services, project) => {
  const isBook = projectIsBook(project);
  const previewQueue = [];
  const outputDir = project?.config?.project["output-dir"];
  const nbDescriptors = {};
  if (nbView) {
    if (typeof nbView !== "boolean") {
      asArray(nbView).forEach((view) => {
        const existingView = nbDescriptors[view.notebook];
        nbDescriptors[view.notebook] = {
          ...existingView,
          ...view
        };
      });
    }
  }
  const descriptor = (notebook) => {
    return nbDescriptors[notebook];
  };
  const enQueuePreview = (input, nbAbsPath2, title3, order, callback) => {
    if (!previewQueue.find((work) => {
      return work.nbPath === nbAbsPath2;
    })) {
      previewQueue.push({
        input,
        nbPath: nbAbsPath2,
        title: title3,
        callback,
        order
      });
    }
  };
  const renderPreviews = async (output, quiet) => {
    const rendered = {};
    const nbOptions = format14.metadata[kNotebookPreviewOptions];
    const notebookPaths = previewQueue.map((work) => work.nbPath);
    const uniquePaths = uniq(notebookPaths);
    const toRenderPaths = uniquePaths.filter((nbPath) => {
      return services.notebook.get(nbPath, project) === void 0;
    });
    const haveRenderedPaths = [];
    if (toRenderPaths.length > 0 && !quiet) {
      logProgress(
        `Rendering notebook previews`
      );
    }
    const total = previewQueue.length;
    let renderCount = 0;
    for (let i6 = 0; i6 < total; i6++) {
      const work = previewQueue[i6];
      const { nbPath, input, title: title3 } = work;
      if (toRenderPaths.includes(nbPath) && !haveRenderedPaths.includes(nbPath) && !quiet) {
        logProgress(
          `[${++renderCount}/${toRenderPaths.length}] ${basename4(nbPath)}`
        );
        haveRenderedPaths.push(nbPath);
      }
      const nbDir = dirname4(nbPath);
      const filename = basename4(nbPath);
      const inputDir = dirname4(input);
      if (nbView !== false) {
        const descriptor2 = nbDescriptors[relative4(dirname4(input), nbPath)];
        const nbAbsPath2 = isAbsolute4(nbPath) ? nbPath : join4(inputDir, nbPath);
        const nbContext = services.notebook;
        const notebook = nbContext.get(nbAbsPath2, project);
        const resolvedTitle = descriptor2?.title || title3 || notebook?.metadata?.title || basename4(nbAbsPath2);
        const notebookIsQmd = !nbAbsPath2.endsWith(".ipynb");
        if (!notebook || !notebook[kHtmlPreview] || !notebook[kRenderedIPynb]) {
          if ((!notebook || !notebook[kRenderedIPynb]) && !descriptor2?.[kDownloadUrl] && !isBook && !notebookIsQmd) {
            const renderedIpynb = await nbContext.render(
              nbAbsPath2,
              format14,
              kRenderedIPynb,
              services,
              {
                title: resolvedTitle,
                filename: basename4(nbAbsPath2)
              },
              project
            );
            if (renderedIpynb && (!project || !outputDir)) {
              nbContext.preserve(nbAbsPath2, kRenderedIPynb);
            }
          }
          if (!notebook || !notebook[kHtmlPreview]) {
            const backHref = nbOptions && nbOptions.back && output ? relative4(dirname4(nbAbsPath2), output) : void 0;
            let downloadHref = basename4(nbAbsPath2);
            let downloadFileName = basename4(nbAbsPath2);
            if (notebook && notebook[kRenderedIPynb] && !notebookIsQmd) {
              downloadHref = relative4(
                dirname4(nbAbsPath2),
                notebook[kRenderedIPynb].hrefPath
              );
              downloadFileName = basename4(notebook[kRenderedIPynb].hrefPath);
            }
            const htmlPreview = await nbContext.render(
              nbAbsPath2,
              format14,
              kHtmlPreview,
              services,
              {
                title: resolvedTitle,
                filename: basename4(nbAbsPath2),
                backHref,
                downloadHref,
                downloadFile: downloadFileName
              },
              project
            );
            if (htmlPreview && (!project || !outputDir)) {
              nbContext.preserve(nbAbsPath2, kHtmlPreview);
            }
          }
        }
        const renderedNotebook = nbContext.get(nbAbsPath2, project);
        if (!renderedNotebook || !renderedNotebook[kHtmlPreview]) {
          throw new InternalError(
            "We just ensured that notebooks had rendered previews, but the preview then didn't exist."
          );
        }
        const supporting = [];
        const resources = [];
        if (renderedNotebook[kRenderedIPynb]) {
          const renderedIpynb = renderedNotebook[kRenderedIPynb];
          if (renderedIpynb) {
            if (project) {
              supporting.push(
                relative4(project.dir, renderedIpynb.hrefPath)
              );
            } else {
              supporting.push(renderedIpynb.hrefPath);
            }
            supporting.push(...renderedIpynb.supporting);
            resources.push(...renderedIpynb.resourceFiles.files);
          }
        }
        if (renderedNotebook[kHtmlPreview]) {
          const htmlPreview = renderedNotebook[kHtmlPreview];
          if (htmlPreview) {
            if (project) {
              supporting.push(relative4(project.dir, htmlPreview.hrefPath));
            } else {
              supporting.push(htmlPreview.hrefPath);
            }
            supporting.push(...htmlPreview.supporting);
            resources.push(...htmlPreview.resourceFiles.files);
          }
        }
        const nbPreview = {
          title: resolvedTitle,
          href: descriptor2?.url || relative4(inputDir, renderedNotebook[kHtmlPreview].hrefPath),
          supporting,
          resources,
          order: work.order
        };
        rendered[work.nbPath] = nbPreview;
        if (work.callback) {
          work.callback(nbPreview);
        }
      } else {
        const nbPreview = {
          href: pathWithForwardSlashes(join4(nbDir, filename)),
          title: title3 || filename,
          filename,
          order: work.order
        };
        rendered[work.nbPath] = nbPreview;
        if (work.callback) {
          work.callback(nbPreview);
        }
      }
    }
    return rendered;
  };
  return {
    enQueuePreview,
    renderPreviews,
    descriptor
  };
};

// format/html/format-html-notebook.ts
await init_project_shared();
var kQuartoNbClass = "quarto-notebook";
var kQuartoCellContainerClass = "cell-container";
var kQuartoCellDecoratorClass = "cell-decorator";
function notebookViewPostProcessor() {
  return (doc) => {
    doc.body.classList.add(kQuartoNbClass);
    const cells = doc.querySelectorAll("div.cell");
    let cellCount = 0;
    for (const cell of cells) {
      const cellEl = cell;
      const count = cellEl.getAttribute("data-execution_count") || ++cellCount;
      const isMarkdown2 = cellEl.classList.contains("markdown");
      const hasCodeFolding = cellEl.querySelector("details.code-fold") !== null;
      if (!isMarkdown2) {
        const containerNode = doc.createElement("div");
        containerNode.classList.add(kQuartoCellContainerClass);
        containerNode.classList.add("column-page-left");
        if (hasCodeFolding) {
          containerNode.classList.add("code-fold");
        }
        const decoratorNode = doc.createElement("div");
        decoratorNode.classList.add(kQuartoCellDecoratorClass);
        const contentsEl = doc.createElement("pre");
        contentsEl.appendChild(doc.createTextNode(`In [${count}]:`));
        decoratorNode.appendChild(contentsEl);
        containerNode.appendChild(decoratorNode);
        const prevSibling = cellEl.previousElementSibling;
        if (prevSibling && prevSibling.tagName === "DIV" && prevSibling.classList.contains("cell-code")) {
          cell.parentElement?.insertBefore(containerNode, cell);
          const wrapperDiv = doc.createElement("div");
          containerNode.appendChild(wrapperDiv);
          wrapperDiv.appendChild(prevSibling.cloneNode(true));
          prevSibling.remove();
          wrapperDiv.appendChild(cell);
        } else {
          cell.parentElement?.insertBefore(containerNode, cell);
          containerNode.appendChild(cell);
        }
      }
    }
    const resources = [];
    const supporting = [];
    return Promise.resolve({
      resources,
      supporting
    });
  };
}
async function emplaceNotebookPreviews(input, doc, format14, services, project, output, quiet) {
  const notebookView = format14.render[kNotebookView] ?? true;
  const notebookViewStyle = format14.render[kNotebookViewStyle];
  if (notebookViewStyle === "notebook") {
    return { resources: [], supporting: [] };
  }
  const isBook = projectIsBook(project);
  if (notebookView !== false && !isBook) {
    const inline = format14.render[kNotebookLinks] === "inline" || format14.render[kNotebookLinks] === true;
    const global2 = format14.render[kNotebookLinks] === "global" || format14.render[kNotebookLinks] === true;
    const addInlineLineNotebookLink = inlineLinkGenerator(doc, format14);
    const previewer = notebookPreviewer(
      notebookView,
      format14,
      services,
      project
    );
    const inputNbName = basename4(input);
    if (previewer.descriptor(inputNbName)) {
      const computationalNodes = doc.querySelectorAll("div.cell");
      for (const computationalNode of computationalNodes) {
        const computeEl = computationalNode;
        const cellId = computeEl.getAttribute("id");
        previewer.enQueuePreview(
          input,
          input,
          void 0,
          // title
          void 0,
          // order
          (nbPreview) => {
            if (inline) {
              if (!computeEl.parentElement?.classList.contains(
                "quarto-embed-nb-cell"
              )) {
                addInlineLineNotebookLink(
                  computeEl,
                  nbPreview,
                  cellId
                );
              }
            }
          }
        );
      }
    }
    if (typeof notebookView !== "boolean") {
      const nbs = Array.isArray(notebookView) ? notebookView : [notebookView];
      for (const nb of nbs) {
        if (nb.url === void 0 && inputNbName !== nb.notebook) {
          const nbAbsPath2 = isAbsolute4(nb.notebook) ? nb.notebook : join4(dirname4(input), nb.notebook);
          previewer.enQueuePreview(input, nbAbsPath2, nb.title, nb.order);
        }
      }
    }
    const notebookDivNodes = doc.querySelectorAll("[data-notebook]");
    for (const nbDivNode of notebookDivNodes) {
      const nbDivEl = nbDivNode;
      const notebookPath = nbDivEl.getAttribute("data-notebook");
      nbDivEl.removeAttribute("data-notebook");
      const notebookCellId = nbDivEl.getAttribute("data-notebook-cellId");
      nbDivEl.removeAttribute("data-notebook-cellId");
      const title3 = nbDivEl.getAttribute("data-notebook-title");
      nbDivEl.removeAttribute("data-notebook-title");
      if (notebookPath) {
        previewer.enQueuePreview(
          input,
          nbAbsPath(input, notebookPath),
          title3 === null ? void 0 : title3,
          void 0,
          // order
          (nbPreview) => {
            if (inline) {
              addInlineLineNotebookLink(nbDivEl, nbPreview, notebookCellId);
            }
          }
        );
      }
    }
    const previews = await previewer.renderPreviews(output, quiet);
    const previewNotebooks = Object.values(previews).sort((a5, b3) => {
      if (a5.order !== void 0 && b3.order !== void 0) {
        return a5.order - b3.order;
      } else if (a5.order !== void 0 && b3.order === void 0) {
        return -1;
      } else if (a5.order === void 0 && b3.order !== void 0) {
        return 1;
      } else {
        return a5.title.localeCompare(b3.title);
      }
    });
    if (global2 && previewNotebooks.length > 0) {
      const containerEl = doc.createElement("div");
      containerEl.classList.add("quarto-alternate-notebooks");
      const heading = doc.createElement("h2");
      if (format14.language[kRelatedNotebooksTitle]) {
        heading.innerText = format14.language[kRelatedNotebooksTitle];
      }
      containerEl.appendChild(heading);
      const formatList = doc.createElement("ul");
      containerEl.appendChild(formatList);
      uniqBy(
        previewNotebooks,
        (nbPath) => {
          return nbPath.href;
        }
      ).forEach((nbPath) => {
        const li = doc.createElement("li");
        const link2 = doc.createElement("a");
        link2.setAttribute("href", nbPath.href);
        if (nbPath.filename) {
          link2.setAttribute("download", nbPath.filename);
        }
        const icon = doc.createElement("i");
        icon.classList.add("bi");
        icon.classList.add(`bi-journal-code`);
        link2.appendChild(icon);
        link2.appendChild(
          doc.createTextNode(nbPath.title)
        );
        li.appendChild(link2);
        formatList.appendChild(li);
      });
      let dlLinkTarget = doc.querySelector(`nav[role="doc-toc"]`);
      if (dlLinkTarget === null) {
        dlLinkTarget = doc.querySelector("#quarto-margin-sidebar");
      }
      if (dlLinkTarget) {
        dlLinkTarget.appendChild(containerEl);
      }
    }
    const supporting = [];
    const resources = [];
    for (const notebookPath of Object.keys(previews)) {
      const nbPath = previews[notebookPath];
      if (nbPath.supporting) {
        supporting.push(...nbPath.supporting);
      }
      if (nbPath.resources) {
        resources.push(...nbPath.resources.map((file) => {
          return project ? relative4(project?.dir, file) : file;
        }));
      }
      resources.push(notebookPath);
    }
    return {
      resources,
      supporting
    };
  }
}
var nbAbsPath = (input, nbPath) => {
  if (isAbsolute4(nbPath)) {
    return nbPath;
  }
  const inputAbsPath = isAbsolute4(input) ? input : join4(Deno.cwd(), input);
  return join4(dirname4(inputAbsPath), nbPath);
};
var inlineLinkGenerator = (doc, format14) => {
  let count = 1;
  return (nbDivEl, nbPreview, cellId) => {
    const id = "nblink-" + count++;
    const nbLinkEl = doc.createElement("a");
    nbLinkEl.classList.add("quarto-notebook-link");
    nbLinkEl.setAttribute("id", `${id}`);
    if (nbPreview.filename) {
      nbLinkEl.setAttribute("download", nbPreview.filename);
      nbLinkEl.setAttribute("href", nbPreview.href);
    } else {
      if (cellId) {
        nbLinkEl.setAttribute(
          "href",
          `${nbPreview.href}#${cellId}`
        );
      } else {
        nbLinkEl.setAttribute("href", `${nbPreview.href}`);
      }
    }
    nbLinkEl.appendChild(
      doc.createTextNode(
        `${format14.language[kSourceNotebookPrefix]}: ${nbPreview.title}`
      )
    );
    const nbParentEl = nbDivEl.parentElement;
    if (nbParentEl?.tagName.toLocaleLowerCase() === "figure") {
      const figCapEl = nbDivEl.parentElement?.querySelector("figcaption");
      if (figCapEl) {
        figCapEl.after(nbLinkEl);
      } else {
        nbDivEl.appendChild(nbLinkEl);
      }
    } else {
      nbDivEl.appendChild(nbLinkEl);
    }
  };
};

// format/html/format-html-links.ts
init_path();
init_constants6();
init_format5();
function otherFormatLinks(input, format14, renderedFormats) {
  const normalizedFormatLinks = (unnormalizedLinks) => {
    if (typeof unnormalizedLinks === "boolean") {
      return void 0;
    } else if (unnormalizedLinks !== void 0) {
      const linksArr = Array.isArray(unnormalizedLinks) ? unnormalizedLinks : [unnormalizedLinks];
      return linksArr;
    } else {
      return void 0;
    }
  };
  const userLinks = normalizedFormatLinks(format14.render[kFormatLinks]);
  const filteredFormats = renderedFormats.filter(
    (renderedFormat) => {
      return !isHtmlOutput(renderedFormat.format.pandoc, true);
    }
  );
  return alternateLinks(
    input,
    filteredFormats,
    userLinks
  );
}
function alternateLinks(input, formats2, userLinks) {
  const alternateLinks2 = [];
  const alternateLinkForFormat = (renderedFormat, order, title3, icon) => {
    const relPath = isAbsolute4(renderedFormat.path) ? relative4(dirname4(input), renderedFormat.path) : renderedFormat.path;
    return {
      title: `${title3 || renderedFormat.format.identifier[kDisplayName] || renderedFormat.format.pandoc.to}${renderedFormat.format.identifier[kExtensionName] ? ` (${renderedFormat.format.identifier[kExtensionName]})` : ""}`,
      href: relPath,
      icon: icon || fileBsIconName(renderedFormat.format),
      order,
      dlAttrValue: fileDownloadAttr(
        renderedFormat.format,
        renderedFormat.path
      )
    };
  };
  let count = 1;
  for (const userLink of userLinks || []) {
    if (typeof userLink === "string") {
      const renderedFormat = formats2.find(
        (f5) => f5.format.identifier[kTargetFormat] === userLink
      );
      if (renderedFormat) {
        alternateLinks2.push(alternateLinkForFormat(renderedFormat, count));
      }
    } else {
      const linkObj = userLink;
      if ("format" in linkObj) {
        const thatLink = userLink;
        const rf = formats2.find(
          (f5) => f5.format.identifier[kTargetFormat] === thatLink.format
        );
        if (rf) {
          alternateLinks2.push(
            alternateLinkForFormat(rf, count, thatLink.text, thatLink.icon)
          );
        }
      } else {
        const thisLink = userLink;
        const alternate = {
          title: thisLink.text,
          href: thisLink.href,
          icon: thisLink.icon || fileBsIconForExt(thisLink.href),
          dlAttrValue: "",
          order: thisLink.order || count,
          attr: thisLink.attr
        };
        alternateLinks2.push(alternate);
      }
    }
    count++;
  }
  const userLinksHasFormat = userLinks && userLinks.some((link2) => typeof link2 === "string");
  if (!userLinksHasFormat) {
    formats2.forEach((renderedFormat) => {
      const baseFormat = renderedFormat.format.identifier["base-format"];
      if (!kExcludeFormatUnlessExplicit.includes(baseFormat || "html")) {
        alternateLinks2.push(alternateLinkForFormat(renderedFormat, count));
      }
      count++;
    });
  }
  return alternateLinks2;
}
var fileBsIconName = (format14) => {
  if (isDocxOutput(format14.pandoc)) {
    return "file-word";
  } else if (isPdfOutput(format14.pandoc)) {
    return "file-pdf";
  } else if (isTypstOutput(format14.pandoc)) {
    return "file-pdf";
  } else if (isIpynbOutput(format14.pandoc)) {
    return "journal-code";
  } else if (isMarkdownOutput(format14)) {
    return "file-code";
  } else if (isPresentationOutput(format14.pandoc)) {
    return "file-slides";
  } else if (isJatsOutput(format14.pandoc)) {
    return "filetype-xml";
  } else {
    return "file";
  }
};
var fileDownloadAttr = (format14, path3) => {
  if (isIpynbOutput(format14.pandoc)) {
    return basename4(path3);
  } else if (isJatsOutput(format14.pandoc)) {
    return basename4(path3);
  } else {
    return void 0;
  }
};
var fileBsIconForExt = (path3) => {
  const ext = extname4(path3);
  switch (ext.toLowerCase()) {
    case ".docx":
      return "file-word";
    case ".pdf":
      return "file-pdf";
    case ".ipynb":
      return "journal-code";
    case ".md":
      return "file-code";
    case ".xml":
      return "filetype-xml";
    default:
      return "file";
  }
};
var kExcludeFormatUnlessExplicit = ["jats"];

// format/html/format-html-bootstrap.ts
init_log();
function bootstrapFormatDependency() {
  const boostrapResource = (resource) => formatResourcePath(
    "html",
    join4("bootstrap", "dist", resource)
  );
  const bootstrapDependency = (resource) => ({
    name: resource,
    path: boostrapResource(resource)
  });
  return {
    name: kBootstrapDependencyName,
    stylesheets: [
      bootstrapDependency("bootstrap-icons.css")
    ],
    scripts: [
      bootstrapDependency("bootstrap.min.js")
    ],
    resources: [
      bootstrapDependency("bootstrap-icons.woff")
    ]
  };
}
function bootstrapExtras(input, flags, format14, services, offset3, project, quiet) {
  const toc = hasTableOfContents(flags, format14);
  const tocLocation = toc ? format14.metadata[kTocLocation] || "right" : void 0;
  const renderTemplate = (template2, pageLayout2) => {
    return renderEjs(formatResourcePath("html", `templates/${template2}`), {
      toc,
      tocLocation,
      pageLayout: pageLayout2
    });
  };
  const pageLayout = formatPageLayout(format14);
  const bodyEnvelope = formatHasArticleLayout(format14) ? {
    before: renderTemplate("before-body-article.ejs", pageLayout),
    afterPreamble: renderTemplate(
      "after-body-article-preamble.ejs",
      pageLayout
    ),
    afterPostamble: renderTemplate(
      "after-body-article-postamble.ejs",
      pageLayout
    )
  } : {
    before: renderTemplate("before-body-custom.ejs", kPageLayoutCustom),
    afterPreamble: renderTemplate(
      "after-body-custom-preamble.ejs",
      kPageLayoutCustom
    ),
    afterPostamble: renderTemplate(
      "after-body-custom-postamble.ejs",
      kPageLayoutCustom
    )
  };
  const { partials, templateParams } = documentTitlePartial(
    format14
  );
  const sassLayers = [];
  const titleSassLayer = documentTitleScssLayer(format14);
  if (titleSassLayer) {
    sassLayers.push(titleSassLayer);
  }
  const includeInHeader = [];
  const titleInclude = documentTitleIncludeInHeader(
    input,
    format14,
    services.temp
  );
  if (titleInclude) {
    includeInHeader.push(titleInclude);
  }
  const titleMetadata = documentTitleMetadata(format14);
  const scssBundles = resolveBootstrapScss(input, format14, sassLayers);
  return {
    pandoc: {
      [kSectionDivs]: true,
      [kHtmlMathMethod]: "mathjax"
    },
    metadata: {
      [kDocumentCss]: false,
      [kLinkCitations]: true,
      [kTemplatePartials]: partials,
      [kQuartoTemplateParams]: templateParams,
      ...titleMetadata
    },
    [kIncludeInHeader]: includeInHeader,
    html: {
      [kSassBundles]: scssBundles,
      [kDependencies]: [bootstrapFormatDependency()],
      [kBodyEnvelope]: bodyEnvelope,
      [kHtmlPostprocessors]: [
        bootstrapHtmlPostprocessor(
          input,
          format14,
          flags,
          services,
          offset3,
          project,
          quiet
        )
      ],
      [kHtmlFinalizers]: [
        bootstrapHtmlFinalizer(format14, flags)
      ]
    }
  };
}
var getColumnLayoutElements = (doc) => {
  return doc.querySelectorAll(kColumnSelector);
};
var removeColumnClasses = (el) => {
  for (const cls of allColumnClz) {
    el.classList.remove(cls);
  }
};
var removeNestedColumnLayouts = (doc) => {
  const columnNodes = doc.querySelectorAll(kColumnSelector);
  columnNodes.forEach((columnNode) => {
    const columnEl = columnNode;
    if (isInColumnLayout(columnEl, doc, nonScreenColumnClz)) {
      removeColumnClasses(columnEl);
    }
  });
};
var cleanNonsensicalMarginCaps = (doc) => {
  const marginCapNodes = doc.querySelectorAll(".margin-caption,.margin-ref");
  marginCapNodes.forEach((capNode) => {
    const capEl = capNode;
    if (isInColumnLayout(capEl, doc, removeMarginClz)) {
      capEl.classList.remove("margin-caption");
      capEl.classList.remove("margin-ref");
    }
  });
};
var isInColumnLayout = (el, doc, clzList) => {
  const parent = el.parentElement;
  if (!parent) {
    return false;
  }
  for (const cls of parent.classList) {
    if (clzList.includes(cls)) {
      return true;
    }
  }
  return isInColumnLayout(parent, doc, clzList);
};
var kColumnSelector = '[class^="column-"], [class*=" column-"], aside:not(.footnotes):not(.sidebar), [class*="margin-caption"], [class*=" margin-caption"], [class*="margin-ref"], [class*=" margin-ref"]';
function bootstrapHtmlPostprocessor(input, format14, flags, services, offset3, project, quiet) {
  return async (doc, options) => {
    const resources = [];
    const supporting = [];
    const title3 = doc.querySelector("header > .title");
    if (title3) {
      title3.classList.add("display-7");
    }
    const subtitle = doc.querySelector("header > .subtitle");
    if (subtitle) {
      subtitle.classList.add("lead");
    }
    const blockquotes = doc.querySelectorAll("blockquote");
    for (let i6 = 0; i6 < blockquotes.length; i6++) {
      const classList = blockquotes[i6].classList;
      classList.add("blockquote");
    }
    const figures = doc.querySelectorAll("figure");
    for (let i6 = 0; i6 < figures.length; i6++) {
      const figure = figures[i6];
      figure.classList.add("figure");
      const images = figure.querySelectorAll("img");
      for (let j3 = 0; j3 < images.length; j3++) {
        images[j3].classList.add("figure-img");
      }
    }
    const marginImgNodes = doc.querySelectorAll(
      ".column-margin .cell-output-display img:not(.img-fluid)"
    );
    for (const marginImgNode of marginImgNodes) {
      const marginImgEl = marginImgNode;
      marginImgEl.classList.add("img-fluid");
    }
    const toc = doc.querySelector('nav[role="doc-toc"]');
    const tocTarget = doc.getElementById("quarto-toc-target");
    const useDoubleToc = format14.metadata[kTocLocation]?.includes("-body") ?? false;
    if (toc && tocTarget) {
      if (useDoubleToc) {
        const clonedToc = toc.cloneNode(true);
        clonedToc.id = "TOC-body";
        const tocActionsEl = clonedToc.querySelector(".toc-actions");
        if (tocActionsEl) {
          tocActionsEl.remove();
        }
        toc.parentElement?.insertBefore(clonedToc, toc);
      }
      toc.classList.add("toc-active");
      const expanded = format14.metadata[kTocExpand];
      if (expanded !== void 0) {
        if (expanded === true) {
          toc.setAttribute("data-toc-expanded", 99);
        } else if (expanded) {
          toc.setAttribute("data-toc-expanded", expanded);
        } else {
          toc.setAttribute("data-toc-expanded", -1);
        }
      }
      const tocLinks = doc.querySelectorAll('nav#TOC[role="doc-toc"] > ul a');
      for (let i6 = 0; i6 < tocLinks.length; i6++) {
        const tocLink = tocLinks[i6];
        tocLink.classList.add("nav-link");
        if (i6 === 0) {
          tocLink.classList.add("active");
        }
        if (!tocLink.hasAttribute("data-scroll-target")) {
          tocLink.setAttribute(
            "data-scroll-target",
            tocLink.getAttribute("href")?.replaceAll(":", "\\:")
          );
        }
      }
      const tocDepth = format14.pandoc[kTocDepth] || 3;
      if (tocDepth > 1) {
        const ulSelector = "ul ".repeat(tocDepth - 1).trim();
        const nestedUls = toc.querySelectorAll(ulSelector);
        for (let i6 = 0; i6 < nestedUls.length; i6++) {
          const ul = nestedUls[i6];
          ul.classList.add("collapse");
        }
      }
      toc.remove();
      tocTarget.replaceWith(toc);
    } else {
      tocTarget?.remove();
    }
    if (format14.render[kFormatLinks] !== false) {
      processAlternateFormatLinks(input, options, doc, format14, resources);
    }
    if (format14.render[kNotebookLinks] !== false) {
      const renderedHtml = options.renderedFormats.find((renderedFormat) => {
        return isHtmlOutput(renderedFormat.format.pandoc, true);
      });
      const notebookResults = await emplaceNotebookPreviews(
        input,
        doc,
        format14,
        services,
        project,
        renderedHtml?.path,
        quiet
      );
      if (notebookResults) {
        resources.push(...notebookResults.resources);
        supporting.push(...notebookResults.supporting);
      }
    }
    await processOtherLinks(doc, format14, project);
    const addTableClasses = (table, computational = false) => {
      table.classList.add("table");
      if (computational) {
        table.classList.add("table-sm");
        table.classList.add("table-striped");
        table.classList.add("small");
      }
    };
    const tableHeaders = doc.querySelectorAll("tbody > tr:first-child.odd");
    for (let i6 = 0; i6 < tableHeaders.length; i6++) {
      const th = tableHeaders[i6];
      if (th.parentNode?.parentNode) {
        const table = th.parentNode.parentNode;
        table.removeAttribute("style");
        addTableClasses(
          table,
          !!findParent(
            table,
            (el) => el.classList.contains("cell") && !el.classList.contains("plain")
          )
        );
      }
    }
    const pandasTables = doc.querySelectorAll("table.dataframe");
    for (let i6 = 0; i6 < pandasTables.length; i6++) {
      const table = pandasTables[i6];
      table.removeAttribute("border");
      addTableClasses(table, true);
      const headerRows = table.querySelectorAll("tr");
      for (let r5 = 0; r5 < headerRows.length; r5++) {
        headerRows[r5].removeAttribute("style");
      }
      if (table.previousElementSibling && table.previousElementSibling.tagName === "STYLE") {
        table.previousElementSibling.remove();
      }
    }
    const dataFramesTables = doc.querySelectorAll("table.data-frame");
    for (let i6 = 0; i6 < dataFramesTables.length; i6++) {
      const table = dataFramesTables[i6];
      addTableClasses(table, true);
    }
    const sections = doc.querySelectorAll('section[class^="level"]');
    for (let i6 = 0; i6 < sections.length; i6++) {
      const section = sections[i6];
      const heading = section.querySelector("h2") || section.querySelector("h3") || section.querySelector("h4") || section.querySelector("h5") || section.querySelector("h6");
      if (heading) {
        heading.setAttribute("data-anchor-id", section.id);
      }
    }
    const titleResourceFiles = processDocumentTitle(
      input,
      format14,
      flags,
      doc
    );
    resources.push(...titleResourceFiles);
    const beforeBodyScript = doc.querySelector(
      "script#quarto-html-before-body"
    );
    if (beforeBodyScript) {
      doc.body.insertBefore(beforeBodyScript, doc.body.firstChild);
    }
    if (format14.metadata[kAppendixStyle] !== false && format14.metadata[kAppendixStyle] !== "none") {
      await processDocumentAppendix(
        input,
        options.inputTraits,
        format14,
        flags,
        doc,
        offset3
      );
    }
    return Promise.resolve({ resources, supporting });
  };
}
function createLinkChild(formatLink, doc) {
  const link2 = doc.createElement("a");
  link2.setAttribute("href", formatLink.href);
  if (formatLink.attr) {
    for (const key of Object.keys(formatLink.attr)) {
      const value = formatLink.attr[key];
      link2.setAttribute(key, value);
    }
  }
  if (formatLink.dlAttrValue) {
    link2.setAttribute("download", formatLink.dlAttrValue);
  }
  const icon = doc.createElement("i");
  icon.classList.add("bi");
  icon.classList.add(`bi-${formatLink.icon}`);
  link2.appendChild(icon);
  link2.appendChild(doc.createTextNode(formatLink.title));
  return link2;
}
async function processOtherLinks(doc, format14, context) {
  const processLinks = (otherLinks, clz, title3) => {
    const dlLinkTarget = getLinkTarget(doc, kLinkProvidersOtherLinks);
    if (otherLinks.length > 0 && dlLinkTarget) {
      const containerEl = doc.createElement("div");
      containerEl.classList.add(clz);
      const heading = dlLinkTarget.makeHeadingEl(
        title3
      );
      containerEl.appendChild(heading);
      const getAttrs = (otherLink) => {
        if (otherLink.rel || otherLink.target) {
          const attrs = {};
          if (otherLink.rel) {
            attrs.rel = otherLink.rel;
          }
          if (otherLink.target) {
            attrs.target = otherLink.target;
          }
          return attrs;
        } else {
          return void 0;
        }
      };
      const linkList = dlLinkTarget.makeContainerEl();
      let order = 0;
      for (let i6 = 0; i6 < otherLinks.length; i6++) {
        const otherLink = otherLinks[i6];
        const alternateLink = {
          icon: otherLink.icon || "link-45deg",
          href: otherLink.href,
          title: otherLink.text,
          order: ++order,
          attr: getAttrs(otherLink)
        };
        const li = dlLinkTarget.makeItemEl(
          createLinkChild(alternateLink, doc),
          i6,
          otherLinks.length
        );
        if (linkList) {
          linkList.appendChild(li);
        } else {
          containerEl.appendChild(li);
        }
      }
      if (linkList) {
        containerEl.appendChild(linkList);
      }
      dlLinkTarget.targetEl.appendChild(containerEl);
    }
  };
  const resolveCodeLinks = async (metadata, context2) => {
    const codeLinks2 = metadata[kCodeLinks];
    if (codeLinks2 !== void 0) {
      if (typeof codeLinks2 === "boolean") {
        return [];
      } else if (typeof codeLinks2 === "string") {
        if (!context2) {
          throw new Error(
            `The code-link value '${codeLinks2}' is only supported from within a project.`
          );
        }
        const resolvedCodeLink = await resolveCodeLink(codeLinks2, context2);
        if (resolvedCodeLink) {
          return [resolvedCodeLink];
        } else {
          throw new Error(`Unknown code-link value '${codeLinks2}'`);
        }
      } else {
        const outputLinks = [];
        for (const codeLink of codeLinks2) {
          if (typeof codeLink === "string") {
            if (!context2) {
              throw new Error(
                `The code-link value '${codeLink}' is only supported from within a project.`
              );
            }
            const resolvedCodeLink = await resolveCodeLink(codeLink, context2);
            if (resolvedCodeLink) {
              outputLinks.push(resolvedCodeLink);
            } else {
              throw new Error(`Unknown code-link value '${codeLink}'`);
            }
          } else {
            outputLinks.push(codeLink);
          }
        }
        return outputLinks;
      }
    }
    return [];
  };
  const resolveCodeLink = async (link2, context2) => {
    if (link2 === "repo") {
      const env2 = await context2.environment();
      if (env2.github.repoUrl) {
        return {
          icon: "github",
          text: "GitHub Repo",
          href: env2.github.repoUrl,
          target: "_blank"
        };
      } else {
        warn(
          "The 'repo' code link is not able to be created as the project isn't a GitHub project."
        );
      }
    } else if (link2 === "devcontainer") {
      const env2 = await context2.environment();
      if (env2.github.organization && env2.github.repository && env2.github.repoUrl) {
        const containerUrl = codeSpacesUrl(env2.github.repoUrl);
        return {
          icon: "github",
          text: format14.language[kLaunchDevContainerTitle] || "Launch Dev Container",
          href: containerUrl,
          target: "_blank"
        };
      } else {
        warn(
          "The 'devcontainer' code link is not able to be created as the project isn't a GitHub project."
        );
      }
    } else if (link2 === "binder") {
      const env2 = await context2.environment();
      if (env2.github.organization && env2.github.repository) {
        const containerUrl = binderUrl(
          env2.github.organization,
          env2.github.repository,
          {
            // TODO: figure out open file path (if support in vscode/rstudio)
            // openFile: extname(source) === ".ipynb" ? source : undefined
            editor: env2.codeEnvironment
          }
        );
        return {
          icon: "journals",
          text: format14.language[kLaunchBinderTitle] || "Launch Binder",
          href: containerUrl,
          target: "_blank"
        };
      } else {
        warn(
          "The 'binder' code link is not able to be created as the project isn't a GitHub project."
        );
      }
    }
  };
  const codeLinks = await resolveCodeLinks(format14.metadata, context);
  const otherLinkOptions = [{
    links: format14.metadata[kOtherLinks] || [],
    clz: "quarto-other-links",
    title: format14.language[kOtherLinksTitle] || "Other Links"
  }, {
    links: codeLinks,
    clz: "quarto-code-links",
    title: format14.language[kCodeLinksTitle] || "Code Links"
  }];
  otherLinkOptions.forEach((linkDesc) => {
    processLinks(linkDesc.links, linkDesc.clz, linkDesc.title);
  });
}
var bannerHeadingLinkProvider = {
  makeHeadingEl: (doc, text) => {
    const headingEl = doc.createElement("div");
    headingEl.classList.add("quarto-title-meta-heading");
    if (text) {
      headingEl.innerText = text;
    }
    return headingEl;
  },
  makeContainerEl: (_doc) => {
    return void 0;
  },
  makeItemEl: (doc, el) => {
    const itemEl = doc.createElement("div");
    itemEl.classList.add("quarto-title-meta-contents");
    const pEl = doc.createElement("p");
    pEl.appendChild(el);
    itemEl.appendChild(pEl);
    return itemEl;
  }
};
var bannerTextLinkProvider = {
  makeHeadingEl: (doc, text) => {
    const headingEl = doc.createElement("div");
    headingEl.classList.add("quarto-title-meta-heading");
    if (text) {
      headingEl.innerText = text;
    }
    return headingEl;
  },
  makeContainerEl: (doc) => {
    const headingEl = doc.createElement("div");
    headingEl.classList.add("quarto-title-meta-contents");
    return headingEl;
  },
  makeItemEl: (doc, el, idx, len) => {
    const itemEl = doc.createElement("span");
    itemEl.appendChild(el);
    if (idx < len - 1) {
      itemEl.append(doc.createTextNode(","));
      itemEl.setAttribute("style", "padding-right: 0.5em;");
    }
    return itemEl;
  }
};
var kLinkProvidersOtherLinks = {
  "quarto-other-links-target": bannerHeadingLinkProvider,
  "quarto-other-links-text-target": bannerTextLinkProvider
};
var kLinkProvidersOtherFormats = {
  "quarto-other-formats-target": bannerHeadingLinkProvider,
  "quarto-other-formats-text-target": bannerTextLinkProvider
};
function getLinkTarget(doc, linkProviders) {
  if (linkProviders) {
    for (const sel of Object.keys(linkProviders)) {
      const explicitTarget = doc.querySelector(`.${sel}`);
      if (explicitTarget !== null) {
        const linkProvider = linkProviders[sel];
        return {
          targetEl: explicitTarget,
          makeHeadingEl: (text) => {
            return linkProvider.makeHeadingEl(doc, text);
          },
          makeContainerEl: () => {
            return linkProvider.makeContainerEl(doc);
          },
          makeItemEl: (el, idx, len) => {
            return linkProvider.makeItemEl(doc, el, idx, len);
          }
        };
      }
    }
  }
  let dlLinkTarget = doc.querySelector(`nav[role="doc-toc"]`);
  if (dlLinkTarget === null) {
    dlLinkTarget = doc.getElementById("quarto-sidebar-toc-left");
  }
  if (dlLinkTarget === null) {
    dlLinkTarget = doc.getElementById(kMarginSidebarId2);
  }
  if (dlLinkTarget !== null) {
    return {
      targetEl: dlLinkTarget,
      makeHeadingEl: (text) => {
        const headingEl = doc.createElement("h2");
        if (text) {
          headingEl.innerText = text;
        }
        return headingEl;
      },
      makeContainerEl: () => {
        return doc.createElement("ul");
      },
      makeItemEl: (el) => {
        const liEl = doc.createElement("li");
        liEl.appendChild(el);
        return liEl;
      }
    };
  }
}
function processAlternateFormatLinks(input, options, doc, format14, resources) {
  if (options.renderedFormats.length > 1) {
    const dlLinkTarget = getLinkTarget(doc, kLinkProvidersOtherFormats);
    if (dlLinkTarget) {
      const containerEl = doc.createElement("div");
      containerEl.classList.add("quarto-alternate-formats");
      const heading = dlLinkTarget.makeHeadingEl(
        format14.language[kRelatedFormatsTitle]
      );
      containerEl.appendChild(heading);
      const otherLinks = otherFormatLinks(
        input,
        format14,
        options.renderedFormats
      );
      const formatList = dlLinkTarget.makeContainerEl();
      const sortedLinks = otherLinks.sort(
        ({ order: a5 }, { order: b3 }) => a5 - b3
      );
      for (let i6 = 0; i6 < sortedLinks.length; i6++) {
        const alternateLink = sortedLinks[i6];
        const link2 = doc.createElement("a");
        link2.setAttribute("href", alternateLink.href);
        if (alternateLink.dlAttrValue) {
          link2.setAttribute("download", alternateLink.dlAttrValue);
        }
        if (alternateLink.attr) {
          for (const key of Object.keys(alternateLink.attr)) {
            const value = alternateLink.attr[key];
            link2.setAttribute(key, value);
          }
        }
        const icon = doc.createElement("i");
        icon.classList.add("bi");
        icon.classList.add(`bi-${alternateLink.icon}`);
        link2.appendChild(icon);
        link2.appendChild(doc.createTextNode(alternateLink.title));
        const li = dlLinkTarget.makeItemEl(link2, i6, sortedLinks.length);
        if (formatList) {
          formatList.appendChild(li);
        } else {
          containerEl.appendChild(li);
        }
        resources.push(alternateLink.href);
      }
      if (otherLinks.length > 0) {
        if (formatList) {
          containerEl.appendChild(formatList);
        }
        dlLinkTarget.targetEl.appendChild(containerEl);
      }
    }
  }
}
function bootstrapHtmlFinalizer(format14, flags) {
  return (doc) => {
    const { citesInMargin, refsInMargin } = processColumnElements(
      doc,
      format14,
      flags
    );
    if (format14.metadata[kDisableArticleLayout]) {
      const stripColumnClasses = (el) => {
        const stripClz = [];
        el.classList.forEach((clz) => {
          if (clz === "margin-caption" || clz === "margin-ref" || clz.startsWith("column-") || clz === "page-columns" || clz === "page-full") {
            stripClz.push(clz);
          }
        });
        el.classList.remove(...stripClz);
        for (const childEl of el.children) {
          stripColumnClasses(childEl);
        }
      };
      const mainEl = doc.body.querySelector("main");
      if (mainEl) {
        stripColumnClasses(mainEl);
      }
    }
    if (refsInMargin) {
      const footNoteSectionEl = doc.querySelector("section.footnotes");
      if (footNoteSectionEl) {
        footNoteSectionEl.remove();
      }
    }
    if (citesInMargin) {
      const bibliographyDiv = doc.querySelector("div#refs");
      if (bibliographyDiv) {
        bibliographyDiv.remove();
      }
    }
    const fullLayout = formatHasFullLayout(format14);
    if (fullLayout) {
      const leftSidebar2 = hasContents(kSidebarId, doc);
      if (!leftSidebar2) {
        const sidebarEl = doc.getElementById(kSidebarId);
        sidebarEl?.remove();
      }
      const column = suggestColumn(doc);
      setMainColumn(doc, column);
    }
    const hasToc = !!format14.pandoc.toc;
    const leftSidebar = doc.getElementById("quarto-sidebar");
    const hasLeftContent = leftSidebar && leftSidebar.children.length > 0;
    const rightSidebar = doc.getElementById("quarto-margin-sidebar");
    const hasRightContent = rightSidebar && rightSidebar.children.length > 0;
    const hasMarginContent = doc.querySelectorAll(".column-margin").length > 0 || doc.querySelectorAll(".margin-caption").length > 0 || doc.querySelectorAll(".margin-ref").length > 0;
    if (rightSidebar && !hasRightContent && !hasMarginContent && !hasToc) {
      rightSidebar.remove();
    }
    const gridObj = format14.metadata[kGrid];
    let contentMode = "auto";
    if (gridObj) {
      contentMode = gridObj[kContentMode];
    }
    if (contentMode === void 0 || contentMode === "auto") {
      const hasColumnElements = getColumnLayoutElements(doc).length > 0;
      if (hasColumnElements) {
        if (hasLeftContent && hasMarginContent) {
          doc.body.classList.add("slimcontent");
        } else if (hasRightContent || hasMarginContent || fullLayout || hasToc) {
        } else {
          doc.body.classList.add("fullcontent");
        }
      } else {
        if (!hasRightContent && !hasMarginContent && !hasToc) {
          doc.body.classList.add("fullcontent");
        } else {
        }
      }
    } else {
      if (contentMode === "slim") {
        doc.body.classList.add("slimcontent");
      } else if (contentMode === "full") {
        doc.body.classList.add("fullcontent");
      }
    }
    let initialLightDarkClass = "quarto-light";
    if (darkModeDefault(format14)) {
      initialLightDarkClass = "quarto-dark";
    }
    doc.body.classList.add(initialLightDarkClass);
    const isFullLayout = format14.metadata[kPageLayout] === "full";
    const marginSidebarEl = doc.getElementById("quarto-margin-sidebar");
    if (!hasMarginContent && isFullLayout && !hasRightContent || marginSidebarEl?.childElementCount === 0) {
      marginSidebarEl?.classList.add("zindex-bottom");
    }
    return Promise.resolve();
  };
}
function processColumnElements(doc, format14, flags) {
  removeNestedColumnLayouts(doc);
  cleanNonsensicalMarginCaps(doc);
  if (!formatHasArticleLayout(format14)) {
    return {
      citesInMargin: false,
      refsInMargin: false
    };
  }
  processMarginCaptions(doc);
  processMarginElsInCallouts(doc);
  processMarginElsInTabsets(doc);
  processFigureOutputs(doc);
  const marginProcessors = [
    simpleMarginProcessor
  ];
  if (hasMarginFigCaps(format14)) {
    marginProcessors.push(figCapInCalloutMarginProcessor);
  }
  const refsInMargin = hasMarginRefs(format14, flags);
  if (refsInMargin) {
    marginProcessors.unshift(footnoteMarginProcessor);
  }
  const citesInMargin = hasMarginCites(format14);
  if (citesInMargin) {
    marginProcessors.push(referenceMarginProcessor);
  }
  processMarginNodes(doc, marginProcessors);
  if (refsInMargin) {
    const footnoteContainer = doc.getElementById("footnotes");
    if (footnoteContainer) {
      footnoteContainer.remove();
    }
  }
  const columnLayouts = getColumnLayoutElements(doc);
  if (columnLayouts && columnLayouts.length > 0) {
    const processEl = (el) => {
      if (el.tagName === "DIV" && el.id === "quarto-content") {
        return false;
      } else if (el.tagName === "BODY") {
        return false;
      } else {
        return true;
      }
    };
    const ensureInGrid = (el, setLayout) => {
      if (processEl(el)) {
        if (!el.classList.contains("quarto-layout-row") && !el.classList.contains("page-columns")) {
          el.classList.add("page-columns");
        }
        if (setLayout && !el.classList.contains("page-full")) {
          el.classList.add("page-full");
        }
        const parent = el.parentElement;
        if (parent) {
          ensureInGrid(parent, true);
        }
      }
    };
    columnLayouts.forEach((node) => {
      const el = node;
      if (el.parentElement) {
        ensureInGrid(el.parentElement, true);
      }
    });
  }
  return {
    citesInMargin,
    refsInMargin
  };
}
var processMarginNodes = (doc, processors) => {
  const marginSelector = processors.map((proc) => proc.selector).join(
    ", "
  );
  const marginNodes = doc.querySelectorAll(marginSelector);
  marginNodes.forEach((marginNode) => {
    const marginEl = marginNode;
    for (const processor of processors) {
      if (processor.canProcess(marginEl)) {
        processor.process(marginEl, doc);
        break;
      }
    }
    marginEl.classList.remove("column-margin");
  });
};
var findQuartoFigure = (el) => {
  if (el.classList.contains("quarto-figure") || el.classList.contains("quarto-layout-panel") || el.classList.contains("quarto-float")) {
    return el;
  } else if (el.parentElement) {
    return findQuartoFigure(el.parentElement);
  } else {
    return void 0;
  }
};
var moveClassToCaption = (container, sel) => {
  const target = container.querySelector(sel);
  if (target) {
    target.classList.add("margin-caption");
    return true;
  } else {
    return false;
  }
};
var removeCaptionClass = (el) => {
  el.classList.remove("margin-caption");
};
var processLayoutPanelMarginCaption = (captionContainer) => {
  const figure = captionContainer.querySelector("figure");
  if (figure) {
    for (const child of figure.children) {
      if (child.tagName === "FIGCAPTION") {
        child.classList.add("margin-caption");
        removeCaptionClass(captionContainer);
        break;
      }
    }
  } else {
    const caption = captionContainer.querySelector(".panel-caption");
    if (caption) {
      caption.classList.add("margin-caption");
      removeCaptionClass(captionContainer);
    }
  }
};
var processFigureMarginCaption = (captionContainer, doc) => {
  const foundCaption = moveClassToCaption(captionContainer, "figcaption");
  if (!foundCaption) {
    const captionEl = captionContainer.querySelector("caption");
    if (captionEl) {
      const parentDivEl = captionEl?.parentElement?.parentElement;
      if (parentDivEl) {
        captionEl.classList.add("hidden");
        const divCopy = doc.createElement("div");
        divCopy.classList.add("figure-caption");
        divCopy.classList.add("margin-caption");
        divCopy.innerHTML = captionEl.innerHTML;
        parentDivEl.appendChild(divCopy);
        removeCaptionClass(captionContainer);
      }
    }
  } else {
    removeCaptionClass(captionContainer);
  }
};
var processTableMarginCaption = (captionContainer, doc) => {
  const caption = captionContainer.querySelector("caption");
  if (caption) {
    const marginCapEl = doc.createElement("DIV");
    marginCapEl.classList.add("quarto-table-caption");
    marginCapEl.classList.add("margin-caption");
    marginCapEl.innerHTML = caption.innerHTML;
    captionContainer.parentElement?.insertBefore(
      marginCapEl,
      captionContainer.nextElementSibling
    );
    caption.remove();
    removeCaptionClass(captionContainer);
  }
};
var processMarginCaptions = (doc) => {
  const captionsAlreadyInMargin = doc.querySelectorAll(
    ".column-margin .margin-caption"
  );
  captionsAlreadyInMargin.forEach((node) => {
    const el = node;
    el.classList.remove("margin-caption");
  });
  const marginCaptions = doc.querySelectorAll(".margin-caption");
  marginCaptions.forEach((node) => {
    const figureEl = node;
    const captionContainer = findQuartoFigure(figureEl);
    if (captionContainer) {
      const isLayoutPanel = captionContainer.classList.contains(
        "quarto-layout-panel"
      );
      const explicitCapLoc = captionContainer.getAttribute("data-cap-location");
      if (explicitCapLoc == null || explicitCapLoc == "margin") {
        if (isLayoutPanel) {
          processLayoutPanelMarginCaption(captionContainer);
        } else {
          processFigureMarginCaption(captionContainer, doc);
        }
      }
    } else {
      if (figureEl.classList.contains("tbl-parent")) {
        const capDivEl = figureEl.querySelector("div.panel-caption");
        if (capDivEl) {
          capDivEl.classList.add("margin-caption");
          capDivEl.remove();
          figureEl.appendChild(capDivEl);
        }
      } else {
        const table = figureEl.querySelector("table");
        if (table) {
          processTableMarginCaption(table, doc);
        }
      }
    }
    removeCaptionClass(figureEl);
  });
};
var processMarginElsInCallouts = (doc) => {
  const calloutNodes = doc.querySelectorAll("div.callout");
  calloutNodes.forEach((calloutNode) => {
    const calloutEl = calloutNode;
    const collapseEl = calloutEl.querySelector(".callout-collapse");
    const isSimple = calloutEl.classList.contains("callout-style-simple");
    const collapseClasses = [];
    if (collapseEl) {
      collapseEl.classList.forEach((clz) => collapseClasses.push(clz));
    }
    const marginNodes = calloutEl.querySelectorAll(
      ".callout-body-container .column-margin, .callout-body-container aside:not(.footnotes):not(.sidebar), .callout-body-container .aside:not(.footnotes)"
    );
    if (marginNodes.length > 0) {
      const marginArr = Array.from(marginNodes);
      marginArr.reverse().forEach((marginNode) => {
        const marginEl = marginNode;
        collapseClasses.forEach((clz) => {
          marginEl.classList.add(clz);
        });
        marginEl.classList.add("callout-margin-content");
        if (isSimple) {
          marginEl.classList.add("callout-margin-content-simple");
        }
        calloutEl.after(marginEl);
      });
    }
  });
};
var figCapInCalloutMarginProcessor = {
  selector: ".callout",
  canProcess(el) {
    const hasFigCap = el.querySelector("figcaption");
    return hasFigCap !== null;
  },
  process(el, doc) {
    const collapseEl = el.querySelector(".callout-collapse");
    const isSimple = el.classList.contains("callout-style-simple");
    const collapseClasses = [];
    if (collapseEl) {
      collapseEl.classList.forEach((clz) => collapseClasses.push(clz));
    }
    const figNodes = el.querySelectorAll("figure");
    for (const figNode of Array.from(figNodes).reverse()) {
      const figEl = figNode;
      const figCaptionEl = figEl.querySelector("figcaption");
      let figureId = figEl.id;
      if (figureId === "") {
        figureId = figEl.parentElement?.id || "";
      }
      const captionId = figureId + "-caption";
      figEl.setAttribute("aria-labelledby", captionId);
      if (figCaptionEl !== null) {
        figCaptionEl.remove();
        const div = doc.createElement("DIV");
        div.id = captionId;
        div.classList.add("margin-figure-caption");
        div.classList.add("column-margin");
        collapseClasses.forEach((clz) => {
          div.classList.add(clz);
        });
        div.classList.add("callout-margin-content");
        if (isSimple) {
          div.classList.add("callout-margin-content-simple");
        }
        figCaptionEl.childNodes.forEach((node) => {
          div.append(node);
        });
        el.parentElement?.insertBefore(div, el.nextElementSibling);
      }
    }
  }
};
var kPreviewFigColumnForwarding = [".grid"];
var isInsideAbout = (el) => !!findParent(
  el,
  (parent) => Array.from(parent.classList).some((x3) => x3.startsWith("quarto-about-"))
);
var processFigureOutputs = (doc) => {
  const columnEls = doc.querySelectorAll(
    '[class^="column-"]:not(.column-margin), [class*=" column-"]:not(.column-margin)'
  );
  const moveColumnClasses = (fromEl, toEl) => {
    const clzList = [];
    for (const clz of fromEl.classList) {
      if (clz.startsWith("column-")) {
        clzList.push(clz);
      }
    }
    fromEl.classList.remove(...clzList);
    toEl.classList.add(...clzList);
  };
  for (const columnNode of columnEls) {
    const columnEl = columnNode;
    if (kPreviewFigColumnForwarding.some((sel) => {
      return columnEl.querySelector(sel) !== null;
    })) {
      continue;
    }
    const figures = columnEl.querySelectorAll("figure img.figure-img");
    if (figures && figures.length === 1 && !isInsideAbout(figures[0])) {
      moveColumnClasses(columnEl, figures[0]);
    } else {
      const layoutFigures = columnEl.querySelectorAll(
        ".quarto-layout-panel > figure.figure .quarto-layout-row"
      );
      if (layoutFigures && layoutFigures.length === 1 && !isInsideAbout(layoutFigures[0])) {
        moveColumnClasses(columnEl, layoutFigures[0]);
      }
    }
  }
};
var processMarginElsInTabsets = (doc) => {
  const tabSetNodes = doc.querySelectorAll("div.panel-tabset");
  tabSetNodes.forEach((tabsetNode) => {
    const tabSetEl = tabsetNode;
    const tabNodes = tabSetEl.querySelectorAll("div.tab-pane");
    const marginEls = [];
    let count = 0;
    tabNodes.forEach((tabNode) => {
      const tabEl = tabNode;
      const tabId = tabEl.id;
      const marginNodes = tabEl.querySelectorAll(
        ".column-margin, aside:not(.footnotes):not(.sidebar), .aside:not(.footnotes)"
      );
      if (tabId && marginNodes.length > 0) {
        const marginArr = Array.from(marginNodes);
        marginArr.forEach((marginNode) => {
          const marginEl = marginNode;
          marginEl.classList.add("tabset-margin-content");
          marginEl.classList.add(`${tabId}-tab-margin-content`);
          if (count > 0) {
            marginEl.classList.add("collapse");
          }
          marginEls.push(marginEl);
        });
      }
      count++;
    });
    if (marginEls) {
      const containerEl = doc.createElement("div");
      containerEl.classList.add("tabset-margin-container");
      marginEls.forEach((marginEl) => {
        containerEl.appendChild(marginEl);
      });
      tabSetEl.before(containerEl);
    }
  });
};
var simpleMarginProcessor = {
  selector: ".column-margin:not(.column-container)",
  canProcess(el) {
    return el.classList.contains("column-margin") && !el.classList.contains("column-container");
  },
  process(el, doc) {
    el.classList.remove("column-margin");
    const kPopMarginElOutOfTags = ["DD"];
    if (el.parentElement && kPopMarginElOutOfTags.includes(el.parentElement?.tagName)) {
      const parentElement = el.parentElement;
      const marginContainer = doc.createElement("DIV");
      el.remove();
      marginContainer.appendChild(el);
      parentElement.parentElement?.insertBefore(
        marginContainer,
        parentElement.nextSibling
      );
      addContentToMarginContainerForEl(marginContainer, marginContainer, doc);
    } else {
      addContentToMarginContainerForEl(el, el, doc);
    }
  }
};
var footnoteMarginProcessor = {
  selector: ".footnote-ref",
  canProcess(el) {
    return el.classList.contains("footnote-ref");
  },
  process(el, doc) {
    if (el.hasAttribute("href")) {
      const target = el.getAttribute("href");
      if (target) {
        const refId = target.slice(1);
        const refContentsEl = doc.getElementById(refId);
        if (refContentsEl) {
          const backLinkEl = refContentsEl.querySelector(".footnote-back");
          if (backLinkEl) {
            backLinkEl.remove();
          }
          const invalidParentTags = [
            "SPAN",
            "EM",
            "STRONG",
            "DEL",
            "H1",
            "H2",
            "H3",
            "H4",
            "H5",
            "H6"
          ];
          const findValidParentEl = (el2) => {
            if (el2.parentElement && !invalidParentTags.includes(el2.parentElement.tagName)) {
              return el2.parentElement;
            } else if (el2.parentElement) {
              return findValidParentEl(el2.parentElement);
            } else {
              return void 0;
            }
          };
          if (refContentsEl.childNodes.length > 0) {
            const firstChild = refContentsEl.childNodes[0];
            firstChild.insertBefore(
              doc.createTextNode("\xA0"),
              firstChild.firstChild
            );
            firstChild.insertBefore(
              el.firstChild.cloneNode(true),
              firstChild.firstChild
            );
          }
          const validParent = findValidParentEl(el);
          if (refContentsEl.tagName === "LI") {
            const containerEl = doc.createElement("DIV");
            containerEl.id = refContentsEl.id;
            containerEl.append(...refContentsEl.childNodes);
            addContentToMarginContainerForEl(
              validParent || el,
              containerEl,
              doc
            );
          } else {
            addContentToMarginContainerForEl(
              validParent || el,
              refContentsEl,
              doc
            );
          }
        }
      }
    }
  }
};
var referenceMarginProcessor = {
  selector: "a[role='doc-biblioref']",
  canProcess(el) {
    return el.hasAttribute("role") && el.getAttribute("role") === "doc-biblioref";
  },
  process(el, doc) {
    if (el.hasAttribute("href")) {
      const target = el.getAttribute("href");
      if (target) {
        const refId = target.slice(1);
        const refContentsEl = doc.getElementById(refId);
        const findCaptionEl = (el2) => {
          if (el2.parentElement?.tagName === "FIGCAPTION") {
            return el2.parentElement;
          } else if (el2.parentElement) {
            return findCaptionEl(el2.parentElement);
          } else {
            return void 0;
          }
        };
        const findNonSpanParentEl = (el2) => {
          if (el2.parentElement && el2.parentElement.tagName !== "SPAN") {
            return el2.parentElement;
          } else if (el2.parentElement) {
            return findNonSpanParentEl(el2.parentElement);
          } else {
            return void 0;
          }
        };
        const figureCaptionEl = findCaptionEl(el);
        if (refContentsEl && figureCaptionEl) {
          if (figureCaptionEl.classList.contains("margin-caption")) {
            figureCaptionEl.appendChild(refContentsEl.cloneNode(true));
          } else {
            addContentToMarginContainerForEl(
              figureCaptionEl,
              refContentsEl,
              doc
            );
          }
        } else if (refContentsEl) {
          const nonSpanParent = findNonSpanParentEl(el);
          if (nonSpanParent) {
            addContentToMarginContainerForEl(
              nonSpanParent,
              refContentsEl,
              doc
            );
          }
        }
      }
    }
  }
};
var isContainer = (el) => {
  return el && el.tagName === "DIV" && el.classList.contains("column-container") && el.classList.contains("column-margin");
};
var isAlreadyInMargin = (el) => {
  const elInMargin = el.classList.contains("column-margin") || el.classList.contains("aside") && !el.classList.contains("footnotes") || el.classList.contains("margin-caption");
  if (elInMargin) {
    return true;
  } else if (el.parentElement !== null) {
    return isAlreadyInMargin(el.parentElement);
  } else {
    return false;
  }
};
var createMarginContainer = (doc) => {
  const container = doc.createElement("div");
  container.classList.add("no-row-height");
  container.classList.add("column-margin");
  container.classList.add("column-container");
  return container;
};
var marginContainerForEl = (el, doc) => {
  if (el.parentElement && isAlreadyInMargin(el.parentElement)) {
    return el.parentElement;
  }
  if (el.nextElementSibling && isContainer(el.nextElementSibling)) {
    return el.nextElementSibling;
  }
  if (el.previousElementSibling && isContainer(el.previousElementSibling)) {
    return el.previousElementSibling;
  }
  const findCalloutEl = (el2) => {
    if (el2.parentElement?.classList.contains("callout")) {
      return el2.parentElement;
    } else if (el2.parentElement) {
      return findCalloutEl(el2.parentElement);
    } else {
      return void 0;
    }
  };
  const calloutEl = findCalloutEl(el);
  if (calloutEl) {
    const container2 = createMarginContainer(doc);
    calloutEl.parentNode?.insertBefore(
      container2,
      calloutEl.nextElementSibling
    );
    return container2;
  }
  const list = findOutermostParentElOfType(el, ["OL", "UL", "TABLE"]);
  if (list) {
    if (list.nextElementSibling && isContainer(list.nextElementSibling)) {
      return list.nextElementSibling;
    } else {
      const container2 = createMarginContainer(doc);
      if (list.parentNode) {
        list.parentNode.insertBefore(container2, list.nextElementSibling);
      }
      return container2;
    }
  }
  const parentEl = el.parentElement;
  const cantContainBlockTags = ["P", "BLOCKQUOTE"];
  if (parentEl && cantContainBlockTags.includes(parentEl.tagName)) {
    if (parentEl.parentElement && parentEl.parentElement.tagName === "DIV" && parentEl.nextElementSibling && isContainer(parentEl.nextElementSibling)) {
      return parentEl.nextElementSibling;
    } else {
      const container2 = createMarginContainer(doc);
      const wrapper = doc.createElement("div");
      parentEl.replaceWith(wrapper);
      wrapper.appendChild(parentEl);
      wrapper.appendChild(container2);
      return container2;
    }
  }
  const container = createMarginContainer(doc);
  el.parentNode?.insertBefore(container, el.nextElementSibling);
  return container;
};
var addContentToMarginContainerForEl = (el, content, doc) => {
  const container = marginContainerForEl(el, doc);
  if (container) {
    container.appendChild(content);
  }
};
var findOutermostParentElOfType = (el, tagNames) => {
  let outEl = void 0;
  if (el.parentElement) {
    if (el.parentElement.tagName === "MAIN") {
      return outEl;
    } else {
      if (tagNames.includes(el.parentElement.tagName)) {
        outEl = el.parentElement;
      }
      outEl = findOutermostParentElOfType(el.parentElement, tagNames) || outEl;
      return outEl;
    }
  } else {
    return void 0;
  }
};
var hasContents = (id, doc) => {
  const el = doc.getElementById(id);
  if (el === null) {
    return false;
  }
  if (el.children.length > 0) {
    return true;
  }
  return !!el.innerText.trim();
};
function suggestColumn(doc) {
  const leftSidebar = hasContents(kSidebarId, doc);
  const leftToc = hasContents(kTocLeftSidebarId, doc);
  const rightSidebar = hasContents(kMarginSidebarId2, doc);
  const columnClasses = getColumnClasses(doc);
  const leftContent = [...fullOccludeClz, ...leftOccludeClz].some((clz) => {
    return columnClasses.has(clz);
  });
  const rightContent = [...fullOccludeClz, ...rightOccludeClz].some((clz) => {
    return columnClasses.has(clz);
  });
  const leftUsed = leftSidebar || leftContent || leftToc;
  const rightUsed = rightSidebar || rightContent;
  if (leftUsed && rightUsed) {
    return "column-body";
  } else if (leftUsed) {
    return "column-page-right";
  } else if (rightUsed) {
    return "column-page-left";
  } else {
    return "column-page";
  }
}
var kSidebarId = "quarto-sidebar";
var kMarginSidebarId2 = "quarto-margin-sidebar";
var kTocLeftSidebarId = "quarto-sidebar-toc-left";
var fullOccludeClz = [
  "column-page",
  "column-screen",
  "column-screen-inset"
];
var leftOccludeClz = [
  "column-page-left",
  "column-screen-inset-left",
  "column-screen-left"
];
var rightOccludeClz = [
  "column-margin",
  "column-page-right",
  "column-screen-inset-right",
  "column-screen-right",
  "margin-caption",
  "margin-ref"
];
var allColumnClz = [
  "column-body-outset",
  "column-body-outset-left",
  "column-body-outset-right",
  "column-page-inset",
  "column-page-inset-left",
  "column-page-inset-right",
  "column-page",
  "column-page-left",
  "column-page-right",
  "column-screen-inset",
  "column-screen-inset-left",
  "column-screen-inset-right",
  "column-screen",
  "column-screen-left",
  "column-screen-right",
  "column-margin"
];
var removeMarginClz = [
  "column-body-outset",
  "column-body-outset-right",
  "column-page-inset",
  "column-page-inset-right",
  "column-page",
  "column-page-right",
  "column-screen-inset",
  "column-screen-inset-right",
  "column-screen",
  "column-screen-right",
  "column-margin"
];
var nonScreenColumnClz = [
  "column-body-outset",
  "column-body-outset-left",
  "column-body-outset-right",
  "column-page-inset",
  "column-page-inset-left",
  "column-page-inset-right",
  "column-page",
  "column-page-left",
  "column-page-right",
  "column-screen-inset",
  "column-screen-inset-left",
  "column-screen-inset-right",
  "column-screen-left",
  "column-screen-right",
  "column-margin"
];
var getColumnClasses = (doc) => {
  const classes = /* @__PURE__ */ new Set();
  const colNodes = getColumnLayoutElements(doc);
  for (const colNode of colNodes) {
    const colEl = colNode;
    colEl.classList.forEach((clz) => {
      if (clz === "margin-caption" || clz === "margin-ref" || clz.startsWith("column-")) {
        classes.add(clz);
      }
    });
  }
  return classes;
};

// format/html/format-html.ts
init_format_html_shared();
init_website_constants();
init_format_handlers();

// core/sass/brand.ts
init_types5();
init_schema_types();
init_format_html_info();
init_constants6();
init_path();
init_url();
var defaultColorNameMap = {
  "link-color": "link",
  "pre-color": "foreground",
  "body-bg": "background",
  "body-color": "foreground",
  "body-secondary-color": "secondary",
  "body-secondary": "secondary",
  "body-tertiary-color": "tertiary",
  "body-tertiary": "secondary"
};
var brandFontWeightValue = (weight) => {
  if (typeof weight === "number") {
    return weight;
  }
  const stringMap = {
    thin: 100,
    "extra-light": 200,
    "ultra-light": 200,
    light: 300,
    normal: 400,
    regular: 400,
    medium: 500,
    "semi-bold": 600,
    "demi-bold": 600,
    bold: 700,
    "extra-bold": 800,
    "ultra-bold": 800,
    black: 900
  };
  const result2 = stringMap[weight];
  if (result2 === void 0) {
    throw new Error(`Unknown font weight ${weight}`);
  }
  return result2;
};
async function brandBootstrapSassBundles(fileName, project, key) {
  const layers = await brandBootstrapSassLayers(
    fileName,
    project,
    defaultColorNameMap
  );
  return [{
    key,
    dependency: "bootstrap",
    user: layers.light,
    dark: {
      user: layers.dark
    }
  }];
}
var bunnyFontImportString = (description) => {
  const bunnyName = (name2) => name2.replace(/ /g, "-");
  const bunnyFamily = description.family;
  if (!bunnyFamily) {
    throw new Error("Bunny font family not specified");
  }
  const styles = !description.style ? ["normal", "italic"] : typeof description.style === "string" ? [description.style] : description.style;
  const weightArray = !description.weight ? [400, 700] : typeof description.weight === "number" || typeof description.weight === "string" ? [brandFontWeightValue(description.weight)] : description.weight.map((w3) => brandFontWeightValue(w3));
  const display = description.display ?? "swap";
  const weights = styles.includes("italic") ? weightArray.map((w3) => `${w3}i`).join(",") + "," + weightArray.join(",") : weightArray.join(",");
  return `@import url('https://fonts.bunny.net/css?family=${bunnyName(bunnyFamily)}:${weights}&display=${display}');`;
};
var googleFontImportString = (description) => {
  const googleFamily = typeof description === "string" ? description : description.family;
  const styles = !description.style ? ["normal", "italic"] : typeof description.style === "string" ? [description.style] : description.style;
  const weightArray = !description.weight ? [400, 700] : typeof description.weight === "number" || typeof description.weight === "string" ? [brandFontWeightValue(description.weight)] : description.weight.map((w3) => brandFontWeightValue(w3));
  const display = description.display ?? "swap";
  let styleString = "";
  let weights = "";
  if (styles.includes("italic")) {
    styleString = "ital,";
    weights = weightArray.map((w3) => `0,${w3}`).join(";") + ";" + weightArray.map((w3) => `1,${w3}`).join(";");
  } else {
    weights = !description.weight ? "400;700" : weightArray.join(";");
  }
  return `@import url('https://fonts.googleapis.com/css2?family=${googleFamily.replace(
    / /g,
    "+"
  )}:${styleString}wght@${weights}&display=${display}');`;
};
var fileFontImportString = (brand, description) => {
  const pathPrefix = relative4(brand.projectDir, brand.brandDir);
  const parts = [];
  for (const file of description.files) {
    let path3, weight, style;
    if (typeof file === "string") {
      path3 = file;
    } else {
      path3 = file.path;
      weight = file.weight;
      style = file.style;
    }
    const fontUrl = isExternalPath(path3) ? path3 : join4(pathPrefix, path3).replace(/\\/g, "/");
    parts.push(`@font-face {
    font-family: '${description.family}';
    src: url('${fontUrl}');
    font-weight: ${weight || "normal"};
    font-style: ${style || "normal"};
}
`);
  }
  return parts.join("\n");
};
var brandColorLayer = (brand, nameMap) => {
  const colorVariables = [
    "/* color variables from _brand.yml */",
    '// quarto-scss-analysis-annotation { "action": "push", "origin": "_brand.yml color" }'
  ];
  const colorCssVariables = [
    "/* color CSS variables from _brand.yml */",
    '// quarto-scss-analysis-annotation { "action": "push", "origin": "_brand.yml color" }',
    ":root {"
  ];
  for (const colorKey of Object.keys(brand.data?.color?.palette ?? {})) {
    const colorVar = colorKey.replace(/[^a-zA-Z0-9_-]+/g, "-");
    colorVariables.push(
      `$brand-${colorVar}: ${brand.getColor(colorKey)} !default;`
    );
    colorCssVariables.push(
      `  --brand-${colorVar}: ${brand.getColor(colorKey)};`
    );
  }
  for (const colorKey of Object.keys(brand.data.color ?? {})) {
    if (colorKey === "palette") {
      continue;
    }
    colorVariables.push(
      `$${colorKey}: ${brand.getColor(colorKey)} !default;`
    );
  }
  for (const [key, value] of Object.entries(nameMap)) {
    const resolvedValue = brand.getColor(value, true);
    if (resolvedValue !== value) {
      colorVariables.push(
        `$${key}: ${resolvedValue} !default;`
      );
    }
  }
  colorVariables.push('// quarto-scss-analysis-annotation { "action": "pop" }');
  colorCssVariables.push(
    "}",
    '// quarto-scss-analysis-annotation { "action": "pop" }'
  );
  return {
    defaults: colorVariables.join("\n"),
    uses: "",
    functions: "",
    mixins: "",
    rules: colorCssVariables.join("\n")
  };
};
var brandDefaultsBootstrapLayer = (brand) => {
  const brandBootstrap = brand?.data?.defaults?.bootstrap;
  const bsVariables = [
    "/* Bootstrap variables from _brand.yml */",
    '// quarto-scss-analysis-annotation { "action": "push", "origin": "_brand.yml defaults.bootstrap.defaults" }'
  ];
  const bsDefaults = brandBootstrap.defaults || "";
  if (typeof bsDefaults === "string") {
    bsVariables.push(bsDefaults);
  } else if (typeof bsDefaults === "object") {
    for (const bsVar of Object.keys(bsDefaults)) {
      bsVariables.push(`$${bsVar}: ${bsDefaults[bsVar]} !default;`);
    }
  } else {
    throw new Error(
      "Invalid bootstrap defaults in _brand.yml or `brand`. `defaults.bootstrap.defaults` expects a string or a dictionary  mapping Sass variables to default values."
    );
  }
  bsVariables.push('// quarto-scss-analysis-annotation { "action": "pop" }');
  const bootstrapColorVariables = [
    "black",
    "white",
    "blue",
    "indigo",
    "purple",
    "pink",
    "red",
    "orange",
    "yellow",
    "green",
    "teal",
    "cyan"
  ];
  const bsColors = [
    "/* Bootstrap color variables from _brand.yml */",
    '// quarto-scss-analysis-annotation { "action": "push", "origin": "_brand.yml color.palette" }'
  ];
  if (bootstrapColorVariables.length > 0) {
    for (const colorKey of Object.keys(brand.data?.color?.palette ?? {})) {
      if (!bootstrapColorVariables.includes(colorKey)) {
        continue;
      }
      bsColors.push(`$${colorKey}: ${brand.getColor(colorKey)} !default;`);
    }
  }
  bsColors.push('// quarto-scss-analysis-annotation { "action": "pop" }');
  const scssWithQuartoAnnotation = (x3, origin) => {
    if (!x3) {
      return "";
    }
    return [
      `// quarto-scss-analysis-annotation { "action": "push", "origin": "_brand.yml defaults.bootstrap.${origin}" }`,
      x3,
      '// quarto-scss-analysis-annotation { "action": "pop" }'
    ].join("\n");
  };
  return {
    defaults: bsColors.join("\n") + "\n" + bsVariables.join("\n"),
    uses: scssWithQuartoAnnotation(brandBootstrap.uses, "uses"),
    functions: scssWithQuartoAnnotation(
      brandBootstrap.functions,
      "functions"
    ),
    mixins: scssWithQuartoAnnotation(brandBootstrap.mixins, "mixins"),
    rules: scssWithQuartoAnnotation(brandBootstrap.rules, "rules")
  };
};
var brandTypographyLayer = (brand) => {
  const typographyVariables = [
    "/* typography variables from _brand.yml */",
    '// quarto-scss-analysis-annotation { "action": "push", "origin": "_brand.yml typography" }'
  ];
  const typographyImports = /* @__PURE__ */ new Set();
  const fonts = brand.data?.typography?.fonts ?? [];
  const resolveHTMLFontInformation = (kind) => {
    let resolvedFontOptions = brand.data.typography?.[kind];
    if (!resolvedFontOptions) {
      return void 0;
    } else if (typeof resolvedFontOptions === "string") {
      resolvedFontOptions = { family: resolvedFontOptions };
    }
    const result2 = {};
    if ("family" in resolvedFontOptions) {
      result2.family = resolvedFontOptions.family;
    }
    for (const entry of [
      "line-height",
      "size",
      "weight",
      "style",
      "color",
      "background-color",
      "decoration"
    ]) {
      if (resolvedFontOptions[entry]) {
        result2[entry] = resolvedFontOptions[entry];
      }
    }
    return result2;
  };
  const variableTranslations = {
    "base": [
      // bootstrap
      ["family", "font-family-base"],
      ["size", "font-size-base"],
      ["line-height", "line-height-base"],
      ["weight", "font-weight-base"],
      // revealjs
      ["family", "mainFont"],
      ["size", "presentation-font-size-root"],
      ["line-height", "presentation-line-height"],
      // TBD?
      // mermaid
      ["family", "mermaid-font-family"],
      ["weight", "mermaid-font-weight"]
      // ["style", "font-style-base"],
      // ["weight", "font-weight-base"],
    ],
    "headings": [
      // bootstrap
      ["family", "headings-font-family"],
      ["line-height", "headings-line-height"],
      ["weight", "headings-font-weight"],
      ["weight", "h1h2h3-font-weight"],
      ["color", "headings-color"],
      ["style", "headings-font-style"],
      // revealjs
      ["family", "presentation-heading-font"],
      ["line-height", "presentation-heading-line-height"],
      ["weight", "presentation-heading-font-weight"],
      ["color", "presentation-heading-color"]
      // TODO: style, needs CSS change
    ],
    "link": [
      // bootstrap + revealjs
      ["color", "link-color"],
      ["background-color", "link-color-bg"],
      ["weight", "link-weight"],
      ["decoration", "link-decoration"]
    ],
    "monospace": [
      // bootstrap + revealjs
      ["family", "font-family-monospace"],
      // bootstrap
      ["size", "code-font-size"],
      // forward explicitly to both `code` and `pre`
      // because that interacts less with the default bootstrap styles
      ["color", "code-color"],
      // this is also revealjs
      ["color", "pre-color"],
      ["weight", "font-weight-monospace"],
      // revealjs
      ["size", "code-block-font-size"],
      ["color", "code-block-color"],
      // monospace forwards to both block and inline
      ["background-color", "code-bg"],
      ["background-color", "code-block-bg"]
    ],
    "monospace-block": [
      // bootstrap + revealjs
      ["family", "font-family-monospace-block"],
      // bootstrap
      ["line-height", "pre-line-height"],
      ["color", "pre-color"],
      ["background-color", "pre-bg"],
      ["size", "code-block-font-size"],
      ["weight", "font-weight-monospace-block"],
      // revealjs
      ["line-height", "code-block-line-height"],
      ["color", "code-block-color"],
      ["background-color", "code-block-bg"]
    ],
    "monospace-inline": [
      // bootstrap + revealjs
      ["family", "font-family-monospace-inline"],
      ["color", "code-color"],
      ["background-color", "code-bg"],
      // bootstrap
      ["size", "code-inline-font-size"],
      ["weight", "font-weight-monospace-inline"]
      // revealjs
      // ["size", "code-block-font-size"],
    ]
  };
  for (const font of fonts) {
    switch (font.source) {
      case "google": {
        const safeResolvedFont = Zod.BrandFontGoogle.safeParse(font);
        if (!safeResolvedFont.success) {
          continue;
        }
        const resolvedFont = safeResolvedFont.data;
        const thisFamily = resolvedFont.family;
        if (!thisFamily) {
          continue;
        }
        typographyImports.add(googleFontImportString(resolvedFont));
        break;
      }
      case "bunny": {
        const safeResolvedFont = Zod.BrandFontBunny.safeParse(font);
        if (!safeResolvedFont.success) {
          continue;
        }
        const resolvedFont = safeResolvedFont.data;
        const thisFamily = resolvedFont.family;
        if (!thisFamily) {
          continue;
        }
        typographyImports.add(bunnyFontImportString(resolvedFont));
        break;
      }
      case "file": {
        const safeResolvedFont = Zod.BrandFontFile.safeParse(font);
        if (!safeResolvedFont.success) {
          continue;
        }
        const resolvedFont = safeResolvedFont.data;
        const thisFamily = resolvedFont.family;
        if (!thisFamily) {
          continue;
        }
        typographyImports.add(fileFontImportString(brand, resolvedFont));
        break;
      }
    }
  }
  for (const kind of [
    // more specific entries go first
    "link",
    "monospace-block",
    "monospace-inline",
    "monospace",
    "headings",
    "base"
  ]) {
    const fontInformation = resolveHTMLFontInformation(kind);
    if (!fontInformation) {
      continue;
    }
    const variables = variableTranslations[kind];
    if (!variables) {
      throw new Error(`Unknown typography kind ${kind}`);
    }
    for (const variable of variables) {
      const source2 = variable[0];
      const target = variable[1];
      if (fontInformation[source2]) {
        let value = fontInformation[source2];
        if (["color", "background-color"].includes(source2)) {
          value = brand.getColor(value);
        }
        typographyVariables.push(
          `$${target}: ${value} !default;`
        );
      }
    }
  }
  typographyVariables.push(
    '// quarto-scss-analysis-annotation { "action": "pop" }'
  );
  return {
    defaults: typographyVariables.join("\n"),
    uses: Array.from(typographyImports).join("\n"),
    functions: "",
    mixins: "",
    rules: ""
  };
};
async function brandSassLayers(fileName, project, nameMap = {}) {
  const brand = await project.resolveBrand(fileName);
  const sassLayers = {
    light: [],
    dark: []
  };
  for (const mode of ["light", "dark"]) {
    if (brand && brand[mode]) {
      sassLayers[mode].push({
        defaults: '$theme: "brand" !default;',
        uses: "",
        functions: "",
        mixins: "",
        rules: ""
      });
    }
  }
  if (brand?.light?.data.color) {
    sassLayers.light.push(brandColorLayer(brand?.light, nameMap));
  }
  if (brand?.dark?.data.color) {
    sassLayers.dark.push(brandColorLayer(brand?.dark, nameMap));
  }
  if (brand?.light?.data.typography) {
    sassLayers.light.push(brandTypographyLayer(brand?.light));
  }
  if (brand?.dark?.data.typography) {
    sassLayers.dark.push(brandTypographyLayer(brand?.dark));
  }
  return sassLayers;
}
async function brandBootstrapSassLayers(fileName, project, nameMap = {}) {
  const layers = await brandSassLayers(
    fileName,
    project,
    nameMap
  );
  const brand = await project.resolveBrand(fileName);
  if (brand?.light?.data?.defaults?.bootstrap) {
    layers.light.unshift(brandDefaultsBootstrapLayer(brand.light));
  }
  if (brand?.dark?.data?.defaults?.bootstrap) {
    layers.dark.unshift(brandDefaultsBootstrapLayer(brand.dark));
  }
  return layers;
}
async function brandRevealSassLayers(input, format14, project) {
  let brandMode = "light";
  if (format14.metadata[kBrandMode] === "dark") {
    brandMode = "dark";
  }
  return (await brandSassLayers(
    input,
    project,
    defaultColorNameMap
  ))[brandMode];
}
async function brandSassFormatExtras(input, format14, project) {
  const htmlSassBundleLayers = await brandBootstrapSassLayers(
    input,
    project,
    defaultColorNameMap
  );
  return {
    html: {
      [kSassBundles]: [
        {
          key: "brand",
          dependency: "bootstrap",
          user: htmlSassBundleLayers.light,
          dark: htmlSassBundleLayers.dark.length ? {
            user: htmlSassBundleLayers.dark,
            default: darkModeDefault(format14)
          } : void 0
        }
      ]
    }
  };
}

// format/html/format-html.ts
init_asserts();

// format/html/format-html-axe.ts
init_format5();
init_types5();
init_resources2();
init_path();
function axeHtmlDependency(options) {
  return {
    name: "quarto-axe",
    head: `<script id="quarto-axe-checker-options" type="text/plain">${encodeBase64(JSON.stringify(options))}<\/script>`,
    scripts: [{
      name: "axe-check.js",
      path: formatResourcePath("html", join4("axe", "axe-check.js")),
      attribs: { type: "module" }
    }]
  };
}
function axeFormatDependencies(format14, options) {
  if (!options) return {};
  const isRevealjs = isRevealjsOutput(format14.pandoc);
  const isDashboard = isHtmlDashboardOutput(format14.identifier["base-format"]);
  const sassDependency = isRevealjs ? "reveal-theme" : "bootstrap";
  const baseRules = `
body div.quarto-axe-report {
  position: fixed;
  bottom: 3rem;
  right: 3rem;
  padding: 1rem;
  border: 1px solid var(--r-main-color, $body-color);
  z-index: 9999;
  background-color: var(--r-background-color, $body-bg);
  color: var(--r-main-color, $body-color);
  max-height: 50vh;
  overflow-y: auto;
}

.quarto-axe-violation-help { padding-left: 0.5rem; }
.quarto-axe-violation-selector { padding-left: 1rem; }
.quarto-axe-violation-target {
  padding: 0.5rem;
  color: $link-color;
  text-decoration: underline;
  cursor: pointer;
}

.quarto-axe-hover-highlight {
  background-color: red;
  border: 2px solid red;
}`;
  const revealjsRules = isRevealjs ? `
.reveal .slides section.quarto-axe-report-slide {
  text-align: left;
  font-size: 0.55em;
  h2 {
    margin-bottom: 0.5em;
    font-size: 1.8em;
  }
  div.quarto-axe-report {
    position: static;
    padding: 0;
    border: none;
    background-color: transparent;
    max-height: none;
    overflow-y: visible;
    z-index: auto;
  }
  .quarto-axe-violation-description {
    margin-top: 0.6em;
    font-weight: bold;
  }
  .quarto-axe-violation-target {
    font-size: 0.9em;
  }
}` : "";
  const dashboardRules = isDashboard ? `
.quarto-dashboard .offcanvas.quarto-axe-offcanvas {
  .quarto-axe-report {
    position: static;
    padding: 0;
    border: none;
    background-color: transparent;
    max-height: none;
    overflow-y: visible;
    z-index: auto;
  }
}
.quarto-dashboard .quarto-axe-toggle {
  position: fixed;
  bottom: 1rem;
  right: 1rem;
  z-index: 1040;
  border-radius: 50%;
  width: 3rem;
  height: 3rem;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.25rem;
}
.quarto-dashboard .quarto-axe-scanning {
  padding: 1rem;
  text-align: center;
  opacity: 0.7;
  font-style: italic;
}` : "";
  return {
    html: {
      [kDependencies]: [
        axeHtmlDependency(options)
      ],
      "sass-bundles": [
        {
          key: "axe",
          dependency: sassDependency,
          user: [{
            uses: "",
            defaults: `
$body-color: #222 !default;
$body-bg: #fff !default;
$link-color: #2a76dd !default;
`,
            functions: "",
            mixins: "",
            rules: baseRules + revealjsRules + dashboardRules
          }]
        }
      ]
    }
  };
}

// format/html/format-html.ts
var esbuildAnalysisCache;
function esbuildCachedAnalysis(input) {
  if (!esbuildAnalysisCache) {
    esbuildAnalysisCache = JSON.parse(
      Deno.readTextFileSync(
        formatResourcePath("html", "esbuild-analysis-cache.json")
      )
    );
  }
  const result2 = esbuildAnalysisCache[input];
  assert7(result2, `Cached analysis not found for ${input}`);
  return result2;
}
function recursiveModuleDependencies(path3) {
  const result2 = [];
  const inpRelPath = relative4(join4(resourcePath("formats"), "html"), path3);
  result2.push({
    name: inpRelPath,
    path: formatResourcePath("html", inpRelPath),
    attribs: { type: "module" }
  });
  const analysis = esbuildCachedAnalysis(inpRelPath);
  for (const [_key, value] of Object.entries(analysis.outputs)) {
    for (const imp of value.imports) {
      if (imp.external) {
        const relPath = relative4(path3, join4(path3, imp.path));
        result2.push({
          name: relPath,
          path: formatResourcePath("html", relPath),
          attribs: { type: "module" }
        });
      }
    }
  }
  return result2;
}
function htmlFormat(figwidth, figheight) {
  return mergeConfigs(
    createHtmlFormat("HTML", figwidth, figheight),
    {
      render: {
        [kNotebookLinks]: true
      },
      resolveFormat: (format14) => {
        if (format14.metadata[kMinimal] === true) {
          if (format14.metadata[kFigResponsive] === void 0) {
            format14.metadata[kFigResponsive] = false;
          }
          if (format14.metadata[kTheme] === void 0) {
            format14.metadata[kTheme] = "none";
          }
        }
      },
      formatExtras: async (input, _markdown, flags, format14, _libDir, services, offset3, project, quiet) => {
        if (!project && format14.metadata[kListing]) {
          warn(
            `Quarto only supports listings within websites. Please ensure that the file ${input} is a part of a website project to enable listing rendering.`
          );
        }
        const htmlFilterParams = htmlFormatFilterParams(format14);
        return mergeConfigs(
          await htmlFormatExtras(
            input,
            flags,
            offset3,
            format14,
            services.temp,
            project
          ),
          themeFormatExtras(
            input,
            flags,
            format14,
            services,
            offset3,
            project,
            quiet
          ),
          await brandSassFormatExtras(input, format14, project),
          { [kFilterParams]: htmlFilterParams }
        );
      },
      extensions: {
        book: {
          multiFile: true
        }
      }
    }
  );
}
async function htmlFormatExtras(input, _flags, offset3, format14, temp, _project, featureDefaults, tippyOptions, scssOptions) {
  const configurableExtras = [
    axeFormatDependencies(format14, format14.metadata[kAxe])
  ];
  const bootstrap = formatHasBootstrap(format14);
  if (!featureDefaults) {
    featureDefaults = htmlFormatFeatureDefaults(format14);
  }
  if (!tippyOptions) {
    tippyOptions = {};
  }
  if (!tippyOptions.config) {
    tippyOptions.config = {};
  }
  if (!scssOptions) {
    scssOptions = {};
  }
  if (scssOptions.quartoBase === void 0) {
    scssOptions.quartoBase = true;
  }
  if (scssOptions.quartoCssVars === void 0) {
    scssOptions.quartoCssVars = true;
  }
  const scripts = [];
  const stylesheets = [];
  const sassBundles = [];
  const dependencies = [];
  const options = isObject(format14.metadata[kComments]) ? {
    [kHypothesis]: format14.metadata[kComments][kHypothesis] || false,
    [kUtterances]: format14.metadata[kComments][kUtterances] || false,
    [kGiscus]: format14.metadata[kComments][kGiscus] || false
  } : {};
  options.codeLink = format14.metadata[kCodeLink] || false;
  if (featureDefaults.tabby) {
    options.tabby = format14.metadata[kTabsets] !== false;
  } else {
    options.tabby = format14.metadata[kTabsets] || false;
  }
  if (featureDefaults.copyCode) {
    options.copyCode = format14.metadata[kCodeCopy] !== false;
  } else {
    options.copyCode = format14.metadata[kCodeCopy] || false;
  }
  if (featureDefaults.anchors) {
    options.anchors = format14.metadata[kAnchorSections] !== false;
  } else {
    options.anchors = format14.metadata[kAnchorSections] || false;
  }
  if (featureDefaults.hoverCitations) {
    options.hoverCitations = format14.metadata[kCitationsHover] !== false;
  } else {
    options.hoverCitations = format14.metadata[kCitationsHover] || false;
  }
  if (featureDefaults.hoverFootnotes) {
    options.hoverFootnotes = format14.metadata[kFootnotesHover] !== false;
  } else {
    options.hoverFootnotes = format14.metadata[kFootnotesHover] || false;
  }
  if (featureDefaults.hoverXrefs) {
    options.hoverXrefs = format14.metadata[kXrefsHover] !== false;
  } else {
    options.hoverXrefs = format14.metadata[kXrefsHover] || false;
  }
  if (featureDefaults.figResponsive) {
    options.figResponsive = format14.metadata[kFigResponsive] !== false;
  } else {
    options.figResponsive = format14.metadata[kFigResponsive] || false;
  }
  if (featureDefaults.codeAnnotations) {
    options.codeAnnotations = format14.metadata[kCodeAnnotations] || true;
  } else {
    options.codeAnnotations = format14.metadata[kCodeAnnotations] || false;
  }
  options.zenscroll = format14.metadata[kSmoothScroll];
  options.codeTools = formatHasCodeTools(format14);
  options.darkMode = formatDarkMode(format14);
  options.darkModeDefault = darkModeDefault(format14);
  options.respectUserColorScheme = format14.metadata[kRespectUserColorScheme] || false;
  options.linkExternalIcon = format14.render[kLinkExternalIcon];
  options.linkExternalNewwindow = format14.render[kLinkExternalNewwindow];
  options.linkExternalFilter = format14.render[kLinkExternalFilter];
  const siteMetadata = format14.metadata[kWebsite];
  if (!options.linkExternalFilter && siteMetadata) {
    const siteUrl2 = siteMetadata[kSiteUrl];
    if (siteUrl2) {
      options.linkExternalFilter = siteUrl2.replaceAll(".", "\\.").replaceAll(
        "/",
        "\\/"
      );
    }
  }
  if (bootstrap) {
    const deps = recursiveModuleDependencies(
      formatResourcePath("html", "quarto.js")
    );
    scripts.push(...deps);
  }
  if (options.tabby) {
    scripts.push({
      name: "tabby.min.js",
      path: formatResourcePath("html", join4("tabby", "js", "tabby.js"))
    });
  }
  const includeInHeader = [];
  if (options.zenscroll) {
    scripts.push({
      name: "zenscroll-min.js",
      path: formatResourcePath("html", join4("zenscroll", "zenscroll-min.js")),
      afterBody: true
    });
    const zenscrollStyle = temp.createFile({ suffix: "-zen.html" });
    Deno.writeTextFileSync(
      zenscrollStyle,
      "<style>html{ scroll-behavior: smooth; }</style>"
    );
    includeInHeader.push(zenscrollStyle);
  }
  options.tippy = options.hoverCitations || options.hoverFootnotes || options.codeAnnotations || options.hoverXrefs;
  if (bootstrap || options.tippy) {
    scripts.push({
      name: "popper.min.js",
      path: formatResourcePath("html", join4("popper", "popper.min.js"))
    });
  }
  if (options.tippy) {
    scripts.push({
      name: "tippy.umd.min.js",
      path: formatResourcePath("html", join4("tippy", "tippy.umd.min.js"))
    });
    stylesheets.push({
      name: "tippy.css",
      path: formatResourcePath("html", join4("tippy", "tippy.css"))
    });
    if (tippyOptions.theme === void 0) {
      if (bootstrap) {
        tippyOptions.theme = "quarto";
        sassBundles.push({
          key: "tippy.scss",
          dependency: kBootstrapDependencyName,
          quarto: {
            uses: "",
            functions: "",
            defaults: "",
            mixins: "",
            rules: Deno.readTextFileSync(
              formatResourcePath("html", join4("tippy", "_tippy.scss"))
            )
          }
        });
      } else {
        tippyOptions.theme = "light-border";
        stylesheets.push({
          name: "light-border.css",
          path: formatResourcePath("html", join4("tippy", "light-border.css"))
        });
      }
    }
  }
  options.tippyOptions = tippyOptions;
  if (options.copyCode) {
    dependencies.push(clipboardDependency());
  }
  options.language = format14.language;
  if (options.anchors) {
    scripts.push({
      name: "anchor.min.js",
      path: formatResourcePath("html", join4("anchor", "anchor.min.js"))
    });
    options.anchors = typeof options.anchors === "string" ? options.anchors : true;
  }
  const minimal = format14.metadata[kMinimal] === true;
  if (!bootstrap && !minimal) {
    if (scssOptions.quartoBase) {
      sassBundles.push({
        dependency: kQuartoHtmlDependency,
        key: kQuartoHtmlDependency,
        quarto: quartoBaseLayer(
          format14,
          !!options.copyCode,
          !!options.tabby,
          !!options.figResponsive
        )
      });
    }
    if (scssOptions.quartoCssVars) {
      sassBundles.push({
        dependency: kQuartoHtmlDependency,
        key: kQuartoHtmlDependency,
        quarto: {
          uses: "",
          defaults: "",
          functions: "",
          mixins: "",
          rules: quartoGlobalCssVariableRules()
        }
      });
    }
  }
  if (options.hypothesis) {
    const hypothesisHeader = temp.createFile({ suffix: "-hypoth.html" });
    Deno.writeTextFileSync(
      hypothesisHeader,
      renderEjs(
        formatResourcePath("html", join4("hypothesis", "hypothesis.ejs")),
        { hypothesis: options.hypothesis }
      )
    );
    includeInHeader.push(hypothesisHeader);
  }
  const includeBeforeBody = [];
  const includeAfterBody = [];
  const quartoHtmlRequired = Object.keys(options).some(
    (option) => !!options[option]
  );
  if (quartoHtmlRequired) {
    for (const { dest, ejsfile } of [
      { dest: includeBeforeBody, ejsfile: "quarto-html-before-body.ejs" },
      { dest: includeAfterBody, ejsfile: "quarto-html-after-body.ejs" }
    ]) {
      const quartoHtmlScript = temp.createFile();
      const renderedHtml = renderEjs(
        formatResourcePath("html", join4("templates", ejsfile)),
        options
      );
      if (renderedHtml.trim() !== "") {
        Deno.writeTextFileSync(quartoHtmlScript, renderedHtml);
        dest.push(quartoHtmlScript);
      }
    }
  }
  if (options.utterances) {
    if (typeof options.utterances !== "object") {
      throw new Error("Invalid utterances configuration (must provide a repo");
    }
    const utterances = options.utterances;
    if (!utterances["repo"]) {
      throw new Error("Invalid utterances coniguration (must provide a repo)");
    }
    utterances["issue-term"] = utterances["issue-term"] || "pathname";
    utterances["theme"] = utterances["theme"] || "github-light";
    const utterancesAfterBody = temp.createFile({ suffix: "-utter.html" });
    Deno.writeTextFileSync(
      utterancesAfterBody,
      renderEjs(
        formatResourcePath("html", join4("utterances", "utterances.ejs")),
        { utterances }
      )
    );
    includeAfterBody.push(utterancesAfterBody);
  }
  if (options.giscus) {
    const giscus = options.giscus;
    giscus.category = giscus.category || "General";
    giscus.theme = giscus.theme || "";
    const themeToggleRecord = buildGiscusThemeKeys(
      Boolean(options.darkModeDefault),
      giscus.theme
    );
    giscus.baseTheme = themeToggleRecord.baseTheme;
    giscus.altTheme = themeToggleRecord.altTheme;
    giscus.theme = giscus.baseTheme;
    giscus.mapping = giscus.mapping || "title";
    giscus["reactions-enabled"] = giscus["reactions-enabled"] !== void 0 ? giscus["reactions-enabled"] : true;
    giscus["input-position"] = giscus["input-position"] || "top";
    giscus.language = giscus.language || "en";
    if (giscus[kGiscusRepoId] === void 0 || giscus[kGiscusCategoryId] === void 0) {
      const discussionData = await getGithubDiscussionsMetadata(
        giscus.repo
      );
      if (giscus[kGiscusRepoId] === void 0 && discussionData.repositoryId) {
        giscus[kGiscusRepoId] = discussionData.repositoryId;
      }
      const categoryId = getDiscussionCategoryId(
        giscus.category,
        discussionData
      );
      if (giscus[kGiscusCategoryId] === void 0 && categoryId) {
        giscus[kGiscusCategoryId] = categoryId;
      }
    }
    const giscusAfterBody = temp.createFile({ suffix: "-giscus.html" });
    Deno.writeTextFileSync(
      giscusAfterBody,
      renderEjs(
        formatResourcePath("html", join4("giscus", "giscus.ejs")),
        { giscus, darkMode: options.darkMode }
      )
    );
    includeAfterBody.push(giscusAfterBody);
  }
  dependencies.push({
    name: kQuartoHtmlDependency,
    scripts,
    stylesheets
  });
  const templateDir = formatResourcePath("html", "pandoc");
  const partials = [
    "metadata.html",
    "title-block.html",
    "toc.html",
    "styles.html"
  ];
  const templateContext = {
    template: join4(templateDir, "template.html"),
    partials: partials.map((partial) => join4(templateDir, partial))
  };
  const htmlPostProcessors = [
    htmlFormatPostprocessor(format14, featureDefaults),
    metadataPostProcessor(input, format14, offset3)
  ];
  const viewStyle = format14.render[kNotebookViewStyle];
  if (viewStyle === kNotebookViewStyleNotebook) {
    htmlPostProcessors.push(notebookViewPostProcessor());
  }
  const metadata = {};
  const result2 = {
    [kIncludeInHeader]: includeInHeader,
    [kIncludeBeforeBody]: includeBeforeBody,
    [kIncludeAfterBody]: includeAfterBody,
    metadata,
    templateContext,
    html: {
      [kDependencies]: dependencies,
      [kSassBundles]: sassBundles,
      [kHtmlPostprocessors]: htmlPostProcessors
    }
  };
  return mergeConfigs(
    result2,
    ...configurableExtras
  );
}
var kFormatHasBootstrap = "has-bootstrap";
function htmlFormatFilterParams(format14) {
  return {
    [kFormatHasBootstrap]: formatHasBootstrap(format14)
  };
}
function htmlFormatFeatureDefaults(format14) {
  const bootstrap = formatHasBootstrap(format14);
  const minimal = format14.metadata[kMinimal] === true;
  return {
    tabby: !minimal && !bootstrap,
    copyCode: !minimal,
    anchors: !minimal,
    hoverCitations: !minimal,
    hoverFootnotes: !minimal,
    figResponsive: !minimal,
    codeAnnotations: !minimal,
    hoverXrefs: !minimal
  };
}
function htmlFormatPostprocessor(format14, featureDefaults) {
  const haveBootstrap = formatHasBootstrap(format14);
  if (!featureDefaults) {
    featureDefaults = htmlFormatFeatureDefaults(format14);
  }
  const codeCopy = featureDefaults.copyCode ? format14.metadata[kCodeCopy] !== false : format14.metadata[kCodeCopy] || false;
  const anchors = featureDefaults.anchors ? format14.metadata[kAnchorSections] !== false : format14.metadata[kAnchorSections] || false;
  return (doc) => {
    if (format14.render[kBodyClasses]) {
      const clz = format14.render[kBodyClasses].split(" ");
      clz.forEach((cls) => {
        doc.body.classList.add(cls);
      });
    }
    const codeBlocks = doc.querySelectorAll("pre.sourceCode");
    const EmbedSourceModal = doc.querySelector(
      `#${kEmbeddedSourceModalId}`
    );
    for (let i6 = 0; i6 < codeBlocks.length; i6++) {
      const code5 = codeBlocks[i6];
      const parentHoist = (clz) => {
        if (code5.classList.contains(clz)) {
          code5.classList.remove(clz);
          code5.parentElement?.classList.add(clz);
        }
      };
      parentHoist("cell-code");
      parentHoist("hidden");
      if (code5.classList.contains("hidden")) {
        code5.classList.remove("hidden");
        code5.parentElement?.classList.add("hidden");
      }
      if (codeCopy) {
        const outerScaffold = doc.createElement("div");
        outerScaffold.classList.add("code-copy-outer-scaffold");
        const copyButton = createCodeCopyButton(doc, format14);
        if (EmbedSourceModal && EmbedSourceModal.contains(code5)) {
          copyButton.setAttribute("data-in-quarto-modal", "");
        }
        code5.classList.add("code-with-copy");
        const sourceCodeDiv = code5.parentElement;
        const sourceCodeDivParent = code5.parentElement?.parentElement;
        sourceCodeDivParent.replaceChild(outerScaffold, sourceCodeDiv);
        outerScaffold.appendChild(sourceCodeDiv);
        outerScaffold.appendChild(copyButton);
      }
      if (code5.parentElement?.getAttribute("data-code-preview")) {
        const codeExample = doc.createElement("iframe");
        for (const parentClass of code5.classList) {
          codeExample.classList.add(parentClass);
        }
        codeExample.setAttribute(
          "src",
          code5.parentElement.getAttribute("data-code-preview").replace(
            /\.qmd$/,
            ".html"
          )
        );
        code5.parentElement.removeAttribute(
          "data-code-preview"
        );
        code5.parentElement.appendChild(codeExample);
      }
    }
    if (anchors) {
      const container = haveBootstrap ? doc.querySelector("main") : doc.querySelector("body");
      if (container) {
        ["h2", "h3", "h4", "h5", "h6", ".quarto-figure[id]", "div[id^=tbl-]"].forEach(
          (selector) => {
            const headings = container.querySelectorAll(selector);
            for (let i6 = 0; i6 < headings.length; i6++) {
              const heading = headings[i6];
              if (heading.id !== "toc-title") {
                if (!heading.classList.contains("no-anchor")) {
                  heading.classList.add("anchored");
                }
              }
            }
          }
        );
      }
    }
    const headerSections = doc.querySelectorAll(".header-section-number");
    for (let i6 = 0; i6 < headerSections.length; i6++) {
      const secNumber = headerSections[i6];
      const prevElement = secNumber.previousElementSibling;
      if (prevElement && prevElement.classList.contains("toc-section-number")) {
        secNumber.remove();
      }
    }
    processCodeAnnotations(format14, doc);
    const tables2 = doc.querySelectorAll(
      'table[data-quarto-postprocess="true"]'
    );
    for (let i6 = 0; i6 < tables2.length; ++i6) {
      const table = tables2[i6];
      if (table.getAttribute("data-quarto-disable-processing") === "true") {
        continue;
      }
      table.removeAttribute("data-quarto-postprocess");
      table.removeAttribute("data-quarto-disable-processing");
      table.querySelectorAll("tr").forEach((tr) => {
        const { children } = tr;
        for (let j3 = 0; j3 < children.length; ++j3) {
          const child = children[j3];
          if (child.tagName === "TH" || child.tagName === "TD") {
            const isTH = child.getAttribute("data-quarto-table-cell-role") === "th";
            const newElement = doc.createElement(isTH ? "th" : "td");
            while (child.firstChild) {
              newElement.appendChild(child.firstChild);
            }
            for (let k3 = 0; k3 < child.attributes.length; ++k3) {
              const attr = child.attributes[k3];
              newElement.setAttribute(attr.name, attr.value);
            }
            child.parentNode?.replaceChild(newElement, child);
          }
        }
      });
    }
    const metadraftEl = doc.querySelector("meta[name='quarto:status']");
    if (metadraftEl !== null) {
      const status = metadraftEl.getAttribute("content");
      if (status === "draft") {
        const draftDivEl = doc.createElement("DIV");
        const iconEl = doc.createElement("I");
        iconEl.classList.add("bi");
        iconEl.classList.add("bi-pencil-square");
        const textNode = doc.createTextNode(format14.language.draft || "Draft");
        draftDivEl.appendChild(iconEl);
        draftDivEl.appendChild(textNode);
        draftDivEl.setAttribute("id", "quarto-draft-alert");
        draftDivEl.classList.add("alert");
        draftDivEl.classList.add("alert-warning");
        let targetEl = doc.body;
        const headerEl = doc.getElementById("quarto-header");
        if (headerEl !== null) {
          targetEl = headerEl;
        }
        targetEl.insertBefore(draftDivEl, targetEl.firstChild);
      }
    }
    return Promise.resolve(kHtmlEmptyPostProcessResult);
  };
}
var kCodeCellAttr = "data-code-cell";
var kCodeLinesAttr = "data-code-lines";
var kCodeAnnotationAttr = "data-code-annotation";
var kCodeCellTargetAttr = "data-target-cell";
var kCodeAnnotationTargetAttr = "data-target-annotation";
var kCodeAnnotationHiddenClz = "code-annotation-container-hidden";
var kCodeAnnotationGridClz = "code-annotation-container-grid";
var kCodeAnnotationAnchorClz = "code-annotation-anchor";
var kCodeAnnotationTargetClz = "code-annotation-target";
var kCodeAnnotationParentClz = "code-annotated";
var kCodeAnnotationGutterClz = "code-annotation-gutter";
var kCodeAnnotationGutterBgClz = "code-annotation-gutter-bg";
function processCodeAnnotations(format14, doc) {
  const annotationStyle = format14.metadata[kCodeAnnotations];
  const replaceLineNumberWithAnnote = (annoteEl, dtEl) => {
    const annotation = annoteEl.getAttribute(kCodeAnnotationAttr);
    if (annotation !== null) {
      const ddEl = dtEl.previousElementSibling;
      if (ddEl) {
        ddEl.innerHTML = "";
        ddEl.innerText = annotation;
        const codeCell = annoteEl.getAttribute(kCodeCellAttr);
        if (codeCell) {
          ddEl.setAttribute(kCodeCellTargetAttr, codeCell);
          ddEl.setAttribute(kCodeAnnotationTargetAttr, annotation);
        }
      }
    }
  };
  if (annotationStyle === false) {
    const annoteNodes = doc.querySelectorAll(`span[${kCodeCellAttr}]`);
    for (const annoteNode of annoteNodes) {
      const annoteEl = annoteNode;
      const parentDL = annoteEl.parentElement?.parentElement;
      if (parentDL && !parentDL.classList.contains(kCodeAnnotationHiddenClz)) {
        parentDL.classList.add(kCodeAnnotationHiddenClz);
      }
    }
  } else if (annotationStyle === "hover" || annotationStyle === "select") {
    const definitionLists = processCodeBlockAnnotation(
      doc,
      true,
      "start",
      replaceLineNumberWithAnnote
    );
    Object.values(definitionLists).forEach((dl) => {
      dl.classList.add(kCodeAnnotationHiddenClz);
      dl.classList.add(kCodeAnnotationGridClz);
    });
  } else {
    const definitionLists = processCodeBlockAnnotation(
      doc,
      false,
      "start",
      replaceLineNumberWithAnnote
    );
    Object.values(definitionLists).forEach((dl) => {
      dl.classList.add(kCodeAnnotationGridClz);
    });
  }
}
function processCodeBlockAnnotation(doc, interactiveAnnotations, annotationPosition, processDt) {
  const definitionLists = {};
  const codeBlockParents = [];
  const annoteNodes = doc.querySelectorAll(`span[${kCodeCellAttr}]`);
  for (const annoteNode of annoteNodes) {
    const annoteEl = annoteNode;
    const parentCodeBlock = processLineAnnotation(
      doc,
      annoteEl,
      interactiveAnnotations,
      annotationPosition
    );
    if (parentCodeBlock && !codeBlockParents.includes(parentCodeBlock)) {
      codeBlockParents.push(parentCodeBlock);
    }
    const parentDL = annoteEl.parentElement?.parentElement;
    const codeParentDivId = parentCodeBlock?.parentElement?.parentElement?.id;
    if (parentDL && codeParentDivId && !Object.keys(definitionLists).includes(codeParentDivId)) {
      definitionLists[codeParentDivId] = parentDL;
    }
    if (annoteEl.parentElement && processDt) {
      processDt(annoteEl, annoteEl.parentElement);
    }
  }
  for (const codeParentEl of codeBlockParents) {
    if (codeParentEl.parentElement) {
      codeParentEl.parentElement.classList.add(kCodeAnnotationParentClz);
    }
    const gutterBgDivEl = doc.createElement("div");
    gutterBgDivEl.classList.add(kCodeAnnotationGutterBgClz);
    codeParentEl?.appendChild(gutterBgDivEl);
    const gutterDivEl = doc.createElement("div");
    gutterDivEl.classList.add(kCodeAnnotationGutterClz);
    codeParentEl?.appendChild(gutterDivEl);
  }
  return definitionLists;
}
function processLineAnnotation(doc, annoteEl, interactive, position) {
  const targetCell = annoteEl.getAttribute(kCodeCellAttr);
  const targetLines = annoteEl.getAttribute(kCodeLinesAttr);
  const targetAnnotation = annoteEl.getAttribute(kCodeAnnotationAttr);
  if (targetCell && targetLines) {
    const lineArr = targetLines?.split(",");
    const targetIndex = position === "start" ? 0 : Math.floor(lineArr.length / 2);
    const line = lineArr[targetIndex];
    const targetId = `${targetCell}-${line}`;
    const targetEl = doc.getElementById(targetId);
    if (targetEl) {
      const annoteAnchorEl = doc.createElement(interactive ? "button" : "a");
      annoteAnchorEl.classList.add(kCodeAnnotationAnchorClz);
      annoteAnchorEl.setAttribute(
        kCodeCellTargetAttr,
        `${targetCell}`
      );
      annoteAnchorEl.setAttribute(
        kCodeAnnotationTargetAttr,
        `${targetAnnotation}`
      );
      if (!interactive) {
        annoteAnchorEl.setAttribute("onclick", "event.preventDefault();");
      }
      annoteAnchorEl.innerText = targetAnnotation || "?";
      targetEl.parentElement?.insertBefore(annoteAnchorEl, targetEl);
      targetEl.classList.add(kCodeAnnotationTargetClz);
      return targetEl.parentElement;
    }
  }
}
function themeFormatExtras(input, flags, format14, sevices, offset3, project, quiet) {
  const theme = format14.metadata[kTheme];
  if (theme === "none") {
    return {
      metadata: {
        [kDocumentCss]: false
      }
    };
  } else if (theme === "pandoc") {
    return pandocExtras(format14);
  } else {
    return bootstrapExtras(
      input,
      flags,
      format14,
      sevices,
      offset3,
      project,
      quiet
    );
  }
}
function pandocExtras(format14) {
  const maxWidth = format14.metadata["max-width"];
  const headerIncludes = maxWidth ? `<style type="text/css">body { max-width: ${asCssSize(maxWidth)};}</style>` : void 0;
  return {
    metadata: {
      [kDocumentCss]: true,
      [kHeaderIncludes]: headerIncludes
    }
  };
}
registerWriterFormatHandler((format14) => {
  switch (format14) {
    case "html":
    case "html4":
    case "html5":
      return {
        format: htmlFormat(7, 5)
      };
  }
});

// format/reveal/format-reveal.ts
init_path();
init_deno_dom();
init_constants6();
init_types5();
init_config2();
init_resources2();
init_html();
init_formats_shared();
init_pandoc_formats();

// format/reveal/format-reveal-plugin.ts
init_fs();
init_path();
init_constants6();
init_log();
init_types5();
init_config2();
init_path2();
init_resources2();

// format/reveal/metadata.ts
init_config2();

// format/reveal/constants.ts
var kRevealJsUrl = "revealjs-url";
var kRevealJsConfig = "revealjs-config";
var kSlideLogo = "logo";
var kSlideFooter = "footer";
var kHashType = "hash-type";
var kScrollable = "scrollable";
var kCenter = "center";
var kCenterTitleSlide = "center-title-slide";
var kControlsAuto = "controlsAuto";
var kPreviewLinksAuto = "previewLinksAuto";
var kPdfMaxPagesPerSlide = "pdfMaxPagesPerSlide";
var kPdfSeparateFragments = "pdfSeparateFragments";
var kAutoAnimateEasing = "autoAnimateEasing";
var kAutoAnimateDuration = "autoAnimateDuration";
var kAutoAnimateUnmatched = "autoAnimateUnmatched";
var kAutoStretch = "auto-stretch";
var kCodeBlockHeight = "code-block-height";
var kJumpToSlide = "jumpToSlide";
var kScrollView = "scroll-view";
var kView = "view";
var kScrollProgress = "scrollProgress";
var kScrollSnap = "scrollSnap";
var kScrollActivationWidth = "scrollActivationWidth";
var kScrollLayout = "scrollLayout";
var kScrollProgressAuto = "scrollProgressAuto";

// format/reveal/metadata.ts
function optionsToKebab(options) {
  return options.reduce(
    (options2, option) => {
      const kebab = camelToKebab(option);
      if (kebab !== option) {
        options2.push(kebab);
      }
      return options2;
    },
    []
  );
}
function revealMetadataFilter(metadata, kebabOptions = kRevealKebabOptions) {
  const mappingExceptions = {
    "fragment-in-url": "fragmentInURL"
  };
  const filtered = {};
  Object.keys(metadata).forEach((key) => {
    const value = metadata[key];
    if (kebabOptions.includes(key)) {
      const camel = mappingExceptions[key] || kebabToCamel(key);
      filtered[camel] = value;
    } else {
      filtered[key] = value;
    }
  });
  return filtered;
}
var kRevealOptions = [
  "controls",
  "controlsTutorial",
  "controlsLayout",
  "controlsBackArrows",
  "progress",
  "slideNumber",
  "showSlideNumber",
  "hash",
  "hashOneBasedIndex",
  "respondToHashChanges",
  "history",
  "keyboard",
  "overview",
  "disableLayout",
  "center",
  "touch",
  "loop",
  "rtl",
  "navigationMode",
  "shuffle",
  "fragments",
  "fragmentInURL",
  "embedded",
  "help",
  "pause",
  "showNotes",
  "autoPlayMedia",
  "preloadIframes",
  "autoAnimate",
  "autoAnimateMatcher",
  kAutoAnimateEasing,
  kAutoAnimateDuration,
  kAutoAnimateUnmatched,
  "autoAnimateStyles",
  "autoSlide",
  "autoSlideStoppable",
  "autoSlideMethod",
  "defaultTiming",
  "mouseWheel",
  "display",
  "hideInactiveCursor",
  "hideCursorTime",
  "previewLinks",
  "transition",
  "transitionSpeed",
  "backgroundTransition",
  "viewDistance",
  "mobileViewDistance",
  "parallaxBackgroundImage",
  "parallaxBackgroundSize",
  "parallaxBackgroundHorizontal",
  "parallaxBackgroundVertical",
  "width",
  "height",
  "margin",
  "minScale",
  "maxScale",
  "mathjax",
  kPdfMaxPagesPerSlide,
  kPdfSeparateFragments,
  "pdfPageHeightOffset",
  kJumpToSlide,
  kView,
  kScrollProgress,
  kScrollSnap,
  kScrollLayout,
  kScrollActivationWidth
];
var kRevealKebabOptions = optionsToKebab(kRevealOptions);

// format/reveal/format-reveal-multiplex.ts
init_fs();
init_path();
init_constants6();
init_path2();
init_resources2();
init_text2();
var kRevealJsMultiplex = "multiplex";
function revealMultiplexPlugin(format14) {
  if (format14.metadata[kRevealJsMultiplex]) {
    return formatResourcePath("revealjs", join4("plugins", "multiplex"));
  } else {
    return void 0;
  }
}
function revealMuliplexPreviewFile(file) {
  const speakerFile = revealSpeakerOutput(file);
  if (existsSync2(speakerFile) && existsSync2(file)) {
    const modTime = Deno.statSync(file).mtime;
    const speakerModTime = Deno.statSync(speakerFile).mtime;
    if (modTime && speakerModTime && speakerModTime > modTime) {
      return speakerFile;
    }
  }
  return file;
}
function revealMultiplexExtras(format14, flags) {
  if (format14.metadata[kRevealJsMultiplex]) {
    return {
      postprocessors: [async (output) => {
        const token = await revealMultiplexToken(format14, output);
        const content = await Deno.readTextFile(output);
        const speakerContent = withMultiplexToken(content, token);
        token.secret = null;
        const clientContent = withMultiplexToken(content, token).replace(
          /(\/\/ reveal\.js plugins\n\s*plugins: \[[^\[]+?)(RevealNotes,)([^\[]+?\])/,
          "$1$3"
        );
        await Deno.writeTextFile(output, clientContent);
        const speakerOutput = revealSpeakerOutput(output);
        await Deno.writeTextFile(speakerOutput, speakerContent);
        const selfContained = isSelfContainedOutput(
          flags,
          format14,
          speakerOutput
        );
        if (selfContained) {
          await pandocIngestSelfContainedContent(
            speakerOutput,
            format14.pandoc[kResourcePath]
          );
        }
      }]
    };
  } else {
    return void 0;
  }
}
function revealSpeakerOutput(output) {
  const [dir, stem] = dirAndStem(output);
  return join4(dir, `${stem}-speaker.html`);
}
var kDefaultMultiplexUrl = "https://multiplex.up.railway.app/";
async function revealMultiplexToken(format14, output) {
  const multiplex = format14.metadata[kRevealJsMultiplex];
  if (typeof multiplex === "object" && typeof multiplex.secret === "string" && typeof multiplex.id === "string") {
    multiplex.url = multiplex.url || kDefaultMultiplexUrl;
    return multiplex;
  }
  const speakerOutput = revealSpeakerOutput(output);
  if (existsSync2(speakerOutput)) {
    const speakerContent = await Deno.readTextFile(speakerOutput);
    const initPos = speakerContent.lastIndexOf("Reveal.initialize({");
    if (initPos !== -1) {
      const initLines = lines(speakerContent.substring(initPos));
      const kMultiplexStart = "'multiplex': {";
      const kMultiplexEnd = "},";
      for (const line of initLines) {
        if (line.startsWith(kMultiplexStart) && line.endsWith(kMultiplexEnd)) {
          const multiplexJson = "{ " + line.substring(
            kMultiplexStart.length,
            line.length - kMultiplexEnd.length
          ) + " }";
          const multiplex2 = JSON.parse(multiplexJson);
          if (!!multiplex2.id && !!multiplex2.secret) {
            return multiplex2;
          }
        }
      }
    }
  }
  const url = typeof multiplex === "object" ? multiplex.url || kDefaultMultiplexUrl : kDefaultMultiplexUrl;
  try {
    const response = await fetch(pathWithForwardSlashes(join4(url, "token")));
    const jsonData = await response.json();
    const multiplex2 = {
      secret: jsonData.secret,
      id: jsonData.socketId,
      url
    };
    return multiplex2;
  } catch (e5) {
    if (!(e5 instanceof Error)) {
      throw e5;
    }
    throw Error(
      "Error attempting to provision multiplex token from '" + url + "': " + e5.message
    );
  }
}
function withMultiplexToken(content, token) {
  return content.replace(
    /(Reveal.initialize\({[\s\S]*?'multiplex': )({.*?},)/g,
    `$1${JSON.stringify(token)},`
  );
}

// format/reveal/format-reveal-plugin.ts
init_validated_yaml2();
init_copy5();
init_constants12();
await init_extension();
var kRevealjsPlugins = "revealjs-plugins";
var kRevealSlideTone = "slide-tone";
var kRevealMenu = "menu";
var kRevealChalkboard = "chalkboard";
var kRevealPluginOptions = [
  // reveal.js-menu
  "side",
  "width",
  "numbers",
  "titleSelector",
  "useTextContentForMissingTitles",
  "hideMissingTitles",
  "markers",
  "custom",
  "themes",
  "themesPath",
  "transitions",
  "openButton",
  "openSlideNumber",
  "keyboard",
  "sticky",
  "autoOpen",
  "delayInit",
  "openOnInit",
  "loadIcons",
  // reveal.js-chalkboard
  "boardmarkerWidth",
  "chalkWidth",
  "chalkEffect",
  "storage",
  "src",
  "readOnly",
  "transition",
  "theme",
  "background",
  "grid",
  "eraser",
  "boardmarkers",
  "chalks",
  "rememberColor",
  // reveal-pdfexport
  "pdfExportShortcut"
];
var kRevealPluginKebabOptions = optionsToKebab(kRevealPluginOptions);
function isPluginBundle(plugin) {
  return plugin.plugin !== void 0;
}
async function revealPluginExtras(input, format14, flags, temp, revealUrl, revealDestDir, extensionContext, project) {
  const pluginsDestDir = join4(revealDestDir, "plugin");
  const register2 = [];
  const scripts = [];
  const stylesheets = [];
  const config2 = {};
  const metadata = [];
  const dependencies = [];
  const pluginBundles = [
    {
      plugin: formatResourcePath("revealjs", join4("plugins", "line-highlight"))
    },
    { plugin: formatResourcePath("revealjs", join4("plugins", "pdfexport")) }
  ];
  const menuPlugin = revealMenuPlugin(format14);
  if (menuPlugin) {
    pluginBundles.push(menuPlugin);
  }
  const chalkboardPlugiln = revealChalkboardPlugin(format14);
  if (chalkboardPlugiln) {
    pluginBundles.push(chalkboardPlugiln);
  }
  const tonePlugin = revealTonePlugin(format14);
  if (tonePlugin) {
    dependencies.push(toneDependency());
    pluginBundles.push(tonePlugin);
  }
  const multiplexPlugin = revealMultiplexPlugin(format14);
  if (multiplexPlugin) {
    pluginBundles.push(multiplexPlugin);
  }
  const resolvePluginPath = async (plugin) => {
    let extensions2 = await extensionContext?.find(
      plugin,
      input,
      kRevealJSPlugins,
      project?.config,
      project?.dir
    ) || [];
    extensions2 = filterExtensions(
      extensions2 || [],
      plugin,
      "revealjs-plugins"
    );
    if (extensions2.length > 0) {
      return extensions2[0].contributes[kRevealJSPlugins] || [];
    } else {
      return [plugin];
    }
  };
  const resolvePlugin = async (plugin) => {
    if (typeof plugin === "string") {
      if (existsSync2(plugin)) {
        return [plugin];
      } else {
        return await resolvePluginPath(plugin);
      }
    } else {
      if (isPluginBundle(plugin)) {
        const path3 = plugin.plugin;
        const resolvedPlugins = await resolvePluginPath(path3);
        const pluginBundles2 = resolvedPlugins.map(
          (resolvedPlug) => {
            if (typeof resolvedPlug === "string") {
              return {
                plugin: resolvedPlug,
                config: plugin.config
              };
            } else if (isPluginBundle(resolvedPlug)) {
              return {
                plugin: resolvedPlug.plugin,
                config: mergeConfigs(
                  plugin.config,
                  resolvedPlug.config
                )
              };
            } else {
              return plugin;
            }
          }
        );
        return pluginBundles2;
      } else {
        return Promise.resolve([plugin]);
      }
    }
  };
  if (Array.isArray(format14.metadata[kRevealjsPlugins])) {
    for (const plugin of format14.metadata[kRevealJSPlugins]) {
      const resolvedPlugins = await resolvePlugin(plugin);
      pluginBundles.push(...resolvedPlugins);
    }
  }
  pluginBundles.push(
    { plugin: formatResourcePath("revealjs", join4("plugins", "support")) }
  );
  for (let bundle2 of pluginBundles) {
    if (typeof bundle2 === "string") {
      bundle2 = {
        plugin: bundle2
      };
    }
    const plugin = isPluginBundle(bundle2) ? await pluginFromBundle(bundle2) : bundle2;
    if (isSelfContained(flags, format14)) {
      if (plugin[kSelfContained] === false) {
        throw new Error(
          "Reveal plugin '" + plugin.name + " is not compatible with self-contained output"
        );
      }
    }
    if (plugin.register !== false) {
      register2.push(plugin.name);
    }
    const pluginUrl = pathWithForwardSlashes(
      join4(revealUrl, "plugin", camelToKebab(plugin.name))
    );
    const pluginDir = join4(pluginsDestDir, camelToKebab(plugin.name));
    if (isPluginBundle(bundle2)) {
      copyMinimal(bundle2.plugin, pluginDir);
    } else {
      ensureDirSync(pluginDir);
      plugin.script?.forEach((script) => {
        Deno.copyFileSync(
          join4(plugin.path, script.path),
          join4(pluginDir, basename4(script.path))
        );
      });
      plugin.stylesheet?.forEach((style) => {
        Deno.copyFileSync(
          join4(plugin.path, style),
          join4(pluginDir, basename4(style))
        );
      });
    }
    if (plugin.script) {
      for (const script of plugin.script) {
        script.path = pathWithForwardSlashes(join4(pluginUrl, script.path));
        scripts.push(script);
      }
    }
    if (plugin.stylesheet) {
      for (const stylesheet of plugin.stylesheet) {
        const pluginStylesheet = pathWithForwardSlashes(
          join4(pluginUrl, stylesheet)
        );
        stylesheets.push(pathWithForwardSlashes(pluginStylesheet));
      }
    }
    if (plugin.config) {
      for (const key of Object.keys(plugin.config)) {
        const kebabKey = camelToKebab(key);
        if (typeof plugin.config[key] === "object") {
          config2[key] = plugin.config[key];
          if (typeof format14.metadata[kebabKey] === "object") {
            config2[key] = mergeConfigs(
              revealMetadataFilter(
                config2[key],
                kRevealPluginKebabOptions
              ),
              revealMetadataFilter(
                format14.metadata[kebabKey],
                kRevealPluginKebabOptions
              )
            );
          }
        } else {
          config2[key] = plugin.config[key];
          if (format14.metadata[key] !== void 0) {
            config2[key] = format14.metadata[key];
          }
        }
      }
    }
    if (plugin.metadata) {
      metadata.push(...plugin.metadata);
    }
  }
  const extras = {
    [kIncludeInHeader]: [],
    html: {
      [kDependencies]: dependencies
    }
  };
  const linkTags = stylesheets.map((file) => {
    return `<link href="${file}" rel="stylesheet">`;
  }).join("\n");
  const linkTagsInclude = temp.createFile({ suffix: ".html" });
  Deno.writeTextFileSync(linkTagsInclude, linkTags);
  extras[kIncludeInHeader]?.push(linkTagsInclude);
  metadata.forEach((option) => {
    if (format14.metadata[option] !== void 0) {
      config2[option] = format14.metadata[option];
    }
  });
  const result2 = {
    pluginInit: {
      scripts,
      register: register2,
      revealConfig: config2
    },
    extras
  };
  return result2;
}
function revealMenuPlugin(format14) {
  return {
    plugin: formatResourcePath("revealjs", join4("plugins", "menu")),
    config: {
      menu: {
        custom: [{
          title: "Tools",
          icon: '<i class="fas fa-gear"></i>',
          content: revealMenuTools(format14)
        }],
        openButton: format14.metadata[kRevealMenu] !== false
      }
    }
  };
}
function revealChalkboardPlugin(format14) {
  if (format14.metadata[kRevealChalkboard]) {
    return {
      plugin: formatResourcePath("revealjs", join4("plugins", "chalkboard"))
    };
  } else {
    return void 0;
  }
}
function revealMenuTools(format14) {
  const tools = [
    {
      title: "Fullscreen",
      key: "f",
      handler: "fullscreen"
    },
    {
      title: "Speaker View",
      key: "s",
      handler: "speakerMode"
    },
    {
      title: "Slide Overview",
      key: "o",
      handler: "overview"
    },
    {
      title: "PDF Export Mode",
      key: "e",
      handler: "togglePdfExport"
    },
    {
      title: "Scroll View Mode",
      key: "r",
      handler: "toggleScrollView"
    }
  ];
  if (format14.metadata[kRevealChalkboard]) {
    tools.push(
      {
        title: "Toggle Chalkboard",
        key: "b",
        handler: "toggleChalkboard"
      },
      {
        title: "Toggle Notes Canvas",
        key: "c",
        handler: "toggleNotesCanvas"
      },
      {
        title: "Download Drawings",
        key: "d",
        handler: "downloadDrawings"
      }
    );
  }
  tools.push({
    title: "Keyboard Help",
    key: "?",
    handler: "keyboardHelp"
  });
  const lines2 = ['<ul class="slide-menu-items">'];
  lines2.push(...tools.map((tool, index2) => {
    return `<li class="slide-tool-item${index2 === 0 ? " active" : ""}" data-item="${index2}"><a href="#" onclick="RevealMenuToolHandlers.${tool.handler}(event)"><kbd>${tool.key || " "}</kbd> ${tool.title}</a></li>`;
  }));
  lines2.push("</ul>");
  return lines2.join("\n");
}
function revealTonePlugin(format14) {
  if (format14.metadata[kRevealSlideTone]) {
    return { plugin: formatResourcePath("revealjs", join4("plugins", "tone")) };
  } else {
    return void 0;
  }
}
function toneDependency() {
  const dependency = {
    name: "tone",
    scripts: [{
      name: "tone.js",
      path: formatResourcePath("revealjs", join4("tone", "tone.js"))
    }]
  };
  return dependency;
}
async function pluginFromBundle(bundle2) {
  if (!existsSync2(bundle2.plugin) || !Deno.statSync(bundle2.plugin).isDirectory) {
    throw new Error(
      "Specified Reveal plugin directory '" + bundle2.plugin + "' does not exist."
    );
  }
  let plugin;
  try {
    plugin = await readAndValidateYamlFromFile(
      join4(bundle2.plugin, "plugin.yml"),
      revealPluginSchema,
      "Validation of reveal plugin object failed."
    );
    plugin.path = bundle2.plugin;
  } catch (e5) {
    error(
      `Validation of plugin configuration ${join4(bundle2.plugin, "plugin.yml")} failed.`
    );
    throw e5;
  }
  if (plugin.script && !Array.isArray(plugin.script)) {
    plugin.script = [plugin.script];
  }
  plugin.script = plugin.script?.map((script) => {
    if (typeof script === "string") {
      return {
        path: script
      };
    } else {
      return script;
    }
  });
  if (plugin.stylesheet && !Array.isArray(plugin.stylesheet)) {
    plugin.stylesheet = [plugin.stylesheet];
  }
  plugin.stylesheet = plugin.stylesheet?.map(
    (stylesheet) => String(stylesheet)
  );
  validatePlugin(plugin);
  if (typeof bundle2.config === "object") {
    plugin.config = mergeConfigs(
      plugin.config || {},
      bundle2.config || {}
    );
  }
  if (typeof plugin.metadata === "string") {
    plugin.metadata = [plugin.metadata];
  }
  return plugin;
}
function validatePlugin(plugin) {
  if (typeof plugin.name !== "string") {
    throw new Error("Reveal plugin definition must include a name.");
  }
  if (!Array.isArray(plugin.script)) {
    throw new Error("Reveal plugin definition must include a script.");
  }
  for (const script of plugin.script) {
    if (!existsSync2(join4(plugin.path, script.path))) {
      throw new Error(
        "Reveal plugin script '" + script + "' not found."
      );
    }
  }
  if (plugin.stylesheet) {
    for (const stylesheet of plugin.stylesheet) {
      if (!existsSync2(join4(plugin.path, stylesheet))) {
        throw new Error(
          "Reveal plugin stylesheet '" + stylesheet + "' not found."
        );
      }
    }
  }
  if (plugin.config) {
    if (typeof plugin.config !== "object") {
      throw new Error(
        "Reveal plugin config must be an object."
      );
    }
  }
}

// format/reveal/format-reveal-theme.ts
init_path();
init_fs();
init_constants6();
init_types5();
init_http();
init_path2();
init_resources2();
init_sass();
init_format_html_shared();
init_copy5();

// format/reveal/format-reveal-title.ts
init_resources2();
init_path();
init_sass();
var kStylePandoc = "pandoc";
function titleSlidePartial(format14) {
  if (isLegacyTitleStyle(format14)) {
    return "title-slide.html";
  } else {
    return "title-fancy/title-slide.html";
  }
}
function titleSlideScss(format14) {
  if (isLegacyTitleStyle(format14)) {
    return void 0;
  } else {
    const titleBlockScss = formatResourcePath(
      "revealjs",
      join4("pandoc", "title-fancy/title-slide.scss")
    );
    return sassLayer(titleBlockScss);
  }
}
function isLegacyTitleStyle(format14) {
  return format14.metadata["title-slide-style"] === kStylePandoc;
}

// format/reveal/format-reveal-theme.ts
init_css();
init_codegen();
init_hash2();
var kRevealLightThemes = [
  "white",
  "beige",
  "sky",
  "serif",
  "simple",
  "solarized"
];
var kRevealDarkThemes = [
  "black",
  "league",
  "night",
  "blood",
  "moon",
  "dracula"
];
var kRevealThemes = [...kRevealLightThemes, ...kRevealDarkThemes];
async function revealTheme(format14, input, libDir, project) {
  const metadata = {};
  const revealDir = join4(libDir, "revealjs");
  const revealJsUrl = format14.metadata[kRevealJsUrl];
  if (revealJsUrl && !isFileRef(revealJsUrl)) {
    throw new Error(
      "Invalid revealjs-url: " + revealJsUrl + " (remote urls are not supported)"
    );
  }
  const revealUrl = pathWithForwardSlashes(revealDir);
  metadata[kRevealJsUrl] = pandocNativeStr(revealUrl).mappedString().value;
  const revealSrcDir = revealJsUrl || formatResourcePath("revealjs", "reveal");
  const revealDestDir = join4(dirname4(input), libDir, "revealjs");
  ["dist", "plugin"].forEach((dir) => {
    copyMinimal(join4(revealSrcDir, dir), join4(revealDestDir, dir));
  });
  const cssThemeDir = join4(revealSrcDir, "css", "theme");
  const loadPaths = [
    join4(cssThemeDir, "source"),
    join4(cssThemeDir, "template")
  ];
  const brandLayers = await brandRevealSassLayers(
    input,
    format14,
    project
  );
  const themeConfig = format14.metadata?.[kTheme] || "default";
  let usedBrandLayers = false;
  const themeLayers = (Array.isArray(themeConfig) ? themeConfig : [themeConfig]).map(
    (theme) => {
      const themePath = join4(relative4(Deno.cwd(), dirname4(input)), theme);
      if (theme === "brand") {
        usedBrandLayers = true;
        return brandLayers;
      } else if (existsSync2(themePath)) {
        loadPaths.unshift(join4(dirname4(input), dirname4(theme)));
        return [themeLayer(themePath)];
      } else {
        if (theme === "white") {
          theme = "default";
        } else if (theme === "black") {
          theme = "dark";
        }
        theme = formatResourcePath(
          "revealjs",
          join4("themes", `${theme}.scss`)
        );
        return [themeLayer(theme)];
      }
    }
  ).flat();
  if (!usedBrandLayers) {
    themeLayers.unshift(...brandLayers);
  }
  const yamlLayer = {
    uses: "",
    defaults: pandocVariablesToThemeScss2(format14.metadata, true),
    functions: "",
    mixins: "",
    rules: ""
  };
  const highlightingLayer = !hasAdaptiveTheme(format14.pandoc) ? resolveTextHighlightingLayer(
    input,
    format14,
    "light"
  ) : void 0;
  const userLayers = [yamlLayer];
  if (highlightingLayer) {
    userLayers.push(highlightingLayer);
  }
  userLayers.push(...themeLayers);
  const quartoLayers = [
    quartoBaseLayer(format14, true, true, false, true),
    quartoLayer(),
    quartoRevealBrandLayer()
  ];
  const titleSlideLayer = titleSlideScss(format14);
  if (titleSlideLayer) {
    userLayers.unshift(titleSlideLayer);
  }
  const bundleLayers = {
    key: "reveal-theme",
    user: userLayers,
    quarto: mergeLayers(
      ...quartoLayers
    ),
    framework: revealFrameworkLayer(revealSrcDir),
    loadPaths
  };
  const css = await compileSass([bundleLayers], project);
  cleanSourceMappingUrl(css);
  const hash = await md5HashBytes(Deno.readFileSync(css));
  const fileName = `quarto-${hash}`;
  copyTo(
    css,
    join4(revealDestDir, "dist", "theme", `${fileName}.css`)
  );
  metadata[kTheme] = fileName;
  const highlightingMode = cssHasDarkModeSentinel(Deno.readTextFileSync(css)) ? "dark" : "light";
  return {
    revealUrl,
    revealDestDir,
    metadata,
    [kTextHighlightingMode]: highlightingMode
  };
}
function revealFrameworkLayer(revealDir) {
  const readTemplate = (template2) => {
    return Deno.readTextFileSync(
      join4(revealDir, "css", "theme", "template", template2)
    );
  };
  return {
    uses: "",
    defaults: "",
    functions: "",
    mixins: readTemplate("mixins.scss"),
    rules: readTemplate("theme.scss")
  };
}
function pandocVariablesToThemeScss2(metadata, asDefaults = false) {
  return pandocVariablesToRevealDefaults(metadata).map(
    (variable) => {
      return outputVariable(variable, asDefaults);
    }
  ).join("\n");
}
function pandocVariablesToRevealDefaults(metadata) {
  const explicitVars = [];
  const add = (defaults, name2, value, formatter) => {
    if (value) {
      const sassVar = sassVariable(name2, value, formatter);
      defaults.push(sassVar);
    }
  };
  add(explicitVars, "font-family-sans-serif", metadata["mainfont"], asCssFont);
  add(explicitVars, "font-family-monospace", metadata["monofont"], asCssFont);
  add(explicitVars, "presentation-font-size-root", metadata["fontsize"]);
  add(
    explicitVars,
    "presentation-line-height",
    metadata["linestretch"],
    asCssNumber
  );
  add(explicitVars, "code-block-bg", metadata["monobackgroundcolor"]);
  add(explicitVars, "code-block-height", metadata[kCodeBlockHeight]);
  return explicitVars;
}
function quartoLayer() {
  return sassLayerFile(formatResourcePath("revealjs", "quarto.scss"));
}
function themeLayer(theme) {
  return sassLayerFile(theme);
}
function quartoRevealBrandLayer() {
  return sassLayerFile(
    resourcePath(join4("formats", "revealjs", "brand", "brand.scss"))
  );
}

// format/reveal/format-reveal.ts
init_format_html_shared();
init_format_handlers();
init_codegen();
init_brand();
function revealResolveFormat(format14) {
  format14.metadata = revealMetadataFilter(format14.metadata);
  if (format14.metadata["navigationMode"] === "vertical") {
    format14.metadata["navigationMode"] = "default";
  }
  const scrollView = format14.metadata[kScrollView];
  if (typeof scrollView === "boolean" && scrollView) {
    format14.metadata[kView] = "scroll";
  } else if (typeof scrollView === "object") {
    const scrollViewRecord = scrollView;
    if (scrollViewRecord["activate"] === true) {
      format14.metadata[kView] = "scroll";
    }
    if (scrollViewRecord["progress"] !== void 0) {
      format14.metadata[kScrollProgress] = scrollViewRecord["progress"];
    }
    if (scrollViewRecord["snap"] !== void 0) {
      format14.metadata[kScrollSnap] = scrollViewRecord["snap"];
    }
    if (scrollViewRecord["layout"] !== void 0) {
      format14.metadata[kScrollLayout] = scrollViewRecord["layout"];
    }
    if (scrollViewRecord["activation-width"] !== void 0) {
      format14.metadata[kScrollActivationWidth] = scrollViewRecord["activation-width"];
    }
  }
  delete format14.metadata[kScrollView];
  if (format14.metadata[kView] === "scroll") {
    if (format14.metadata[kScrollProgress] === "auto" || format14.metadata[kScrollProgress] === void 0) {
      format14.metadata[kScrollProgressAuto] = true;
      delete format14.metadata[kScrollProgress];
    }
  }
}
function revealjsFormat() {
  return mergeConfigs(
    createHtmlPresentationFormat("RevealJS", 10, 5),
    {
      pandoc: {
        [kHtmlMathMethod]: {
          method: "mathjax",
          url: "https://cdn.jsdelivr.net/npm/mathjax@2.7.9/MathJax.js?config=TeX-AMS_HTML-full"
        },
        [kSlideLevel]: 2
      },
      render: {
        [kCodeLineNumbers]: true
      },
      metadata: {
        [kAutoStretch]: true
      },
      resolveFormat: revealResolveFormat,
      formatPreviewFile: revealMuliplexPreviewFile,
      formatExtras: async (input, _markdown, flags, format14, libDir, services, offset3, project) => {
        const stylesFile = services.temp.createFile({ suffix: ".html" });
        const styles = renderEjs(
          formatResourcePath("revealjs", "styles.html"),
          { [kScrollable]: format14.metadata[kScrollable] }
        );
        Deno.writeTextFileSync(stylesFile, styles);
        const metadataOverride = {};
        const controlsAuto = typeof format14.metadata["controls"] !== "boolean";
        if (controlsAuto) {
          metadataOverride.controls = false;
        }
        const previewLinksAuto = format14.metadata["previewLinks"] === "auto";
        if (previewLinksAuto) {
          metadataOverride.previewLinks = false;
        }
        const extraConfig = {
          [kControlsAuto]: controlsAuto,
          [kPreviewLinksAuto]: previewLinksAuto,
          [kPdfSeparateFragments]: !!format14.metadata[kPdfSeparateFragments],
          [kAutoAnimateEasing]: format14.metadata[kAutoAnimateEasing] || "ease",
          [kAutoAnimateDuration]: format14.metadata[kAutoAnimateDuration] || 1,
          [kAutoAnimateUnmatched]: format14.metadata[kAutoAnimateUnmatched] !== void 0 ? format14.metadata[kAutoAnimateUnmatched] : true,
          [kJumpToSlide]: format14.metadata[kJumpToSlide] !== void 0 ? !!format14.metadata[kJumpToSlide] : true
        };
        if (format14.metadata[kPdfMaxPagesPerSlide]) {
          extraConfig[kPdfMaxPagesPerSlide] = format14.metadata[kPdfMaxPagesPerSlide];
        }
        const theme = await revealTheme(
          format14,
          input,
          libDir,
          project
        );
        const revealPluginData = await revealPluginExtras(
          input,
          format14,
          flags,
          services.temp,
          theme.revealUrl,
          theme.revealDestDir,
          services.extension,
          project
        );
        const templateDir = formatResourcePath("revealjs", "pandoc");
        const partials = [
          "toc-slide.html",
          titleSlidePartial(format14)
        ];
        const templateContext = {
          template: join4(templateDir, "template.html"),
          partials: partials.map((partial) => join4(templateDir, partial))
        };
        let extras = mergeConfigs(
          // extras for all html formats
          await htmlFormatExtras(
            input,
            flags,
            offset3,
            format14,
            services.temp,
            project,
            {
              tabby: true,
              anchors: false,
              copyCode: true,
              hoverCitations: true,
              hoverFootnotes: true,
              hoverXrefs: false,
              figResponsive: false
            },
            // tippy options
            {
              parent: "section.slide",
              config: {
                offset: [0, 0],
                maxWidth: 700
              }
            },
            {
              quartoBase: false
            }
          ),
          // default extras for reveal
          {
            args: [],
            pandoc: {},
            metadata: {
              [kLinkCitations]: true,
              [kRevealJsScripts]: revealPluginData.pluginInit.scripts.map(
                (script) => {
                  return pandocNativeStr(script.path).mappedString().value;
                }
              )
            },
            metadataOverride,
            templateContext,
            [kIncludeInHeader]: [
              stylesFile
            ],
            html: {
              [kHtmlPostprocessors]: [
                revealHtmlPostprocessor(
                  format14,
                  extraConfig,
                  revealPluginData.pluginInit,
                  theme["text-highlighting-mode"]
                )
              ],
              [kMarkdownAfterBody]: [revealMarkdownAfterBody(format14, input)]
            }
          }
        );
        extras.metadataOverride = {
          ...extras.metadataOverride,
          ...theme.metadata
        };
        extras.html[kTextHighlightingMode] = theme[kTextHighlightingMode];
        extras = mergeConfigs(
          revealPluginData.extras,
          extras
        );
        const multiplexExtras = revealMultiplexExtras(format14, flags);
        if (multiplexExtras) {
          extras = mergeConfigs(extras, multiplexExtras);
        }
        if (format14.metadata[kRevealJsConfig] !== "default") {
          const navigationMode = format14.metadata["navigationMode"];
          const verticalSlides = navigationMode === "default" || navigationMode === "grid";
          if (format14.metadata["slideNumber"] === true) {
            extras.metadataOverride["slideNumber"] = verticalSlides ? "h.v" : "c/t";
          }
          extras.metadata = {
            ...extras.metadata,
            ...revealMetadataFilter({
              width: 1050,
              height: 700,
              margin: 0.1,
              center: false,
              navigationMode: "linear",
              controlsLayout: "edges",
              controlsTutorial: false,
              hash: true,
              history: true,
              hashOneBasedIndex: false,
              fragmentInURL: false,
              transition: "none",
              backgroundTransition: "none",
              pdfSeparateFragments: false
            })
          };
        }
        if (format14.metadata[kView] === "scroll") {
          extras.metadata = {
            ...extras.metadata,
            [kScrollSnap]: "mandatory",
            [kScrollLayout]: "full",
            [kScrollActivationWidth]: 0
          };
        }
        if (format14.metadata[kHashType] === "number") {
          extras.pandoc = {
            ...extras.pandoc,
            from: pandocFormatWith(
              format14.pandoc[kFrom] || "markdown",
              "",
              "-auto_identifiers"
            )
          };
        }
        return extras;
      }
    }
  );
}
function revealMarkdownAfterBody(format14, input) {
  let brandMode = "light";
  if (format14.metadata[kBrandMode] === "dark") {
    brandMode = "dark";
  }
  const lines2 = [];
  lines2.push("::: {.quarto-auto-generated-content style='display: none;'}\n");
  const revealLogo = format14.metadata[kSlideLogo];
  let logo = resolveLogo(format14.render.brand, revealLogo, [
    "small",
    "medium",
    "large"
  ]);
  if (logo && logo[brandMode]) {
    logo = logoAddLeadingSlashes(logo, format14.render.brand, input);
    const modeLogo = logo[brandMode];
    const altText = modeLogo.alt ? `alt="${modeLogo.alt}" ` : "";
    lines2.push(
      `<img src="${modeLogo.path}" ${altText}class="slide-logo" />`
    );
    lines2.push("\n");
  }
  lines2.push("::: {.footer .footer-default}");
  if (format14.metadata[kSlideFooter]) {
    lines2.push(String(format14.metadata[kSlideFooter]));
  } else {
    lines2.push("");
  }
  lines2.push(":::");
  lines2.push("\n");
  lines2.push(":::");
  lines2.push("\n");
  return lines2.join("\n");
}
var handleOutputLocationSlide = (doc, slideHeadingTags) => {
  const slideOutputs = doc.querySelectorAll(`.${kOutputLocationSlide}`);
  for (const slideOutput of slideOutputs) {
    const slideOutputEl = slideOutput;
    const parentSlide = findParentSlide(slideOutputEl);
    if (parentSlide && parentSlide.parentElement) {
      const newSlide = doc.createElement("section");
      newSlide.setAttribute(
        "id",
        parentSlide?.id ? parentSlide.id + "-output" : ""
      );
      for (const clz of parentSlide.classList) {
        newSlide.classList.add(clz);
      }
      newSlide.classList.add(kOutputLocationSlide);
      if (slideHeadingTags.includes(parentSlide.firstElementChild?.tagName || "")) {
        const headingEl = doc.createElement(
          parentSlide.firstElementChild?.tagName
        );
        headingEl.innerHTML = parentSlide.firstElementChild?.innerHTML || "";
        newSlide.appendChild(headingEl);
      }
      newSlide.appendChild(slideOutputEl);
      const nextSlide = parentSlide.nextElementSibling;
      parentSlide.parentElement.insertBefore(newSlide, nextSlide);
    }
  }
};
var handleHashTypeNumber = (doc, format14) => {
  if (format14.metadata[kHashType] === "number") {
    const titleSlide = doc.getElementById("title-slide");
    if (titleSlide) {
      titleSlide.removeAttribute("id");
      titleSlide.classList.add("quarto-title-block");
    }
  }
};
var handleAutoGeneratedContent = (doc) => {
  const slideContentFromQuarto = doc.querySelector(
    ".quarto-auto-generated-content"
  );
  if (slideContentFromQuarto) {
    doc.querySelector("div.reveal")?.appendChild(slideContentFromQuarto);
  }
};
var fixupRevealJsInitialization = (doc, extraConfig, pluginInit) => {
  const scripts = doc.querySelectorAll("script");
  for (const script of scripts) {
    const scriptEl = script;
    if (scriptEl.innerText && scriptEl.innerText.indexOf("Reveal.initialize({") !== -1) {
      scriptEl.innerText = scriptEl.innerText.replace(
        /slideNumber: (h[\.\/]v|c(?:\/t)?)/,
        "slideNumber: '$1'"
      );
      scriptEl.innerText = scriptEl.innerText.replace(
        /width: (\d+(\.\d+)?%)/,
        "width: '$1'"
      );
      scriptEl.innerText = scriptEl.innerText.replace(
        /height: (\d+(\.\d+)?%)/,
        "height: '$1'"
      );
      if (pluginInit.register.length > 0) {
        const kRevealPluginArray = "plugins: [";
        scriptEl.innerText = scriptEl.innerText.replace(
          kRevealPluginArray,
          kRevealPluginArray + pluginInit.register.join(", ") + ",\n"
        );
      }
      const configJs = [];
      Object.keys(extraConfig).forEach((key) => {
        configJs.push(
          `'${key}': ${JSON.stringify(extraConfig[key])}`
        );
      });
      Object.keys(pluginInit.revealConfig).forEach((key) => {
        configJs.push(
          `'${key}': ${JSON.stringify(pluginInit.revealConfig[key])}`
        );
      });
      const configStr = configJs.join(",\n");
      scriptEl.innerText = scriptEl.innerText.replace(
        "Reveal.initialize({",
        `Reveal.initialize({
${configStr},
`
      );
    }
  }
};
var kOutputLocationSlide = "output-location-slide";
var handleInvisibleSlides = (doc) => {
  const invisibleSlides = doc.querySelectorAll(
    'section.slide[data-visibility="hidden"]'
  );
  for (let i6 = invisibleSlides.length - 1; i6 >= 0; i6--) {
    const slide = invisibleSlides.item(i6);
    const id = slide.id;
    if (id) {
      const tocEntry = doc.querySelector(
        'nav[role="doc-toc"] a[href="#/' + id + '"]'
      );
      if (tocEntry) {
        tocEntry.parentElement?.remove();
      }
    }
    slide.parentNode?.removeChild(slide);
  }
};
var handleUntitledSlidesInToc = (doc) => {
  const tocEntries = Array.from(doc.querySelectorAll(
    'nav[role="doc-toc"] ul > li'
  ));
  for (const tocEntry of tocEntries) {
    const tocEntryEl = tocEntry;
    if (tocEntryEl.textContent.trim() === "") {
      tocEntryEl.remove();
    }
  }
};
var handleSlideHeadingAttributes = (doc, slideHeadingTags) => {
  const slideHeadings = doc.querySelectorAll("section.slide > :first-child");
  slideHeadings.forEach((slideHeading) => {
    const slideHeadingEl = slideHeading;
    if (slideHeadingTags.includes(slideHeadingEl.tagName)) {
      for (const attrib of slideHeadingEl.getAttributeNames()) {
        slideHeadingEl.removeAttribute(attrib);
        if (attrib === "data-auto-animate") {
          slideHeadingEl.setAttribute("data-id", "quarto-animate-title");
          const codeBlocks = slideHeadingEl.parentElement?.querySelectorAll(
            "div.sourceCode > pre > code"
          );
          if (codeBlocks?.length === 1) {
            const codeEl = codeBlocks.item(0);
            const preEl = codeEl.parentElement;
            preEl.setAttribute(
              "data-id",
              "quarto-animate-code"
            );
            codeEl.classList.add("hljs");
            codeEl.childNodes.forEach((spanNode) => {
              if (spanNode.nodeType === 1 /* ELEMENT_NODE */) {
                const spanEl = spanNode;
                spanEl.classList.add("hljs-ln-code");
              }
            });
          }
        }
      }
    }
  });
};
var handleCenteredSlides = (doc, format14) => {
  if (format14.metadata[kCenterTitleSlide] !== false) {
    const titleSlide = doc.getElementById("title-slide") ?? // when hash-type: number, id are removed
    doc.querySelector(".reveal .slides section.quarto-title-block");
    if (titleSlide) {
      titleSlide.classList.add("center");
    }
    const titleSlides = doc.querySelectorAll(".title-slide");
    for (const slide of titleSlides) {
      slide.classList.add("center");
    }
  }
  if (format14.metadata[kCenter] === true) {
    for (const slide of doc.querySelectorAll("section.slide")) {
      const slideEl = slide;
      slideEl.classList.add("center");
    }
  }
};
var fixupAssistiveMmlInNotes = (doc) => {
  const notes = doc.querySelectorAll("aside.notes");
  for (const note of notes) {
    const style = doc.createElement("style");
    style.setAttribute("type", "text/css");
    style.innerHTML = `
        span.MJX_Assistive_MathML {
          position:absolute!important;
          clip: rect(1px, 1px, 1px, 1px);
          padding: 1px 0 0 0!important;
          border: 0!important;
          height: 1px!important;
          width: 1px!important;
          overflow: hidden!important;
          display:block!important;
      }`;
    note.appendChild(style);
  }
};
var coalesceAsides = (doc, slideFootnotes) => {
  const slides = doc.querySelectorAll("section.slide");
  for (const slide of slides) {
    const slideEl = slide;
    const asides = slideEl.querySelectorAll("aside:not(.notes)");
    const asideDivs = slideEl.querySelectorAll("div.aside");
    const footnotes = slideEl.querySelectorAll('a[role="doc-noteref"]');
    if (asides.length > 0 || asideDivs.length > 0 || footnotes.length > 0) {
      const aside = doc.createElement("aside");
      const collectAsides = (asideList) => {
        asideList.forEach((asideEl) => {
          const asideDiv = doc.createElement("div");
          asideDiv.innerHTML = asideEl.innerHTML;
          aside.appendChild(asideDiv);
        });
        asideList.forEach((asideEl) => {
          asideEl.remove();
        });
      };
      collectAsides(asides);
      collectAsides(asideDivs);
      if (slideFootnotes && footnotes.length > 0) {
        const ol = doc.createElement("ol");
        ol.classList.add("aside-footnotes");
        footnotes.forEach((note, index2) => {
          const noteEl = note;
          const href = noteEl.getAttribute("href");
          if (href) {
            const noteLi = doc.getElementById(href.replace(/^#\//, ""));
            if (noteLi) {
              const footnoteBack = noteLi.querySelector(".footnote-back");
              if (footnoteBack) {
                footnoteBack.remove();
              }
              ol.appendChild(noteLi);
            }
          }
          const sup = doc.createElement("sup");
          sup.innerText = index2 + 1 + "";
          noteEl.replaceWith(sup);
        });
        aside.appendChild(ol);
      }
      slide.appendChild(aside);
    }
  }
};
var handleSlideFootnotes = (doc, slideFootnotes, format14, slideLevel) => {
  const footnotes = doc.querySelectorAll('section[role="doc-endnotes"]');
  if (slideFootnotes) {
    for (const footnoteSection of footnotes) {
      footnoteSection.remove();
    }
  } else {
    let footnotesId;
    const footnotes2 = doc.querySelectorAll('section[role="doc-endnotes"]');
    if (footnotes2.length === 1) {
      const footnotesEl = footnotes2[0];
      footnotesId = footnotesEl?.getAttribute("id") || "footnotes";
      footnotesEl.setAttribute("id", footnotesId);
      insertFootnotesTitle(doc, footnotesEl, format14.language, slideLevel);
      footnotesEl.classList.add("smaller");
      footnotesEl.classList.add("scrollable");
      footnotesEl.classList.remove("center");
      removeFootnoteBacklinks(footnotesEl);
    }
    const notes = doc.querySelectorAll('a[role="doc-noteref"]');
    for (const note of notes) {
      const noteEl = note;
      noteEl.setAttribute("data-footnote-href", noteEl.getAttribute("href"));
      noteEl.setAttribute("href", footnotesId ? `#/${footnotesId}` : "");
      noteEl.setAttribute("onclick", footnotesId ? "" : "return false;");
    }
  }
};
var handleRefs = (doc) => {
  let refsId;
  const refs = doc.querySelector("#refs");
  if (refs) {
    const refsSlide = findParentSlide(refs);
    if (refsSlide) {
      refsId = refsSlide?.getAttribute("id") || "references";
      refsSlide.setAttribute("id", refsId);
    }
    applyClassesToParentSlide(refs, ["smaller", "scrollable"]);
    removeClassesFromParentSlide(refs, ["center"]);
  }
  return refsId;
};
var handleScrollable = (doc, format14) => {
  if (format14.metadata[kScrollable] === true) {
    const ol = doc.querySelectorAll("ol");
    for (const olEl of ol) {
      const olParent = findParent(olEl, (el) => {
        return el.nodeName === "SECTION";
      });
      if (olParent) {
        olParent.classList.add("scrollable");
      }
    }
  }
};
var handleCitationLinks = (doc, refsId) => {
  const cites = doc.querySelectorAll('a[role="doc-biblioref"]');
  for (const cite of cites) {
    const citeEl = cite;
    citeEl.setAttribute("href", refsId ? `#/${refsId}` : "");
    citeEl.setAttribute("onclick", refsId ? "" : "return false;");
  }
};
var handleChalkboard = (result2, format14) => {
  const chalkboard = format14.metadata["chalkboard"];
  if (typeof chalkboard === "object") {
    const chalkboardSrc = chalkboard["src"];
    if (typeof chalkboardSrc === "string") {
      result2.resources.push(chalkboardSrc);
    }
  }
};
var handleAnchors = (doc) => {
  const codeLinesAnchors = doc.querySelectorAll(
    "span[id^='cb'] > a[href^='#c']"
  );
  codeLinesAnchors.forEach((codeLineAnchor) => {
    const codeLineAnchorEl = codeLineAnchor;
    codeLineAnchorEl.removeAttribute("href");
  });
};
var handleInterColumnDivSpaces = (doc) => {
  for (const slide of doc.querySelectorAll("section.slide")) {
    for (const column of slide.querySelectorAll("div.column")) {
      const columnEl = column;
      let next = columnEl.nextSibling;
      while (next && next.nodeType === 3 /* TEXT_NODE */ && next.textContent?.trim() === "") {
        next.parentElement?.removeChild(next);
        next = columnEl.nextSibling;
      }
    }
  }
};
function revealHtmlPostprocessor(format14, extraConfig, pluginInit, highlightingMode) {
  return (doc) => {
    const result2 = {
      resources: [],
      supporting: []
    };
    if (doc.querySelectorAll("div.blockquote-list-scaffold")) {
      const blockquoteListScaffolds = doc.querySelectorAll(
        "div.blockquote-list-scaffold"
      );
      for (const blockquoteListScaffold of blockquoteListScaffolds) {
        const blockquoteListScaffoldEL = blockquoteListScaffold;
        const blockquoteListScaffoldParent = blockquoteListScaffoldEL.parentNode;
        if (blockquoteListScaffoldParent) {
          while (blockquoteListScaffoldEL.firstChild) {
            blockquoteListScaffoldParent.insertBefore(
              blockquoteListScaffoldEL.firstChild,
              blockquoteListScaffoldEL
            );
          }
          blockquoteListScaffoldParent.removeChild(blockquoteListScaffoldEL);
        }
      }
    }
    doc.body.classList.add("quarto-" + highlightingMode);
    const slideFootnotes = format14.pandoc[kReferenceLocation] !== "document";
    const slideLevel = format14.pandoc[kSlideLevel] || 2;
    const slideHeadingTags = Array.from(Array(slideLevel)).map(
      (_e, i6) => "H" + (i6 + 1)
    );
    handleOutputLocationSlide(doc, slideHeadingTags);
    handleHashTypeNumber(doc, format14);
    fixupRevealJsInitialization(doc, extraConfig, pluginInit);
    handleAutoGeneratedContent(doc);
    handleInvisibleSlides(doc);
    handleUntitledSlidesInToc(doc);
    handleSlideHeadingAttributes(doc, slideHeadingTags);
    handleCenteredSlides(doc, format14);
    fixupAssistiveMmlInNotes(doc);
    coalesceAsides(doc, slideFootnotes);
    handleSlideFootnotes(doc, slideFootnotes, format14, slideLevel);
    const refsId = handleRefs(doc);
    handleScrollable(doc, format14);
    handleCitationLinks(doc, refsId);
    applyStretch(doc, format14.metadata[kAutoStretch]);
    handleChalkboard(result2, format14);
    handleAnchors(doc);
    handleInterColumnDivSpaces(doc);
    return Promise.resolve(result2);
  };
}
function applyStretch(doc, autoStretch) {
  const allSlides = doc.querySelectorAll("section.slide");
  for (const slide of allSlides) {
    const slideEl = slide;
    if (slideEl.classList.contains("nostretch")) continue;
    const images = slideEl.querySelectorAll("img");
    if (images.length === 1) {
      const image2 = images[0];
      const imageEl = image2;
      if (imageEl.classList.contains("nostretch")) {
        imageEl.classList.remove("nostretch");
        continue;
      }
      if (
        // screen out early specials divs (layout panels, columns, fragments, ...)
        findParent(imageEl, (el) => {
          return el.classList.contains("column") || el.classList.contains("quarto-layout-panel") || el.classList.contains("fragment") || el.classList.contains(kOutputLocationSlide) || !!el.className.match(/panel-/);
        }) || // Do not autostrech if an aside is used
        slideEl.querySelectorAll("aside:not(.notes)").length !== 0
      ) {
        continue;
      }
      let selNode;
      for (const node of slide.childNodes) {
        if (node.contains(image2)) {
          selNode = node;
          break;
        }
      }
      const nodeEl = selNode;
      if (!nodeEl || nodeEl.nodeName === "P" && nodeEl.childNodes.length > 1) {
        continue;
      }
      const hasStretchClass = function(el) {
        return el.classList.contains("stretch") || el.classList.contains("r-stretch");
      };
      if (
        // on <p><img> (created by Pandoc)
        nodeEl.nodeName === "P" || // on quarto figure divs
        nodeEl.nodeName === "DIV" && nodeEl.classList.contains("quarto-figure") || // on computation output created image
        nodeEl.nodeName === "DIV" && nodeEl.classList.contains("cell") || // on other divs (custom divs) when explicitly opt-in
        nodeEl.nodeName === "DIV" && hasStretchClass(nodeEl)
      ) {
        if (nodeEl.nodeName === "DIV" && hasStretchClass(nodeEl)) {
          nodeEl.classList.remove("r-stretch");
          nodeEl.classList.remove("stretch");
        }
        if (autoStretch === true && !hasStretchClass(imageEl) && // if height is already set, we do nothing
        !imageEl.getAttribute("style")?.match("height:") && !imageEl.hasAttribute("height") && // do not add when .absolute is used
        !imageEl.classList.contains("absolute") && // do not add when image is inside a link
        imageEl.parentElement?.nodeName !== "A") {
          imageEl.classList.add("r-stretch");
        }
        if (hasStretchClass(imageEl) && imageEl.parentNode?.nodeName !== "SECTION") {
          const removeEmpty2 = function(el) {
            const parentEl = el.parentElement;
            parentEl?.removeChild(el);
            if (parentEl?.innerText.trim() === "" && // Stop at section leveal and do not remove empty slides
            parentEl?.nodeName !== "SECTION") {
              removeEmpty2(parentEl);
            }
          };
          const quartoFig = slideEl.querySelector("div.quarto-figure");
          const caption = doc.createElement("p");
          if (quartoFig) {
            const align = quartoFig.className.match(
              "quarto-figure-(center|left|right)"
            );
            if (align) imageEl.classList.add(align[0]);
            const quartoFigId = quartoFig?.id;
            if (quartoFigId) imageEl.id = quartoFigId;
            const figCaption = nodeEl.querySelector("figcaption");
            if (figCaption) {
              caption.classList.add("caption");
              caption.innerHTML = figCaption.innerHTML;
            }
          }
          const nextEl = nodeEl.nextElementSibling;
          removeEmpty2(imageEl);
          slideEl.insertBefore(image2, nextEl);
          if (caption.classList.contains("caption")) {
            slideEl.insertBefore(
              caption,
              imageEl.nextElementSibling
            );
          }
          if (quartoFig) removeEmpty2(quartoFig);
        }
      }
    }
  }
}
function applyClassesToParentSlide(el, classes, slideClass = "slide") {
  const slideEl = findParentSlide(el, slideClass);
  if (slideEl) {
    classes.forEach((clz) => slideEl.classList.add(clz));
  }
}
function removeClassesFromParentSlide(el, classes, slideClass = "slide") {
  const slideEl = findParentSlide(el, slideClass);
  if (slideEl) {
    classes.forEach((clz) => slideEl.classList.remove(clz));
  }
}
function findParentSlide(el, slideClass = "slide") {
  return findParent(el, (el2) => {
    return el2.classList.contains(slideClass);
  });
}
registerWriterFormatHandler((format14) => {
  switch (format14) {
    case "revealjs":
      return {
        format: revealjsFormat()
      };
  }
});

// format/asciidoc/format-asciidoc.ts
init_config2();
init_book_shared();
init_book_constants();
init_path();
init_formats_shared();
init_path2();
init_resources2();
init_constants6();
init_fs();
init_text2();
await init_project_shared();
init_format_handlers();
function asciidocFormat() {
  return mergeConfigs(
    plaintextFormat("Asciidoc", "adoc"),
    {
      pandoc: {
        // This is required because Pandoc is wrapping asciidoc images which must be on one line
        wrap: "none",
        template: formatResourcePath(
          "asciidoc",
          join4(
            "pandoc",
            "template.asciidoc"
          )
        ),
        to: "asciidoc"
      },
      extensions: {
        book: asciidocBookExtension
      }
    }
  );
}
var kFormatOutputDir = "book-asciidoc";
var kAsciidocDocType = "asciidoc-doctype";
var kAtlasConfigFile = "atlas.json";
var kRefTargetIdentifier = "refs-target-identifier";
var kRefTargetIndentifierValue = "// quarto-refs-target-378736AB";
var kRefTargetIndentifierMatch = /\/\/ quarto-refs-target-378736AB/g;
var kUseAsciidocNativeCites = "use-asciidoc-native-cites";
var asciidocBookExtension = {
  multiFile: true,
  formatOutputDirectory() {
    return kFormatOutputDir;
  },
  filterParams: (_options) => {
    return {
      [kUseAsciidocNativeCites]: true,
      [kRefTargetIdentifier]: kRefTargetIndentifierValue
    };
  },
  filterFormat: (source2, format14, project) => {
    if (project) {
      const inputFile = relative4(project.dir, source2);
      if (isBookIndexPage(inputFile) && !format14.pandoc[kOutputFile]) {
        const title3 = bookOutputStem(project.dir, project.config);
        const adocOutputFile = title3 + ".adoc";
        format14.pandoc[kOutputFile] = adocOutputFile;
      }
      return format14;
    } else {
      return format14;
    }
  },
  async onMultiFilePrePrender(isIndex, format14, markdown, project) {
    if (isIndex) {
      const rootPageMd = await bookRootPageMarkdown(project);
      const completeMd = markdown + "\n" + rootPageMd;
      format14.pandoc.variables = format14.pandoc.variables || {};
      format14.pandoc.variables[kAsciidocDocType] = "book";
      return { markdown: completeMd, format: format14 };
    } else {
      format14.pandoc.toc = false;
      format14.pandoc[kShiftHeadingLevelBy] = -1;
      return { format: format14 };
    }
  },
  async bookPostRender(format14, context, _incremental, outputFiles) {
    const projDir = projectOutputDir(context);
    const outDir = join4(projDir, kFormatOutputDir);
    const atlasInFile = join4(context.dir, kAtlasConfigFile);
    const atlasOutFile = join4(outDir, kAtlasConfigFile);
    if (existsSync2(atlasInFile)) {
      Deno.copyFileSync(atlasInFile, atlasOutFile);
    } else {
      Deno.writeTextFileSync(atlasOutFile, project2Atlas(projDir, context));
    }
    let refsTarget;
    let indexPage;
    for (const outputFile5 of outputFiles) {
      const path3 = outputFile5.file;
      if (existsSync2(path3)) {
        const contents = Deno.readTextFileSync(path3);
        if (contents.match(kRefTargetIndentifierMatch)) {
          refsTarget = path3;
        }
      }
      const relativePath = relative4(outDir, outputFile5.file);
      if (isBookIndexPage(relativePath)) {
        indexPage = outputFile5.file;
      }
    }
    if (refsTarget || indexPage) {
      const cites = /* @__PURE__ */ new Set();
      const citeIndexObj = citeIndex(context.dir);
      for (const key of Object.keys(citeIndexObj)) {
        const citeArr = citeIndexObj[key];
        citeArr.forEach((cite) => {
          cites.add(cite);
        });
      }
      const biblio = await bookBibliography(outputFiles, context);
      if (biblio.nocite) {
        biblio.nocite.forEach((no) => {
          cites.add(no);
        });
      }
      let bibliographyContents = "";
      if (biblio.bibliographyPaths && cites.size) {
        bibliographyContents = await generateBibliography(
          context,
          biblio.bibliographyPaths,
          Array.from(cites),
          "asciidoc",
          biblio.csl
        );
      }
      const cleanedBibliography = lines(bibliographyContents).filter(
        (line) => {
          return line !== "[[refs]]";
        }
      ).map((line) => {
        if (line.startsWith("[[ref-")) {
          return line.replace("[[ref-", "- [[");
        } else {
          return `  ${line}`;
        }
      }).join("\n").trim();
      if (refsTarget) {
        const refTargetContents = Deno.readTextFileSync(refsTarget);
        const updatedContents = refTargetContents.replace(
          kRefTargetIndentifierMatch,
          cleanedBibliography
        );
        Deno.writeTextFileSync(
          refsTarget,
          updatedContents
        );
      } else if (indexPage) {
        const title3 = format14.language[kSectionTitleReferences] || "References";
        const titleAdoc = `== ${title3}`;
        const indexPageContents = Deno.readTextFileSync(indexPage);
        const updatedContents = `${indexPageContents}

${titleAdoc}

[[refs]]

${cleanedBibliography}`;
        Deno.writeTextFileSync(
          indexPage,
          updatedContents
        );
      }
    }
  }
};
function project2Atlas(projDir, context) {
  const bookStem = bookOutputStem(projDir, context.config);
  const bookTitle = bookConfig("title", context.config);
  const atlasJson = {
    branch: "main",
    "files": [
      `${bookStem}.adoc`
    ],
    "formats": {
      "pdf": {
        "version": "web",
        "color_count": "1",
        "index": false,
        "toc": true,
        "syntaxhighlighting": true,
        "show_comments": false
      },
      "epub": {
        "index": false,
        "toc": true,
        "epubcheck": true,
        "syntaxhighlighting": true,
        "show_comments": false
      },
      "mobi": {
        "index": false,
        "toc": true,
        "syntaxhighlighting": true,
        "show_comments": false
      },
      "html": {
        "index": false,
        "toc": true,
        "syntaxhighlighting": true,
        "show_comments": false,
        "consolidated": false
      }
    },
    "title": bookTitle,
    "compat-mode": "false"
  };
  return JSON.stringify(atlasJson, void 0, 2);
}
async function bookRootPageMarkdown(project) {
  const chapters = await chapterInputs(project);
  const appendices = await appendixInputs(project);
  const fileContents = [
    "\n```{=asciidoc}\n\n",
    levelOffset("+1"),
    partsAndChapters(chapters, chapter),
    partsAndChapters(appendices, appendix),
    levelOffset("-1"),
    "```\n"
  ];
  return fileContents.join("\n");
}
function levelOffset(offset3) {
  return `:leveloffset: ${offset3}
`;
}
function partsAndChapters(entries, include2) {
  return entries.map((entry) => {
    if (typeof entry === "string") {
      return include2(entry);
    } else {
      const partOutput = [];
      if (entry.partPath) {
        partOutput.push(include2(entry.partPath));
      } else {
        partOutput.push(levelOffset("-1"));
        partOutput.push(`= ${entry.part}`);
        partOutput.push(levelOffset("+1"));
      }
      for (const chap of entry.chapters) {
        partOutput.push(include2(chap));
      }
      return partOutput.join("\n");
    }
  }).join("\n");
}
function chapter(path3) {
  return `include::${path3}[]
`;
}
function appendix(path3) {
  return `[appendix]
${chapter(path3)}
`;
}
async function chapterInputs(project) {
  const bookContents = bookConfig(
    kBookChapters,
    project.config
  );
  return await resolveBookInputs(
    bookContents,
    project,
    (input) => {
      return !isBookIndexPage(input);
    }
  );
}
async function appendixInputs(project) {
  const bookApps = bookConfig(
    kBookAppendix,
    project.config
  );
  return bookApps ? await resolveBookInputs(
    bookApps,
    project
  ) : [];
}
async function resolveBookInputs(inputs, project, filter3) {
  const resolveChapter = async (input) => {
    if (filter3 && !filter3(input)) {
      return void 0;
    } else {
      const target = await resolveInputTarget(
        project,
        input,
        false
      );
      if (target) {
        const [dir, stem] = dirAndStem(target?.outputHref);
        const outputFile5 = join4(
          dir,
          `${stem}.adoc`
        );
        return outputFile5;
      } else {
        return void 0;
      }
    }
  };
  const outputs = [];
  for (const input of inputs) {
    if (typeof input === "string") {
      const chapterOutput = await resolveChapter(input);
      if (chapterOutput) {
        outputs.push(chapterOutput);
      }
    } else {
      const entry = input;
      const resolvedPart = await resolveChapter(entry.part);
      const entryOutput = {
        partPath: resolvedPart,
        part: resolvedPart ? void 0 : entry.part,
        chapters: []
      };
      for (const chapter2 of entry.chapters) {
        const resolved = await resolveChapter(chapter2);
        if (resolved) {
          entryOutput.chapters.push(resolved);
        }
      }
      outputs.push(entryOutput);
    }
  }
  return outputs;
}
registerWriterFormatHandler((format14) => {
  switch (format14) {
    case "asciidoc":
    case "asciidoctor":
      return {
        format: asciidocFormat()
      };
  }
});

// format/dashboard/format-dashboard.ts
init_constants6();
init_types5();
init_config2();
init_error2();
init_resources2();
init_types4();
init_format_handlers();
init_format_html_shared();
init_path();

// format/dashboard/format-dashboard-card.ts
init_deno_dom();

// format/dashboard/format-dashboard-valuebox.ts
var kValueboxBodySelector = ".card-body > div";
var kValueboxShowcaseClass = ".value-box-showcase";
var kValueboxTitleClass = "value-box-title";
var kValueBoxValueClass = "value-box-value";
var kToParagraphsClz = [kValueboxTitleClass, kValueBoxValueClass];
var kValueBoxColorAttr = "data-color";
var kValueBoxBgColorAttr = "data-bg-color";
var kValueBoxFgColorAttr = "data-fg-color";
var kValueBoxIconAttr = "data-icon";
var kValueBoxShowcasePositionAttr = "data-showcase-position";
var kDefaultShowcasePosition = "left-center";
var bsLibValueBoxClass = "bslib-value-box";
var bsLibValueBoxGridClass = "value-box-grid";
var kDefaultColors = ["secondary"];
function isValueBox(el) {
  return el.classList.contains(kValueboxClass) || el.classList.contains(bsLibValueBoxClass);
}
function processValueBoxes(doc) {
  const valueboxNodes = doc.body.querySelectorAll(`.${kValueboxClass}`);
  let autoColorizeCount = 0;
  for (const valueboxNode of valueboxNodes) {
    const valueboxEl = valueboxNode;
    applyClasses(valueboxEl, [bsLibValueBoxClass]);
    const valueboxBodyEl = valueboxEl.querySelector(kValueboxBodySelector);
    if (valueboxBodyEl) {
      applyClasses(valueboxBodyEl, [bsLibValueBoxGridClass]);
      kToParagraphsClz.forEach((cls) => {
        const toParaEl = valueboxEl.querySelector(`.${cls}`);
        if (toParaEl && toParaEl.tagName !== "P") {
          const paraEl = doc.createElement("P");
          paraEl.childNodes = toParaEl.childNodes;
          for (const toClass of toParaEl.classList) {
            paraEl.classList.add(toClass);
          }
          toParaEl.replaceWith(paraEl);
        }
      });
      let colorProcessed = false;
      processAndRemoveAttr(
        valueboxBodyEl,
        kValueBoxColorAttr,
        (_el, attrValue) => {
          colorEl(valueboxEl, attrValue, "background");
          colorProcessed = true;
        }
      );
      if (!colorProcessed) {
        processAndRemoveAttr(
          valueboxBodyEl,
          kValueBoxBgColorAttr,
          (_el, attrValue) => {
            colorEl(valueboxEl, attrValue, "background");
            colorProcessed = true;
          }
        );
        processAndRemoveAttr(
          valueboxBodyEl,
          kValueBoxFgColorAttr,
          (_el, attrValue) => {
            colorEl(valueboxEl, attrValue, "foreground");
            colorProcessed = true;
          }
        );
      }
      if (!colorProcessed) {
        const suggestedColorIndex = autoColorizeCount % kDefaultColors.length;
        colorEl(valueboxEl, kDefaultColors[suggestedColorIndex], "background");
        autoColorizeCount++;
      }
    }
    const showcaseEl = valueboxEl.querySelector(kValueboxShowcaseClass);
    if (showcaseEl) {
      processAndRemoveAttr(
        showcaseEl,
        kValueBoxIconAttr,
        (el, attrValue) => {
          const iconEl = doc.createElement("I");
          iconEl.classList.add("bi");
          iconEl.classList.add(`bi-${attrValue}`);
          el.append(iconEl);
        }
      );
      processAndRemoveAttr(
        showcaseEl,
        kValueBoxShowcasePositionAttr,
        (_el, attrValue) => {
          valueboxEl.classList.add(`showcase-${attrValue}`);
        },
        kDefaultShowcasePosition
      );
    }
  }
}
var isHtmlColor = (color) => {
  return color.startsWith("#");
};
var colorEl = (el, color, type4) => {
  if (isHtmlColor(color)) {
    const styleName = type4 === "background" ? "background" : "color";
    const style = el.getAttribute("style");
    const currentStyle = style !== null ? style : "";
    el.setAttribute("style", currentStyle + ` ${styleName}: ${color};`);
  } else {
    const clsPrefix = type4 === "background" ? "bg-" : "text-";
    el.classList.add(`${clsPrefix}${color}`);
  }
};

// format/dashboard/format-dashboard-layout.ts
init_css();
var kRowsClass = "rows";
var kColumnsClass = "columns";
var kHeightAttr = "data-height";
var kWidthAttr = "data-width";
var kBsLibGridClass = "bslib-grid";
var kHtmlFillItemClass = "html-fill-item";
var kHtmlFillContainerClass = "html-fill-container";
var kHiddenClass = "hidden";
var kNeverFillClasses = [
  "value-box-grid",
  "value-box-area",
  "value-box-title",
  "value-box-value",
  "nav-tabs",
  "card-header",
  "card-footer",
  "callout",
  "h1",
  "h2",
  "h3",
  "h4",
  "h5",
  "h6",
  "input-panel",
  "toolbar",
  "flow"
];
var kFillContentElements = {
  tags: [{
    name: "div",
    ignoreClasses: kNeverFillClasses
  }],
  classes: [
    "card",
    "card-body",
    "tab-pane",
    "tab-content",
    "tabset",
    "bslib-grid",
    "bslib-grid-item",
    "sidebar-content",
    "main",
    "bslib-sidebar-layout",
    "cell-output-display",
    "quarto-float"
  ]
};
var kFillContainerElements = {
  tags: kFillContentElements.tags,
  classes: [
    ...kFillContentElements.classes,
    "bslib-page-fill"
  ]
};
var kFillDontRecurseInsideClasses = ["sidebar", "toolbar"];
function processRows(doc) {
  const rowNodes = doc.querySelectorAll(`div.${kRowsClass}`);
  if (rowNodes !== null) {
    for (const rowNode of rowNodes) {
      const rowEl = rowNode;
      rowEl.classList.add(kBsLibGridClass);
      rowEl.classList.remove(kRowsClass);
      const rowLayouts = computeRowLayouts(rowEl);
      const fillFr = computeFillFr(rowLayouts);
      const rowGridSizes = rowLayouts.map((layout) => {
        return toGridSize(layout, fillFr);
      });
      const gridTemplRowsVal = `${rowGridSizes.join(" ")}`;
      const currentStyle = rowEl.getAttribute("style");
      const template2 = `display: grid; grid-template-rows: ${gridTemplRowsVal}; grid-auto-columns: minmax(0, 1fr);`;
      rowEl.setAttribute(
        "style",
        currentStyle === null ? template2 : `${currentStyle}
${template2}`
      );
    }
  }
}
function processColumns(doc) {
  const colNodes = doc.querySelectorAll(`div.${kColumnsClass}`);
  if (colNodes !== null) {
    for (const colNode of colNodes) {
      const colEl = colNode;
      colEl.classList.add(kBsLibGridClass);
      colEl.classList.remove(kColumnsClass);
      const colLayouts = computeColumnLayouts(colEl);
      const fillFr = computeFillFr(colLayouts);
      const gridTemplColVal = `${colLayouts.map((layout) => {
        return toGridSize(layout, fillFr);
      }).join(" ")}`;
      const currentStyle = colEl.getAttribute("style");
      const template2 = `display: grid; grid-template-columns: ${gridTemplColVal};
grid-auto-rows: minmax(0, 1fr);`;
      colEl.setAttribute(
        "style",
        currentStyle === null ? template2 : `${currentStyle}
${template2}`
      );
    }
  }
}
function computeColumnLayouts(colEl) {
  const layouts = [];
  for (const childEl of colEl.children) {
    if (childEl.classList.contains(kHiddenClass) || childEl.classList.contains(kDashboardGridSkip)) {
    } else {
      const explicitWidth = childEl.getAttribute(kWidthAttr);
      if (explicitWidth !== null) {
        childEl.removeAttribute(kWidthAttr);
        layouts.push(explicitWidth);
      } else {
        layouts.push(kLayoutFill);
      }
    }
  }
  return layouts;
}
function computeRowLayouts(rowEl) {
  const parentFillRaw = rowEl.getAttribute(kFillAttr);
  const parentLayout = parentFillRaw !== null ? asLayout(parentFillRaw) : null;
  const layouts = [];
  for (const childEl of rowEl.children) {
    const explicitHeight = childEl.getAttribute(kHeightAttr);
    if (childEl.classList.contains(kHiddenClass) || childEl.classList.contains(kDashboardGridSkip)) {
    } else if (explicitHeight !== null) {
      childEl.removeAttribute(kHeightAttr);
      layouts.push(explicitHeight);
    } else {
      const fill = childEl.getAttribute(kFillAttr);
      if (fill !== null) {
        layouts.push(asLayout(fill));
      } else {
        if (childEl.classList.contains(kRowsClass)) {
          const rowLayouts = computeRowLayouts(childEl);
          if (rowLayouts.some((layout) => layout === kLayoutFill)) {
            layouts.push(kLayoutFill);
          } else {
            layouts.push(kLayoutFlow);
          }
        } else if (childEl.classList.contains(kColumnsClass)) {
          const layout = rowLayoutForColumn(childEl, parentLayout);
          layouts.push(layout);
        } else if (childEl.classList.contains(kCardClass)) {
          const isFlow = isFlowCard(childEl);
          layouts.push(isFlow ? kLayoutFlow : kLayoutFill);
        } else {
          if (parentLayout !== null) {
            layouts.push(parentLayout);
          } else {
            layouts.push(kLayoutFill);
          }
        }
      }
    }
  }
  return layouts;
}
function toGridSize(layout, fillFr) {
  if (layout === kLayoutFill) {
    return `minmax(${kMinSizeRow}, ${fillFr}fr)`;
  } else if (layout === kLayoutFlow) {
    return `minmax(${kMinSizeRow}, max-content)`;
  } else {
    if (layout.endsWith("px")) {
      return layout;
    } else if (layout.match(kEndsWithNumber2)) {
      return `${layout}px`;
    } else if (layout.endsWith("%")) {
      const percentRaw = parseFloat(layout.slice(0, -1));
      const layoutSize = `minmax(${kMinSizeRow}, ${percentRaw}fr)`;
      return layoutSize;
    } else {
      return `minmax(${kMinSizeRow}, ${asCssSize(layout)})`;
    }
  }
}
var kEndsWithNumber2 = /[0-9]$/;
var kMinSizeRow = "3em";
function computeFillFr(layouts) {
  const percents = [];
  let unallocatedFills = 0;
  for (const layout of layouts) {
    if (layout === kLayoutFill) {
      unallocatedFills++;
    } else if (layout.endsWith("%")) {
      const unitless = layout.slice(0, -1);
      percents.push(parseFloat(unitless));
    }
  }
  const allocatedPercent = percents.reduce((prev, current3) => {
    return prev + current3;
  }, 0);
  let fillFr = 1;
  if (allocatedPercent > 0) {
    if (allocatedPercent < 100) {
      fillFr = (100 - allocatedPercent) / unallocatedFills;
    } else {
      fillFr = percents[percents.length - 1];
    }
  }
  return fillFr;
}
function asLayout(fill) {
  if (fill !== "false") {
    return kLayoutFill;
  } else {
    return kLayoutFlow;
  }
}
var kFlowLayoutDetectors = [
  isValueBox,
  isFlowCard
];
function suggestsFlowLayout(el) {
  return kFlowLayoutDetectors.some((detector) => {
    return detector(el);
  });
}
function suggestLayout(el) {
  const explicitFill = el.getAttribute(kFillAttr);
  if (explicitFill !== null) {
    return explicitFill !== "false" ? kLayoutFill : kLayoutFlow;
  } else {
    if (suggestsFlowLayout(el)) {
      return kLayoutFlow;
    } else {
      return kLayoutFill;
    }
  }
}
function rowLayoutForColumn(colEl, defaultLayout) {
  const layouts = [];
  for (const childEl of colEl.children) {
    layouts.push(suggestLayout(childEl));
  }
  return layouts.some((layout) => layout === kLayoutFill) ? defaultLayout ? defaultLayout : kLayoutFill : kLayoutFlow;
}
var recursiveApplyFillClasses = (el) => {
  applyFillItemClasses(el);
  applyFillContainerClasses(el);
  for (const childEl of el.children) {
    const recurse = !kFillDontRecurseInsideClasses.some((cls) => {
      return el.classList.contains(cls);
    });
    if (recurse) {
      recursiveApplyFillClasses(childEl);
    }
  }
};
var shouldApplyClasses = (el, fillDescriptor) => {
  if (kDontMutateTags.includes(el.tagName.toUpperCase())) {
    return false;
  }
  if (kNeverFillClasses.some((neverFillClass) => {
    return el.classList.contains(neverFillClass);
  })) {
    return false;
  }
  if (el.tagName === "DIV" && el.children.length > 0) {
    let hasFillChild = false;
    for (const childNode of el.childNodes) {
      const childEl = childNode;
      if (!childEl.classList?.contains(kLayoutFlow)) {
        hasFillChild = true;
        break;
      }
    }
    return hasFillChild;
  }
  const fillForClass = fillDescriptor.classes.some((clz) => {
    if (el.classList.contains(clz)) {
      return true;
    }
  });
  if (fillForClass) {
    return true;
  }
  const fillForTagDesc = fillDescriptor.tags.some((tagDesc) => {
    return tagDesc.name.toLowerCase() === el.tagName.toLowerCase() && !tagDesc.ignoreClasses.some((clz) => {
      return el.classList.contains(clz);
    });
  });
  if (fillForTagDesc) {
    return true;
  }
  return false;
};
var applyFillItemClasses = (el) => {
  if (shouldApplyClasses(el, kFillContentElements)) {
    el.classList.add(kHtmlFillItemClass);
  }
};
var applyFillContainerClasses = (el) => {
  if (shouldApplyClasses(el, kFillContainerElements)) {
    el.classList.add(kHtmlFillContainerClass);
  }
};

// format/dashboard/format-dashboard-sidebar.ts
init_css();
var kSidebarPanelClass = "sidebar-panel";
var kSidebarClass = "sidebar";
var kSidebarContentClass = "sidebar-content";
var kSidebarAttrPosition = "data-position";
var kSidebarAttrPositionRight = "right";
var kBsLibSidebarRight = "sidebar-right";
function makeSidebar(id, sidebar, contents, doc) {
  const sidebarContainerEl = makeEl("div", {
    classes: ["bslib-sidebar-layout", "html-fill-item"],
    attributes: {
      "data-bslib-sidebar-open": "desktop",
      "data-bslib-sidebar-init": "true"
    }
  }, doc);
  const sidebarMainEl = makeEl("div", {
    classes: ["main", "html-fill-container"]
  }, doc);
  contents.forEach((content) => {
    sidebarMainEl.appendChild(content);
  });
  processAndRemoveAttr(
    sidebar,
    kSidebarAttrPosition,
    (_el, value) => {
      if (value === kSidebarAttrPositionRight) {
        sidebarContainerEl.classList.add(kBsLibSidebarRight);
      }
    }
  );
  processAndRemoveAttr(
    sidebar,
    "data-width",
    (_el, value) => {
      const size = asCssSize(value);
      const styleRaw = sidebarContainerEl.getAttribute("style");
      const styleVal = styleRaw !== null ? styleRaw : "";
      const newStyle = styleVal + " --bslib-sidebar-width: " + size;
      sidebarContainerEl.setAttribute("style", newStyle);
    }
  );
  sidebar?.classList.remove(kSidebarClass);
  const sidebarAsideEl = makeEl("aside", {
    id,
    classes: [kSidebarClass, "html-fill-container", "html-fill-item"]
  }, doc);
  if (sidebar !== null) {
    sidebar.classList.add("html-fill-container", "html-fill-item");
    sidebarAsideEl.appendChild(sidebar);
  }
  sidebarContainerEl.appendChild(sidebarMainEl);
  recursiveApplyFillClasses(sidebarContainerEl);
  sidebarContainerEl.appendChild(sidebarAsideEl);
  sidebarContainerEl.append(...sidebarToggle(id, doc));
  return sidebarContainerEl;
}
function processSidebars(doc) {
  const sidebarNodes = doc.querySelectorAll(`.${kSidebarPanelClass}`);
  let sidebarCount = 1;
  for (const sidebarNode of sidebarNodes) {
    const sidebarEl = sidebarNode;
    const sidebarId = sidebarEl.id !== "" ? sidebarEl.id : `bslib-sidebar-${sidebarCount++}`;
    const sidebarContentsEl = sidebarEl.querySelector(`.${kSidebarClass}`);
    const sidebarMainContentsEl = sidebarEl.querySelector(
      `.${kSidebarContentClass}`
    );
    let sidebarContainerEl = void 0;
    if (sidebarContentsEl !== null && sidebarMainContentsEl !== null) {
      sidebarContainerEl = makeSidebar(sidebarId, sidebarContentsEl, [
        sidebarMainContentsEl
      ], doc);
      sidebarEl.replaceWith(sidebarContainerEl);
      sidebarContainerEl.parentElement?.classList.add(
        "dashboard-sidebar-container"
      );
    }
  }
  const topLevelSidebar = doc.querySelector(
    ".page-layout-custom > .bslib-sidebar-layout, .page-layout-custom .dashboard-page > .bslib-sidebar-layout"
  );
  if (topLevelSidebar !== null) {
    topLevelSidebar.setAttribute("data-bslib-sidebar-border", "false");
    topLevelSidebar.setAttribute("data-bslib-sidebar-border-radius", "false");
    doc.body.classList.add("dashboard-sidebar");
  }
}
function sidebarToggle(id, doc) {
  const html = `
<button class="collapse-toggle" type="button" title="Toggle sidebar" aria-expanded="true" aria-controls="${id}">
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" class="bi bi-chevron-left collapse-icon" style="fill:currentColor;" aria-hidden="true" role="img">
      <path fill-rule="evenodd" d="M11.354 1.646a.5.5 0 0 1 0 .708L5.707 8l5.647 5.646a.5.5 0 0 1-.708.708l-6-6a.5.5 0 0 1 0-.708l6-6a.5.5 0 0 1 .708 0z"></path>
    </svg>
</button>
<script data-bslib-sidebar-init>
bslib.Sidebar.initCollapsibleAll()
<\/script>
`;
  const container = doc.createElement("DIV");
  container.innerHTML = html;
  return container.childNodes;
}

// format/dashboard/format-dashboard-card.ts
var kExpandBtnHtml = `
<bslib-tooltip placement="auto" bsoptions="[]" data-require-bs-version="5" data-require-bs-caller="tooltip()">
    <template>Expand</template>
    <span class="bslib-full-screen-enter badge rounded-pill">
        <svg xmlns="http://www.w3.org/2000/svg" viewbox="0 0 24 24" style="height:1em;width:1em;" aria-hidden="true" role="img"><path d="M20 5C20 4.4 19.6 4 19 4H13C12.4 4 12 3.6 12 3C12 2.4 12.4 2 13 2H21C21.6 2 22 2.4 22 3V11C22 11.6 21.6 12 21 12C20.4 12 20 11.6 20 11V5ZM4 19C4 19.6 4.4 20 5 20H11C11.6 20 12 20.4 12 21C12 21.6 11.6 22 11 22H3C2.4 22 2 21.6 2 21V13C2 12.4 2.4 12 3 12C3.6 12 4 12.4 4 13V19Z"></path></svg>
    </span>
</bslib-tooltip>
`;
var kCardBodyClass = "card-body";
var kCardHeaderClass = "card-header";
var kCardFooterClass = "card-footer";
var kCardTitleClass = "card-title";
var kCardToolbarClass = "card-toolbar";
var kCardSidebarClass = "card-sidebar";
var kTabsetClass = "tabset";
var kTabsetIdPrefix = "card-tabset-";
var kAttrTitle = "data-title";
var kAttrExpandable = "data-expandable";
var kAttrMaxHeight = "data-max-height";
var kAttrMinHeight = "data-min-height";
var kAttrHeight = "data-height";
var kAttrPadding = "data-padding";
var kAttrFullScreen = "data-full-screen";
var kBsCardClasses = ["bslib-card", "html-fill-container"];
var kBsCardScriptInitAttrs = { ["data-bslib-card-init"]: "" };
var kBsTabsetCardHeaderClasses = ["bslib-navs-card-title"];
var kQuartoHideTitleClass = "dashboard-card-no-title";
var kBsCardAttributes = {
  ["data-bslib-card-init"]: "",
  ["data-require-bs-caller"]: "card()"
};
var cardAttrHandlers = (doc, dashboardMeta2) => {
  return [
    {
      attr: kAttrExpandable,
      handle: (el, attrValue) => {
        if (attrValue !== "false") {
          const shellEl = doc.createElement("DIV");
          shellEl.innerHTML = kExpandBtnHtml;
          for (const childEl of shellEl.children) {
            el.appendChild(childEl);
          }
          el.setAttribute(kAttrFullScreen, "false");
        }
      },
      defaultValue: (el) => {
        if (el.classList.contains(kValueboxClass) || hasFlowLayout(el)) {
          return "false";
        } else {
          return dashboardMeta2.expandable ? "true" : "false";
        }
      }
    },
    {
      attr: kAttrMaxHeight,
      handle: ensureCssUnits(attrToStyle("max-height"))
    },
    { attr: kAttrMinHeight, handle: ensureCssUnits(attrToStyle("min-height")) },
    { attr: kAttrHeight, handle: ensureCssUnits(attrToStyle("height")) },
    {
      attr: kAttrPadding,
      handle: ensureCssUnits(attrToCardBodyStyle("padding"))
    }
  ];
};
var cardBodyAttrHandlers = () => {
  return [
    {
      attr: kAttrMaxHeight,
      handle: ensureCssUnits(attrToStyle("max-height"))
    },
    { attr: kAttrMinHeight, handle: ensureCssUnits(attrToStyle("min-height")) },
    { attr: kAttrHeight, handle: ensureCssUnits(attrToStyle("height")) }
  ];
};
function processCards(doc, dashboardMeta2) {
  const cardNodes = doc.body.querySelectorAll(`.${kCardClass}`);
  let cardCount = 0;
  for (const cardNode of cardNodes) {
    cardCount++;
    const cardEl = cardNode;
    const cardBodyEls = [];
    let cardHeaderEl = void 0;
    let cardSidebarEl = void 0;
    for (const cardChildEl of cardEl.children) {
      if (cardChildEl.classList.contains(kCardBodyClass)) {
        cardBodyEls.push(cardChildEl);
      } else if (cardChildEl.classList.contains(kCardHeaderClass)) {
        cardHeaderEl = cardChildEl;
      } else if (cardChildEl.classList.contains(kCardSidebarClass)) {
        cardSidebarEl = cardChildEl;
      }
    }
    if (cardHeaderEl) {
      const looseText = [];
      const cardToolbarEl = cardHeaderEl.querySelector(`.${kCardToolbarClass}`);
      const isText = (node) => node.nodeType === Node2.TEXT_NODE;
      const isEmphasis = (node) => node.nodeName === "EM";
      const isBold = (node) => node.nodeName === "STRONG";
      const isMath = (node) => node.nodeName === "SPAN" && node.classList.contains("math") && node.classList.contains("inline");
      for (const headerChildNode of Array.from(cardHeaderEl.childNodes)) {
        if ((isText(headerChildNode) || isEmphasis(headerChildNode) || isBold(headerChildNode) || isMath(headerChildNode)) && headerChildNode.textContent.trim() !== "") {
          looseText.push(headerChildNode);
          headerChildNode.parentNode?.removeChild(headerChildNode);
        }
      }
      if (looseText.length > 0) {
        const classes = [kCardTitleClass];
        const titleTextDiv = makeEl("DIV", { classes }, doc);
        const innerSpan = makeEl("SPAN", {
          attributes: { style: "display: inline" }
        }, doc);
        titleTextDiv.appendChild(innerSpan);
        for (const node of looseText) {
          innerSpan.appendChild(node);
        }
        if (cardToolbarEl) {
          cardToolbarEl.insertBefore(titleTextDiv, cardToolbarEl.firstChild);
        } else {
          cardHeaderEl.insertBefore(titleTextDiv, cardHeaderEl.firstChild);
        }
      } else {
        cardHeaderEl.classList.add(kQuartoHideTitleClass);
      }
    }
    applyClasses(cardEl, kBsCardClasses);
    applyAttributes(cardEl, kBsCardAttributes);
    const tabSetId = cardEl.classList.contains(kTabsetClass) ? `${kTabsetIdPrefix}${cardCount}` : void 0;
    if (tabSetId) {
      if (cardHeaderEl) {
        convertToTabsetHeader(tabSetId, cardHeaderEl, cardBodyEls, doc);
      }
      convertToTabs(tabSetId, cardEl, cardBodyEls, cardSidebarEl, doc);
    } else {
      if (cardSidebarEl) {
        cardBodyEls.forEach((el) => el.remove);
        const sidebarId = `card-${cardCount}-card-sidebar`;
        const sidebarContainerEl = makeSidebar(
          sidebarId,
          cardSidebarEl,
          cardBodyEls,
          doc
        );
        cardEl.appendChild(sidebarContainerEl);
      }
    }
    for (const cardAttrHandler of cardAttrHandlers(doc, dashboardMeta2)) {
      const defaultValue = cardAttrHandler.defaultValue ? cardAttrHandler.defaultValue(cardEl) : void 0;
      processAndRemoveAttr(
        cardEl,
        cardAttrHandler.attr,
        cardAttrHandler.handle,
        defaultValue
      );
    }
    for (const cardBodyEl of cardBodyEls) {
      const layout = cardBodyLayout(cardBodyEl);
      if (layout === kLayoutFlow) {
        cardBodyEl.classList.add(kLayoutFlow);
      }
      for (const cardBodyAttrHandler of cardBodyAttrHandlers()) {
        processAndRemoveAttr(
          cardBodyEl,
          cardBodyAttrHandler.attr,
          cardBodyAttrHandler.handle
        );
        if (!tabSetId) {
          recursiveApplyFillClasses(cardBodyEl);
        }
      }
    }
    cardEl.appendChild(initCardScript(doc));
  }
}
function isFlowCard(el) {
  const layouts = cardBodyLayouts(el);
  return layouts.every((layout) => {
    return layout === kLayoutFlow;
  });
}
function cardBodyLayouts(el) {
  const cardBodyNodes = el.querySelectorAll(`.${kCardBodyClass}`);
  const layouts = [];
  for (const cardBodyNode of cardBodyNodes) {
    layouts.push(cardBodyLayout(cardBodyNode));
  }
  return layouts;
}
function cardBodyLayout(cardBodyEl) {
  const explicitFill = cardBodyEl.getAttribute(kFillAttr);
  if (explicitFill !== null) {
    return explicitFill !== "false" ? kLayoutFill : kLayoutFlow;
  } else if (shinyInputs(cardBodyEl)) {
    return kLayoutFlow;
  } else {
    return kLayoutFill;
  }
}
function shinyInputs(cardBodyEl) {
  for (const childEl of cardBodyEl.children) {
    if (!childEl.classList.contains("cell-output")) {
      return false;
    }
    if (childEl.childElementCount < 1) {
      return false;
    }
    const firstChildEl = childEl.children.item(0);
    if (!firstChildEl.classList.contains("shiny-input-container")) {
      return false;
    }
  }
  return true;
}
function initCardScript(doc) {
  const scriptInitEl = doc.createElement("SCRIPT");
  applyAttributes(scriptInitEl, kBsCardScriptInitAttrs);
  scriptInitEl.innerText = "bslib.Card.initializeAllCards();";
  return scriptInitEl;
}
function convertToTabsetHeader(tabSetId, cardHeaderEl, cardBodyEls, doc) {
  applyClasses(cardHeaderEl, kBsTabsetCardHeaderClasses);
  const ulEl = doc.createElement("UL");
  applyClasses(ulEl, ["nav", "nav-tabs", "card-header-tabs"]);
  applyAttributes(ulEl, {
    role: "tablist",
    ["data-tabsetid"]: tabSetId
  });
  let cardBodyCount = 0;
  for (const cardBodyEl of cardBodyEls) {
    cardBodyCount++;
    let cardBodyTitle = cardBodyEl.getAttribute(kAttrTitle);
    if (cardBodyTitle == null) {
      cardBodyTitle = `Tab ${cardBodyCount}`;
    }
    const liEl = doc.createElement("LI");
    applyClasses(liEl, ["nav-item"]);
    applyAttributes(liEl, { role: "presentation" });
    const aEl = doc.createElement("A");
    applyAttributes(aEl, {
      href: `#${tabSetId}-${cardBodyCount}`,
      role: "tab",
      ["data-toggle"]: "tab",
      ["data-bs-toggle"]: "tab",
      ["data-value"]: cardBodyTitle,
      ["aria-selected"]: cardBodyCount === 1 ? "true" : "false"
    });
    const clz = ["nav-link"];
    if (cardBodyCount === 1) {
      clz.push("active");
    }
    applyClasses(aEl, clz);
    aEl.innerText = cardBodyTitle;
    liEl.appendChild(aEl);
    ulEl.appendChild(liEl);
  }
  cardHeaderEl.appendChild(ulEl);
}
function findFooterEl(cardEl) {
  for (const childEl of cardEl.children) {
    if (childEl.classList.contains(kCardFooterClass)) {
      return childEl;
    }
  }
}
function convertToTabs(tabSetId, cardEl, cardBodyEls, cardSidebarEl, doc) {
  const cardFooterEl = findFooterEl(cardEl);
  const tabContainerEl = tabSetId ? doc.createElement("DIV") : void 0;
  if (tabContainerEl) {
    tabContainerEl.classList.add("tab-content");
    tabContainerEl.setAttribute("data-tabset-id", tabSetId);
    if (cardFooterEl) {
      cardEl.insertBefore(tabContainerEl, cardFooterEl);
    } else {
      cardEl.appendChild(tabContainerEl);
    }
  }
  let cardBodyCount = 0;
  for (const cardBodyEl of cardBodyEls) {
    cardBodyCount++;
    for (const cardBodyAttrHandler of cardBodyAttrHandlers()) {
      processAndRemoveAttr(
        cardBodyEl,
        cardBodyAttrHandler.attr,
        cardBodyAttrHandler.handle
      );
    }
    if (tabContainerEl) {
      const tabPaneEl = doc.createElement("DIV");
      tabPaneEl.classList.add("tab-pane");
      if (cardBodyCount === 1) {
        tabPaneEl.classList.add("active");
        tabPaneEl.classList.add("show");
      }
      tabPaneEl.setAttribute("role", "tabpanel");
      tabPaneEl.id = `${tabSetId}-${cardBodyCount}`;
      tabPaneEl.appendChild(cardBodyEl);
      tabContainerEl.appendChild(tabPaneEl);
    }
  }
  if (tabContainerEl) {
    recursiveApplyFillClasses(tabContainerEl);
  }
  if (cardSidebarEl && tabContainerEl) {
    const sidebarId = `${tabSetId}-card-sidebar`;
    const sidebarContainerEl = makeSidebar(
      sidebarId,
      cardSidebarEl,
      [tabContainerEl],
      doc
    );
    if (cardFooterEl) {
      cardEl.insertBefore(sidebarContainerEl, cardFooterEl);
    } else {
      cardEl.appendChild(sidebarContainerEl);
    }
  }
}

// format/dashboard/format-dashboard.ts
init_template();

// format/dashboard/format-dashboard-page.ts
var kPageClass = "dashboard-page";
var kAttrTitle2 = "data-title";
var kAttrScrolling = "data-scrolling";
var kDashboardPagesClass = "quarto-dashboard-pages";
function processPages(doc, dashboardMeta2) {
  const pageNodes = doc.querySelectorAll(`.${kPageClass}`);
  if (pageNodes.length === 0) {
    return;
  }
  const contentEl = doc.querySelector(".quarto-dashboard-content");
  if (contentEl !== null) {
    contentEl.classList.add(kDashboardPagesClass);
  }
  const navbarEl = doc.querySelector("#quarto-dashboard-header .navbar");
  if (!navbarEl) {
    throw new Error(
      "Expected a navbar in the dashboard output since pages are specified."
    );
  }
  const navbarContainerEl = navbarEl.querySelector(".navbar-container");
  if (!navbarContainerEl) {
    throw new Error(
      "Expected the navbar to have a container marked with `.navbar-container`."
    );
  }
  const navbarTogglerEl = navbarEl.querySelector(".navbar-toggler");
  if (navbarTogglerEl) {
    navbarTogglerEl.classList.remove("hidden");
  }
  if (dashboardMeta2.hasDarkMode) {
    const toggleEl = makeEl("a", {
      classes: ["quarto-color-scheme-toggle"],
      attributes: {
        href: "",
        onclick: "window.quartoToggleColorScheme(); return false;"
      }
    }, doc);
    const iEl = makeEl("i", { classes: ["bi"] }, doc);
    toggleEl.append(iEl);
    navbarContainerEl.append(toggleEl);
  }
  const navItems = [];
  let counter2 = 1;
  for (const pageNode of pageNodes) {
    const pageEl = pageNode;
    const scrolling = pageEl.getAttribute(kAttrScrolling) !== null ? pageEl.getAttribute(kAttrScrolling) === "true" : dashboardMeta2.scrolling;
    const id = pageEl.id ? pageEl.id : "dashboard-page-" + counter2;
    const text = pageEl.getAttribute(kAttrTitle2);
    pageEl.removeAttribute(kAttrTitle2);
    const active = counter2 === 1;
    pageEl.parentElement?.classList.add("tab-content");
    pageEl.id = id;
    pageEl.classList.add("tab-pane");
    pageEl.setAttribute("aria-labelledby", `tab-${id}`);
    if (active) {
      pageEl.classList.add("show");
      pageEl.classList.add("active");
    } else {
      pageEl.classList.add(kDashboardGridSkip);
    }
    recursiveApplyFillClasses(pageEl);
    navItems.push({
      id,
      text: text !== null ? text : "Page " + counter2,
      active,
      scrolling
    });
    counter2++;
  }
  const navUlEl = makeEl("ul", {
    classes: ["navbar-nav", "navbar-nav-scroll", "me-auto"],
    attributes: { role: "tablist" }
  }, doc);
  for (const navItem of navItems) {
    navUlEl.append(toNav(navItem, doc));
  }
  const collapseEl = makeEl("div", {
    id: "dashboard-collapse",
    classes: ["navbar-collapse", "collapse"]
  }, doc);
  collapseEl.append(navUlEl);
  navbarContainerEl.append(collapseEl);
}
function toNav(navItem, doc) {
  const liEl = makeEl("li", {
    classes: ["nav-item"],
    attributes: { role: "presentation" }
  }, doc);
  const classes = ["nav-link"];
  if (navItem.active) {
    classes.push("active");
  }
  const aEl = makeEl("a", {
    id: `tab-${navItem.id}`,
    classes,
    attributes: {
      "data-bs-toggle": "tab",
      "role": "tab",
      "data-bs-target": `#${navItem.id}`,
      [kAttrScrolling]: navItem.scrolling.toString(),
      "href": `#${navItem.id}`,
      "aria-controls": navItem.id,
      "aria-selected": navItem.active.toString()
    }
  }, doc);
  const spanEl = makeEl("span", {
    classes: ["nav-link-text"]
  }, doc);
  spanEl.innerText = navItem.text;
  aEl.append(spanEl);
  liEl.append(aEl);
  return liEl;
}

// format/dashboard/format-dashboard-navbutton.ts
function processNavButtons(doc, dashboardMeta2) {
  const buttons = dashboardMeta2[kNavButtons];
  if (buttons === void 0 || buttons.length === 0) {
    return;
  }
  const navbarEl = doc.querySelector(".navbar");
  if (!navbarEl) {
    throw new Error(
      "Expected a navbar in the dashboard output since pages are specified."
    );
  }
  const navbarContainerEl = navbarEl.querySelector(".navbar-container");
  if (!navbarContainerEl) {
    throw new Error(
      "Expected the navbar to have a container marked with `.navbar-container`."
    );
  }
  const containerEl = makeEl(
    "DIV",
    { classes: ["quarto-dashboard-links"] },
    doc
  );
  buttons.forEach((btn) => {
    const linkAttr = {
      href: btn.href
    };
    if (btn.rel) {
      linkAttr.rel = btn.rel;
    }
    if (btn.title) {
      linkAttr.title = btn.title;
    }
    if (btn.target) {
      linkAttr.target = btn.target;
    }
    if (btn["aria-label"]) {
      linkAttr["aria-label"] = btn["aria-label"];
    }
    const linkEl = makeEl("A", {
      classes: ["quarto-dashboard-link"],
      attributes: linkAttr
    }, doc);
    if (btn.icon) {
      const iconEl = makeEl("I", { classes: ["bi", `bi-${btn.icon}`] }, doc);
      linkEl.appendChild(iconEl);
    }
    if (btn.text) {
      const textEl = makeEl(
        "SPAN",
        { classes: ["quarto-dashboard-link-text"] },
        doc
      );
      textEl.innerText = btn.text;
      linkEl.appendChild(textEl);
    }
    containerEl.appendChild(linkEl);
  });
  const navbarCollapseEl = navbarEl.querySelector(`.navbar-collapse`);
  if (navbarCollapseEl) {
    navbarCollapseEl.appendChild(containerEl);
  } else {
    navbarContainerEl.appendChild(containerEl);
  }
}

// format/dashboard/format-dashboard-website.ts
function processNavigation(doc) {
  const websiteNavbarHeaderEl = doc.getElementById("quarto-header");
  if (websiteNavbarHeaderEl) {
    const dashboardHeaderEl = doc.getElementById("quarto-dashboard-header");
    if (dashboardHeaderEl) {
      websiteNavbarHeaderEl.appendChild(dashboardHeaderEl);
    }
  }
}

// format/dashboard/format-dashboard.ts
await init_project_shared();

// format/dashboard/format-dashboard-shiny.ts
function processShinyComponents(doc) {
  const inputContainerNodes = doc.querySelectorAll(".shiny-input-container");
  for (const inputContainerNode of inputContainerNodes) {
    const inputContainerEl = inputContainerNode;
    const sliderEl = inputContainerEl.querySelector("input.js-range-slider");
    if (sliderEl) {
      inputContainerEl.classList.add("no-baseline");
    }
  }
}

// format/dashboard/format-dashboard-toolbar.ts
init_css();
var kToolbarPanelClass = "toolbar-panel";
var kToolbarClass = "toolbar";
var kToolbarContentClass = "toolbar-content";
var kToolbarAttrHeight = "data-height";
var kToolbarAttrPosition = "data-position";
var kToolbarAttrPositionEnd = "end";
var kToolbarBottomClass = "toolbar-bottom";
var kToolbarTopLevelClass = "toolbar-toplevel";
var kDashboardToolbarClass = "dashboard-toolbar";
function processToolbars(doc) {
  const toolbarNodes = doc.querySelectorAll(`.${kToolbarPanelClass}`);
  for (const toolbarNode of toolbarNodes) {
    const toolbarInputEl = toolbarNode;
    const toolbarContainerEl = makeEl("div", {
      classes: ["html-fill-item", "html-fill-container"],
      attributes: {}
    }, doc);
    const toolbarEl = toolbarInputEl.querySelector(`.${kToolbarClass}`);
    if (toolbarEl) {
      processAndRemoveAttr(
        toolbarEl,
        kToolbarAttrPosition,
        (el, value) => {
          if (value === kToolbarAttrPositionEnd) {
            el.classList.add(kToolbarBottomClass);
          }
        }
      );
      processAndRemoveAttr(
        toolbarEl,
        kToolbarAttrHeight,
        (_el, value) => {
          const size = asCssSize(value);
          const styleRaw = toolbarInputEl.parentElement?.getAttribute("style");
          const styleVal = styleRaw !== null ? styleRaw : "";
          const newStyle = styleVal + " --bslib-sidebar-height: " + size;
          toolbarInputEl.parentElement?.setAttribute("style", newStyle);
        }
      );
      toolbarEl.classList.add("html-fill-container");
      toolbarContainerEl.appendChild(toolbarEl);
    }
    const toolbarMainContentsEl = toolbarInputEl.querySelector(
      `.${kToolbarContentClass}`
    );
    if (toolbarMainContentsEl !== null) {
      toolbarContainerEl.appendChild(toolbarMainContentsEl);
    }
    recursiveApplyFillClasses(toolbarContainerEl);
    toolbarInputEl.replaceWith(toolbarContainerEl);
    toolbarContainerEl.classList.add(
      "dashboard-toolbar-container"
    );
    const topLevelToolbar = doc.querySelector(
      ".page-layout-custom >  .dashboard-toolbar-container"
    );
    if (topLevelToolbar !== null) {
      topLevelToolbar.classList.add(kToolbarTopLevelClass);
      doc.body.classList.add(kDashboardToolbarClass);
    }
  }
}

// format/dashboard/format-dashboard-tables.ts
init_text2();
var kStripRegexes = [
  /\/\/ Import jquery and DataTable/,
  /^\s*import 'https:\/\/code\.jquery\.com\/jquery\-.*';$/,
  /^\s*import dt from 'https:\/\/cdn\.datatables\.net\/.*\.mjs';$/,
  /^\s*dt\(\$\);/
];
var kDatatableInit = /\$\(document\).ready\(function \(\) \{(?:\s|.)*?\$\('#(.*?)'\)\.DataTable\(dt_args\);(?:\s|.)*?\}\);.*/g;
var kDatatable16 = /.DataTable\(dt_args\)/g;
var kDtCssHrefRegex = /^\s*https:\/\/cdn\.datatables\.net\/.*?\/jquery\.dataTables\.min\.css$/;
function processDatatables(doc) {
  const resources = [];
  const supporting = [];
  const scriptNodes = doc.querySelectorAll(
    ".cell-output script[type='module']"
  );
  let keepDeps = false;
  for (const scriptNode of scriptNodes) {
    const scriptEl = scriptNode;
    const code5 = scriptEl.innerText;
    let hasConnectedDt = false;
    const codeFiltered = [];
    for (const line of lines(code5)) {
      if (kStripRegexes.some((regex) => {
        return !!line.match(regex);
      })) {
        hasConnectedDt = true;
      } else {
        codeFiltered.push(line);
      }
    }
    if (hasConnectedDt) {
      keepDeps = true;
      const codeText = codeFiltered.join("\n");
      if (codeText.match(kDatatable16)) {
        const codeWithInit = codeText.replace(
          kDatatableInit,
          "let table = new DataTable('#$1', dt_args);"
        );
        scriptEl.innerText = codeWithInit;
      } else {
        scriptEl.innerText = codeText;
      }
      const linkCssNodes = doc.querySelectorAll(
        'link[rel="stylesheet"][type="text/css"][href]'
      );
      for (const linkCssNode of linkCssNodes) {
        const linkCssEl = linkCssNode;
        const href = linkCssEl.getAttribute("href");
        if (href?.match(kDtCssHrefRegex)) {
          linkCssEl.remove();
        }
      }
    }
  }
  if (keepDeps) {
    const dtNodes = doc.querySelectorAll(`[${kDTTableSentinel}="true"]`);
    dtNodes.forEach((node) => {
      node.removeAttribute(kDTTableSentinel);
    });
  } else {
    const dtNodes = doc.querySelectorAll(`[${kDTTableSentinel}="true"]`);
    dtNodes.forEach((node) => {
      node.remove();
    });
  }
  return {
    resources,
    supporting
  };
}

// format/dashboard/format-dashboard.ts
init_asserts();
init_brand();
var kDashboardClz = "quarto-dashboard";
function dashboardFormat() {
  const baseHtmlFormat = htmlFormat(8, 5);
  const dashboardFormat2 = mergeConfigs(
    baseHtmlFormat,
    {
      execute: {
        [kEcho]: false,
        [kWarning]: false,
        [kIpynbShellInteractivity]: "all",
        [kPlotlyConnected]: false
      },
      metadata: {
        [kPageLayout]: kPageLayoutCustom
      }
    }
  );
  if (baseHtmlFormat.formatExtras) {
    const dashboardExtras = async (input, markdown, flags, format14, libDir, services, offset3, project, quiet) => {
      assert7(project);
      if (baseHtmlFormat.formatExtras) {
        const dashboard = await dashboardMeta(format14);
        const isWebsiteProject = projectIsWebsite(project);
        if (isWebsiteProject) {
          const formats2 = format14.metadata.format;
          const htmlFormat2 = formats2["html"];
          const dashboardFormat3 = formats2["dashboard"];
          if (dashboardFormat3 && dashboardFormat3[kTheme]) {
            format14.metadata[kTheme] = dashboardFormat3[kTheme];
          } else if (htmlFormat2 && htmlFormat2[kTheme]) {
            format14.metadata[kTheme] = htmlFormat2[kTheme];
          }
        }
        const brand = format14.render.brand;
        let logoSpec = format14.metadata[kLogo];
        if (typeof logoSpec === "string" && format14.metadata[kLogoAlt]) {
          logoSpec = {
            path: logoSpec,
            alt: format14.metadata[kLogoAlt]
          };
        }
        let logo = resolveLogo(brand, logoSpec, [
          "small",
          "medium",
          "large"
        ]);
        logo = logoAddLeadingSlashes(logo, brand, input);
        format14.metadata[kLogo] = logo;
        const extras = await baseHtmlFormat.formatExtras(
          input,
          markdown,
          flags,
          format14,
          libDir,
          services,
          offset3,
          project,
          quiet
        );
        extras.html = extras.html || {};
        extras.html[kHtmlPostprocessors] = extras.html[kHtmlPostprocessors] || [];
        extras.html[kHtmlPostprocessors].push(
          dashboardHtmlPostProcessor(dashboard)
        );
        extras.metadata = extras.metadata || {};
        extras.metadata[kTemplatePartials] = [
          "title-block.html",
          "_nav-container.html"
        ].map(
          (file) => {
            return formatResourcePath(
              "dashboard",
              file
            );
          }
        );
        extras.pandoc = extras.pandoc || {};
        extras.pandoc[kTemplate] = formatResourcePath(
          "dashboard",
          "template.html"
        );
        extras[kFilterParams] = extras[kFilterParams] || {};
        extras[kFilterParams][kDashboard] = {
          orientation: dashboard.orientation,
          scrolling: dashboard.scrolling
        };
        extras.html[kSassBundles] = extras.html[kSassBundles] || [];
        if (!isWebsiteProject) {
          extras.html[kSassBundles].unshift(dashboardScssLayer());
        }
        extras.html[kSassBundles].push(
          ...await brandBootstrapSassBundles(input, project, "bootstrap")
        );
        const scripts = [];
        const stylesheets = [];
        scripts.push({
          name: "quarto-dashboard.js",
          path: formatResourcePath("dashboard", "quarto-dashboard.js")
        });
        scripts.push({
          name: "stickythead.js",
          path: formatResourcePath("dashboard", join4("js", "stickythead.js"))
        });
        scripts.push({
          name: "datatables.min.js",
          path: formatResourcePath(
            "dashboard",
            join4("js", "dt", "datatables.min.js")
          ),
          attribs: {
            [kDTTableSentinel]: "true"
          }
        });
        stylesheets.push({
          name: "datatables.min.css",
          path: formatResourcePath(
            "dashboard",
            join4("js", "dt", "datatables.min.css")
          ),
          attribs: {
            [kDTTableSentinel]: "true"
          }
        });
        scripts.push({
          name: "pdfmake.min.js",
          path: formatResourcePath(
            "dashboard",
            join4("js", "dt", "pdfmake.min.js")
          ),
          attribs: {
            [kDTTableSentinel]: "true"
          }
        });
        scripts.push({
          name: "vfs_fonts.js",
          path: formatResourcePath(
            "dashboard",
            join4("js", "dt", "vfs_fonts.js")
          ),
          attribs: {
            [kDTTableSentinel]: "true"
          }
        });
        const componentDir = join4(
          "bslib",
          "components",
          "dist"
        );
        [{
          name: "web-components",
          module: true
        }, { name: "components", module: false }].forEach(
          (dependency) => {
            const attribs = {};
            if (dependency.module) {
              attribs["type"] = "module";
            }
            scripts.push({
              name: `${dependency.name}.js`,
              path: formatResourcePath(
                "html",
                join4(componentDir, `${dependency.name}.js`)
              ),
              attribs
            });
          }
        );
        extras.html[kDependencies] = extras.html[kDependencies] || [];
        extras.html[kDependencies].push({
          name: "quarto-dashboard",
          scripts,
          stylesheets
        });
        extras[kIncludeAfterBody] = extras[kIncludeAfterBody] || [];
        return extras;
      } else {
        throw new InternalError(
          "Dashboard superclass must provide a format extras"
        );
      }
    };
    if (dashboardExtras) {
      dashboardFormat2.formatExtras = dashboardExtras;
    }
  }
  return dashboardFormat2;
}
registerWriterFormatHandler((format14) => {
  switch (format14) {
    case "dashboard":
      return {
        format: dashboardFormat(),
        pandocTo: "html"
      };
  }
});
function dashboardHtmlPostProcessor(dashboardMeta2) {
  return (doc) => {
    const result2 = {
      resources: [],
      supporting: []
    };
    doc.body.classList.add(kDashboardClz);
    if (!dashboardMeta2.scrolling) {
      doc.body.classList.add("dashboard-fill");
    }
    const containerEl = doc.querySelector("div.page-layout-custom");
    if (containerEl) {
      const containerClz = [
        "quarto-dashboard-content",
        "bslib-gap-spacing",
        "html-fill-container"
      ];
      if (!dashboardMeta2.scrolling) {
        containerClz.push("bslib-page-fill");
      } else {
        containerClz.push("dashboard-scrolling");
      }
      containerClz.forEach(
        (clz) => {
          containerEl.classList.add(clz);
        }
      );
    }
    const children = containerEl?.children;
    if (children) {
      for (const childEl of children) {
        if (!childEl.classList.contains("quarto-title-block") && !kDontMutateTags.includes(childEl.tagName.toUpperCase())) {
          childEl.classList.add("bslib-grid-item");
          applyFillItemClasses(childEl);
        }
      }
    }
    const addResults = (res) => {
      if (res) {
        result2.resources.push(...res.resources);
        result2.supporting.push(...res.supporting);
      }
    };
    addResults(processDatatables(doc));
    processNavigation(doc);
    processPages(doc, dashboardMeta2);
    processNavButtons(doc, dashboardMeta2);
    processRows(doc);
    processColumns(doc);
    processCards(doc, dashboardMeta2);
    processValueBoxes(doc);
    processSidebars(doc);
    processToolbars(doc);
    processTables(doc);
    processShinyComponents(doc);
    const imgFillSelectors = [
      "div.cell-output-display > div.quarto-figure > .quarto-float img",
      "div.cell-output-display > img"
    ];
    imgFillSelectors.forEach((selector) => {
      const fillImgNodes = doc.body.querySelectorAll(selector);
      for (const fillImgNode of fillImgNodes) {
        const fillImgEl = fillImgNode;
        fillImgEl.classList.add("quarto-dashboard-img-contain");
        fillImgEl.removeAttribute("height");
        fillImgEl.removeAttribute("width");
      }
    });
    return Promise.resolve(result2);
  };
}
function processTables(doc) {
  doc.querySelectorAll(".itables table").forEach((tableEl) => {
    tableEl.setAttribute("style", "width:100%;");
  });
}

// format/email/format-email.ts
init_config2();
init_format_handlers();
function emailFormat() {
  return mergeConfigs(
    htmlFormat(7, 5)
  );
}
registerWriterFormatHandler((format14) => {
  switch (format14) {
    case "email":
      return {
        format: emailFormat(),
        pandocTo: "html"
      };
  }
});

// core/api/markdown-regex.ts
init_registry2();
init_yaml();
init_pandoc_partition();
init_break_quarto_md();
globalRegistry.register("markdownRegex", () => {
  return {
    extractYaml: readYamlFromMarkdown,
    partition: partitionMarkdown,
    getLanguages: languagesInMarkdown,
    getLanguagesWithClasses: languagesWithClasses,
    breakQuartoMd
  };
});

// core/api/mapped-string.ts
init_registry2();
init_mapped_text();
init_mapped_text2();
globalRegistry.register("mappedString", () => {
  return {
    fromString: asMappedString,
    fromFile: mappedStringFromFile,
    normalizeNewlines: mappedNormalizeNewlines,
    splitLines: (str3, keepNewLines) => {
      return mappedLines(str3, keepNewLines);
    },
    indexToLineCol: (str3, offset3) => {
      const fn = mappedIndexToLineCol(str3);
      return fn(offset3);
    }
  };
});

// core/api/jupyter.ts
init_registry2();
init_jupyter();

// core/jupyter/jupyter-filters.ts
init_fs();
init_path();
init_constants6();
init_process();

// core/jupyter/filtered-notebook-cache.ts
init_fs();
init_path();
init_appdirs();
init_path2();
async function filteredNotebookFromCache(file, filters) {
  file = normalizeNotebookPath(file);
  const invalidation = await notebookInvalidation(file, filters);
  const notebook = getCachedNotebook(file);
  if (notebook?.invalidation === invalidation) {
    return Deno.readTextFileSync(notebook.fullPath);
  } else {
    return void 0;
  }
}
async function cacheFilteredNotebook(file, filters, json3) {
  file = normalizeNotebookPath(file);
  const invalidation = await notebookInvalidation(file, filters);
  cacheNotebook(file, { invalidation, json: json3 });
}
function normalizeNotebookPath(file) {
  return isAbsolute4(file) ? file : join4(Deno.cwd(), file);
}
async function notebookInvalidation(file, filters) {
  return [file, ...await filterScriptPaths(file, filters || [])].reduce(
    (hash, file2) => {
      try {
        return hash + Deno.statSync(file2).mtime?.toUTCString();
      } catch {
        return hash;
      }
    },
    ""
  );
}
async function filterScriptPaths(file, filters) {
  const filterPaths2 = [];
  for (const filter3 of filters) {
    const args = parseShellRunCommand(filter3);
    const script = args[0];
    const scriptPath = join4(dirname4(file), script);
    if (existsSync2(scriptPath)) {
      filterPaths2.push(scriptPath);
    } else if (isAbsolute4(script) && existsSync2(script)) {
      filterPaths2.push(script);
    } else {
      const scriptPath2 = await which(script);
      if (scriptPath2 && existsSync2(scriptPath2)) {
        filterPaths2.push(scriptPath2);
      }
    }
  }
  return filterPaths2;
}
function getCachedNotebook(file) {
  const contents = readNotebookIndex()[file];
  if (contents) {
    return {
      invalidation: contents.invalidation,
      fullPath: notebookCachePath(contents.path)
    };
  }
}
function cacheNotebook(file, contents) {
  const index2 = readNotebookIndex();
  const path3 = index2[file]?.path || globalThis.crypto.randomUUID();
  Deno.writeTextFileSync(notebookCachePath(path3), contents.json);
  index2[file] = { invalidation: contents.invalidation, path: path3 };
  writeNotebookIndex(index2);
}
function readNotebookIndex() {
  const index2 = notebookIndexFile();
  if (existsSync2(index2)) {
    return JSON.parse(Deno.readTextFileSync(index2));
  }
  return {};
}
function writeNotebookIndex(index2) {
  Deno.writeTextFileSync(
    notebookIndexFile(),
    JSON.stringify(index2, void 0, 2)
  );
}
var notebookIndexFile = () => notebookCachePath("INDEX");
function notebookCachePath(file) {
  const cacheDir = join4(quartoCacheDir(), "filtered-notebooks");
  ensureDirSync(cacheDir);
  return file ? join4(cacheDir, file) : cacheDir;
}

// core/jupyter/jupyter-filters.ts
init_jupyter_fixups();
init_jupyter_shared();
async function markdownFromNotebookFile(file, format14) {
  const nbContents = await jupyterNotebookFiltered(
    file,
    format14?.execute[kIpynbFilters]
  );
  const nb = JSON.parse(nbContents);
  return markdownFromNotebookJSON(nb);
}
function markdownFromNotebookJSON(nb) {
  nb = fixupFrontMatter(nb);
  const markdown = nb.cells.reduce((md, cell) => {
    if (["markdown", "raw"].includes(cell.cell_type)) {
      return md + "\n" + jupyterCellSrcAsStr(cell) + "\n";
    } else {
      return md;
    }
  }, "");
  return markdown;
}
async function jupyterNotebookFiltered(file, filters) {
  let json3 = Deno.readTextFileSync(file);
  if (filters && filters.length > 0) {
    const cached = await filteredNotebookFromCache(file, filters);
    if (cached) {
      return cached;
    }
    for (const filter3 of filters) {
      const args = parseShellRunCommand(filter3);
      const script = args[0];
      const scriptPath = join4(dirname4(file), script);
      const handler = handlerForScript(scriptPath);
      const result2 = handler && existsSync2(scriptPath) ? await handler.run(script, args.splice(1), json3, {
        cwd: dirname4(file),
        env: {
          PYTHONUNBUFFERED: "1"
        },
        stdout: "piped"
      }) : await execProcess({
        cmd: isAbsolute4(script) ? script : basename4(script),
        args: args.slice(1),
        cwd: dirname4(file),
        env: {
          PYTHONUNBUFFERED: "1"
        },
        stdout: "piped"
      }, json3);
      if (!result2.success) {
        throw new Error();
      }
      json3 = result2.stdout || json3;
    }
    await cacheFilteredNotebook(file, filters, json3);
    return json3;
  } else {
    return json3;
  }
}

// core/api/jupyter.ts
init_widgets();
init_exec();
init_capabilities();
init_kernels();
init_jupyter_shared();
init_percent();
globalRegistry.register("jupyter", () => {
  return {
    // 1. Notebook Detection & Introspection
    isJupyterNotebook,
    isPercentScript: isJupyterPercentScript,
    notebookExtensions: kJupyterNotebookExtensions,
    kernelspecFromMarkdown: jupyterKernelspecFromMarkdown,
    kernelspecForLanguage: jupyterKernelspecForLanguage,
    fromJSON: jupyterFromJSON,
    // 2. Notebook Conversion
    toMarkdown: jupyterToMarkdown,
    markdownFromNotebookFile,
    markdownFromNotebookJSON,
    percentScriptToMarkdown: markdownFromJupyterPercentScript,
    quartoMdToJupyter,
    // 3. Notebook Processing & Assets
    notebookFiltered: jupyterNotebookFiltered,
    assets: jupyterAssets,
    widgetDependencyIncludes: includesForJupyterWidgetDependencies,
    resultIncludes: (tempDir2, dependencies) => {
      return executeResultIncludes(tempDir2, dependencies) || {};
    },
    resultEngineDependencies: (dependencies) => {
      const result2 = executeResultEngineDependencies(dependencies);
      return result2;
    },
    // 4. Runtime & Environment
    pythonExec,
    capabilities: jupyterCapabilities,
    capabilitiesMessage: jupyterCapabilitiesMessage,
    capabilitiesJson: jupyterCapabilitiesJson,
    installationMessage: jupyterInstallationMessage,
    unactivatedEnvMessage: jupyterUnactivatedEnvMessage,
    pythonInstallationMessage
  };
});

// core/api/format.ts
init_registry2();
init_format5();
init_render();
globalRegistry.register("format", () => {
  return {
    isHtmlCompatible,
    isIpynbOutput,
    isLatexOutput,
    isMarkdownOutput,
    isPresentationOutput,
    isHtmlDashboardOutput: (format14) => !!isHtmlDashboardOutput(format14),
    isServerShiny,
    isServerShinyPython
  };
});

// core/api/path.ts
init_registry2();
init_path2();
init_appdirs();
init_resources2();
init_render();
globalRegistry.register("path", () => {
  return {
    absolute: normalizePath,
    toForwardSlashes: pathWithForwardSlashes,
    runtime: quartoRuntimeDir,
    resource: (...parts) => {
      if (parts.length === 0) {
        return resourcePath();
      } else if (parts.length === 1) {
        return resourcePath(parts[0]);
      } else {
        const joined = parts.join("/");
        return resourcePath(joined);
      }
    },
    dirAndStem,
    isQmdFile,
    inputFilesDir,
    dataDir: quartoDataDir
  };
});

// core/api/system.ts
init_registry2();
init_process();
init_cleanup();
init_temp();

// command/check/check-render.ts
async function checkRender(options) {
  const { content, services } = options;
  const tempFile = services.temp.createFile({ suffix: ".qmd" });
  Deno.writeTextFileSync(tempFile, content);
  const result2 = await render(tempFile, {
    services,
    flags: { quiet: true, executeDaemon: 0 }
  });
  return {
    success: !result2.error,
    error: result2.error
  };
}

// core/api/system.ts
init_resources2();
globalRegistry.register("system", () => {
  return {
    isInteractiveSession,
    runningInCI,
    execProcess,
    runExternalPreviewServer,
    onCleanup,
    tempContext: globalTempContext,
    checkRender,
    pandoc: (args, stdin2) => {
      return execProcess(
        {
          cmd: pandocBinaryPath(),
          args,
          stdout: "piped",
          stderr: "piped"
        },
        stdin2
      );
    }
  };
});

// core/api/text.ts
init_registry2();
init_text();
init_preserve();
init_execute_inline();
init_jupyter_fixups();
globalRegistry.register("text", () => {
  return {
    lines,
    trimEmptyLines,
    postProcessRestorePreservedHtml,
    lineColToIndex,
    executeInlineCodeHandler,
    asYamlText
  };
});

// core/api/console.ts
init_registry2();
init_log();
globalRegistry.register("console", () => {
  return {
    withSpinner,
    completeMessage,
    info: (message, options) => info(message, options),
    warning: (message, options) => warn(message, options),
    error: (message, options) => error(message, options)
  };
});

// core/api/crypto.ts
init_registry2();
init_hash2();
globalRegistry.register("crypto", () => {
  return {
    md5Hash: md5HashSync
  };
});

// quarto.ts
init_constants6();

// core/main.ts
init_log2();

// https://jsr.io/@std/flags/0.224.0/mod.ts
init_assert_exists();
var { hasOwn } = Object;
function get(obj, key) {
  if (hasOwn(obj, key)) {
    return obj[key];
  }
}
function getForce(obj, key) {
  const v4 = get(obj, key);
  assertExists(v4);
  return v4;
}
function isNumber4(x3) {
  if (typeof x3 === "number") return true;
  if (/^0x[0-9a-f]+$/i.test(String(x3))) return true;
  return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(String(x3));
}
function hasKey(obj, keys) {
  let o5 = obj;
  keys.slice(0, -1).forEach((key2) => {
    o5 = get(o5, key2) ?? {};
  });
  const key = keys.at(-1);
  return key !== void 0 && hasOwn(o5, key);
}
function parse21(args, {
  "--": doubleDash = false,
  alias = {},
  boolean: boolean2 = false,
  default: defaults = {},
  stopEarly = false,
  string: string2 = [],
  collect = [],
  negatable = [],
  unknown = (i6) => i6
} = {}) {
  const aliases = {};
  const flags = {
    bools: {},
    strings: {},
    unknownFn: unknown,
    allBools: false,
    collect: {},
    negatable: {}
  };
  if (alias !== void 0) {
    for (const key in alias) {
      const val = getForce(alias, key);
      if (typeof val === "string") {
        aliases[key] = [val];
      } else {
        aliases[key] = val;
      }
      const aliasesForKey = getForce(aliases, key);
      for (const alias2 of aliasesForKey) {
        aliases[alias2] = [key].concat(aliasesForKey.filter((y4) => alias2 !== y4));
      }
    }
  }
  if (boolean2 !== void 0) {
    if (typeof boolean2 === "boolean") {
      flags.allBools = !!boolean2;
    } else {
      const booleanArgs = typeof boolean2 === "string" ? [boolean2] : boolean2;
      for (const key of booleanArgs.filter(Boolean)) {
        flags.bools[key] = true;
        const alias2 = get(aliases, key);
        if (alias2) {
          for (const al of alias2) {
            flags.bools[al] = true;
          }
        }
      }
    }
  }
  if (string2 !== void 0) {
    const stringArgs = typeof string2 === "string" ? [string2] : string2;
    for (const key of stringArgs.filter(Boolean)) {
      flags.strings[key] = true;
      const alias2 = get(aliases, key);
      if (alias2) {
        for (const al of alias2) {
          flags.strings[al] = true;
        }
      }
    }
  }
  if (collect !== void 0) {
    const collectArgs = typeof collect === "string" ? [collect] : collect;
    for (const key of collectArgs.filter(Boolean)) {
      flags.collect[key] = true;
      const alias2 = get(aliases, key);
      if (alias2) {
        for (const al of alias2) {
          flags.collect[al] = true;
        }
      }
    }
  }
  if (negatable !== void 0) {
    const negatableArgs = typeof negatable === "string" ? [negatable] : negatable;
    for (const key of negatableArgs.filter(Boolean)) {
      flags.negatable[key] = true;
      const alias2 = get(aliases, key);
      if (alias2) {
        for (const al of alias2) {
          flags.negatable[al] = true;
        }
      }
    }
  }
  const argv2 = { _: [] };
  function argDefined(key, arg) {
    return flags.allBools && /^--[^=]+$/.test(arg) || get(flags.bools, key) || !!get(flags.strings, key) || !!get(aliases, key);
  }
  function setKey(obj, name2, value, collect2 = true) {
    let o5 = obj;
    const keys = name2.split(".");
    keys.slice(0, -1).forEach(function(key2) {
      if (get(o5, key2) === void 0) {
        o5[key2] = {};
      }
      o5 = get(o5, key2);
    });
    const key = keys.at(-1);
    const collectable = collect2 && !!get(flags.collect, name2);
    if (!collectable) {
      o5[key] = value;
    } else if (get(o5, key) === void 0) {
      o5[key] = [value];
    } else if (Array.isArray(get(o5, key))) {
      o5[key].push(value);
    } else {
      o5[key] = [get(o5, key), value];
    }
  }
  function setArg(key, val, arg = void 0, collect2) {
    if (arg && flags.unknownFn && !argDefined(key, arg)) {
      if (flags.unknownFn(arg, key, val) === false) return;
    }
    const value = !get(flags.strings, key) && isNumber4(val) ? Number(val) : val;
    setKey(argv2, key, value, collect2);
    const alias2 = get(aliases, key);
    if (alias2) {
      for (const x3 of alias2) {
        setKey(argv2, x3, value, collect2);
      }
    }
  }
  function aliasIsBoolean(key) {
    return getForce(aliases, key).some(
      (x3) => typeof get(flags.bools, x3) === "boolean"
    );
  }
  let notFlags = [];
  if (args.includes("--")) {
    notFlags = args.slice(args.indexOf("--") + 1);
    args = args.slice(0, args.indexOf("--"));
  }
  for (let i6 = 0; i6 < args.length; i6++) {
    const arg = args[i6];
    assertExists(arg);
    if (/^--.+=/.test(arg)) {
      const m4 = arg.match(/^--([^=]+)=(.*)$/s);
      assertExists(m4);
      const [, key, value] = m4;
      assertExists(key);
      if (flags.bools[key]) {
        const booleanValue = value !== "false";
        setArg(key, booleanValue, arg);
      } else {
        setArg(key, value, arg);
      }
    } else if (/^--no-.+/.test(arg) && get(flags.negatable, arg.replace(/^--no-/, ""))) {
      const m4 = arg.match(/^--no-(.+)/);
      assertExists(m4);
      assertExists(m4[1]);
      setArg(m4[1], false, arg, false);
    } else if (/^--.+/.test(arg)) {
      const m4 = arg.match(/^--(.+)/);
      assertExists(m4);
      assertExists(m4[1]);
      const [, key] = m4;
      const next = args[i6 + 1];
      if (next !== void 0 && !/^-/.test(next) && !get(flags.bools, key) && !flags.allBools && (get(aliases, key) ? !aliasIsBoolean(key) : true)) {
        setArg(key, next, arg);
        i6++;
      } else if (next !== void 0 && (next === "true" || next === "false")) {
        setArg(key, next === "true", arg);
        i6++;
      } else {
        setArg(key, get(flags.strings, key) ? "" : true, arg);
      }
    } else if (/^-[^-]+/.test(arg)) {
      const letters = arg.slice(1, -1).split("");
      let broken = false;
      for (const [j3, letter] of letters.entries()) {
        const next = arg.slice(j3 + 2);
        if (next === "-") {
          setArg(letter, next, arg);
          continue;
        }
        if (/[A-Za-z]/.test(letter) && next.includes("=")) {
          setArg(letter, next.split(/=(.+)/)[1], arg);
          broken = true;
          break;
        }
        if (/[A-Za-z]/.test(letter) && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
          setArg(letter, next, arg);
          broken = true;
          break;
        }
        if (letters[j3 + 1]?.match(/\W/)) {
          setArg(letter, arg.slice(j3 + 2), arg);
          broken = true;
          break;
        } else {
          setArg(letter, get(flags.strings, letter) ? "" : true, arg);
        }
      }
      const key = arg.at(-1);
      if (!broken && key !== "-") {
        const nextArg = args[i6 + 1];
        if (nextArg && !/^(-|--)[^-]/.test(nextArg) && !get(flags.bools, key) && (get(aliases, key) ? !aliasIsBoolean(key) : true)) {
          setArg(key, nextArg, arg);
          i6++;
        } else if (nextArg && (nextArg === "true" || nextArg === "false")) {
          setArg(key, nextArg === "true", arg);
          i6++;
        } else {
          setArg(key, get(flags.strings, key) ? "" : true, arg);
        }
      }
    } else {
      if (!flags.unknownFn || flags.unknownFn(arg) !== false) {
        argv2._.push(flags.strings["_"] ?? !isNumber4(arg) ? arg : Number(arg));
      }
      if (stopEarly) {
        argv2._.push(...args.slice(i6 + 1));
        break;
      }
    }
  }
  for (const [key, value] of Object.entries(defaults)) {
    if (!hasKey(argv2, key.split("."))) {
      setKey(argv2, key, value, false);
      const alias2 = aliases[key];
      if (alias2 !== void 0) {
        for (const x3 of alias2) {
          setKey(argv2, x3, value, false);
        }
      }
    }
  }
  for (const key of Object.keys(flags.bools)) {
    if (!hasKey(argv2, key.split("."))) {
      const value = get(flags.collect, key) ? [] : false;
      setKey(
        argv2,
        key,
        value,
        false
      );
    }
  }
  for (const key of Object.keys(flags.strings)) {
    if (!hasKey(argv2, key.split(".")) && get(flags.collect, key)) {
      setKey(
        argv2,
        key,
        [],
        false
      );
    }
  }
  if (doubleDash) {
    argv2["--"] = [];
    for (const key of notFlags) {
      argv2["--"].push(key);
    }
  } else {
    for (const key of notFlags) {
      argv2._.push(key);
    }
  }
  return argv2;
}

// core/main.ts
init_cleanup();

// core/performance/metrics.ts
init_function_times();
var fileReads = void 0;
function captureFileReads() {
  fileReads = [];
  const originalReadTextFileSync = Deno.readTextFileSync;
  Deno.readTextFileSync = function(path3) {
    try {
      throw new Error("File read");
    } catch (e5) {
      if (!(e5 instanceof Error)) throw e5;
      const stack = e5.stack.split("\n").slice(2);
      fileReads.push({ path: String(path3), stack });
    }
    return originalReadTextFileSync(path3);
  };
}
var metricsObject = {
  inputTargetIndexCache: inputTargetIndexCacheMetrics,
  fileReads,
  functionTimes
};
function quartoPerformanceMetrics(keys) {
  if (!keys) {
    return metricsObject;
  }
  const result2 = {};
  for (const key of keys) {
    if (key === "functionTimes") {
      const metricsObjects = metricsObject[key];
      const entries = Object.entries(metricsObjects);
      result2[key] = Object.fromEntries(
        entries.map(([name2, stats]) => [name2, stats.report()])
      );
    } else {
      result2[key] = metricsObject[key];
    }
  }
  return result2;
}
function reportPerformanceMetrics(keys) {
  const content = JSON.stringify(quartoPerformanceMetrics(keys), null, 2);
  const outFile = Deno.env.get("QUARTO_REPORT_PERFORMANCE_METRICS_FILE");
  if (outFile) {
    Deno.writeTextFileSync(outFile, content);
  } else {
    console.log("---");
    console.log("Performance metrics");
    console.log("Quarto:");
    console.log(content);
  }
}

// core/main.ts
init_function_times();
init_platform();
async function mainRunner(runner) {
  try {
    const args = parse21(Deno.args);
    await initializeLogger(logOptions(args));
    Deno.addSignalListener("SIGINT", abend);
    if (!isWindows4) {
      Deno.addSignalListener("SIGTERM", abend);
    }
    const metricEnv = Deno.env.get("QUARTO_REPORT_PERFORMANCE_METRICS");
    if (metricEnv === "true" || metricEnv?.split(",").includes("fileReads")) {
      captureFileReads();
    }
    const main2 = makeTimedFunctionAsync("main", async () => {
      return await runner(args);
    });
    await main2();
    if (Deno.env.get("QUARTO_TS_PROFILE") !== void 0) {
      console.log("Program finished. Turn off the Chrome profiler now!");
      console.log("Waiting for 10 seconds ...");
      await new Promise((resolve16) => setTimeout(resolve16, 1e4));
    }
    const combinedLuaProfile = Deno.env.get("QUARTO_COMBINED_LUA_PROFILE");
    if (combinedLuaProfile) {
      convertCombinedLuaProfileToCSV(combinedLuaProfile);
    }
    if (metricEnv !== void 0) {
      if (metricEnv !== "true") {
        reportPerformanceMetrics(metricEnv.split(","));
      } else {
        reportPerformanceMetrics();
      }
    }
    exitWithCleanup(0);
  } catch (e5) {
    if (e5) {
      logError(e5);
    }
  } finally {
    abend();
  }
}
function abend() {
  exitWithCleanup(1);
}

// quarto.ts
var checkVersionRequirement = () => {
  const versionReq = Deno.env.get("QUARTO_VERSION_REQUIREMENT");
  if (versionReq) {
    if (!satisfies(quartoConfig.version(), versionReq)) {
      error(
        `Quarto version ${quartoConfig.version()} does not meet semver requirement ${versionReq}`
      );
      Deno.exit(1);
    }
  }
};
var checkReconfiguration = async () => {
  if (quartoConfig.isDebug()) {
    const installed5 = readInstalledDevConfig();
    const source2 = readSourceDevConfig();
    if (installed5 == null || !devConfigsEqual(installed5, source2)) {
      await reconfigureQuarto(installed5, source2);
      Deno.exit(1);
    }
  }
};
var passThroughPandoc = async (args, env2) => {
  const result2 = await execProcess(
    {
      cmd: pandocBinaryPath(),
      args: args.slice(1),
      env: env2
    },
    void 0,
    void 0,
    void 0,
    true
  );
  Deno.exit(result2.code);
};
var passThroughTypst = async (args, env2) => {
  if (args[1] === "update") {
    error(
      "The 'typst update' command is not supported.\nPlease install the latest version of Quarto from http://quarto.org to get the latest supported typst features."
    );
    Deno.exit(1);
  }
  const result2 = await execProcess({
    cmd: typstBinaryPath(),
    args: args.slice(1),
    env: env2
  });
  Deno.exit(result2.code);
};
async function quarto4(args, cmdHandler, env2) {
  await checkReconfiguration();
  checkVersionRequirement();
  if (args[0] === "pandoc" && args[1] !== "help") {
    await passThroughPandoc(args, env2);
  }
  if (args[0] === "typst") {
    await passThroughTypst(args, env2);
  }
  if (args[0] === "run" && args[1] !== "help" && args[1] !== "--help") {
    const result2 = await runScript(args.slice(1), env2);
    Deno.exit(result2.code);
  }
  if (args.length > 1 && (args[0] === "render" || args[0] === "preview") && args[1].startsWith("-")) {
    args = [args[0], kCliffyImplicitCwd, ...args.slice(1)];
  }
  debug("Quarto version: " + quartoConfig.version());
  const oldEnv = {};
  for (const [key, value] of Object.entries(env2 || {})) {
    const oldV = Deno.env.get(key);
    oldEnv[key] = oldV;
    Deno.env.set(key, value);
  }
  const quartoCommand = new Command().name("quarto").help({ colors: false }).version(quartoConfig.version() + "\n").description("Quarto CLI").throwErrors();
  commands().forEach((command) => {
    command.help({ colors: false });
    quartoCommand.command(
      command.getName(),
      cmdHandler !== void 0 ? cmdHandler(command) : command
    );
  });
  initSessionTempDir();
  onCleanup(cleanupSessionTempDir);
  const promise = quartoCommand.command("help", new HelpCommand().global()).command("completions", new CompletionsCommand()).hidden().parse(args);
  try {
    await promise;
    if (commandFailed()) {
      exitWithCleanup(1);
    }
  } catch (e5) {
    if (e5 instanceof CommandError) {
      logError(e5, false);
      exitWithCleanup(1);
    } else {
      throw e5;
    }
  } finally {
    for (const [key, value] of Object.entries(oldEnv)) {
      if (value === void 0) {
        Deno.env.delete(key);
      } else {
        Deno.env.set(key, value);
      }
    }
  }
}
if (import.meta.main) {
  await mainRunner(async (args) => {
    let quartoArgs = [...Deno.args];
    if (setProfileFromArg(args)) {
      const removeArgs = /* @__PURE__ */ new Map();
      removeArgs.set("--profile", true);
      quartoArgs = removeFlags(quartoArgs, removeArgs);
    }
    await quarto4(quartoArgs, (cmd) => {
      cmd = appendLogOptions(cmd);
      return appendProfileArg(cmd);
    });
    if (commandFailed()) {
      exitWithCleanup(1);
    }
  });
}
export {
  quarto4 as quarto
};
/*! @author Toru Nagashima <https://github.com/mysticatea> */
/*! js-yaml 4.1.0 https://github.com/nodeca/js-yaml @license MIT */
/*! js-yaml 4.1.1 https://github.com/nodeca/js-yaml @license MIT */
/*!
 * Sizzle CSS Selector Engine v2.3.7-pre
 * https://sizzlejs.com/
 *
 * Copyright JS Foundation and other contributors
 * Released under the MIT license
 * https://js.foundation/
 *
 * Date: 2022-04-02
 *
 * git commit hash for Deno DOM: ede0e97563c8473b8cfa4045c7c2cd6129ecc1aa
 */
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
/*!
 * Ported from: https://github.com/jshttp/mime-db and licensed as:
 *
 * (The MIT License)
 *
 * Copyright (c) 2014 Jonathan Ong <me@jongleberry.com>
 * Copyright (c) 2020 the Deno authors
 * Copyright (c) 2020 the oak authors
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * 'Software'), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
/*!
 * Ported from: https://github.com/jshttp/mime-types and licensed as:
 *
 * (The MIT License)
 *
 * Copyright (c) 2014 Jonathan Ong <me@jongleberry.com>
 * Copyright (c) 2015 Douglas Christopher Wilson <doug@somethingdoug.com>
 * Copyright (c) 2020 the Deno authors
 * Copyright (c) 2020 the oak authors
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * 'Software'), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
