/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/

"use strict";
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, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from2, except, desc) => {
  if (from2 && typeof from2 === "object" || typeof from2 === "function") {
    for (let key of __getOwnPropNames(from2))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from2[key], enumerable: !(desc = __getOwnPropDesc(from2, 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
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// node_modules/buffer-es6/base64.js
function init() {
  inited = true;
  var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  for (var i = 0, len = code.length; i < len; ++i) {
    lookup[i] = code[i];
    revLookup[code.charCodeAt(i)] = i;
  }
  revLookup["-".charCodeAt(0)] = 62;
  revLookup["_".charCodeAt(0)] = 63;
}
function toByteArray(b64) {
  if (!inited) {
    init();
  }
  var i, j, l2, tmp, placeHolders, arr;
  var len = b64.length;
  if (len % 4 > 0) {
    throw new Error("Invalid string. Length must be a multiple of 4");
  }
  placeHolders = b64[len - 2] === "=" ? 2 : b64[len - 1] === "=" ? 1 : 0;
  arr = new Arr(len * 3 / 4 - placeHolders);
  l2 = placeHolders > 0 ? len - 4 : len;
  var L = 0;
  for (i = 0, j = 0; i < l2; i += 4, j += 3) {
    tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)];
    arr[L++] = tmp >> 16 & 255;
    arr[L++] = tmp >> 8 & 255;
    arr[L++] = tmp & 255;
  }
  if (placeHolders === 2) {
    tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4;
    arr[L++] = tmp & 255;
  } else if (placeHolders === 1) {
    tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2;
    arr[L++] = tmp >> 8 & 255;
    arr[L++] = tmp & 255;
  }
  return arr;
}
function tripletToBase64(num) {
  return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63];
}
function encodeChunk(uint8, start, end) {
  var tmp;
  var output = [];
  for (var i = start; i < end; i += 3) {
    tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + uint8[i + 2];
    output.push(tripletToBase64(tmp));
  }
  return output.join("");
}
function fromByteArray(uint8) {
  if (!inited) {
    init();
  }
  var tmp;
  var len = uint8.length;
  var extraBytes = len % 3;
  var output = "";
  var parts = [];
  var maxChunkLength = 16383;
  for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
    parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength));
  }
  if (extraBytes === 1) {
    tmp = uint8[len - 1];
    output += lookup[tmp >> 2];
    output += lookup[tmp << 4 & 63];
    output += "==";
  } else if (extraBytes === 2) {
    tmp = (uint8[len - 2] << 8) + uint8[len - 1];
    output += lookup[tmp >> 10];
    output += lookup[tmp >> 4 & 63];
    output += lookup[tmp << 2 & 63];
    output += "=";
  }
  parts.push(output);
  return parts.join("");
}
var lookup, revLookup, Arr, inited;
var init_base64 = __esm({
  "node_modules/buffer-es6/base64.js"() {
    init_esbuild_buffer_shim();
    lookup = [];
    revLookup = [];
    Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array;
    inited = false;
  }
});

// node_modules/buffer-es6/ieee754.js
function read(buffer, offset2, isLE, mLen, nBytes) {
  var e, m;
  var eLen = nBytes * 8 - mLen - 1;
  var eMax = (1 << eLen) - 1;
  var eBias = eMax >> 1;
  var nBits = -7;
  var i = isLE ? nBytes - 1 : 0;
  var d = isLE ? -1 : 1;
  var s2 = buffer[offset2 + i];
  i += d;
  e = s2 & (1 << -nBits) - 1;
  s2 >>= -nBits;
  nBits += eLen;
  for (; nBits > 0; e = e * 256 + buffer[offset2 + i], i += d, nBits -= 8) {
  }
  m = e & (1 << -nBits) - 1;
  e >>= -nBits;
  nBits += mLen;
  for (; nBits > 0; m = m * 256 + buffer[offset2 + i], i += d, nBits -= 8) {
  }
  if (e === 0) {
    e = 1 - eBias;
  } else if (e === eMax) {
    return m ? NaN : (s2 ? -1 : 1) * Infinity;
  } else {
    m = m + Math.pow(2, mLen);
    e = e - eBias;
  }
  return (s2 ? -1 : 1) * m * Math.pow(2, e - mLen);
}
function write(buffer, value, offset2, isLE, mLen, nBytes) {
  var e, m, c;
  var eLen = nBytes * 8 - mLen - 1;
  var eMax = (1 << eLen) - 1;
  var eBias = eMax >> 1;
  var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
  var i = isLE ? 0 : nBytes - 1;
  var d = isLE ? 1 : -1;
  var s2 = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
  value = Math.abs(value);
  if (isNaN(value) || value === Infinity) {
    m = isNaN(value) ? 1 : 0;
    e = eMax;
  } else {
    e = Math.floor(Math.log(value) / Math.LN2);
    if (value * (c = Math.pow(2, -e)) < 1) {
      e--;
      c *= 2;
    }
    if (e + eBias >= 1) {
      value += rt / c;
    } else {
      value += rt * Math.pow(2, 1 - eBias);
    }
    if (value * c >= 2) {
      e++;
      c /= 2;
    }
    if (e + eBias >= eMax) {
      m = 0;
      e = eMax;
    } else if (e + eBias >= 1) {
      m = (value * c - 1) * Math.pow(2, mLen);
      e = e + eBias;
    } else {
      m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
      e = 0;
    }
  }
  for (; mLen >= 8; buffer[offset2 + i] = m & 255, i += d, m /= 256, mLen -= 8) {
  }
  e = e << mLen | m;
  eLen += mLen;
  for (; eLen > 0; buffer[offset2 + i] = e & 255, i += d, e /= 256, eLen -= 8) {
  }
  buffer[offset2 + i - d] |= s2 * 128;
}
var init_ieee754 = __esm({
  "node_modules/buffer-es6/ieee754.js"() {
    init_esbuild_buffer_shim();
  }
});

// node_modules/buffer-es6/isArray.js
var toString, isArray_default;
var init_isArray = __esm({
  "node_modules/buffer-es6/isArray.js"() {
    init_esbuild_buffer_shim();
    toString = {}.toString;
    isArray_default = Array.isArray || function(arr) {
      return toString.call(arr) == "[object Array]";
    };
  }
});

// node_modules/buffer-es6/index.js
var buffer_es6_exports = {};
__export(buffer_es6_exports, {
  Buffer: () => Buffer2,
  INSPECT_MAX_BYTES: () => INSPECT_MAX_BYTES,
  SlowBuffer: () => SlowBuffer,
  isBuffer: () => isBuffer,
  kMaxLength: () => _kMaxLength
});
function kMaxLength() {
  return Buffer2.TYPED_ARRAY_SUPPORT ? 2147483647 : 1073741823;
}
function createBuffer(that, length) {
  if (kMaxLength() < length) {
    throw new RangeError("Invalid typed array length");
  }
  if (Buffer2.TYPED_ARRAY_SUPPORT) {
    that = new Uint8Array(length);
    that.__proto__ = Buffer2.prototype;
  } else {
    if (that === null) {
      that = new Buffer2(length);
    }
    that.length = length;
  }
  return that;
}
function Buffer2(arg, encodingOrOffset, length) {
  if (!Buffer2.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer2)) {
    return new Buffer2(arg, encodingOrOffset, length);
  }
  if (typeof arg === "number") {
    if (typeof encodingOrOffset === "string") {
      throw new Error(
        "If encoding is specified then the first argument must be a string"
      );
    }
    return allocUnsafe(this, arg);
  }
  return from(this, arg, encodingOrOffset, length);
}
function from(that, value, encodingOrOffset, length) {
  if (typeof value === "number") {
    throw new TypeError('"value" argument must not be a number');
  }
  if (typeof ArrayBuffer !== "undefined" && value instanceof ArrayBuffer) {
    return fromArrayBuffer(that, value, encodingOrOffset, length);
  }
  if (typeof value === "string") {
    return fromString(that, value, encodingOrOffset);
  }
  return fromObject(that, value);
}
function assertSize(size) {
  if (typeof size !== "number") {
    throw new TypeError('"size" argument must be a number');
  } else if (size < 0) {
    throw new RangeError('"size" argument must not be negative');
  }
}
function alloc(that, size, fill2, encoding) {
  assertSize(size);
  if (size <= 0) {
    return createBuffer(that, size);
  }
  if (fill2 !== void 0) {
    return typeof encoding === "string" ? createBuffer(that, size).fill(fill2, encoding) : createBuffer(that, size).fill(fill2);
  }
  return createBuffer(that, size);
}
function allocUnsafe(that, size) {
  assertSize(size);
  that = createBuffer(that, size < 0 ? 0 : checked(size) | 0);
  if (!Buffer2.TYPED_ARRAY_SUPPORT) {
    for (var i = 0; i < size; ++i) {
      that[i] = 0;
    }
  }
  return that;
}
function fromString(that, string, encoding) {
  if (typeof encoding !== "string" || encoding === "") {
    encoding = "utf8";
  }
  if (!Buffer2.isEncoding(encoding)) {
    throw new TypeError('"encoding" must be a valid string encoding');
  }
  var length = byteLength(string, encoding) | 0;
  that = createBuffer(that, length);
  var actual = that.write(string, encoding);
  if (actual !== length) {
    that = that.slice(0, actual);
  }
  return that;
}
function fromArrayLike(that, array) {
  var length = array.length < 0 ? 0 : checked(array.length) | 0;
  that = createBuffer(that, length);
  for (var i = 0; i < length; i += 1) {
    that[i] = array[i] & 255;
  }
  return that;
}
function fromArrayBuffer(that, array, byteOffset, length) {
  array.byteLength;
  if (byteOffset < 0 || array.byteLength < byteOffset) {
    throw new RangeError("'offset' is out of bounds");
  }
  if (array.byteLength < byteOffset + (length || 0)) {
    throw new RangeError("'length' is out of bounds");
  }
  if (byteOffset === void 0 && length === void 0) {
    array = new Uint8Array(array);
  } else if (length === void 0) {
    array = new Uint8Array(array, byteOffset);
  } else {
    array = new Uint8Array(array, byteOffset, length);
  }
  if (Buffer2.TYPED_ARRAY_SUPPORT) {
    that = array;
    that.__proto__ = Buffer2.prototype;
  } else {
    that = fromArrayLike(that, array);
  }
  return that;
}
function fromObject(that, obj) {
  if (internalIsBuffer(obj)) {
    var len = checked(obj.length) | 0;
    that = createBuffer(that, len);
    if (that.length === 0) {
      return that;
    }
    obj.copy(that, 0, 0, len);
    return that;
  }
  if (obj) {
    if (typeof ArrayBuffer !== "undefined" && obj.buffer instanceof ArrayBuffer || "length" in obj) {
      if (typeof obj.length !== "number" || isnan(obj.length)) {
        return createBuffer(that, 0);
      }
      return fromArrayLike(that, obj);
    }
    if (obj.type === "Buffer" && isArray_default(obj.data)) {
      return fromArrayLike(that, obj.data);
    }
  }
  throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.");
}
function checked(length) {
  if (length >= kMaxLength()) {
    throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + kMaxLength().toString(16) + " bytes");
  }
  return length | 0;
}
function SlowBuffer(length) {
  if (+length != length) {
    length = 0;
  }
  return Buffer2.alloc(+length);
}
function internalIsBuffer(b) {
  return !!(b != null && b._isBuffer);
}
function byteLength(string, encoding) {
  if (internalIsBuffer(string)) {
    return string.length;
  }
  if (typeof ArrayBuffer !== "undefined" && typeof ArrayBuffer.isView === "function" && (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
    return string.byteLength;
  }
  if (typeof string !== "string") {
    string = "" + string;
  }
  var len = string.length;
  if (len === 0) return 0;
  var loweredCase = false;
  for (; ; ) {
    switch (encoding) {
      case "ascii":
      case "latin1":
      case "binary":
        return len;
      case "utf8":
      case "utf-8":
      case void 0:
        return utf8ToBytes(string).length;
      case "ucs2":
      case "ucs-2":
      case "utf16le":
      case "utf-16le":
        return len * 2;
      case "hex":
        return len >>> 1;
      case "base64":
        return base64ToBytes(string).length;
      default:
        if (loweredCase) return utf8ToBytes(string).length;
        encoding = ("" + encoding).toLowerCase();
        loweredCase = true;
    }
  }
}
function slowToString(encoding, start, end) {
  var 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;
    }
  }
}
function swap(b, n2, m) {
  var i = b[n2];
  b[n2] = b[m];
  b[m] = i;
}
function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) {
  if (buffer.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 (isNaN(byteOffset)) {
    byteOffset = dir ? 0 : buffer.length - 1;
  }
  if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
  if (byteOffset >= buffer.length) {
    if (dir) return -1;
    else byteOffset = buffer.length - 1;
  } else if (byteOffset < 0) {
    if (dir) byteOffset = 0;
    else return -1;
  }
  if (typeof val === "string") {
    val = Buffer2.from(val, encoding);
  }
  if (internalIsBuffer(val)) {
    if (val.length === 0) {
      return -1;
    }
    return arrayIndexOf(buffer, val, byteOffset, encoding, dir);
  } else if (typeof val === "number") {
    val = val & 255;
    if (Buffer2.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === "function") {
      if (dir) {
        return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset);
      } else {
        return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset);
      }
    }
    return arrayIndexOf(buffer, [val], byteOffset, encoding, dir);
  }
  throw new TypeError("val must be string, number or Buffer");
}
function arrayIndexOf(arr, val, byteOffset, encoding, dir) {
  var indexSize = 1;
  var arrLength = arr.length;
  var 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 read2(buf, i2) {
    if (indexSize === 1) {
      return buf[i2];
    } else {
      return buf.readUInt16BE(i2 * indexSize);
    }
  }
  var i;
  if (dir) {
    var foundIndex = -1;
    for (i = byteOffset; i < arrLength; i++) {
      if (read2(arr, i) === read2(val, foundIndex === -1 ? 0 : i - foundIndex)) {
        if (foundIndex === -1) foundIndex = i;
        if (i - foundIndex + 1 === valLength) return foundIndex * indexSize;
      } else {
        if (foundIndex !== -1) i -= i - foundIndex;
        foundIndex = -1;
      }
    }
  } else {
    if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
    for (i = byteOffset; i >= 0; i--) {
      var found = true;
      for (var j = 0; j < valLength; j++) {
        if (read2(arr, i + j) !== read2(val, j)) {
          found = false;
          break;
        }
      }
      if (found) return i;
    }
  }
  return -1;
}
function hexWrite(buf, string, offset2, length) {
  offset2 = Number(offset2) || 0;
  var remaining = buf.length - offset2;
  if (!length) {
    length = remaining;
  } else {
    length = Number(length);
    if (length > remaining) {
      length = remaining;
    }
  }
  var strLen = string.length;
  if (strLen % 2 !== 0) throw new TypeError("Invalid hex string");
  if (length > strLen / 2) {
    length = strLen / 2;
  }
  for (var i = 0; i < length; ++i) {
    var parsed = parseInt(string.substr(i * 2, 2), 16);
    if (isNaN(parsed)) return i;
    buf[offset2 + i] = parsed;
  }
  return i;
}
function utf8Write(buf, string, offset2, length) {
  return blitBuffer(utf8ToBytes(string, buf.length - offset2), buf, offset2, length);
}
function asciiWrite(buf, string, offset2, length) {
  return blitBuffer(asciiToBytes(string), buf, offset2, length);
}
function latin1Write(buf, string, offset2, length) {
  return asciiWrite(buf, string, offset2, length);
}
function base64Write(buf, string, offset2, length) {
  return blitBuffer(base64ToBytes(string), buf, offset2, length);
}
function ucs2Write(buf, string, offset2, length) {
  return blitBuffer(utf16leToBytes(string, buf.length - offset2), buf, offset2, length);
}
function base64Slice(buf, start, end) {
  if (start === 0 && end === buf.length) {
    return fromByteArray(buf);
  } else {
    return fromByteArray(buf.slice(start, end));
  }
}
function utf8Slice(buf, start, end) {
  end = Math.min(buf.length, end);
  var res = [];
  var i = start;
  while (i < end) {
    var firstByte = buf[i];
    var codePoint = null;
    var bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1;
    if (i + bytesPerSequence <= end) {
      var secondByte, thirdByte, fourthByte, tempCodePoint;
      switch (bytesPerSequence) {
        case 1:
          if (firstByte < 128) {
            codePoint = firstByte;
          }
          break;
        case 2:
          secondByte = buf[i + 1];
          if ((secondByte & 192) === 128) {
            tempCodePoint = (firstByte & 31) << 6 | secondByte & 63;
            if (tempCodePoint > 127) {
              codePoint = tempCodePoint;
            }
          }
          break;
        case 3:
          secondByte = buf[i + 1];
          thirdByte = buf[i + 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[i + 1];
          thirdByte = buf[i + 2];
          fourthByte = buf[i + 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);
    i += bytesPerSequence;
  }
  return decodeCodePointsArray(res);
}
function decodeCodePointsArray(codePoints) {
  var len = codePoints.length;
  if (len <= MAX_ARGUMENTS_LENGTH) {
    return String.fromCharCode.apply(String, codePoints);
  }
  var res = "";
  var i = 0;
  while (i < len) {
    res += String.fromCharCode.apply(
      String,
      codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
    );
  }
  return res;
}
function asciiSlice(buf, start, end) {
  var ret = "";
  end = Math.min(buf.length, end);
  for (var i = start; i < end; ++i) {
    ret += String.fromCharCode(buf[i] & 127);
  }
  return ret;
}
function latin1Slice(buf, start, end) {
  var ret = "";
  end = Math.min(buf.length, end);
  for (var i = start; i < end; ++i) {
    ret += String.fromCharCode(buf[i]);
  }
  return ret;
}
function hexSlice(buf, start, end) {
  var len = buf.length;
  if (!start || start < 0) start = 0;
  if (!end || end < 0 || end > len) end = len;
  var out = "";
  for (var i = start; i < end; ++i) {
    out += toHex(buf[i]);
  }
  return out;
}
function utf16leSlice(buf, start, end) {
  var bytes = buf.slice(start, end);
  var res = "";
  for (var i = 0; i < bytes.length; i += 2) {
    res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
  }
  return res;
}
function checkOffset(offset2, ext, length) {
  if (offset2 % 1 !== 0 || offset2 < 0) throw new RangeError("offset is not uint");
  if (offset2 + ext > length) throw new RangeError("Trying to access beyond buffer length");
}
function checkInt(buf, value, offset2, ext, max, min) {
  if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance');
  if (value > max || value < min) throw new RangeError('"value" argument is out of bounds');
  if (offset2 + ext > buf.length) throw new RangeError("Index out of range");
}
function objectWriteUInt16(buf, value, offset2, littleEndian) {
  if (value < 0) value = 65535 + value + 1;
  for (var i = 0, j = Math.min(buf.length - offset2, 2); i < j; ++i) {
    buf[offset2 + i] = (value & 255 << 8 * (littleEndian ? i : 1 - i)) >>> (littleEndian ? i : 1 - i) * 8;
  }
}
function objectWriteUInt32(buf, value, offset2, littleEndian) {
  if (value < 0) value = 4294967295 + value + 1;
  for (var i = 0, j = Math.min(buf.length - offset2, 4); i < j; ++i) {
    buf[offset2 + i] = value >>> (littleEndian ? i : 3 - i) * 8 & 255;
  }
}
function checkIEEE754(buf, value, offset2, ext, max, min) {
  if (offset2 + ext > buf.length) throw new RangeError("Index out of range");
  if (offset2 < 0) throw new RangeError("Index out of range");
}
function writeFloat(buf, value, offset2, littleEndian, noAssert) {
  if (!noAssert) {
    checkIEEE754(buf, value, offset2, 4, 34028234663852886e22, -34028234663852886e22);
  }
  write(buf, value, offset2, littleEndian, 23, 4);
  return offset2 + 4;
}
function writeDouble(buf, value, offset2, littleEndian, noAssert) {
  if (!noAssert) {
    checkIEEE754(buf, value, offset2, 8, 17976931348623157e292, -17976931348623157e292);
  }
  write(buf, value, offset2, littleEndian, 52, 8);
  return offset2 + 8;
}
function base64clean(str) {
  str = stringtrim(str).replace(INVALID_BASE64_RE, "");
  if (str.length < 2) return "";
  while (str.length % 4 !== 0) {
    str = str + "=";
  }
  return str;
}
function stringtrim(str) {
  if (str.trim) return str.trim();
  return str.replace(/^\s+|\s+$/g, "");
}
function toHex(n2) {
  if (n2 < 16) return "0" + n2.toString(16);
  return n2.toString(16);
}
function utf8ToBytes(string, units) {
  units = units || Infinity;
  var codePoint;
  var length = string.length;
  var leadSurrogate = null;
  var bytes = [];
  for (var i = 0; i < length; ++i) {
    codePoint = string.charCodeAt(i);
    if (codePoint > 55295 && codePoint < 57344) {
      if (!leadSurrogate) {
        if (codePoint > 56319) {
          if ((units -= 3) > -1) bytes.push(239, 191, 189);
          continue;
        } else if (i + 1 === length) {
          if ((units -= 3) > -1) bytes.push(239, 191, 189);
          continue;
        }
        leadSurrogate = codePoint;
        continue;
      }
      if (codePoint < 56320) {
        if ((units -= 3) > -1) bytes.push(239, 191, 189);
        leadSurrogate = codePoint;
        continue;
      }
      codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536;
    } else if (leadSurrogate) {
      if ((units -= 3) > -1) bytes.push(239, 191, 189);
    }
    leadSurrogate = null;
    if (codePoint < 128) {
      if ((units -= 1) < 0) break;
      bytes.push(codePoint);
    } else if (codePoint < 2048) {
      if ((units -= 2) < 0) break;
      bytes.push(
        codePoint >> 6 | 192,
        codePoint & 63 | 128
      );
    } else if (codePoint < 65536) {
      if ((units -= 3) < 0) break;
      bytes.push(
        codePoint >> 12 | 224,
        codePoint >> 6 & 63 | 128,
        codePoint & 63 | 128
      );
    } else if (codePoint < 1114112) {
      if ((units -= 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(str) {
  var byteArray = [];
  for (var i = 0; i < str.length; ++i) {
    byteArray.push(str.charCodeAt(i) & 255);
  }
  return byteArray;
}
function utf16leToBytes(str, units) {
  var c, hi, lo;
  var byteArray = [];
  for (var i = 0; i < str.length; ++i) {
    if ((units -= 2) < 0) break;
    c = str.charCodeAt(i);
    hi = c >> 8;
    lo = c % 256;
    byteArray.push(lo);
    byteArray.push(hi);
  }
  return byteArray;
}
function base64ToBytes(str) {
  return toByteArray(base64clean(str));
}
function blitBuffer(src, dst, offset2, length) {
  for (var i = 0; i < length; ++i) {
    if (i + offset2 >= dst.length || i >= src.length) break;
    dst[i + offset2] = src[i];
  }
  return i;
}
function isnan(val) {
  return val !== val;
}
function isBuffer(obj) {
  return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj));
}
function isFastBuffer(obj) {
  return !!obj.constructor && typeof obj.constructor.isBuffer === "function" && obj.constructor.isBuffer(obj);
}
function isSlowBuffer(obj) {
  return typeof obj.readFloatLE === "function" && typeof obj.slice === "function" && isFastBuffer(obj.slice(0, 0));
}
var INSPECT_MAX_BYTES, _kMaxLength, MAX_ARGUMENTS_LENGTH, INVALID_BASE64_RE;
var init_buffer_es6 = __esm({
  "node_modules/buffer-es6/index.js"() {
    init_esbuild_buffer_shim();
    init_base64();
    init_ieee754();
    init_isArray();
    INSPECT_MAX_BYTES = 50;
    Buffer2.TYPED_ARRAY_SUPPORT = globalThis.TYPED_ARRAY_SUPPORT !== void 0 ? globalThis.TYPED_ARRAY_SUPPORT : true;
    _kMaxLength = kMaxLength();
    Buffer2.poolSize = 8192;
    Buffer2._augment = function(arr) {
      arr.__proto__ = Buffer2.prototype;
      return arr;
    };
    Buffer2.from = function(value, encodingOrOffset, length) {
      return from(null, value, encodingOrOffset, length);
    };
    if (Buffer2.TYPED_ARRAY_SUPPORT) {
      Buffer2.prototype.__proto__ = Uint8Array.prototype;
      Buffer2.__proto__ = Uint8Array;
      if (typeof Symbol !== "undefined" && Symbol.species && Buffer2[Symbol.species] === Buffer2) {
      }
    }
    Buffer2.alloc = function(size, fill2, encoding) {
      return alloc(null, size, fill2, encoding);
    };
    Buffer2.allocUnsafe = function(size) {
      return allocUnsafe(null, size);
    };
    Buffer2.allocUnsafeSlow = function(size) {
      return allocUnsafe(null, size);
    };
    Buffer2.isBuffer = isBuffer;
    Buffer2.compare = function compare(a, b) {
      if (!internalIsBuffer(a) || !internalIsBuffer(b)) {
        throw new TypeError("Arguments must be Buffers");
      }
      if (a === b) return 0;
      var x = a.length;
      var y = b.length;
      for (var i = 0, len = Math.min(x, y); i < len; ++i) {
        if (a[i] !== b[i]) {
          x = a[i];
          y = b[i];
          break;
        }
      }
      if (x < y) return -1;
      if (y < x) return 1;
      return 0;
    };
    Buffer2.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;
      }
    };
    Buffer2.concat = function concat(list, length) {
      if (!isArray_default(list)) {
        throw new TypeError('"list" argument must be an Array of Buffers');
      }
      if (list.length === 0) {
        return Buffer2.alloc(0);
      }
      var i;
      if (length === void 0) {
        length = 0;
        for (i = 0; i < list.length; ++i) {
          length += list[i].length;
        }
      }
      var buffer = Buffer2.allocUnsafe(length);
      var pos = 0;
      for (i = 0; i < list.length; ++i) {
        var buf = list[i];
        if (!internalIsBuffer(buf)) {
          throw new TypeError('"list" argument must be an Array of Buffers');
        }
        buf.copy(buffer, pos);
        pos += buf.length;
      }
      return buffer;
    };
    Buffer2.byteLength = byteLength;
    Buffer2.prototype._isBuffer = true;
    Buffer2.prototype.swap16 = function swap16() {
      var len = this.length;
      if (len % 2 !== 0) {
        throw new RangeError("Buffer size must be a multiple of 16-bits");
      }
      for (var i = 0; i < len; i += 2) {
        swap(this, i, i + 1);
      }
      return this;
    };
    Buffer2.prototype.swap32 = function swap32() {
      var len = this.length;
      if (len % 4 !== 0) {
        throw new RangeError("Buffer size must be a multiple of 32-bits");
      }
      for (var i = 0; i < len; i += 4) {
        swap(this, i, i + 3);
        swap(this, i + 1, i + 2);
      }
      return this;
    };
    Buffer2.prototype.swap64 = function swap64() {
      var len = this.length;
      if (len % 8 !== 0) {
        throw new RangeError("Buffer size must be a multiple of 64-bits");
      }
      for (var i = 0; i < len; i += 8) {
        swap(this, i, i + 7);
        swap(this, i + 1, i + 6);
        swap(this, i + 2, i + 5);
        swap(this, i + 3, i + 4);
      }
      return this;
    };
    Buffer2.prototype.toString = function toString2() {
      var length = this.length | 0;
      if (length === 0) return "";
      if (arguments.length === 0) return utf8Slice(this, 0, length);
      return slowToString.apply(this, arguments);
    };
    Buffer2.prototype.equals = function equals(b) {
      if (!internalIsBuffer(b)) throw new TypeError("Argument must be a Buffer");
      if (this === b) return true;
      return Buffer2.compare(this, b) === 0;
    };
    Buffer2.prototype.inspect = function inspect() {
      var str = "";
      var max = INSPECT_MAX_BYTES;
      if (this.length > 0) {
        str = this.toString("hex", 0, max).match(/.{2}/g).join(" ");
        if (this.length > max) str += " ... ";
      }
      return "<Buffer " + str + ">";
    };
    Buffer2.prototype.compare = function compare2(target, start, end, thisStart, thisEnd) {
      if (!internalIsBuffer(target)) {
        throw new TypeError("Argument must be a Buffer");
      }
      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;
      var x = thisEnd - thisStart;
      var y = end - start;
      var len = Math.min(x, y);
      var thisCopy = this.slice(thisStart, thisEnd);
      var targetCopy = target.slice(start, end);
      for (var i = 0; i < len; ++i) {
        if (thisCopy[i] !== targetCopy[i]) {
          x = thisCopy[i];
          y = targetCopy[i];
          break;
        }
      }
      if (x < y) return -1;
      if (y < x) return 1;
      return 0;
    };
    Buffer2.prototype.includes = function includes(val, byteOffset, encoding) {
      return this.indexOf(val, byteOffset, encoding) !== -1;
    };
    Buffer2.prototype.indexOf = function indexOf(val, byteOffset, encoding) {
      return bidirectionalIndexOf(this, val, byteOffset, encoding, true);
    };
    Buffer2.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) {
      return bidirectionalIndexOf(this, val, byteOffset, encoding, false);
    };
    Buffer2.prototype.write = function write2(string, offset2, length, encoding) {
      if (offset2 === void 0) {
        encoding = "utf8";
        length = this.length;
        offset2 = 0;
      } else if (length === void 0 && typeof offset2 === "string") {
        encoding = offset2;
        length = this.length;
        offset2 = 0;
      } else if (isFinite(offset2)) {
        offset2 = offset2 | 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"
        );
      }
      var remaining = this.length - offset2;
      if (length === void 0 || length > remaining) length = remaining;
      if (string.length > 0 && (length < 0 || offset2 < 0) || offset2 > this.length) {
        throw new RangeError("Attempt to write outside buffer bounds");
      }
      if (!encoding) encoding = "utf8";
      var loweredCase = false;
      for (; ; ) {
        switch (encoding) {
          case "hex":
            return hexWrite(this, string, offset2, length);
          case "utf8":
          case "utf-8":
            return utf8Write(this, string, offset2, length);
          case "ascii":
            return asciiWrite(this, string, offset2, length);
          case "latin1":
          case "binary":
            return latin1Write(this, string, offset2, length);
          case "base64":
            return base64Write(this, string, offset2, length);
          case "ucs2":
          case "ucs-2":
          case "utf16le":
          case "utf-16le":
            return ucs2Write(this, string, offset2, length);
          default:
            if (loweredCase) throw new TypeError("Unknown encoding: " + encoding);
            encoding = ("" + encoding).toLowerCase();
            loweredCase = true;
        }
      }
    };
    Buffer2.prototype.toJSON = function toJSON() {
      return {
        type: "Buffer",
        data: Array.prototype.slice.call(this._arr || this, 0)
      };
    };
    MAX_ARGUMENTS_LENGTH = 4096;
    Buffer2.prototype.slice = function slice(start, end) {
      var 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;
      var newBuf;
      if (Buffer2.TYPED_ARRAY_SUPPORT) {
        newBuf = this.subarray(start, end);
        newBuf.__proto__ = Buffer2.prototype;
      } else {
        var sliceLen = end - start;
        newBuf = new Buffer2(sliceLen, void 0);
        for (var i = 0; i < sliceLen; ++i) {
          newBuf[i] = this[i + start];
        }
      }
      return newBuf;
    };
    Buffer2.prototype.readUIntLE = function readUIntLE(offset2, byteLength2, noAssert) {
      offset2 = offset2 | 0;
      byteLength2 = byteLength2 | 0;
      if (!noAssert) checkOffset(offset2, byteLength2, this.length);
      var val = this[offset2];
      var mul = 1;
      var i = 0;
      while (++i < byteLength2 && (mul *= 256)) {
        val += this[offset2 + i] * mul;
      }
      return val;
    };
    Buffer2.prototype.readUIntBE = function readUIntBE(offset2, byteLength2, noAssert) {
      offset2 = offset2 | 0;
      byteLength2 = byteLength2 | 0;
      if (!noAssert) {
        checkOffset(offset2, byteLength2, this.length);
      }
      var val = this[offset2 + --byteLength2];
      var mul = 1;
      while (byteLength2 > 0 && (mul *= 256)) {
        val += this[offset2 + --byteLength2] * mul;
      }
      return val;
    };
    Buffer2.prototype.readUInt8 = function readUInt8(offset2, noAssert) {
      if (!noAssert) checkOffset(offset2, 1, this.length);
      return this[offset2];
    };
    Buffer2.prototype.readUInt16LE = function readUInt16LE(offset2, noAssert) {
      if (!noAssert) checkOffset(offset2, 2, this.length);
      return this[offset2] | this[offset2 + 1] << 8;
    };
    Buffer2.prototype.readUInt16BE = function readUInt16BE(offset2, noAssert) {
      if (!noAssert) checkOffset(offset2, 2, this.length);
      return this[offset2] << 8 | this[offset2 + 1];
    };
    Buffer2.prototype.readUInt32LE = function readUInt32LE(offset2, noAssert) {
      if (!noAssert) checkOffset(offset2, 4, this.length);
      return (this[offset2] | this[offset2 + 1] << 8 | this[offset2 + 2] << 16) + this[offset2 + 3] * 16777216;
    };
    Buffer2.prototype.readUInt32BE = function readUInt32BE(offset2, noAssert) {
      if (!noAssert) checkOffset(offset2, 4, this.length);
      return this[offset2] * 16777216 + (this[offset2 + 1] << 16 | this[offset2 + 2] << 8 | this[offset2 + 3]);
    };
    Buffer2.prototype.readIntLE = function readIntLE(offset2, byteLength2, noAssert) {
      offset2 = offset2 | 0;
      byteLength2 = byteLength2 | 0;
      if (!noAssert) checkOffset(offset2, byteLength2, this.length);
      var val = this[offset2];
      var mul = 1;
      var i = 0;
      while (++i < byteLength2 && (mul *= 256)) {
        val += this[offset2 + i] * mul;
      }
      mul *= 128;
      if (val >= mul) val -= Math.pow(2, 8 * byteLength2);
      return val;
    };
    Buffer2.prototype.readIntBE = function readIntBE(offset2, byteLength2, noAssert) {
      offset2 = offset2 | 0;
      byteLength2 = byteLength2 | 0;
      if (!noAssert) checkOffset(offset2, byteLength2, this.length);
      var i = byteLength2;
      var mul = 1;
      var val = this[offset2 + --i];
      while (i > 0 && (mul *= 256)) {
        val += this[offset2 + --i] * mul;
      }
      mul *= 128;
      if (val >= mul) val -= Math.pow(2, 8 * byteLength2);
      return val;
    };
    Buffer2.prototype.readInt8 = function readInt8(offset2, noAssert) {
      if (!noAssert) checkOffset(offset2, 1, this.length);
      if (!(this[offset2] & 128)) return this[offset2];
      return (255 - this[offset2] + 1) * -1;
    };
    Buffer2.prototype.readInt16LE = function readInt16LE(offset2, noAssert) {
      if (!noAssert) checkOffset(offset2, 2, this.length);
      var val = this[offset2] | this[offset2 + 1] << 8;
      return val & 32768 ? val | 4294901760 : val;
    };
    Buffer2.prototype.readInt16BE = function readInt16BE(offset2, noAssert) {
      if (!noAssert) checkOffset(offset2, 2, this.length);
      var val = this[offset2 + 1] | this[offset2] << 8;
      return val & 32768 ? val | 4294901760 : val;
    };
    Buffer2.prototype.readInt32LE = function readInt32LE(offset2, noAssert) {
      if (!noAssert) checkOffset(offset2, 4, this.length);
      return this[offset2] | this[offset2 + 1] << 8 | this[offset2 + 2] << 16 | this[offset2 + 3] << 24;
    };
    Buffer2.prototype.readInt32BE = function readInt32BE(offset2, noAssert) {
      if (!noAssert) checkOffset(offset2, 4, this.length);
      return this[offset2] << 24 | this[offset2 + 1] << 16 | this[offset2 + 2] << 8 | this[offset2 + 3];
    };
    Buffer2.prototype.readFloatLE = function readFloatLE(offset2, noAssert) {
      if (!noAssert) checkOffset(offset2, 4, this.length);
      return read(this, offset2, true, 23, 4);
    };
    Buffer2.prototype.readFloatBE = function readFloatBE(offset2, noAssert) {
      if (!noAssert) checkOffset(offset2, 4, this.length);
      return read(this, offset2, false, 23, 4);
    };
    Buffer2.prototype.readDoubleLE = function readDoubleLE(offset2, noAssert) {
      if (!noAssert) checkOffset(offset2, 8, this.length);
      return read(this, offset2, true, 52, 8);
    };
    Buffer2.prototype.readDoubleBE = function readDoubleBE(offset2, noAssert) {
      if (!noAssert) checkOffset(offset2, 8, this.length);
      return read(this, offset2, false, 52, 8);
    };
    Buffer2.prototype.writeUIntLE = function writeUIntLE(value, offset2, byteLength2, noAssert) {
      value = +value;
      offset2 = offset2 | 0;
      byteLength2 = byteLength2 | 0;
      if (!noAssert) {
        var maxBytes = Math.pow(2, 8 * byteLength2) - 1;
        checkInt(this, value, offset2, byteLength2, maxBytes, 0);
      }
      var mul = 1;
      var i = 0;
      this[offset2] = value & 255;
      while (++i < byteLength2 && (mul *= 256)) {
        this[offset2 + i] = value / mul & 255;
      }
      return offset2 + byteLength2;
    };
    Buffer2.prototype.writeUIntBE = function writeUIntBE(value, offset2, byteLength2, noAssert) {
      value = +value;
      offset2 = offset2 | 0;
      byteLength2 = byteLength2 | 0;
      if (!noAssert) {
        var maxBytes = Math.pow(2, 8 * byteLength2) - 1;
        checkInt(this, value, offset2, byteLength2, maxBytes, 0);
      }
      var i = byteLength2 - 1;
      var mul = 1;
      this[offset2 + i] = value & 255;
      while (--i >= 0 && (mul *= 256)) {
        this[offset2 + i] = value / mul & 255;
      }
      return offset2 + byteLength2;
    };
    Buffer2.prototype.writeUInt8 = function writeUInt8(value, offset2, noAssert) {
      value = +value;
      offset2 = offset2 | 0;
      if (!noAssert) checkInt(this, value, offset2, 1, 255, 0);
      if (!Buffer2.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
      this[offset2] = value & 255;
      return offset2 + 1;
    };
    Buffer2.prototype.writeUInt16LE = function writeUInt16LE(value, offset2, noAssert) {
      value = +value;
      offset2 = offset2 | 0;
      if (!noAssert) checkInt(this, value, offset2, 2, 65535, 0);
      if (Buffer2.TYPED_ARRAY_SUPPORT) {
        this[offset2] = value & 255;
        this[offset2 + 1] = value >>> 8;
      } else {
        objectWriteUInt16(this, value, offset2, true);
      }
      return offset2 + 2;
    };
    Buffer2.prototype.writeUInt16BE = function writeUInt16BE(value, offset2, noAssert) {
      value = +value;
      offset2 = offset2 | 0;
      if (!noAssert) checkInt(this, value, offset2, 2, 65535, 0);
      if (Buffer2.TYPED_ARRAY_SUPPORT) {
        this[offset2] = value >>> 8;
        this[offset2 + 1] = value & 255;
      } else {
        objectWriteUInt16(this, value, offset2, false);
      }
      return offset2 + 2;
    };
    Buffer2.prototype.writeUInt32LE = function writeUInt32LE(value, offset2, noAssert) {
      value = +value;
      offset2 = offset2 | 0;
      if (!noAssert) checkInt(this, value, offset2, 4, 4294967295, 0);
      if (Buffer2.TYPED_ARRAY_SUPPORT) {
        this[offset2 + 3] = value >>> 24;
        this[offset2 + 2] = value >>> 16;
        this[offset2 + 1] = value >>> 8;
        this[offset2] = value & 255;
      } else {
        objectWriteUInt32(this, value, offset2, true);
      }
      return offset2 + 4;
    };
    Buffer2.prototype.writeUInt32BE = function writeUInt32BE(value, offset2, noAssert) {
      value = +value;
      offset2 = offset2 | 0;
      if (!noAssert) checkInt(this, value, offset2, 4, 4294967295, 0);
      if (Buffer2.TYPED_ARRAY_SUPPORT) {
        this[offset2] = value >>> 24;
        this[offset2 + 1] = value >>> 16;
        this[offset2 + 2] = value >>> 8;
        this[offset2 + 3] = value & 255;
      } else {
        objectWriteUInt32(this, value, offset2, false);
      }
      return offset2 + 4;
    };
    Buffer2.prototype.writeIntLE = function writeIntLE(value, offset2, byteLength2, noAssert) {
      value = +value;
      offset2 = offset2 | 0;
      if (!noAssert) {
        var limit = Math.pow(2, 8 * byteLength2 - 1);
        checkInt(this, value, offset2, byteLength2, limit - 1, -limit);
      }
      var i = 0;
      var mul = 1;
      var sub = 0;
      this[offset2] = value & 255;
      while (++i < byteLength2 && (mul *= 256)) {
        if (value < 0 && sub === 0 && this[offset2 + i - 1] !== 0) {
          sub = 1;
        }
        this[offset2 + i] = (value / mul >> 0) - sub & 255;
      }
      return offset2 + byteLength2;
    };
    Buffer2.prototype.writeIntBE = function writeIntBE(value, offset2, byteLength2, noAssert) {
      value = +value;
      offset2 = offset2 | 0;
      if (!noAssert) {
        var limit = Math.pow(2, 8 * byteLength2 - 1);
        checkInt(this, value, offset2, byteLength2, limit - 1, -limit);
      }
      var i = byteLength2 - 1;
      var mul = 1;
      var sub = 0;
      this[offset2 + i] = value & 255;
      while (--i >= 0 && (mul *= 256)) {
        if (value < 0 && sub === 0 && this[offset2 + i + 1] !== 0) {
          sub = 1;
        }
        this[offset2 + i] = (value / mul >> 0) - sub & 255;
      }
      return offset2 + byteLength2;
    };
    Buffer2.prototype.writeInt8 = function writeInt8(value, offset2, noAssert) {
      value = +value;
      offset2 = offset2 | 0;
      if (!noAssert) checkInt(this, value, offset2, 1, 127, -128);
      if (!Buffer2.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
      if (value < 0) value = 255 + value + 1;
      this[offset2] = value & 255;
      return offset2 + 1;
    };
    Buffer2.prototype.writeInt16LE = function writeInt16LE(value, offset2, noAssert) {
      value = +value;
      offset2 = offset2 | 0;
      if (!noAssert) checkInt(this, value, offset2, 2, 32767, -32768);
      if (Buffer2.TYPED_ARRAY_SUPPORT) {
        this[offset2] = value & 255;
        this[offset2 + 1] = value >>> 8;
      } else {
        objectWriteUInt16(this, value, offset2, true);
      }
      return offset2 + 2;
    };
    Buffer2.prototype.writeInt16BE = function writeInt16BE(value, offset2, noAssert) {
      value = +value;
      offset2 = offset2 | 0;
      if (!noAssert) checkInt(this, value, offset2, 2, 32767, -32768);
      if (Buffer2.TYPED_ARRAY_SUPPORT) {
        this[offset2] = value >>> 8;
        this[offset2 + 1] = value & 255;
      } else {
        objectWriteUInt16(this, value, offset2, false);
      }
      return offset2 + 2;
    };
    Buffer2.prototype.writeInt32LE = function writeInt32LE(value, offset2, noAssert) {
      value = +value;
      offset2 = offset2 | 0;
      if (!noAssert) checkInt(this, value, offset2, 4, 2147483647, -2147483648);
      if (Buffer2.TYPED_ARRAY_SUPPORT) {
        this[offset2] = value & 255;
        this[offset2 + 1] = value >>> 8;
        this[offset2 + 2] = value >>> 16;
        this[offset2 + 3] = value >>> 24;
      } else {
        objectWriteUInt32(this, value, offset2, true);
      }
      return offset2 + 4;
    };
    Buffer2.prototype.writeInt32BE = function writeInt32BE(value, offset2, noAssert) {
      value = +value;
      offset2 = offset2 | 0;
      if (!noAssert) checkInt(this, value, offset2, 4, 2147483647, -2147483648);
      if (value < 0) value = 4294967295 + value + 1;
      if (Buffer2.TYPED_ARRAY_SUPPORT) {
        this[offset2] = value >>> 24;
        this[offset2 + 1] = value >>> 16;
        this[offset2 + 2] = value >>> 8;
        this[offset2 + 3] = value & 255;
      } else {
        objectWriteUInt32(this, value, offset2, false);
      }
      return offset2 + 4;
    };
    Buffer2.prototype.writeFloatLE = function writeFloatLE(value, offset2, noAssert) {
      return writeFloat(this, value, offset2, true, noAssert);
    };
    Buffer2.prototype.writeFloatBE = function writeFloatBE(value, offset2, noAssert) {
      return writeFloat(this, value, offset2, false, noAssert);
    };
    Buffer2.prototype.writeDoubleLE = function writeDoubleLE(value, offset2, noAssert) {
      return writeDouble(this, value, offset2, true, noAssert);
    };
    Buffer2.prototype.writeDoubleBE = function writeDoubleBE(value, offset2, noAssert) {
      return writeDouble(this, value, offset2, false, noAssert);
    };
    Buffer2.prototype.copy = function copy(target, targetStart, start, end) {
      if (!start) start = 0;
      if (!end && end !== 0) end = this.length;
      if (targetStart >= target.length) targetStart = target.length;
      if (!targetStart) targetStart = 0;
      if (end > 0 && end < start) end = start;
      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("sourceStart out of bounds");
      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;
      }
      var len = end - start;
      var i;
      if (this === target && start < targetStart && targetStart < end) {
        for (i = len - 1; i >= 0; --i) {
          target[i + targetStart] = this[i + start];
        }
      } else if (len < 1e3 || !Buffer2.TYPED_ARRAY_SUPPORT) {
        for (i = 0; i < len; ++i) {
          target[i + targetStart] = this[i + start];
        }
      } else {
        Uint8Array.prototype.set.call(
          target,
          this.subarray(start, start + len),
          targetStart
        );
      }
      return len;
    };
    Buffer2.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 (val.length === 1) {
          var code = val.charCodeAt(0);
          if (code < 256) {
            val = code;
          }
        }
        if (encoding !== void 0 && typeof encoding !== "string") {
          throw new TypeError("encoding must be a string");
        }
        if (typeof encoding === "string" && !Buffer2.isEncoding(encoding)) {
          throw new TypeError("Unknown encoding: " + encoding);
        }
      } else if (typeof val === "number") {
        val = val & 255;
      }
      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;
      var i;
      if (typeof val === "number") {
        for (i = start; i < end; ++i) {
          this[i] = val;
        }
      } else {
        var bytes = internalIsBuffer(val) ? val : utf8ToBytes(new Buffer2(val, encoding).toString());
        var len = bytes.length;
        for (i = 0; i < end - start; ++i) {
          this[i + start] = bytes[i % len];
        }
      }
      return this;
    };
    INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g;
  }
});

// esbuild-buffer-shim.js
var init_esbuild_buffer_shim = __esm({
  "esbuild-buffer-shim.js"() {
    "use strict";
    init_buffer_es6();
    globalThis.Buffer = Buffer2;
  }
});

// node_modules/escape-string-regexp/index.js
var require_escape_string_regexp = __commonJS({
  "node_modules/escape-string-regexp/index.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    module2.exports = (string) => {
      if (typeof string !== "string") {
        throw new TypeError("Expected a string");
      }
      return string.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&").replace(/-/g, "\\x2d");
    };
  }
});

// node_modules/lodash.deburr/index.js
var require_lodash = __commonJS({
  "node_modules/lodash.deburr/index.js"(exports, module2) {
    init_esbuild_buffer_shim();
    var INFINITY = 1 / 0;
    var symbolTag = "[object Symbol]";
    var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;
    var rsComboMarksRange = "\\u0300-\\u036f\\ufe20-\\ufe23";
    var rsComboSymbolsRange = "\\u20d0-\\u20f0";
    var rsCombo = "[" + rsComboMarksRange + rsComboSymbolsRange + "]";
    var reComboMark = RegExp(rsCombo, "g");
    var deburredLetters = {
      // Latin-1 Supplement block.
      "\xC0": "A",
      "\xC1": "A",
      "\xC2": "A",
      "\xC3": "A",
      "\xC4": "A",
      "\xC5": "A",
      "\xE0": "a",
      "\xE1": "a",
      "\xE2": "a",
      "\xE3": "a",
      "\xE4": "a",
      "\xE5": "a",
      "\xC7": "C",
      "\xE7": "c",
      "\xD0": "D",
      "\xF0": "d",
      "\xC8": "E",
      "\xC9": "E",
      "\xCA": "E",
      "\xCB": "E",
      "\xE8": "e",
      "\xE9": "e",
      "\xEA": "e",
      "\xEB": "e",
      "\xCC": "I",
      "\xCD": "I",
      "\xCE": "I",
      "\xCF": "I",
      "\xEC": "i",
      "\xED": "i",
      "\xEE": "i",
      "\xEF": "i",
      "\xD1": "N",
      "\xF1": "n",
      "\xD2": "O",
      "\xD3": "O",
      "\xD4": "O",
      "\xD5": "O",
      "\xD6": "O",
      "\xD8": "O",
      "\xF2": "o",
      "\xF3": "o",
      "\xF4": "o",
      "\xF5": "o",
      "\xF6": "o",
      "\xF8": "o",
      "\xD9": "U",
      "\xDA": "U",
      "\xDB": "U",
      "\xDC": "U",
      "\xF9": "u",
      "\xFA": "u",
      "\xFB": "u",
      "\xFC": "u",
      "\xDD": "Y",
      "\xFD": "y",
      "\xFF": "y",
      "\xC6": "Ae",
      "\xE6": "ae",
      "\xDE": "Th",
      "\xFE": "th",
      "\xDF": "ss",
      // Latin Extended-A block.
      "\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": "ss"
    };
    var freeGlobal = typeof globalThis == "object" && globalThis && globalThis.Object === Object && globalThis;
    var freeSelf = typeof self == "object" && self && self.Object === Object && self;
    var root = freeGlobal || freeSelf || Function("return this")();
    function basePropertyOf(object) {
      return function(key) {
        return object == null ? void 0 : object[key];
      };
    }
    var deburrLetter = basePropertyOf(deburredLetters);
    var objectProto = Object.prototype;
    var objectToString = objectProto.toString;
    var Symbol2 = root.Symbol;
    var symbolProto = Symbol2 ? Symbol2.prototype : void 0;
    var symbolToString = symbolProto ? symbolProto.toString : void 0;
    function baseToString(value) {
      if (typeof value == "string") {
        return value;
      }
      if (isSymbol(value)) {
        return symbolToString ? symbolToString.call(value) : "";
      }
      var result = value + "";
      return result == "0" && 1 / value == -INFINITY ? "-0" : result;
    }
    function isObjectLike(value) {
      return !!value && typeof value == "object";
    }
    function isSymbol(value) {
      return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag;
    }
    function toString3(value) {
      return value == null ? "" : baseToString(value);
    }
    function deburr(string) {
      string = toString3(string);
      return string && string.replace(reLatin, deburrLetter).replace(reComboMark, "");
    }
    module2.exports = deburr;
  }
});

// node_modules/@sindresorhus/transliterate/node_modules/escape-string-regexp/index.js
var require_escape_string_regexp2 = __commonJS({
  "node_modules/@sindresorhus/transliterate/node_modules/escape-string-regexp/index.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    var matchOperatorsRegex = /[|\\{}()[\]^$+*?.-]/g;
    module2.exports = (string) => {
      if (typeof string !== "string") {
        throw new TypeError("Expected a string");
      }
      return string.replace(matchOperatorsRegex, "\\$&");
    };
  }
});

// node_modules/@sindresorhus/transliterate/replacements.js
var require_replacements = __commonJS({
  "node_modules/@sindresorhus/transliterate/replacements.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    module2.exports = [
      // German umlauts
      ["\xDF", "ss"],
      ["\xE4", "ae"],
      ["\xC4", "Ae"],
      ["\xF6", "oe"],
      ["\xD6", "Oe"],
      ["\xFC", "ue"],
      ["\xDC", "Ue"],
      // Latin
      ["\xC0", "A"],
      ["\xC1", "A"],
      ["\xC2", "A"],
      ["\xC3", "A"],
      ["\xC4", "Ae"],
      ["\xC5", "A"],
      ["\xC6", "AE"],
      ["\xC7", "C"],
      ["\xC8", "E"],
      ["\xC9", "E"],
      ["\xCA", "E"],
      ["\xCB", "E"],
      ["\xCC", "I"],
      ["\xCD", "I"],
      ["\xCE", "I"],
      ["\xCF", "I"],
      ["\xD0", "D"],
      ["\xD1", "N"],
      ["\xD2", "O"],
      ["\xD3", "O"],
      ["\xD4", "O"],
      ["\xD5", "O"],
      ["\xD6", "Oe"],
      ["\u0150", "O"],
      ["\xD8", "O"],
      ["\xD9", "U"],
      ["\xDA", "U"],
      ["\xDB", "U"],
      ["\xDC", "Ue"],
      ["\u0170", "U"],
      ["\xDD", "Y"],
      ["\xDE", "TH"],
      ["\xDF", "ss"],
      ["\xE0", "a"],
      ["\xE1", "a"],
      ["\xE2", "a"],
      ["\xE3", "a"],
      ["\xE4", "ae"],
      ["\xE5", "a"],
      ["\xE6", "ae"],
      ["\xE7", "c"],
      ["\xE8", "e"],
      ["\xE9", "e"],
      ["\xEA", "e"],
      ["\xEB", "e"],
      ["\xEC", "i"],
      ["\xED", "i"],
      ["\xEE", "i"],
      ["\xEF", "i"],
      ["\xF0", "d"],
      ["\xF1", "n"],
      ["\xF2", "o"],
      ["\xF3", "o"],
      ["\xF4", "o"],
      ["\xF5", "o"],
      ["\xF6", "oe"],
      ["\u0151", "o"],
      ["\xF8", "o"],
      ["\xF9", "u"],
      ["\xFA", "u"],
      ["\xFB", "u"],
      ["\xFC", "ue"],
      ["\u0171", "u"],
      ["\xFD", "y"],
      ["\xFE", "th"],
      ["\xFF", "y"],
      ["\u1E9E", "SS"],
      // Vietnamese
      ["\xE0", "a"],
      ["\xC0", "A"],
      ["\xE1", "a"],
      ["\xC1", "A"],
      ["\xE2", "a"],
      ["\xC2", "A"],
      ["\xE3", "a"],
      ["\xC3", "A"],
      ["\xE8", "e"],
      ["\xC8", "E"],
      ["\xE9", "e"],
      ["\xC9", "E"],
      ["\xEA", "e"],
      ["\xCA", "E"],
      ["\xEC", "i"],
      ["\xCC", "I"],
      ["\xED", "i"],
      ["\xCD", "I"],
      ["\xF2", "o"],
      ["\xD2", "O"],
      ["\xF3", "o"],
      ["\xD3", "O"],
      ["\xF4", "o"],
      ["\xD4", "O"],
      ["\xF5", "o"],
      ["\xD5", "O"],
      ["\xF9", "u"],
      ["\xD9", "U"],
      ["\xFA", "u"],
      ["\xDA", "U"],
      ["\xFD", "y"],
      ["\xDD", "Y"],
      ["\u0103", "a"],
      ["\u0102", "A"],
      ["\u0110", "D"],
      ["\u0111", "d"],
      ["\u0129", "i"],
      ["\u0128", "I"],
      ["\u0169", "u"],
      ["\u0168", "U"],
      ["\u01A1", "o"],
      ["\u01A0", "O"],
      ["\u01B0", "u"],
      ["\u01AF", "U"],
      ["\u1EA1", "a"],
      ["\u1EA0", "A"],
      ["\u1EA3", "a"],
      ["\u1EA2", "A"],
      ["\u1EA5", "a"],
      ["\u1EA4", "A"],
      ["\u1EA7", "a"],
      ["\u1EA6", "A"],
      ["\u1EA9", "a"],
      ["\u1EA8", "A"],
      ["\u1EAB", "a"],
      ["\u1EAA", "A"],
      ["\u1EAD", "a"],
      ["\u1EAC", "A"],
      ["\u1EAF", "a"],
      ["\u1EAE", "A"],
      ["\u1EB1", "a"],
      ["\u1EB0", "A"],
      ["\u1EB3", "a"],
      ["\u1EB2", "A"],
      ["\u1EB5", "a"],
      ["\u1EB4", "A"],
      ["\u1EB7", "a"],
      ["\u1EB6", "A"],
      ["\u1EB9", "e"],
      ["\u1EB8", "E"],
      ["\u1EBB", "e"],
      ["\u1EBA", "E"],
      ["\u1EBD", "e"],
      ["\u1EBC", "E"],
      ["\u1EBF", "e"],
      ["\u1EBE", "E"],
      ["\u1EC1", "e"],
      ["\u1EC0", "E"],
      ["\u1EC3", "e"],
      ["\u1EC2", "E"],
      ["\u1EC5", "e"],
      ["\u1EC4", "E"],
      ["\u1EC7", "e"],
      ["\u1EC6", "E"],
      ["\u1EC9", "i"],
      ["\u1EC8", "I"],
      ["\u1ECB", "i"],
      ["\u1ECA", "I"],
      ["\u1ECD", "o"],
      ["\u1ECC", "O"],
      ["\u1ECF", "o"],
      ["\u1ECE", "O"],
      ["\u1ED1", "o"],
      ["\u1ED0", "O"],
      ["\u1ED3", "o"],
      ["\u1ED2", "O"],
      ["\u1ED5", "o"],
      ["\u1ED4", "O"],
      ["\u1ED7", "o"],
      ["\u1ED6", "O"],
      ["\u1ED9", "o"],
      ["\u1ED8", "O"],
      ["\u1EDB", "o"],
      ["\u1EDA", "O"],
      ["\u1EDD", "o"],
      ["\u1EDC", "O"],
      ["\u1EDF", "o"],
      ["\u1EDE", "O"],
      ["\u1EE1", "o"],
      ["\u1EE0", "O"],
      ["\u1EE3", "o"],
      ["\u1EE2", "O"],
      ["\u1EE5", "u"],
      ["\u1EE4", "U"],
      ["\u1EE7", "u"],
      ["\u1EE6", "U"],
      ["\u1EE9", "u"],
      ["\u1EE8", "U"],
      ["\u1EEB", "u"],
      ["\u1EEA", "U"],
      ["\u1EED", "u"],
      ["\u1EEC", "U"],
      ["\u1EEF", "u"],
      ["\u1EEE", "U"],
      ["\u1EF1", "u"],
      ["\u1EF0", "U"],
      ["\u1EF3", "y"],
      ["\u1EF2", "Y"],
      ["\u1EF5", "y"],
      ["\u1EF4", "Y"],
      ["\u1EF7", "y"],
      ["\u1EF6", "Y"],
      ["\u1EF9", "y"],
      ["\u1EF8", "Y"],
      // Arabic
      ["\u0621", "e"],
      ["\u0622", "a"],
      ["\u0623", "a"],
      ["\u0624", "w"],
      ["\u0625", "i"],
      ["\u0626", "y"],
      ["\u0627", "a"],
      ["\u0628", "b"],
      ["\u0629", "t"],
      ["\u062A", "t"],
      ["\u062B", "th"],
      ["\u062C", "j"],
      ["\u062D", "h"],
      ["\u062E", "kh"],
      ["\u062F", "d"],
      ["\u0630", "dh"],
      ["\u0631", "r"],
      ["\u0632", "z"],
      ["\u0633", "s"],
      ["\u0634", "sh"],
      ["\u0635", "s"],
      ["\u0636", "d"],
      ["\u0637", "t"],
      ["\u0638", "z"],
      ["\u0639", "e"],
      ["\u063A", "gh"],
      ["\u0640", "_"],
      ["\u0641", "f"],
      ["\u0642", "q"],
      ["\u0643", "k"],
      ["\u0644", "l"],
      ["\u0645", "m"],
      ["\u0646", "n"],
      ["\u0647", "h"],
      ["\u0648", "w"],
      ["\u0649", "a"],
      ["\u064A", "y"],
      ["\u064E\u200E", "a"],
      ["\u064F", "u"],
      ["\u0650\u200E", "i"],
      ["\u0660", "0"],
      ["\u0661", "1"],
      ["\u0662", "2"],
      ["\u0663", "3"],
      ["\u0664", "4"],
      ["\u0665", "5"],
      ["\u0666", "6"],
      ["\u0667", "7"],
      ["\u0668", "8"],
      ["\u0669", "9"],
      // Persian / Farsi
      ["\u0686", "ch"],
      ["\u06A9", "k"],
      ["\u06AF", "g"],
      ["\u067E", "p"],
      ["\u0698", "zh"],
      ["\u06CC", "y"],
      ["\u06F0", "0"],
      ["\u06F1", "1"],
      ["\u06F2", "2"],
      ["\u06F3", "3"],
      ["\u06F4", "4"],
      ["\u06F5", "5"],
      ["\u06F6", "6"],
      ["\u06F7", "7"],
      ["\u06F8", "8"],
      ["\u06F9", "9"],
      // Pashto
      ["\u067C", "p"],
      ["\u0681", "z"],
      ["\u0685", "c"],
      ["\u0689", "d"],
      ["\uFEAB", "d"],
      ["\uFEAD", "r"],
      ["\u0693", "r"],
      ["\uFEAF", "z"],
      ["\u0696", "g"],
      ["\u069A", "x"],
      ["\u06AB", "g"],
      ["\u06BC", "n"],
      ["\u06C0", "e"],
      ["\u06D0", "e"],
      ["\u06CD", "ai"],
      // Urdu
      ["\u0679", "t"],
      ["\u0688", "d"],
      ["\u0691", "r"],
      ["\u06BA", "n"],
      ["\u06C1", "h"],
      ["\u06BE", "h"],
      ["\u06D2", "e"],
      // Russian
      ["\u0410", "A"],
      ["\u0430", "a"],
      ["\u0411", "B"],
      ["\u0431", "b"],
      ["\u0412", "V"],
      ["\u0432", "v"],
      ["\u0413", "G"],
      ["\u0433", "g"],
      ["\u0414", "D"],
      ["\u0434", "d"],
      ["\u0415", "E"],
      ["\u0435", "e"],
      ["\u0416", "Zh"],
      ["\u0436", "zh"],
      ["\u0417", "Z"],
      ["\u0437", "z"],
      ["\u0418", "I"],
      ["\u0438", "i"],
      ["\u0419", "J"],
      ["\u0439", "j"],
      ["\u041A", "K"],
      ["\u043A", "k"],
      ["\u041B", "L"],
      ["\u043B", "l"],
      ["\u041C", "M"],
      ["\u043C", "m"],
      ["\u041D", "N"],
      ["\u043D", "n"],
      ["\u041E", "O"],
      ["\u043E", "o"],
      ["\u041F", "P"],
      ["\u043F", "p"],
      ["\u0420", "R"],
      ["\u0440", "r"],
      ["\u0421", "S"],
      ["\u0441", "s"],
      ["\u0422", "T"],
      ["\u0442", "t"],
      ["\u0423", "U"],
      ["\u0443", "u"],
      ["\u0424", "F"],
      ["\u0444", "f"],
      ["\u0425", "H"],
      ["\u0445", "h"],
      ["\u0426", "Cz"],
      ["\u0446", "cz"],
      ["\u0427", "Ch"],
      ["\u0447", "ch"],
      ["\u0428", "Sh"],
      ["\u0448", "sh"],
      ["\u0429", "Shh"],
      ["\u0449", "shh"],
      ["\u042A", ""],
      ["\u044A", ""],
      ["\u042B", "Y"],
      ["\u044B", "y"],
      ["\u042C", ""],
      ["\u044C", ""],
      ["\u042D", "E"],
      ["\u044D", "e"],
      ["\u042E", "Yu"],
      ["\u044E", "yu"],
      ["\u042F", "Ya"],
      ["\u044F", "ya"],
      ["\u0401", "Yo"],
      ["\u0451", "yo"],
      // Romanian
      ["\u0103", "a"],
      ["\u0102", "A"],
      ["\u0219", "s"],
      ["\u0218", "S"],
      ["\u021B", "t"],
      ["\u021A", "T"],
      ["\u0163", "t"],
      ["\u0162", "T"],
      // Turkish
      ["\u015F", "s"],
      ["\u015E", "S"],
      ["\xE7", "c"],
      ["\xC7", "C"],
      ["\u011F", "g"],
      ["\u011E", "G"],
      ["\u0131", "i"],
      ["\u0130", "I"],
      // Armenian
      ["\u0561", "a"],
      ["\u0531", "A"],
      ["\u0562", "b"],
      ["\u0532", "B"],
      ["\u0563", "g"],
      ["\u0533", "G"],
      ["\u0564", "d"],
      ["\u0534", "D"],
      ["\u0565", "ye"],
      ["\u0535", "Ye"],
      ["\u0566", "z"],
      ["\u0536", "Z"],
      ["\u0567", "e"],
      ["\u0537", "E"],
      ["\u0568", "y"],
      ["\u0538", "Y"],
      ["\u0569", "t"],
      ["\u0539", "T"],
      ["\u056A", "zh"],
      ["\u053A", "Zh"],
      ["\u056B", "i"],
      ["\u053B", "I"],
      ["\u056C", "l"],
      ["\u053C", "L"],
      ["\u056D", "kh"],
      ["\u053D", "Kh"],
      ["\u056E", "ts"],
      ["\u053E", "Ts"],
      ["\u056F", "k"],
      ["\u053F", "K"],
      ["\u0570", "h"],
      ["\u0540", "H"],
      ["\u0571", "dz"],
      ["\u0541", "Dz"],
      ["\u0572", "gh"],
      ["\u0542", "Gh"],
      ["\u0573", "tch"],
      ["\u0543", "Tch"],
      ["\u0574", "m"],
      ["\u0544", "M"],
      ["\u0575", "y"],
      ["\u0545", "Y"],
      ["\u0576", "n"],
      ["\u0546", "N"],
      ["\u0577", "sh"],
      ["\u0547", "Sh"],
      ["\u0578", "vo"],
      ["\u0548", "Vo"],
      ["\u0579", "ch"],
      ["\u0549", "Ch"],
      ["\u057A", "p"],
      ["\u054A", "P"],
      ["\u057B", "j"],
      ["\u054B", "J"],
      ["\u057C", "r"],
      ["\u054C", "R"],
      ["\u057D", "s"],
      ["\u054D", "S"],
      ["\u057E", "v"],
      ["\u054E", "V"],
      ["\u057F", "t"],
      ["\u054F", "T"],
      ["\u0580", "r"],
      ["\u0550", "R"],
      ["\u0581", "c"],
      ["\u0551", "C"],
      ["\u0578\u0582", "u"],
      ["\u0548\u0552", "U"],
      ["\u0548\u0582", "U"],
      ["\u0583", "p"],
      ["\u0553", "P"],
      ["\u0584", "q"],
      ["\u0554", "Q"],
      ["\u0585", "o"],
      ["\u0555", "O"],
      ["\u0586", "f"],
      ["\u0556", "F"],
      ["\u0587", "yev"],
      // Georgian
      ["\u10D0", "a"],
      ["\u10D1", "b"],
      ["\u10D2", "g"],
      ["\u10D3", "d"],
      ["\u10D4", "e"],
      ["\u10D5", "v"],
      ["\u10D6", "z"],
      ["\u10D7", "t"],
      ["\u10D8", "i"],
      ["\u10D9", "k"],
      ["\u10DA", "l"],
      ["\u10DB", "m"],
      ["\u10DC", "n"],
      ["\u10DD", "o"],
      ["\u10DE", "p"],
      ["\u10DF", "zh"],
      ["\u10E0", "r"],
      ["\u10E1", "s"],
      ["\u10E2", "t"],
      ["\u10E3", "u"],
      ["\u10E4", "ph"],
      ["\u10E5", "q"],
      ["\u10E6", "gh"],
      ["\u10E7", "k"],
      ["\u10E8", "sh"],
      ["\u10E9", "ch"],
      ["\u10EA", "ts"],
      ["\u10EB", "dz"],
      ["\u10EC", "ts"],
      ["\u10ED", "tch"],
      ["\u10EE", "kh"],
      ["\u10EF", "j"],
      ["\u10F0", "h"],
      // Czech
      ["\u010D", "c"],
      ["\u010F", "d"],
      ["\u011B", "e"],
      ["\u0148", "n"],
      ["\u0159", "r"],
      ["\u0161", "s"],
      ["\u0165", "t"],
      ["\u016F", "u"],
      ["\u017E", "z"],
      ["\u010C", "C"],
      ["\u010E", "D"],
      ["\u011A", "E"],
      ["\u0147", "N"],
      ["\u0158", "R"],
      ["\u0160", "S"],
      ["\u0164", "T"],
      ["\u016E", "U"],
      ["\u017D", "Z"],
      // Dhivehi
      ["\u0780", "h"],
      ["\u0781", "sh"],
      ["\u0782", "n"],
      ["\u0783", "r"],
      ["\u0784", "b"],
      ["\u0785", "lh"],
      ["\u0786", "k"],
      ["\u0787", "a"],
      ["\u0788", "v"],
      ["\u0789", "m"],
      ["\u078A", "f"],
      ["\u078B", "dh"],
      ["\u078C", "th"],
      ["\u078D", "l"],
      ["\u078E", "g"],
      ["\u078F", "gn"],
      ["\u0790", "s"],
      ["\u0791", "d"],
      ["\u0792", "z"],
      ["\u0793", "t"],
      ["\u0794", "y"],
      ["\u0795", "p"],
      ["\u0796", "j"],
      ["\u0797", "ch"],
      ["\u0798", "tt"],
      ["\u0799", "hh"],
      ["\u079A", "kh"],
      ["\u079B", "th"],
      ["\u079C", "z"],
      ["\u079D", "sh"],
      ["\u079E", "s"],
      ["\u079F", "d"],
      ["\u07A0", "t"],
      ["\u07A1", "z"],
      ["\u07A2", "a"],
      ["\u07A3", "gh"],
      ["\u07A4", "q"],
      ["\u07A5", "w"],
      ["\u07A6", "a"],
      ["\u07A7", "aa"],
      ["\u07A8", "i"],
      ["\u07A9", "ee"],
      ["\u07AA", "u"],
      ["\u07AB", "oo"],
      ["\u07AC", "e"],
      ["\u07AD", "ey"],
      ["\u07AE", "o"],
      ["\u07AF", "oa"],
      ["\u07B0", ""],
      // Greek
      ["\u03B1", "a"],
      ["\u03B2", "v"],
      ["\u03B3", "g"],
      ["\u03B4", "d"],
      ["\u03B5", "e"],
      ["\u03B6", "z"],
      ["\u03B7", "i"],
      ["\u03B8", "th"],
      ["\u03B9", "i"],
      ["\u03BA", "k"],
      ["\u03BB", "l"],
      ["\u03BC", "m"],
      ["\u03BD", "n"],
      ["\u03BE", "ks"],
      ["\u03BF", "o"],
      ["\u03C0", "p"],
      ["\u03C1", "r"],
      ["\u03C3", "s"],
      ["\u03C4", "t"],
      ["\u03C5", "y"],
      ["\u03C6", "f"],
      ["\u03C7", "x"],
      ["\u03C8", "ps"],
      ["\u03C9", "o"],
      ["\u03AC", "a"],
      ["\u03AD", "e"],
      ["\u03AF", "i"],
      ["\u03CC", "o"],
      ["\u03CD", "y"],
      ["\u03AE", "i"],
      ["\u03CE", "o"],
      ["\u03C2", "s"],
      ["\u03CA", "i"],
      ["\u03B0", "y"],
      ["\u03CB", "y"],
      ["\u0390", "i"],
      ["\u0391", "A"],
      ["\u0392", "B"],
      ["\u0393", "G"],
      ["\u0394", "D"],
      ["\u0395", "E"],
      ["\u0396", "Z"],
      ["\u0397", "I"],
      ["\u0398", "TH"],
      ["\u0399", "I"],
      ["\u039A", "K"],
      ["\u039B", "L"],
      ["\u039C", "M"],
      ["\u039D", "N"],
      ["\u039E", "KS"],
      ["\u039F", "O"],
      ["\u03A0", "P"],
      ["\u03A1", "R"],
      ["\u03A3", "S"],
      ["\u03A4", "T"],
      ["\u03A5", "Y"],
      ["\u03A6", "F"],
      ["\u03A7", "X"],
      ["\u03A8", "PS"],
      ["\u03A9", "O"],
      ["\u0386", "A"],
      ["\u0388", "E"],
      ["\u038A", "I"],
      ["\u038C", "O"],
      ["\u038E", "Y"],
      ["\u0389", "I"],
      ["\u038F", "O"],
      ["\u03AA", "I"],
      ["\u03AB", "Y"],
      // Disabled as it conflicts with German and Latin.
      // Hungarian
      // ['ä', 'a'],
      // ['Ä', 'A'],
      // ['ö', 'o'],
      // ['Ö', 'O'],
      // ['ü', 'u'],
      // ['Ü', 'U'],
      // ['ű', 'u'],
      // ['Ű', 'U'],
      // Latvian
      ["\u0101", "a"],
      ["\u0113", "e"],
      ["\u0123", "g"],
      ["\u012B", "i"],
      ["\u0137", "k"],
      ["\u013C", "l"],
      ["\u0146", "n"],
      ["\u016B", "u"],
      ["\u0100", "A"],
      ["\u0112", "E"],
      ["\u0122", "G"],
      ["\u012A", "I"],
      ["\u0136", "K"],
      ["\u013B", "L"],
      ["\u0145", "N"],
      ["\u016A", "U"],
      ["\u010D", "c"],
      ["\u0161", "s"],
      ["\u017E", "z"],
      ["\u010C", "C"],
      ["\u0160", "S"],
      ["\u017D", "Z"],
      // Lithuanian
      ["\u0105", "a"],
      ["\u010D", "c"],
      ["\u0119", "e"],
      ["\u0117", "e"],
      ["\u012F", "i"],
      ["\u0161", "s"],
      ["\u0173", "u"],
      ["\u016B", "u"],
      ["\u017E", "z"],
      ["\u0104", "A"],
      ["\u010C", "C"],
      ["\u0118", "E"],
      ["\u0116", "E"],
      ["\u012E", "I"],
      ["\u0160", "S"],
      ["\u0172", "U"],
      ["\u016A", "U"],
      // Macedonian
      ["\u040C", "Kj"],
      ["\u045C", "kj"],
      ["\u0409", "Lj"],
      ["\u0459", "lj"],
      ["\u040A", "Nj"],
      ["\u045A", "nj"],
      ["\u0422\u0441", "Ts"],
      ["\u0442\u0441", "ts"],
      // Polish
      ["\u0105", "a"],
      ["\u0107", "c"],
      ["\u0119", "e"],
      ["\u0142", "l"],
      ["\u0144", "n"],
      ["\u015B", "s"],
      ["\u017A", "z"],
      ["\u017C", "z"],
      ["\u0104", "A"],
      ["\u0106", "C"],
      ["\u0118", "E"],
      ["\u0141", "L"],
      ["\u0143", "N"],
      ["\u015A", "S"],
      ["\u0179", "Z"],
      ["\u017B", "Z"],
      // Disabled as it conflicts with Vietnamese.
      // Serbian
      // ['љ', 'lj'],
      // ['њ', 'nj'],
      // ['Љ', 'Lj'],
      // ['Њ', 'Nj'],
      // ['đ', 'dj'],
      // ['Đ', 'Dj'],
      // ['ђ', 'dj'],
      // ['ј', 'j'],
      // ['ћ', 'c'],
      // ['џ', 'dz'],
      // ['Ђ', 'Dj'],
      // ['Ј', 'j'],
      // ['Ћ', 'C'],
      // ['Џ', 'Dz'],
      // Disabled as it conflicts with German and Latin.
      // Slovak
      // ['ä', 'a'],
      // ['Ä', 'A'],
      // ['ľ', 'l'],
      // ['ĺ', 'l'],
      // ['ŕ', 'r'],
      // ['Ľ', 'L'],
      // ['Ĺ', 'L'],
      // ['Ŕ', 'R'],
      // Disabled as it conflicts with German and Latin.
      // Swedish
      // ['å', 'o'],
      // ['Å', 'o'],
      // ['ä', 'a'],
      // ['Ä', 'A'],
      // ['ë', 'e'],
      // ['Ë', 'E'],
      // ['ö', 'o'],
      // ['Ö', 'O'],
      // Ukrainian
      ["\u0404", "Ye"],
      ["\u0406", "I"],
      ["\u0407", "Yi"],
      ["\u0490", "G"],
      ["\u0454", "ye"],
      ["\u0456", "i"],
      ["\u0457", "yi"],
      ["\u0491", "g"]
      // Danish
      // ['Æ', 'Ae'],
      // ['Ø', 'Oe'],
      // ['Å', 'Aa'],
      // ['æ', 'ae'],
      // ['ø', 'oe'],
      // ['å', 'aa']
    ];
  }
});

// node_modules/@sindresorhus/transliterate/index.js
var require_transliterate = __commonJS({
  "node_modules/@sindresorhus/transliterate/index.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    var deburr = require_lodash();
    var escapeStringRegexp = require_escape_string_regexp2();
    var builtinReplacements = require_replacements();
    var doCustomReplacements = (string, replacements) => {
      for (const [key, value] of replacements) {
        string = string.replace(new RegExp(escapeStringRegexp(key), "g"), value);
      }
      return string;
    };
    module2.exports = (string, options) => {
      if (typeof string !== "string") {
        throw new TypeError(`Expected a string, got \`${typeof string}\``);
      }
      options = {
        customReplacements: [],
        ...options
      };
      const customReplacements = new Map([
        ...builtinReplacements,
        ...options.customReplacements
      ]);
      string = string.normalize();
      string = doCustomReplacements(string, customReplacements);
      string = deburr(string);
      return string;
    };
  }
});

// node_modules/@sindresorhus/slugify/overridable-replacements.js
var require_overridable_replacements = __commonJS({
  "node_modules/@sindresorhus/slugify/overridable-replacements.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    module2.exports = [
      ["&", " and "],
      ["\u{1F984}", " unicorn "],
      ["\u2665", " love "]
    ];
  }
});

// node_modules/@sindresorhus/slugify/index.js
var require_slugify = __commonJS({
  "node_modules/@sindresorhus/slugify/index.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    var escapeStringRegexp = require_escape_string_regexp();
    var transliterate = require_transliterate();
    var builtinOverridableReplacements = require_overridable_replacements();
    var decamelize = (string) => {
      return string.replace(/([A-Z]{2,})(\d+)/g, "$1 $2").replace(/([a-z\d]+)([A-Z]{2,})/g, "$1 $2").replace(/([a-z\d])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z\d]+)/g, "$1 $2");
    };
    var removeMootSeparators = (string, separator) => {
      const escapedSeparator = escapeStringRegexp(separator);
      return string.replace(new RegExp(`${escapedSeparator}{2,}`, "g"), separator).replace(new RegExp(`^${escapedSeparator}|${escapedSeparator}$`, "g"), "");
    };
    var slugify3 = (string, options) => {
      if (typeof string !== "string") {
        throw new TypeError(`Expected a string, got \`${typeof string}\``);
      }
      options = {
        separator: "-",
        lowercase: true,
        decamelize: true,
        customReplacements: [],
        preserveLeadingUnderscore: false,
        ...options
      };
      const shouldPrependUnderscore = options.preserveLeadingUnderscore && string.startsWith("_");
      const customReplacements = new Map([
        ...builtinOverridableReplacements,
        ...options.customReplacements
      ]);
      string = transliterate(string, { customReplacements });
      if (options.decamelize) {
        string = decamelize(string);
      }
      let patternSlug = /[^a-zA-Z\d]+/g;
      if (options.lowercase) {
        string = string.toLowerCase();
        patternSlug = /[^a-z\d]+/g;
      }
      string = string.replace(patternSlug, options.separator);
      string = string.replace(/\\/g, "");
      if (options.separator) {
        string = removeMootSeparators(string, options.separator);
      }
      if (shouldPrependUnderscore) {
        string = `_${string}`;
      }
      return string;
    };
    var counter = () => {
      const occurrences = /* @__PURE__ */ new Map();
      const countable = (string, options) => {
        string = slugify3(string, options);
        if (!string) {
          return "";
        }
        const stringLower = string.toLowerCase();
        const numberless = occurrences.get(stringLower.replace(/(?:-\d+?)+?$/, "")) || 0;
        const counter2 = occurrences.get(stringLower);
        occurrences.set(stringLower, typeof counter2 === "number" ? counter2 + 1 : 1);
        const newCounter = occurrences.get(stringLower) || 2;
        if (newCounter >= 2 || numberless > 2) {
          string = `${string}-${newCounter}`;
        }
        return string;
      };
      countable.reset = () => {
        occurrences.clear();
      };
      return countable;
    };
    module2.exports = slugify3;
    module2.exports.counter = counter;
  }
});

// node_modules/crypto-js/core.js
var require_core = __commonJS({
  "node_modules/crypto-js/core.js"(exports, module2) {
    init_esbuild_buffer_shim();
    (function(root, factory) {
      if (typeof exports === "object") {
        module2.exports = exports = factory();
      } else if (typeof define === "function" && define.amd) {
        define([], factory);
      } else {
        root.CryptoJS = factory();
      }
    })(exports, function() {
      var CryptoJS = CryptoJS || function(Math2, undefined2) {
        var crypto2;
        if (typeof window !== "undefined" && window.crypto) {
          crypto2 = window.crypto;
        }
        if (typeof self !== "undefined" && self.crypto) {
          crypto2 = self.crypto;
        }
        if (typeof globalThis !== "undefined" && globalThis.crypto) {
          crypto2 = globalThis.crypto;
        }
        if (!crypto2 && typeof window !== "undefined" && window.msCrypto) {
          crypto2 = window.msCrypto;
        }
        if (!crypto2 && typeof globalThis !== "undefined" && globalThis.crypto) {
          crypto2 = globalThis.crypto;
        }
        if (!crypto2 && typeof require === "function") {
          try {
            crypto2 = require("crypto");
          } catch (err) {
          }
        }
        var cryptoSecureRandomInt = function() {
          if (crypto2) {
            if (typeof crypto2.getRandomValues === "function") {
              try {
                return crypto2.getRandomValues(new Uint32Array(1))[0];
              } catch (err) {
              }
            }
            if (typeof crypto2.randomBytes === "function") {
              try {
                return crypto2.randomBytes(4).readInt32LE();
              } catch (err) {
              }
            }
          }
          throw new Error("Native crypto module could not be used to get secure random number.");
        };
        var create = Object.create || /* @__PURE__ */ function() {
          function F() {
          }
          return function(obj) {
            var subtype;
            F.prototype = obj;
            subtype = new F();
            F.prototype = null;
            return subtype;
          };
        }();
        var C = {};
        var C_lib = C.lib = {};
        var Base = C_lib.Base = /* @__PURE__ */ function() {
          return {
            /**
             * Creates a new object that inherits from this object.
             *
             * @param {Object} overrides Properties to copy into the new object.
             *
             * @return {Object} The new object.
             *
             * @static
             *
             * @example
             *
             *     var MyType = CryptoJS.lib.Base.extend({
             *         field: 'value',
             *
             *         method: function () {
             *         }
             *     });
             */
            extend: function(overrides) {
              var subtype = create(this);
              if (overrides) {
                subtype.mixIn(overrides);
              }
              if (!subtype.hasOwnProperty("init") || this.init === subtype.init) {
                subtype.init = function() {
                  subtype.$super.init.apply(this, arguments);
                };
              }
              subtype.init.prototype = subtype;
              subtype.$super = this;
              return subtype;
            },
            /**
             * Extends this object and runs the init method.
             * Arguments to create() will be passed to init().
             *
             * @return {Object} The new object.
             *
             * @static
             *
             * @example
             *
             *     var instance = MyType.create();
             */
            create: function() {
              var instance6 = this.extend();
              instance6.init.apply(instance6, arguments);
              return instance6;
            },
            /**
             * Initializes a newly created object.
             * Override this method to add some logic when your objects are created.
             *
             * @example
             *
             *     var MyType = CryptoJS.lib.Base.extend({
             *         init: function () {
             *             // ...
             *         }
             *     });
             */
            init: function() {
            },
            /**
             * Copies properties into this object.
             *
             * @param {Object} properties The properties to mix in.
             *
             * @example
             *
             *     MyType.mixIn({
             *         field: 'value'
             *     });
             */
            mixIn: function(properties) {
              for (var propertyName in properties) {
                if (properties.hasOwnProperty(propertyName)) {
                  this[propertyName] = properties[propertyName];
                }
              }
              if (properties.hasOwnProperty("toString")) {
                this.toString = properties.toString;
              }
            },
            /**
             * Creates a copy of this object.
             *
             * @return {Object} The clone.
             *
             * @example
             *
             *     var clone = instance.clone();
             */
            clone: function() {
              return this.init.prototype.extend(this);
            }
          };
        }();
        var WordArray = C_lib.WordArray = Base.extend({
          /**
           * Initializes a newly created word array.
           *
           * @param {Array} words (Optional) An array of 32-bit words.
           * @param {number} sigBytes (Optional) The number of significant bytes in the words.
           *
           * @example
           *
           *     var wordArray = CryptoJS.lib.WordArray.create();
           *     var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);
           *     var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
           */
          init: function(words, sigBytes) {
            words = this.words = words || [];
            if (sigBytes != undefined2) {
              this.sigBytes = sigBytes;
            } else {
              this.sigBytes = words.length * 4;
            }
          },
          /**
           * Converts this word array to a string.
           *
           * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
           *
           * @return {string} The stringified word array.
           *
           * @example
           *
           *     var string = wordArray + '';
           *     var string = wordArray.toString();
           *     var string = wordArray.toString(CryptoJS.enc.Utf8);
           */
          toString: function(encoder) {
            return (encoder || Hex).stringify(this);
          },
          /**
           * Concatenates a word array to this word array.
           *
           * @param {WordArray} wordArray The word array to append.
           *
           * @return {WordArray} This word array.
           *
           * @example
           *
           *     wordArray1.concat(wordArray2);
           */
          concat: function(wordArray) {
            var thisWords = this.words;
            var thatWords = wordArray.words;
            var thisSigBytes = this.sigBytes;
            var thatSigBytes = wordArray.sigBytes;
            this.clamp();
            if (thisSigBytes % 4) {
              for (var i = 0; i < thatSigBytes; i++) {
                var thatByte = thatWords[i >>> 2] >>> 24 - i % 4 * 8 & 255;
                thisWords[thisSigBytes + i >>> 2] |= thatByte << 24 - (thisSigBytes + i) % 4 * 8;
              }
            } else {
              for (var j = 0; j < thatSigBytes; j += 4) {
                thisWords[thisSigBytes + j >>> 2] = thatWords[j >>> 2];
              }
            }
            this.sigBytes += thatSigBytes;
            return this;
          },
          /**
           * Removes insignificant bits.
           *
           * @example
           *
           *     wordArray.clamp();
           */
          clamp: function() {
            var words = this.words;
            var sigBytes = this.sigBytes;
            words[sigBytes >>> 2] &= 4294967295 << 32 - sigBytes % 4 * 8;
            words.length = Math2.ceil(sigBytes / 4);
          },
          /**
           * Creates a copy of this word array.
           *
           * @return {WordArray} The clone.
           *
           * @example
           *
           *     var clone = wordArray.clone();
           */
          clone: function() {
            var clone3 = Base.clone.call(this);
            clone3.words = this.words.slice(0);
            return clone3;
          },
          /**
           * Creates a word array filled with random bytes.
           *
           * @param {number} nBytes The number of random bytes to generate.
           *
           * @return {WordArray} The random word array.
           *
           * @static
           *
           * @example
           *
           *     var wordArray = CryptoJS.lib.WordArray.random(16);
           */
          random: function(nBytes) {
            var words = [];
            for (var i = 0; i < nBytes; i += 4) {
              words.push(cryptoSecureRandomInt());
            }
            return new WordArray.init(words, nBytes);
          }
        });
        var C_enc = C.enc = {};
        var Hex = C_enc.Hex = {
          /**
           * Converts a word array to a hex string.
           *
           * @param {WordArray} wordArray The word array.
           *
           * @return {string} The hex string.
           *
           * @static
           *
           * @example
           *
           *     var hexString = CryptoJS.enc.Hex.stringify(wordArray);
           */
          stringify: function(wordArray) {
            var words = wordArray.words;
            var sigBytes = wordArray.sigBytes;
            var hexChars = [];
            for (var i = 0; i < sigBytes; i++) {
              var bite = words[i >>> 2] >>> 24 - i % 4 * 8 & 255;
              hexChars.push((bite >>> 4).toString(16));
              hexChars.push((bite & 15).toString(16));
            }
            return hexChars.join("");
          },
          /**
           * Converts a hex string to a word array.
           *
           * @param {string} hexStr The hex string.
           *
           * @return {WordArray} The word array.
           *
           * @static
           *
           * @example
           *
           *     var wordArray = CryptoJS.enc.Hex.parse(hexString);
           */
          parse: function(hexStr) {
            var hexStrLength = hexStr.length;
            var words = [];
            for (var i = 0; i < hexStrLength; i += 2) {
              words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << 24 - i % 8 * 4;
            }
            return new WordArray.init(words, hexStrLength / 2);
          }
        };
        var Latin1 = C_enc.Latin1 = {
          /**
           * Converts a word array to a Latin1 string.
           *
           * @param {WordArray} wordArray The word array.
           *
           * @return {string} The Latin1 string.
           *
           * @static
           *
           * @example
           *
           *     var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
           */
          stringify: function(wordArray) {
            var words = wordArray.words;
            var sigBytes = wordArray.sigBytes;
            var latin1Chars = [];
            for (var i = 0; i < sigBytes; i++) {
              var bite = words[i >>> 2] >>> 24 - i % 4 * 8 & 255;
              latin1Chars.push(String.fromCharCode(bite));
            }
            return latin1Chars.join("");
          },
          /**
           * Converts a Latin1 string to a word array.
           *
           * @param {string} latin1Str The Latin1 string.
           *
           * @return {WordArray} The word array.
           *
           * @static
           *
           * @example
           *
           *     var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
           */
          parse: function(latin1Str) {
            var latin1StrLength = latin1Str.length;
            var words = [];
            for (var i = 0; i < latin1StrLength; i++) {
              words[i >>> 2] |= (latin1Str.charCodeAt(i) & 255) << 24 - i % 4 * 8;
            }
            return new WordArray.init(words, latin1StrLength);
          }
        };
        var Utf8 = C_enc.Utf8 = {
          /**
           * Converts a word array to a UTF-8 string.
           *
           * @param {WordArray} wordArray The word array.
           *
           * @return {string} The UTF-8 string.
           *
           * @static
           *
           * @example
           *
           *     var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
           */
          stringify: function(wordArray) {
            try {
              return decodeURIComponent(escape(Latin1.stringify(wordArray)));
            } catch (e) {
              throw new Error("Malformed UTF-8 data");
            }
          },
          /**
           * Converts a UTF-8 string to a word array.
           *
           * @param {string} utf8Str The UTF-8 string.
           *
           * @return {WordArray} The word array.
           *
           * @static
           *
           * @example
           *
           *     var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
           */
          parse: function(utf8Str) {
            return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
          }
        };
        var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({
          /**
           * Resets this block algorithm's data buffer to its initial state.
           *
           * @example
           *
           *     bufferedBlockAlgorithm.reset();
           */
          reset: function() {
            this._data = new WordArray.init();
            this._nDataBytes = 0;
          },
          /**
           * Adds new data to this block algorithm's buffer.
           *
           * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8.
           *
           * @example
           *
           *     bufferedBlockAlgorithm._append('data');
           *     bufferedBlockAlgorithm._append(wordArray);
           */
          _append: function(data) {
            if (typeof data == "string") {
              data = Utf8.parse(data);
            }
            this._data.concat(data);
            this._nDataBytes += data.sigBytes;
          },
          /**
           * Processes available data blocks.
           *
           * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.
           *
           * @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
           *
           * @return {WordArray} The processed data.
           *
           * @example
           *
           *     var processedData = bufferedBlockAlgorithm._process();
           *     var processedData = bufferedBlockAlgorithm._process(!!'flush');
           */
          _process: function(doFlush) {
            var processedWords;
            var data = this._data;
            var dataWords = data.words;
            var dataSigBytes = data.sigBytes;
            var blockSize = this.blockSize;
            var blockSizeBytes = blockSize * 4;
            var nBlocksReady = dataSigBytes / blockSizeBytes;
            if (doFlush) {
              nBlocksReady = Math2.ceil(nBlocksReady);
            } else {
              nBlocksReady = Math2.max((nBlocksReady | 0) - this._minBufferSize, 0);
            }
            var nWordsReady = nBlocksReady * blockSize;
            var nBytesReady = Math2.min(nWordsReady * 4, dataSigBytes);
            if (nWordsReady) {
              for (var offset2 = 0; offset2 < nWordsReady; offset2 += blockSize) {
                this._doProcessBlock(dataWords, offset2);
              }
              processedWords = dataWords.splice(0, nWordsReady);
              data.sigBytes -= nBytesReady;
            }
            return new WordArray.init(processedWords, nBytesReady);
          },
          /**
           * Creates a copy of this object.
           *
           * @return {Object} The clone.
           *
           * @example
           *
           *     var clone = bufferedBlockAlgorithm.clone();
           */
          clone: function() {
            var clone3 = Base.clone.call(this);
            clone3._data = this._data.clone();
            return clone3;
          },
          _minBufferSize: 0
        });
        var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({
          /**
           * Configuration options.
           */
          cfg: Base.extend(),
          /**
           * Initializes a newly created hasher.
           *
           * @param {Object} cfg (Optional) The configuration options to use for this hash computation.
           *
           * @example
           *
           *     var hasher = CryptoJS.algo.SHA256.create();
           */
          init: function(cfg) {
            this.cfg = this.cfg.extend(cfg);
            this.reset();
          },
          /**
           * Resets this hasher to its initial state.
           *
           * @example
           *
           *     hasher.reset();
           */
          reset: function() {
            BufferedBlockAlgorithm.reset.call(this);
            this._doReset();
          },
          /**
           * Updates this hasher with a message.
           *
           * @param {WordArray|string} messageUpdate The message to append.
           *
           * @return {Hasher} This hasher.
           *
           * @example
           *
           *     hasher.update('message');
           *     hasher.update(wordArray);
           */
          update: function(messageUpdate) {
            this._append(messageUpdate);
            this._process();
            return this;
          },
          /**
           * Finalizes the hash computation.
           * Note that the finalize operation is effectively a destructive, read-once operation.
           *
           * @param {WordArray|string} messageUpdate (Optional) A final message update.
           *
           * @return {WordArray} The hash.
           *
           * @example
           *
           *     var hash = hasher.finalize();
           *     var hash = hasher.finalize('message');
           *     var hash = hasher.finalize(wordArray);
           */
          finalize: function(messageUpdate) {
            if (messageUpdate) {
              this._append(messageUpdate);
            }
            var hash = this._doFinalize();
            return hash;
          },
          blockSize: 512 / 32,
          /**
           * Creates a shortcut function to a hasher's object interface.
           *
           * @param {Hasher} hasher The hasher to create a helper for.
           *
           * @return {Function} The shortcut function.
           *
           * @static
           *
           * @example
           *
           *     var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
           */
          _createHelper: function(hasher) {
            return function(message, cfg) {
              return new hasher.init(cfg).finalize(message);
            };
          },
          /**
           * Creates a shortcut function to the HMAC's object interface.
           *
           * @param {Hasher} hasher The hasher to use in this HMAC helper.
           *
           * @return {Function} The shortcut function.
           *
           * @static
           *
           * @example
           *
           *     var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
           */
          _createHmacHelper: function(hasher) {
            return function(message, key) {
              return new C_algo.HMAC.init(hasher, key).finalize(message);
            };
          }
        });
        var C_algo = C.algo = {};
        return C;
      }(Math);
      return CryptoJS;
    });
  }
});

// node_modules/crypto-js/sha1.js
var require_sha1 = __commonJS({
  "node_modules/crypto-js/sha1.js"(exports, module2) {
    init_esbuild_buffer_shim();
    (function(root, factory) {
      if (typeof exports === "object") {
        module2.exports = exports = factory(require_core());
      } else if (typeof define === "function" && define.amd) {
        define(["./core"], factory);
      } else {
        factory(root.CryptoJS);
      }
    })(exports, function(CryptoJS) {
      (function() {
        var C = CryptoJS;
        var C_lib = C.lib;
        var WordArray = C_lib.WordArray;
        var Hasher = C_lib.Hasher;
        var C_algo = C.algo;
        var W = [];
        var SHA1 = C_algo.SHA1 = Hasher.extend({
          _doReset: function() {
            this._hash = new WordArray.init([
              1732584193,
              4023233417,
              2562383102,
              271733878,
              3285377520
            ]);
          },
          _doProcessBlock: function(M, offset2) {
            var H = this._hash.words;
            var a = H[0];
            var b = H[1];
            var c = H[2];
            var d = H[3];
            var e = H[4];
            for (var i = 0; i < 80; i++) {
              if (i < 16) {
                W[i] = M[offset2 + i] | 0;
              } else {
                var n2 = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];
                W[i] = n2 << 1 | n2 >>> 31;
              }
              var t = (a << 5 | a >>> 27) + e + W[i];
              if (i < 20) {
                t += (b & c | ~b & d) + 1518500249;
              } else if (i < 40) {
                t += (b ^ c ^ d) + 1859775393;
              } else if (i < 60) {
                t += (b & c | b & d | c & d) - 1894007588;
              } else {
                t += (b ^ c ^ d) - 899497514;
              }
              e = d;
              d = c;
              c = b << 30 | b >>> 2;
              b = a;
              a = t;
            }
            H[0] = H[0] + a | 0;
            H[1] = H[1] + b | 0;
            H[2] = H[2] + c | 0;
            H[3] = H[3] + d | 0;
            H[4] = H[4] + e | 0;
          },
          _doFinalize: function() {
            var data = this._data;
            var dataWords = data.words;
            var nBitsTotal = this._nDataBytes * 8;
            var nBitsLeft = data.sigBytes * 8;
            dataWords[nBitsLeft >>> 5] |= 128 << 24 - nBitsLeft % 32;
            dataWords[(nBitsLeft + 64 >>> 9 << 4) + 14] = Math.floor(nBitsTotal / 4294967296);
            dataWords[(nBitsLeft + 64 >>> 9 << 4) + 15] = nBitsTotal;
            data.sigBytes = dataWords.length * 4;
            this._process();
            return this._hash;
          },
          clone: function() {
            var clone3 = Hasher.clone.call(this);
            clone3._hash = this._hash.clone();
            return clone3;
          }
        });
        C.SHA1 = Hasher._createHelper(SHA1);
        C.HmacSHA1 = Hasher._createHmacHelper(SHA1);
      })();
      return CryptoJS.SHA1;
    });
  }
});

// node_modules/js-logger/src/logger.js
var require_logger = __commonJS({
  "node_modules/js-logger/src/logger.js"(exports, module2) {
    init_esbuild_buffer_shim();
    (function(global2) {
      "use strict";
      var Logger12 = {};
      Logger12.VERSION = "1.6.1";
      var logHandler;
      var contextualLoggersByNameMap = {};
      var bind = function(scope, func) {
        return function() {
          return func.apply(scope, arguments);
        };
      };
      var merge = function() {
        var args = arguments, target = args[0], key, i;
        for (i = 1; i < args.length; i++) {
          for (key in args[i]) {
            if (!(key in target) && args[i].hasOwnProperty(key)) {
              target[key] = args[i][key];
            }
          }
        }
        return target;
      };
      var defineLogLevel = function(value, name) {
        return { value, name };
      };
      Logger12.TRACE = defineLogLevel(1, "TRACE");
      Logger12.DEBUG = defineLogLevel(2, "DEBUG");
      Logger12.INFO = defineLogLevel(3, "INFO");
      Logger12.TIME = defineLogLevel(4, "TIME");
      Logger12.WARN = defineLogLevel(5, "WARN");
      Logger12.ERROR = defineLogLevel(8, "ERROR");
      Logger12.OFF = defineLogLevel(99, "OFF");
      var ContextualLogger = function(defaultContext) {
        this.context = defaultContext;
        this.setLevel(defaultContext.filterLevel);
        this.log = this.info;
      };
      ContextualLogger.prototype = {
        // Changes the current logging level for the logging instance.
        setLevel: function(newLevel) {
          if (newLevel && "value" in newLevel) {
            this.context.filterLevel = newLevel;
          }
        },
        // Gets the current logging level for the logging instance
        getLevel: function() {
          return this.context.filterLevel;
        },
        // Is the logger configured to output messages at the supplied level?
        enabledFor: function(lvl) {
          var filterLevel = this.context.filterLevel;
          return lvl.value >= filterLevel.value;
        },
        trace: function() {
          this.invoke(Logger12.TRACE, arguments);
        },
        debug: function() {
          this.invoke(Logger12.DEBUG, arguments);
        },
        info: function() {
          this.invoke(Logger12.INFO, arguments);
        },
        warn: function() {
          this.invoke(Logger12.WARN, arguments);
        },
        error: function() {
          this.invoke(Logger12.ERROR, arguments);
        },
        time: function(label) {
          if (typeof label === "string" && label.length > 0) {
            this.invoke(Logger12.TIME, [label, "start"]);
          }
        },
        timeEnd: function(label) {
          if (typeof label === "string" && label.length > 0) {
            this.invoke(Logger12.TIME, [label, "end"]);
          }
        },
        // Invokes the logger callback if it's not being filtered.
        invoke: function(level, msgArgs) {
          if (logHandler && this.enabledFor(level)) {
            logHandler(msgArgs, merge({ level }, this.context));
          }
        }
      };
      var globalLogger = new ContextualLogger({ filterLevel: Logger12.OFF });
      (function() {
        var L = Logger12;
        L.enabledFor = bind(globalLogger, globalLogger.enabledFor);
        L.trace = bind(globalLogger, globalLogger.trace);
        L.debug = bind(globalLogger, globalLogger.debug);
        L.time = bind(globalLogger, globalLogger.time);
        L.timeEnd = bind(globalLogger, globalLogger.timeEnd);
        L.info = bind(globalLogger, globalLogger.info);
        L.warn = bind(globalLogger, globalLogger.warn);
        L.error = bind(globalLogger, globalLogger.error);
        L.log = L.info;
      })();
      Logger12.setHandler = function(func) {
        logHandler = func;
      };
      Logger12.setLevel = function(level) {
        globalLogger.setLevel(level);
        for (var key in contextualLoggersByNameMap) {
          if (contextualLoggersByNameMap.hasOwnProperty(key)) {
            contextualLoggersByNameMap[key].setLevel(level);
          }
        }
      };
      Logger12.getLevel = function() {
        return globalLogger.getLevel();
      };
      Logger12.get = function(name) {
        return contextualLoggersByNameMap[name] || (contextualLoggersByNameMap[name] = new ContextualLogger(merge({ name }, globalLogger.context)));
      };
      Logger12.createDefaultHandler = function(options) {
        options = options || {};
        options.formatter = options.formatter || function defaultMessageFormatter(messages, context) {
          if (context.name) {
            messages.unshift("[" + context.name + "]");
          }
        };
        var timerStartTimeByLabelMap = {};
        var invokeConsoleMethod = function(hdlr, messages) {
          Function.prototype.apply.call(hdlr, console, messages);
        };
        if (typeof console === "undefined") {
          return function() {
          };
        }
        return function(messages, context) {
          messages = Array.prototype.slice.call(messages);
          var hdlr = console.log;
          var timerLabel;
          if (context.level === Logger12.TIME) {
            timerLabel = (context.name ? "[" + context.name + "] " : "") + messages[0];
            if (messages[1] === "start") {
              if (console.time) {
                console.time(timerLabel);
              } else {
                timerStartTimeByLabelMap[timerLabel] = (/* @__PURE__ */ new Date()).getTime();
              }
            } else {
              if (console.timeEnd) {
                console.timeEnd(timerLabel);
              } else {
                invokeConsoleMethod(hdlr, [timerLabel + ": " + ((/* @__PURE__ */ new Date()).getTime() - timerStartTimeByLabelMap[timerLabel]) + "ms"]);
              }
            }
          } else {
            if (context.level === Logger12.WARN && console.warn) {
              hdlr = console.warn;
            } else if (context.level === Logger12.ERROR && console.error) {
              hdlr = console.error;
            } else if (context.level === Logger12.INFO && console.info) {
              hdlr = console.info;
            } else if (context.level === Logger12.DEBUG && console.debug) {
              hdlr = console.debug;
            } else if (context.level === Logger12.TRACE && console.trace) {
              hdlr = console.trace;
            }
            options.formatter(messages, context);
            invokeConsoleMethod(hdlr, messages);
          }
        };
      };
      Logger12.useDefaults = function(options) {
        Logger12.setLevel(options && options.defaultLevel || Logger12.DEBUG);
        Logger12.setHandler(Logger12.createDefaultHandler(options));
      };
      Logger12.setDefaults = Logger12.useDefaults;
      if (typeof define === "function" && define.amd) {
        define(Logger12);
      } else if (typeof module2 !== "undefined" && module2.exports) {
        module2.exports = Logger12;
      } else {
        Logger12._prevLogger = global2.Logger;
        Logger12.noConflict = function() {
          global2.Logger = Logger12._prevLogger;
          return Logger12;
        };
        global2.Logger = Logger12;
      }
    })(exports);
  }
});

// node_modules/obsidian-dataview/lib/index.js
var require_lib = __commonJS({
  "node_modules/obsidian-dataview/lib/index.js"(exports) {
    "use strict";
    init_esbuild_buffer_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    require("obsidian");
    var LuxonError2 = class extends Error {
    };
    var InvalidDateTimeError2 = class extends LuxonError2 {
      constructor(reason) {
        super(`Invalid DateTime: ${reason.toMessage()}`);
      }
    };
    var InvalidIntervalError2 = class extends LuxonError2 {
      constructor(reason) {
        super(`Invalid Interval: ${reason.toMessage()}`);
      }
    };
    var InvalidDurationError2 = class extends LuxonError2 {
      constructor(reason) {
        super(`Invalid Duration: ${reason.toMessage()}`);
      }
    };
    var ConflictingSpecificationError2 = class extends LuxonError2 {
    };
    var InvalidUnitError2 = class extends LuxonError2 {
      constructor(unit) {
        super(`Invalid unit ${unit}`);
      }
    };
    var InvalidArgumentError2 = class extends LuxonError2 {
    };
    var ZoneIsAbstractError2 = class extends LuxonError2 {
      constructor() {
        super("Zone is an abstract class");
      }
    };
    var n2 = "numeric";
    var s2 = "short";
    var l2 = "long";
    var DATE_SHORT2 = {
      year: n2,
      month: n2,
      day: n2
    };
    var DATE_MED2 = {
      year: n2,
      month: s2,
      day: n2
    };
    var DATE_MED_WITH_WEEKDAY2 = {
      year: n2,
      month: s2,
      day: n2,
      weekday: s2
    };
    var DATE_FULL2 = {
      year: n2,
      month: l2,
      day: n2
    };
    var DATE_HUGE2 = {
      year: n2,
      month: l2,
      day: n2,
      weekday: l2
    };
    var TIME_SIMPLE2 = {
      hour: n2,
      minute: n2
    };
    var TIME_WITH_SECONDS2 = {
      hour: n2,
      minute: n2,
      second: n2
    };
    var TIME_WITH_SHORT_OFFSET2 = {
      hour: n2,
      minute: n2,
      second: n2,
      timeZoneName: s2
    };
    var TIME_WITH_LONG_OFFSET2 = {
      hour: n2,
      minute: n2,
      second: n2,
      timeZoneName: l2
    };
    var TIME_24_SIMPLE2 = {
      hour: n2,
      minute: n2,
      hourCycle: "h23"
    };
    var TIME_24_WITH_SECONDS2 = {
      hour: n2,
      minute: n2,
      second: n2,
      hourCycle: "h23"
    };
    var TIME_24_WITH_SHORT_OFFSET2 = {
      hour: n2,
      minute: n2,
      second: n2,
      hourCycle: "h23",
      timeZoneName: s2
    };
    var TIME_24_WITH_LONG_OFFSET2 = {
      hour: n2,
      minute: n2,
      second: n2,
      hourCycle: "h23",
      timeZoneName: l2
    };
    var DATETIME_SHORT2 = {
      year: n2,
      month: n2,
      day: n2,
      hour: n2,
      minute: n2
    };
    var DATETIME_SHORT_WITH_SECONDS2 = {
      year: n2,
      month: n2,
      day: n2,
      hour: n2,
      minute: n2,
      second: n2
    };
    var DATETIME_MED2 = {
      year: n2,
      month: s2,
      day: n2,
      hour: n2,
      minute: n2
    };
    var DATETIME_MED_WITH_SECONDS2 = {
      year: n2,
      month: s2,
      day: n2,
      hour: n2,
      minute: n2,
      second: n2
    };
    var DATETIME_MED_WITH_WEEKDAY2 = {
      year: n2,
      month: s2,
      day: n2,
      weekday: s2,
      hour: n2,
      minute: n2
    };
    var DATETIME_FULL2 = {
      year: n2,
      month: l2,
      day: n2,
      hour: n2,
      minute: n2,
      timeZoneName: s2
    };
    var DATETIME_FULL_WITH_SECONDS2 = {
      year: n2,
      month: l2,
      day: n2,
      hour: n2,
      minute: n2,
      second: n2,
      timeZoneName: s2
    };
    var DATETIME_HUGE2 = {
      year: n2,
      month: l2,
      day: n2,
      weekday: l2,
      hour: n2,
      minute: n2,
      timeZoneName: l2
    };
    var DATETIME_HUGE_WITH_SECONDS2 = {
      year: n2,
      month: l2,
      day: n2,
      weekday: l2,
      hour: n2,
      minute: n2,
      second: n2,
      timeZoneName: l2
    };
    var Zone2 = class {
      /**
       * The type of zone
       * @abstract
       * @type {string}
       */
      get type() {
        throw new ZoneIsAbstractError2();
      }
      /**
       * The name of this zone.
       * @abstract
       * @type {string}
       */
      get name() {
        throw new ZoneIsAbstractError2();
      }
      get ianaName() {
        return this.name;
      }
      /**
       * Returns whether the offset is known to be fixed for the whole year.
       * @abstract
       * @type {boolean}
       */
      get isUniversal() {
        throw new ZoneIsAbstractError2();
      }
      /**
       * Returns the offset's common name (such as EST) at the specified timestamp
       * @abstract
       * @param {number} ts - Epoch milliseconds for which to get the name
       * @param {Object} opts - Options to affect the format
       * @param {string} opts.format - What style of offset to return. Accepts 'long' or 'short'.
       * @param {string} opts.locale - What locale to return the offset name in.
       * @return {string}
       */
      offsetName(ts, opts) {
        throw new ZoneIsAbstractError2();
      }
      /**
       * Returns the offset's value as a string
       * @abstract
       * @param {number} ts - Epoch milliseconds for which to get the offset
       * @param {string} format - What style of offset to return.
       *                          Accepts 'narrow', 'short', or 'techie'. Returning '+6', '+06:00', or '+0600' respectively
       * @return {string}
       */
      formatOffset(ts, format) {
        throw new ZoneIsAbstractError2();
      }
      /**
       * Return the offset in minutes for this zone at the specified timestamp.
       * @abstract
       * @param {number} ts - Epoch milliseconds for which to compute the offset
       * @return {number}
       */
      offset(ts) {
        throw new ZoneIsAbstractError2();
      }
      /**
       * Return whether this Zone is equal to another zone
       * @abstract
       * @param {Zone} otherZone - the zone to compare
       * @return {boolean}
       */
      equals(otherZone) {
        throw new ZoneIsAbstractError2();
      }
      /**
       * Return whether this Zone is valid.
       * @abstract
       * @type {boolean}
       */
      get isValid() {
        throw new ZoneIsAbstractError2();
      }
    };
    var singleton$1 = null;
    var SystemZone2 = class _SystemZone extends Zone2 {
      /**
       * Get a singleton instance of the local zone
       * @return {SystemZone}
       */
      static get instance() {
        if (singleton$1 === null) {
          singleton$1 = new _SystemZone();
        }
        return singleton$1;
      }
      /** @override **/
      get type() {
        return "system";
      }
      /** @override **/
      get name() {
        return new Intl.DateTimeFormat().resolvedOptions().timeZone;
      }
      /** @override **/
      get isUniversal() {
        return false;
      }
      /** @override **/
      offsetName(ts, { format, locale }) {
        return parseZoneInfo2(ts, format, locale);
      }
      /** @override **/
      formatOffset(ts, format) {
        return formatOffset2(this.offset(ts), format);
      }
      /** @override **/
      offset(ts) {
        return -new Date(ts).getTimezoneOffset();
      }
      /** @override **/
      equals(otherZone) {
        return otherZone.type === "system";
      }
      /** @override **/
      get isValid() {
        return true;
      }
    };
    var dtfCache2 = {};
    function makeDTF2(zone) {
      if (!dtfCache2[zone]) {
        dtfCache2[zone] = new Intl.DateTimeFormat("en-US", {
          hour12: false,
          timeZone: zone,
          year: "numeric",
          month: "2-digit",
          day: "2-digit",
          hour: "2-digit",
          minute: "2-digit",
          second: "2-digit",
          era: "short"
        });
      }
      return dtfCache2[zone];
    }
    var typeToPos2 = {
      year: 0,
      month: 1,
      day: 2,
      era: 3,
      hour: 4,
      minute: 5,
      second: 6
    };
    function hackyOffset2(dtf, date) {
      const formatted = dtf.format(date).replace(/\u200E/g, ""), parsed = /(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(formatted), [, fMonth, fDay, fYear, fadOrBc, fHour, fMinute, fSecond] = parsed;
      return [fYear, fMonth, fDay, fadOrBc, fHour, fMinute, fSecond];
    }
    function partsOffset2(dtf, date) {
      const formatted = dtf.formatToParts(date);
      const filled = [];
      for (let i = 0; i < formatted.length; i++) {
        const { type, value } = formatted[i];
        const pos = typeToPos2[type];
        if (type === "era") {
          filled[pos] = value;
        } else if (!isUndefined2(pos)) {
          filled[pos] = parseInt(value, 10);
        }
      }
      return filled;
    }
    var ianaZoneCache2 = {};
    var IANAZone2 = class _IANAZone extends Zone2 {
      /**
       * @param {string} name - Zone name
       * @return {IANAZone}
       */
      static create(name) {
        if (!ianaZoneCache2[name]) {
          ianaZoneCache2[name] = new _IANAZone(name);
        }
        return ianaZoneCache2[name];
      }
      /**
       * Reset local caches. Should only be necessary in testing scenarios.
       * @return {void}
       */
      static resetCache() {
        ianaZoneCache2 = {};
        dtfCache2 = {};
      }
      /**
       * Returns whether the provided string is a valid specifier. This only checks the string's format, not that the specifier identifies a known zone; see isValidZone for that.
       * @param {string} s - The string to check validity on
       * @example IANAZone.isValidSpecifier("America/New_York") //=> true
       * @example IANAZone.isValidSpecifier("Sport~~blorp") //=> false
       * @deprecated This method returns false for some valid IANA names. Use isValidZone instead.
       * @return {boolean}
       */
      static isValidSpecifier(s3) {
        return this.isValidZone(s3);
      }
      /**
       * Returns whether the provided string identifies a real zone
       * @param {string} zone - The string to check
       * @example IANAZone.isValidZone("America/New_York") //=> true
       * @example IANAZone.isValidZone("Fantasia/Castle") //=> false
       * @example IANAZone.isValidZone("Sport~~blorp") //=> false
       * @return {boolean}
       */
      static isValidZone(zone) {
        if (!zone) {
          return false;
        }
        try {
          new Intl.DateTimeFormat("en-US", { timeZone: zone }).format();
          return true;
        } catch (e) {
          return false;
        }
      }
      constructor(name) {
        super();
        this.zoneName = name;
        this.valid = _IANAZone.isValidZone(name);
      }
      /** @override **/
      get type() {
        return "iana";
      }
      /** @override **/
      get name() {
        return this.zoneName;
      }
      /** @override **/
      get isUniversal() {
        return false;
      }
      /** @override **/
      offsetName(ts, { format, locale }) {
        return parseZoneInfo2(ts, format, locale, this.name);
      }
      /** @override **/
      formatOffset(ts, format) {
        return formatOffset2(this.offset(ts), format);
      }
      /** @override **/
      offset(ts) {
        const date = new Date(ts);
        if (isNaN(date)) return NaN;
        const dtf = makeDTF2(this.name);
        let [year, month, day, adOrBc, hour, minute, second] = dtf.formatToParts ? partsOffset2(dtf, date) : hackyOffset2(dtf, date);
        if (adOrBc === "BC") {
          year = -Math.abs(year) + 1;
        }
        const adjustedHour = hour === 24 ? 0 : hour;
        const asUTC = objToLocalTS2({
          year,
          month,
          day,
          hour: adjustedHour,
          minute,
          second,
          millisecond: 0
        });
        let asTS = +date;
        const over = asTS % 1e3;
        asTS -= over >= 0 ? over : 1e3 + over;
        return (asUTC - asTS) / (60 * 1e3);
      }
      /** @override **/
      equals(otherZone) {
        return otherZone.type === "iana" && otherZone.name === this.name;
      }
      /** @override **/
      get isValid() {
        return this.valid;
      }
    };
    var intlLFCache2 = {};
    function getCachedLF2(locString, opts = {}) {
      const key = JSON.stringify([locString, opts]);
      let dtf = intlLFCache2[key];
      if (!dtf) {
        dtf = new Intl.ListFormat(locString, opts);
        intlLFCache2[key] = dtf;
      }
      return dtf;
    }
    var intlDTCache2 = {};
    function getCachedDTF2(locString, opts = {}) {
      const key = JSON.stringify([locString, opts]);
      let dtf = intlDTCache2[key];
      if (!dtf) {
        dtf = new Intl.DateTimeFormat(locString, opts);
        intlDTCache2[key] = dtf;
      }
      return dtf;
    }
    var intlNumCache2 = {};
    function getCachedINF2(locString, opts = {}) {
      const key = JSON.stringify([locString, opts]);
      let inf = intlNumCache2[key];
      if (!inf) {
        inf = new Intl.NumberFormat(locString, opts);
        intlNumCache2[key] = inf;
      }
      return inf;
    }
    var intlRelCache2 = {};
    function getCachedRTF2(locString, opts = {}) {
      const { base, ...cacheKeyOpts } = opts;
      const key = JSON.stringify([locString, cacheKeyOpts]);
      let inf = intlRelCache2[key];
      if (!inf) {
        inf = new Intl.RelativeTimeFormat(locString, opts);
        intlRelCache2[key] = inf;
      }
      return inf;
    }
    var sysLocaleCache2 = null;
    function systemLocale2() {
      if (sysLocaleCache2) {
        return sysLocaleCache2;
      } else {
        sysLocaleCache2 = new Intl.DateTimeFormat().resolvedOptions().locale;
        return sysLocaleCache2;
      }
    }
    function parseLocaleString2(localeStr) {
      const xIndex = localeStr.indexOf("-x-");
      if (xIndex !== -1) {
        localeStr = localeStr.substring(0, xIndex);
      }
      const uIndex = localeStr.indexOf("-u-");
      if (uIndex === -1) {
        return [localeStr];
      } else {
        let options;
        let selectedStr;
        try {
          options = getCachedDTF2(localeStr).resolvedOptions();
          selectedStr = localeStr;
        } catch (e) {
          const smaller = localeStr.substring(0, uIndex);
          options = getCachedDTF2(smaller).resolvedOptions();
          selectedStr = smaller;
        }
        const { numberingSystem, calendar } = options;
        return [selectedStr, numberingSystem, calendar];
      }
    }
    function intlConfigString2(localeStr, numberingSystem, outputCalendar) {
      if (outputCalendar || numberingSystem) {
        if (!localeStr.includes("-u-")) {
          localeStr += "-u";
        }
        if (outputCalendar) {
          localeStr += `-ca-${outputCalendar}`;
        }
        if (numberingSystem) {
          localeStr += `-nu-${numberingSystem}`;
        }
        return localeStr;
      } else {
        return localeStr;
      }
    }
    function mapMonths2(f) {
      const ms = [];
      for (let i = 1; i <= 12; i++) {
        const dt = DateTime2.utc(2009, i, 1);
        ms.push(f(dt));
      }
      return ms;
    }
    function mapWeekdays2(f) {
      const ms = [];
      for (let i = 1; i <= 7; i++) {
        const dt = DateTime2.utc(2016, 11, 13 + i);
        ms.push(f(dt));
      }
      return ms;
    }
    function listStuff2(loc, length, englishFn, intlFn) {
      const mode = loc.listingMode();
      if (mode === "error") {
        return null;
      } else if (mode === "en") {
        return englishFn(length);
      } else {
        return intlFn(length);
      }
    }
    function supportsFastNumbers2(loc) {
      if (loc.numberingSystem && loc.numberingSystem !== "latn") {
        return false;
      } else {
        return loc.numberingSystem === "latn" || !loc.locale || loc.locale.startsWith("en") || new Intl.DateTimeFormat(loc.intl).resolvedOptions().numberingSystem === "latn";
      }
    }
    var PolyNumberFormatter2 = class {
      constructor(intl, forceSimple, opts) {
        this.padTo = opts.padTo || 0;
        this.floor = opts.floor || false;
        const { padTo, floor, ...otherOpts } = opts;
        if (!forceSimple || Object.keys(otherOpts).length > 0) {
          const intlOpts = { useGrouping: false, ...opts };
          if (opts.padTo > 0) intlOpts.minimumIntegerDigits = opts.padTo;
          this.inf = getCachedINF2(intl, intlOpts);
        }
      }
      format(i) {
        if (this.inf) {
          const fixed = this.floor ? Math.floor(i) : i;
          return this.inf.format(fixed);
        } else {
          const fixed = this.floor ? Math.floor(i) : roundTo2(i, 3);
          return padStart2(fixed, this.padTo);
        }
      }
    };
    var PolyDateFormatter2 = class {
      constructor(dt, intl, opts) {
        this.opts = opts;
        this.originalZone = void 0;
        let z = void 0;
        if (this.opts.timeZone) {
          this.dt = dt;
        } else if (dt.zone.type === "fixed") {
          const gmtOffset = -1 * (dt.offset / 60);
          const offsetZ = gmtOffset >= 0 ? `Etc/GMT+${gmtOffset}` : `Etc/GMT${gmtOffset}`;
          if (dt.offset !== 0 && IANAZone2.create(offsetZ).valid) {
            z = offsetZ;
            this.dt = dt;
          } else {
            z = "UTC";
            this.dt = dt.offset === 0 ? dt : dt.setZone("UTC").plus({ minutes: dt.offset });
            this.originalZone = dt.zone;
          }
        } else if (dt.zone.type === "system") {
          this.dt = dt;
        } else if (dt.zone.type === "iana") {
          this.dt = dt;
          z = dt.zone.name;
        } else {
          z = "UTC";
          this.dt = dt.setZone("UTC").plus({ minutes: dt.offset });
          this.originalZone = dt.zone;
        }
        const intlOpts = { ...this.opts };
        intlOpts.timeZone = intlOpts.timeZone || z;
        this.dtf = getCachedDTF2(intl, intlOpts);
      }
      format() {
        if (this.originalZone) {
          return this.formatToParts().map(({ value }) => value).join("");
        }
        return this.dtf.format(this.dt.toJSDate());
      }
      formatToParts() {
        const parts = this.dtf.formatToParts(this.dt.toJSDate());
        if (this.originalZone) {
          return parts.map((part) => {
            if (part.type === "timeZoneName") {
              const offsetName = this.originalZone.offsetName(this.dt.ts, {
                locale: this.dt.locale,
                format: this.opts.timeZoneName
              });
              return {
                ...part,
                value: offsetName
              };
            } else {
              return part;
            }
          });
        }
        return parts;
      }
      resolvedOptions() {
        return this.dtf.resolvedOptions();
      }
    };
    var PolyRelFormatter2 = class {
      constructor(intl, isEnglish, opts) {
        this.opts = { style: "long", ...opts };
        if (!isEnglish && hasRelative2()) {
          this.rtf = getCachedRTF2(intl, opts);
        }
      }
      format(count, unit) {
        if (this.rtf) {
          return this.rtf.format(count, unit);
        } else {
          return formatRelativeTime2(unit, count, this.opts.numeric, this.opts.style !== "long");
        }
      }
      formatToParts(count, unit) {
        if (this.rtf) {
          return this.rtf.formatToParts(count, unit);
        } else {
          return [];
        }
      }
    };
    var Locale2 = class _Locale {
      static fromOpts(opts) {
        return _Locale.create(opts.locale, opts.numberingSystem, opts.outputCalendar, opts.defaultToEN);
      }
      static create(locale, numberingSystem, outputCalendar, defaultToEN = false) {
        const specifiedLocale = locale || Settings2.defaultLocale;
        const localeR = specifiedLocale || (defaultToEN ? "en-US" : systemLocale2());
        const numberingSystemR = numberingSystem || Settings2.defaultNumberingSystem;
        const outputCalendarR = outputCalendar || Settings2.defaultOutputCalendar;
        return new _Locale(localeR, numberingSystemR, outputCalendarR, specifiedLocale);
      }
      static resetCache() {
        sysLocaleCache2 = null;
        intlDTCache2 = {};
        intlNumCache2 = {};
        intlRelCache2 = {};
      }
      static fromObject({ locale, numberingSystem, outputCalendar } = {}) {
        return _Locale.create(locale, numberingSystem, outputCalendar);
      }
      constructor(locale, numbering, outputCalendar, specifiedLocale) {
        const [parsedLocale, parsedNumberingSystem, parsedOutputCalendar] = parseLocaleString2(locale);
        this.locale = parsedLocale;
        this.numberingSystem = numbering || parsedNumberingSystem || null;
        this.outputCalendar = outputCalendar || parsedOutputCalendar || null;
        this.intl = intlConfigString2(this.locale, this.numberingSystem, this.outputCalendar);
        this.weekdaysCache = { format: {}, standalone: {} };
        this.monthsCache = { format: {}, standalone: {} };
        this.meridiemCache = null;
        this.eraCache = {};
        this.specifiedLocale = specifiedLocale;
        this.fastNumbersCached = null;
      }
      get fastNumbers() {
        if (this.fastNumbersCached == null) {
          this.fastNumbersCached = supportsFastNumbers2(this);
        }
        return this.fastNumbersCached;
      }
      listingMode() {
        const isActuallyEn = this.isEnglish();
        const hasNoWeirdness = (this.numberingSystem === null || this.numberingSystem === "latn") && (this.outputCalendar === null || this.outputCalendar === "gregory");
        return isActuallyEn && hasNoWeirdness ? "en" : "intl";
      }
      clone(alts) {
        if (!alts || Object.getOwnPropertyNames(alts).length === 0) {
          return this;
        } else {
          return _Locale.create(
            alts.locale || this.specifiedLocale,
            alts.numberingSystem || this.numberingSystem,
            alts.outputCalendar || this.outputCalendar,
            alts.defaultToEN || false
          );
        }
      }
      redefaultToEN(alts = {}) {
        return this.clone({ ...alts, defaultToEN: true });
      }
      redefaultToSystem(alts = {}) {
        return this.clone({ ...alts, defaultToEN: false });
      }
      months(length, format = false) {
        return listStuff2(this, length, months2, () => {
          const intl = format ? { month: length, day: "numeric" } : { month: length }, formatStr = format ? "format" : "standalone";
          if (!this.monthsCache[formatStr][length]) {
            this.monthsCache[formatStr][length] = mapMonths2((dt) => this.extract(dt, intl, "month"));
          }
          return this.monthsCache[formatStr][length];
        });
      }
      weekdays(length, format = false) {
        return listStuff2(this, length, weekdays2, () => {
          const intl = format ? { weekday: length, year: "numeric", month: "long", day: "numeric" } : { weekday: length }, formatStr = format ? "format" : "standalone";
          if (!this.weekdaysCache[formatStr][length]) {
            this.weekdaysCache[formatStr][length] = mapWeekdays2(
              (dt) => this.extract(dt, intl, "weekday")
            );
          }
          return this.weekdaysCache[formatStr][length];
        });
      }
      meridiems() {
        return listStuff2(
          this,
          void 0,
          () => meridiems2,
          () => {
            if (!this.meridiemCache) {
              const intl = { hour: "numeric", hourCycle: "h12" };
              this.meridiemCache = [DateTime2.utc(2016, 11, 13, 9), DateTime2.utc(2016, 11, 13, 19)].map(
                (dt) => this.extract(dt, intl, "dayperiod")
              );
            }
            return this.meridiemCache;
          }
        );
      }
      eras(length) {
        return listStuff2(this, length, eras2, () => {
          const intl = { era: length };
          if (!this.eraCache[length]) {
            this.eraCache[length] = [DateTime2.utc(-40, 1, 1), DateTime2.utc(2017, 1, 1)].map(
              (dt) => this.extract(dt, intl, "era")
            );
          }
          return this.eraCache[length];
        });
      }
      extract(dt, intlOpts, field) {
        const df = this.dtFormatter(dt, intlOpts), results = df.formatToParts(), matching = results.find((m) => m.type.toLowerCase() === field);
        return matching ? matching.value : null;
      }
      numberFormatter(opts = {}) {
        return new PolyNumberFormatter2(this.intl, opts.forceSimple || this.fastNumbers, opts);
      }
      dtFormatter(dt, intlOpts = {}) {
        return new PolyDateFormatter2(dt, this.intl, intlOpts);
      }
      relFormatter(opts = {}) {
        return new PolyRelFormatter2(this.intl, this.isEnglish(), opts);
      }
      listFormatter(opts = {}) {
        return getCachedLF2(this.intl, opts);
      }
      isEnglish() {
        return this.locale === "en" || this.locale.toLowerCase() === "en-us" || new Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith("en-us");
      }
      equals(other) {
        return this.locale === other.locale && this.numberingSystem === other.numberingSystem && this.outputCalendar === other.outputCalendar;
      }
    };
    var singleton3 = null;
    var FixedOffsetZone2 = class _FixedOffsetZone extends Zone2 {
      /**
       * Get a singleton instance of UTC
       * @return {FixedOffsetZone}
       */
      static get utcInstance() {
        if (singleton3 === null) {
          singleton3 = new _FixedOffsetZone(0);
        }
        return singleton3;
      }
      /**
       * Get an instance with a specified offset
       * @param {number} offset - The offset in minutes
       * @return {FixedOffsetZone}
       */
      static instance(offset3) {
        return offset3 === 0 ? _FixedOffsetZone.utcInstance : new _FixedOffsetZone(offset3);
      }
      /**
       * Get an instance of FixedOffsetZone from a UTC offset string, like "UTC+6"
       * @param {string} s - The offset string to parse
       * @example FixedOffsetZone.parseSpecifier("UTC+6")
       * @example FixedOffsetZone.parseSpecifier("UTC+06")
       * @example FixedOffsetZone.parseSpecifier("UTC-6:00")
       * @return {FixedOffsetZone}
       */
      static parseSpecifier(s3) {
        if (s3) {
          const r = s3.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);
          if (r) {
            return new _FixedOffsetZone(signedOffset2(r[1], r[2]));
          }
        }
        return null;
      }
      constructor(offset3) {
        super();
        this.fixed = offset3;
      }
      /** @override **/
      get type() {
        return "fixed";
      }
      /** @override **/
      get name() {
        return this.fixed === 0 ? "UTC" : `UTC${formatOffset2(this.fixed, "narrow")}`;
      }
      get ianaName() {
        if (this.fixed === 0) {
          return "Etc/UTC";
        } else {
          return `Etc/GMT${formatOffset2(-this.fixed, "narrow")}`;
        }
      }
      /** @override **/
      offsetName() {
        return this.name;
      }
      /** @override **/
      formatOffset(ts, format) {
        return formatOffset2(this.fixed, format);
      }
      /** @override **/
      get isUniversal() {
        return true;
      }
      /** @override **/
      offset() {
        return this.fixed;
      }
      /** @override **/
      equals(otherZone) {
        return otherZone.type === "fixed" && otherZone.fixed === this.fixed;
      }
      /** @override **/
      get isValid() {
        return true;
      }
    };
    var InvalidZone2 = class extends Zone2 {
      constructor(zoneName) {
        super();
        this.zoneName = zoneName;
      }
      /** @override **/
      get type() {
        return "invalid";
      }
      /** @override **/
      get name() {
        return this.zoneName;
      }
      /** @override **/
      get isUniversal() {
        return false;
      }
      /** @override **/
      offsetName() {
        return null;
      }
      /** @override **/
      formatOffset() {
        return "";
      }
      /** @override **/
      offset() {
        return NaN;
      }
      /** @override **/
      equals() {
        return false;
      }
      /** @override **/
      get isValid() {
        return false;
      }
    };
    function normalizeZone2(input, defaultZone3) {
      if (isUndefined2(input) || input === null) {
        return defaultZone3;
      } else if (input instanceof Zone2) {
        return input;
      } else if (isString2(input)) {
        const lowered = input.toLowerCase();
        if (lowered === "default") return defaultZone3;
        else if (lowered === "local" || lowered === "system") return SystemZone2.instance;
        else if (lowered === "utc" || lowered === "gmt") return FixedOffsetZone2.utcInstance;
        else return FixedOffsetZone2.parseSpecifier(lowered) || IANAZone2.create(input);
      } else if (isNumber2(input)) {
        return FixedOffsetZone2.instance(input);
      } else if (typeof input === "object" && "offset" in input && typeof input.offset === "function") {
        return input;
      } else {
        return new InvalidZone2(input);
      }
    }
    var now3 = () => Date.now();
    var defaultZone2 = "system";
    var defaultLocale2 = null;
    var defaultNumberingSystem2 = null;
    var defaultOutputCalendar2 = null;
    var twoDigitCutoffYear2 = 60;
    var throwOnInvalid2;
    var Settings2 = class {
      /**
       * Get the callback for returning the current timestamp.
       * @type {function}
       */
      static get now() {
        return now3;
      }
      /**
       * Set the callback for returning the current timestamp.
       * The function should return a number, which will be interpreted as an Epoch millisecond count
       * @type {function}
       * @example Settings.now = () => Date.now() + 3000 // pretend it is 3 seconds in the future
       * @example Settings.now = () => 0 // always pretend it's Jan 1, 1970 at midnight in UTC time
       */
      static set now(n3) {
        now3 = n3;
      }
      /**
       * Set the default time zone to create DateTimes in. Does not affect existing instances.
       * Use the value "system" to reset this value to the system's time zone.
       * @type {string}
       */
      static set defaultZone(zone) {
        defaultZone2 = zone;
      }
      /**
       * Get the default time zone object currently used to create DateTimes. Does not affect existing instances.
       * The default value is the system's time zone (the one set on the machine that runs this code).
       * @type {Zone}
       */
      static get defaultZone() {
        return normalizeZone2(defaultZone2, SystemZone2.instance);
      }
      /**
       * Get the default locale to create DateTimes with. Does not affect existing instances.
       * @type {string}
       */
      static get defaultLocale() {
        return defaultLocale2;
      }
      /**
       * Set the default locale to create DateTimes with. Does not affect existing instances.
       * @type {string}
       */
      static set defaultLocale(locale) {
        defaultLocale2 = locale;
      }
      /**
       * Get the default numbering system to create DateTimes with. Does not affect existing instances.
       * @type {string}
       */
      static get defaultNumberingSystem() {
        return defaultNumberingSystem2;
      }
      /**
       * Set the default numbering system to create DateTimes with. Does not affect existing instances.
       * @type {string}
       */
      static set defaultNumberingSystem(numberingSystem) {
        defaultNumberingSystem2 = numberingSystem;
      }
      /**
       * Get the default output calendar to create DateTimes with. Does not affect existing instances.
       * @type {string}
       */
      static get defaultOutputCalendar() {
        return defaultOutputCalendar2;
      }
      /**
       * Set the default output calendar to create DateTimes with. Does not affect existing instances.
       * @type {string}
       */
      static set defaultOutputCalendar(outputCalendar) {
        defaultOutputCalendar2 = outputCalendar;
      }
      /**
       * Get the cutoff year after which a string encoding a year as two digits is interpreted to occur in the current century.
       * @type {number}
       */
      static get twoDigitCutoffYear() {
        return twoDigitCutoffYear2;
      }
      /**
       * Set the cutoff year after which a string encoding a year as two digits is interpreted to occur in the current century.
       * @type {number}
       * @example Settings.twoDigitCutoffYear = 0 // cut-off year is 0, so all 'yy' are interpreted as current century
       * @example Settings.twoDigitCutoffYear = 50 // '49' -> 1949; '50' -> 2050
       * @example Settings.twoDigitCutoffYear = 1950 // interpreted as 50
       * @example Settings.twoDigitCutoffYear = 2050 // ALSO interpreted as 50
       */
      static set twoDigitCutoffYear(cutoffYear) {
        twoDigitCutoffYear2 = cutoffYear % 100;
      }
      /**
       * Get whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals
       * @type {boolean}
       */
      static get throwOnInvalid() {
        return throwOnInvalid2;
      }
      /**
       * Set whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals
       * @type {boolean}
       */
      static set throwOnInvalid(t) {
        throwOnInvalid2 = t;
      }
      /**
       * Reset Luxon's global caches. Should only be necessary in testing scenarios.
       * @return {void}
       */
      static resetCaches() {
        Locale2.resetCache();
        IANAZone2.resetCache();
      }
    };
    function isUndefined2(o) {
      return typeof o === "undefined";
    }
    function isNumber2(o) {
      return typeof o === "number";
    }
    function isInteger2(o) {
      return typeof o === "number" && o % 1 === 0;
    }
    function isString2(o) {
      return typeof o === "string";
    }
    function isDate2(o) {
      return Object.prototype.toString.call(o) === "[object Date]";
    }
    function hasRelative2() {
      try {
        return typeof Intl !== "undefined" && !!Intl.RelativeTimeFormat;
      } catch (e) {
        return false;
      }
    }
    function maybeArray2(thing) {
      return Array.isArray(thing) ? thing : [thing];
    }
    function bestBy2(arr, by, compare3) {
      if (arr.length === 0) {
        return void 0;
      }
      return arr.reduce((best, next) => {
        const pair = [by(next), next];
        if (!best) {
          return pair;
        } else if (compare3(best[0], pair[0]) === best[0]) {
          return best;
        } else {
          return pair;
        }
      }, null)[1];
    }
    function pick2(obj, keys) {
      return keys.reduce((a, k) => {
        a[k] = obj[k];
        return a;
      }, {});
    }
    function hasOwnProperty2(obj, prop) {
      return Object.prototype.hasOwnProperty.call(obj, prop);
    }
    function integerBetween2(thing, bottom, top) {
      return isInteger2(thing) && thing >= bottom && thing <= top;
    }
    function floorMod2(x, n3) {
      return x - n3 * Math.floor(x / n3);
    }
    function padStart2(input, n3 = 2) {
      const isNeg = input < 0;
      let padded;
      if (isNeg) {
        padded = "-" + ("" + -input).padStart(n3, "0");
      } else {
        padded = ("" + input).padStart(n3, "0");
      }
      return padded;
    }
    function parseInteger2(string) {
      if (isUndefined2(string) || string === null || string === "") {
        return void 0;
      } else {
        return parseInt(string, 10);
      }
    }
    function parseFloating2(string) {
      if (isUndefined2(string) || string === null || string === "") {
        return void 0;
      } else {
        return parseFloat(string);
      }
    }
    function parseMillis2(fraction) {
      if (isUndefined2(fraction) || fraction === null || fraction === "") {
        return void 0;
      } else {
        const f = parseFloat("0." + fraction) * 1e3;
        return Math.floor(f);
      }
    }
    function roundTo2(number, digits, towardZero = false) {
      const factor = 10 ** digits, rounder = towardZero ? Math.trunc : Math.round;
      return rounder(number * factor) / factor;
    }
    function isLeapYear2(year) {
      return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
    }
    function daysInYear2(year) {
      return isLeapYear2(year) ? 366 : 365;
    }
    function daysInMonth2(year, month) {
      const modMonth = floorMod2(month - 1, 12) + 1, modYear = year + (month - modMonth) / 12;
      if (modMonth === 2) {
        return isLeapYear2(modYear) ? 29 : 28;
      } else {
        return [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][modMonth - 1];
      }
    }
    function objToLocalTS2(obj) {
      let d = Date.UTC(
        obj.year,
        obj.month - 1,
        obj.day,
        obj.hour,
        obj.minute,
        obj.second,
        obj.millisecond
      );
      if (obj.year < 100 && obj.year >= 0) {
        d = new Date(d);
        d.setUTCFullYear(obj.year, obj.month - 1, obj.day);
      }
      return +d;
    }
    function weeksInWeekYear2(weekYear) {
      const p1 = (weekYear + Math.floor(weekYear / 4) - Math.floor(weekYear / 100) + Math.floor(weekYear / 400)) % 7, last = weekYear - 1, p2 = (last + Math.floor(last / 4) - Math.floor(last / 100) + Math.floor(last / 400)) % 7;
      return p1 === 4 || p2 === 3 ? 53 : 52;
    }
    function untruncateYear2(year) {
      if (year > 99) {
        return year;
      } else return year > Settings2.twoDigitCutoffYear ? 1900 + year : 2e3 + year;
    }
    function parseZoneInfo2(ts, offsetFormat, locale, timeZone = null) {
      const date = new Date(ts), intlOpts = {
        hourCycle: "h23",
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
        hour: "2-digit",
        minute: "2-digit"
      };
      if (timeZone) {
        intlOpts.timeZone = timeZone;
      }
      const modified = { timeZoneName: offsetFormat, ...intlOpts };
      const parsed = new Intl.DateTimeFormat(locale, modified).formatToParts(date).find((m) => m.type.toLowerCase() === "timezonename");
      return parsed ? parsed.value : null;
    }
    function signedOffset2(offHourStr, offMinuteStr) {
      let offHour = parseInt(offHourStr, 10);
      if (Number.isNaN(offHour)) {
        offHour = 0;
      }
      const offMin = parseInt(offMinuteStr, 10) || 0, offMinSigned = offHour < 0 || Object.is(offHour, -0) ? -offMin : offMin;
      return offHour * 60 + offMinSigned;
    }
    function asNumber2(value) {
      const numericValue = Number(value);
      if (typeof value === "boolean" || value === "" || Number.isNaN(numericValue))
        throw new InvalidArgumentError2(`Invalid unit value ${value}`);
      return numericValue;
    }
    function normalizeObject2(obj, normalizer) {
      const normalized = {};
      for (const u in obj) {
        if (hasOwnProperty2(obj, u)) {
          const v = obj[u];
          if (v === void 0 || v === null) continue;
          normalized[normalizer(u)] = asNumber2(v);
        }
      }
      return normalized;
    }
    function formatOffset2(offset3, format) {
      const hours = Math.trunc(Math.abs(offset3 / 60)), minutes = Math.trunc(Math.abs(offset3 % 60)), sign = offset3 >= 0 ? "+" : "-";
      switch (format) {
        case "short":
          return `${sign}${padStart2(hours, 2)}:${padStart2(minutes, 2)}`;
        case "narrow":
          return `${sign}${hours}${minutes > 0 ? `:${minutes}` : ""}`;
        case "techie":
          return `${sign}${padStart2(hours, 2)}${padStart2(minutes, 2)}`;
        default:
          throw new RangeError(`Value format ${format} is out of range for property format`);
      }
    }
    function timeObject2(obj) {
      return pick2(obj, ["hour", "minute", "second", "millisecond"]);
    }
    var monthsLong2 = [
      "January",
      "February",
      "March",
      "April",
      "May",
      "June",
      "July",
      "August",
      "September",
      "October",
      "November",
      "December"
    ];
    var monthsShort2 = [
      "Jan",
      "Feb",
      "Mar",
      "Apr",
      "May",
      "Jun",
      "Jul",
      "Aug",
      "Sep",
      "Oct",
      "Nov",
      "Dec"
    ];
    var monthsNarrow2 = ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"];
    function months2(length) {
      switch (length) {
        case "narrow":
          return [...monthsNarrow2];
        case "short":
          return [...monthsShort2];
        case "long":
          return [...monthsLong2];
        case "numeric":
          return ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"];
        case "2-digit":
          return ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];
        default:
          return null;
      }
    }
    var weekdaysLong2 = [
      "Monday",
      "Tuesday",
      "Wednesday",
      "Thursday",
      "Friday",
      "Saturday",
      "Sunday"
    ];
    var weekdaysShort2 = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
    var weekdaysNarrow2 = ["M", "T", "W", "T", "F", "S", "S"];
    function weekdays2(length) {
      switch (length) {
        case "narrow":
          return [...weekdaysNarrow2];
        case "short":
          return [...weekdaysShort2];
        case "long":
          return [...weekdaysLong2];
        case "numeric":
          return ["1", "2", "3", "4", "5", "6", "7"];
        default:
          return null;
      }
    }
    var meridiems2 = ["AM", "PM"];
    var erasLong2 = ["Before Christ", "Anno Domini"];
    var erasShort2 = ["BC", "AD"];
    var erasNarrow2 = ["B", "A"];
    function eras2(length) {
      switch (length) {
        case "narrow":
          return [...erasNarrow2];
        case "short":
          return [...erasShort2];
        case "long":
          return [...erasLong2];
        default:
          return null;
      }
    }
    function meridiemForDateTime2(dt) {
      return meridiems2[dt.hour < 12 ? 0 : 1];
    }
    function weekdayForDateTime2(dt, length) {
      return weekdays2(length)[dt.weekday - 1];
    }
    function monthForDateTime2(dt, length) {
      return months2(length)[dt.month - 1];
    }
    function eraForDateTime2(dt, length) {
      return eras2(length)[dt.year < 0 ? 0 : 1];
    }
    function formatRelativeTime2(unit, count, numeric = "always", narrow = false) {
      const units = {
        years: ["year", "yr."],
        quarters: ["quarter", "qtr."],
        months: ["month", "mo."],
        weeks: ["week", "wk."],
        days: ["day", "day", "days"],
        hours: ["hour", "hr."],
        minutes: ["minute", "min."],
        seconds: ["second", "sec."]
      };
      const lastable = ["hours", "minutes", "seconds"].indexOf(unit) === -1;
      if (numeric === "auto" && lastable) {
        const isDay = unit === "days";
        switch (count) {
          case 1:
            return isDay ? "tomorrow" : `next ${units[unit][0]}`;
          case -1:
            return isDay ? "yesterday" : `last ${units[unit][0]}`;
          case 0:
            return isDay ? "today" : `this ${units[unit][0]}`;
        }
      }
      const isInPast = Object.is(count, -0) || count < 0, fmtValue = Math.abs(count), singular = fmtValue === 1, lilUnits = units[unit], fmtUnit = narrow ? singular ? lilUnits[1] : lilUnits[2] || lilUnits[1] : singular ? units[unit][0] : unit;
      return isInPast ? `${fmtValue} ${fmtUnit} ago` : `in ${fmtValue} ${fmtUnit}`;
    }
    function stringifyTokens2(splits, tokenToString) {
      let s3 = "";
      for (const token of splits) {
        if (token.literal) {
          s3 += token.val;
        } else {
          s3 += tokenToString(token.val);
        }
      }
      return s3;
    }
    var macroTokenToFormatOpts2 = {
      D: DATE_SHORT2,
      DD: DATE_MED2,
      DDD: DATE_FULL2,
      DDDD: DATE_HUGE2,
      t: TIME_SIMPLE2,
      tt: TIME_WITH_SECONDS2,
      ttt: TIME_WITH_SHORT_OFFSET2,
      tttt: TIME_WITH_LONG_OFFSET2,
      T: TIME_24_SIMPLE2,
      TT: TIME_24_WITH_SECONDS2,
      TTT: TIME_24_WITH_SHORT_OFFSET2,
      TTTT: TIME_24_WITH_LONG_OFFSET2,
      f: DATETIME_SHORT2,
      ff: DATETIME_MED2,
      fff: DATETIME_FULL2,
      ffff: DATETIME_HUGE2,
      F: DATETIME_SHORT_WITH_SECONDS2,
      FF: DATETIME_MED_WITH_SECONDS2,
      FFF: DATETIME_FULL_WITH_SECONDS2,
      FFFF: DATETIME_HUGE_WITH_SECONDS2
    };
    var Formatter2 = class _Formatter {
      static create(locale, opts = {}) {
        return new _Formatter(locale, opts);
      }
      static parseFormat(fmt) {
        let current = null, currentFull = "", bracketed = false;
        const splits = [];
        for (let i = 0; i < fmt.length; i++) {
          const c = fmt.charAt(i);
          if (c === "'") {
            if (currentFull.length > 0) {
              splits.push({ literal: bracketed || /^\s+$/.test(currentFull), val: currentFull });
            }
            current = null;
            currentFull = "";
            bracketed = !bracketed;
          } else if (bracketed) {
            currentFull += c;
          } else if (c === current) {
            currentFull += c;
          } else {
            if (currentFull.length > 0) {
              splits.push({ literal: /^\s+$/.test(currentFull), val: currentFull });
            }
            currentFull = c;
            current = c;
          }
        }
        if (currentFull.length > 0) {
          splits.push({ literal: bracketed || /^\s+$/.test(currentFull), val: currentFull });
        }
        return splits;
      }
      static macroTokenToFormatOpts(token) {
        return macroTokenToFormatOpts2[token];
      }
      constructor(locale, formatOpts) {
        this.opts = formatOpts;
        this.loc = locale;
        this.systemLoc = null;
      }
      formatWithSystemDefault(dt, opts) {
        if (this.systemLoc === null) {
          this.systemLoc = this.loc.redefaultToSystem();
        }
        const df = this.systemLoc.dtFormatter(dt, { ...this.opts, ...opts });
        return df.format();
      }
      dtFormatter(dt, opts = {}) {
        return this.loc.dtFormatter(dt, { ...this.opts, ...opts });
      }
      formatDateTime(dt, opts) {
        return this.dtFormatter(dt, opts).format();
      }
      formatDateTimeParts(dt, opts) {
        return this.dtFormatter(dt, opts).formatToParts();
      }
      formatInterval(interval, opts) {
        const df = this.dtFormatter(interval.start, opts);
        return df.dtf.formatRange(interval.start.toJSDate(), interval.end.toJSDate());
      }
      resolvedOptions(dt, opts) {
        return this.dtFormatter(dt, opts).resolvedOptions();
      }
      num(n3, p = 0) {
        if (this.opts.forceSimple) {
          return padStart2(n3, p);
        }
        const opts = { ...this.opts };
        if (p > 0) {
          opts.padTo = p;
        }
        return this.loc.numberFormatter(opts).format(n3);
      }
      formatDateTimeFromString(dt, fmt) {
        const knownEnglish = this.loc.listingMode() === "en", useDateTimeFormatter = this.loc.outputCalendar && this.loc.outputCalendar !== "gregory", string = (opts, extract) => this.loc.extract(dt, opts, extract), formatOffset3 = (opts) => {
          if (dt.isOffsetFixed && dt.offset === 0 && opts.allowZ) {
            return "Z";
          }
          return dt.isValid ? dt.zone.formatOffset(dt.ts, opts.format) : "";
        }, meridiem = () => knownEnglish ? meridiemForDateTime2(dt) : string({ hour: "numeric", hourCycle: "h12" }, "dayperiod"), month = (length, standalone) => knownEnglish ? monthForDateTime2(dt, length) : string(standalone ? { month: length } : { month: length, day: "numeric" }, "month"), weekday = (length, standalone) => knownEnglish ? weekdayForDateTime2(dt, length) : string(
          standalone ? { weekday: length } : { weekday: length, month: "long", day: "numeric" },
          "weekday"
        ), maybeMacro = (token) => {
          const formatOpts = _Formatter.macroTokenToFormatOpts(token);
          if (formatOpts) {
            return this.formatWithSystemDefault(dt, formatOpts);
          } else {
            return token;
          }
        }, era = (length) => knownEnglish ? eraForDateTime2(dt, length) : string({ era: length }, "era"), tokenToString = (token) => {
          switch (token) {
            // ms
            case "S":
              return this.num(dt.millisecond);
            case "u":
            // falls through
            case "SSS":
              return this.num(dt.millisecond, 3);
            // seconds
            case "s":
              return this.num(dt.second);
            case "ss":
              return this.num(dt.second, 2);
            // fractional seconds
            case "uu":
              return this.num(Math.floor(dt.millisecond / 10), 2);
            case "uuu":
              return this.num(Math.floor(dt.millisecond / 100));
            // minutes
            case "m":
              return this.num(dt.minute);
            case "mm":
              return this.num(dt.minute, 2);
            // hours
            case "h":
              return this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12);
            case "hh":
              return this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12, 2);
            case "H":
              return this.num(dt.hour);
            case "HH":
              return this.num(dt.hour, 2);
            // offset
            case "Z":
              return formatOffset3({ format: "narrow", allowZ: this.opts.allowZ });
            case "ZZ":
              return formatOffset3({ format: "short", allowZ: this.opts.allowZ });
            case "ZZZ":
              return formatOffset3({ format: "techie", allowZ: this.opts.allowZ });
            case "ZZZZ":
              return dt.zone.offsetName(dt.ts, { format: "short", locale: this.loc.locale });
            case "ZZZZZ":
              return dt.zone.offsetName(dt.ts, { format: "long", locale: this.loc.locale });
            // zone
            case "z":
              return dt.zoneName;
            // meridiems
            case "a":
              return meridiem();
            // dates
            case "d":
              return useDateTimeFormatter ? string({ day: "numeric" }, "day") : this.num(dt.day);
            case "dd":
              return useDateTimeFormatter ? string({ day: "2-digit" }, "day") : this.num(dt.day, 2);
            // weekdays - standalone
            case "c":
              return this.num(dt.weekday);
            case "ccc":
              return weekday("short", true);
            case "cccc":
              return weekday("long", true);
            case "ccccc":
              return weekday("narrow", true);
            // weekdays - format
            case "E":
              return this.num(dt.weekday);
            case "EEE":
              return weekday("short", false);
            case "EEEE":
              return weekday("long", false);
            case "EEEEE":
              return weekday("narrow", false);
            // months - standalone
            case "L":
              return useDateTimeFormatter ? string({ month: "numeric", day: "numeric" }, "month") : this.num(dt.month);
            case "LL":
              return useDateTimeFormatter ? string({ month: "2-digit", day: "numeric" }, "month") : this.num(dt.month, 2);
            case "LLL":
              return month("short", true);
            case "LLLL":
              return month("long", true);
            case "LLLLL":
              return month("narrow", true);
            // months - format
            case "M":
              return useDateTimeFormatter ? string({ month: "numeric" }, "month") : this.num(dt.month);
            case "MM":
              return useDateTimeFormatter ? string({ month: "2-digit" }, "month") : this.num(dt.month, 2);
            case "MMM":
              return month("short", false);
            case "MMMM":
              return month("long", false);
            case "MMMMM":
              return month("narrow", false);
            // years
            case "y":
              return useDateTimeFormatter ? string({ year: "numeric" }, "year") : this.num(dt.year);
            case "yy":
              return useDateTimeFormatter ? string({ year: "2-digit" }, "year") : this.num(dt.year.toString().slice(-2), 2);
            case "yyyy":
              return useDateTimeFormatter ? string({ year: "numeric" }, "year") : this.num(dt.year, 4);
            case "yyyyyy":
              return useDateTimeFormatter ? string({ year: "numeric" }, "year") : this.num(dt.year, 6);
            // eras
            case "G":
              return era("short");
            case "GG":
              return era("long");
            case "GGGGG":
              return era("narrow");
            case "kk":
              return this.num(dt.weekYear.toString().slice(-2), 2);
            case "kkkk":
              return this.num(dt.weekYear, 4);
            case "W":
              return this.num(dt.weekNumber);
            case "WW":
              return this.num(dt.weekNumber, 2);
            case "o":
              return this.num(dt.ordinal);
            case "ooo":
              return this.num(dt.ordinal, 3);
            case "q":
              return this.num(dt.quarter);
            case "qq":
              return this.num(dt.quarter, 2);
            case "X":
              return this.num(Math.floor(dt.ts / 1e3));
            case "x":
              return this.num(dt.ts);
            default:
              return maybeMacro(token);
          }
        };
        return stringifyTokens2(_Formatter.parseFormat(fmt), tokenToString);
      }
      formatDurationFromString(dur, fmt) {
        const tokenToField = (token) => {
          switch (token[0]) {
            case "S":
              return "millisecond";
            case "s":
              return "second";
            case "m":
              return "minute";
            case "h":
              return "hour";
            case "d":
              return "day";
            case "w":
              return "week";
            case "M":
              return "month";
            case "y":
              return "year";
            default:
              return null;
          }
        }, tokenToString = (lildur) => (token) => {
          const mapped = tokenToField(token);
          if (mapped) {
            return this.num(lildur.get(mapped), token.length);
          } else {
            return token;
          }
        }, tokens = _Formatter.parseFormat(fmt), realTokens = tokens.reduce(
          (found, { literal, val }) => literal ? found : found.concat(val),
          []
        ), collapsed = dur.shiftTo(...realTokens.map(tokenToField).filter((t) => t));
        return stringifyTokens2(tokens, tokenToString(collapsed));
      }
    };
    var Invalid2 = class {
      constructor(reason, explanation) {
        this.reason = reason;
        this.explanation = explanation;
      }
      toMessage() {
        if (this.explanation) {
          return `${this.reason}: ${this.explanation}`;
        } else {
          return this.reason;
        }
      }
    };
    var ianaRegex2 = /[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;
    function combineRegexes2(...regexes) {
      const full = regexes.reduce((f, r) => f + r.source, "");
      return RegExp(`^${full}$`);
    }
    function combineExtractors2(...extractors) {
      return (m) => extractors.reduce(
        ([mergedVals, mergedZone, cursor], ex) => {
          const [val, zone, next] = ex(m, cursor);
          return [{ ...mergedVals, ...val }, zone || mergedZone, next];
        },
        [{}, null, 1]
      ).slice(0, 2);
    }
    function parse2(s3, ...patterns) {
      if (s3 == null) {
        return [null, null];
      }
      for (const [regex, extractor] of patterns) {
        const m = regex.exec(s3);
        if (m) {
          return extractor(m);
        }
      }
      return [null, null];
    }
    function simpleParse2(...keys) {
      return (match3, cursor) => {
        const ret = {};
        let i;
        for (i = 0; i < keys.length; i++) {
          ret[keys[i]] = parseInteger2(match3[cursor + i]);
        }
        return [ret, null, cursor + i];
      };
    }
    var offsetRegex2 = /(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/;
    var isoExtendedZone2 = `(?:${offsetRegex2.source}?(?:\\[(${ianaRegex2.source})\\])?)?`;
    var isoTimeBaseRegex2 = /(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/;
    var isoTimeRegex2 = RegExp(`${isoTimeBaseRegex2.source}${isoExtendedZone2}`);
    var isoTimeExtensionRegex2 = RegExp(`(?:T${isoTimeRegex2.source})?`);
    var isoYmdRegex2 = /([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/;
    var isoWeekRegex2 = /(\d{4})-?W(\d\d)(?:-?(\d))?/;
    var isoOrdinalRegex2 = /(\d{4})-?(\d{3})/;
    var extractISOWeekData2 = simpleParse2("weekYear", "weekNumber", "weekDay");
    var extractISOOrdinalData2 = simpleParse2("year", "ordinal");
    var sqlYmdRegex2 = /(\d{4})-(\d\d)-(\d\d)/;
    var sqlTimeRegex2 = RegExp(
      `${isoTimeBaseRegex2.source} ?(?:${offsetRegex2.source}|(${ianaRegex2.source}))?`
    );
    var sqlTimeExtensionRegex2 = RegExp(`(?: ${sqlTimeRegex2.source})?`);
    function int2(match3, pos, fallback) {
      const m = match3[pos];
      return isUndefined2(m) ? fallback : parseInteger2(m);
    }
    function extractISOYmd2(match3, cursor) {
      const item = {
        year: int2(match3, cursor),
        month: int2(match3, cursor + 1, 1),
        day: int2(match3, cursor + 2, 1)
      };
      return [item, null, cursor + 3];
    }
    function extractISOTime2(match3, cursor) {
      const item = {
        hours: int2(match3, cursor, 0),
        minutes: int2(match3, cursor + 1, 0),
        seconds: int2(match3, cursor + 2, 0),
        milliseconds: parseMillis2(match3[cursor + 3])
      };
      return [item, null, cursor + 4];
    }
    function extractISOOffset2(match3, cursor) {
      const local = !match3[cursor] && !match3[cursor + 1], fullOffset = signedOffset2(match3[cursor + 1], match3[cursor + 2]), zone = local ? null : FixedOffsetZone2.instance(fullOffset);
      return [{}, zone, cursor + 3];
    }
    function extractIANAZone2(match3, cursor) {
      const zone = match3[cursor] ? IANAZone2.create(match3[cursor]) : null;
      return [{}, zone, cursor + 1];
    }
    var isoTimeOnly2 = RegExp(`^T?${isoTimeBaseRegex2.source}$`);
    var isoDuration2 = /^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/;
    function extractISODuration2(match3) {
      const [s3, yearStr, monthStr, weekStr, dayStr, hourStr, minuteStr, secondStr, millisecondsStr] = match3;
      const hasNegativePrefix = s3[0] === "-";
      const negativeSeconds = secondStr && secondStr[0] === "-";
      const maybeNegate = (num, force = false) => num !== void 0 && (force || num && hasNegativePrefix) ? -num : num;
      return [
        {
          years: maybeNegate(parseFloating2(yearStr)),
          months: maybeNegate(parseFloating2(monthStr)),
          weeks: maybeNegate(parseFloating2(weekStr)),
          days: maybeNegate(parseFloating2(dayStr)),
          hours: maybeNegate(parseFloating2(hourStr)),
          minutes: maybeNegate(parseFloating2(minuteStr)),
          seconds: maybeNegate(parseFloating2(secondStr), secondStr === "-0"),
          milliseconds: maybeNegate(parseMillis2(millisecondsStr), negativeSeconds)
        }
      ];
    }
    var obsOffsets2 = {
      GMT: 0,
      EDT: -4 * 60,
      EST: -5 * 60,
      CDT: -5 * 60,
      CST: -6 * 60,
      MDT: -6 * 60,
      MST: -7 * 60,
      PDT: -7 * 60,
      PST: -8 * 60
    };
    function fromStrings2(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) {
      const result = {
        year: yearStr.length === 2 ? untruncateYear2(parseInteger2(yearStr)) : parseInteger2(yearStr),
        month: monthsShort2.indexOf(monthStr) + 1,
        day: parseInteger2(dayStr),
        hour: parseInteger2(hourStr),
        minute: parseInteger2(minuteStr)
      };
      if (secondStr) result.second = parseInteger2(secondStr);
      if (weekdayStr) {
        result.weekday = weekdayStr.length > 3 ? weekdaysLong2.indexOf(weekdayStr) + 1 : weekdaysShort2.indexOf(weekdayStr) + 1;
      }
      return result;
    }
    var rfc28222 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/;
    function extractRFC28222(match3) {
      const [
        ,
        weekdayStr,
        dayStr,
        monthStr,
        yearStr,
        hourStr,
        minuteStr,
        secondStr,
        obsOffset,
        milOffset,
        offHourStr,
        offMinuteStr
      ] = match3, result = fromStrings2(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);
      let offset3;
      if (obsOffset) {
        offset3 = obsOffsets2[obsOffset];
      } else if (milOffset) {
        offset3 = 0;
      } else {
        offset3 = signedOffset2(offHourStr, offMinuteStr);
      }
      return [result, new FixedOffsetZone2(offset3)];
    }
    function preprocessRFC28222(s3) {
      return s3.replace(/\([^()]*\)|[\n\t]/g, " ").replace(/(\s\s+)/g, " ").trim();
    }
    var rfc11232 = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/;
    var rfc8502 = /^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/;
    var ascii2 = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;
    function extractRFC1123Or8502(match3) {
      const [, weekdayStr, dayStr, monthStr, yearStr, hourStr, minuteStr, secondStr] = match3, result = fromStrings2(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);
      return [result, FixedOffsetZone2.utcInstance];
    }
    function extractASCII2(match3) {
      const [, weekdayStr, monthStr, dayStr, hourStr, minuteStr, secondStr, yearStr] = match3, result = fromStrings2(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);
      return [result, FixedOffsetZone2.utcInstance];
    }
    var isoYmdWithTimeExtensionRegex2 = combineRegexes2(isoYmdRegex2, isoTimeExtensionRegex2);
    var isoWeekWithTimeExtensionRegex2 = combineRegexes2(isoWeekRegex2, isoTimeExtensionRegex2);
    var isoOrdinalWithTimeExtensionRegex2 = combineRegexes2(isoOrdinalRegex2, isoTimeExtensionRegex2);
    var isoTimeCombinedRegex2 = combineRegexes2(isoTimeRegex2);
    var extractISOYmdTimeAndOffset2 = combineExtractors2(
      extractISOYmd2,
      extractISOTime2,
      extractISOOffset2,
      extractIANAZone2
    );
    var extractISOWeekTimeAndOffset2 = combineExtractors2(
      extractISOWeekData2,
      extractISOTime2,
      extractISOOffset2,
      extractIANAZone2
    );
    var extractISOOrdinalDateAndTime2 = combineExtractors2(
      extractISOOrdinalData2,
      extractISOTime2,
      extractISOOffset2,
      extractIANAZone2
    );
    var extractISOTimeAndOffset2 = combineExtractors2(
      extractISOTime2,
      extractISOOffset2,
      extractIANAZone2
    );
    function parseISODate2(s3) {
      return parse2(
        s3,
        [isoYmdWithTimeExtensionRegex2, extractISOYmdTimeAndOffset2],
        [isoWeekWithTimeExtensionRegex2, extractISOWeekTimeAndOffset2],
        [isoOrdinalWithTimeExtensionRegex2, extractISOOrdinalDateAndTime2],
        [isoTimeCombinedRegex2, extractISOTimeAndOffset2]
      );
    }
    function parseRFC2822Date2(s3) {
      return parse2(preprocessRFC28222(s3), [rfc28222, extractRFC28222]);
    }
    function parseHTTPDate2(s3) {
      return parse2(
        s3,
        [rfc11232, extractRFC1123Or8502],
        [rfc8502, extractRFC1123Or8502],
        [ascii2, extractASCII2]
      );
    }
    function parseISODuration2(s3) {
      return parse2(s3, [isoDuration2, extractISODuration2]);
    }
    var extractISOTimeOnly2 = combineExtractors2(extractISOTime2);
    function parseISOTimeOnly2(s3) {
      return parse2(s3, [isoTimeOnly2, extractISOTimeOnly2]);
    }
    var sqlYmdWithTimeExtensionRegex2 = combineRegexes2(sqlYmdRegex2, sqlTimeExtensionRegex2);
    var sqlTimeCombinedRegex2 = combineRegexes2(sqlTimeRegex2);
    var extractISOTimeOffsetAndIANAZone2 = combineExtractors2(
      extractISOTime2,
      extractISOOffset2,
      extractIANAZone2
    );
    function parseSQL2(s3) {
      return parse2(
        s3,
        [sqlYmdWithTimeExtensionRegex2, extractISOYmdTimeAndOffset2],
        [sqlTimeCombinedRegex2, extractISOTimeOffsetAndIANAZone2]
      );
    }
    var INVALID$2 = "Invalid Duration";
    var lowOrderMatrix2 = {
      weeks: {
        days: 7,
        hours: 7 * 24,
        minutes: 7 * 24 * 60,
        seconds: 7 * 24 * 60 * 60,
        milliseconds: 7 * 24 * 60 * 60 * 1e3
      },
      days: {
        hours: 24,
        minutes: 24 * 60,
        seconds: 24 * 60 * 60,
        milliseconds: 24 * 60 * 60 * 1e3
      },
      hours: { minutes: 60, seconds: 60 * 60, milliseconds: 60 * 60 * 1e3 },
      minutes: { seconds: 60, milliseconds: 60 * 1e3 },
      seconds: { milliseconds: 1e3 }
    };
    var casualMatrix2 = {
      years: {
        quarters: 4,
        months: 12,
        weeks: 52,
        days: 365,
        hours: 365 * 24,
        minutes: 365 * 24 * 60,
        seconds: 365 * 24 * 60 * 60,
        milliseconds: 365 * 24 * 60 * 60 * 1e3
      },
      quarters: {
        months: 3,
        weeks: 13,
        days: 91,
        hours: 91 * 24,
        minutes: 91 * 24 * 60,
        seconds: 91 * 24 * 60 * 60,
        milliseconds: 91 * 24 * 60 * 60 * 1e3
      },
      months: {
        weeks: 4,
        days: 30,
        hours: 30 * 24,
        minutes: 30 * 24 * 60,
        seconds: 30 * 24 * 60 * 60,
        milliseconds: 30 * 24 * 60 * 60 * 1e3
      },
      ...lowOrderMatrix2
    };
    var daysInYearAccurate2 = 146097 / 400;
    var daysInMonthAccurate2 = 146097 / 4800;
    var accurateMatrix2 = {
      years: {
        quarters: 4,
        months: 12,
        weeks: daysInYearAccurate2 / 7,
        days: daysInYearAccurate2,
        hours: daysInYearAccurate2 * 24,
        minutes: daysInYearAccurate2 * 24 * 60,
        seconds: daysInYearAccurate2 * 24 * 60 * 60,
        milliseconds: daysInYearAccurate2 * 24 * 60 * 60 * 1e3
      },
      quarters: {
        months: 3,
        weeks: daysInYearAccurate2 / 28,
        days: daysInYearAccurate2 / 4,
        hours: daysInYearAccurate2 * 24 / 4,
        minutes: daysInYearAccurate2 * 24 * 60 / 4,
        seconds: daysInYearAccurate2 * 24 * 60 * 60 / 4,
        milliseconds: daysInYearAccurate2 * 24 * 60 * 60 * 1e3 / 4
      },
      months: {
        weeks: daysInMonthAccurate2 / 7,
        days: daysInMonthAccurate2,
        hours: daysInMonthAccurate2 * 24,
        minutes: daysInMonthAccurate2 * 24 * 60,
        seconds: daysInMonthAccurate2 * 24 * 60 * 60,
        milliseconds: daysInMonthAccurate2 * 24 * 60 * 60 * 1e3
      },
      ...lowOrderMatrix2
    };
    var orderedUnits$1 = [
      "years",
      "quarters",
      "months",
      "weeks",
      "days",
      "hours",
      "minutes",
      "seconds",
      "milliseconds"
    ];
    var reverseUnits2 = orderedUnits$1.slice(0).reverse();
    function clone$1(dur, alts, clear = false) {
      const conf = {
        values: clear ? alts.values : { ...dur.values, ...alts.values || {} },
        loc: dur.loc.clone(alts.loc),
        conversionAccuracy: alts.conversionAccuracy || dur.conversionAccuracy,
        matrix: alts.matrix || dur.matrix
      };
      return new Duration2(conf);
    }
    function durationToMillis2(matrix, vals) {
      let sum = vals.milliseconds ?? 0;
      for (const unit of reverseUnits2.slice(1)) {
        if (vals[unit]) {
          sum += vals[unit] * matrix[unit]["milliseconds"];
        }
      }
      return sum;
    }
    function normalizeValues2(matrix, vals) {
      const factor = durationToMillis2(matrix, vals) < 0 ? -1 : 1;
      orderedUnits$1.reduceRight((previous, current) => {
        if (!isUndefined2(vals[current])) {
          if (previous) {
            const previousVal = vals[previous] * factor;
            const conv = matrix[current][previous];
            const rollUp = Math.floor(previousVal / conv);
            vals[current] += rollUp * factor;
            vals[previous] -= rollUp * conv * factor;
          }
          return current;
        } else {
          return previous;
        }
      }, null);
      orderedUnits$1.reduce((previous, current) => {
        if (!isUndefined2(vals[current])) {
          if (previous) {
            const fraction = vals[previous] % 1;
            vals[previous] -= fraction;
            vals[current] += fraction * matrix[previous][current];
          }
          return current;
        } else {
          return previous;
        }
      }, null);
    }
    function removeZeroes2(vals) {
      const newVals = {};
      for (const [key, value] of Object.entries(vals)) {
        if (value !== 0) {
          newVals[key] = value;
        }
      }
      return newVals;
    }
    var Duration2 = class _Duration {
      /**
       * @private
       */
      constructor(config) {
        const accurate = config.conversionAccuracy === "longterm" || false;
        let matrix = accurate ? accurateMatrix2 : casualMatrix2;
        if (config.matrix) {
          matrix = config.matrix;
        }
        this.values = config.values;
        this.loc = config.loc || Locale2.create();
        this.conversionAccuracy = accurate ? "longterm" : "casual";
        this.invalid = config.invalid || null;
        this.matrix = matrix;
        this.isLuxonDuration = true;
      }
      /**
       * Create Duration from a number of milliseconds.
       * @param {number} count of milliseconds
       * @param {Object} opts - options for parsing
       * @param {string} [opts.locale='en-US'] - the locale to use
       * @param {string} opts.numberingSystem - the numbering system to use
       * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
       * @return {Duration}
       */
      static fromMillis(count, opts) {
        return _Duration.fromObject({ milliseconds: count }, opts);
      }
      /**
       * Create a Duration from a JavaScript object with keys like 'years' and 'hours'.
       * If this object is empty then a zero milliseconds duration is returned.
       * @param {Object} obj - the object to create the DateTime from
       * @param {number} obj.years
       * @param {number} obj.quarters
       * @param {number} obj.months
       * @param {number} obj.weeks
       * @param {number} obj.days
       * @param {number} obj.hours
       * @param {number} obj.minutes
       * @param {number} obj.seconds
       * @param {number} obj.milliseconds
       * @param {Object} [opts=[]] - options for creating this Duration
       * @param {string} [opts.locale='en-US'] - the locale to use
       * @param {string} opts.numberingSystem - the numbering system to use
       * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use
       * @param {string} [opts.matrix=Object] - the custom conversion system to use
       * @return {Duration}
       */
      static fromObject(obj, opts = {}) {
        if (obj == null || typeof obj !== "object") {
          throw new InvalidArgumentError2(
            `Duration.fromObject: argument expected to be an object, got ${obj === null ? "null" : typeof obj}`
          );
        }
        return new _Duration({
          values: normalizeObject2(obj, _Duration.normalizeUnit),
          loc: Locale2.fromObject(opts),
          conversionAccuracy: opts.conversionAccuracy,
          matrix: opts.matrix
        });
      }
      /**
       * Create a Duration from DurationLike.
       *
       * @param {Object | number | Duration} durationLike
       * One of:
       * - object with keys like 'years' and 'hours'.
       * - number representing milliseconds
       * - Duration instance
       * @return {Duration}
       */
      static fromDurationLike(durationLike) {
        if (isNumber2(durationLike)) {
          return _Duration.fromMillis(durationLike);
        } else if (_Duration.isDuration(durationLike)) {
          return durationLike;
        } else if (typeof durationLike === "object") {
          return _Duration.fromObject(durationLike);
        } else {
          throw new InvalidArgumentError2(
            `Unknown duration argument ${durationLike} of type ${typeof durationLike}`
          );
        }
      }
      /**
       * Create a Duration from an ISO 8601 duration string.
       * @param {string} text - text to parse
       * @param {Object} opts - options for parsing
       * @param {string} [opts.locale='en-US'] - the locale to use
       * @param {string} opts.numberingSystem - the numbering system to use
       * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use
       * @param {string} [opts.matrix=Object] - the preset conversion system to use
       * @see https://en.wikipedia.org/wiki/ISO_8601#Durations
       * @example Duration.fromISO('P3Y6M1W4DT12H30M5S').toObject() //=> { years: 3, months: 6, weeks: 1, days: 4, hours: 12, minutes: 30, seconds: 5 }
       * @example Duration.fromISO('PT23H').toObject() //=> { hours: 23 }
       * @example Duration.fromISO('P5Y3M').toObject() //=> { years: 5, months: 3 }
       * @return {Duration}
       */
      static fromISO(text2, opts) {
        const [parsed] = parseISODuration2(text2);
        if (parsed) {
          return _Duration.fromObject(parsed, opts);
        } else {
          return _Duration.invalid("unparsable", `the input "${text2}" can't be parsed as ISO 8601`);
        }
      }
      /**
       * Create a Duration from an ISO 8601 time string.
       * @param {string} text - text to parse
       * @param {Object} opts - options for parsing
       * @param {string} [opts.locale='en-US'] - the locale to use
       * @param {string} opts.numberingSystem - the numbering system to use
       * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use
       * @param {string} [opts.matrix=Object] - the conversion system to use
       * @see https://en.wikipedia.org/wiki/ISO_8601#Times
       * @example Duration.fromISOTime('11:22:33.444').toObject() //=> { hours: 11, minutes: 22, seconds: 33, milliseconds: 444 }
       * @example Duration.fromISOTime('11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }
       * @example Duration.fromISOTime('T11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }
       * @example Duration.fromISOTime('1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }
       * @example Duration.fromISOTime('T1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }
       * @return {Duration}
       */
      static fromISOTime(text2, opts) {
        const [parsed] = parseISOTimeOnly2(text2);
        if (parsed) {
          return _Duration.fromObject(parsed, opts);
        } else {
          return _Duration.invalid("unparsable", `the input "${text2}" can't be parsed as ISO 8601`);
        }
      }
      /**
       * Create an invalid Duration.
       * @param {string} reason - simple string of why this datetime is invalid. Should not contain parameters or anything else data-dependent
       * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information
       * @return {Duration}
       */
      static invalid(reason, explanation = null) {
        if (!reason) {
          throw new InvalidArgumentError2("need to specify a reason the Duration is invalid");
        }
        const invalid = reason instanceof Invalid2 ? reason : new Invalid2(reason, explanation);
        if (Settings2.throwOnInvalid) {
          throw new InvalidDurationError2(invalid);
        } else {
          return new _Duration({ invalid });
        }
      }
      /**
       * @private
       */
      static normalizeUnit(unit) {
        const normalized = {
          year: "years",
          years: "years",
          quarter: "quarters",
          quarters: "quarters",
          month: "months",
          months: "months",
          week: "weeks",
          weeks: "weeks",
          day: "days",
          days: "days",
          hour: "hours",
          hours: "hours",
          minute: "minutes",
          minutes: "minutes",
          second: "seconds",
          seconds: "seconds",
          millisecond: "milliseconds",
          milliseconds: "milliseconds"
        }[unit ? unit.toLowerCase() : unit];
        if (!normalized) throw new InvalidUnitError2(unit);
        return normalized;
      }
      /**
       * Check if an object is a Duration. Works across context boundaries
       * @param {object} o
       * @return {boolean}
       */
      static isDuration(o) {
        return o && o.isLuxonDuration || false;
      }
      /**
       * Get  the locale of a Duration, such 'en-GB'
       * @type {string}
       */
      get locale() {
        return this.isValid ? this.loc.locale : null;
      }
      /**
       * Get the numbering system of a Duration, such 'beng'. The numbering system is used when formatting the Duration
       *
       * @type {string}
       */
      get numberingSystem() {
        return this.isValid ? this.loc.numberingSystem : null;
      }
      /**
       * Returns a string representation of this Duration formatted according to the specified format string. You may use these tokens:
       * * `S` for milliseconds
       * * `s` for seconds
       * * `m` for minutes
       * * `h` for hours
       * * `d` for days
       * * `w` for weeks
       * * `M` for months
       * * `y` for years
       * Notes:
       * * Add padding by repeating the token, e.g. "yy" pads the years to two digits, "hhhh" pads the hours out to four digits
       * * Tokens can be escaped by wrapping with single quotes.
       * * The duration will be converted to the set of units in the format string using {@link Duration#shiftTo} and the Durations's conversion accuracy setting.
       * @param {string} fmt - the format string
       * @param {Object} opts - options
       * @param {boolean} [opts.floor=true] - floor numerical values
       * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("y d s") //=> "1 6 2"
       * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("yy dd sss") //=> "01 06 002"
       * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("M S") //=> "12 518402000"
       * @return {string}
       */
      toFormat(fmt, opts = {}) {
        const fmtOpts = {
          ...opts,
          floor: opts.round !== false && opts.floor !== false
        };
        return this.isValid ? Formatter2.create(this.loc, fmtOpts).formatDurationFromString(this, fmt) : INVALID$2;
      }
      /**
       * Returns a string representation of a Duration with all units included.
       * To modify its behavior use the `listStyle` and any Intl.NumberFormat option, though `unitDisplay` is especially relevant.
       * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat
       * @param opts - On option object to override the formatting. Accepts the same keys as the options parameter of the native `Int.NumberFormat` constructor, as well as `listStyle`.
       * @example
       * ```js
       * var dur = Duration.fromObject({ days: 1, hours: 5, minutes: 6 })
       * dur.toHuman() //=> '1 day, 5 hours, 6 minutes'
       * dur.toHuman({ listStyle: "long" }) //=> '1 day, 5 hours, and 6 minutes'
       * dur.toHuman({ unitDisplay: "short" }) //=> '1 day, 5 hr, 6 min'
       * ```
       */
      toHuman(opts = {}) {
        if (!this.isValid) return INVALID$2;
        const l3 = orderedUnits$1.map((unit) => {
          const val = this.values[unit];
          if (isUndefined2(val)) {
            return null;
          }
          return this.loc.numberFormatter({ style: "unit", unitDisplay: "long", ...opts, unit: unit.slice(0, -1) }).format(val);
        }).filter((n3) => n3);
        return this.loc.listFormatter({ type: "conjunction", style: opts.listStyle || "narrow", ...opts }).format(l3);
      }
      /**
       * Returns a JavaScript object with this Duration's values.
       * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toObject() //=> { years: 1, days: 6, seconds: 2 }
       * @return {Object}
       */
      toObject() {
        if (!this.isValid) return {};
        return { ...this.values };
      }
      /**
       * Returns an ISO 8601-compliant string representation of this Duration.
       * @see https://en.wikipedia.org/wiki/ISO_8601#Durations
       * @example Duration.fromObject({ years: 3, seconds: 45 }).toISO() //=> 'P3YT45S'
       * @example Duration.fromObject({ months: 4, seconds: 45 }).toISO() //=> 'P4MT45S'
       * @example Duration.fromObject({ months: 5 }).toISO() //=> 'P5M'
       * @example Duration.fromObject({ minutes: 5 }).toISO() //=> 'PT5M'
       * @example Duration.fromObject({ milliseconds: 6 }).toISO() //=> 'PT0.006S'
       * @return {string}
       */
      toISO() {
        if (!this.isValid) return null;
        let s3 = "P";
        if (this.years !== 0) s3 += this.years + "Y";
        if (this.months !== 0 || this.quarters !== 0) s3 += this.months + this.quarters * 3 + "M";
        if (this.weeks !== 0) s3 += this.weeks + "W";
        if (this.days !== 0) s3 += this.days + "D";
        if (this.hours !== 0 || this.minutes !== 0 || this.seconds !== 0 || this.milliseconds !== 0)
          s3 += "T";
        if (this.hours !== 0) s3 += this.hours + "H";
        if (this.minutes !== 0) s3 += this.minutes + "M";
        if (this.seconds !== 0 || this.milliseconds !== 0)
          s3 += roundTo2(this.seconds + this.milliseconds / 1e3, 3) + "S";
        if (s3 === "P") s3 += "T0S";
        return s3;
      }
      /**
       * Returns an ISO 8601-compliant string representation of this Duration, formatted as a time of day.
       * Note that this will return null if the duration is invalid, negative, or equal to or greater than 24 hours.
       * @see https://en.wikipedia.org/wiki/ISO_8601#Times
       * @param {Object} opts - options
       * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0
       * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0
       * @param {boolean} [opts.includePrefix=false] - include the `T` prefix
       * @param {string} [opts.format='extended'] - choose between the basic and extended format
       * @example Duration.fromObject({ hours: 11 }).toISOTime() //=> '11:00:00.000'
       * @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressMilliseconds: true }) //=> '11:00:00'
       * @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressSeconds: true }) //=> '11:00'
       * @example Duration.fromObject({ hours: 11 }).toISOTime({ includePrefix: true }) //=> 'T11:00:00.000'
       * @example Duration.fromObject({ hours: 11 }).toISOTime({ format: 'basic' }) //=> '110000.000'
       * @return {string}
       */
      toISOTime(opts = {}) {
        if (!this.isValid) return null;
        const millis = this.toMillis();
        if (millis < 0 || millis >= 864e5) return null;
        opts = {
          suppressMilliseconds: false,
          suppressSeconds: false,
          includePrefix: false,
          format: "extended",
          ...opts,
          includeOffset: false
        };
        const dateTime = DateTime2.fromMillis(millis, { zone: "UTC" });
        return dateTime.toISOTime(opts);
      }
      /**
       * Returns an ISO 8601 representation of this Duration appropriate for use in JSON.
       * @return {string}
       */
      toJSON() {
        return this.toISO();
      }
      /**
       * Returns an ISO 8601 representation of this Duration appropriate for use in debugging.
       * @return {string}
       */
      toString() {
        return this.toISO();
      }
      /**
       * Returns an milliseconds value of this Duration.
       * @return {number}
       */
      toMillis() {
        if (!this.isValid) return NaN;
        return durationToMillis2(this.matrix, this.values);
      }
      /**
       * Returns an milliseconds value of this Duration. Alias of {@link toMillis}
       * @return {number}
       */
      valueOf() {
        return this.toMillis();
      }
      /**
       * Make this Duration longer by the specified amount. Return a newly-constructed Duration.
       * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
       * @return {Duration}
       */
      plus(duration) {
        if (!this.isValid) return this;
        const dur = _Duration.fromDurationLike(duration), result = {};
        for (const k of orderedUnits$1) {
          if (hasOwnProperty2(dur.values, k) || hasOwnProperty2(this.values, k)) {
            result[k] = dur.get(k) + this.get(k);
          }
        }
        return clone$1(this, { values: result }, true);
      }
      /**
       * Make this Duration shorter by the specified amount. Return a newly-constructed Duration.
       * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
       * @return {Duration}
       */
      minus(duration) {
        if (!this.isValid) return this;
        const dur = _Duration.fromDurationLike(duration);
        return this.plus(dur.negate());
      }
      /**
       * Scale this Duration by the specified amount. Return a newly-constructed Duration.
       * @param {function} fn - The function to apply to each unit. Arity is 1 or 2: the value of the unit and, optionally, the unit name. Must return a number.
       * @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnits(x => x * 2) //=> { hours: 2, minutes: 60 }
       * @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnits((x, u) => u === "hours" ? x * 2 : x) //=> { hours: 2, minutes: 30 }
       * @return {Duration}
       */
      mapUnits(fn) {
        if (!this.isValid) return this;
        const result = {};
        for (const k of Object.keys(this.values)) {
          result[k] = asNumber2(fn(this.values[k], k));
        }
        return clone$1(this, { values: result }, true);
      }
      /**
       * Get the value of unit.
       * @param {string} unit - a unit such as 'minute' or 'day'
       * @example Duration.fromObject({years: 2, days: 3}).get('years') //=> 2
       * @example Duration.fromObject({years: 2, days: 3}).get('months') //=> 0
       * @example Duration.fromObject({years: 2, days: 3}).get('days') //=> 3
       * @return {number}
       */
      get(unit) {
        return this[_Duration.normalizeUnit(unit)];
      }
      /**
       * "Set" the values of specified units. Return a newly-constructed Duration.
       * @param {Object} values - a mapping of units to numbers
       * @example dur.set({ years: 2017 })
       * @example dur.set({ hours: 8, minutes: 30 })
       * @return {Duration}
       */
      set(values) {
        if (!this.isValid) return this;
        const mixed = { ...this.values, ...normalizeObject2(values, _Duration.normalizeUnit) };
        return clone$1(this, { values: mixed });
      }
      /**
       * "Set" the locale and/or numberingSystem.  Returns a newly-constructed Duration.
       * @example dur.reconfigure({ locale: 'en-GB' })
       * @return {Duration}
       */
      reconfigure({ locale, numberingSystem, conversionAccuracy, matrix } = {}) {
        const loc = this.loc.clone({ locale, numberingSystem });
        const opts = { loc, matrix, conversionAccuracy };
        return clone$1(this, opts);
      }
      /**
       * Return the length of the duration in the specified unit.
       * @param {string} unit - a unit such as 'minutes' or 'days'
       * @example Duration.fromObject({years: 1}).as('days') //=> 365
       * @example Duration.fromObject({years: 1}).as('months') //=> 12
       * @example Duration.fromObject({hours: 60}).as('days') //=> 2.5
       * @return {number}
       */
      as(unit) {
        return this.isValid ? this.shiftTo(unit).get(unit) : NaN;
      }
      /**
       * Reduce this Duration to its canonical representation in its current units.
       * Assuming the overall value of the Duration is positive, this means:
       * - excessive values for lower-order units are converted to higher-order units (if possible, see first and second example)
       * - negative lower-order units are converted to higher order units (there must be such a higher order unit, otherwise
       *   the overall value would be negative, see second example)
       * - fractional values for higher-order units are converted to lower-order units (if possible, see fourth example)
       *
       * If the overall value is negative, the result of this method is equivalent to `this.negate().normalize().negate()`.
       * @example Duration.fromObject({ years: 2, days: 5000 }).normalize().toObject() //=> { years: 15, days: 255 }
       * @example Duration.fromObject({ days: 5000 }).normalize().toObject() //=> { days: 5000 }
       * @example Duration.fromObject({ hours: 12, minutes: -45 }).normalize().toObject() //=> { hours: 11, minutes: 15 }
       * @example Duration.fromObject({ years: 2.5, days: 0, hours: 0 }).normalize().toObject() //=> { years: 2, days: 182, hours: 12 }
       * @return {Duration}
       */
      normalize() {
        if (!this.isValid) return this;
        const vals = this.toObject();
        normalizeValues2(this.matrix, vals);
        return clone$1(this, { values: vals }, true);
      }
      /**
       * Rescale units to its largest representation
       * @example Duration.fromObject({ milliseconds: 90000 }).rescale().toObject() //=> { minutes: 1, seconds: 30 }
       * @return {Duration}
       */
      rescale() {
        if (!this.isValid) return this;
        const vals = removeZeroes2(this.normalize().shiftToAll().toObject());
        return clone$1(this, { values: vals }, true);
      }
      /**
       * Convert this Duration into its representation in a different set of units.
       * @example Duration.fromObject({ hours: 1, seconds: 30 }).shiftTo('minutes', 'milliseconds').toObject() //=> { minutes: 60, milliseconds: 30000 }
       * @return {Duration}
       */
      shiftTo(...units) {
        if (!this.isValid) return this;
        if (units.length === 0) {
          return this;
        }
        units = units.map((u) => _Duration.normalizeUnit(u));
        const built = {}, accumulated = {}, vals = this.toObject();
        let lastUnit;
        for (const k of orderedUnits$1) {
          if (units.indexOf(k) >= 0) {
            lastUnit = k;
            let own = 0;
            for (const ak in accumulated) {
              own += this.matrix[ak][k] * accumulated[ak];
              accumulated[ak] = 0;
            }
            if (isNumber2(vals[k])) {
              own += vals[k];
            }
            const i = Math.trunc(own);
            built[k] = i;
            accumulated[k] = (own * 1e3 - i * 1e3) / 1e3;
          } else if (isNumber2(vals[k])) {
            accumulated[k] = vals[k];
          }
        }
        for (const key in accumulated) {
          if (accumulated[key] !== 0) {
            built[lastUnit] += key === lastUnit ? accumulated[key] : accumulated[key] / this.matrix[lastUnit][key];
          }
        }
        normalizeValues2(this.matrix, built);
        return clone$1(this, { values: built }, true);
      }
      /**
       * Shift this Duration to all available units.
       * Same as shiftTo("years", "months", "weeks", "days", "hours", "minutes", "seconds", "milliseconds")
       * @return {Duration}
       */
      shiftToAll() {
        if (!this.isValid) return this;
        return this.shiftTo(
          "years",
          "months",
          "weeks",
          "days",
          "hours",
          "minutes",
          "seconds",
          "milliseconds"
        );
      }
      /**
       * Return the negative of this Duration.
       * @example Duration.fromObject({ hours: 1, seconds: 30 }).negate().toObject() //=> { hours: -1, seconds: -30 }
       * @return {Duration}
       */
      negate() {
        if (!this.isValid) return this;
        const negated = {};
        for (const k of Object.keys(this.values)) {
          negated[k] = this.values[k] === 0 ? 0 : -this.values[k];
        }
        return clone$1(this, { values: negated }, true);
      }
      /**
       * Get the years.
       * @type {number}
       */
      get years() {
        return this.isValid ? this.values.years || 0 : NaN;
      }
      /**
       * Get the quarters.
       * @type {number}
       */
      get quarters() {
        return this.isValid ? this.values.quarters || 0 : NaN;
      }
      /**
       * Get the months.
       * @type {number}
       */
      get months() {
        return this.isValid ? this.values.months || 0 : NaN;
      }
      /**
       * Get the weeks
       * @type {number}
       */
      get weeks() {
        return this.isValid ? this.values.weeks || 0 : NaN;
      }
      /**
       * Get the days.
       * @type {number}
       */
      get days() {
        return this.isValid ? this.values.days || 0 : NaN;
      }
      /**
       * Get the hours.
       * @type {number}
       */
      get hours() {
        return this.isValid ? this.values.hours || 0 : NaN;
      }
      /**
       * Get the minutes.
       * @type {number}
       */
      get minutes() {
        return this.isValid ? this.values.minutes || 0 : NaN;
      }
      /**
       * Get the seconds.
       * @return {number}
       */
      get seconds() {
        return this.isValid ? this.values.seconds || 0 : NaN;
      }
      /**
       * Get the milliseconds.
       * @return {number}
       */
      get milliseconds() {
        return this.isValid ? this.values.milliseconds || 0 : NaN;
      }
      /**
       * Returns whether the Duration is invalid. Invalid durations are returned by diff operations
       * on invalid DateTimes or Intervals.
       * @return {boolean}
       */
      get isValid() {
        return this.invalid === null;
      }
      /**
       * Returns an error code if this Duration became invalid, or null if the Duration is valid
       * @return {string}
       */
      get invalidReason() {
        return this.invalid ? this.invalid.reason : null;
      }
      /**
       * Returns an explanation of why this Duration became invalid, or null if the Duration is valid
       * @type {string}
       */
      get invalidExplanation() {
        return this.invalid ? this.invalid.explanation : null;
      }
      /**
       * Equality check
       * Two Durations are equal iff they have the same units and the same values for each unit.
       * @param {Duration} other
       * @return {boolean}
       */
      equals(other) {
        if (!this.isValid || !other.isValid) {
          return false;
        }
        if (!this.loc.equals(other.loc)) {
          return false;
        }
        function eq(v1, v2) {
          if (v1 === void 0 || v1 === 0) return v2 === void 0 || v2 === 0;
          return v1 === v2;
        }
        for (const u of orderedUnits$1) {
          if (!eq(this.values[u], other.values[u])) {
            return false;
          }
        }
        return true;
      }
    };
    var INVALID$1 = "Invalid Interval";
    function validateStartEnd2(start, end) {
      if (!start || !start.isValid) {
        return Interval2.invalid("missing or invalid start");
      } else if (!end || !end.isValid) {
        return Interval2.invalid("missing or invalid end");
      } else if (end < start) {
        return Interval2.invalid(
          "end before start",
          `The end of an interval must be after its start, but you had start=${start.toISO()} and end=${end.toISO()}`
        );
      } else {
        return null;
      }
    }
    var Interval2 = class _Interval {
      /**
       * @private
       */
      constructor(config) {
        this.s = config.start;
        this.e = config.end;
        this.invalid = config.invalid || null;
        this.isLuxonInterval = true;
      }
      /**
       * Create an invalid Interval.
       * @param {string} reason - simple string of why this Interval is invalid. Should not contain parameters or anything else data-dependent
       * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information
       * @return {Interval}
       */
      static invalid(reason, explanation = null) {
        if (!reason) {
          throw new InvalidArgumentError2("need to specify a reason the Interval is invalid");
        }
        const invalid = reason instanceof Invalid2 ? reason : new Invalid2(reason, explanation);
        if (Settings2.throwOnInvalid) {
          throw new InvalidIntervalError2(invalid);
        } else {
          return new _Interval({ invalid });
        }
      }
      /**
       * Create an Interval from a start DateTime and an end DateTime. Inclusive of the start but not the end.
       * @param {DateTime|Date|Object} start
       * @param {DateTime|Date|Object} end
       * @return {Interval}
       */
      static fromDateTimes(start, end) {
        const builtStart = friendlyDateTime2(start), builtEnd = friendlyDateTime2(end);
        const validateError = validateStartEnd2(builtStart, builtEnd);
        if (validateError == null) {
          return new _Interval({
            start: builtStart,
            end: builtEnd
          });
        } else {
          return validateError;
        }
      }
      /**
       * Create an Interval from a start DateTime and a Duration to extend to.
       * @param {DateTime|Date|Object} start
       * @param {Duration|Object|number} duration - the length of the Interval.
       * @return {Interval}
       */
      static after(start, duration) {
        const dur = Duration2.fromDurationLike(duration), dt = friendlyDateTime2(start);
        return _Interval.fromDateTimes(dt, dt.plus(dur));
      }
      /**
       * Create an Interval from an end DateTime and a Duration to extend backwards to.
       * @param {DateTime|Date|Object} end
       * @param {Duration|Object|number} duration - the length of the Interval.
       * @return {Interval}
       */
      static before(end, duration) {
        const dur = Duration2.fromDurationLike(duration), dt = friendlyDateTime2(end);
        return _Interval.fromDateTimes(dt.minus(dur), dt);
      }
      /**
       * Create an Interval from an ISO 8601 string.
       * Accepts `<start>/<end>`, `<start>/<duration>`, and `<duration>/<end>` formats.
       * @param {string} text - the ISO string to parse
       * @param {Object} [opts] - options to pass {@link DateTime#fromISO} and optionally {@link Duration#fromISO}
       * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals
       * @return {Interval}
       */
      static fromISO(text2, opts) {
        const [s3, e] = (text2 || "").split("/", 2);
        if (s3 && e) {
          let start, startIsValid;
          try {
            start = DateTime2.fromISO(s3, opts);
            startIsValid = start.isValid;
          } catch (e2) {
            startIsValid = false;
          }
          let end, endIsValid;
          try {
            end = DateTime2.fromISO(e, opts);
            endIsValid = end.isValid;
          } catch (e2) {
            endIsValid = false;
          }
          if (startIsValid && endIsValid) {
            return _Interval.fromDateTimes(start, end);
          }
          if (startIsValid) {
            const dur = Duration2.fromISO(e, opts);
            if (dur.isValid) {
              return _Interval.after(start, dur);
            }
          } else if (endIsValid) {
            const dur = Duration2.fromISO(s3, opts);
            if (dur.isValid) {
              return _Interval.before(end, dur);
            }
          }
        }
        return _Interval.invalid("unparsable", `the input "${text2}" can't be parsed as ISO 8601`);
      }
      /**
       * Check if an object is an Interval. Works across context boundaries
       * @param {object} o
       * @return {boolean}
       */
      static isInterval(o) {
        return o && o.isLuxonInterval || false;
      }
      /**
       * Returns the start of the Interval
       * @type {DateTime}
       */
      get start() {
        return this.isValid ? this.s : null;
      }
      /**
       * Returns the end of the Interval
       * @type {DateTime}
       */
      get end() {
        return this.isValid ? this.e : null;
      }
      /**
       * Returns whether this Interval's end is at least its start, meaning that the Interval isn't 'backwards'.
       * @type {boolean}
       */
      get isValid() {
        return this.invalidReason === null;
      }
      /**
       * Returns an error code if this Interval is invalid, or null if the Interval is valid
       * @type {string}
       */
      get invalidReason() {
        return this.invalid ? this.invalid.reason : null;
      }
      /**
       * Returns an explanation of why this Interval became invalid, or null if the Interval is valid
       * @type {string}
       */
      get invalidExplanation() {
        return this.invalid ? this.invalid.explanation : null;
      }
      /**
       * Returns the length of the Interval in the specified unit.
       * @param {string} unit - the unit (such as 'hours' or 'days') to return the length in.
       * @return {number}
       */
      length(unit = "milliseconds") {
        return this.isValid ? this.toDuration(...[unit]).get(unit) : NaN;
      }
      /**
       * Returns the count of minutes, hours, days, months, or years included in the Interval, even in part.
       * Unlike {@link Interval#length} this counts sections of the calendar, not periods of time, e.g. specifying 'day'
       * asks 'what dates are included in this interval?', not 'how many days long is this interval?'
       * @param {string} [unit='milliseconds'] - the unit of time to count.
       * @return {number}
       */
      count(unit = "milliseconds") {
        if (!this.isValid) return NaN;
        const start = this.start.startOf(unit), end = this.end.startOf(unit);
        return Math.floor(end.diff(start, unit).get(unit)) + (end.valueOf() !== this.end.valueOf());
      }
      /**
       * Returns whether this Interval's start and end are both in the same unit of time
       * @param {string} unit - the unit of time to check sameness on
       * @return {boolean}
       */
      hasSame(unit) {
        return this.isValid ? this.isEmpty() || this.e.minus(1).hasSame(this.s, unit) : false;
      }
      /**
       * Return whether this Interval has the same start and end DateTimes.
       * @return {boolean}
       */
      isEmpty() {
        return this.s.valueOf() === this.e.valueOf();
      }
      /**
       * Return whether this Interval's start is after the specified DateTime.
       * @param {DateTime} dateTime
       * @return {boolean}
       */
      isAfter(dateTime) {
        if (!this.isValid) return false;
        return this.s > dateTime;
      }
      /**
       * Return whether this Interval's end is before the specified DateTime.
       * @param {DateTime} dateTime
       * @return {boolean}
       */
      isBefore(dateTime) {
        if (!this.isValid) return false;
        return this.e <= dateTime;
      }
      /**
       * Return whether this Interval contains the specified DateTime.
       * @param {DateTime} dateTime
       * @return {boolean}
       */
      contains(dateTime) {
        if (!this.isValid) return false;
        return this.s <= dateTime && this.e > dateTime;
      }
      /**
       * "Sets" the start and/or end dates. Returns a newly-constructed Interval.
       * @param {Object} values - the values to set
       * @param {DateTime} values.start - the starting DateTime
       * @param {DateTime} values.end - the ending DateTime
       * @return {Interval}
       */
      set({ start, end } = {}) {
        if (!this.isValid) return this;
        return _Interval.fromDateTimes(start || this.s, end || this.e);
      }
      /**
       * Split this Interval at each of the specified DateTimes
       * @param {...DateTime} dateTimes - the unit of time to count.
       * @return {Array}
       */
      splitAt(...dateTimes) {
        if (!this.isValid) return [];
        const sorted = dateTimes.map(friendlyDateTime2).filter((d) => this.contains(d)).sort(), results = [];
        let { s: s3 } = this, i = 0;
        while (s3 < this.e) {
          const added = sorted[i] || this.e, next = +added > +this.e ? this.e : added;
          results.push(_Interval.fromDateTimes(s3, next));
          s3 = next;
          i += 1;
        }
        return results;
      }
      /**
       * Split this Interval into smaller Intervals, each of the specified length.
       * Left over time is grouped into a smaller interval
       * @param {Duration|Object|number} duration - The length of each resulting interval.
       * @return {Array}
       */
      splitBy(duration) {
        const dur = Duration2.fromDurationLike(duration);
        if (!this.isValid || !dur.isValid || dur.as("milliseconds") === 0) {
          return [];
        }
        let { s: s3 } = this, idx = 1, next;
        const results = [];
        while (s3 < this.e) {
          const added = this.start.plus(dur.mapUnits((x) => x * idx));
          next = +added > +this.e ? this.e : added;
          results.push(_Interval.fromDateTimes(s3, next));
          s3 = next;
          idx += 1;
        }
        return results;
      }
      /**
       * Split this Interval into the specified number of smaller intervals.
       * @param {number} numberOfParts - The number of Intervals to divide the Interval into.
       * @return {Array}
       */
      divideEqually(numberOfParts) {
        if (!this.isValid) return [];
        return this.splitBy(this.length() / numberOfParts).slice(0, numberOfParts);
      }
      /**
       * Return whether this Interval overlaps with the specified Interval
       * @param {Interval} other
       * @return {boolean}
       */
      overlaps(other) {
        return this.e > other.s && this.s < other.e;
      }
      /**
       * Return whether this Interval's end is adjacent to the specified Interval's start.
       * @param {Interval} other
       * @return {boolean}
       */
      abutsStart(other) {
        if (!this.isValid) return false;
        return +this.e === +other.s;
      }
      /**
       * Return whether this Interval's start is adjacent to the specified Interval's end.
       * @param {Interval} other
       * @return {boolean}
       */
      abutsEnd(other) {
        if (!this.isValid) return false;
        return +other.e === +this.s;
      }
      /**
       * Return whether this Interval engulfs the start and end of the specified Interval.
       * @param {Interval} other
       * @return {boolean}
       */
      engulfs(other) {
        if (!this.isValid) return false;
        return this.s <= other.s && this.e >= other.e;
      }
      /**
       * Return whether this Interval has the same start and end as the specified Interval.
       * @param {Interval} other
       * @return {boolean}
       */
      equals(other) {
        if (!this.isValid || !other.isValid) {
          return false;
        }
        return this.s.equals(other.s) && this.e.equals(other.e);
      }
      /**
       * Return an Interval representing the intersection of this Interval and the specified Interval.
       * Specifically, the resulting Interval has the maximum start time and the minimum end time of the two Intervals.
       * Returns null if the intersection is empty, meaning, the intervals don't intersect.
       * @param {Interval} other
       * @return {Interval}
       */
      intersection(other) {
        if (!this.isValid) return this;
        const s3 = this.s > other.s ? this.s : other.s, e = this.e < other.e ? this.e : other.e;
        if (s3 >= e) {
          return null;
        } else {
          return _Interval.fromDateTimes(s3, e);
        }
      }
      /**
       * Return an Interval representing the union of this Interval and the specified Interval.
       * Specifically, the resulting Interval has the minimum start time and the maximum end time of the two Intervals.
       * @param {Interval} other
       * @return {Interval}
       */
      union(other) {
        if (!this.isValid) return this;
        const s3 = this.s < other.s ? this.s : other.s, e = this.e > other.e ? this.e : other.e;
        return _Interval.fromDateTimes(s3, e);
      }
      /**
       * Merge an array of Intervals into a equivalent minimal set of Intervals.
       * Combines overlapping and adjacent Intervals.
       * @param {Array} intervals
       * @return {Array}
       */
      static merge(intervals) {
        const [found, final] = intervals.sort((a, b) => a.s - b.s).reduce(
          ([sofar, current], item) => {
            if (!current) {
              return [sofar, item];
            } else if (current.overlaps(item) || current.abutsStart(item)) {
              return [sofar, current.union(item)];
            } else {
              return [sofar.concat([current]), item];
            }
          },
          [[], null]
        );
        if (final) {
          found.push(final);
        }
        return found;
      }
      /**
       * Return an array of Intervals representing the spans of time that only appear in one of the specified Intervals.
       * @param {Array} intervals
       * @return {Array}
       */
      static xor(intervals) {
        let start = null, currentCount = 0;
        const results = [], ends = intervals.map((i) => [
          { time: i.s, type: "s" },
          { time: i.e, type: "e" }
        ]), flattened = Array.prototype.concat(...ends), arr = flattened.sort((a, b) => a.time - b.time);
        for (const i of arr) {
          currentCount += i.type === "s" ? 1 : -1;
          if (currentCount === 1) {
            start = i.time;
          } else {
            if (start && +start !== +i.time) {
              results.push(_Interval.fromDateTimes(start, i.time));
            }
            start = null;
          }
        }
        return _Interval.merge(results);
      }
      /**
       * Return an Interval representing the span of time in this Interval that doesn't overlap with any of the specified Intervals.
       * @param {...Interval} intervals
       * @return {Array}
       */
      difference(...intervals) {
        return _Interval.xor([this].concat(intervals)).map((i) => this.intersection(i)).filter((i) => i && !i.isEmpty());
      }
      /**
       * Returns a string representation of this Interval appropriate for debugging.
       * @return {string}
       */
      toString() {
        if (!this.isValid) return INVALID$1;
        return `[${this.s.toISO()} \u2013 ${this.e.toISO()})`;
      }
      /**
       * Returns a localized string representing this Interval. Accepts the same options as the
       * Intl.DateTimeFormat constructor and any presets defined by Luxon, such as
       * {@link DateTime.DATE_FULL} or {@link DateTime.TIME_SIMPLE}. The exact behavior of this method
       * is browser-specific, but in general it will return an appropriate representation of the
       * Interval in the assigned locale. Defaults to the system's locale if no locale has been
       * specified.
       * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
       * @param {Object} [formatOpts=DateTime.DATE_SHORT] - Either a DateTime preset or
       * Intl.DateTimeFormat constructor options.
       * @param {Object} opts - Options to override the configuration of the start DateTime.
       * @example Interval.fromISO('2022-11-07T09:00Z/2022-11-08T09:00Z').toLocaleString(); //=> 11/7/2022 – 11/8/2022
       * @example Interval.fromISO('2022-11-07T09:00Z/2022-11-08T09:00Z').toLocaleString(DateTime.DATE_FULL); //=> November 7 – 8, 2022
       * @example Interval.fromISO('2022-11-07T09:00Z/2022-11-08T09:00Z').toLocaleString(DateTime.DATE_FULL, { locale: 'fr-FR' }); //=> 7–8 novembre 2022
       * @example Interval.fromISO('2022-11-07T17:00Z/2022-11-07T19:00Z').toLocaleString(DateTime.TIME_SIMPLE); //=> 6:00 – 8:00 PM
       * @example Interval.fromISO('2022-11-07T17:00Z/2022-11-07T19:00Z').toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }); //=> Mon, Nov 07, 6:00 – 8:00 p
       * @return {string}
       */
      toLocaleString(formatOpts = DATE_SHORT2, opts = {}) {
        return this.isValid ? Formatter2.create(this.s.loc.clone(opts), formatOpts).formatInterval(this) : INVALID$1;
      }
      /**
       * Returns an ISO 8601-compliant string representation of this Interval.
       * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals
       * @param {Object} opts - The same options as {@link DateTime#toISO}
       * @return {string}
       */
      toISO(opts) {
        if (!this.isValid) return INVALID$1;
        return `${this.s.toISO(opts)}/${this.e.toISO(opts)}`;
      }
      /**
       * Returns an ISO 8601-compliant string representation of date of this Interval.
       * The time components are ignored.
       * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals
       * @return {string}
       */
      toISODate() {
        if (!this.isValid) return INVALID$1;
        return `${this.s.toISODate()}/${this.e.toISODate()}`;
      }
      /**
       * Returns an ISO 8601-compliant string representation of time of this Interval.
       * The date components are ignored.
       * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals
       * @param {Object} opts - The same options as {@link DateTime#toISO}
       * @return {string}
       */
      toISOTime(opts) {
        if (!this.isValid) return INVALID$1;
        return `${this.s.toISOTime(opts)}/${this.e.toISOTime(opts)}`;
      }
      /**
       * Returns a string representation of this Interval formatted according to the specified format
       * string. **You may not want this.** See {@link Interval#toLocaleString} for a more flexible
       * formatting tool.
       * @param {string} dateFormat - The format string. This string formats the start and end time.
       * See {@link DateTime#toFormat} for details.
       * @param {Object} opts - Options.
       * @param {string} [opts.separator =  ' – '] - A separator to place between the start and end
       * representations.
       * @return {string}
       */
      toFormat(dateFormat, { separator = " \u2013 " } = {}) {
        if (!this.isValid) return INVALID$1;
        return `${this.s.toFormat(dateFormat)}${separator}${this.e.toFormat(dateFormat)}`;
      }
      /**
       * Return a Duration representing the time spanned by this interval.
       * @param {string|string[]} [unit=['milliseconds']] - the unit or units (such as 'hours' or 'days') to include in the duration.
       * @param {Object} opts - options that affect the creation of the Duration
       * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
       * @example Interval.fromDateTimes(dt1, dt2).toDuration().toObject() //=> { milliseconds: 88489257 }
       * @example Interval.fromDateTimes(dt1, dt2).toDuration('days').toObject() //=> { days: 1.0241812152777778 }
       * @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes']).toObject() //=> { hours: 24, minutes: 34.82095 }
       * @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes', 'seconds']).toObject() //=> { hours: 24, minutes: 34, seconds: 49.257 }
       * @example Interval.fromDateTimes(dt1, dt2).toDuration('seconds').toObject() //=> { seconds: 88489.257 }
       * @return {Duration}
       */
      toDuration(unit, opts) {
        if (!this.isValid) {
          return Duration2.invalid(this.invalidReason);
        }
        return this.e.diff(this.s, unit, opts);
      }
      /**
       * Run mapFn on the interval start and end, returning a new Interval from the resulting DateTimes
       * @param {function} mapFn
       * @return {Interval}
       * @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.toUTC())
       * @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.plus({ hours: 2 }))
       */
      mapEndpoints(mapFn) {
        return _Interval.fromDateTimes(mapFn(this.s), mapFn(this.e));
      }
    };
    var Info2 = class {
      /**
       * Return whether the specified zone contains a DST.
       * @param {string|Zone} [zone='local'] - Zone to check. Defaults to the environment's local zone.
       * @return {boolean}
       */
      static hasDST(zone = Settings2.defaultZone) {
        const proto = DateTime2.now().setZone(zone).set({ month: 12 });
        return !zone.isUniversal && proto.offset !== proto.set({ month: 6 }).offset;
      }
      /**
       * Return whether the specified zone is a valid IANA specifier.
       * @param {string} zone - Zone to check
       * @return {boolean}
       */
      static isValidIANAZone(zone) {
        return IANAZone2.isValidZone(zone);
      }
      /**
       * Converts the input into a {@link Zone} instance.
       *
       * * If `input` is already a Zone instance, it is returned unchanged.
       * * If `input` is a string containing a valid time zone name, a Zone instance
       *   with that name is returned.
       * * If `input` is a string that doesn't refer to a known time zone, a Zone
       *   instance with {@link Zone#isValid} == false is returned.
       * * If `input is a number, a Zone instance with the specified fixed offset
       *   in minutes is returned.
       * * If `input` is `null` or `undefined`, the default zone is returned.
       * @param {string|Zone|number} [input] - the value to be converted
       * @return {Zone}
       */
      static normalizeZone(input) {
        return normalizeZone2(input, Settings2.defaultZone);
      }
      /**
       * Return an array of standalone month names.
       * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
       * @param {string} [length='long'] - the length of the month representation, such as "numeric", "2-digit", "narrow", "short", "long"
       * @param {Object} opts - options
       * @param {string} [opts.locale] - the locale code
       * @param {string} [opts.numberingSystem=null] - the numbering system
       * @param {string} [opts.locObj=null] - an existing locale object to use
       * @param {string} [opts.outputCalendar='gregory'] - the calendar
       * @example Info.months()[0] //=> 'January'
       * @example Info.months('short')[0] //=> 'Jan'
       * @example Info.months('numeric')[0] //=> '1'
       * @example Info.months('short', { locale: 'fr-CA' } )[0] //=> 'janv.'
       * @example Info.months('numeric', { locale: 'ar' })[0] //=> '١'
       * @example Info.months('long', { outputCalendar: 'islamic' })[0] //=> 'Rabiʻ I'
       * @return {Array}
       */
      static months(length = "long", { locale = null, numberingSystem = null, locObj = null, outputCalendar = "gregory" } = {}) {
        return (locObj || Locale2.create(locale, numberingSystem, outputCalendar)).months(length);
      }
      /**
       * Return an array of format month names.
       * Format months differ from standalone months in that they're meant to appear next to the day of the month. In some languages, that
       * changes the string.
       * See {@link Info#months}
       * @param {string} [length='long'] - the length of the month representation, such as "numeric", "2-digit", "narrow", "short", "long"
       * @param {Object} opts - options
       * @param {string} [opts.locale] - the locale code
       * @param {string} [opts.numberingSystem=null] - the numbering system
       * @param {string} [opts.locObj=null] - an existing locale object to use
       * @param {string} [opts.outputCalendar='gregory'] - the calendar
       * @return {Array}
       */
      static monthsFormat(length = "long", { locale = null, numberingSystem = null, locObj = null, outputCalendar = "gregory" } = {}) {
        return (locObj || Locale2.create(locale, numberingSystem, outputCalendar)).months(length, true);
      }
      /**
       * Return an array of standalone week names.
       * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
       * @param {string} [length='long'] - the length of the weekday representation, such as "narrow", "short", "long".
       * @param {Object} opts - options
       * @param {string} [opts.locale] - the locale code
       * @param {string} [opts.numberingSystem=null] - the numbering system
       * @param {string} [opts.locObj=null] - an existing locale object to use
       * @example Info.weekdays()[0] //=> 'Monday'
       * @example Info.weekdays('short')[0] //=> 'Mon'
       * @example Info.weekdays('short', { locale: 'fr-CA' })[0] //=> 'lun.'
       * @example Info.weekdays('short', { locale: 'ar' })[0] //=> 'الاثنين'
       * @return {Array}
       */
      static weekdays(length = "long", { locale = null, numberingSystem = null, locObj = null } = {}) {
        return (locObj || Locale2.create(locale, numberingSystem, null)).weekdays(length);
      }
      /**
       * Return an array of format week names.
       * Format weekdays differ from standalone weekdays in that they're meant to appear next to more date information. In some languages, that
       * changes the string.
       * See {@link Info#weekdays}
       * @param {string} [length='long'] - the length of the month representation, such as "narrow", "short", "long".
       * @param {Object} opts - options
       * @param {string} [opts.locale=null] - the locale code
       * @param {string} [opts.numberingSystem=null] - the numbering system
       * @param {string} [opts.locObj=null] - an existing locale object to use
       * @return {Array}
       */
      static weekdaysFormat(length = "long", { locale = null, numberingSystem = null, locObj = null } = {}) {
        return (locObj || Locale2.create(locale, numberingSystem, null)).weekdays(length, true);
      }
      /**
       * Return an array of meridiems.
       * @param {Object} opts - options
       * @param {string} [opts.locale] - the locale code
       * @example Info.meridiems() //=> [ 'AM', 'PM' ]
       * @example Info.meridiems({ locale: 'my' }) //=> [ 'နံနက်', 'ညနေ' ]
       * @return {Array}
       */
      static meridiems({ locale = null } = {}) {
        return Locale2.create(locale).meridiems();
      }
      /**
       * Return an array of eras, such as ['BC', 'AD']. The locale can be specified, but the calendar system is always Gregorian.
       * @param {string} [length='short'] - the length of the era representation, such as "short" or "long".
       * @param {Object} opts - options
       * @param {string} [opts.locale] - the locale code
       * @example Info.eras() //=> [ 'BC', 'AD' ]
       * @example Info.eras('long') //=> [ 'Before Christ', 'Anno Domini' ]
       * @example Info.eras('long', { locale: 'fr' }) //=> [ 'avant Jésus-Christ', 'après Jésus-Christ' ]
       * @return {Array}
       */
      static eras(length = "short", { locale = null } = {}) {
        return Locale2.create(locale, null, "gregory").eras(length);
      }
      /**
       * Return the set of available features in this environment.
       * Some features of Luxon are not available in all environments. For example, on older browsers, relative time formatting support is not available. Use this function to figure out if that's the case.
       * Keys:
       * * `relative`: whether this environment supports relative time formatting
       * @example Info.features() //=> { relative: false }
       * @return {Object}
       */
      static features() {
        return { relative: hasRelative2() };
      }
    };
    function dayDiff2(earlier, later) {
      const utcDayStart = (dt) => dt.toUTC(0, { keepLocalTime: true }).startOf("day").valueOf(), ms = utcDayStart(later) - utcDayStart(earlier);
      return Math.floor(Duration2.fromMillis(ms).as("days"));
    }
    function highOrderDiffs2(cursor, later, units) {
      const differs = [
        ["years", (a, b) => b.year - a.year],
        ["quarters", (a, b) => b.quarter - a.quarter + (b.year - a.year) * 4],
        ["months", (a, b) => b.month - a.month + (b.year - a.year) * 12],
        [
          "weeks",
          (a, b) => {
            const days = dayDiff2(a, b);
            return (days - days % 7) / 7;
          }
        ],
        ["days", dayDiff2]
      ];
      const results = {};
      const earlier = cursor;
      let lowestOrder, highWater;
      for (const [unit, differ] of differs) {
        if (units.indexOf(unit) >= 0) {
          lowestOrder = unit;
          results[unit] = differ(cursor, later);
          highWater = earlier.plus(results);
          if (highWater > later) {
            results[unit]--;
            cursor = earlier.plus(results);
            if (cursor > later) {
              highWater = cursor;
              results[unit]--;
              cursor = earlier.plus(results);
            }
          } else {
            cursor = highWater;
          }
        }
      }
      return [cursor, results, highWater, lowestOrder];
    }
    function diff(earlier, later, units, opts) {
      let [cursor, results, highWater, lowestOrder] = highOrderDiffs2(earlier, later, units);
      const remainingMillis = later - cursor;
      const lowerOrderUnits = units.filter(
        (u) => ["hours", "minutes", "seconds", "milliseconds"].indexOf(u) >= 0
      );
      if (lowerOrderUnits.length === 0) {
        if (highWater < later) {
          highWater = cursor.plus({ [lowestOrder]: 1 });
        }
        if (highWater !== cursor) {
          results[lowestOrder] = (results[lowestOrder] || 0) + remainingMillis / (highWater - cursor);
        }
      }
      const duration = Duration2.fromObject(results, opts);
      if (lowerOrderUnits.length > 0) {
        return Duration2.fromMillis(remainingMillis, opts).shiftTo(...lowerOrderUnits).plus(duration);
      } else {
        return duration;
      }
    }
    var numberingSystems2 = {
      arab: "[\u0660-\u0669]",
      arabext: "[\u06F0-\u06F9]",
      bali: "[\u1B50-\u1B59]",
      beng: "[\u09E6-\u09EF]",
      deva: "[\u0966-\u096F]",
      fullwide: "[\uFF10-\uFF19]",
      gujr: "[\u0AE6-\u0AEF]",
      hanidec: "[\u3007|\u4E00|\u4E8C|\u4E09|\u56DB|\u4E94|\u516D|\u4E03|\u516B|\u4E5D]",
      khmr: "[\u17E0-\u17E9]",
      knda: "[\u0CE6-\u0CEF]",
      laoo: "[\u0ED0-\u0ED9]",
      limb: "[\u1946-\u194F]",
      mlym: "[\u0D66-\u0D6F]",
      mong: "[\u1810-\u1819]",
      mymr: "[\u1040-\u1049]",
      orya: "[\u0B66-\u0B6F]",
      tamldec: "[\u0BE6-\u0BEF]",
      telu: "[\u0C66-\u0C6F]",
      thai: "[\u0E50-\u0E59]",
      tibt: "[\u0F20-\u0F29]",
      latn: "\\d"
    };
    var numberingSystemsUTF162 = {
      arab: [1632, 1641],
      arabext: [1776, 1785],
      bali: [6992, 7001],
      beng: [2534, 2543],
      deva: [2406, 2415],
      fullwide: [65296, 65303],
      gujr: [2790, 2799],
      khmr: [6112, 6121],
      knda: [3302, 3311],
      laoo: [3792, 3801],
      limb: [6470, 6479],
      mlym: [3430, 3439],
      mong: [6160, 6169],
      mymr: [4160, 4169],
      orya: [2918, 2927],
      tamldec: [3046, 3055],
      telu: [3174, 3183],
      thai: [3664, 3673],
      tibt: [3872, 3881]
    };
    var hanidecChars2 = numberingSystems2.hanidec.replace(/[\[|\]]/g, "").split("");
    function parseDigits2(str) {
      let value = parseInt(str, 10);
      if (isNaN(value)) {
        value = "";
        for (let i = 0; i < str.length; i++) {
          const code = str.charCodeAt(i);
          if (str[i].search(numberingSystems2.hanidec) !== -1) {
            value += hanidecChars2.indexOf(str[i]);
          } else {
            for (const key in numberingSystemsUTF162) {
              const [min, max] = numberingSystemsUTF162[key];
              if (code >= min && code <= max) {
                value += code - min;
              }
            }
          }
        }
        return parseInt(value, 10);
      } else {
        return value;
      }
    }
    function digitRegex2({ numberingSystem }, append2 = "") {
      return new RegExp(`${numberingSystems2[numberingSystem || "latn"]}${append2}`);
    }
    var MISSING_FTP2 = "missing Intl.DateTimeFormat.formatToParts support";
    function intUnit2(regex, post = (i) => i) {
      return { regex, deser: ([s3]) => post(parseDigits2(s3)) };
    }
    var NBSP2 = String.fromCharCode(160);
    var spaceOrNBSP2 = `[ ${NBSP2}]`;
    var spaceOrNBSPRegExp2 = new RegExp(spaceOrNBSP2, "g");
    function fixListRegex2(s3) {
      return s3.replace(/\./g, "\\.?").replace(spaceOrNBSPRegExp2, spaceOrNBSP2);
    }
    function stripInsensitivities2(s3) {
      return s3.replace(/\./g, "").replace(spaceOrNBSPRegExp2, " ").toLowerCase();
    }
    function oneOf2(strings, startIndex) {
      if (strings === null) {
        return null;
      } else {
        return {
          regex: RegExp(strings.map(fixListRegex2).join("|")),
          deser: ([s3]) => strings.findIndex((i) => stripInsensitivities2(s3) === stripInsensitivities2(i)) + startIndex
        };
      }
    }
    function offset2(regex, groups) {
      return { regex, deser: ([, h, m]) => signedOffset2(h, m), groups };
    }
    function simple2(regex) {
      return { regex, deser: ([s3]) => s3 };
    }
    function escapeToken2(value) {
      return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
    }
    function unitForToken2(token, loc) {
      const one = digitRegex2(loc), two = digitRegex2(loc, "{2}"), three = digitRegex2(loc, "{3}"), four = digitRegex2(loc, "{4}"), six = digitRegex2(loc, "{6}"), oneOrTwo = digitRegex2(loc, "{1,2}"), oneToThree = digitRegex2(loc, "{1,3}"), oneToSix = digitRegex2(loc, "{1,6}"), oneToNine = digitRegex2(loc, "{1,9}"), twoToFour = digitRegex2(loc, "{2,4}"), fourToSix = digitRegex2(loc, "{4,6}"), literal = (t) => ({ regex: RegExp(escapeToken2(t.val)), deser: ([s3]) => s3, literal: true }), unitate = (t) => {
        if (token.literal) {
          return literal(t);
        }
        switch (t.val) {
          // era
          case "G":
            return oneOf2(loc.eras("short"), 0);
          case "GG":
            return oneOf2(loc.eras("long"), 0);
          // years
          case "y":
            return intUnit2(oneToSix);
          case "yy":
            return intUnit2(twoToFour, untruncateYear2);
          case "yyyy":
            return intUnit2(four);
          case "yyyyy":
            return intUnit2(fourToSix);
          case "yyyyyy":
            return intUnit2(six);
          // months
          case "M":
            return intUnit2(oneOrTwo);
          case "MM":
            return intUnit2(two);
          case "MMM":
            return oneOf2(loc.months("short", true), 1);
          case "MMMM":
            return oneOf2(loc.months("long", true), 1);
          case "L":
            return intUnit2(oneOrTwo);
          case "LL":
            return intUnit2(two);
          case "LLL":
            return oneOf2(loc.months("short", false), 1);
          case "LLLL":
            return oneOf2(loc.months("long", false), 1);
          // dates
          case "d":
            return intUnit2(oneOrTwo);
          case "dd":
            return intUnit2(two);
          // ordinals
          case "o":
            return intUnit2(oneToThree);
          case "ooo":
            return intUnit2(three);
          // time
          case "HH":
            return intUnit2(two);
          case "H":
            return intUnit2(oneOrTwo);
          case "hh":
            return intUnit2(two);
          case "h":
            return intUnit2(oneOrTwo);
          case "mm":
            return intUnit2(two);
          case "m":
            return intUnit2(oneOrTwo);
          case "q":
            return intUnit2(oneOrTwo);
          case "qq":
            return intUnit2(two);
          case "s":
            return intUnit2(oneOrTwo);
          case "ss":
            return intUnit2(two);
          case "S":
            return intUnit2(oneToThree);
          case "SSS":
            return intUnit2(three);
          case "u":
            return simple2(oneToNine);
          case "uu":
            return simple2(oneOrTwo);
          case "uuu":
            return intUnit2(one);
          // meridiem
          case "a":
            return oneOf2(loc.meridiems(), 0);
          // weekYear (k)
          case "kkkk":
            return intUnit2(four);
          case "kk":
            return intUnit2(twoToFour, untruncateYear2);
          // weekNumber (W)
          case "W":
            return intUnit2(oneOrTwo);
          case "WW":
            return intUnit2(two);
          // weekdays
          case "E":
          case "c":
            return intUnit2(one);
          case "EEE":
            return oneOf2(loc.weekdays("short", false), 1);
          case "EEEE":
            return oneOf2(loc.weekdays("long", false), 1);
          case "ccc":
            return oneOf2(loc.weekdays("short", true), 1);
          case "cccc":
            return oneOf2(loc.weekdays("long", true), 1);
          // offset/zone
          case "Z":
          case "ZZ":
            return offset2(new RegExp(`([+-]${oneOrTwo.source})(?::(${two.source}))?`), 2);
          case "ZZZ":
            return offset2(new RegExp(`([+-]${oneOrTwo.source})(${two.source})?`), 2);
          // we don't support ZZZZ (PST) or ZZZZZ (Pacific Standard Time) in parsing
          // because we don't have any way to figure out what they are
          case "z":
            return simple2(/[a-z_+-/]{1,256}?/i);
          // this special-case "token" represents a place where a macro-token expanded into a white-space literal
          // in this case we accept any non-newline white-space
          case " ":
            return simple2(/[^\S\n\r]/);
          default:
            return literal(t);
        }
      };
      const unit = unitate(token) || {
        invalidReason: MISSING_FTP2
      };
      unit.token = token;
      return unit;
    }
    var partTypeStyleToTokenVal2 = {
      year: {
        "2-digit": "yy",
        numeric: "yyyyy"
      },
      month: {
        numeric: "M",
        "2-digit": "MM",
        short: "MMM",
        long: "MMMM"
      },
      day: {
        numeric: "d",
        "2-digit": "dd"
      },
      weekday: {
        short: "EEE",
        long: "EEEE"
      },
      dayperiod: "a",
      dayPeriod: "a",
      hour12: {
        numeric: "h",
        "2-digit": "hh"
      },
      hour24: {
        numeric: "H",
        "2-digit": "HH"
      },
      minute: {
        numeric: "m",
        "2-digit": "mm"
      },
      second: {
        numeric: "s",
        "2-digit": "ss"
      },
      timeZoneName: {
        long: "ZZZZZ",
        short: "ZZZ"
      }
    };
    function tokenForPart2(part, formatOpts, resolvedOpts) {
      const { type, value } = part;
      if (type === "literal") {
        const isSpace = /^\s+$/.test(value);
        return {
          literal: !isSpace,
          val: isSpace ? " " : value
        };
      }
      const style = formatOpts[type];
      let actualType = type;
      if (type === "hour") {
        if (formatOpts.hour12 != null) {
          actualType = formatOpts.hour12 ? "hour12" : "hour24";
        } else if (formatOpts.hourCycle != null) {
          if (formatOpts.hourCycle === "h11" || formatOpts.hourCycle === "h12") {
            actualType = "hour12";
          } else {
            actualType = "hour24";
          }
        } else {
          actualType = resolvedOpts.hour12 ? "hour12" : "hour24";
        }
      }
      let val = partTypeStyleToTokenVal2[actualType];
      if (typeof val === "object") {
        val = val[style];
      }
      if (val) {
        return {
          literal: false,
          val
        };
      }
      return void 0;
    }
    function buildRegex2(units) {
      const re = units.map((u) => u.regex).reduce((f, r) => `${f}(${r.source})`, "");
      return [`^${re}$`, units];
    }
    function match2(input, regex, handlers) {
      const matches = input.match(regex);
      if (matches) {
        const all = {};
        let matchIndex = 1;
        for (const i in handlers) {
          if (hasOwnProperty2(handlers, i)) {
            const h = handlers[i], groups = h.groups ? h.groups + 1 : 1;
            if (!h.literal && h.token) {
              all[h.token.val[0]] = h.deser(matches.slice(matchIndex, matchIndex + groups));
            }
            matchIndex += groups;
          }
        }
        return [matches, all];
      } else {
        return [matches, {}];
      }
    }
    function dateTimeFromMatches2(matches) {
      const toField = (token) => {
        switch (token) {
          case "S":
            return "millisecond";
          case "s":
            return "second";
          case "m":
            return "minute";
          case "h":
          case "H":
            return "hour";
          case "d":
            return "day";
          case "o":
            return "ordinal";
          case "L":
          case "M":
            return "month";
          case "y":
            return "year";
          case "E":
          case "c":
            return "weekday";
          case "W":
            return "weekNumber";
          case "k":
            return "weekYear";
          case "q":
            return "quarter";
          default:
            return null;
        }
      };
      let zone = null;
      let specificOffset;
      if (!isUndefined2(matches.z)) {
        zone = IANAZone2.create(matches.z);
      }
      if (!isUndefined2(matches.Z)) {
        if (!zone) {
          zone = new FixedOffsetZone2(matches.Z);
        }
        specificOffset = matches.Z;
      }
      if (!isUndefined2(matches.q)) {
        matches.M = (matches.q - 1) * 3 + 1;
      }
      if (!isUndefined2(matches.h)) {
        if (matches.h < 12 && matches.a === 1) {
          matches.h += 12;
        } else if (matches.h === 12 && matches.a === 0) {
          matches.h = 0;
        }
      }
      if (matches.G === 0 && matches.y) {
        matches.y = -matches.y;
      }
      if (!isUndefined2(matches.u)) {
        matches.S = parseMillis2(matches.u);
      }
      const vals = Object.keys(matches).reduce((r, k) => {
        const f = toField(k);
        if (f) {
          r[f] = matches[k];
        }
        return r;
      }, {});
      return [vals, zone, specificOffset];
    }
    var dummyDateTimeCache2 = null;
    function getDummyDateTime2() {
      if (!dummyDateTimeCache2) {
        dummyDateTimeCache2 = DateTime2.fromMillis(1555555555555);
      }
      return dummyDateTimeCache2;
    }
    function maybeExpandMacroToken2(token, locale) {
      if (token.literal) {
        return token;
      }
      const formatOpts = Formatter2.macroTokenToFormatOpts(token.val);
      const tokens = formatOptsToTokens2(formatOpts, locale);
      if (tokens == null || tokens.includes(void 0)) {
        return token;
      }
      return tokens;
    }
    function expandMacroTokens2(tokens, locale) {
      return Array.prototype.concat(...tokens.map((t) => maybeExpandMacroToken2(t, locale)));
    }
    function explainFromTokens2(locale, input, format) {
      const tokens = expandMacroTokens2(Formatter2.parseFormat(format), locale), units = tokens.map((t) => unitForToken2(t, locale)), disqualifyingUnit = units.find((t) => t.invalidReason);
      if (disqualifyingUnit) {
        return { input, tokens, invalidReason: disqualifyingUnit.invalidReason };
      } else {
        const [regexString, handlers] = buildRegex2(units), regex = RegExp(regexString, "i"), [rawMatches, matches] = match2(input, regex, handlers), [result, zone, specificOffset] = matches ? dateTimeFromMatches2(matches) : [null, null, void 0];
        if (hasOwnProperty2(matches, "a") && hasOwnProperty2(matches, "H")) {
          throw new ConflictingSpecificationError2(
            "Can't include meridiem when specifying 24-hour format"
          );
        }
        return { input, tokens, regex, rawMatches, matches, result, zone, specificOffset };
      }
    }
    function parseFromTokens2(locale, input, format) {
      const { result, zone, specificOffset, invalidReason } = explainFromTokens2(locale, input, format);
      return [result, zone, specificOffset, invalidReason];
    }
    function formatOptsToTokens2(formatOpts, locale) {
      if (!formatOpts) {
        return null;
      }
      const formatter = Formatter2.create(locale, formatOpts);
      const df = formatter.dtFormatter(getDummyDateTime2());
      const parts = df.formatToParts();
      const resolvedOpts = df.resolvedOptions();
      return parts.map((p) => tokenForPart2(p, formatOpts, resolvedOpts));
    }
    var nonLeapLadder2 = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
    var leapLadder2 = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335];
    function unitOutOfRange2(unit, value) {
      return new Invalid2(
        "unit out of range",
        `you specified ${value} (of type ${typeof value}) as a ${unit}, which is invalid`
      );
    }
    function dayOfWeek2(year, month, day) {
      const d = new Date(Date.UTC(year, month - 1, day));
      if (year < 100 && year >= 0) {
        d.setUTCFullYear(d.getUTCFullYear() - 1900);
      }
      const js = d.getUTCDay();
      return js === 0 ? 7 : js;
    }
    function computeOrdinal2(year, month, day) {
      return day + (isLeapYear2(year) ? leapLadder2 : nonLeapLadder2)[month - 1];
    }
    function uncomputeOrdinal2(year, ordinal) {
      const table = isLeapYear2(year) ? leapLadder2 : nonLeapLadder2, month0 = table.findIndex((i) => i < ordinal), day = ordinal - table[month0];
      return { month: month0 + 1, day };
    }
    function gregorianToWeek2(gregObj) {
      const { year, month, day } = gregObj, ordinal = computeOrdinal2(year, month, day), weekday = dayOfWeek2(year, month, day);
      let weekNumber = Math.floor((ordinal - weekday + 10) / 7), weekYear;
      if (weekNumber < 1) {
        weekYear = year - 1;
        weekNumber = weeksInWeekYear2(weekYear);
      } else if (weekNumber > weeksInWeekYear2(year)) {
        weekYear = year + 1;
        weekNumber = 1;
      } else {
        weekYear = year;
      }
      return { weekYear, weekNumber, weekday, ...timeObject2(gregObj) };
    }
    function weekToGregorian2(weekData) {
      const { weekYear, weekNumber, weekday } = weekData, weekdayOfJan4 = dayOfWeek2(weekYear, 1, 4), yearInDays = daysInYear2(weekYear);
      let ordinal = weekNumber * 7 + weekday - weekdayOfJan4 - 3, year;
      if (ordinal < 1) {
        year = weekYear - 1;
        ordinal += daysInYear2(year);
      } else if (ordinal > yearInDays) {
        year = weekYear + 1;
        ordinal -= daysInYear2(weekYear);
      } else {
        year = weekYear;
      }
      const { month, day } = uncomputeOrdinal2(year, ordinal);
      return { year, month, day, ...timeObject2(weekData) };
    }
    function gregorianToOrdinal2(gregData) {
      const { year, month, day } = gregData;
      const ordinal = computeOrdinal2(year, month, day);
      return { year, ordinal, ...timeObject2(gregData) };
    }
    function ordinalToGregorian2(ordinalData) {
      const { year, ordinal } = ordinalData;
      const { month, day } = uncomputeOrdinal2(year, ordinal);
      return { year, month, day, ...timeObject2(ordinalData) };
    }
    function hasInvalidWeekData2(obj) {
      const validYear = isInteger2(obj.weekYear), validWeek = integerBetween2(obj.weekNumber, 1, weeksInWeekYear2(obj.weekYear)), validWeekday = integerBetween2(obj.weekday, 1, 7);
      if (!validYear) {
        return unitOutOfRange2("weekYear", obj.weekYear);
      } else if (!validWeek) {
        return unitOutOfRange2("week", obj.week);
      } else if (!validWeekday) {
        return unitOutOfRange2("weekday", obj.weekday);
      } else return false;
    }
    function hasInvalidOrdinalData2(obj) {
      const validYear = isInteger2(obj.year), validOrdinal = integerBetween2(obj.ordinal, 1, daysInYear2(obj.year));
      if (!validYear) {
        return unitOutOfRange2("year", obj.year);
      } else if (!validOrdinal) {
        return unitOutOfRange2("ordinal", obj.ordinal);
      } else return false;
    }
    function hasInvalidGregorianData2(obj) {
      const validYear = isInteger2(obj.year), validMonth = integerBetween2(obj.month, 1, 12), validDay = integerBetween2(obj.day, 1, daysInMonth2(obj.year, obj.month));
      if (!validYear) {
        return unitOutOfRange2("year", obj.year);
      } else if (!validMonth) {
        return unitOutOfRange2("month", obj.month);
      } else if (!validDay) {
        return unitOutOfRange2("day", obj.day);
      } else return false;
    }
    function hasInvalidTimeData2(obj) {
      const { hour, minute, second, millisecond } = obj;
      const validHour = integerBetween2(hour, 0, 23) || hour === 24 && minute === 0 && second === 0 && millisecond === 0, validMinute = integerBetween2(minute, 0, 59), validSecond = integerBetween2(second, 0, 59), validMillisecond = integerBetween2(millisecond, 0, 999);
      if (!validHour) {
        return unitOutOfRange2("hour", hour);
      } else if (!validMinute) {
        return unitOutOfRange2("minute", minute);
      } else if (!validSecond) {
        return unitOutOfRange2("second", second);
      } else if (!validMillisecond) {
        return unitOutOfRange2("millisecond", millisecond);
      } else return false;
    }
    var INVALID4 = "Invalid DateTime";
    var MAX_DATE2 = 864e13;
    function unsupportedZone2(zone) {
      return new Invalid2("unsupported zone", `the zone "${zone.name}" is not supported`);
    }
    function possiblyCachedWeekData2(dt) {
      if (dt.weekData === null) {
        dt.weekData = gregorianToWeek2(dt.c);
      }
      return dt.weekData;
    }
    function clone3(inst, alts) {
      const current = {
        ts: inst.ts,
        zone: inst.zone,
        c: inst.c,
        o: inst.o,
        loc: inst.loc,
        invalid: inst.invalid
      };
      return new DateTime2({ ...current, ...alts, old: current });
    }
    function fixOffset2(localTS, o, tz) {
      let utcGuess = localTS - o * 60 * 1e3;
      const o2 = tz.offset(utcGuess);
      if (o === o2) {
        return [utcGuess, o];
      }
      utcGuess -= (o2 - o) * 60 * 1e3;
      const o3 = tz.offset(utcGuess);
      if (o2 === o3) {
        return [utcGuess, o2];
      }
      return [localTS - Math.min(o2, o3) * 60 * 1e3, Math.max(o2, o3)];
    }
    function tsToObj2(ts, offset3) {
      ts += offset3 * 60 * 1e3;
      const d = new Date(ts);
      return {
        year: d.getUTCFullYear(),
        month: d.getUTCMonth() + 1,
        day: d.getUTCDate(),
        hour: d.getUTCHours(),
        minute: d.getUTCMinutes(),
        second: d.getUTCSeconds(),
        millisecond: d.getUTCMilliseconds()
      };
    }
    function objToTS2(obj, offset3, zone) {
      return fixOffset2(objToLocalTS2(obj), offset3, zone);
    }
    function adjustTime2(inst, dur) {
      const oPre = inst.o, year = inst.c.year + Math.trunc(dur.years), month = inst.c.month + Math.trunc(dur.months) + Math.trunc(dur.quarters) * 3, c = {
        ...inst.c,
        year,
        month,
        day: Math.min(inst.c.day, daysInMonth2(year, month)) + Math.trunc(dur.days) + Math.trunc(dur.weeks) * 7
      }, millisToAdd = Duration2.fromObject({
        years: dur.years - Math.trunc(dur.years),
        quarters: dur.quarters - Math.trunc(dur.quarters),
        months: dur.months - Math.trunc(dur.months),
        weeks: dur.weeks - Math.trunc(dur.weeks),
        days: dur.days - Math.trunc(dur.days),
        hours: dur.hours,
        minutes: dur.minutes,
        seconds: dur.seconds,
        milliseconds: dur.milliseconds
      }).as("milliseconds"), localTS = objToLocalTS2(c);
      let [ts, o] = fixOffset2(localTS, oPre, inst.zone);
      if (millisToAdd !== 0) {
        ts += millisToAdd;
        o = inst.zone.offset(ts);
      }
      return { ts, o };
    }
    function parseDataToDateTime2(parsed, parsedZone, opts, format, text2, specificOffset) {
      const { setZone, zone } = opts;
      if (parsed && Object.keys(parsed).length !== 0 || parsedZone) {
        const interpretationZone = parsedZone || zone, inst = DateTime2.fromObject(parsed, {
          ...opts,
          zone: interpretationZone,
          specificOffset
        });
        return setZone ? inst : inst.setZone(zone);
      } else {
        return DateTime2.invalid(
          new Invalid2("unparsable", `the input "${text2}" can't be parsed as ${format}`)
        );
      }
    }
    function toTechFormat2(dt, format, allowZ = true) {
      return dt.isValid ? Formatter2.create(Locale2.create("en-US"), {
        allowZ,
        forceSimple: true
      }).formatDateTimeFromString(dt, format) : null;
    }
    function toISODate2(o, extended) {
      const longFormat = o.c.year > 9999 || o.c.year < 0;
      let c = "";
      if (longFormat && o.c.year >= 0) c += "+";
      c += padStart2(o.c.year, longFormat ? 6 : 4);
      if (extended) {
        c += "-";
        c += padStart2(o.c.month);
        c += "-";
        c += padStart2(o.c.day);
      } else {
        c += padStart2(o.c.month);
        c += padStart2(o.c.day);
      }
      return c;
    }
    function toISOTime2(o, extended, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone) {
      let c = padStart2(o.c.hour);
      if (extended) {
        c += ":";
        c += padStart2(o.c.minute);
        if (o.c.millisecond !== 0 || o.c.second !== 0 || !suppressSeconds) {
          c += ":";
        }
      } else {
        c += padStart2(o.c.minute);
      }
      if (o.c.millisecond !== 0 || o.c.second !== 0 || !suppressSeconds) {
        c += padStart2(o.c.second);
        if (o.c.millisecond !== 0 || !suppressMilliseconds) {
          c += ".";
          c += padStart2(o.c.millisecond, 3);
        }
      }
      if (includeOffset) {
        if (o.isOffsetFixed && o.offset === 0 && !extendedZone) {
          c += "Z";
        } else if (o.o < 0) {
          c += "-";
          c += padStart2(Math.trunc(-o.o / 60));
          c += ":";
          c += padStart2(Math.trunc(-o.o % 60));
        } else {
          c += "+";
          c += padStart2(Math.trunc(o.o / 60));
          c += ":";
          c += padStart2(Math.trunc(o.o % 60));
        }
      }
      if (extendedZone) {
        c += "[" + o.zone.ianaName + "]";
      }
      return c;
    }
    var defaultUnitValues2 = {
      month: 1,
      day: 1,
      hour: 0,
      minute: 0,
      second: 0,
      millisecond: 0
    };
    var defaultWeekUnitValues2 = {
      weekNumber: 1,
      weekday: 1,
      hour: 0,
      minute: 0,
      second: 0,
      millisecond: 0
    };
    var defaultOrdinalUnitValues2 = {
      ordinal: 1,
      hour: 0,
      minute: 0,
      second: 0,
      millisecond: 0
    };
    var orderedUnits3 = ["year", "month", "day", "hour", "minute", "second", "millisecond"];
    var orderedWeekUnits2 = [
      "weekYear",
      "weekNumber",
      "weekday",
      "hour",
      "minute",
      "second",
      "millisecond"
    ];
    var orderedOrdinalUnits2 = ["year", "ordinal", "hour", "minute", "second", "millisecond"];
    function normalizeUnit2(unit) {
      const normalized = {
        year: "year",
        years: "year",
        month: "month",
        months: "month",
        day: "day",
        days: "day",
        hour: "hour",
        hours: "hour",
        minute: "minute",
        minutes: "minute",
        quarter: "quarter",
        quarters: "quarter",
        second: "second",
        seconds: "second",
        millisecond: "millisecond",
        milliseconds: "millisecond",
        weekday: "weekday",
        weekdays: "weekday",
        weeknumber: "weekNumber",
        weeksnumber: "weekNumber",
        weeknumbers: "weekNumber",
        weekyear: "weekYear",
        weekyears: "weekYear",
        ordinal: "ordinal"
      }[unit.toLowerCase()];
      if (!normalized) throw new InvalidUnitError2(unit);
      return normalized;
    }
    function quickDT2(obj, opts) {
      const zone = normalizeZone2(opts.zone, Settings2.defaultZone), loc = Locale2.fromObject(opts), tsNow = Settings2.now();
      let ts, o;
      if (!isUndefined2(obj.year)) {
        for (const u of orderedUnits3) {
          if (isUndefined2(obj[u])) {
            obj[u] = defaultUnitValues2[u];
          }
        }
        const invalid = hasInvalidGregorianData2(obj) || hasInvalidTimeData2(obj);
        if (invalid) {
          return DateTime2.invalid(invalid);
        }
        const offsetProvis = zone.offset(tsNow);
        [ts, o] = objToTS2(obj, offsetProvis, zone);
      } else {
        ts = tsNow;
      }
      return new DateTime2({ ts, zone, loc, o });
    }
    function diffRelative2(start, end, opts) {
      const round = isUndefined2(opts.round) ? true : opts.round, format = (c, unit) => {
        c = roundTo2(c, round || opts.calendary ? 0 : 2, true);
        const formatter = end.loc.clone(opts).relFormatter(opts);
        return formatter.format(c, unit);
      }, differ = (unit) => {
        if (opts.calendary) {
          if (!end.hasSame(start, unit)) {
            return end.startOf(unit).diff(start.startOf(unit), unit).get(unit);
          } else return 0;
        } else {
          return end.diff(start, unit).get(unit);
        }
      };
      if (opts.unit) {
        return format(differ(opts.unit), opts.unit);
      }
      for (const unit of opts.units) {
        const count = differ(unit);
        if (Math.abs(count) >= 1) {
          return format(count, unit);
        }
      }
      return format(start > end ? -0 : 0, opts.units[opts.units.length - 1]);
    }
    function lastOpts2(argList) {
      let opts = {}, args;
      if (argList.length > 0 && typeof argList[argList.length - 1] === "object") {
        opts = argList[argList.length - 1];
        args = Array.from(argList).slice(0, argList.length - 1);
      } else {
        args = Array.from(argList);
      }
      return [opts, args];
    }
    var DateTime2 = class _DateTime {
      /**
       * @access private
       */
      constructor(config) {
        const zone = config.zone || Settings2.defaultZone;
        let invalid = config.invalid || (Number.isNaN(config.ts) ? new Invalid2("invalid input") : null) || (!zone.isValid ? unsupportedZone2(zone) : null);
        this.ts = isUndefined2(config.ts) ? Settings2.now() : config.ts;
        let c = null, o = null;
        if (!invalid) {
          const unchanged = config.old && config.old.ts === this.ts && config.old.zone.equals(zone);
          if (unchanged) {
            [c, o] = [config.old.c, config.old.o];
          } else {
            const ot = zone.offset(this.ts);
            c = tsToObj2(this.ts, ot);
            invalid = Number.isNaN(c.year) ? new Invalid2("invalid input") : null;
            c = invalid ? null : c;
            o = invalid ? null : ot;
          }
        }
        this._zone = zone;
        this.loc = config.loc || Locale2.create();
        this.invalid = invalid;
        this.weekData = null;
        this.c = c;
        this.o = o;
        this.isLuxonDateTime = true;
      }
      // CONSTRUCT
      /**
       * Create a DateTime for the current instant, in the system's time zone.
       *
       * Use Settings to override these default values if needed.
       * @example DateTime.now().toISO() //~> now in the ISO format
       * @return {DateTime}
       */
      static now() {
        return new _DateTime({});
      }
      /**
       * Create a local DateTime
       * @param {number} [year] - The calendar year. If omitted (as in, call `local()` with no arguments), the current time will be used
       * @param {number} [month=1] - The month, 1-indexed
       * @param {number} [day=1] - The day of the month, 1-indexed
       * @param {number} [hour=0] - The hour of the day, in 24-hour time
       * @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59
       * @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59
       * @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999
       * @example DateTime.local()                                  //~> now
       * @example DateTime.local({ zone: "America/New_York" })      //~> now, in US east coast time
       * @example DateTime.local(2017)                              //~> 2017-01-01T00:00:00
       * @example DateTime.local(2017, 3)                           //~> 2017-03-01T00:00:00
       * @example DateTime.local(2017, 3, 12, { locale: "fr" })     //~> 2017-03-12T00:00:00, with a French locale
       * @example DateTime.local(2017, 3, 12, 5)                    //~> 2017-03-12T05:00:00
       * @example DateTime.local(2017, 3, 12, 5, { zone: "utc" })   //~> 2017-03-12T05:00:00, in UTC
       * @example DateTime.local(2017, 3, 12, 5, 45)                //~> 2017-03-12T05:45:00
       * @example DateTime.local(2017, 3, 12, 5, 45, 10)            //~> 2017-03-12T05:45:10
       * @example DateTime.local(2017, 3, 12, 5, 45, 10, 765)       //~> 2017-03-12T05:45:10.765
       * @return {DateTime}
       */
      static local() {
        const [opts, args] = lastOpts2(arguments), [year, month, day, hour, minute, second, millisecond] = args;
        return quickDT2({ year, month, day, hour, minute, second, millisecond }, opts);
      }
      /**
       * Create a DateTime in UTC
       * @param {number} [year] - The calendar year. If omitted (as in, call `utc()` with no arguments), the current time will be used
       * @param {number} [month=1] - The month, 1-indexed
       * @param {number} [day=1] - The day of the month
       * @param {number} [hour=0] - The hour of the day, in 24-hour time
       * @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59
       * @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59
       * @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999
       * @param {Object} options - configuration options for the DateTime
       * @param {string} [options.locale] - a locale to set on the resulting DateTime instance
       * @param {string} [options.outputCalendar] - the output calendar to set on the resulting DateTime instance
       * @param {string} [options.numberingSystem] - the numbering system to set on the resulting DateTime instance
       * @example DateTime.utc()                                              //~> now
       * @example DateTime.utc(2017)                                          //~> 2017-01-01T00:00:00Z
       * @example DateTime.utc(2017, 3)                                       //~> 2017-03-01T00:00:00Z
       * @example DateTime.utc(2017, 3, 12)                                   //~> 2017-03-12T00:00:00Z
       * @example DateTime.utc(2017, 3, 12, 5)                                //~> 2017-03-12T05:00:00Z
       * @example DateTime.utc(2017, 3, 12, 5, 45)                            //~> 2017-03-12T05:45:00Z
       * @example DateTime.utc(2017, 3, 12, 5, 45, { locale: "fr" })          //~> 2017-03-12T05:45:00Z with a French locale
       * @example DateTime.utc(2017, 3, 12, 5, 45, 10)                        //~> 2017-03-12T05:45:10Z
       * @example DateTime.utc(2017, 3, 12, 5, 45, 10, 765, { locale: "fr" }) //~> 2017-03-12T05:45:10.765Z with a French locale
       * @return {DateTime}
       */
      static utc() {
        const [opts, args] = lastOpts2(arguments), [year, month, day, hour, minute, second, millisecond] = args;
        opts.zone = FixedOffsetZone2.utcInstance;
        return quickDT2({ year, month, day, hour, minute, second, millisecond }, opts);
      }
      /**
       * Create a DateTime from a JavaScript Date object. Uses the default zone.
       * @param {Date} date - a JavaScript Date object
       * @param {Object} options - configuration options for the DateTime
       * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into
       * @return {DateTime}
       */
      static fromJSDate(date, options = {}) {
        const ts = isDate2(date) ? date.valueOf() : NaN;
        if (Number.isNaN(ts)) {
          return _DateTime.invalid("invalid input");
        }
        const zoneToUse = normalizeZone2(options.zone, Settings2.defaultZone);
        if (!zoneToUse.isValid) {
          return _DateTime.invalid(unsupportedZone2(zoneToUse));
        }
        return new _DateTime({
          ts,
          zone: zoneToUse,
          loc: Locale2.fromObject(options)
        });
      }
      /**
       * Create a DateTime from a number of milliseconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone.
       * @param {number} milliseconds - a number of milliseconds since 1970 UTC
       * @param {Object} options - configuration options for the DateTime
       * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into
       * @param {string} [options.locale] - a locale to set on the resulting DateTime instance
       * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance
       * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance
       * @return {DateTime}
       */
      static fromMillis(milliseconds, options = {}) {
        if (!isNumber2(milliseconds)) {
          throw new InvalidArgumentError2(
            `fromMillis requires a numerical input, but received a ${typeof milliseconds} with value ${milliseconds}`
          );
        } else if (milliseconds < -MAX_DATE2 || milliseconds > MAX_DATE2) {
          return _DateTime.invalid("Timestamp out of range");
        } else {
          return new _DateTime({
            ts: milliseconds,
            zone: normalizeZone2(options.zone, Settings2.defaultZone),
            loc: Locale2.fromObject(options)
          });
        }
      }
      /**
       * Create a DateTime from a number of seconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone.
       * @param {number} seconds - a number of seconds since 1970 UTC
       * @param {Object} options - configuration options for the DateTime
       * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into
       * @param {string} [options.locale] - a locale to set on the resulting DateTime instance
       * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance
       * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance
       * @return {DateTime}
       */
      static fromSeconds(seconds, options = {}) {
        if (!isNumber2(seconds)) {
          throw new InvalidArgumentError2("fromSeconds requires a numerical input");
        } else {
          return new _DateTime({
            ts: seconds * 1e3,
            zone: normalizeZone2(options.zone, Settings2.defaultZone),
            loc: Locale2.fromObject(options)
          });
        }
      }
      /**
       * Create a DateTime from a JavaScript object with keys like 'year' and 'hour' with reasonable defaults.
       * @param {Object} obj - the object to create the DateTime from
       * @param {number} obj.year - a year, such as 1987
       * @param {number} obj.month - a month, 1-12
       * @param {number} obj.day - a day of the month, 1-31, depending on the month
       * @param {number} obj.ordinal - day of the year, 1-365 or 366
       * @param {number} obj.weekYear - an ISO week year
       * @param {number} obj.weekNumber - an ISO week number, between 1 and 52 or 53, depending on the year
       * @param {number} obj.weekday - an ISO weekday, 1-7, where 1 is Monday and 7 is Sunday
       * @param {number} obj.hour - hour of the day, 0-23
       * @param {number} obj.minute - minute of the hour, 0-59
       * @param {number} obj.second - second of the minute, 0-59
       * @param {number} obj.millisecond - millisecond of the second, 0-999
       * @param {Object} opts - options for creating this DateTime
       * @param {string|Zone} [opts.zone='local'] - interpret the numbers in the context of a particular zone. Can take any value taken as the first argument to setZone()
       * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance
       * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
       * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance
       * @example DateTime.fromObject({ year: 1982, month: 5, day: 25}).toISODate() //=> '1982-05-25'
       * @example DateTime.fromObject({ year: 1982 }).toISODate() //=> '1982-01-01'
       * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }) //~> today at 10:26:06
       * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'utc' }),
       * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'local' })
       * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'America/New_York' })
       * @example DateTime.fromObject({ weekYear: 2016, weekNumber: 2, weekday: 3 }).toISODate() //=> '2016-01-13'
       * @return {DateTime}
       */
      static fromObject(obj, opts = {}) {
        obj = obj || {};
        const zoneToUse = normalizeZone2(opts.zone, Settings2.defaultZone);
        if (!zoneToUse.isValid) {
          return _DateTime.invalid(unsupportedZone2(zoneToUse));
        }
        const tsNow = Settings2.now(), offsetProvis = !isUndefined2(opts.specificOffset) ? opts.specificOffset : zoneToUse.offset(tsNow), normalized = normalizeObject2(obj, normalizeUnit2), containsOrdinal = !isUndefined2(normalized.ordinal), containsGregorYear = !isUndefined2(normalized.year), containsGregorMD = !isUndefined2(normalized.month) || !isUndefined2(normalized.day), containsGregor = containsGregorYear || containsGregorMD, definiteWeekDef = normalized.weekYear || normalized.weekNumber, loc = Locale2.fromObject(opts);
        if ((containsGregor || containsOrdinal) && definiteWeekDef) {
          throw new ConflictingSpecificationError2(
            "Can't mix weekYear/weekNumber units with year/month/day or ordinals"
          );
        }
        if (containsGregorMD && containsOrdinal) {
          throw new ConflictingSpecificationError2("Can't mix ordinal dates with month/day");
        }
        const useWeekData = definiteWeekDef || normalized.weekday && !containsGregor;
        let units, defaultValues, objNow = tsToObj2(tsNow, offsetProvis);
        if (useWeekData) {
          units = orderedWeekUnits2;
          defaultValues = defaultWeekUnitValues2;
          objNow = gregorianToWeek2(objNow);
        } else if (containsOrdinal) {
          units = orderedOrdinalUnits2;
          defaultValues = defaultOrdinalUnitValues2;
          objNow = gregorianToOrdinal2(objNow);
        } else {
          units = orderedUnits3;
          defaultValues = defaultUnitValues2;
        }
        let foundFirst = false;
        for (const u of units) {
          const v = normalized[u];
          if (!isUndefined2(v)) {
            foundFirst = true;
          } else if (foundFirst) {
            normalized[u] = defaultValues[u];
          } else {
            normalized[u] = objNow[u];
          }
        }
        const higherOrderInvalid = useWeekData ? hasInvalidWeekData2(normalized) : containsOrdinal ? hasInvalidOrdinalData2(normalized) : hasInvalidGregorianData2(normalized), invalid = higherOrderInvalid || hasInvalidTimeData2(normalized);
        if (invalid) {
          return _DateTime.invalid(invalid);
        }
        const gregorian = useWeekData ? weekToGregorian2(normalized) : containsOrdinal ? ordinalToGregorian2(normalized) : normalized, [tsFinal, offsetFinal] = objToTS2(gregorian, offsetProvis, zoneToUse), inst = new _DateTime({
          ts: tsFinal,
          zone: zoneToUse,
          o: offsetFinal,
          loc
        });
        if (normalized.weekday && containsGregor && obj.weekday !== inst.weekday) {
          return _DateTime.invalid(
            "mismatched weekday",
            `you can't specify both a weekday of ${normalized.weekday} and a date of ${inst.toISO()}`
          );
        }
        return inst;
      }
      /**
       * Create a DateTime from an ISO 8601 string
       * @param {string} text - the ISO string
       * @param {Object} opts - options to affect the creation
       * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the time to this zone
       * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one
       * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance
       * @param {string} [opts.outputCalendar] - the output calendar to set on the resulting DateTime instance
       * @param {string} [opts.numberingSystem] - the numbering system to set on the resulting DateTime instance
       * @example DateTime.fromISO('2016-05-25T09:08:34.123')
       * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00')
       * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00', {setZone: true})
       * @example DateTime.fromISO('2016-05-25T09:08:34.123', {zone: 'utc'})
       * @example DateTime.fromISO('2016-W05-4')
       * @return {DateTime}
       */
      static fromISO(text2, opts = {}) {
        const [vals, parsedZone] = parseISODate2(text2);
        return parseDataToDateTime2(vals, parsedZone, opts, "ISO 8601", text2);
      }
      /**
       * Create a DateTime from an RFC 2822 string
       * @param {string} text - the RFC 2822 string
       * @param {Object} opts - options to affect the creation
       * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since the offset is always specified in the string itself, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in.
       * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one
       * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance
       * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
       * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance
       * @example DateTime.fromRFC2822('25 Nov 2016 13:23:12 GMT')
       * @example DateTime.fromRFC2822('Fri, 25 Nov 2016 13:23:12 +0600')
       * @example DateTime.fromRFC2822('25 Nov 2016 13:23 Z')
       * @return {DateTime}
       */
      static fromRFC2822(text2, opts = {}) {
        const [vals, parsedZone] = parseRFC2822Date2(text2);
        return parseDataToDateTime2(vals, parsedZone, opts, "RFC 2822", text2);
      }
      /**
       * Create a DateTime from an HTTP header date
       * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1
       * @param {string} text - the HTTP header date
       * @param {Object} opts - options to affect the creation
       * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since HTTP dates are always in UTC, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in.
       * @param {boolean} [opts.setZone=false] - override the zone with the fixed-offset zone specified in the string. For HTTP dates, this is always UTC, so this option is equivalent to setting the `zone` option to 'utc', but this option is included for consistency with similar methods.
       * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance
       * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
       * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance
       * @example DateTime.fromHTTP('Sun, 06 Nov 1994 08:49:37 GMT')
       * @example DateTime.fromHTTP('Sunday, 06-Nov-94 08:49:37 GMT')
       * @example DateTime.fromHTTP('Sun Nov  6 08:49:37 1994')
       * @return {DateTime}
       */
      static fromHTTP(text2, opts = {}) {
        const [vals, parsedZone] = parseHTTPDate2(text2);
        return parseDataToDateTime2(vals, parsedZone, opts, "HTTP", opts);
      }
      /**
       * Create a DateTime from an input string and format string.
       * Defaults to en-US if no locale has been specified, regardless of the system's locale. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/#/parsing?id=table-of-tokens).
       * @param {string} text - the string to parse
       * @param {string} fmt - the format the string is expected to be in (see the link below for the formats)
       * @param {Object} opts - options to affect the creation
       * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone
       * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one
       * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale
       * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system
       * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
       * @return {DateTime}
       */
      static fromFormat(text2, fmt, opts = {}) {
        if (isUndefined2(text2) || isUndefined2(fmt)) {
          throw new InvalidArgumentError2("fromFormat requires an input string and a format");
        }
        const { locale = null, numberingSystem = null } = opts, localeToUse = Locale2.fromOpts({
          locale,
          numberingSystem,
          defaultToEN: true
        }), [vals, parsedZone, specificOffset, invalid] = parseFromTokens2(localeToUse, text2, fmt);
        if (invalid) {
          return _DateTime.invalid(invalid);
        } else {
          return parseDataToDateTime2(vals, parsedZone, opts, `format ${fmt}`, text2, specificOffset);
        }
      }
      /**
       * @deprecated use fromFormat instead
       */
      static fromString(text2, fmt, opts = {}) {
        return _DateTime.fromFormat(text2, fmt, opts);
      }
      /**
       * Create a DateTime from a SQL date, time, or datetime
       * Defaults to en-US if no locale has been specified, regardless of the system's locale
       * @param {string} text - the string to parse
       * @param {Object} opts - options to affect the creation
       * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone
       * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one
       * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale
       * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system
       * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
       * @example DateTime.fromSQL('2017-05-15')
       * @example DateTime.fromSQL('2017-05-15 09:12:34')
       * @example DateTime.fromSQL('2017-05-15 09:12:34.342')
       * @example DateTime.fromSQL('2017-05-15 09:12:34.342+06:00')
       * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles')
       * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles', { setZone: true })
       * @example DateTime.fromSQL('2017-05-15 09:12:34.342', { zone: 'America/Los_Angeles' })
       * @example DateTime.fromSQL('09:12:34.342')
       * @return {DateTime}
       */
      static fromSQL(text2, opts = {}) {
        const [vals, parsedZone] = parseSQL2(text2);
        return parseDataToDateTime2(vals, parsedZone, opts, "SQL", text2);
      }
      /**
       * Create an invalid DateTime.
       * @param {string} reason - simple string of why this DateTime is invalid. Should not contain parameters or anything else data-dependent.
       * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information
       * @return {DateTime}
       */
      static invalid(reason, explanation = null) {
        if (!reason) {
          throw new InvalidArgumentError2("need to specify a reason the DateTime is invalid");
        }
        const invalid = reason instanceof Invalid2 ? reason : new Invalid2(reason, explanation);
        if (Settings2.throwOnInvalid) {
          throw new InvalidDateTimeError2(invalid);
        } else {
          return new _DateTime({ invalid });
        }
      }
      /**
       * Check if an object is an instance of DateTime. Works across context boundaries
       * @param {object} o
       * @return {boolean}
       */
      static isDateTime(o) {
        return o && o.isLuxonDateTime || false;
      }
      /**
       * Produce the format string for a set of options
       * @param formatOpts
       * @param localeOpts
       * @returns {string}
       */
      static parseFormatForOpts(formatOpts, localeOpts = {}) {
        const tokenList = formatOptsToTokens2(formatOpts, Locale2.fromObject(localeOpts));
        return !tokenList ? null : tokenList.map((t) => t ? t.val : null).join("");
      }
      /**
       * Produce the the fully expanded format token for the locale
       * Does NOT quote characters, so quoted tokens will not round trip correctly
       * @param fmt
       * @param localeOpts
       * @returns {string}
       */
      static expandFormat(fmt, localeOpts = {}) {
        const expanded = expandMacroTokens2(Formatter2.parseFormat(fmt), Locale2.fromObject(localeOpts));
        return expanded.map((t) => t.val).join("");
      }
      // INFO
      /**
       * Get the value of unit.
       * @param {string} unit - a unit such as 'minute' or 'day'
       * @example DateTime.local(2017, 7, 4).get('month'); //=> 7
       * @example DateTime.local(2017, 7, 4).get('day'); //=> 4
       * @return {number}
       */
      get(unit) {
        return this[unit];
      }
      /**
       * Returns whether the DateTime is valid. Invalid DateTimes occur when:
       * * The DateTime was created from invalid calendar information, such as the 13th month or February 30
       * * The DateTime was created by an operation on another invalid date
       * @type {boolean}
       */
      get isValid() {
        return this.invalid === null;
      }
      /**
       * Returns an error code if this DateTime is invalid, or null if the DateTime is valid
       * @type {string}
       */
      get invalidReason() {
        return this.invalid ? this.invalid.reason : null;
      }
      /**
       * Returns an explanation of why this DateTime became invalid, or null if the DateTime is valid
       * @type {string}
       */
      get invalidExplanation() {
        return this.invalid ? this.invalid.explanation : null;
      }
      /**
       * Get the locale of a DateTime, such 'en-GB'. The locale is used when formatting the DateTime
       *
       * @type {string}
       */
      get locale() {
        return this.isValid ? this.loc.locale : null;
      }
      /**
       * Get the numbering system of a DateTime, such 'beng'. The numbering system is used when formatting the DateTime
       *
       * @type {string}
       */
      get numberingSystem() {
        return this.isValid ? this.loc.numberingSystem : null;
      }
      /**
       * Get the output calendar of a DateTime, such 'islamic'. The output calendar is used when formatting the DateTime
       *
       * @type {string}
       */
      get outputCalendar() {
        return this.isValid ? this.loc.outputCalendar : null;
      }
      /**
       * Get the time zone associated with this DateTime.
       * @type {Zone}
       */
      get zone() {
        return this._zone;
      }
      /**
       * Get the name of the time zone.
       * @type {string}
       */
      get zoneName() {
        return this.isValid ? this.zone.name : null;
      }
      /**
       * Get the year
       * @example DateTime.local(2017, 5, 25).year //=> 2017
       * @type {number}
       */
      get year() {
        return this.isValid ? this.c.year : NaN;
      }
      /**
       * Get the quarter
       * @example DateTime.local(2017, 5, 25).quarter //=> 2
       * @type {number}
       */
      get quarter() {
        return this.isValid ? Math.ceil(this.c.month / 3) : NaN;
      }
      /**
       * Get the month (1-12).
       * @example DateTime.local(2017, 5, 25).month //=> 5
       * @type {number}
       */
      get month() {
        return this.isValid ? this.c.month : NaN;
      }
      /**
       * Get the day of the month (1-30ish).
       * @example DateTime.local(2017, 5, 25).day //=> 25
       * @type {number}
       */
      get day() {
        return this.isValid ? this.c.day : NaN;
      }
      /**
       * Get the hour of the day (0-23).
       * @example DateTime.local(2017, 5, 25, 9).hour //=> 9
       * @type {number}
       */
      get hour() {
        return this.isValid ? this.c.hour : NaN;
      }
      /**
       * Get the minute of the hour (0-59).
       * @example DateTime.local(2017, 5, 25, 9, 30).minute //=> 30
       * @type {number}
       */
      get minute() {
        return this.isValid ? this.c.minute : NaN;
      }
      /**
       * Get the second of the minute (0-59).
       * @example DateTime.local(2017, 5, 25, 9, 30, 52).second //=> 52
       * @type {number}
       */
      get second() {
        return this.isValid ? this.c.second : NaN;
      }
      /**
       * Get the millisecond of the second (0-999).
       * @example DateTime.local(2017, 5, 25, 9, 30, 52, 654).millisecond //=> 654
       * @type {number}
       */
      get millisecond() {
        return this.isValid ? this.c.millisecond : NaN;
      }
      /**
       * Get the week year
       * @see https://en.wikipedia.org/wiki/ISO_week_date
       * @example DateTime.local(2014, 12, 31).weekYear //=> 2015
       * @type {number}
       */
      get weekYear() {
        return this.isValid ? possiblyCachedWeekData2(this).weekYear : NaN;
      }
      /**
       * Get the week number of the week year (1-52ish).
       * @see https://en.wikipedia.org/wiki/ISO_week_date
       * @example DateTime.local(2017, 5, 25).weekNumber //=> 21
       * @type {number}
       */
      get weekNumber() {
        return this.isValid ? possiblyCachedWeekData2(this).weekNumber : NaN;
      }
      /**
       * Get the day of the week.
       * 1 is Monday and 7 is Sunday
       * @see https://en.wikipedia.org/wiki/ISO_week_date
       * @example DateTime.local(2014, 11, 31).weekday //=> 4
       * @type {number}
       */
      get weekday() {
        return this.isValid ? possiblyCachedWeekData2(this).weekday : NaN;
      }
      /**
       * Get the ordinal (meaning the day of the year)
       * @example DateTime.local(2017, 5, 25).ordinal //=> 145
       * @type {number|DateTime}
       */
      get ordinal() {
        return this.isValid ? gregorianToOrdinal2(this.c).ordinal : NaN;
      }
      /**
       * Get the human readable short month name, such as 'Oct'.
       * Defaults to the system's locale if no locale has been specified
       * @example DateTime.local(2017, 10, 30).monthShort //=> Oct
       * @type {string}
       */
      get monthShort() {
        return this.isValid ? Info2.months("short", { locObj: this.loc })[this.month - 1] : null;
      }
      /**
       * Get the human readable long month name, such as 'October'.
       * Defaults to the system's locale if no locale has been specified
       * @example DateTime.local(2017, 10, 30).monthLong //=> October
       * @type {string}
       */
      get monthLong() {
        return this.isValid ? Info2.months("long", { locObj: this.loc })[this.month - 1] : null;
      }
      /**
       * Get the human readable short weekday, such as 'Mon'.
       * Defaults to the system's locale if no locale has been specified
       * @example DateTime.local(2017, 10, 30).weekdayShort //=> Mon
       * @type {string}
       */
      get weekdayShort() {
        return this.isValid ? Info2.weekdays("short", { locObj: this.loc })[this.weekday - 1] : null;
      }
      /**
       * Get the human readable long weekday, such as 'Monday'.
       * Defaults to the system's locale if no locale has been specified
       * @example DateTime.local(2017, 10, 30).weekdayLong //=> Monday
       * @type {string}
       */
      get weekdayLong() {
        return this.isValid ? Info2.weekdays("long", { locObj: this.loc })[this.weekday - 1] : null;
      }
      /**
       * Get the UTC offset of this DateTime in minutes
       * @example DateTime.now().offset //=> -240
       * @example DateTime.utc().offset //=> 0
       * @type {number}
       */
      get offset() {
        return this.isValid ? +this.o : NaN;
      }
      /**
       * Get the short human name for the zone's current offset, for example "EST" or "EDT".
       * Defaults to the system's locale if no locale has been specified
       * @type {string}
       */
      get offsetNameShort() {
        if (this.isValid) {
          return this.zone.offsetName(this.ts, {
            format: "short",
            locale: this.locale
          });
        } else {
          return null;
        }
      }
      /**
       * Get the long human name for the zone's current offset, for example "Eastern Standard Time" or "Eastern Daylight Time".
       * Defaults to the system's locale if no locale has been specified
       * @type {string}
       */
      get offsetNameLong() {
        if (this.isValid) {
          return this.zone.offsetName(this.ts, {
            format: "long",
            locale: this.locale
          });
        } else {
          return null;
        }
      }
      /**
       * Get whether this zone's offset ever changes, as in a DST.
       * @type {boolean}
       */
      get isOffsetFixed() {
        return this.isValid ? this.zone.isUniversal : null;
      }
      /**
       * Get whether the DateTime is in a DST.
       * @type {boolean}
       */
      get isInDST() {
        if (this.isOffsetFixed) {
          return false;
        } else {
          return this.offset > this.set({ month: 1, day: 1 }).offset || this.offset > this.set({ month: 5 }).offset;
        }
      }
      /**
       * Get those DateTimes which have the same local time as this DateTime, but a different offset from UTC
       * in this DateTime's zone. During DST changes local time can be ambiguous, for example
       * `2023-10-29T02:30:00` in `Europe/Berlin` can have offset `+01:00` or `+02:00`.
       * This method will return both possible DateTimes if this DateTime's local time is ambiguous.
       * @returns {DateTime[]}
       */
      getPossibleOffsets() {
        if (!this.isValid || this.isOffsetFixed) {
          return [this];
        }
        const dayMs = 864e5;
        const minuteMs = 6e4;
        const localTS = objToLocalTS2(this.c);
        const oEarlier = this.zone.offset(localTS - dayMs);
        const oLater = this.zone.offset(localTS + dayMs);
        const o1 = this.zone.offset(localTS - oEarlier * minuteMs);
        const o2 = this.zone.offset(localTS - oLater * minuteMs);
        if (o1 === o2) {
          return [this];
        }
        const ts1 = localTS - o1 * minuteMs;
        const ts2 = localTS - o2 * minuteMs;
        const c1 = tsToObj2(ts1, o1);
        const c2 = tsToObj2(ts2, o2);
        if (c1.hour === c2.hour && c1.minute === c2.minute && c1.second === c2.second && c1.millisecond === c2.millisecond) {
          return [clone3(this, { ts: ts1 }), clone3(this, { ts: ts2 })];
        }
        return [this];
      }
      /**
       * Returns true if this DateTime is in a leap year, false otherwise
       * @example DateTime.local(2016).isInLeapYear //=> true
       * @example DateTime.local(2013).isInLeapYear //=> false
       * @type {boolean}
       */
      get isInLeapYear() {
        return isLeapYear2(this.year);
      }
      /**
       * Returns the number of days in this DateTime's month
       * @example DateTime.local(2016, 2).daysInMonth //=> 29
       * @example DateTime.local(2016, 3).daysInMonth //=> 31
       * @type {number}
       */
      get daysInMonth() {
        return daysInMonth2(this.year, this.month);
      }
      /**
       * Returns the number of days in this DateTime's year
       * @example DateTime.local(2016).daysInYear //=> 366
       * @example DateTime.local(2013).daysInYear //=> 365
       * @type {number}
       */
      get daysInYear() {
        return this.isValid ? daysInYear2(this.year) : NaN;
      }
      /**
       * Returns the number of weeks in this DateTime's year
       * @see https://en.wikipedia.org/wiki/ISO_week_date
       * @example DateTime.local(2004).weeksInWeekYear //=> 53
       * @example DateTime.local(2013).weeksInWeekYear //=> 52
       * @type {number}
       */
      get weeksInWeekYear() {
        return this.isValid ? weeksInWeekYear2(this.weekYear) : NaN;
      }
      /**
       * Returns the resolved Intl options for this DateTime.
       * This is useful in understanding the behavior of formatting methods
       * @param {Object} opts - the same options as toLocaleString
       * @return {Object}
       */
      resolvedLocaleOptions(opts = {}) {
        const { locale, numberingSystem, calendar } = Formatter2.create(
          this.loc.clone(opts),
          opts
        ).resolvedOptions(this);
        return { locale, numberingSystem, outputCalendar: calendar };
      }
      // TRANSFORM
      /**
       * "Set" the DateTime's zone to UTC. Returns a newly-constructed DateTime.
       *
       * Equivalent to {@link DateTime#setZone}('utc')
       * @param {number} [offset=0] - optionally, an offset from UTC in minutes
       * @param {Object} [opts={}] - options to pass to `setZone()`
       * @return {DateTime}
       */
      toUTC(offset3 = 0, opts = {}) {
        return this.setZone(FixedOffsetZone2.instance(offset3), opts);
      }
      /**
       * "Set" the DateTime's zone to the host's local zone. Returns a newly-constructed DateTime.
       *
       * Equivalent to `setZone('local')`
       * @return {DateTime}
       */
      toLocal() {
        return this.setZone(Settings2.defaultZone);
      }
      /**
       * "Set" the DateTime's zone to specified zone. Returns a newly-constructed DateTime.
       *
       * By default, the setter keeps the underlying time the same (as in, the same timestamp), but the new instance will report different local times and consider DSTs when making computations, as with {@link DateTime#plus}. You may wish to use {@link DateTime#toLocal} and {@link DateTime#toUTC} which provide simple convenience wrappers for commonly used zones.
       * @param {string|Zone} [zone='local'] - a zone identifier. As a string, that can be any IANA zone supported by the host environment, or a fixed-offset name of the form 'UTC+3', or the strings 'local' or 'utc'. You may also supply an instance of a {@link DateTime#Zone} class.
       * @param {Object} opts - options
       * @param {boolean} [opts.keepLocalTime=false] - If true, adjust the underlying time so that the local time stays the same, but in the target zone. You should rarely need this.
       * @return {DateTime}
       */
      setZone(zone, { keepLocalTime = false, keepCalendarTime = false } = {}) {
        zone = normalizeZone2(zone, Settings2.defaultZone);
        if (zone.equals(this.zone)) {
          return this;
        } else if (!zone.isValid) {
          return _DateTime.invalid(unsupportedZone2(zone));
        } else {
          let newTS = this.ts;
          if (keepLocalTime || keepCalendarTime) {
            const offsetGuess = zone.offset(this.ts);
            const asObj = this.toObject();
            [newTS] = objToTS2(asObj, offsetGuess, zone);
          }
          return clone3(this, { ts: newTS, zone });
        }
      }
      /**
       * "Set" the locale, numberingSystem, or outputCalendar. Returns a newly-constructed DateTime.
       * @param {Object} properties - the properties to set
       * @example DateTime.local(2017, 5, 25).reconfigure({ locale: 'en-GB' })
       * @return {DateTime}
       */
      reconfigure({ locale, numberingSystem, outputCalendar } = {}) {
        const loc = this.loc.clone({ locale, numberingSystem, outputCalendar });
        return clone3(this, { loc });
      }
      /**
       * "Set" the locale. Returns a newly-constructed DateTime.
       * Just a convenient alias for reconfigure({ locale })
       * @example DateTime.local(2017, 5, 25).setLocale('en-GB')
       * @return {DateTime}
       */
      setLocale(locale) {
        return this.reconfigure({ locale });
      }
      /**
       * "Set" the values of specified units. Returns a newly-constructed DateTime.
       * You can only set units with this method; for "setting" metadata, see {@link DateTime#reconfigure} and {@link DateTime#setZone}.
       * @param {Object} values - a mapping of units to numbers
       * @example dt.set({ year: 2017 })
       * @example dt.set({ hour: 8, minute: 30 })
       * @example dt.set({ weekday: 5 })
       * @example dt.set({ year: 2005, ordinal: 234 })
       * @return {DateTime}
       */
      set(values) {
        if (!this.isValid) return this;
        const normalized = normalizeObject2(values, normalizeUnit2), settingWeekStuff = !isUndefined2(normalized.weekYear) || !isUndefined2(normalized.weekNumber) || !isUndefined2(normalized.weekday), containsOrdinal = !isUndefined2(normalized.ordinal), containsGregorYear = !isUndefined2(normalized.year), containsGregorMD = !isUndefined2(normalized.month) || !isUndefined2(normalized.day), containsGregor = containsGregorYear || containsGregorMD, definiteWeekDef = normalized.weekYear || normalized.weekNumber;
        if ((containsGregor || containsOrdinal) && definiteWeekDef) {
          throw new ConflictingSpecificationError2(
            "Can't mix weekYear/weekNumber units with year/month/day or ordinals"
          );
        }
        if (containsGregorMD && containsOrdinal) {
          throw new ConflictingSpecificationError2("Can't mix ordinal dates with month/day");
        }
        let mixed;
        if (settingWeekStuff) {
          mixed = weekToGregorian2({ ...gregorianToWeek2(this.c), ...normalized });
        } else if (!isUndefined2(normalized.ordinal)) {
          mixed = ordinalToGregorian2({ ...gregorianToOrdinal2(this.c), ...normalized });
        } else {
          mixed = { ...this.toObject(), ...normalized };
          if (isUndefined2(normalized.day)) {
            mixed.day = Math.min(daysInMonth2(mixed.year, mixed.month), mixed.day);
          }
        }
        const [ts, o] = objToTS2(mixed, this.o, this.zone);
        return clone3(this, { ts, o });
      }
      /**
       * Add a period of time to this DateTime and return the resulting DateTime
       *
       * Adding hours, minutes, seconds, or milliseconds increases the timestamp by the right number of milliseconds. Adding days, months, or years shifts the calendar, accounting for DSTs and leap years along the way. Thus, `dt.plus({ hours: 24 })` may result in a different time than `dt.plus({ days: 1 })` if there's a DST shift in between.
       * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
       * @example DateTime.now().plus(123) //~> in 123 milliseconds
       * @example DateTime.now().plus({ minutes: 15 }) //~> in 15 minutes
       * @example DateTime.now().plus({ days: 1 }) //~> this time tomorrow
       * @example DateTime.now().plus({ days: -1 }) //~> this time yesterday
       * @example DateTime.now().plus({ hours: 3, minutes: 13 }) //~> in 3 hr, 13 min
       * @example DateTime.now().plus(Duration.fromObject({ hours: 3, minutes: 13 })) //~> in 3 hr, 13 min
       * @return {DateTime}
       */
      plus(duration) {
        if (!this.isValid) return this;
        const dur = Duration2.fromDurationLike(duration);
        return clone3(this, adjustTime2(this, dur));
      }
      /**
       * Subtract a period of time to this DateTime and return the resulting DateTime
       * See {@link DateTime#plus}
       * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
       @return {DateTime}
       */
      minus(duration) {
        if (!this.isValid) return this;
        const dur = Duration2.fromDurationLike(duration).negate();
        return clone3(this, adjustTime2(this, dur));
      }
      /**
       * "Set" this DateTime to the beginning of a unit of time.
       * @param {string} unit - The unit to go to the beginning of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'.
       * @example DateTime.local(2014, 3, 3).startOf('month').toISODate(); //=> '2014-03-01'
       * @example DateTime.local(2014, 3, 3).startOf('year').toISODate(); //=> '2014-01-01'
       * @example DateTime.local(2014, 3, 3).startOf('week').toISODate(); //=> '2014-03-03', weeks always start on Mondays
       * @example DateTime.local(2014, 3, 3, 5, 30).startOf('day').toISOTime(); //=> '00:00.000-05:00'
       * @example DateTime.local(2014, 3, 3, 5, 30).startOf('hour').toISOTime(); //=> '05:00:00.000-05:00'
       * @return {DateTime}
       */
      startOf(unit) {
        if (!this.isValid) return this;
        const o = {}, normalizedUnit = Duration2.normalizeUnit(unit);
        switch (normalizedUnit) {
          case "years":
            o.month = 1;
          // falls through
          case "quarters":
          case "months":
            o.day = 1;
          // falls through
          case "weeks":
          case "days":
            o.hour = 0;
          // falls through
          case "hours":
            o.minute = 0;
          // falls through
          case "minutes":
            o.second = 0;
          // falls through
          case "seconds":
            o.millisecond = 0;
            break;
        }
        if (normalizedUnit === "weeks") {
          o.weekday = 1;
        }
        if (normalizedUnit === "quarters") {
          const q = Math.ceil(this.month / 3);
          o.month = (q - 1) * 3 + 1;
        }
        return this.set(o);
      }
      /**
       * "Set" this DateTime to the end (meaning the last millisecond) of a unit of time
       * @param {string} unit - The unit to go to the end of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'.
       * @example DateTime.local(2014, 3, 3).endOf('month').toISO(); //=> '2014-03-31T23:59:59.999-05:00'
       * @example DateTime.local(2014, 3, 3).endOf('year').toISO(); //=> '2014-12-31T23:59:59.999-05:00'
       * @example DateTime.local(2014, 3, 3).endOf('week').toISO(); // => '2014-03-09T23:59:59.999-05:00', weeks start on Mondays
       * @example DateTime.local(2014, 3, 3, 5, 30).endOf('day').toISO(); //=> '2014-03-03T23:59:59.999-05:00'
       * @example DateTime.local(2014, 3, 3, 5, 30).endOf('hour').toISO(); //=> '2014-03-03T05:59:59.999-05:00'
       * @return {DateTime}
       */
      endOf(unit) {
        return this.isValid ? this.plus({ [unit]: 1 }).startOf(unit).minus(1) : this;
      }
      // OUTPUT
      /**
       * Returns a string representation of this DateTime formatted according to the specified format string.
       * **You may not want this.** See {@link DateTime#toLocaleString} for a more flexible formatting tool. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/#/formatting?id=table-of-tokens).
       * Defaults to en-US if no locale has been specified, regardless of the system's locale.
       * @param {string} fmt - the format string
       * @param {Object} opts - opts to override the configuration options on this DateTime
       * @example DateTime.now().toFormat('yyyy LLL dd') //=> '2017 Apr 22'
       * @example DateTime.now().setLocale('fr').toFormat('yyyy LLL dd') //=> '2017 avr. 22'
       * @example DateTime.now().toFormat('yyyy LLL dd', { locale: "fr" }) //=> '2017 avr. 22'
       * @example DateTime.now().toFormat("HH 'hours and' mm 'minutes'") //=> '20 hours and 55 minutes'
       * @return {string}
       */
      toFormat(fmt, opts = {}) {
        return this.isValid ? Formatter2.create(this.loc.redefaultToEN(opts)).formatDateTimeFromString(this, fmt) : INVALID4;
      }
      /**
       * Returns a localized string representing this date. Accepts the same options as the Intl.DateTimeFormat constructor and any presets defined by Luxon, such as `DateTime.DATE_FULL` or `DateTime.TIME_SIMPLE`.
       * The exact behavior of this method is browser-specific, but in general it will return an appropriate representation
       * of the DateTime in the assigned locale.
       * Defaults to the system's locale if no locale has been specified
       * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
       * @param formatOpts {Object} - Intl.DateTimeFormat constructor options and configuration options
       * @param {Object} opts - opts to override the configuration options on this DateTime
       * @example DateTime.now().toLocaleString(); //=> 4/20/2017
       * @example DateTime.now().setLocale('en-gb').toLocaleString(); //=> '20/04/2017'
       * @example DateTime.now().toLocaleString(DateTime.DATE_FULL); //=> 'April 20, 2017'
       * @example DateTime.now().toLocaleString(DateTime.DATE_FULL, { locale: 'fr' }); //=> '28 août 2022'
       * @example DateTime.now().toLocaleString(DateTime.TIME_SIMPLE); //=> '11:32 AM'
       * @example DateTime.now().toLocaleString(DateTime.DATETIME_SHORT); //=> '4/20/2017, 11:32 AM'
       * @example DateTime.now().toLocaleString({ weekday: 'long', month: 'long', day: '2-digit' }); //=> 'Thursday, April 20'
       * @example DateTime.now().toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }); //=> 'Thu, Apr 20, 11:27 AM'
       * @example DateTime.now().toLocaleString({ hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }); //=> '11:32'
       * @return {string}
       */
      toLocaleString(formatOpts = DATE_SHORT2, opts = {}) {
        return this.isValid ? Formatter2.create(this.loc.clone(opts), formatOpts).formatDateTime(this) : INVALID4;
      }
      /**
       * Returns an array of format "parts", meaning individual tokens along with metadata. This is allows callers to post-process individual sections of the formatted output.
       * Defaults to the system's locale if no locale has been specified
       * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/formatToParts
       * @param opts {Object} - Intl.DateTimeFormat constructor options, same as `toLocaleString`.
       * @example DateTime.now().toLocaleParts(); //=> [
       *                                   //=>   { type: 'day', value: '25' },
       *                                   //=>   { type: 'literal', value: '/' },
       *                                   //=>   { type: 'month', value: '05' },
       *                                   //=>   { type: 'literal', value: '/' },
       *                                   //=>   { type: 'year', value: '1982' }
       *                                   //=> ]
       */
      toLocaleParts(opts = {}) {
        return this.isValid ? Formatter2.create(this.loc.clone(opts), opts).formatDateTimeParts(this) : [];
      }
      /**
       * Returns an ISO 8601-compliant string representation of this DateTime
       * @param {Object} opts - options
       * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0
       * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0
       * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'
       * @param {boolean} [opts.extendedZone=false] - add the time zone format extension
       * @param {string} [opts.format='extended'] - choose between the basic and extended format
       * @example DateTime.utc(1983, 5, 25).toISO() //=> '1982-05-25T00:00:00.000Z'
       * @example DateTime.now().toISO() //=> '2017-04-22T20:47:05.335-04:00'
       * @example DateTime.now().toISO({ includeOffset: false }) //=> '2017-04-22T20:47:05.335'
       * @example DateTime.now().toISO({ format: 'basic' }) //=> '20170422T204705.335-0400'
       * @return {string}
       */
      toISO({
        format = "extended",
        suppressSeconds = false,
        suppressMilliseconds = false,
        includeOffset = true,
        extendedZone = false
      } = {}) {
        if (!this.isValid) {
          return null;
        }
        const ext = format === "extended";
        let c = toISODate2(this, ext);
        c += "T";
        c += toISOTime2(this, ext, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone);
        return c;
      }
      /**
       * Returns an ISO 8601-compliant string representation of this DateTime's date component
       * @param {Object} opts - options
       * @param {string} [opts.format='extended'] - choose between the basic and extended format
       * @example DateTime.utc(1982, 5, 25).toISODate() //=> '1982-05-25'
       * @example DateTime.utc(1982, 5, 25).toISODate({ format: 'basic' }) //=> '19820525'
       * @return {string}
       */
      toISODate({ format = "extended" } = {}) {
        if (!this.isValid) {
          return null;
        }
        return toISODate2(this, format === "extended");
      }
      /**
       * Returns an ISO 8601-compliant string representation of this DateTime's week date
       * @example DateTime.utc(1982, 5, 25).toISOWeekDate() //=> '1982-W21-2'
       * @return {string}
       */
      toISOWeekDate() {
        return toTechFormat2(this, "kkkk-'W'WW-c");
      }
      /**
       * Returns an ISO 8601-compliant string representation of this DateTime's time component
       * @param {Object} opts - options
       * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0
       * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0
       * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'
       * @param {boolean} [opts.extendedZone=true] - add the time zone format extension
       * @param {boolean} [opts.includePrefix=false] - include the `T` prefix
       * @param {string} [opts.format='extended'] - choose between the basic and extended format
       * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime() //=> '07:34:19.361Z'
       * @example DateTime.utc().set({ hour: 7, minute: 34, seconds: 0, milliseconds: 0 }).toISOTime({ suppressSeconds: true }) //=> '07:34Z'
       * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ format: 'basic' }) //=> '073419.361Z'
       * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ includePrefix: true }) //=> 'T07:34:19.361Z'
       * @return {string}
       */
      toISOTime({
        suppressMilliseconds = false,
        suppressSeconds = false,
        includeOffset = true,
        includePrefix = false,
        extendedZone = false,
        format = "extended"
      } = {}) {
        if (!this.isValid) {
          return null;
        }
        let c = includePrefix ? "T" : "";
        return c + toISOTime2(
          this,
          format === "extended",
          suppressSeconds,
          suppressMilliseconds,
          includeOffset,
          extendedZone
        );
      }
      /**
       * Returns an RFC 2822-compatible string representation of this DateTime
       * @example DateTime.utc(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 +0000'
       * @example DateTime.local(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 -0400'
       * @return {string}
       */
      toRFC2822() {
        return toTechFormat2(this, "EEE, dd LLL yyyy HH:mm:ss ZZZ", false);
      }
      /**
       * Returns a string representation of this DateTime appropriate for use in HTTP headers. The output is always expressed in GMT.
       * Specifically, the string conforms to RFC 1123.
       * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1
       * @example DateTime.utc(2014, 7, 13).toHTTP() //=> 'Sun, 13 Jul 2014 00:00:00 GMT'
       * @example DateTime.utc(2014, 7, 13, 19).toHTTP() //=> 'Sun, 13 Jul 2014 19:00:00 GMT'
       * @return {string}
       */
      toHTTP() {
        return toTechFormat2(this.toUTC(), "EEE, dd LLL yyyy HH:mm:ss 'GMT'");
      }
      /**
       * Returns a string representation of this DateTime appropriate for use in SQL Date
       * @example DateTime.utc(2014, 7, 13).toSQLDate() //=> '2014-07-13'
       * @return {string}
       */
      toSQLDate() {
        if (!this.isValid) {
          return null;
        }
        return toISODate2(this, true);
      }
      /**
       * Returns a string representation of this DateTime appropriate for use in SQL Time
       * @param {Object} opts - options
       * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset.
       * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'
       * @param {boolean} [opts.includeOffsetSpace=true] - include the space between the time and the offset, such as '05:15:16.345 -04:00'
       * @example DateTime.utc().toSQL() //=> '05:15:16.345'
       * @example DateTime.now().toSQL() //=> '05:15:16.345 -04:00'
       * @example DateTime.now().toSQL({ includeOffset: false }) //=> '05:15:16.345'
       * @example DateTime.now().toSQL({ includeZone: false }) //=> '05:15:16.345 America/New_York'
       * @return {string}
       */
      toSQLTime({ includeOffset = true, includeZone = false, includeOffsetSpace = true } = {}) {
        let fmt = "HH:mm:ss.SSS";
        if (includeZone || includeOffset) {
          if (includeOffsetSpace) {
            fmt += " ";
          }
          if (includeZone) {
            fmt += "z";
          } else if (includeOffset) {
            fmt += "ZZ";
          }
        }
        return toTechFormat2(this, fmt, true);
      }
      /**
       * Returns a string representation of this DateTime appropriate for use in SQL DateTime
       * @param {Object} opts - options
       * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset.
       * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'
       * @param {boolean} [opts.includeOffsetSpace=true] - include the space between the time and the offset, such as '05:15:16.345 -04:00'
       * @example DateTime.utc(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 Z'
       * @example DateTime.local(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 -04:00'
       * @example DateTime.local(2014, 7, 13).toSQL({ includeOffset: false }) //=> '2014-07-13 00:00:00.000'
       * @example DateTime.local(2014, 7, 13).toSQL({ includeZone: true }) //=> '2014-07-13 00:00:00.000 America/New_York'
       * @return {string}
       */
      toSQL(opts = {}) {
        if (!this.isValid) {
          return null;
        }
        return `${this.toSQLDate()} ${this.toSQLTime(opts)}`;
      }
      /**
       * Returns a string representation of this DateTime appropriate for debugging
       * @return {string}
       */
      toString() {
        return this.isValid ? this.toISO() : INVALID4;
      }
      /**
       * Returns the epoch milliseconds of this DateTime. Alias of {@link DateTime#toMillis}
       * @return {number}
       */
      valueOf() {
        return this.toMillis();
      }
      /**
       * Returns the epoch milliseconds of this DateTime.
       * @return {number}
       */
      toMillis() {
        return this.isValid ? this.ts : NaN;
      }
      /**
       * Returns the epoch seconds of this DateTime.
       * @return {number}
       */
      toSeconds() {
        return this.isValid ? this.ts / 1e3 : NaN;
      }
      /**
       * Returns the epoch seconds (as a whole number) of this DateTime.
       * @return {number}
       */
      toUnixInteger() {
        return this.isValid ? Math.floor(this.ts / 1e3) : NaN;
      }
      /**
       * Returns an ISO 8601 representation of this DateTime appropriate for use in JSON.
       * @return {string}
       */
      toJSON() {
        return this.toISO();
      }
      /**
       * Returns a BSON serializable equivalent to this DateTime.
       * @return {Date}
       */
      toBSON() {
        return this.toJSDate();
      }
      /**
       * Returns a JavaScript object with this DateTime's year, month, day, and so on.
       * @param opts - options for generating the object
       * @param {boolean} [opts.includeConfig=false] - include configuration attributes in the output
       * @example DateTime.now().toObject() //=> { year: 2017, month: 4, day: 22, hour: 20, minute: 49, second: 42, millisecond: 268 }
       * @return {Object}
       */
      toObject(opts = {}) {
        if (!this.isValid) return {};
        const base = { ...this.c };
        if (opts.includeConfig) {
          base.outputCalendar = this.outputCalendar;
          base.numberingSystem = this.loc.numberingSystem;
          base.locale = this.loc.locale;
        }
        return base;
      }
      /**
       * Returns a JavaScript Date equivalent to this DateTime.
       * @return {Date}
       */
      toJSDate() {
        return new Date(this.isValid ? this.ts : NaN);
      }
      // COMPARE
      /**
       * Return the difference between two DateTimes as a Duration.
       * @param {DateTime} otherDateTime - the DateTime to compare this one to
       * @param {string|string[]} [unit=['milliseconds']] - the unit or array of units (such as 'hours' or 'days') to include in the duration.
       * @param {Object} opts - options that affect the creation of the Duration
       * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
       * @example
       * var i1 = DateTime.fromISO('1982-05-25T09:45'),
       *     i2 = DateTime.fromISO('1983-10-14T10:30');
       * i2.diff(i1).toObject() //=> { milliseconds: 43807500000 }
       * i2.diff(i1, 'hours').toObject() //=> { hours: 12168.75 }
       * i2.diff(i1, ['months', 'days']).toObject() //=> { months: 16, days: 19.03125 }
       * i2.diff(i1, ['months', 'days', 'hours']).toObject() //=> { months: 16, days: 19, hours: 0.75 }
       * @return {Duration}
       */
      diff(otherDateTime, unit = "milliseconds", opts = {}) {
        if (!this.isValid || !otherDateTime.isValid) {
          return Duration2.invalid("created by diffing an invalid DateTime");
        }
        const durOpts = { locale: this.locale, numberingSystem: this.numberingSystem, ...opts };
        const units = maybeArray2(unit).map(Duration2.normalizeUnit), otherIsLater = otherDateTime.valueOf() > this.valueOf(), earlier = otherIsLater ? this : otherDateTime, later = otherIsLater ? otherDateTime : this, diffed = diff(earlier, later, units, durOpts);
        return otherIsLater ? diffed.negate() : diffed;
      }
      /**
       * Return the difference between this DateTime and right now.
       * See {@link DateTime#diff}
       * @param {string|string[]} [unit=['milliseconds']] - the unit or units units (such as 'hours' or 'days') to include in the duration
       * @param {Object} opts - options that affect the creation of the Duration
       * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
       * @return {Duration}
       */
      diffNow(unit = "milliseconds", opts = {}) {
        return this.diff(_DateTime.now(), unit, opts);
      }
      /**
       * Return an Interval spanning between this DateTime and another DateTime
       * @param {DateTime} otherDateTime - the other end point of the Interval
       * @return {Interval}
       */
      until(otherDateTime) {
        return this.isValid ? Interval2.fromDateTimes(this, otherDateTime) : this;
      }
      /**
       * Return whether this DateTime is in the same unit of time as another DateTime.
       * Higher-order units must also be identical for this function to return `true`.
       * Note that time zones are **ignored** in this comparison, which compares the **local** calendar time. Use {@link DateTime#setZone} to convert one of the dates if needed.
       * @param {DateTime} otherDateTime - the other DateTime
       * @param {string} unit - the unit of time to check sameness on
       * @example DateTime.now().hasSame(otherDT, 'day'); //~> true if otherDT is in the same current calendar day
       * @return {boolean}
       */
      hasSame(otherDateTime, unit) {
        if (!this.isValid) return false;
        const inputMs = otherDateTime.valueOf();
        const adjustedToZone = this.setZone(otherDateTime.zone, { keepLocalTime: true });
        return adjustedToZone.startOf(unit) <= inputMs && inputMs <= adjustedToZone.endOf(unit);
      }
      /**
       * Equality check
       * Two DateTimes are equal if and only if they represent the same millisecond, have the same zone and location, and are both valid.
       * To compare just the millisecond values, use `+dt1 === +dt2`.
       * @param {DateTime} other - the other DateTime
       * @return {boolean}
       */
      equals(other) {
        return this.isValid && other.isValid && this.valueOf() === other.valueOf() && this.zone.equals(other.zone) && this.loc.equals(other.loc);
      }
      /**
       * Returns a string representation of a this time relative to now, such as "in two days". Can only internationalize if your
       * platform supports Intl.RelativeTimeFormat. Rounds down by default.
       * @param {Object} options - options that affect the output
       * @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now.
       * @param {string} [options.style="long"] - the style of units, must be "long", "short", or "narrow"
       * @param {string|string[]} options.unit - use a specific unit or array of units; if omitted, or an array, the method will pick the best unit. Use an array or one of "years", "quarters", "months", "weeks", "days", "hours", "minutes", or "seconds"
       * @param {boolean} [options.round=true] - whether to round the numbers in the output.
       * @param {number} [options.padding=0] - padding in milliseconds. This allows you to round up the result if it fits inside the threshold. Don't use in combination with {round: false} because the decimal output will include the padding.
       * @param {string} options.locale - override the locale of this DateTime
       * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this
       * @example DateTime.now().plus({ days: 1 }).toRelative() //=> "in 1 day"
       * @example DateTime.now().setLocale("es").toRelative({ days: 1 }) //=> "dentro de 1 día"
       * @example DateTime.now().plus({ days: 1 }).toRelative({ locale: "fr" }) //=> "dans 23 heures"
       * @example DateTime.now().minus({ days: 2 }).toRelative() //=> "2 days ago"
       * @example DateTime.now().minus({ days: 2 }).toRelative({ unit: "hours" }) //=> "48 hours ago"
       * @example DateTime.now().minus({ hours: 36 }).toRelative({ round: false }) //=> "1.5 days ago"
       */
      toRelative(options = {}) {
        if (!this.isValid) return null;
        const base = options.base || _DateTime.fromObject({}, { zone: this.zone }), padding = options.padding ? this < base ? -options.padding : options.padding : 0;
        let units = ["years", "months", "days", "hours", "minutes", "seconds"];
        let unit = options.unit;
        if (Array.isArray(options.unit)) {
          units = options.unit;
          unit = void 0;
        }
        return diffRelative2(base, this.plus(padding), {
          ...options,
          numeric: "always",
          units,
          unit
        });
      }
      /**
       * Returns a string representation of this date relative to today, such as "yesterday" or "next month".
       * Only internationalizes on platforms that supports Intl.RelativeTimeFormat.
       * @param {Object} options - options that affect the output
       * @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now.
       * @param {string} options.locale - override the locale of this DateTime
       * @param {string} options.unit - use a specific unit; if omitted, the method will pick the unit. Use one of "years", "quarters", "months", "weeks", or "days"
       * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this
       * @example DateTime.now().plus({ days: 1 }).toRelativeCalendar() //=> "tomorrow"
       * @example DateTime.now().setLocale("es").plus({ days: 1 }).toRelative() //=> ""mañana"
       * @example DateTime.now().plus({ days: 1 }).toRelativeCalendar({ locale: "fr" }) //=> "demain"
       * @example DateTime.now().minus({ days: 2 }).toRelativeCalendar() //=> "2 days ago"
       */
      toRelativeCalendar(options = {}) {
        if (!this.isValid) return null;
        return diffRelative2(options.base || _DateTime.fromObject({}, { zone: this.zone }), this, {
          ...options,
          numeric: "auto",
          units: ["years", "months", "days"],
          calendary: true
        });
      }
      /**
       * Return the min of several date times
       * @param {...DateTime} dateTimes - the DateTimes from which to choose the minimum
       * @return {DateTime} the min DateTime, or undefined if called with no argument
       */
      static min(...dateTimes) {
        if (!dateTimes.every(_DateTime.isDateTime)) {
          throw new InvalidArgumentError2("min requires all arguments be DateTimes");
        }
        return bestBy2(dateTimes, (i) => i.valueOf(), Math.min);
      }
      /**
       * Return the max of several date times
       * @param {...DateTime} dateTimes - the DateTimes from which to choose the maximum
       * @return {DateTime} the max DateTime, or undefined if called with no argument
       */
      static max(...dateTimes) {
        if (!dateTimes.every(_DateTime.isDateTime)) {
          throw new InvalidArgumentError2("max requires all arguments be DateTimes");
        }
        return bestBy2(dateTimes, (i) => i.valueOf(), Math.max);
      }
      // MISC
      /**
       * Explain how a string would be parsed by fromFormat()
       * @param {string} text - the string to parse
       * @param {string} fmt - the format the string is expected to be in (see description)
       * @param {Object} options - options taken by fromFormat()
       * @return {Object}
       */
      static fromFormatExplain(text2, fmt, options = {}) {
        const { locale = null, numberingSystem = null } = options, localeToUse = Locale2.fromOpts({
          locale,
          numberingSystem,
          defaultToEN: true
        });
        return explainFromTokens2(localeToUse, text2, fmt);
      }
      /**
       * @deprecated use fromFormatExplain instead
       */
      static fromStringExplain(text2, fmt, options = {}) {
        return _DateTime.fromFormatExplain(text2, fmt, options);
      }
      // FORMAT PRESETS
      /**
       * {@link DateTime#toLocaleString} format like 10/14/1983
       * @type {Object}
       */
      static get DATE_SHORT() {
        return DATE_SHORT2;
      }
      /**
       * {@link DateTime#toLocaleString} format like 'Oct 14, 1983'
       * @type {Object}
       */
      static get DATE_MED() {
        return DATE_MED2;
      }
      /**
       * {@link DateTime#toLocaleString} format like 'Fri, Oct 14, 1983'
       * @type {Object}
       */
      static get DATE_MED_WITH_WEEKDAY() {
        return DATE_MED_WITH_WEEKDAY2;
      }
      /**
       * {@link DateTime#toLocaleString} format like 'October 14, 1983'
       * @type {Object}
       */
      static get DATE_FULL() {
        return DATE_FULL2;
      }
      /**
       * {@link DateTime#toLocaleString} format like 'Tuesday, October 14, 1983'
       * @type {Object}
       */
      static get DATE_HUGE() {
        return DATE_HUGE2;
      }
      /**
       * {@link DateTime#toLocaleString} format like '09:30 AM'. Only 12-hour if the locale is.
       * @type {Object}
       */
      static get TIME_SIMPLE() {
        return TIME_SIMPLE2;
      }
      /**
       * {@link DateTime#toLocaleString} format like '09:30:23 AM'. Only 12-hour if the locale is.
       * @type {Object}
       */
      static get TIME_WITH_SECONDS() {
        return TIME_WITH_SECONDS2;
      }
      /**
       * {@link DateTime#toLocaleString} format like '09:30:23 AM EDT'. Only 12-hour if the locale is.
       * @type {Object}
       */
      static get TIME_WITH_SHORT_OFFSET() {
        return TIME_WITH_SHORT_OFFSET2;
      }
      /**
       * {@link DateTime#toLocaleString} format like '09:30:23 AM Eastern Daylight Time'. Only 12-hour if the locale is.
       * @type {Object}
       */
      static get TIME_WITH_LONG_OFFSET() {
        return TIME_WITH_LONG_OFFSET2;
      }
      /**
       * {@link DateTime#toLocaleString} format like '09:30', always 24-hour.
       * @type {Object}
       */
      static get TIME_24_SIMPLE() {
        return TIME_24_SIMPLE2;
      }
      /**
       * {@link DateTime#toLocaleString} format like '09:30:23', always 24-hour.
       * @type {Object}
       */
      static get TIME_24_WITH_SECONDS() {
        return TIME_24_WITH_SECONDS2;
      }
      /**
       * {@link DateTime#toLocaleString} format like '09:30:23 EDT', always 24-hour.
       * @type {Object}
       */
      static get TIME_24_WITH_SHORT_OFFSET() {
        return TIME_24_WITH_SHORT_OFFSET2;
      }
      /**
       * {@link DateTime#toLocaleString} format like '09:30:23 Eastern Daylight Time', always 24-hour.
       * @type {Object}
       */
      static get TIME_24_WITH_LONG_OFFSET() {
        return TIME_24_WITH_LONG_OFFSET2;
      }
      /**
       * {@link DateTime#toLocaleString} format like '10/14/1983, 9:30 AM'. Only 12-hour if the locale is.
       * @type {Object}
       */
      static get DATETIME_SHORT() {
        return DATETIME_SHORT2;
      }
      /**
       * {@link DateTime#toLocaleString} format like '10/14/1983, 9:30:33 AM'. Only 12-hour if the locale is.
       * @type {Object}
       */
      static get DATETIME_SHORT_WITH_SECONDS() {
        return DATETIME_SHORT_WITH_SECONDS2;
      }
      /**
       * {@link DateTime#toLocaleString} format like 'Oct 14, 1983, 9:30 AM'. Only 12-hour if the locale is.
       * @type {Object}
       */
      static get DATETIME_MED() {
        return DATETIME_MED2;
      }
      /**
       * {@link DateTime#toLocaleString} format like 'Oct 14, 1983, 9:30:33 AM'. Only 12-hour if the locale is.
       * @type {Object}
       */
      static get DATETIME_MED_WITH_SECONDS() {
        return DATETIME_MED_WITH_SECONDS2;
      }
      /**
       * {@link DateTime#toLocaleString} format like 'Fri, 14 Oct 1983, 9:30 AM'. Only 12-hour if the locale is.
       * @type {Object}
       */
      static get DATETIME_MED_WITH_WEEKDAY() {
        return DATETIME_MED_WITH_WEEKDAY2;
      }
      /**
       * {@link DateTime#toLocaleString} format like 'October 14, 1983, 9:30 AM EDT'. Only 12-hour if the locale is.
       * @type {Object}
       */
      static get DATETIME_FULL() {
        return DATETIME_FULL2;
      }
      /**
       * {@link DateTime#toLocaleString} format like 'October 14, 1983, 9:30:33 AM EDT'. Only 12-hour if the locale is.
       * @type {Object}
       */
      static get DATETIME_FULL_WITH_SECONDS() {
        return DATETIME_FULL_WITH_SECONDS2;
      }
      /**
       * {@link DateTime#toLocaleString} format like 'Friday, October 14, 1983, 9:30 AM Eastern Daylight Time'. Only 12-hour if the locale is.
       * @type {Object}
       */
      static get DATETIME_HUGE() {
        return DATETIME_HUGE2;
      }
      /**
       * {@link DateTime#toLocaleString} format like 'Friday, October 14, 1983, 9:30:33 AM Eastern Daylight Time'. Only 12-hour if the locale is.
       * @type {Object}
       */
      static get DATETIME_HUGE_WITH_SECONDS() {
        return DATETIME_HUGE_WITH_SECONDS2;
      }
    };
    function friendlyDateTime2(dateTimeish) {
      if (DateTime2.isDateTime(dateTimeish)) {
        return dateTimeish;
      } else if (dateTimeish && dateTimeish.valueOf && isNumber2(dateTimeish.valueOf())) {
        return DateTime2.fromJSDate(dateTimeish);
      } else if (dateTimeish && typeof dateTimeish === "object") {
        return DateTime2.fromObject(dateTimeish);
      } else {
        throw new InvalidArgumentError2(
          `Unknown datetime argument: ${dateTimeish}, of type ${typeof dateTimeish}`
        );
      }
    }
    var DEFAULT_QUERY_SETTINGS = {
      renderNullAs: "\\-",
      taskCompletionTracking: false,
      taskCompletionUseEmojiShorthand: false,
      taskCompletionText: "completion",
      taskCompletionDateFormat: "yyyy-MM-dd",
      recursiveSubTaskCompletion: false,
      warnOnEmptyResult: true,
      refreshEnabled: true,
      refreshInterval: 2500,
      defaultDateFormat: "MMMM dd, yyyy",
      defaultDateTimeFormat: "h:mm a - MMMM dd, yyyy",
      maxRecursiveRenderDepth: 4,
      tableIdColumnName: "File",
      tableGroupColumnName: "Group",
      showResultCount: true
    };
    var DEFAULT_EXPORT_SETTINGS = {
      allowHtml: true
    };
    ({
      ...DEFAULT_QUERY_SETTINGS,
      ...DEFAULT_EXPORT_SETTINGS,
      ...{
        inlineQueryPrefix: "=",
        inlineJsQueryPrefix: "$=",
        inlineQueriesInCodeblocks: true,
        enableInlineDataview: true,
        enableDataviewJs: false,
        enableInlineDataviewJs: false,
        prettyRenderInlineFields: true,
        prettyRenderInlineFieldsInLivePreview: true,
        dataviewJsKeyword: "dataviewjs"
      }
    });
    var Success = class _Success {
      value;
      successful;
      constructor(value) {
        this.value = value;
        this.successful = true;
      }
      map(f) {
        return new _Success(f(this.value));
      }
      flatMap(f) {
        return f(this.value);
      }
      mapErr(f) {
        return this;
      }
      bimap(succ, _fail) {
        return this.map(succ);
      }
      orElse(_value) {
        return this.value;
      }
      cast() {
        return this;
      }
      orElseThrow(_message) {
        return this.value;
      }
    };
    var Failure = class _Failure {
      error;
      successful;
      constructor(error) {
        this.error = error;
        this.successful = false;
      }
      map(_f) {
        return this;
      }
      flatMap(_f) {
        return this;
      }
      mapErr(f) {
        return new _Failure(f(this.error));
      }
      bimap(_succ, fail) {
        return this.mapErr(fail);
      }
      orElse(value) {
        return value;
      }
      cast() {
        return this;
      }
      orElseThrow(message) {
        if (message)
          throw new Error(message(this.error));
        else
          throw new Error("" + this.error);
      }
    };
    var Result;
    (function(Result2) {
      function success(value) {
        return new Success(value);
      }
      Result2.success = success;
      function failure(error) {
        return new Failure(error);
      }
      Result2.failure = failure;
      function flatMap2(first, second, f) {
        if (first.successful) {
          if (second.successful)
            return f(first.value, second.value);
          else
            return failure(second.error);
        } else {
          return failure(first.error);
        }
      }
      Result2.flatMap2 = flatMap2;
      function map2(first, second, f) {
        return flatMap2(first, second, (a, b) => success(f(a, b)));
      }
      Result2.map2 = map2;
    })(Result || (Result = {}));
    var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : {};
    var parsimmon_umd_min = { exports: {} };
    parsimmon_umd_min.exports;
    (function(module3, exports2) {
      !function(n3, t) {
        module3.exports = t();
      }("undefined" != typeof self ? self : commonjsGlobal, function() {
        return function(n3) {
          var t = {};
          function r(e) {
            if (t[e]) return t[e].exports;
            var u = t[e] = { i: e, l: false, exports: {} };
            return n3[e].call(u.exports, u, u.exports, r), u.l = true, u.exports;
          }
          return r.m = n3, r.c = t, r.d = function(n4, t2, e) {
            r.o(n4, t2) || Object.defineProperty(n4, t2, { configurable: false, enumerable: true, get: e });
          }, r.r = function(n4) {
            Object.defineProperty(n4, "__esModule", { value: true });
          }, r.n = function(n4) {
            var t2 = n4 && n4.__esModule ? function() {
              return n4.default;
            } : function() {
              return n4;
            };
            return r.d(t2, "a", t2), t2;
          }, r.o = function(n4, t2) {
            return Object.prototype.hasOwnProperty.call(n4, t2);
          }, r.p = "", r(r.s = 0);
        }([function(n3, t, r) {
          function e(n4) {
            if (!(this instanceof e)) return new e(n4);
            this._ = n4;
          }
          var u = e.prototype;
          function o(n4, t2) {
            for (var r2 = 0; r2 < n4; r2++) t2(r2);
          }
          function i(n4, t2, r2) {
            return function(n5, t3) {
              o(t3.length, function(r3) {
                n5(t3[r3], r3, t3);
              });
            }(function(r3, e2, u2) {
              t2 = n4(t2, r3, e2, u2);
            }, r2), t2;
          }
          function a(n4, t2) {
            return i(function(t3, r2, e2, u2) {
              return t3.concat([n4(r2, e2, u2)]);
            }, [], t2);
          }
          function f(n4, t2) {
            var r2 = { v: 0, buf: t2 };
            return o(n4, function() {
              var n5;
              r2 = { v: r2.v << 1 | (n5 = r2.buf, n5[0] >> 7), buf: function(n6) {
                var t3 = i(function(n7, t4, r3, e2) {
                  return n7.concat(r3 === e2.length - 1 ? Buffer.from([t4, 0]).readUInt16BE(0) : e2.readUInt16BE(r3));
                }, [], n6);
                return Buffer.from(a(function(n7) {
                  return (n7 << 1 & 65535) >> 8;
                }, t3));
              }(r2.buf) };
            }), r2;
          }
          function c() {
            return "undefined" != typeof Buffer;
          }
          function s3() {
            if (!c()) throw new Error("Buffer global does not exist; please use webpack if you need to parse Buffers in the browser.");
          }
          function l3(n4) {
            s3();
            var t2 = i(function(n5, t3) {
              return n5 + t3;
            }, 0, n4);
            if (t2 % 8 != 0) throw new Error("The bits [" + n4.join(", ") + "] add up to " + t2 + " which is not an even number of bytes; the total should be divisible by 8");
            var r2, u2 = t2 / 8, o2 = (r2 = function(n5) {
              return n5 > 48;
            }, i(function(n5, t3) {
              return n5 || (r2(t3) ? t3 : n5);
            }, null, n4));
            if (o2) throw new Error(o2 + " bit range requested exceeds 48 bit (6 byte) Number max.");
            return new e(function(t3, r3) {
              var e2 = u2 + r3;
              return e2 > t3.length ? x(r3, u2.toString() + " bytes") : b(e2, i(function(n5, t4) {
                var r4 = f(t4, n5.buf);
                return { coll: n5.coll.concat(r4.v), buf: r4.buf };
              }, { coll: [], buf: t3.slice(r3, e2) }, n4).coll);
            });
          }
          function h(n4, t2) {
            return new e(function(r2, e2) {
              return s3(), e2 + t2 > r2.length ? x(e2, t2 + " bytes for " + n4) : b(e2 + t2, r2.slice(e2, e2 + t2));
            });
          }
          function p(n4, t2) {
            if ("number" != typeof (r2 = t2) || Math.floor(r2) !== r2 || t2 < 0 || t2 > 6) throw new Error(n4 + " requires integer length in range [0, 6].");
            var r2;
          }
          function d(n4) {
            return p("uintBE", n4), h("uintBE(" + n4 + ")", n4).map(function(t2) {
              return t2.readUIntBE(0, n4);
            });
          }
          function v(n4) {
            return p("uintLE", n4), h("uintLE(" + n4 + ")", n4).map(function(t2) {
              return t2.readUIntLE(0, n4);
            });
          }
          function g(n4) {
            return p("intBE", n4), h("intBE(" + n4 + ")", n4).map(function(t2) {
              return t2.readIntBE(0, n4);
            });
          }
          function m(n4) {
            return p("intLE", n4), h("intLE(" + n4 + ")", n4).map(function(t2) {
              return t2.readIntLE(0, n4);
            });
          }
          function y(n4) {
            return n4 instanceof e;
          }
          function E(n4) {
            return "[object Array]" === {}.toString.call(n4);
          }
          function w(n4) {
            return c() && Buffer.isBuffer(n4);
          }
          function b(n4, t2) {
            return { status: true, index: n4, value: t2, furthest: -1, expected: [] };
          }
          function x(n4, t2) {
            return E(t2) || (t2 = [t2]), { status: false, index: -1, value: null, furthest: n4, expected: t2 };
          }
          function B(n4, t2) {
            if (!t2) return n4;
            if (n4.furthest > t2.furthest) return n4;
            var r2 = n4.furthest === t2.furthest ? function(n5, t3) {
              if (function() {
                if (void 0 !== e._supportsSet) return e._supportsSet;
                var n6 = "undefined" != typeof Set;
                return e._supportsSet = n6, n6;
              }() && Array.from) {
                for (var r3 = new Set(n5), u2 = 0; u2 < t3.length; u2++) r3.add(t3[u2]);
                var o2 = Array.from(r3);
                return o2.sort(), o2;
              }
              for (var i2 = {}, a2 = 0; a2 < n5.length; a2++) i2[n5[a2]] = true;
              for (var f2 = 0; f2 < t3.length; f2++) i2[t3[f2]] = true;
              var c2 = [];
              for (var s4 in i2) ({}).hasOwnProperty.call(i2, s4) && c2.push(s4);
              return c2.sort(), c2;
            }(n4.expected, t2.expected) : t2.expected;
            return { status: n4.status, index: n4.index, value: n4.value, furthest: t2.furthest, expected: r2 };
          }
          var j = {};
          function S(n4, t2) {
            if (w(n4)) return { offset: t2, line: -1, column: -1 };
            n4 in j || (j[n4] = {});
            for (var r2 = j[n4], e2 = 0, u2 = 0, o2 = 0, i2 = t2; i2 >= 0; ) {
              if (i2 in r2) {
                e2 = r2[i2].line, 0 === o2 && (o2 = r2[i2].lineStart);
                break;
              }
              ("\n" === n4.charAt(i2) || "\r" === n4.charAt(i2) && "\n" !== n4.charAt(i2 + 1)) && (u2++, 0 === o2 && (o2 = i2 + 1)), i2--;
            }
            var a2 = e2 + u2, f2 = t2 - o2;
            return r2[t2] = { line: a2, lineStart: o2 }, { offset: t2, line: a2 + 1, column: f2 + 1 };
          }
          function _(n4) {
            if (!y(n4)) throw new Error("not a parser: " + n4);
          }
          function L(n4, t2) {
            return "string" == typeof n4 ? n4.charAt(t2) : n4[t2];
          }
          function O(n4) {
            if ("number" != typeof n4) throw new Error("not a number: " + n4);
          }
          function k(n4) {
            if ("function" != typeof n4) throw new Error("not a function: " + n4);
          }
          function P(n4) {
            if ("string" != typeof n4) throw new Error("not a string: " + n4);
          }
          var q = 2, A = 3, I = 8, F = 5 * I, M = 4 * I, z = "  ";
          function R(n4, t2) {
            return new Array(t2 + 1).join(n4);
          }
          function U(n4, t2, r2) {
            var e2 = t2 - n4.length;
            return e2 <= 0 ? n4 : R(r2, e2) + n4;
          }
          function W(n4, t2, r2, e2) {
            return { from: n4 - t2 > 0 ? n4 - t2 : 0, to: n4 + r2 > e2 ? e2 : n4 + r2 };
          }
          function D(n4, t2) {
            var r2, e2, u2, o2, f2, c2 = t2.index, s4 = c2.offset, l4 = 1;
            if (s4 === n4.length) return "Got the end of the input";
            if (w(n4)) {
              var h2 = s4 - s4 % I, p2 = s4 - h2, d2 = W(h2, F, M + I, n4.length), v2 = a(function(n5) {
                return a(function(n6) {
                  return U(n6.toString(16), 2, "0");
                }, n5);
              }, function(n5, t3) {
                var r3 = n5.length, e3 = [], u3 = 0;
                if (r3 <= t3) return [n5.slice()];
                for (var o3 = 0; o3 < r3; o3++) e3[u3] || e3.push([]), e3[u3].push(n5[o3]), (o3 + 1) % t3 == 0 && u3++;
                return e3;
              }(n4.slice(d2.from, d2.to).toJSON().data, I));
              o2 = function(n5) {
                return 0 === n5.from && 1 === n5.to ? { from: n5.from, to: n5.to } : { from: n5.from / I, to: Math.floor(n5.to / I) };
              }(d2), e2 = h2 / I, r2 = 3 * p2, p2 >= 4 && (r2 += 1), l4 = 2, u2 = a(function(n5) {
                return n5.length <= 4 ? n5.join(" ") : n5.slice(0, 4).join(" ") + "  " + n5.slice(4).join(" ");
              }, v2), (f2 = (8 * (o2.to > 0 ? o2.to - 1 : o2.to)).toString(16).length) < 2 && (f2 = 2);
            } else {
              var g2 = n4.split(/\r\n|[\n\r\u2028\u2029]/);
              r2 = c2.column - 1, e2 = c2.line - 1, o2 = W(e2, q, A, g2.length), u2 = g2.slice(o2.from, o2.to), f2 = o2.to.toString().length;
            }
            var m2 = e2 - o2.from;
            return w(n4) && (f2 = (8 * (o2.to > 0 ? o2.to - 1 : o2.to)).toString(16).length) < 2 && (f2 = 2), i(function(t3, e3, u3) {
              var i2, a2 = u3 === m2, c3 = a2 ? "> " : z;
              return i2 = w(n4) ? U((8 * (o2.from + u3)).toString(16), f2, "0") : U((o2.from + u3 + 1).toString(), f2, " "), [].concat(t3, [c3 + i2 + " | " + e3], a2 ? [z + R(" ", f2) + " | " + U("", r2, " ") + R("^", l4)] : []);
            }, [], u2).join("\n");
          }
          function N(n4, t2) {
            return ["\n", "-- PARSING FAILED " + R("-", 50), "\n\n", D(n4, t2), "\n\n", (r2 = t2.expected, 1 === r2.length ? "Expected:\n\n" + r2[0] : "Expected one of the following: \n\n" + r2.join(", ")), "\n"].join("");
            var r2;
          }
          function G(n4) {
            return void 0 !== n4.flags ? n4.flags : [n4.global ? "g" : "", n4.ignoreCase ? "i" : "", n4.multiline ? "m" : "", n4.unicode ? "u" : "", n4.sticky ? "y" : ""].join("");
          }
          function C() {
            for (var n4 = [].slice.call(arguments), t2 = n4.length, r2 = 0; r2 < t2; r2 += 1) _(n4[r2]);
            return e(function(r3, e2) {
              for (var u2, o2 = new Array(t2), i2 = 0; i2 < t2; i2 += 1) {
                if (!(u2 = B(n4[i2]._(r3, e2), u2)).status) return u2;
                o2[i2] = u2.value, e2 = u2.index;
              }
              return B(b(e2, o2), u2);
            });
          }
          function J() {
            var n4 = [].slice.call(arguments);
            if (0 === n4.length) throw new Error("seqMap needs at least one argument");
            var t2 = n4.pop();
            return k(t2), C.apply(null, n4).map(function(n5) {
              return t2.apply(null, n5);
            });
          }
          function T() {
            var n4 = [].slice.call(arguments), t2 = n4.length;
            if (0 === t2) return Y("zero alternates");
            for (var r2 = 0; r2 < t2; r2 += 1) _(n4[r2]);
            return e(function(t3, r3) {
              for (var e2, u2 = 0; u2 < n4.length; u2 += 1) if ((e2 = B(n4[u2]._(t3, r3), e2)).status) return e2;
              return e2;
            });
          }
          function V(n4, t2) {
            return H(n4, t2).or(X([]));
          }
          function H(n4, t2) {
            return _(n4), _(t2), J(n4, t2.then(n4).many(), function(n5, t3) {
              return [n5].concat(t3);
            });
          }
          function K(n4) {
            P(n4);
            var t2 = "'" + n4 + "'";
            return e(function(r2, e2) {
              var u2 = e2 + n4.length, o2 = r2.slice(e2, u2);
              return o2 === n4 ? b(u2, o2) : x(e2, t2);
            });
          }
          function Q(n4, t2) {
            !function(n5) {
              if (!(n5 instanceof RegExp)) throw new Error("not a regexp: " + n5);
              for (var t3 = G(n5), r3 = 0; r3 < t3.length; r3++) {
                var e2 = t3.charAt(r3);
                if ("i" !== e2 && "m" !== e2 && "u" !== e2 && "s" !== e2) throw new Error('unsupported regexp flag "' + e2 + '": ' + n5);
              }
            }(n4), arguments.length >= 2 ? O(t2) : t2 = 0;
            var r2 = function(n5) {
              return RegExp("^(?:" + n5.source + ")", G(n5));
            }(n4), u2 = "" + n4;
            return e(function(n5, e2) {
              var o2 = r2.exec(n5.slice(e2));
              if (o2) {
                if (0 <= t2 && t2 <= o2.length) {
                  var i2 = o2[0], a2 = o2[t2];
                  return b(e2 + i2.length, a2);
                }
                return x(e2, "valid match group (0 to " + o2.length + ") in " + u2);
              }
              return x(e2, u2);
            });
          }
          function X(n4) {
            return e(function(t2, r2) {
              return b(r2, n4);
            });
          }
          function Y(n4) {
            return e(function(t2, r2) {
              return x(r2, n4);
            });
          }
          function Z(n4) {
            if (y(n4)) return e(function(t2, r2) {
              var e2 = n4._(t2, r2);
              return e2.index = r2, e2.value = "", e2;
            });
            if ("string" == typeof n4) return Z(K(n4));
            if (n4 instanceof RegExp) return Z(Q(n4));
            throw new Error("not a string, regexp, or parser: " + n4);
          }
          function $(n4) {
            return _(n4), e(function(t2, r2) {
              var e2 = n4._(t2, r2), u2 = t2.slice(r2, e2.index);
              return e2.status ? x(r2, 'not "' + u2 + '"') : b(r2, null);
            });
          }
          function nn(n4) {
            return k(n4), e(function(t2, r2) {
              var e2 = L(t2, r2);
              return r2 < t2.length && n4(e2) ? b(r2 + 1, e2) : x(r2, "a character/byte matching " + n4);
            });
          }
          function tn(n4, t2) {
            arguments.length < 2 && (t2 = n4, n4 = void 0);
            var r2 = e(function(n5, e2) {
              return r2._ = t2()._, r2._(n5, e2);
            });
            return n4 ? r2.desc(n4) : r2;
          }
          function rn() {
            return Y("fantasy-land/empty");
          }
          u.parse = function(n4) {
            if ("string" != typeof n4 && !w(n4)) throw new Error(".parse must be called with a string or Buffer as its argument");
            var t2, r2 = this.skip(an)._(n4, 0);
            return t2 = r2.status ? { status: true, value: r2.value } : { status: false, index: S(n4, r2.furthest), expected: r2.expected }, delete j[n4], t2;
          }, u.tryParse = function(n4) {
            var t2 = this.parse(n4);
            if (t2.status) return t2.value;
            var r2 = N(n4, t2), e2 = new Error(r2);
            throw e2.type = "ParsimmonError", e2.result = t2, e2;
          }, u.assert = function(n4, t2) {
            return this.chain(function(r2) {
              return n4(r2) ? X(r2) : Y(t2);
            });
          }, u.or = function(n4) {
            return T(this, n4);
          }, u.trim = function(n4) {
            return this.wrap(n4, n4);
          }, u.wrap = function(n4, t2) {
            return J(n4, this, t2, function(n5, t3) {
              return t3;
            });
          }, u.thru = function(n4) {
            return n4(this);
          }, u.then = function(n4) {
            return _(n4), C(this, n4).map(function(n5) {
              return n5[1];
            });
          }, u.many = function() {
            var n4 = this;
            return e(function(t2, r2) {
              for (var e2 = [], u2 = void 0; ; ) {
                if (!(u2 = B(n4._(t2, r2), u2)).status) return B(b(r2, e2), u2);
                if (r2 === u2.index) throw new Error("infinite loop detected in .many() parser --- calling .many() on a parser which can accept zero characters is usually the cause");
                r2 = u2.index, e2.push(u2.value);
              }
            });
          }, u.tieWith = function(n4) {
            return P(n4), this.map(function(t2) {
              if (function(n5) {
                if (!E(n5)) throw new Error("not an array: " + n5);
              }(t2), t2.length) {
                P(t2[0]);
                for (var r2 = t2[0], e2 = 1; e2 < t2.length; e2++) P(t2[e2]), r2 += n4 + t2[e2];
                return r2;
              }
              return "";
            });
          }, u.tie = function() {
            return this.tieWith("");
          }, u.times = function(n4, t2) {
            var r2 = this;
            return arguments.length < 2 && (t2 = n4), O(n4), O(t2), e(function(e2, u2) {
              for (var o2 = [], i2 = void 0, a2 = void 0, f2 = 0; f2 < n4; f2 += 1) {
                if (a2 = B(i2 = r2._(e2, u2), a2), !i2.status) return a2;
                u2 = i2.index, o2.push(i2.value);
              }
              for (; f2 < t2 && (a2 = B(i2 = r2._(e2, u2), a2), i2.status); f2 += 1) u2 = i2.index, o2.push(i2.value);
              return B(b(u2, o2), a2);
            });
          }, u.result = function(n4) {
            return this.map(function() {
              return n4;
            });
          }, u.atMost = function(n4) {
            return this.times(0, n4);
          }, u.atLeast = function(n4) {
            return J(this.times(n4), this.many(), function(n5, t2) {
              return n5.concat(t2);
            });
          }, u.map = function(n4) {
            k(n4);
            var t2 = this;
            return e(function(r2, e2) {
              var u2 = t2._(r2, e2);
              return u2.status ? B(b(u2.index, n4(u2.value)), u2) : u2;
            });
          }, u.contramap = function(n4) {
            k(n4);
            var t2 = this;
            return e(function(r2, e2) {
              var u2 = t2.parse(n4(r2.slice(e2)));
              return u2.status ? b(e2 + r2.length, u2.value) : u2;
            });
          }, u.promap = function(n4, t2) {
            return k(n4), k(t2), this.contramap(n4).map(t2);
          }, u.skip = function(n4) {
            return C(this, n4).map(function(n5) {
              return n5[0];
            });
          }, u.mark = function() {
            return J(en, this, en, function(n4, t2, r2) {
              return { start: n4, value: t2, end: r2 };
            });
          }, u.node = function(n4) {
            return J(en, this, en, function(t2, r2, e2) {
              return { name: n4, value: r2, start: t2, end: e2 };
            });
          }, u.sepBy = function(n4) {
            return V(this, n4);
          }, u.sepBy1 = function(n4) {
            return H(this, n4);
          }, u.lookahead = function(n4) {
            return this.skip(Z(n4));
          }, u.notFollowedBy = function(n4) {
            return this.skip($(n4));
          }, u.desc = function(n4) {
            E(n4) || (n4 = [n4]);
            var t2 = this;
            return e(function(r2, e2) {
              var u2 = t2._(r2, e2);
              return u2.status || (u2.expected = n4), u2;
            });
          }, u.fallback = function(n4) {
            return this.or(X(n4));
          }, u.ap = function(n4) {
            return J(n4, this, function(n5, t2) {
              return n5(t2);
            });
          }, u.chain = function(n4) {
            var t2 = this;
            return e(function(r2, e2) {
              var u2 = t2._(r2, e2);
              return u2.status ? B(n4(u2.value)._(r2, u2.index), u2) : u2;
            });
          }, u.concat = u.or, u.empty = rn, u.of = X, u["fantasy-land/ap"] = u.ap, u["fantasy-land/chain"] = u.chain, u["fantasy-land/concat"] = u.concat, u["fantasy-land/empty"] = u.empty, u["fantasy-land/of"] = u.of, u["fantasy-land/map"] = u.map;
          var en = e(function(n4, t2) {
            return b(t2, S(n4, t2));
          }), un = e(function(n4, t2) {
            return t2 >= n4.length ? x(t2, "any character/byte") : b(t2 + 1, L(n4, t2));
          }), on = e(function(n4, t2) {
            return b(n4.length, n4.slice(t2));
          }), an = e(function(n4, t2) {
            return t2 < n4.length ? x(t2, "EOF") : b(t2, null);
          }), fn = Q(/[0-9]/).desc("a digit"), cn = Q(/[0-9]*/).desc("optional digits"), sn = Q(/[a-z]/i).desc("a letter"), ln = Q(/[a-z]*/i).desc("optional letters"), hn = Q(/\s*/).desc("optional whitespace"), pn = Q(/\s+/).desc("whitespace"), dn = K("\r"), vn = K("\n"), gn = K("\r\n"), mn = T(gn, vn, dn).desc("newline"), yn = T(mn, an);
          e.all = on, e.alt = T, e.any = un, e.cr = dn, e.createLanguage = function(n4) {
            var t2 = {};
            for (var r2 in n4) ({}).hasOwnProperty.call(n4, r2) && function(r3) {
              t2[r3] = tn(function() {
                return n4[r3](t2);
              });
            }(r2);
            return t2;
          }, e.crlf = gn, e.custom = function(n4) {
            return e(n4(b, x));
          }, e.digit = fn, e.digits = cn, e.empty = rn, e.end = yn, e.eof = an, e.fail = Y, e.formatError = N, e.index = en, e.isParser = y, e.lazy = tn, e.letter = sn, e.letters = ln, e.lf = vn, e.lookahead = Z, e.makeFailure = x, e.makeSuccess = b, e.newline = mn, e.noneOf = function(n4) {
            return nn(function(t2) {
              return n4.indexOf(t2) < 0;
            }).desc("none of '" + n4 + "'");
          }, e.notFollowedBy = $, e.of = X, e.oneOf = function(n4) {
            for (var t2 = n4.split(""), r2 = 0; r2 < t2.length; r2++) t2[r2] = "'" + t2[r2] + "'";
            return nn(function(t3) {
              return n4.indexOf(t3) >= 0;
            }).desc(t2);
          }, e.optWhitespace = hn, e.Parser = e, e.range = function(n4, t2) {
            return nn(function(r2) {
              return n4 <= r2 && r2 <= t2;
            }).desc(n4 + "-" + t2);
          }, e.regex = Q, e.regexp = Q, e.sepBy = V, e.sepBy1 = H, e.seq = C, e.seqMap = J, e.seqObj = function() {
            for (var n4, t2 = {}, r2 = 0, u2 = (n4 = arguments, Array.prototype.slice.call(n4)), o2 = u2.length, i2 = 0; i2 < o2; i2 += 1) {
              var a2 = u2[i2];
              if (!y(a2)) {
                if (E(a2) && 2 === a2.length && "string" == typeof a2[0] && y(a2[1])) {
                  var f2 = a2[0];
                  if (Object.prototype.hasOwnProperty.call(t2, f2)) throw new Error("seqObj: duplicate key " + f2);
                  t2[f2] = true, r2++;
                  continue;
                }
                throw new Error("seqObj arguments must be parsers or [string, parser] array pairs.");
              }
            }
            if (0 === r2) throw new Error("seqObj expects at least one named parser, found zero");
            return e(function(n5, t3) {
              for (var r3, e2 = {}, i3 = 0; i3 < o2; i3 += 1) {
                var a3, f3;
                if (E(u2[i3]) ? (a3 = u2[i3][0], f3 = u2[i3][1]) : (a3 = null, f3 = u2[i3]), !(r3 = B(f3._(n5, t3), r3)).status) return r3;
                a3 && (e2[a3] = r3.value), t3 = r3.index;
              }
              return B(b(t3, e2), r3);
            });
          }, e.string = K, e.succeed = X, e.takeWhile = function(n4) {
            return k(n4), e(function(t2, r2) {
              for (var e2 = r2; e2 < t2.length && n4(L(t2, e2)); ) e2++;
              return b(e2, t2.slice(r2, e2));
            });
          }, e.test = nn, e.whitespace = pn, e["fantasy-land/empty"] = rn, e["fantasy-land/of"] = X, e.Binary = { bitSeq: l3, bitSeqObj: function(n4) {
            s3();
            var t2 = {}, r2 = 0, e2 = a(function(n5) {
              if (E(n5)) {
                var e3 = n5;
                if (2 !== e3.length) throw new Error("[" + e3.join(", ") + "] should be length 2, got length " + e3.length);
                if (P(e3[0]), O(e3[1]), Object.prototype.hasOwnProperty.call(t2, e3[0])) throw new Error("duplicate key in bitSeqObj: " + e3[0]);
                return t2[e3[0]] = true, r2++, e3;
              }
              return O(n5), [null, n5];
            }, n4);
            if (r2 < 1) throw new Error("bitSeqObj expects at least one named pair, got [" + n4.join(", ") + "]");
            var u2 = a(function(n5) {
              return n5[0];
            }, e2);
            return l3(a(function(n5) {
              return n5[1];
            }, e2)).map(function(n5) {
              return i(function(n6, t3) {
                return null !== t3[0] && (n6[t3[0]] = t3[1]), n6;
              }, {}, a(function(t3, r3) {
                return [t3, n5[r3]];
              }, u2));
            });
          }, byte: function(n4) {
            if (s3(), O(n4), n4 > 255) throw new Error("Value specified to byte constructor (" + n4 + "=0x" + n4.toString(16) + ") is larger in value than a single byte.");
            var t2 = (n4 > 15 ? "0x" : "0x0") + n4.toString(16);
            return e(function(r2, e2) {
              var u2 = L(r2, e2);
              return u2 === n4 ? b(e2 + 1, u2) : x(e2, t2);
            });
          }, buffer: function(n4) {
            return h("buffer", n4).map(function(n5) {
              return Buffer.from(n5);
            });
          }, encodedString: function(n4, t2) {
            return h("string", t2).map(function(t3) {
              return t3.toString(n4);
            });
          }, uintBE: d, uint8BE: d(1), uint16BE: d(2), uint32BE: d(4), uintLE: v, uint8LE: v(1), uint16LE: v(2), uint32LE: v(4), intBE: g, int8BE: g(1), int16BE: g(2), int32BE: g(4), intLE: m, int8LE: m(1), int16LE: m(2), int32LE: m(4), floatBE: h("floatBE", 4).map(function(n4) {
            return n4.readFloatBE(0);
          }), floatLE: h("floatLE", 4).map(function(n4) {
            return n4.readFloatLE(0);
          }), doubleBE: h("doubleBE", 8).map(function(n4) {
            return n4.readDoubleBE(0);
          }), doubleLE: h("doubleLE", 8).map(function(n4) {
            return n4.readDoubleLE(0);
          }) }, n3.exports = e;
        }]);
      });
    })(parsimmon_umd_min, parsimmon_umd_min.exports);
    var parsimmon_umd_minExports = parsimmon_umd_min.exports;
    var emojiRegex = () => {
      return /[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26F9(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC3\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC08\uDC26](?:\u200D\u2B1B)?|[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE])))?))?|\uDC6F(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDD75(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE88\uDE90-\uDEBD\uDEBF-\uDEC2\uDECE-\uDEDB\uDEE0-\uDEE8]|\uDD3C(?:\u200D[\u2640\u2642]\uFE0F?|\uD83C[\uDFFB-\uDFFF])?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g;
    };
    function normalizeDuration(dur) {
      if (dur === void 0 || dur === null)
        return dur;
      return dur.shiftToAll().normalize();
    }
    function getFileTitle(path) {
      if (path.includes("/"))
        path = path.substring(path.lastIndexOf("/") + 1);
      if (path.endsWith(".md"))
        path = path.substring(0, path.length - 3);
      return path;
    }
    parsimmon_umd_minExports.alt(parsimmon_umd_minExports.regex(new RegExp(emojiRegex(), "")), parsimmon_umd_minExports.regex(/[0-9\p{Letter}_-]+/u).map((str) => str.toLocaleLowerCase()), parsimmon_umd_minExports.whitespace.map((_) => "-"), parsimmon_umd_minExports.any.map((_) => "")).many().map((result) => result.join(""));
    var HEADER_CANONICALIZER = parsimmon_umd_minExports.alt(parsimmon_umd_minExports.regex(new RegExp(emojiRegex(), "")), parsimmon_umd_minExports.regex(/[0-9\p{Letter}_-]+/u), parsimmon_umd_minExports.whitespace.map((_) => " "), parsimmon_umd_minExports.any.map((_) => " ")).many().map((result) => {
      return result.join("").split(/\s+/).join(" ").trim();
    });
    function normalizeHeaderForLink(header) {
      return HEADER_CANONICALIZER.tryParse(header);
    }
    function renderMinimalDuration(dur) {
      dur = normalizeDuration(dur);
      dur = Duration2.fromObject(Object.fromEntries(Object.entries(dur.toObject()).filter(([, quantity]) => quantity != 0)));
      return dur.toHuman();
    }
    var Values;
    (function(Values2) {
      function toString3(field, setting = DEFAULT_QUERY_SETTINGS, recursive = false) {
        let wrapped = wrapValue(field);
        if (!wrapped)
          return setting.renderNullAs;
        switch (wrapped.type) {
          case "null":
            return setting.renderNullAs;
          case "string":
            return wrapped.value;
          case "number":
          case "boolean":
            return "" + wrapped.value;
          case "html":
            return wrapped.value.outerHTML;
          case "widget":
            return wrapped.value.markdown();
          case "link":
            return wrapped.value.markdown();
          case "function":
            return "<function>";
          case "array":
            let result = "";
            if (recursive)
              result += "[";
            result += wrapped.value.map((f) => toString3(f, setting, true)).join(", ");
            if (recursive)
              result += "]";
            return result;
          case "object":
            return "{ " + Object.entries(wrapped.value).map((e) => e[0] + ": " + toString3(e[1], setting, true)).join(", ") + " }";
          case "date":
            if (wrapped.value.second == 0 && wrapped.value.hour == 0 && wrapped.value.minute == 0) {
              return wrapped.value.toFormat(setting.defaultDateFormat);
            }
            return wrapped.value.toFormat(setting.defaultDateTimeFormat);
          case "duration":
            return renderMinimalDuration(wrapped.value);
        }
      }
      Values2.toString = toString3;
      function wrapValue(val) {
        if (isNull(val))
          return { type: "null", value: val };
        else if (isNumber3(val))
          return { type: "number", value: val };
        else if (isString3(val))
          return { type: "string", value: val };
        else if (isBoolean(val))
          return { type: "boolean", value: val };
        else if (isDuration(val))
          return { type: "duration", value: val };
        else if (isDate3(val))
          return { type: "date", value: val };
        else if (isWidget(val))
          return { type: "widget", value: val };
        else if (isArray(val))
          return { type: "array", value: val };
        else if (isLink(val))
          return { type: "link", value: val };
        else if (isFunction(val))
          return { type: "function", value: val };
        else if (isHtml(val))
          return { type: "html", value: val };
        else if (isObject(val))
          return { type: "object", value: val };
        else
          return void 0;
      }
      Values2.wrapValue = wrapValue;
      function mapLeaves(val, func) {
        if (isObject(val)) {
          let result = {};
          for (let [key, value] of Object.entries(val))
            result[key] = mapLeaves(value, func);
          return result;
        } else if (isArray(val)) {
          let result = [];
          for (let value of val)
            result.push(mapLeaves(value, func));
          return result;
        } else {
          return func(val);
        }
      }
      Values2.mapLeaves = mapLeaves;
      function compareValue(val1, val2, linkNormalizer) {
        if (val1 === void 0)
          val1 = null;
        if (val2 === void 0)
          val2 = null;
        if (val1 === null && val2 === null)
          return 0;
        else if (val1 === null)
          return -1;
        else if (val2 === null)
          return 1;
        let wrap1 = wrapValue(val1);
        let wrap2 = wrapValue(val2);
        if (wrap1 === void 0 && wrap2 === void 0)
          return 0;
        else if (wrap1 === void 0)
          return -1;
        else if (wrap2 === void 0)
          return 1;
        if (wrap1.type != wrap2.type)
          return wrap1.type.localeCompare(wrap2.type);
        if (wrap1.value === wrap2.value)
          return 0;
        switch (wrap1.type) {
          case "string":
            return wrap1.value.localeCompare(wrap2.value);
          case "number":
            if (wrap1.value < wrap2.value)
              return -1;
            else if (wrap1.value == wrap2.value)
              return 0;
            return 1;
          case "null":
            return 0;
          case "boolean":
            if (wrap1.value == wrap2.value)
              return 0;
            else
              return wrap1.value ? 1 : -1;
          case "link":
            let link1 = wrap1.value;
            let link2 = wrap2.value;
            let normalize = linkNormalizer ?? ((x) => x);
            let pathCompare = normalize(link1.path).localeCompare(normalize(link2.path));
            if (pathCompare != 0)
              return pathCompare;
            let typeCompare = link1.type.localeCompare(link2.type);
            if (typeCompare != 0)
              return typeCompare;
            if (link1.subpath && !link2.subpath)
              return 1;
            if (!link1.subpath && link2.subpath)
              return -1;
            if (!link1.subpath && !link2.subpath)
              return 0;
            return (link1.subpath ?? "").localeCompare(link2.subpath ?? "");
          case "date":
            return wrap1.value < wrap2.value ? -1 : wrap1.value.equals(wrap2.value) ? 0 : 1;
          case "duration":
            return wrap1.value < wrap2.value ? -1 : wrap1.value.equals(wrap2.value) ? 0 : 1;
          case "array":
            let f1 = wrap1.value;
            let f2 = wrap2.value;
            for (let index = 0; index < Math.min(f1.length, f2.length); index++) {
              let comp = compareValue(f1[index], f2[index]);
              if (comp != 0)
                return comp;
            }
            return f1.length - f2.length;
          case "object":
            let o1 = wrap1.value;
            let o2 = wrap2.value;
            let k1 = Array.from(Object.keys(o1));
            let k2 = Array.from(Object.keys(o2));
            k1.sort();
            k2.sort();
            let keyCompare = compareValue(k1, k2);
            if (keyCompare != 0)
              return keyCompare;
            for (let key of k1) {
              let comp = compareValue(o1[key], o2[key]);
              if (comp != 0)
                return comp;
            }
            return 0;
          case "widget":
          case "html":
          case "function":
            return 0;
        }
      }
      Values2.compareValue = compareValue;
      function typeOf(val) {
        return wrapValue(val)?.type;
      }
      Values2.typeOf = typeOf;
      function isTruthy(field) {
        let wrapped = wrapValue(field);
        if (!wrapped)
          return false;
        switch (wrapped.type) {
          case "number":
            return wrapped.value != 0;
          case "string":
            return wrapped.value.length > 0;
          case "boolean":
            return wrapped.value;
          case "link":
            return !!wrapped.value.path;
          case "date":
            return wrapped.value.toMillis() != 0;
          case "duration":
            return wrapped.value.as("seconds") != 0;
          case "object":
            return Object.keys(wrapped.value).length > 0;
          case "array":
            return wrapped.value.length > 0;
          case "null":
            return false;
          case "html":
          case "widget":
          case "function":
            return true;
        }
      }
      Values2.isTruthy = isTruthy;
      function deepCopy(field) {
        if (field === null || field === void 0)
          return field;
        if (Values2.isArray(field)) {
          return [].concat(field.map((v) => deepCopy(v)));
        } else if (Values2.isObject(field)) {
          let result = {};
          for (let [key, value] of Object.entries(field))
            result[key] = deepCopy(value);
          return result;
        } else {
          return field;
        }
      }
      Values2.deepCopy = deepCopy;
      function isString3(val) {
        return typeof val == "string";
      }
      Values2.isString = isString3;
      function isNumber3(val) {
        return typeof val == "number";
      }
      Values2.isNumber = isNumber3;
      function isDate3(val) {
        return val instanceof DateTime2;
      }
      Values2.isDate = isDate3;
      function isDuration(val) {
        return val instanceof Duration2;
      }
      Values2.isDuration = isDuration;
      function isNull(val) {
        return val === null || val === void 0;
      }
      Values2.isNull = isNull;
      function isArray(val) {
        return Array.isArray(val);
      }
      Values2.isArray = isArray;
      function isBoolean(val) {
        return typeof val === "boolean";
      }
      Values2.isBoolean = isBoolean;
      function isLink(val) {
        return val instanceof Link;
      }
      Values2.isLink = isLink;
      function isWidget(val) {
        return val instanceof Widget;
      }
      Values2.isWidget = isWidget;
      function isHtml(val) {
        if (typeof HTMLElement !== "undefined") {
          return val instanceof HTMLElement;
        } else {
          return false;
        }
      }
      Values2.isHtml = isHtml;
      function isObject(val) {
        return typeof val == "object" && !isHtml(val) && !isWidget(val) && !isArray(val) && !isDuration(val) && !isDate3(val) && !isLink(val) && val !== void 0 && !isNull(val);
      }
      Values2.isObject = isObject;
      function isFunction(val) {
        return typeof val == "function";
      }
      Values2.isFunction = isFunction;
    })(Values || (Values = {}));
    var Groupings;
    (function(Groupings2) {
      function isElementGroup(entry) {
        return Values.isObject(entry) && Object.keys(entry).length == 2 && "key" in entry && "rows" in entry;
      }
      Groupings2.isElementGroup = isElementGroup;
      function isGrouping(entry) {
        for (let element2 of entry)
          if (!isElementGroup(element2))
            return false;
        return true;
      }
      Groupings2.isGrouping = isGrouping;
      function count(elements) {
        if (isGrouping(elements)) {
          let result = 0;
          for (let subgroup of elements)
            result += count(subgroup.rows);
          return result;
        } else {
          return elements.length;
        }
      }
      Groupings2.count = count;
    })(Groupings || (Groupings = {}));
    var Link = class _Link {
      /** The file path this link points to. */
      path;
      /** The display name associated with the link. */
      display;
      /** The block ID or header this link points to within a file, if relevant. */
      subpath;
      /** Is this link an embedded link (!)? */
      embed;
      /** The type of this link, which determines what 'subpath' refers to, if anything. */
      type;
      /** Create a link to a specific file. */
      static file(path, embed = false, display) {
        return new _Link({
          path,
          embed,
          display,
          subpath: void 0,
          type: "file"
        });
      }
      static infer(linkpath, embed = false, display) {
        if (linkpath.includes("#^")) {
          let split = linkpath.split("#^");
          return _Link.block(split[0], split[1], embed, display);
        } else if (linkpath.includes("#")) {
          let split = linkpath.split("#");
          return _Link.header(split[0], split[1], embed, display);
        } else
          return _Link.file(linkpath, embed, display);
      }
      /** Create a link to a specific file and header in that file. */
      static header(path, header, embed, display) {
        return new _Link({
          path,
          embed,
          display,
          subpath: normalizeHeaderForLink(header),
          type: "header"
        });
      }
      /** Create a link to a specific file and block in that file. */
      static block(path, blockId, embed, display) {
        return new _Link({
          path,
          embed,
          display,
          subpath: blockId,
          type: "block"
        });
      }
      static fromObject(object) {
        return new _Link(object);
      }
      constructor(fields) {
        Object.assign(this, fields);
      }
      /** Checks for link equality (i.e., that the links are pointing to the same exact location). */
      equals(other) {
        if (other == void 0 || other == null)
          return false;
        return this.path == other.path && this.type == other.type && this.subpath == other.subpath;
      }
      /** Convert this link to it's markdown representation. */
      toString() {
        return this.markdown();
      }
      /** Convert this link to a raw object which is serialization-friendly. */
      toObject() {
        return { path: this.path, type: this.type, subpath: this.subpath, display: this.display, embed: this.embed };
      }
      /** Update this link with a new path. */
      //@ts-ignore; error appeared after updating Obsidian to 0.15.4; it also updated other packages but didn't say which
      withPath(path) {
        return new _Link(Object.assign({}, this, { path }));
      }
      /** Return a new link which points to the same location but with a new display value. */
      withDisplay(display) {
        return new _Link(Object.assign({}, this, { display }));
      }
      /** Convert a file link into a link to a specific header. */
      withHeader(header) {
        return _Link.header(this.path, header, this.embed, this.display);
      }
      /** Convert any link into a link to its file. */
      toFile() {
        return _Link.file(this.path, this.embed, this.display);
      }
      /** Convert this link into an embedded link. */
      toEmbed() {
        if (this.embed) {
          return this;
        } else {
          let link = new _Link(this);
          link.embed = true;
          return link;
        }
      }
      /** Convert this link into a non-embedded link. */
      fromEmbed() {
        if (!this.embed) {
          return this;
        } else {
          let link = new _Link(this);
          link.embed = false;
          return link;
        }
      }
      /** Convert this link to markdown so it can be rendered. */
      markdown() {
        let result = (this.embed ? "!" : "") + "[[" + this.obsidianLink();
        if (this.display) {
          result += "|" + this.display;
        } else {
          result += "|" + getFileTitle(this.path);
          if (this.type == "header" || this.type == "block")
            result += " > " + this.subpath;
        }
        result += "]]";
        return result;
      }
      /** Convert the inner part of the link to something that Obsidian can open / understand. */
      obsidianLink() {
        const escaped = this.path.replaceAll("|", "\\|");
        if (this.type == "header")
          return escaped + "#" + this.subpath?.replaceAll("|", "\\|");
        if (this.type == "block")
          return escaped + "#^" + this.subpath?.replaceAll("|", "\\|");
        else
          return escaped;
      }
      /** The stripped name of the file this link points to. */
      fileName() {
        return getFileTitle(this.path).replace(".md", "");
      }
    };
    var Widget = class {
      $widget;
      constructor($widget) {
        this.$widget = $widget;
      }
    };
    var ListPairWidget = class extends Widget {
      key;
      value;
      constructor(key, value) {
        super("dataview:list-pair");
        this.key = key;
        this.value = value;
      }
      markdown() {
        return `${Values.toString(this.key)}: ${Values.toString(this.value)}`;
      }
    };
    var ExternalLinkWidget = class extends Widget {
      url;
      display;
      constructor(url, display) {
        super("dataview:external-link");
        this.url = url;
        this.display = display;
      }
      markdown() {
        return `[${this.display ?? this.url}](${this.url})`;
      }
    };
    var Widgets;
    (function(Widgets2) {
      function listPair(key, value) {
        return new ListPairWidget(key, value);
      }
      Widgets2.listPair = listPair;
      function externalLink(url, display) {
        return new ExternalLinkWidget(url, display);
      }
      Widgets2.externalLink = externalLink;
      function isListPair(widget) {
        return widget.$widget === "dataview:list-pair";
      }
      Widgets2.isListPair = isListPair;
      function isExternalLink(widget) {
        return widget.$widget === "dataview:external-link";
      }
      Widgets2.isExternalLink = isExternalLink;
      function isBuiltin(widget) {
        return isListPair(widget) || isExternalLink(widget);
      }
      Widgets2.isBuiltin = isBuiltin;
    })(Widgets || (Widgets = {}));
    var Fields;
    (function(Fields2) {
      function variable(name) {
        return { type: "variable", name };
      }
      Fields2.variable = variable;
      function literal(value) {
        return { type: "literal", value };
      }
      Fields2.literal = literal;
      function binaryOp(left, op, right) {
        return { type: "binaryop", left, op, right };
      }
      Fields2.binaryOp = binaryOp;
      function index(obj, index2) {
        return { type: "index", object: obj, index: index2 };
      }
      Fields2.index = index;
      function indexVariable(name) {
        let parts = name.split(".");
        let result = Fields2.variable(parts[0]);
        for (let index2 = 1; index2 < parts.length; index2++) {
          result = Fields2.index(result, Fields2.literal(parts[index2]));
        }
        return result;
      }
      Fields2.indexVariable = indexVariable;
      function lambda(args, value) {
        return { type: "lambda", arguments: args, value };
      }
      Fields2.lambda = lambda;
      function func(func2, args) {
        return { type: "function", func: func2, arguments: args };
      }
      Fields2.func = func;
      function list(values) {
        return { type: "list", values };
      }
      Fields2.list = list;
      function object(values) {
        return { type: "object", values };
      }
      Fields2.object = object;
      function negate(child) {
        return { type: "negated", child };
      }
      Fields2.negate = negate;
      function isCompareOp(op) {
        return op == "<=" || op == "<" || op == ">" || op == ">=" || op == "!=" || op == "=";
      }
      Fields2.isCompareOp = isCompareOp;
      Fields2.NULL = Fields2.literal(null);
    })(Fields || (Fields = {}));
    var Sources;
    (function(Sources2) {
      function tag(tag2) {
        return { type: "tag", tag: tag2 };
      }
      Sources2.tag = tag;
      function csv(path) {
        return { type: "csv", path };
      }
      Sources2.csv = csv;
      function folder(prefix) {
        return { type: "folder", folder: prefix };
      }
      Sources2.folder = folder;
      function link(file, incoming) {
        return { type: "link", file, direction: incoming ? "incoming" : "outgoing" };
      }
      Sources2.link = link;
      function binaryOp(left, op, right) {
        return { type: "binaryop", left, op, right };
      }
      Sources2.binaryOp = binaryOp;
      function and(left, right) {
        return { type: "binaryop", left, op: "&", right };
      }
      Sources2.and = and;
      function or(left, right) {
        return { type: "binaryop", left, op: "|", right };
      }
      Sources2.or = or;
      function negate(child) {
        return { type: "negate", child };
      }
      Sources2.negate = negate;
      function empty2() {
        return { type: "empty" };
      }
      Sources2.empty = empty2;
    })(Sources || (Sources = {}));
    var EMOJI_REGEX = new RegExp(emojiRegex(), "");
    var DURATION_TYPES = {
      year: Duration2.fromObject({ years: 1 }),
      years: Duration2.fromObject({ years: 1 }),
      yr: Duration2.fromObject({ years: 1 }),
      yrs: Duration2.fromObject({ years: 1 }),
      month: Duration2.fromObject({ months: 1 }),
      months: Duration2.fromObject({ months: 1 }),
      mo: Duration2.fromObject({ months: 1 }),
      mos: Duration2.fromObject({ months: 1 }),
      week: Duration2.fromObject({ weeks: 1 }),
      weeks: Duration2.fromObject({ weeks: 1 }),
      wk: Duration2.fromObject({ weeks: 1 }),
      wks: Duration2.fromObject({ weeks: 1 }),
      w: Duration2.fromObject({ weeks: 1 }),
      day: Duration2.fromObject({ days: 1 }),
      days: Duration2.fromObject({ days: 1 }),
      d: Duration2.fromObject({ days: 1 }),
      hour: Duration2.fromObject({ hours: 1 }),
      hours: Duration2.fromObject({ hours: 1 }),
      hr: Duration2.fromObject({ hours: 1 }),
      hrs: Duration2.fromObject({ hours: 1 }),
      h: Duration2.fromObject({ hours: 1 }),
      minute: Duration2.fromObject({ minutes: 1 }),
      minutes: Duration2.fromObject({ minutes: 1 }),
      min: Duration2.fromObject({ minutes: 1 }),
      mins: Duration2.fromObject({ minutes: 1 }),
      m: Duration2.fromObject({ minutes: 1 }),
      second: Duration2.fromObject({ seconds: 1 }),
      seconds: Duration2.fromObject({ seconds: 1 }),
      sec: Duration2.fromObject({ seconds: 1 }),
      secs: Duration2.fromObject({ seconds: 1 }),
      s: Duration2.fromObject({ seconds: 1 })
    };
    var DATE_SHORTHANDS = {
      now: () => DateTime2.local(),
      today: () => DateTime2.local().startOf("day"),
      yesterday: () => DateTime2.local().startOf("day").minus(Duration2.fromObject({ days: 1 })),
      tomorrow: () => DateTime2.local().startOf("day").plus(Duration2.fromObject({ days: 1 })),
      sow: () => DateTime2.local().startOf("week"),
      "start-of-week": () => DateTime2.local().startOf("week"),
      eow: () => DateTime2.local().endOf("week"),
      "end-of-week": () => DateTime2.local().endOf("week"),
      soy: () => DateTime2.local().startOf("year"),
      "start-of-year": () => DateTime2.local().startOf("year"),
      eoy: () => DateTime2.local().endOf("year"),
      "end-of-year": () => DateTime2.local().endOf("year"),
      som: () => DateTime2.local().startOf("month"),
      "start-of-month": () => DateTime2.local().startOf("month"),
      eom: () => DateTime2.local().endOf("month"),
      "end-of-month": () => DateTime2.local().endOf("month")
    };
    var KEYWORDS = ["FROM", "WHERE", "LIMIT", "GROUP", "FLATTEN"];
    function splitOnUnescapedPipe(link) {
      let pipe = -1;
      while ((pipe = link.indexOf("|", pipe + 1)) >= 0) {
        if (pipe > 0 && link[pipe - 1] == "\\")
          continue;
        return [link.substring(0, pipe).replace(/\\\|/g, "|"), link.substring(pipe + 1)];
      }
      return [link.replace(/\\\|/g, "|"), void 0];
    }
    function parseInnerLink(rawlink) {
      let [link, display] = splitOnUnescapedPipe(rawlink);
      return Link.infer(link, false, display);
    }
    function createBinaryParser(child, sep, combine) {
      return parsimmon_umd_minExports.seqMap(child, parsimmon_umd_minExports.seq(parsimmon_umd_minExports.optWhitespace, sep, parsimmon_umd_minExports.optWhitespace, child).many(), (first, rest) => {
        if (rest.length == 0)
          return first;
        let node = combine(first, rest[0][1], rest[0][3]);
        for (let index = 1; index < rest.length; index++) {
          node = combine(node, rest[index][1], rest[index][3]);
        }
        return node;
      });
    }
    function chainOpt(base, ...funcs) {
      return parsimmon_umd_minExports.custom((success, failure) => {
        return (input, i) => {
          let result = base._(input, i);
          if (!result.status)
            return result;
          for (let func of funcs) {
            let next = func(result.value)._(input, result.index);
            if (!next.status)
              return result;
            result = next;
          }
          return result;
        };
      });
    }
    var EXPRESSION = parsimmon_umd_minExports.createLanguage({
      // A floating point number; the decimal point is optional.
      number: (q) => parsimmon_umd_minExports.regexp(/-?[0-9]+(\.[0-9]+)?/).map((str) => Number.parseFloat(str)).desc("number"),
      // A quote-surrounded string which supports escape characters ('\').
      string: (q) => parsimmon_umd_minExports.string('"').then(parsimmon_umd_minExports.alt(q.escapeCharacter, parsimmon_umd_minExports.noneOf('"\\')).atLeast(0).map((chars) => chars.join(""))).skip(parsimmon_umd_minExports.string('"')).desc("string"),
      escapeCharacter: (_) => parsimmon_umd_minExports.string("\\").then(parsimmon_umd_minExports.any).map((escaped) => {
        if (escaped === '"')
          return '"';
        if (escaped === "\\")
          return "\\";
        else
          return "\\" + escaped;
      }),
      // A boolean true/false value.
      bool: (_) => parsimmon_umd_minExports.regexp(/true|false|True|False/).map((str) => str.toLowerCase() == "true").desc("boolean ('true' or 'false')"),
      // A tag of the form '#stuff/hello-there'.
      tag: (_) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("#"), parsimmon_umd_minExports.alt(parsimmon_umd_minExports.regexp(/[^\u2000-\u206F\u2E00-\u2E7F'!"#$%&()*+,.:;<=>?@^`{|}~\[\]\\\s]/).desc("text")).many(), (start, rest) => start + rest.join("")).desc("tag ('#hello/stuff')"),
      // A variable identifier, which is alphanumeric and must start with a letter or... emoji.
      identifier: (_) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.alt(parsimmon_umd_minExports.regexp(/\p{Letter}/u), parsimmon_umd_minExports.regexp(EMOJI_REGEX).desc("text")), parsimmon_umd_minExports.alt(parsimmon_umd_minExports.regexp(/[0-9\p{Letter}_-]/u), parsimmon_umd_minExports.regexp(EMOJI_REGEX).desc("text")).many(), (first, rest) => first + rest.join("")).desc("variable identifier"),
      // An Obsidian link of the form [[<link>]].
      link: (_) => parsimmon_umd_minExports.regexp(/\[\[([^\[\]]*?)\]\]/u, 1).map((linkInner) => parseInnerLink(linkInner)).desc("file link"),
      // An embeddable link which can start with '!'. This overlaps with the normal negation operator, so it is only
      // provided for metadata parsing.
      embedLink: (q) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("!").atMost(1), q.link, (p, l3) => {
        if (p.length > 0)
          l3.embed = true;
        return l3;
      }).desc("file link"),
      // Binary plus or minus operator.
      binaryPlusMinus: (_) => parsimmon_umd_minExports.regexp(/\+|-/).map((str) => str).desc("'+' or '-'"),
      // Binary times or divide operator.
      binaryMulDiv: (_) => parsimmon_umd_minExports.regexp(/\*|\/|%/).map((str) => str).desc("'*' or '/' or '%'"),
      // Binary comparison operator.
      binaryCompareOp: (_) => parsimmon_umd_minExports.regexp(/>=|<=|!=|>|<|=/).map((str) => str).desc("'>=' or '<=' or '!=' or '=' or '>' or '<'"),
      // Binary boolean combination operator.
      binaryBooleanOp: (_) => parsimmon_umd_minExports.regexp(/and|or|&|\|/i).map((str) => {
        if (str.toLowerCase() == "and")
          return "&";
        else if (str.toLowerCase() == "or")
          return "|";
        else
          return str;
      }).desc("'and' or 'or'"),
      // A date which can be YYYY-MM[-DDTHH:mm:ss].
      rootDate: (_) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.regexp(/\d{4}/), parsimmon_umd_minExports.string("-"), parsimmon_umd_minExports.regexp(/\d{2}/), (year, _2, month) => {
        return DateTime2.fromObject({ year: Number.parseInt(year), month: Number.parseInt(month) });
      }).desc("date in format YYYY-MM[-DDTHH-MM-SS.MS]"),
      dateShorthand: (_) => parsimmon_umd_minExports.alt(...Object.keys(DATE_SHORTHANDS).sort((a, b) => b.length - a.length).map(parsimmon_umd_minExports.string)),
      date: (q) => chainOpt(q.rootDate, (ym) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("-"), parsimmon_umd_minExports.regexp(/\d{2}/), (_, day) => ym.set({ day: Number.parseInt(day) })), (ymd) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("T"), parsimmon_umd_minExports.regexp(/\d{2}/), (_, hour) => ymd.set({ hour: Number.parseInt(hour) })), (ymdh) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string(":"), parsimmon_umd_minExports.regexp(/\d{2}/), (_, minute) => ymdh.set({ minute: Number.parseInt(minute) })), (ymdhm) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string(":"), parsimmon_umd_minExports.regexp(/\d{2}/), (_, second) => ymdhm.set({ second: Number.parseInt(second) })), (ymdhms) => parsimmon_umd_minExports.alt(
        parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("."), parsimmon_umd_minExports.regexp(/\d{3}/), (_, millisecond) => ymdhms.set({ millisecond: Number.parseInt(millisecond) })),
        parsimmon_umd_minExports.succeed(ymdhms)
        // pass
      ), (dt) => parsimmon_umd_minExports.alt(parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("+").or(parsimmon_umd_minExports.string("-")), parsimmon_umd_minExports.regexp(/\d{1,2}(:\d{2})?/), (pm, hr) => dt.setZone("UTC" + pm + hr, { keepLocalTime: true })), parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("Z"), () => dt.setZone("utc", { keepLocalTime: true })), parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("["), parsimmon_umd_minExports.regexp(/[0-9A-Za-z+-\/]+/u), parsimmon_umd_minExports.string("]"), (_a, zone, _b) => dt.setZone(zone, { keepLocalTime: true })))).assert((dt) => dt.isValid, "valid date").desc("date in format YYYY-MM[-DDTHH-MM-SS.MS]"),
      // A date, plus various shorthand times of day it could be.
      datePlus: (q) => parsimmon_umd_minExports.alt(q.dateShorthand.map((d) => DATE_SHORTHANDS[d]()), q.date).desc("date in format YYYY-MM[-DDTHH-MM-SS.MS] or in shorthand"),
      // A duration of time.
      durationType: (_) => parsimmon_umd_minExports.alt(...Object.keys(DURATION_TYPES).sort((a, b) => b.length - a.length).map(parsimmon_umd_minExports.string)),
      duration: (q) => parsimmon_umd_minExports.seqMap(q.number, parsimmon_umd_minExports.optWhitespace, q.durationType, (count, _, t) => DURATION_TYPES[t].mapUnits((x) => x * count)).sepBy1(parsimmon_umd_minExports.string(",").trim(parsimmon_umd_minExports.optWhitespace).or(parsimmon_umd_minExports.optWhitespace)).map((durations) => durations.reduce((p, c) => p.plus(c))).desc("duration like 4hr2min"),
      // A raw null value.
      rawNull: (_) => parsimmon_umd_minExports.string("null"),
      // Source parsing.
      tagSource: (q) => q.tag.map((tag) => Sources.tag(tag)),
      csvSource: (q) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("csv(").skip(parsimmon_umd_minExports.optWhitespace), q.string, parsimmon_umd_minExports.string(")"), (_1, path, _2) => Sources.csv(path)),
      linkIncomingSource: (q) => q.link.map((link) => Sources.link(link.path, true)),
      linkOutgoingSource: (q) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("outgoing(").skip(parsimmon_umd_minExports.optWhitespace), q.link, parsimmon_umd_minExports.string(")"), (_1, link, _2) => Sources.link(link.path, false)),
      folderSource: (q) => q.string.map((str) => Sources.folder(str)),
      parensSource: (q) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("("), parsimmon_umd_minExports.optWhitespace, q.source, parsimmon_umd_minExports.optWhitespace, parsimmon_umd_minExports.string(")"), (_1, _2, field, _3, _4) => field),
      negateSource: (q) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.alt(parsimmon_umd_minExports.string("-"), parsimmon_umd_minExports.string("!")), q.atomSource, (_, source) => Sources.negate(source)),
      atomSource: (q) => parsimmon_umd_minExports.alt(q.parensSource, q.negateSource, q.linkOutgoingSource, q.linkIncomingSource, q.folderSource, q.tagSource, q.csvSource),
      binaryOpSource: (q) => createBinaryParser(q.atomSource, q.binaryBooleanOp.map((s3) => s3), Sources.binaryOp),
      source: (q) => q.binaryOpSource,
      // Field parsing.
      variableField: (q) => q.identifier.chain((r) => {
        if (KEYWORDS.includes(r.toUpperCase())) {
          return parsimmon_umd_minExports.fail("Variable fields cannot be a keyword (" + KEYWORDS.join(" or ") + ")");
        } else {
          return parsimmon_umd_minExports.succeed(Fields.variable(r));
        }
      }).desc("variable"),
      numberField: (q) => q.number.map((val) => Fields.literal(val)).desc("number"),
      stringField: (q) => q.string.map((val) => Fields.literal(val)).desc("string"),
      boolField: (q) => q.bool.map((val) => Fields.literal(val)).desc("boolean"),
      dateField: (q) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("date("), parsimmon_umd_minExports.optWhitespace, q.datePlus, parsimmon_umd_minExports.optWhitespace, parsimmon_umd_minExports.string(")"), (prefix, _1, date, _2, postfix) => Fields.literal(date)).desc("date"),
      durationField: (q) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("dur("), parsimmon_umd_minExports.optWhitespace, q.duration, parsimmon_umd_minExports.optWhitespace, parsimmon_umd_minExports.string(")"), (prefix, _1, dur, _2, postfix) => Fields.literal(dur)).desc("duration"),
      nullField: (q) => q.rawNull.map((_) => Fields.NULL),
      linkField: (q) => q.link.map((f) => Fields.literal(f)),
      listField: (q) => q.field.sepBy(parsimmon_umd_minExports.string(",").trim(parsimmon_umd_minExports.optWhitespace)).wrap(parsimmon_umd_minExports.string("[").skip(parsimmon_umd_minExports.optWhitespace), parsimmon_umd_minExports.optWhitespace.then(parsimmon_umd_minExports.string("]"))).map((l3) => Fields.list(l3)).desc("list ('[1, 2, 3]')"),
      objectField: (q) => parsimmon_umd_minExports.seqMap(q.identifier.or(q.string), parsimmon_umd_minExports.string(":").trim(parsimmon_umd_minExports.optWhitespace), q.field, (name, _sep, value) => {
        return { name, value };
      }).sepBy(parsimmon_umd_minExports.string(",").trim(parsimmon_umd_minExports.optWhitespace)).wrap(parsimmon_umd_minExports.string("{").skip(parsimmon_umd_minExports.optWhitespace), parsimmon_umd_minExports.optWhitespace.then(parsimmon_umd_minExports.string("}"))).map((vals) => {
        let res = {};
        for (let entry of vals)
          res[entry.name] = entry.value;
        return Fields.object(res);
      }).desc("object ('{ a: 1, b: 2 }')"),
      atomInlineField: (q) => parsimmon_umd_minExports.alt(q.date, q.duration.map((d) => normalizeDuration(d)), q.string, q.tag, q.embedLink, q.bool, q.number, q.rawNull),
      inlineFieldList: (q) => q.atomInlineField.sepBy(parsimmon_umd_minExports.string(",").trim(parsimmon_umd_minExports.optWhitespace).lookahead(q.atomInlineField)),
      inlineField: (q) => parsimmon_umd_minExports.alt(parsimmon_umd_minExports.seqMap(q.atomInlineField, parsimmon_umd_minExports.string(",").trim(parsimmon_umd_minExports.optWhitespace), q.inlineFieldList, (f, _s, l3) => [f].concat(l3)), q.atomInlineField),
      atomField: (q) => parsimmon_umd_minExports.alt(
        // Place embed links above negated fields as they are the special parser case '![[thing]]' and are generally unambiguous.
        q.embedLink.map((l3) => Fields.literal(l3)),
        q.negatedField,
        q.linkField,
        q.listField,
        q.objectField,
        q.lambdaField,
        q.parensField,
        q.boolField,
        q.numberField,
        q.stringField,
        q.dateField,
        q.durationField,
        q.nullField,
        q.variableField
      ),
      indexField: (q) => parsimmon_umd_minExports.seqMap(q.atomField, parsimmon_umd_minExports.alt(q.dotPostfix, q.indexPostfix, q.functionPostfix).many(), (obj, postfixes) => {
        let result = obj;
        for (let post of postfixes) {
          switch (post.type) {
            case "dot":
              result = Fields.index(result, Fields.literal(post.field));
              break;
            case "index":
              result = Fields.index(result, post.field);
              break;
            case "function":
              result = Fields.func(result, post.fields);
              break;
          }
        }
        return result;
      }),
      negatedField: (q) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("!"), q.indexField, (_, field) => Fields.negate(field)).desc("negated field"),
      parensField: (q) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("("), parsimmon_umd_minExports.optWhitespace, q.field, parsimmon_umd_minExports.optWhitespace, parsimmon_umd_minExports.string(")"), (_1, _2, field, _3, _4) => field),
      lambdaField: (q) => parsimmon_umd_minExports.seqMap(q.identifier.sepBy(parsimmon_umd_minExports.string(",").trim(parsimmon_umd_minExports.optWhitespace)).wrap(parsimmon_umd_minExports.string("(").trim(parsimmon_umd_minExports.optWhitespace), parsimmon_umd_minExports.string(")").trim(parsimmon_umd_minExports.optWhitespace)), parsimmon_umd_minExports.string("=>").trim(parsimmon_umd_minExports.optWhitespace), q.field, (ident, _ignore, value) => {
        return { type: "lambda", arguments: ident, value };
      }),
      dotPostfix: (q) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("."), q.identifier, (_, field) => {
        return { type: "dot", field };
      }),
      indexPostfix: (q) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("["), parsimmon_umd_minExports.optWhitespace, q.field, parsimmon_umd_minExports.optWhitespace, parsimmon_umd_minExports.string("]"), (_, _2, field, _3, _4) => {
        return { type: "index", field };
      }),
      functionPostfix: (q) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("("), parsimmon_umd_minExports.optWhitespace, q.field.sepBy(parsimmon_umd_minExports.string(",").trim(parsimmon_umd_minExports.optWhitespace)), parsimmon_umd_minExports.optWhitespace, parsimmon_umd_minExports.string(")"), (_, _1, fields, _2, _3) => {
        return { type: "function", fields };
      }),
      // The precedence hierarchy of operators - multiply/divide, add/subtract, compare, and then boolean operations.
      binaryMulDivField: (q) => createBinaryParser(q.indexField, q.binaryMulDiv, Fields.binaryOp),
      binaryPlusMinusField: (q) => createBinaryParser(q.binaryMulDivField, q.binaryPlusMinus, Fields.binaryOp),
      binaryCompareField: (q) => createBinaryParser(q.binaryPlusMinusField, q.binaryCompareOp, Fields.binaryOp),
      binaryBooleanField: (q) => createBinaryParser(q.binaryCompareField, q.binaryBooleanOp, Fields.binaryOp),
      binaryOpField: (q) => q.binaryBooleanField,
      field: (q) => q.binaryOpField
    });
    function parseField(text2) {
      try {
        return Result.success(EXPRESSION.field.tryParse(text2));
      } catch (error) {
        return Result.failure("" + error);
      }
    }
    var QueryFields;
    (function(QueryFields2) {
      function named(name, field) {
        return { name, field };
      }
      QueryFields2.named = named;
      function sortBy(field, dir) {
        return { field, direction: dir };
      }
      QueryFields2.sortBy = sortBy;
    })(QueryFields || (QueryFields = {}));
    function captureRaw(base) {
      return parsimmon_umd_minExports.custom((success, failure) => {
        return (input, i) => {
          let result = base._(input, i);
          if (!result.status)
            return result;
          return Object.assign({}, result, { value: [result.value, input.substring(i, result.index)] });
        };
      });
    }
    function stripNewlines(text2) {
      return text2.split(/[\r\n]+/).map((t) => t.trim()).join("");
    }
    function precededByWhitespaceIfNotEof(if_eof, parser) {
      return parsimmon_umd_minExports.eof.map(if_eof).or(parsimmon_umd_minExports.whitespace.then(parser));
    }
    var QUERY_LANGUAGE = parsimmon_umd_minExports.createLanguage({
      // Simple atom parsing, like words, identifiers, numbers.
      queryType: (q) => parsimmon_umd_minExports.alt(parsimmon_umd_minExports.regexp(/TABLE|LIST|TASK|CALENDAR/i)).map((str) => str.toLowerCase()).desc("query type ('TABLE', 'LIST', 'TASK', or 'CALENDAR')"),
      explicitNamedField: (q) => parsimmon_umd_minExports.seqMap(EXPRESSION.field.skip(parsimmon_umd_minExports.whitespace), parsimmon_umd_minExports.regexp(/AS/i).skip(parsimmon_umd_minExports.whitespace), EXPRESSION.identifier.or(EXPRESSION.string), (field, _as, ident) => QueryFields.named(ident, field)),
      comment: () => parsimmon_umd_minExports.Parser((input, i) => {
        let line = input.substring(i);
        if (!line.startsWith("//"))
          return parsimmon_umd_minExports.makeFailure(i, "Not a comment");
        line = line.split("\n")[0];
        let comment = line.substring(2).trim();
        return parsimmon_umd_minExports.makeSuccess(i + line.length, comment);
      }),
      namedField: (q) => parsimmon_umd_minExports.alt(q.explicitNamedField, captureRaw(EXPRESSION.field).map(([value, text2]) => QueryFields.named(stripNewlines(text2), value))),
      sortField: (q) => parsimmon_umd_minExports.seqMap(EXPRESSION.field.skip(parsimmon_umd_minExports.optWhitespace), parsimmon_umd_minExports.regexp(/ASCENDING|DESCENDING|ASC|DESC/i).atMost(1), (field, dir) => {
        let direction = dir.length == 0 ? "ascending" : dir[0].toLowerCase();
        if (direction == "desc")
          direction = "descending";
        if (direction == "asc")
          direction = "ascending";
        return {
          field,
          direction
        };
      }),
      headerClause: (q) => q.queryType.chain((type) => {
        switch (type) {
          case "table": {
            return precededByWhitespaceIfNotEof(() => ({ type, fields: [], showId: true }), parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.regexp(/WITHOUT\s+ID/i).skip(parsimmon_umd_minExports.optWhitespace).atMost(1), parsimmon_umd_minExports.sepBy(q.namedField, parsimmon_umd_minExports.string(",").trim(parsimmon_umd_minExports.optWhitespace)), (withoutId, fields) => {
              return { type, fields, showId: withoutId.length == 0 };
            }));
          }
          case "list":
            return precededByWhitespaceIfNotEof(() => ({ type, format: void 0, showId: true }), parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.regexp(/WITHOUT\s+ID/i).skip(parsimmon_umd_minExports.optWhitespace).atMost(1), EXPRESSION.field.atMost(1), (withoutId, format) => {
              return {
                type,
                format: format.length == 1 ? format[0] : void 0,
                showId: withoutId.length == 0
              };
            }));
          case "task":
            return parsimmon_umd_minExports.succeed({ type });
          case "calendar":
            return parsimmon_umd_minExports.whitespace.then(parsimmon_umd_minExports.seqMap(q.namedField, (field) => {
              return {
                type,
                showId: true,
                field
              };
            }));
          default:
            return parsimmon_umd_minExports.fail(`Unrecognized query type '${type}'`);
        }
      }).desc("TABLE or LIST or TASK or CALENDAR"),
      fromClause: (q) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.regexp(/FROM/i), parsimmon_umd_minExports.whitespace, EXPRESSION.source, (_1, _2, source) => source),
      whereClause: (q) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.regexp(/WHERE/i), parsimmon_umd_minExports.whitespace, EXPRESSION.field, (where, _, field) => {
        return { type: "where", clause: field };
      }).desc("WHERE <expression>"),
      sortByClause: (q) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.regexp(/SORT/i), parsimmon_umd_minExports.whitespace, q.sortField.sepBy1(parsimmon_umd_minExports.string(",").trim(parsimmon_umd_minExports.optWhitespace)), (sort, _1, fields) => {
        return { type: "sort", fields };
      }).desc("SORT field [ASC/DESC]"),
      limitClause: (q) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.regexp(/LIMIT/i), parsimmon_umd_minExports.whitespace, EXPRESSION.field, (limit, _1, field) => {
        return { type: "limit", amount: field };
      }).desc("LIMIT <value>"),
      flattenClause: (q) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.regexp(/FLATTEN/i).skip(parsimmon_umd_minExports.whitespace), q.namedField, (_, field) => {
        return { type: "flatten", field };
      }).desc("FLATTEN <value> [AS <name>]"),
      groupByClause: (q) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.regexp(/GROUP BY/i).skip(parsimmon_umd_minExports.whitespace), q.namedField, (_, field) => {
        return { type: "group", field };
      }).desc("GROUP BY <value> [AS <name>]"),
      // Full query parsing.
      clause: (q) => parsimmon_umd_minExports.alt(q.fromClause, q.whereClause, q.sortByClause, q.limitClause, q.groupByClause, q.flattenClause),
      query: (q) => parsimmon_umd_minExports.seqMap(q.headerClause.trim(optionalWhitespaceOrComment), q.fromClause.trim(optionalWhitespaceOrComment).atMost(1), q.clause.trim(optionalWhitespaceOrComment).many(), (header, from2, clauses) => {
        return {
          header,
          source: from2.length == 0 ? Sources.folder("") : from2[0],
          operations: clauses,
          settings: DEFAULT_QUERY_SETTINGS
        };
      })
    });
    var optionalWhitespaceOrComment = parsimmon_umd_minExports.alt(parsimmon_umd_minExports.whitespace, QUERY_LANGUAGE.comment).many().map((arr) => arr.join(""));
    var getAPI3 = (app2) => {
      if (app2)
        return app2.plugins.plugins.dataview?.api;
      else
        return window.DataviewAPI;
    };
    var isPluginEnabled2 = (app2) => app2.plugins.enabledPlugins.has("dataview");
    exports.DATE_SHORTHANDS = DATE_SHORTHANDS;
    exports.DURATION_TYPES = DURATION_TYPES;
    exports.EXPRESSION = EXPRESSION;
    exports.KEYWORDS = KEYWORDS;
    exports.QUERY_LANGUAGE = QUERY_LANGUAGE;
    exports.getAPI = getAPI3;
    exports.isPluginEnabled = isPluginEnabled2;
    exports.parseField = parseField;
  }
});

// node_modules/async-lock/lib/index.js
var require_lib2 = __commonJS({
  "node_modules/async-lock/lib/index.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    var AsyncLock = function(opts) {
      opts = opts || {};
      this.Promise = opts.Promise || Promise;
      this.queues = /* @__PURE__ */ Object.create(null);
      this.domainReentrant = opts.domainReentrant || false;
      if (this.domainReentrant) {
        if (typeof process === "undefined" || typeof process.domain === "undefined") {
          throw new Error(
            "Domain-reentrant locks require `process.domain` to exist. Please flip `opts.domainReentrant = false`, use a NodeJS version that still implements Domain, or install a browser polyfill."
          );
        }
        this.domains = /* @__PURE__ */ Object.create(null);
      }
      this.timeout = opts.timeout || AsyncLock.DEFAULT_TIMEOUT;
      this.maxOccupationTime = opts.maxOccupationTime || AsyncLock.DEFAULT_MAX_OCCUPATION_TIME;
      this.maxExecutionTime = opts.maxExecutionTime || AsyncLock.DEFAULT_MAX_EXECUTION_TIME;
      if (opts.maxPending === Infinity || Number.isInteger(opts.maxPending) && opts.maxPending >= 0) {
        this.maxPending = opts.maxPending;
      } else {
        this.maxPending = AsyncLock.DEFAULT_MAX_PENDING;
      }
    };
    AsyncLock.DEFAULT_TIMEOUT = 0;
    AsyncLock.DEFAULT_MAX_OCCUPATION_TIME = 0;
    AsyncLock.DEFAULT_MAX_EXECUTION_TIME = 0;
    AsyncLock.DEFAULT_MAX_PENDING = 1e3;
    AsyncLock.prototype.acquire = function(key, fn, cb, opts) {
      if (Array.isArray(key)) {
        return this._acquireBatch(key, fn, cb, opts);
      }
      if (typeof fn !== "function") {
        throw new Error("You must pass a function to execute");
      }
      var deferredResolve = null;
      var deferredReject = null;
      var deferred = null;
      if (typeof cb !== "function") {
        opts = cb;
        cb = null;
        deferred = new this.Promise(function(resolve, reject) {
          deferredResolve = resolve;
          deferredReject = reject;
        });
      }
      opts = opts || {};
      var resolved = false;
      var timer = null;
      var occupationTimer = null;
      var executionTimer = null;
      var self2 = this;
      var done = function(locked, err, ret) {
        if (occupationTimer) {
          clearTimeout(occupationTimer);
          occupationTimer = null;
        }
        if (executionTimer) {
          clearTimeout(executionTimer);
          executionTimer = null;
        }
        if (locked) {
          if (!!self2.queues[key] && self2.queues[key].length === 0) {
            delete self2.queues[key];
          }
          if (self2.domainReentrant) {
            delete self2.domains[key];
          }
        }
        if (!resolved) {
          if (!deferred) {
            if (typeof cb === "function") {
              cb(err, ret);
            }
          } else {
            if (err) {
              deferredReject(err);
            } else {
              deferredResolve(ret);
            }
          }
          resolved = true;
        }
        if (locked) {
          if (!!self2.queues[key] && self2.queues[key].length > 0) {
            self2.queues[key].shift()();
          }
        }
      };
      var exec = function(locked) {
        if (resolved) {
          return done(locked);
        }
        if (timer) {
          clearTimeout(timer);
          timer = null;
        }
        if (self2.domainReentrant && locked) {
          self2.domains[key] = process.domain;
        }
        var maxExecutionTime = opts.maxExecutionTime || self2.maxExecutionTime;
        if (maxExecutionTime) {
          executionTimer = setTimeout(function() {
            if (!!self2.queues[key]) {
              done(locked, new Error("Maximum execution time is exceeded " + key));
            }
          }, maxExecutionTime);
        }
        if (fn.length === 1) {
          var called = false;
          try {
            fn(function(err, ret) {
              if (!called) {
                called = true;
                done(locked, err, ret);
              }
            });
          } catch (err) {
            if (!called) {
              called = true;
              done(locked, err);
            }
          }
        } else {
          self2._promiseTry(function() {
            return fn();
          }).then(function(ret) {
            done(locked, void 0, ret);
          }, function(error) {
            done(locked, error);
          });
        }
      };
      if (self2.domainReentrant && !!process.domain) {
        exec = process.domain.bind(exec);
      }
      var maxPending = opts.maxPending || self2.maxPending;
      if (!self2.queues[key]) {
        self2.queues[key] = [];
        exec(true);
      } else if (self2.domainReentrant && !!process.domain && process.domain === self2.domains[key]) {
        exec(false);
      } else if (self2.queues[key].length >= maxPending) {
        done(false, new Error("Too many pending tasks in queue " + key));
      } else {
        var taskFn = function() {
          exec(true);
        };
        if (opts.skipQueue) {
          self2.queues[key].unshift(taskFn);
        } else {
          self2.queues[key].push(taskFn);
        }
        var timeout = opts.timeout || self2.timeout;
        if (timeout) {
          timer = setTimeout(function() {
            timer = null;
            done(false, new Error("async-lock timed out in queue " + key));
          }, timeout);
        }
      }
      var maxOccupationTime = opts.maxOccupationTime || self2.maxOccupationTime;
      if (maxOccupationTime) {
        occupationTimer = setTimeout(function() {
          if (!!self2.queues[key]) {
            done(false, new Error("Maximum occupation time is exceeded in queue " + key));
          }
        }, maxOccupationTime);
      }
      if (deferred) {
        return deferred;
      }
    };
    AsyncLock.prototype._acquireBatch = function(keys, fn, cb, opts) {
      if (typeof cb !== "function") {
        opts = cb;
        cb = null;
      }
      var self2 = this;
      var getFn = function(key, fn2) {
        return function(cb2) {
          self2.acquire(key, fn2, cb2, opts);
        };
      };
      var fnx = keys.reduceRight(function(prev, key) {
        return getFn(key, prev);
      }, fn);
      if (typeof cb === "function") {
        fnx(cb);
      } else {
        return new this.Promise(function(resolve, reject) {
          if (fnx.length === 1) {
            fnx(function(err, ret) {
              if (err) {
                reject(err);
              } else {
                resolve(ret);
              }
            });
          } else {
            resolve(fnx());
          }
        });
      }
    };
    AsyncLock.prototype.isBusy = function(key) {
      if (!key) {
        return Object.keys(this.queues).length > 0;
      } else {
        return !!this.queues[key];
      }
    };
    AsyncLock.prototype._promiseTry = function(fn) {
      try {
        return this.Promise.resolve(fn());
      } catch (e) {
        return this.Promise.reject(e);
      }
    };
    module2.exports = AsyncLock;
  }
});

// node_modules/async-lock/index.js
var require_async_lock = __commonJS({
  "node_modules/async-lock/index.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    module2.exports = require_lib2();
  }
});

// node_modules/inherits/inherits_browser.js
var require_inherits_browser = __commonJS({
  "node_modules/inherits/inherits_browser.js"(exports, module2) {
    init_esbuild_buffer_shim();
    if (typeof Object.create === "function") {
      module2.exports = function inherits(ctor, superCtor) {
        if (superCtor) {
          ctor.super_ = superCtor;
          ctor.prototype = Object.create(superCtor.prototype, {
            constructor: {
              value: ctor,
              enumerable: false,
              writable: true,
              configurable: true
            }
          });
        }
      };
    } else {
      module2.exports = function inherits(ctor, superCtor) {
        if (superCtor) {
          ctor.super_ = superCtor;
          var TempCtor = function() {
          };
          TempCtor.prototype = superCtor.prototype;
          ctor.prototype = new TempCtor();
          ctor.prototype.constructor = ctor;
        }
      };
    }
  }
});

// node_modules/sha.js/node_modules/safe-buffer/index.js
var require_safe_buffer = __commonJS({
  "node_modules/sha.js/node_modules/safe-buffer/index.js"(exports, module2) {
    init_esbuild_buffer_shim();
    var buffer = (init_buffer_es6(), __toCommonJS(buffer_es6_exports));
    var Buffer3 = buffer.Buffer;
    function copyProps(src, dst) {
      for (var key in src) {
        dst[key] = src[key];
      }
    }
    if (Buffer3.from && Buffer3.alloc && Buffer3.allocUnsafe && Buffer3.allocUnsafeSlow) {
      module2.exports = buffer;
    } else {
      copyProps(buffer, exports);
      exports.Buffer = SafeBuffer;
    }
    function SafeBuffer(arg, encodingOrOffset, length) {
      return Buffer3(arg, encodingOrOffset, length);
    }
    SafeBuffer.prototype = Object.create(Buffer3.prototype);
    copyProps(Buffer3, SafeBuffer);
    SafeBuffer.from = function(arg, encodingOrOffset, length) {
      if (typeof arg === "number") {
        throw new TypeError("Argument must not be a number");
      }
      return Buffer3(arg, encodingOrOffset, length);
    };
    SafeBuffer.alloc = function(size, fill2, encoding) {
      if (typeof size !== "number") {
        throw new TypeError("Argument must be a number");
      }
      var buf = Buffer3(size);
      if (fill2 !== void 0) {
        if (typeof encoding === "string") {
          buf.fill(fill2, encoding);
        } else {
          buf.fill(fill2);
        }
      } else {
        buf.fill(0);
      }
      return buf;
    };
    SafeBuffer.allocUnsafe = function(size) {
      if (typeof size !== "number") {
        throw new TypeError("Argument must be a number");
      }
      return Buffer3(size);
    };
    SafeBuffer.allocUnsafeSlow = function(size) {
      if (typeof size !== "number") {
        throw new TypeError("Argument must be a number");
      }
      return buffer.SlowBuffer(size);
    };
  }
});

// node_modules/to-buffer/node_modules/safe-buffer/index.js
var require_safe_buffer2 = __commonJS({
  "node_modules/to-buffer/node_modules/safe-buffer/index.js"(exports, module2) {
    init_esbuild_buffer_shim();
    var buffer = (init_buffer_es6(), __toCommonJS(buffer_es6_exports));
    var Buffer3 = buffer.Buffer;
    function copyProps(src, dst) {
      for (var key in src) {
        dst[key] = src[key];
      }
    }
    if (Buffer3.from && Buffer3.alloc && Buffer3.allocUnsafe && Buffer3.allocUnsafeSlow) {
      module2.exports = buffer;
    } else {
      copyProps(buffer, exports);
      exports.Buffer = SafeBuffer;
    }
    function SafeBuffer(arg, encodingOrOffset, length) {
      return Buffer3(arg, encodingOrOffset, length);
    }
    SafeBuffer.prototype = Object.create(Buffer3.prototype);
    copyProps(Buffer3, SafeBuffer);
    SafeBuffer.from = function(arg, encodingOrOffset, length) {
      if (typeof arg === "number") {
        throw new TypeError("Argument must not be a number");
      }
      return Buffer3(arg, encodingOrOffset, length);
    };
    SafeBuffer.alloc = function(size, fill2, encoding) {
      if (typeof size !== "number") {
        throw new TypeError("Argument must be a number");
      }
      var buf = Buffer3(size);
      if (fill2 !== void 0) {
        if (typeof encoding === "string") {
          buf.fill(fill2, encoding);
        } else {
          buf.fill(fill2);
        }
      } else {
        buf.fill(0);
      }
      return buf;
    };
    SafeBuffer.allocUnsafe = function(size) {
      if (typeof size !== "number") {
        throw new TypeError("Argument must be a number");
      }
      return Buffer3(size);
    };
    SafeBuffer.allocUnsafeSlow = function(size) {
      if (typeof size !== "number") {
        throw new TypeError("Argument must be a number");
      }
      return buffer.SlowBuffer(size);
    };
  }
});

// node_modules/to-buffer/node_modules/isarray/index.js
var require_isarray = __commonJS({
  "node_modules/to-buffer/node_modules/isarray/index.js"(exports, module2) {
    init_esbuild_buffer_shim();
    var toString3 = {}.toString;
    module2.exports = Array.isArray || function(arr) {
      return toString3.call(arr) == "[object Array]";
    };
  }
});

// node_modules/es-errors/type.js
var require_type = __commonJS({
  "node_modules/es-errors/type.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    module2.exports = TypeError;
  }
});

// node_modules/es-object-atoms/index.js
var require_es_object_atoms = __commonJS({
  "node_modules/es-object-atoms/index.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    module2.exports = Object;
  }
});

// node_modules/es-errors/index.js
var require_es_errors = __commonJS({
  "node_modules/es-errors/index.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    module2.exports = Error;
  }
});

// node_modules/es-errors/eval.js
var require_eval = __commonJS({
  "node_modules/es-errors/eval.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    module2.exports = EvalError;
  }
});

// node_modules/es-errors/range.js
var require_range = __commonJS({
  "node_modules/es-errors/range.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    module2.exports = RangeError;
  }
});

// node_modules/es-errors/ref.js
var require_ref = __commonJS({
  "node_modules/es-errors/ref.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    module2.exports = ReferenceError;
  }
});

// node_modules/es-errors/syntax.js
var require_syntax = __commonJS({
  "node_modules/es-errors/syntax.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    module2.exports = SyntaxError;
  }
});

// node_modules/es-errors/uri.js
var require_uri = __commonJS({
  "node_modules/es-errors/uri.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    module2.exports = URIError;
  }
});

// node_modules/math-intrinsics/abs.js
var require_abs = __commonJS({
  "node_modules/math-intrinsics/abs.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    module2.exports = Math.abs;
  }
});

// node_modules/math-intrinsics/floor.js
var require_floor = __commonJS({
  "node_modules/math-intrinsics/floor.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    module2.exports = Math.floor;
  }
});

// node_modules/math-intrinsics/max.js
var require_max = __commonJS({
  "node_modules/math-intrinsics/max.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    module2.exports = Math.max;
  }
});

// node_modules/math-intrinsics/min.js
var require_min = __commonJS({
  "node_modules/math-intrinsics/min.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    module2.exports = Math.min;
  }
});

// node_modules/math-intrinsics/pow.js
var require_pow = __commonJS({
  "node_modules/math-intrinsics/pow.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    module2.exports = Math.pow;
  }
});

// node_modules/math-intrinsics/round.js
var require_round = __commonJS({
  "node_modules/math-intrinsics/round.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    module2.exports = Math.round;
  }
});

// node_modules/math-intrinsics/isNaN.js
var require_isNaN = __commonJS({
  "node_modules/math-intrinsics/isNaN.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    module2.exports = Number.isNaN || function isNaN2(a) {
      return a !== a;
    };
  }
});

// node_modules/math-intrinsics/sign.js
var require_sign = __commonJS({
  "node_modules/math-intrinsics/sign.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    var $isNaN = require_isNaN();
    module2.exports = function sign(number) {
      if ($isNaN(number) || number === 0) {
        return number;
      }
      return number < 0 ? -1 : 1;
    };
  }
});

// node_modules/gopd/gOPD.js
var require_gOPD = __commonJS({
  "node_modules/gopd/gOPD.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    module2.exports = Object.getOwnPropertyDescriptor;
  }
});

// node_modules/gopd/index.js
var require_gopd = __commonJS({
  "node_modules/gopd/index.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    var $gOPD = require_gOPD();
    if ($gOPD) {
      try {
        $gOPD([], "length");
      } catch (e) {
        $gOPD = null;
      }
    }
    module2.exports = $gOPD;
  }
});

// node_modules/es-define-property/index.js
var require_es_define_property = __commonJS({
  "node_modules/es-define-property/index.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    var $defineProperty = Object.defineProperty || false;
    if ($defineProperty) {
      try {
        $defineProperty({}, "a", { value: 1 });
      } catch (e) {
        $defineProperty = false;
      }
    }
    module2.exports = $defineProperty;
  }
});

// node_modules/has-symbols/shams.js
var require_shams = __commonJS({
  "node_modules/has-symbols/shams.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    module2.exports = function hasSymbols() {
      if (typeof Symbol !== "function" || typeof Object.getOwnPropertySymbols !== "function") {
        return false;
      }
      if (typeof Symbol.iterator === "symbol") {
        return true;
      }
      var obj = {};
      var sym = Symbol("test");
      var symObj = Object(sym);
      if (typeof sym === "string") {
        return false;
      }
      if (Object.prototype.toString.call(sym) !== "[object Symbol]") {
        return false;
      }
      if (Object.prototype.toString.call(symObj) !== "[object Symbol]") {
        return false;
      }
      var symVal = 42;
      obj[sym] = symVal;
      for (var _ in obj) {
        return false;
      }
      if (typeof Object.keys === "function" && Object.keys(obj).length !== 0) {
        return false;
      }
      if (typeof Object.getOwnPropertyNames === "function" && Object.getOwnPropertyNames(obj).length !== 0) {
        return false;
      }
      var syms = Object.getOwnPropertySymbols(obj);
      if (syms.length !== 1 || syms[0] !== sym) {
        return false;
      }
      if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) {
        return false;
      }
      if (typeof Object.getOwnPropertyDescriptor === "function") {
        var descriptor = (
          /** @type {PropertyDescriptor} */
          Object.getOwnPropertyDescriptor(obj, sym)
        );
        if (descriptor.value !== symVal || descriptor.enumerable !== true) {
          return false;
        }
      }
      return true;
    };
  }
});

// node_modules/has-symbols/index.js
var require_has_symbols = __commonJS({
  "node_modules/has-symbols/index.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    var origSymbol = typeof Symbol !== "undefined" && Symbol;
    var hasSymbolSham = require_shams();
    module2.exports = function hasNativeSymbols() {
      if (typeof origSymbol !== "function") {
        return false;
      }
      if (typeof Symbol !== "function") {
        return false;
      }
      if (typeof origSymbol("foo") !== "symbol") {
        return false;
      }
      if (typeof Symbol("bar") !== "symbol") {
        return false;
      }
      return hasSymbolSham();
    };
  }
});

// node_modules/get-proto/Reflect.getPrototypeOf.js
var require_Reflect_getPrototypeOf = __commonJS({
  "node_modules/get-proto/Reflect.getPrototypeOf.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    module2.exports = typeof Reflect !== "undefined" && Reflect.getPrototypeOf || null;
  }
});

// node_modules/get-proto/Object.getPrototypeOf.js
var require_Object_getPrototypeOf = __commonJS({
  "node_modules/get-proto/Object.getPrototypeOf.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    var $Object = require_es_object_atoms();
    module2.exports = $Object.getPrototypeOf || null;
  }
});

// node_modules/function-bind/implementation.js
var require_implementation = __commonJS({
  "node_modules/function-bind/implementation.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    var ERROR_MESSAGE = "Function.prototype.bind called on incompatible ";
    var toStr = Object.prototype.toString;
    var max = Math.max;
    var funcType = "[object Function]";
    var concatty = function concatty2(a, b) {
      var arr = [];
      for (var i = 0; i < a.length; i += 1) {
        arr[i] = a[i];
      }
      for (var j = 0; j < b.length; j += 1) {
        arr[j + a.length] = b[j];
      }
      return arr;
    };
    var slicy = function slicy2(arrLike, offset2) {
      var arr = [];
      for (var i = offset2 || 0, j = 0; i < arrLike.length; i += 1, j += 1) {
        arr[j] = arrLike[i];
      }
      return arr;
    };
    var joiny = function(arr, joiner) {
      var str = "";
      for (var i = 0; i < arr.length; i += 1) {
        str += arr[i];
        if (i + 1 < arr.length) {
          str += joiner;
        }
      }
      return str;
    };
    module2.exports = function bind(that) {
      var target = this;
      if (typeof target !== "function" || toStr.apply(target) !== funcType) {
        throw new TypeError(ERROR_MESSAGE + target);
      }
      var args = slicy(arguments, 1);
      var bound;
      var binder = function() {
        if (this instanceof bound) {
          var result = target.apply(
            this,
            concatty(args, arguments)
          );
          if (Object(result) === result) {
            return result;
          }
          return this;
        }
        return target.apply(
          that,
          concatty(args, arguments)
        );
      };
      var boundLength = max(0, target.length - args.length);
      var boundArgs = [];
      for (var i = 0; i < boundLength; i++) {
        boundArgs[i] = "$" + i;
      }
      bound = Function("binder", "return function (" + joiny(boundArgs, ",") + "){ return binder.apply(this,arguments); }")(binder);
      if (target.prototype) {
        var Empty = function Empty2() {
        };
        Empty.prototype = target.prototype;
        bound.prototype = new Empty();
        Empty.prototype = null;
      }
      return bound;
    };
  }
});

// node_modules/function-bind/index.js
var require_function_bind = __commonJS({
  "node_modules/function-bind/index.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    var implementation = require_implementation();
    module2.exports = Function.prototype.bind || implementation;
  }
});

// node_modules/call-bind-apply-helpers/functionCall.js
var require_functionCall = __commonJS({
  "node_modules/call-bind-apply-helpers/functionCall.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    module2.exports = Function.prototype.call;
  }
});

// node_modules/call-bind-apply-helpers/functionApply.js
var require_functionApply = __commonJS({
  "node_modules/call-bind-apply-helpers/functionApply.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    module2.exports = Function.prototype.apply;
  }
});

// node_modules/call-bind-apply-helpers/reflectApply.js
var require_reflectApply = __commonJS({
  "node_modules/call-bind-apply-helpers/reflectApply.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    module2.exports = typeof Reflect !== "undefined" && Reflect && Reflect.apply;
  }
});

// node_modules/call-bind-apply-helpers/actualApply.js
var require_actualApply = __commonJS({
  "node_modules/call-bind-apply-helpers/actualApply.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    var bind = require_function_bind();
    var $apply = require_functionApply();
    var $call = require_functionCall();
    var $reflectApply = require_reflectApply();
    module2.exports = $reflectApply || bind.call($call, $apply);
  }
});

// node_modules/call-bind-apply-helpers/index.js
var require_call_bind_apply_helpers = __commonJS({
  "node_modules/call-bind-apply-helpers/index.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    var bind = require_function_bind();
    var $TypeError = require_type();
    var $call = require_functionCall();
    var $actualApply = require_actualApply();
    module2.exports = function callBindBasic(args) {
      if (args.length < 1 || typeof args[0] !== "function") {
        throw new $TypeError("a function is required");
      }
      return $actualApply(bind, $call, args);
    };
  }
});

// node_modules/dunder-proto/get.js
var require_get = __commonJS({
  "node_modules/dunder-proto/get.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    var callBind = require_call_bind_apply_helpers();
    var gOPD = require_gopd();
    var hasProtoAccessor;
    try {
      hasProtoAccessor = /** @type {{ __proto__?: typeof Array.prototype }} */
      [].__proto__ === Array.prototype;
    } catch (e) {
      if (!e || typeof e !== "object" || !("code" in e) || e.code !== "ERR_PROTO_ACCESS") {
        throw e;
      }
    }
    var desc = !!hasProtoAccessor && gOPD && gOPD(
      Object.prototype,
      /** @type {keyof typeof Object.prototype} */
      "__proto__"
    );
    var $Object = Object;
    var $getPrototypeOf = $Object.getPrototypeOf;
    module2.exports = desc && typeof desc.get === "function" ? callBind([desc.get]) : typeof $getPrototypeOf === "function" ? (
      /** @type {import('./get')} */
      function getDunder(value) {
        return $getPrototypeOf(value == null ? value : $Object(value));
      }
    ) : false;
  }
});

// node_modules/get-proto/index.js
var require_get_proto = __commonJS({
  "node_modules/get-proto/index.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    var reflectGetProto = require_Reflect_getPrototypeOf();
    var originalGetProto = require_Object_getPrototypeOf();
    var getDunderProto = require_get();
    module2.exports = reflectGetProto ? function getProto(O) {
      return reflectGetProto(O);
    } : originalGetProto ? function getProto(O) {
      if (!O || typeof O !== "object" && typeof O !== "function") {
        throw new TypeError("getProto: not an object");
      }
      return originalGetProto(O);
    } : getDunderProto ? function getProto(O) {
      return getDunderProto(O);
    } : null;
  }
});

// node_modules/hasown/index.js
var require_hasown = __commonJS({
  "node_modules/hasown/index.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    var call = Function.prototype.call;
    var $hasOwn = Object.prototype.hasOwnProperty;
    var bind = require_function_bind();
    module2.exports = bind.call(call, $hasOwn);
  }
});

// node_modules/get-intrinsic/index.js
var require_get_intrinsic = __commonJS({
  "node_modules/get-intrinsic/index.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    var undefined2;
    var $Object = require_es_object_atoms();
    var $Error = require_es_errors();
    var $EvalError = require_eval();
    var $RangeError = require_range();
    var $ReferenceError = require_ref();
    var $SyntaxError = require_syntax();
    var $TypeError = require_type();
    var $URIError = require_uri();
    var abs = require_abs();
    var floor = require_floor();
    var max = require_max();
    var min = require_min();
    var pow = require_pow();
    var round = require_round();
    var sign = require_sign();
    var $Function = Function;
    var getEvalledConstructor = function(expressionSyntax) {
      try {
        return $Function('"use strict"; return (' + expressionSyntax + ").constructor;")();
      } catch (e) {
      }
    };
    var $gOPD = require_gopd();
    var $defineProperty = require_es_define_property();
    var throwTypeError = function() {
      throw new $TypeError();
    };
    var ThrowTypeError = $gOPD ? function() {
      try {
        arguments.callee;
        return throwTypeError;
      } catch (calleeThrows) {
        try {
          return $gOPD(arguments, "callee").get;
        } catch (gOPDthrows) {
          return throwTypeError;
        }
      }
    }() : throwTypeError;
    var hasSymbols = require_has_symbols()();
    var getProto = require_get_proto();
    var $ObjectGPO = require_Object_getPrototypeOf();
    var $ReflectGPO = require_Reflect_getPrototypeOf();
    var $apply = require_functionApply();
    var $call = require_functionCall();
    var needsEval = {};
    var TypedArray = typeof Uint8Array === "undefined" || !getProto ? undefined2 : getProto(Uint8Array);
    var INTRINSICS = {
      __proto__: null,
      "%AggregateError%": typeof AggregateError === "undefined" ? undefined2 : AggregateError,
      "%Array%": Array,
      "%ArrayBuffer%": typeof ArrayBuffer === "undefined" ? undefined2 : ArrayBuffer,
      "%ArrayIteratorPrototype%": hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined2,
      "%AsyncFromSyncIteratorPrototype%": undefined2,
      "%AsyncFunction%": needsEval,
      "%AsyncGenerator%": needsEval,
      "%AsyncGeneratorFunction%": needsEval,
      "%AsyncIteratorPrototype%": needsEval,
      "%Atomics%": typeof Atomics === "undefined" ? undefined2 : Atomics,
      "%BigInt%": typeof BigInt === "undefined" ? undefined2 : BigInt,
      "%BigInt64Array%": typeof BigInt64Array === "undefined" ? undefined2 : BigInt64Array,
      "%BigUint64Array%": typeof BigUint64Array === "undefined" ? undefined2 : BigUint64Array,
      "%Boolean%": Boolean,
      "%DataView%": typeof DataView === "undefined" ? undefined2 : DataView,
      "%Date%": Date,
      "%decodeURI%": decodeURI,
      "%decodeURIComponent%": decodeURIComponent,
      "%encodeURI%": encodeURI,
      "%encodeURIComponent%": encodeURIComponent,
      "%Error%": $Error,
      "%eval%": eval,
      // eslint-disable-line no-eval
      "%EvalError%": $EvalError,
      "%Float16Array%": typeof Float16Array === "undefined" ? undefined2 : Float16Array,
      "%Float32Array%": typeof Float32Array === "undefined" ? undefined2 : Float32Array,
      "%Float64Array%": typeof Float64Array === "undefined" ? undefined2 : Float64Array,
      "%FinalizationRegistry%": typeof FinalizationRegistry === "undefined" ? undefined2 : FinalizationRegistry,
      "%Function%": $Function,
      "%GeneratorFunction%": needsEval,
      "%Int8Array%": typeof Int8Array === "undefined" ? undefined2 : Int8Array,
      "%Int16Array%": typeof Int16Array === "undefined" ? undefined2 : Int16Array,
      "%Int32Array%": typeof Int32Array === "undefined" ? undefined2 : Int32Array,
      "%isFinite%": isFinite,
      "%isNaN%": isNaN,
      "%IteratorPrototype%": hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined2,
      "%JSON%": typeof JSON === "object" ? JSON : undefined2,
      "%Map%": typeof Map === "undefined" ? undefined2 : Map,
      "%MapIteratorPrototype%": typeof Map === "undefined" || !hasSymbols || !getProto ? undefined2 : getProto((/* @__PURE__ */ new Map())[Symbol.iterator]()),
      "%Math%": Math,
      "%Number%": Number,
      "%Object%": $Object,
      "%Object.getOwnPropertyDescriptor%": $gOPD,
      "%parseFloat%": parseFloat,
      "%parseInt%": parseInt,
      "%Promise%": typeof Promise === "undefined" ? undefined2 : Promise,
      "%Proxy%": typeof Proxy === "undefined" ? undefined2 : Proxy,
      "%RangeError%": $RangeError,
      "%ReferenceError%": $ReferenceError,
      "%Reflect%": typeof Reflect === "undefined" ? undefined2 : Reflect,
      "%RegExp%": RegExp,
      "%Set%": typeof Set === "undefined" ? undefined2 : Set,
      "%SetIteratorPrototype%": typeof Set === "undefined" || !hasSymbols || !getProto ? undefined2 : getProto((/* @__PURE__ */ new Set())[Symbol.iterator]()),
      "%SharedArrayBuffer%": typeof SharedArrayBuffer === "undefined" ? undefined2 : SharedArrayBuffer,
      "%String%": String,
      "%StringIteratorPrototype%": hasSymbols && getProto ? getProto(""[Symbol.iterator]()) : undefined2,
      "%Symbol%": hasSymbols ? Symbol : undefined2,
      "%SyntaxError%": $SyntaxError,
      "%ThrowTypeError%": ThrowTypeError,
      "%TypedArray%": TypedArray,
      "%TypeError%": $TypeError,
      "%Uint8Array%": typeof Uint8Array === "undefined" ? undefined2 : Uint8Array,
      "%Uint8ClampedArray%": typeof Uint8ClampedArray === "undefined" ? undefined2 : Uint8ClampedArray,
      "%Uint16Array%": typeof Uint16Array === "undefined" ? undefined2 : Uint16Array,
      "%Uint32Array%": typeof Uint32Array === "undefined" ? undefined2 : Uint32Array,
      "%URIError%": $URIError,
      "%WeakMap%": typeof WeakMap === "undefined" ? undefined2 : WeakMap,
      "%WeakRef%": typeof WeakRef === "undefined" ? undefined2 : WeakRef,
      "%WeakSet%": typeof WeakSet === "undefined" ? undefined2 : WeakSet,
      "%Function.prototype.call%": $call,
      "%Function.prototype.apply%": $apply,
      "%Object.defineProperty%": $defineProperty,
      "%Object.getPrototypeOf%": $ObjectGPO,
      "%Math.abs%": abs,
      "%Math.floor%": floor,
      "%Math.max%": max,
      "%Math.min%": min,
      "%Math.pow%": pow,
      "%Math.round%": round,
      "%Math.sign%": sign,
      "%Reflect.getPrototypeOf%": $ReflectGPO
    };
    if (getProto) {
      try {
        null.error;
      } catch (e) {
        errorProto = getProto(getProto(e));
        INTRINSICS["%Error.prototype%"] = errorProto;
      }
    }
    var errorProto;
    var doEval = function doEval2(name) {
      var value;
      if (name === "%AsyncFunction%") {
        value = getEvalledConstructor("async function () {}");
      } else if (name === "%GeneratorFunction%") {
        value = getEvalledConstructor("function* () {}");
      } else if (name === "%AsyncGeneratorFunction%") {
        value = getEvalledConstructor("async function* () {}");
      } else if (name === "%AsyncGenerator%") {
        var fn = doEval2("%AsyncGeneratorFunction%");
        if (fn) {
          value = fn.prototype;
        }
      } else if (name === "%AsyncIteratorPrototype%") {
        var gen = doEval2("%AsyncGenerator%");
        if (gen && getProto) {
          value = getProto(gen.prototype);
        }
      }
      INTRINSICS[name] = value;
      return value;
    };
    var LEGACY_ALIASES = {
      __proto__: null,
      "%ArrayBufferPrototype%": ["ArrayBuffer", "prototype"],
      "%ArrayPrototype%": ["Array", "prototype"],
      "%ArrayProto_entries%": ["Array", "prototype", "entries"],
      "%ArrayProto_forEach%": ["Array", "prototype", "forEach"],
      "%ArrayProto_keys%": ["Array", "prototype", "keys"],
      "%ArrayProto_values%": ["Array", "prototype", "values"],
      "%AsyncFunctionPrototype%": ["AsyncFunction", "prototype"],
      "%AsyncGenerator%": ["AsyncGeneratorFunction", "prototype"],
      "%AsyncGeneratorPrototype%": ["AsyncGeneratorFunction", "prototype", "prototype"],
      "%BooleanPrototype%": ["Boolean", "prototype"],
      "%DataViewPrototype%": ["DataView", "prototype"],
      "%DatePrototype%": ["Date", "prototype"],
      "%ErrorPrototype%": ["Error", "prototype"],
      "%EvalErrorPrototype%": ["EvalError", "prototype"],
      "%Float32ArrayPrototype%": ["Float32Array", "prototype"],
      "%Float64ArrayPrototype%": ["Float64Array", "prototype"],
      "%FunctionPrototype%": ["Function", "prototype"],
      "%Generator%": ["GeneratorFunction", "prototype"],
      "%GeneratorPrototype%": ["GeneratorFunction", "prototype", "prototype"],
      "%Int8ArrayPrototype%": ["Int8Array", "prototype"],
      "%Int16ArrayPrototype%": ["Int16Array", "prototype"],
      "%Int32ArrayPrototype%": ["Int32Array", "prototype"],
      "%JSONParse%": ["JSON", "parse"],
      "%JSONStringify%": ["JSON", "stringify"],
      "%MapPrototype%": ["Map", "prototype"],
      "%NumberPrototype%": ["Number", "prototype"],
      "%ObjectPrototype%": ["Object", "prototype"],
      "%ObjProto_toString%": ["Object", "prototype", "toString"],
      "%ObjProto_valueOf%": ["Object", "prototype", "valueOf"],
      "%PromisePrototype%": ["Promise", "prototype"],
      "%PromiseProto_then%": ["Promise", "prototype", "then"],
      "%Promise_all%": ["Promise", "all"],
      "%Promise_reject%": ["Promise", "reject"],
      "%Promise_resolve%": ["Promise", "resolve"],
      "%RangeErrorPrototype%": ["RangeError", "prototype"],
      "%ReferenceErrorPrototype%": ["ReferenceError", "prototype"],
      "%RegExpPrototype%": ["RegExp", "prototype"],
      "%SetPrototype%": ["Set", "prototype"],
      "%SharedArrayBufferPrototype%": ["SharedArrayBuffer", "prototype"],
      "%StringPrototype%": ["String", "prototype"],
      "%SymbolPrototype%": ["Symbol", "prototype"],
      "%SyntaxErrorPrototype%": ["SyntaxError", "prototype"],
      "%TypedArrayPrototype%": ["TypedArray", "prototype"],
      "%TypeErrorPrototype%": ["TypeError", "prototype"],
      "%Uint8ArrayPrototype%": ["Uint8Array", "prototype"],
      "%Uint8ClampedArrayPrototype%": ["Uint8ClampedArray", "prototype"],
      "%Uint16ArrayPrototype%": ["Uint16Array", "prototype"],
      "%Uint32ArrayPrototype%": ["Uint32Array", "prototype"],
      "%URIErrorPrototype%": ["URIError", "prototype"],
      "%WeakMapPrototype%": ["WeakMap", "prototype"],
      "%WeakSetPrototype%": ["WeakSet", "prototype"]
    };
    var bind = require_function_bind();
    var hasOwn = require_hasown();
    var $concat = bind.call($call, Array.prototype.concat);
    var $spliceApply = bind.call($apply, Array.prototype.splice);
    var $replace = bind.call($call, String.prototype.replace);
    var $strSlice = bind.call($call, String.prototype.slice);
    var $exec = bind.call($call, RegExp.prototype.exec);
    var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
    var reEscapeChar = /\\(\\)?/g;
    var stringToPath = function stringToPath2(string) {
      var first = $strSlice(string, 0, 1);
      var last = $strSlice(string, -1);
      if (first === "%" && last !== "%") {
        throw new $SyntaxError("invalid intrinsic syntax, expected closing `%`");
      } else if (last === "%" && first !== "%") {
        throw new $SyntaxError("invalid intrinsic syntax, expected opening `%`");
      }
      var result = [];
      $replace(string, rePropName, function(match2, number, quote, subString) {
        result[result.length] = quote ? $replace(subString, reEscapeChar, "$1") : number || match2;
      });
      return result;
    };
    var getBaseIntrinsic = function getBaseIntrinsic2(name, allowMissing) {
      var intrinsicName = name;
      var alias;
      if (hasOwn(LEGACY_ALIASES, intrinsicName)) {
        alias = LEGACY_ALIASES[intrinsicName];
        intrinsicName = "%" + alias[0] + "%";
      }
      if (hasOwn(INTRINSICS, intrinsicName)) {
        var value = INTRINSICS[intrinsicName];
        if (value === needsEval) {
          value = doEval(intrinsicName);
        }
        if (typeof value === "undefined" && !allowMissing) {
          throw new $TypeError("intrinsic " + name + " exists, but is not available. Please file an issue!");
        }
        return {
          alias,
          name: intrinsicName,
          value
        };
      }
      throw new $SyntaxError("intrinsic " + name + " does not exist!");
    };
    module2.exports = function GetIntrinsic(name, allowMissing) {
      if (typeof name !== "string" || name.length === 0) {
        throw new $TypeError("intrinsic name must be a non-empty string");
      }
      if (arguments.length > 1 && typeof allowMissing !== "boolean") {
        throw new $TypeError('"allowMissing" argument must be a boolean');
      }
      if ($exec(/^%?[^%]*%?$/, name) === null) {
        throw new $SyntaxError("`%` may not be present anywhere but at the beginning and end of the intrinsic name");
      }
      var parts = stringToPath(name);
      var intrinsicBaseName = parts.length > 0 ? parts[0] : "";
      var intrinsic = getBaseIntrinsic("%" + intrinsicBaseName + "%", allowMissing);
      var intrinsicRealName = intrinsic.name;
      var value = intrinsic.value;
      var skipFurtherCaching = false;
      var alias = intrinsic.alias;
      if (alias) {
        intrinsicBaseName = alias[0];
        $spliceApply(parts, $concat([0, 1], alias));
      }
      for (var i = 1, isOwn = true; i < parts.length; i += 1) {
        var part = parts[i];
        var first = $strSlice(part, 0, 1);
        var last = $strSlice(part, -1);
        if ((first === '"' || first === "'" || first === "`" || (last === '"' || last === "'" || last === "`")) && first !== last) {
          throw new $SyntaxError("property names with quotes must have matching quotes");
        }
        if (part === "constructor" || !isOwn) {
          skipFurtherCaching = true;
        }
        intrinsicBaseName += "." + part;
        intrinsicRealName = "%" + intrinsicBaseName + "%";
        if (hasOwn(INTRINSICS, intrinsicRealName)) {
          value = INTRINSICS[intrinsicRealName];
        } else if (value != null) {
          if (!(part in value)) {
            if (!allowMissing) {
              throw new $TypeError("base intrinsic for " + name + " exists, but the property is not available.");
            }
            return void undefined2;
          }
          if ($gOPD && i + 1 >= parts.length) {
            var desc = $gOPD(value, part);
            isOwn = !!desc;
            if (isOwn && "get" in desc && !("originalValue" in desc.get)) {
              value = desc.get;
            } else {
              value = value[part];
            }
          } else {
            isOwn = hasOwn(value, part);
            value = value[part];
          }
          if (isOwn && !skipFurtherCaching) {
            INTRINSICS[intrinsicRealName] = value;
          }
        }
      }
      return value;
    };
  }
});

// node_modules/call-bound/index.js
var require_call_bound = __commonJS({
  "node_modules/call-bound/index.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    var GetIntrinsic = require_get_intrinsic();
    var callBindBasic = require_call_bind_apply_helpers();
    var $indexOf = callBindBasic([GetIntrinsic("%String.prototype.indexOf%")]);
    module2.exports = function callBoundIntrinsic(name, allowMissing) {
      var intrinsic = (
        /** @type {(this: unknown, ...args: unknown[]) => unknown} */
        GetIntrinsic(name, !!allowMissing)
      );
      if (typeof intrinsic === "function" && $indexOf(name, ".prototype.") > -1) {
        return callBindBasic(
          /** @type {const} */
          [intrinsic]
        );
      }
      return intrinsic;
    };
  }
});

// node_modules/is-callable/index.js
var require_is_callable = __commonJS({
  "node_modules/is-callable/index.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    var fnToStr = Function.prototype.toString;
    var reflectApply = typeof Reflect === "object" && Reflect !== null && Reflect.apply;
    var badArrayLike;
    var isCallableMarker;
    if (typeof reflectApply === "function" && typeof Object.defineProperty === "function") {
      try {
        badArrayLike = Object.defineProperty({}, "length", {
          get: function() {
            throw isCallableMarker;
          }
        });
        isCallableMarker = {};
        reflectApply(function() {
          throw 42;
        }, null, badArrayLike);
      } catch (_) {
        if (_ !== isCallableMarker) {
          reflectApply = null;
        }
      }
    } else {
      reflectApply = null;
    }
    var constructorRegex = /^\s*class\b/;
    var isES6ClassFn = function isES6ClassFunction(value) {
      try {
        var fnStr = fnToStr.call(value);
        return constructorRegex.test(fnStr);
      } catch (e) {
        return false;
      }
    };
    var tryFunctionObject = function tryFunctionToStr(value) {
      try {
        if (isES6ClassFn(value)) {
          return false;
        }
        fnToStr.call(value);
        return true;
      } catch (e) {
        return false;
      }
    };
    var toStr = Object.prototype.toString;
    var objectClass = "[object Object]";
    var fnClass = "[object Function]";
    var genClass = "[object GeneratorFunction]";
    var ddaClass = "[object HTMLAllCollection]";
    var ddaClass2 = "[object HTML document.all class]";
    var ddaClass3 = "[object HTMLCollection]";
    var hasToStringTag = typeof Symbol === "function" && !!Symbol.toStringTag;
    var isIE68 = !(0 in [,]);
    var isDDA = function isDocumentDotAll() {
      return false;
    };
    if (typeof document === "object") {
      all = document.all;
      if (toStr.call(all) === toStr.call(document.all)) {
        isDDA = function isDocumentDotAll(value) {
          if ((isIE68 || !value) && (typeof value === "undefined" || typeof value === "object")) {
            try {
              var str = toStr.call(value);
              return (str === ddaClass || str === ddaClass2 || str === ddaClass3 || str === objectClass) && value("") == null;
            } catch (e) {
            }
          }
          return false;
        };
      }
    }
    var all;
    module2.exports = reflectApply ? function isCallable(value) {
      if (isDDA(value)) {
        return true;
      }
      if (!value) {
        return false;
      }
      if (typeof value !== "function" && typeof value !== "object") {
        return false;
      }
      try {
        reflectApply(value, null, badArrayLike);
      } catch (e) {
        if (e !== isCallableMarker) {
          return false;
        }
      }
      return !isES6ClassFn(value) && tryFunctionObject(value);
    } : function isCallable(value) {
      if (isDDA(value)) {
        return true;
      }
      if (!value) {
        return false;
      }
      if (typeof value !== "function" && typeof value !== "object") {
        return false;
      }
      if (hasToStringTag) {
        return tryFunctionObject(value);
      }
      if (isES6ClassFn(value)) {
        return false;
      }
      var strClass = toStr.call(value);
      if (strClass !== fnClass && strClass !== genClass && !/^\[object HTML/.test(strClass)) {
        return false;
      }
      return tryFunctionObject(value);
    };
  }
});

// node_modules/for-each/index.js
var require_for_each = __commonJS({
  "node_modules/for-each/index.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    var isCallable = require_is_callable();
    var toStr = Object.prototype.toString;
    var hasOwnProperty2 = Object.prototype.hasOwnProperty;
    var forEachArray = function forEachArray2(array, iterator, receiver) {
      for (var i = 0, len = array.length; i < len; i++) {
        if (hasOwnProperty2.call(array, i)) {
          if (receiver == null) {
            iterator(array[i], i, array);
          } else {
            iterator.call(receiver, array[i], i, array);
          }
        }
      }
    };
    var forEachString = function forEachString2(string, iterator, receiver) {
      for (var i = 0, len = string.length; i < len; i++) {
        if (receiver == null) {
          iterator(string.charAt(i), i, string);
        } else {
          iterator.call(receiver, string.charAt(i), i, string);
        }
      }
    };
    var forEachObject = function forEachObject2(object, iterator, receiver) {
      for (var k in object) {
        if (hasOwnProperty2.call(object, k)) {
          if (receiver == null) {
            iterator(object[k], k, object);
          } else {
            iterator.call(receiver, object[k], k, object);
          }
        }
      }
    };
    function isArray(x) {
      return toStr.call(x) === "[object Array]";
    }
    module2.exports = function forEach(list, iterator, thisArg) {
      if (!isCallable(iterator)) {
        throw new TypeError("iterator must be a function");
      }
      var receiver;
      if (arguments.length >= 3) {
        receiver = thisArg;
      }
      if (isArray(list)) {
        forEachArray(list, iterator, receiver);
      } else if (typeof list === "string") {
        forEachString(list, iterator, receiver);
      } else {
        forEachObject(list, iterator, receiver);
      }
    };
  }
});

// node_modules/possible-typed-array-names/index.js
var require_possible_typed_array_names = __commonJS({
  "node_modules/possible-typed-array-names/index.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    module2.exports = [
      "Float16Array",
      "Float32Array",
      "Float64Array",
      "Int8Array",
      "Int16Array",
      "Int32Array",
      "Uint8Array",
      "Uint8ClampedArray",
      "Uint16Array",
      "Uint32Array",
      "BigInt64Array",
      "BigUint64Array"
    ];
  }
});

// node_modules/available-typed-arrays/index.js
var require_available_typed_arrays = __commonJS({
  "node_modules/available-typed-arrays/index.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    var possibleNames = require_possible_typed_array_names();
    var g = typeof globalThis === "undefined" ? globalThis : globalThis;
    module2.exports = function availableTypedArrays() {
      var out = [];
      for (var i = 0; i < possibleNames.length; i++) {
        if (typeof g[possibleNames[i]] === "function") {
          out[out.length] = possibleNames[i];
        }
      }
      return out;
    };
  }
});

// node_modules/define-data-property/index.js
var require_define_data_property = __commonJS({
  "node_modules/define-data-property/index.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    var $defineProperty = require_es_define_property();
    var $SyntaxError = require_syntax();
    var $TypeError = require_type();
    var gopd = require_gopd();
    module2.exports = function defineDataProperty(obj, property, value) {
      if (!obj || typeof obj !== "object" && typeof obj !== "function") {
        throw new $TypeError("`obj` must be an object or a function`");
      }
      if (typeof property !== "string" && typeof property !== "symbol") {
        throw new $TypeError("`property` must be a string or a symbol`");
      }
      if (arguments.length > 3 && typeof arguments[3] !== "boolean" && arguments[3] !== null) {
        throw new $TypeError("`nonEnumerable`, if provided, must be a boolean or null");
      }
      if (arguments.length > 4 && typeof arguments[4] !== "boolean" && arguments[4] !== null) {
        throw new $TypeError("`nonWritable`, if provided, must be a boolean or null");
      }
      if (arguments.length > 5 && typeof arguments[5] !== "boolean" && arguments[5] !== null) {
        throw new $TypeError("`nonConfigurable`, if provided, must be a boolean or null");
      }
      if (arguments.length > 6 && typeof arguments[6] !== "boolean") {
        throw new $TypeError("`loose`, if provided, must be a boolean");
      }
      var nonEnumerable = arguments.length > 3 ? arguments[3] : null;
      var nonWritable = arguments.length > 4 ? arguments[4] : null;
      var nonConfigurable = arguments.length > 5 ? arguments[5] : null;
      var loose = arguments.length > 6 ? arguments[6] : false;
      var desc = !!gopd && gopd(obj, property);
      if ($defineProperty) {
        $defineProperty(obj, property, {
          configurable: nonConfigurable === null && desc ? desc.configurable : !nonConfigurable,
          enumerable: nonEnumerable === null && desc ? desc.enumerable : !nonEnumerable,
          value,
          writable: nonWritable === null && desc ? desc.writable : !nonWritable
        });
      } else if (loose || !nonEnumerable && !nonWritable && !nonConfigurable) {
        obj[property] = value;
      } else {
        throw new $SyntaxError("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.");
      }
    };
  }
});

// node_modules/has-property-descriptors/index.js
var require_has_property_descriptors = __commonJS({
  "node_modules/has-property-descriptors/index.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    var $defineProperty = require_es_define_property();
    var hasPropertyDescriptors = function hasPropertyDescriptors2() {
      return !!$defineProperty;
    };
    hasPropertyDescriptors.hasArrayLengthDefineBug = function hasArrayLengthDefineBug() {
      if (!$defineProperty) {
        return null;
      }
      try {
        return $defineProperty([], "length", { value: 1 }).length !== 1;
      } catch (e) {
        return true;
      }
    };
    module2.exports = hasPropertyDescriptors;
  }
});

// node_modules/set-function-length/index.js
var require_set_function_length = __commonJS({
  "node_modules/set-function-length/index.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    var GetIntrinsic = require_get_intrinsic();
    var define2 = require_define_data_property();
    var hasDescriptors = require_has_property_descriptors()();
    var gOPD = require_gopd();
    var $TypeError = require_type();
    var $floor = GetIntrinsic("%Math.floor%");
    module2.exports = function setFunctionLength(fn, length) {
      if (typeof fn !== "function") {
        throw new $TypeError("`fn` is not a function");
      }
      if (typeof length !== "number" || length < 0 || length > 4294967295 || $floor(length) !== length) {
        throw new $TypeError("`length` must be a positive 32-bit integer");
      }
      var loose = arguments.length > 2 && !!arguments[2];
      var functionLengthIsConfigurable = true;
      var functionLengthIsWritable = true;
      if ("length" in fn && gOPD) {
        var desc = gOPD(fn, "length");
        if (desc && !desc.configurable) {
          functionLengthIsConfigurable = false;
        }
        if (desc && !desc.writable) {
          functionLengthIsWritable = false;
        }
      }
      if (functionLengthIsConfigurable || functionLengthIsWritable || !loose) {
        if (hasDescriptors) {
          define2(
            /** @type {Parameters<define>[0]} */
            fn,
            "length",
            length,
            true,
            true
          );
        } else {
          define2(
            /** @type {Parameters<define>[0]} */
            fn,
            "length",
            length
          );
        }
      }
      return fn;
    };
  }
});

// node_modules/call-bind-apply-helpers/applyBind.js
var require_applyBind = __commonJS({
  "node_modules/call-bind-apply-helpers/applyBind.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    var bind = require_function_bind();
    var $apply = require_functionApply();
    var actualApply = require_actualApply();
    module2.exports = function applyBind() {
      return actualApply(bind, $apply, arguments);
    };
  }
});

// node_modules/call-bind/index.js
var require_call_bind = __commonJS({
  "node_modules/call-bind/index.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    var setFunctionLength = require_set_function_length();
    var $defineProperty = require_es_define_property();
    var callBindBasic = require_call_bind_apply_helpers();
    var applyBind = require_applyBind();
    module2.exports = function callBind(originalFunction) {
      var func = callBindBasic(arguments);
      var adjustedLength = originalFunction.length - (arguments.length - 1);
      return setFunctionLength(
        func,
        1 + (adjustedLength > 0 ? adjustedLength : 0),
        true
      );
    };
    if ($defineProperty) {
      $defineProperty(module2.exports, "apply", { value: applyBind });
    } else {
      module2.exports.apply = applyBind;
    }
  }
});

// node_modules/has-tostringtag/shams.js
var require_shams2 = __commonJS({
  "node_modules/has-tostringtag/shams.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    var hasSymbols = require_shams();
    module2.exports = function hasToStringTagShams() {
      return hasSymbols() && !!Symbol.toStringTag;
    };
  }
});

// node_modules/which-typed-array/index.js
var require_which_typed_array = __commonJS({
  "node_modules/which-typed-array/index.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    var forEach = require_for_each();
    var availableTypedArrays = require_available_typed_arrays();
    var callBind = require_call_bind();
    var callBound = require_call_bound();
    var gOPD = require_gopd();
    var getProto = require_get_proto();
    var $toString = callBound("Object.prototype.toString");
    var hasToStringTag = require_shams2()();
    var g = typeof globalThis === "undefined" ? globalThis : globalThis;
    var typedArrays = availableTypedArrays();
    var $slice = callBound("String.prototype.slice");
    var $indexOf = callBound("Array.prototype.indexOf", true) || function indexOf2(array, value) {
      for (var i = 0; i < array.length; i += 1) {
        if (array[i] === value) {
          return i;
        }
      }
      return -1;
    };
    var cache = { __proto__: null };
    if (hasToStringTag && gOPD && getProto) {
      forEach(typedArrays, function(typedArray) {
        var arr = new g[typedArray]();
        if (Symbol.toStringTag in arr && getProto) {
          var proto = getProto(arr);
          var descriptor = gOPD(proto, Symbol.toStringTag);
          if (!descriptor && proto) {
            var superProto = getProto(proto);
            descriptor = gOPD(superProto, Symbol.toStringTag);
          }
          cache["$" + typedArray] = callBind(descriptor.get);
        }
      });
    } else {
      forEach(typedArrays, function(typedArray) {
        var arr = new g[typedArray]();
        var fn = arr.slice || arr.set;
        if (fn) {
          cache[
            /** @type {`$${import('.').TypedArrayName}`} */
            "$" + typedArray
          ] = /** @type {import('./types').BoundSlice | import('./types').BoundSet} */
          // @ts-expect-error TODO FIXME
          callBind(fn);
        }
      });
    }
    var tryTypedArrays = function tryAllTypedArrays(value) {
      var found = false;
      forEach(
        /** @type {Record<`\$${import('.').TypedArrayName}`, Getter>} */
        cache,
        /** @type {(getter: Getter, name: `\$${import('.').TypedArrayName}`) => void} */
        function(getter, typedArray) {
          if (!found) {
            try {
              if ("$" + getter(value) === typedArray) {
                found = /** @type {import('.').TypedArrayName} */
                $slice(typedArray, 1);
              }
            } catch (e) {
            }
          }
        }
      );
      return found;
    };
    var trySlices = function tryAllSlices(value) {
      var found = false;
      forEach(
        /** @type {Record<`\$${import('.').TypedArrayName}`, Getter>} */
        cache,
        /** @type {(getter: Getter, name: `\$${import('.').TypedArrayName}`) => void} */
        function(getter, name) {
          if (!found) {
            try {
              getter(value);
              found = /** @type {import('.').TypedArrayName} */
              $slice(name, 1);
            } catch (e) {
            }
          }
        }
      );
      return found;
    };
    module2.exports = function whichTypedArray(value) {
      if (!value || typeof value !== "object") {
        return false;
      }
      if (!hasToStringTag) {
        var tag = $slice($toString(value), 8, -1);
        if ($indexOf(typedArrays, tag) > -1) {
          return tag;
        }
        if (tag !== "Object") {
          return false;
        }
        return trySlices(value);
      }
      if (!gOPD) {
        return null;
      }
      return tryTypedArrays(value);
    };
  }
});

// node_modules/is-typed-array/index.js
var require_is_typed_array = __commonJS({
  "node_modules/is-typed-array/index.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    var whichTypedArray = require_which_typed_array();
    module2.exports = function isTypedArray(value) {
      return !!whichTypedArray(value);
    };
  }
});

// node_modules/typed-array-buffer/index.js
var require_typed_array_buffer = __commonJS({
  "node_modules/typed-array-buffer/index.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    var $TypeError = require_type();
    var callBound = require_call_bound();
    var $typedArrayBuffer = callBound("TypedArray.prototype.buffer", true);
    var isTypedArray = require_is_typed_array();
    module2.exports = $typedArrayBuffer || function typedArrayBuffer(x) {
      if (!isTypedArray(x)) {
        throw new $TypeError("Not a Typed Array");
      }
      return x.buffer;
    };
  }
});

// node_modules/to-buffer/index.js
var require_to_buffer = __commonJS({
  "node_modules/to-buffer/index.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    var Buffer3 = require_safe_buffer2().Buffer;
    var isArray = require_isarray();
    var typedArrayBuffer = require_typed_array_buffer();
    var isView = ArrayBuffer.isView || function isView2(obj) {
      try {
        typedArrayBuffer(obj);
        return true;
      } catch (e) {
        return false;
      }
    };
    var useUint8Array = typeof Uint8Array !== "undefined";
    var useArrayBuffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined";
    var useFromArrayBuffer = useArrayBuffer && (Buffer3.prototype instanceof Uint8Array || Buffer3.TYPED_ARRAY_SUPPORT);
    module2.exports = function toBuffer(data, encoding) {
      if (Buffer3.isBuffer(data)) {
        if (data.constructor && !("isBuffer" in data)) {
          return Buffer3.from(data);
        }
        return data;
      }
      if (typeof data === "string") {
        return Buffer3.from(data, encoding);
      }
      if (useArrayBuffer && isView(data)) {
        if (data.byteLength === 0) {
          return Buffer3.alloc(0);
        }
        if (useFromArrayBuffer) {
          var res = Buffer3.from(data.buffer, data.byteOffset, data.byteLength);
          if (res.byteLength === data.byteLength) {
            return res;
          }
        }
        var uint8 = data instanceof Uint8Array ? data : new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
        var result = Buffer3.from(uint8);
        if (result.length === data.byteLength) {
          return result;
        }
      }
      if (useUint8Array && data instanceof Uint8Array) {
        return Buffer3.from(data);
      }
      var isArr = isArray(data);
      if (isArr) {
        for (var i = 0; i < data.length; i += 1) {
          var x = data[i];
          if (typeof x !== "number" || x < 0 || x > 255 || ~~x !== x) {
            throw new RangeError("Array items must be numbers in the range 0-255.");
          }
        }
      }
      if (isArr || Buffer3.isBuffer(data) && data.constructor && typeof data.constructor.isBuffer === "function" && data.constructor.isBuffer(data)) {
        return Buffer3.from(data);
      }
      throw new TypeError('The "data" argument must be a string, an Array, a Buffer, a Uint8Array, or a DataView.');
    };
  }
});

// node_modules/sha.js/hash.js
var require_hash = __commonJS({
  "node_modules/sha.js/hash.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    var Buffer3 = require_safe_buffer().Buffer;
    var toBuffer = require_to_buffer();
    function Hash(blockSize, finalSize) {
      this._block = Buffer3.alloc(blockSize);
      this._finalSize = finalSize;
      this._blockSize = blockSize;
      this._len = 0;
    }
    Hash.prototype.update = function(data, enc) {
      data = toBuffer(data, enc || "utf8");
      var block = this._block;
      var blockSize = this._blockSize;
      var length = data.length;
      var accum = this._len;
      for (var offset2 = 0; offset2 < length; ) {
        var assigned = accum % blockSize;
        var remainder = Math.min(length - offset2, blockSize - assigned);
        for (var i = 0; i < remainder; i++) {
          block[assigned + i] = data[offset2 + i];
        }
        accum += remainder;
        offset2 += remainder;
        if (accum % blockSize === 0) {
          this._update(block);
        }
      }
      this._len += length;
      return this;
    };
    Hash.prototype.digest = function(enc) {
      var rem = this._len % this._blockSize;
      this._block[rem] = 128;
      this._block.fill(0, rem + 1);
      if (rem >= this._finalSize) {
        this._update(this._block);
        this._block.fill(0);
      }
      var bits = this._len * 8;
      if (bits <= 4294967295) {
        this._block.writeUInt32BE(bits, this._blockSize - 4);
      } else {
        var lowBits = (bits & 4294967295) >>> 0;
        var highBits = (bits - lowBits) / 4294967296;
        this._block.writeUInt32BE(highBits, this._blockSize - 8);
        this._block.writeUInt32BE(lowBits, this._blockSize - 4);
      }
      this._update(this._block);
      var hash = this._hash();
      return enc ? hash.toString(enc) : hash;
    };
    Hash.prototype._update = function() {
      throw new Error("_update must be implemented by subclass");
    };
    module2.exports = Hash;
  }
});

// node_modules/sha.js/sha1.js
var require_sha12 = __commonJS({
  "node_modules/sha.js/sha1.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    var inherits = require_inherits_browser();
    var Hash = require_hash();
    var Buffer3 = require_safe_buffer().Buffer;
    var K = [
      1518500249,
      1859775393,
      2400959708 | 0,
      3395469782 | 0
    ];
    var W = new Array(80);
    function Sha1() {
      this.init();
      this._w = W;
      Hash.call(this, 64, 56);
    }
    inherits(Sha1, Hash);
    Sha1.prototype.init = function() {
      this._a = 1732584193;
      this._b = 4023233417;
      this._c = 2562383102;
      this._d = 271733878;
      this._e = 3285377520;
      return this;
    };
    function rotl1(num) {
      return num << 1 | num >>> 31;
    }
    function rotl5(num) {
      return num << 5 | num >>> 27;
    }
    function rotl30(num) {
      return num << 30 | num >>> 2;
    }
    function ft(s2, b, c, d) {
      if (s2 === 0) {
        return b & c | ~b & d;
      }
      if (s2 === 2) {
        return b & c | b & d | c & d;
      }
      return b ^ c ^ d;
    }
    Sha1.prototype._update = function(M) {
      var w = this._w;
      var a = this._a | 0;
      var b = this._b | 0;
      var c = this._c | 0;
      var d = this._d | 0;
      var e = this._e | 0;
      for (var i = 0; i < 16; ++i) {
        w[i] = M.readInt32BE(i * 4);
      }
      for (; i < 80; ++i) {
        w[i] = rotl1(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]);
      }
      for (var j = 0; j < 80; ++j) {
        var s2 = ~~(j / 20);
        var t = rotl5(a) + ft(s2, b, c, d) + e + w[j] + K[s2] | 0;
        e = d;
        d = c;
        c = rotl30(b);
        b = a;
        a = t;
      }
      this._a = a + this._a | 0;
      this._b = b + this._b | 0;
      this._c = c + this._c | 0;
      this._d = d + this._d | 0;
      this._e = e + this._e | 0;
    };
    Sha1.prototype._hash = function() {
      var H = Buffer3.allocUnsafe(20);
      H.writeInt32BE(this._a | 0, 0);
      H.writeInt32BE(this._b | 0, 4);
      H.writeInt32BE(this._c | 0, 8);
      H.writeInt32BE(this._d | 0, 12);
      H.writeInt32BE(this._e | 0, 16);
      return H;
    };
    module2.exports = Sha1;
  }
});

// node_modules/crc-32/crc32.js
var require_crc32 = __commonJS({
  "node_modules/crc-32/crc32.js"(exports) {
    init_esbuild_buffer_shim();
    var CRC32;
    (function(factory) {
      if (typeof DO_NOT_EXPORT_CRC === "undefined") {
        if ("object" === typeof exports) {
          factory(exports);
        } else if ("function" === typeof define && define.amd) {
          define(function() {
            var module3 = {};
            factory(module3);
            return module3;
          });
        } else {
          factory(CRC32 = {});
        }
      } else {
        factory(CRC32 = {});
      }
    })(function(CRC322) {
      CRC322.version = "1.2.2";
      function signed_crc_table() {
        var c = 0, table = new Array(256);
        for (var n2 = 0; n2 != 256; ++n2) {
          c = n2;
          c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;
          c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;
          c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;
          c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;
          c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;
          c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;
          c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;
          c = c & 1 ? -306674912 ^ c >>> 1 : c >>> 1;
          table[n2] = c;
        }
        return typeof Int32Array !== "undefined" ? new Int32Array(table) : table;
      }
      var T0 = signed_crc_table();
      function slice_by_16_tables(T) {
        var c = 0, v = 0, n2 = 0, table = typeof Int32Array !== "undefined" ? new Int32Array(4096) : new Array(4096);
        for (n2 = 0; n2 != 256; ++n2) table[n2] = T[n2];
        for (n2 = 0; n2 != 256; ++n2) {
          v = T[n2];
          for (c = 256 + n2; c < 4096; c += 256) v = table[c] = v >>> 8 ^ T[v & 255];
        }
        var out = [];
        for (n2 = 1; n2 != 16; ++n2) out[n2 - 1] = typeof Int32Array !== "undefined" ? table.subarray(n2 * 256, n2 * 256 + 256) : table.slice(n2 * 256, n2 * 256 + 256);
        return out;
      }
      var TT = slice_by_16_tables(T0);
      var T1 = TT[0], T2 = TT[1], T3 = TT[2], T4 = TT[3], T5 = TT[4];
      var T6 = TT[5], T7 = TT[6], T8 = TT[7], T9 = TT[8], Ta = TT[9];
      var Tb = TT[10], Tc = TT[11], Td = TT[12], Te = TT[13], Tf = TT[14];
      function crc32_bstr(bstr, seed) {
        var C = seed ^ -1;
        for (var i = 0, L = bstr.length; i < L; ) C = C >>> 8 ^ T0[(C ^ bstr.charCodeAt(i++)) & 255];
        return ~C;
      }
      function crc32_buf(B, seed) {
        var C = seed ^ -1, L = B.length - 15, i = 0;
        for (; i < L; ) C = Tf[B[i++] ^ C & 255] ^ Te[B[i++] ^ C >> 8 & 255] ^ Td[B[i++] ^ C >> 16 & 255] ^ Tc[B[i++] ^ C >>> 24] ^ Tb[B[i++]] ^ Ta[B[i++]] ^ T9[B[i++]] ^ T8[B[i++]] ^ T7[B[i++]] ^ T6[B[i++]] ^ T5[B[i++]] ^ T4[B[i++]] ^ T3[B[i++]] ^ T2[B[i++]] ^ T1[B[i++]] ^ T0[B[i++]];
        L += 15;
        while (i < L) C = C >>> 8 ^ T0[(C ^ B[i++]) & 255];
        return ~C;
      }
      function crc32_str(str, seed) {
        var C = seed ^ -1;
        for (var i = 0, L = str.length, c = 0, d = 0; i < L; ) {
          c = str.charCodeAt(i++);
          if (c < 128) {
            C = C >>> 8 ^ T0[(C ^ c) & 255];
          } else if (c < 2048) {
            C = C >>> 8 ^ T0[(C ^ (192 | c >> 6 & 31)) & 255];
            C = C >>> 8 ^ T0[(C ^ (128 | c & 63)) & 255];
          } else if (c >= 55296 && c < 57344) {
            c = (c & 1023) + 64;
            d = str.charCodeAt(i++) & 1023;
            C = C >>> 8 ^ T0[(C ^ (240 | c >> 8 & 7)) & 255];
            C = C >>> 8 ^ T0[(C ^ (128 | c >> 2 & 63)) & 255];
            C = C >>> 8 ^ T0[(C ^ (128 | d >> 6 & 15 | (c & 3) << 4)) & 255];
            C = C >>> 8 ^ T0[(C ^ (128 | d & 63)) & 255];
          } else {
            C = C >>> 8 ^ T0[(C ^ (224 | c >> 12 & 15)) & 255];
            C = C >>> 8 ^ T0[(C ^ (128 | c >> 6 & 63)) & 255];
            C = C >>> 8 ^ T0[(C ^ (128 | c & 63)) & 255];
          }
        }
        return ~C;
      }
      CRC322.table = T0;
      CRC322.bstr = crc32_bstr;
      CRC322.buf = crc32_buf;
      CRC322.str = crc32_str;
    });
  }
});

// node_modules/pako/lib/utils/common.js
var require_common = __commonJS({
  "node_modules/pako/lib/utils/common.js"(exports) {
    "use strict";
    init_esbuild_buffer_shim();
    var TYPED_OK = typeof Uint8Array !== "undefined" && typeof Uint16Array !== "undefined" && typeof Int32Array !== "undefined";
    function _has(obj, key) {
      return Object.prototype.hasOwnProperty.call(obj, key);
    }
    exports.assign = function(obj) {
      var sources = Array.prototype.slice.call(arguments, 1);
      while (sources.length) {
        var source = sources.shift();
        if (!source) {
          continue;
        }
        if (typeof source !== "object") {
          throw new TypeError(source + "must be non-object");
        }
        for (var p in source) {
          if (_has(source, p)) {
            obj[p] = source[p];
          }
        }
      }
      return obj;
    };
    exports.shrinkBuf = function(buf, size) {
      if (buf.length === size) {
        return buf;
      }
      if (buf.subarray) {
        return buf.subarray(0, size);
      }
      buf.length = size;
      return buf;
    };
    var fnTyped = {
      arraySet: function(dest, src, src_offs, len, dest_offs) {
        if (src.subarray && dest.subarray) {
          dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
          return;
        }
        for (var i = 0; i < len; i++) {
          dest[dest_offs + i] = src[src_offs + i];
        }
      },
      // Join array of chunks to single array.
      flattenChunks: function(chunks) {
        var i, l2, len, pos, chunk, result;
        len = 0;
        for (i = 0, l2 = chunks.length; i < l2; i++) {
          len += chunks[i].length;
        }
        result = new Uint8Array(len);
        pos = 0;
        for (i = 0, l2 = chunks.length; i < l2; i++) {
          chunk = chunks[i];
          result.set(chunk, pos);
          pos += chunk.length;
        }
        return result;
      }
    };
    var fnUntyped = {
      arraySet: function(dest, src, src_offs, len, dest_offs) {
        for (var i = 0; i < len; i++) {
          dest[dest_offs + i] = src[src_offs + i];
        }
      },
      // Join array of chunks to single array.
      flattenChunks: function(chunks) {
        return [].concat.apply([], chunks);
      }
    };
    exports.setTyped = function(on) {
      if (on) {
        exports.Buf8 = Uint8Array;
        exports.Buf16 = Uint16Array;
        exports.Buf32 = Int32Array;
        exports.assign(exports, fnTyped);
      } else {
        exports.Buf8 = Array;
        exports.Buf16 = Array;
        exports.Buf32 = Array;
        exports.assign(exports, fnUntyped);
      }
    };
    exports.setTyped(TYPED_OK);
  }
});

// node_modules/pako/lib/zlib/trees.js
var require_trees = __commonJS({
  "node_modules/pako/lib/zlib/trees.js"(exports) {
    "use strict";
    init_esbuild_buffer_shim();
    var utils = require_common();
    var Z_FIXED = 4;
    var Z_BINARY = 0;
    var Z_TEXT = 1;
    var Z_UNKNOWN = 2;
    function zero(buf) {
      var len = buf.length;
      while (--len >= 0) {
        buf[len] = 0;
      }
    }
    var STORED_BLOCK = 0;
    var STATIC_TREES = 1;
    var DYN_TREES = 2;
    var MIN_MATCH = 3;
    var MAX_MATCH = 258;
    var LENGTH_CODES = 29;
    var LITERALS = 256;
    var L_CODES = LITERALS + 1 + LENGTH_CODES;
    var D_CODES = 30;
    var BL_CODES = 19;
    var HEAP_SIZE = 2 * L_CODES + 1;
    var MAX_BITS = 15;
    var Buf_size = 16;
    var MAX_BL_BITS = 7;
    var END_BLOCK = 256;
    var REP_3_6 = 16;
    var REPZ_3_10 = 17;
    var REPZ_11_138 = 18;
    var 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]
    );
    var 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]
    );
    var 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]
    );
    var bl_order = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
    var DIST_CODE_LEN = 512;
    var static_ltree = new Array((L_CODES + 2) * 2);
    zero(static_ltree);
    var static_dtree = new Array(D_CODES * 2);
    zero(static_dtree);
    var _dist_code = new Array(DIST_CODE_LEN);
    zero(_dist_code);
    var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);
    zero(_length_code);
    var base_length = new Array(LENGTH_CODES);
    zero(base_length);
    var base_dist = new Array(D_CODES);
    zero(base_dist);
    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;
    }
    var static_l_desc;
    var static_d_desc;
    var static_bl_desc;
    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(s2, w) {
      s2.pending_buf[s2.pending++] = w & 255;
      s2.pending_buf[s2.pending++] = w >>> 8 & 255;
    }
    function send_bits(s2, value, length) {
      if (s2.bi_valid > Buf_size - length) {
        s2.bi_buf |= value << s2.bi_valid & 65535;
        put_short(s2, s2.bi_buf);
        s2.bi_buf = value >> Buf_size - s2.bi_valid;
        s2.bi_valid += length - Buf_size;
      } else {
        s2.bi_buf |= value << s2.bi_valid & 65535;
        s2.bi_valid += length;
      }
    }
    function send_code(s2, c, tree) {
      send_bits(
        s2,
        tree[c * 2],
        tree[c * 2 + 1]
        /*.Len*/
      );
    }
    function bi_reverse(code, len) {
      var res = 0;
      do {
        res |= code & 1;
        code >>>= 1;
        res <<= 1;
      } while (--len > 0);
      return res >>> 1;
    }
    function bi_flush(s2) {
      if (s2.bi_valid === 16) {
        put_short(s2, s2.bi_buf);
        s2.bi_buf = 0;
        s2.bi_valid = 0;
      } else if (s2.bi_valid >= 8) {
        s2.pending_buf[s2.pending++] = s2.bi_buf & 255;
        s2.bi_buf >>= 8;
        s2.bi_valid -= 8;
      }
    }
    function gen_bitlen(s2, 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 base = desc.stat_desc.extra_base;
      var max_length = desc.stat_desc.max_length;
      var h;
      var n2, m;
      var bits;
      var xbits;
      var f;
      var overflow = 0;
      for (bits = 0; bits <= MAX_BITS; bits++) {
        s2.bl_count[bits] = 0;
      }
      tree[s2.heap[s2.heap_max] * 2 + 1] = 0;
      for (h = s2.heap_max + 1; h < HEAP_SIZE; h++) {
        n2 = s2.heap[h];
        bits = tree[tree[n2 * 2 + 1] * 2 + 1] + 1;
        if (bits > max_length) {
          bits = max_length;
          overflow++;
        }
        tree[n2 * 2 + 1] = bits;
        if (n2 > max_code) {
          continue;
        }
        s2.bl_count[bits]++;
        xbits = 0;
        if (n2 >= base) {
          xbits = extra[n2 - base];
        }
        f = tree[n2 * 2];
        s2.opt_len += f * (bits + xbits);
        if (has_stree) {
          s2.static_len += f * (stree[n2 * 2 + 1] + xbits);
        }
      }
      if (overflow === 0) {
        return;
      }
      do {
        bits = max_length - 1;
        while (s2.bl_count[bits] === 0) {
          bits--;
        }
        s2.bl_count[bits]--;
        s2.bl_count[bits + 1] += 2;
        s2.bl_count[max_length]--;
        overflow -= 2;
      } while (overflow > 0);
      for (bits = max_length; bits !== 0; bits--) {
        n2 = s2.bl_count[bits];
        while (n2 !== 0) {
          m = s2.heap[--h];
          if (m > max_code) {
            continue;
          }
          if (tree[m * 2 + 1] !== bits) {
            s2.opt_len += (bits - tree[m * 2 + 1]) * tree[m * 2];
            tree[m * 2 + 1] = bits;
          }
          n2--;
        }
      }
    }
    function gen_codes(tree, max_code, bl_count) {
      var next_code = new Array(MAX_BITS + 1);
      var code = 0;
      var bits;
      var n2;
      for (bits = 1; bits <= MAX_BITS; bits++) {
        next_code[bits] = code = code + bl_count[bits - 1] << 1;
      }
      for (n2 = 0; n2 <= max_code; n2++) {
        var len = tree[n2 * 2 + 1];
        if (len === 0) {
          continue;
        }
        tree[n2 * 2] = bi_reverse(next_code[len]++, len);
      }
    }
    function tr_static_init() {
      var n2;
      var bits;
      var length;
      var code;
      var dist;
      var bl_count = new Array(MAX_BITS + 1);
      length = 0;
      for (code = 0; code < LENGTH_CODES - 1; code++) {
        base_length[code] = length;
        for (n2 = 0; n2 < 1 << extra_lbits[code]; n2++) {
          _length_code[length++] = code;
        }
      }
      _length_code[length - 1] = code;
      dist = 0;
      for (code = 0; code < 16; code++) {
        base_dist[code] = dist;
        for (n2 = 0; n2 < 1 << extra_dbits[code]; n2++) {
          _dist_code[dist++] = code;
        }
      }
      dist >>= 7;
      for (; code < D_CODES; code++) {
        base_dist[code] = dist << 7;
        for (n2 = 0; n2 < 1 << extra_dbits[code] - 7; n2++) {
          _dist_code[256 + dist++] = code;
        }
      }
      for (bits = 0; bits <= MAX_BITS; bits++) {
        bl_count[bits] = 0;
      }
      n2 = 0;
      while (n2 <= 143) {
        static_ltree[n2 * 2 + 1] = 8;
        n2++;
        bl_count[8]++;
      }
      while (n2 <= 255) {
        static_ltree[n2 * 2 + 1] = 9;
        n2++;
        bl_count[9]++;
      }
      while (n2 <= 279) {
        static_ltree[n2 * 2 + 1] = 7;
        n2++;
        bl_count[7]++;
      }
      while (n2 <= 287) {
        static_ltree[n2 * 2 + 1] = 8;
        n2++;
        bl_count[8]++;
      }
      gen_codes(static_ltree, L_CODES + 1, bl_count);
      for (n2 = 0; n2 < D_CODES; n2++) {
        static_dtree[n2 * 2 + 1] = 5;
        static_dtree[n2 * 2] = bi_reverse(n2, 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(s2) {
      var n2;
      for (n2 = 0; n2 < L_CODES; n2++) {
        s2.dyn_ltree[n2 * 2] = 0;
      }
      for (n2 = 0; n2 < D_CODES; n2++) {
        s2.dyn_dtree[n2 * 2] = 0;
      }
      for (n2 = 0; n2 < BL_CODES; n2++) {
        s2.bl_tree[n2 * 2] = 0;
      }
      s2.dyn_ltree[END_BLOCK * 2] = 1;
      s2.opt_len = s2.static_len = 0;
      s2.last_lit = s2.matches = 0;
    }
    function bi_windup(s2) {
      if (s2.bi_valid > 8) {
        put_short(s2, s2.bi_buf);
      } else if (s2.bi_valid > 0) {
        s2.pending_buf[s2.pending++] = s2.bi_buf;
      }
      s2.bi_buf = 0;
      s2.bi_valid = 0;
    }
    function copy_block(s2, buf, len, header) {
      bi_windup(s2);
      if (header) {
        put_short(s2, len);
        put_short(s2, ~len);
      }
      utils.arraySet(s2.pending_buf, s2.window, buf, len, s2.pending);
      s2.pending += len;
    }
    function smaller(tree, n2, m, depth) {
      var _n2 = n2 * 2;
      var _m2 = m * 2;
      return tree[_n2] < tree[_m2] || tree[_n2] === tree[_m2] && depth[n2] <= depth[m];
    }
    function pqdownheap(s2, tree, k) {
      var v = s2.heap[k];
      var j = k << 1;
      while (j <= s2.heap_len) {
        if (j < s2.heap_len && smaller(tree, s2.heap[j + 1], s2.heap[j], s2.depth)) {
          j++;
        }
        if (smaller(tree, v, s2.heap[j], s2.depth)) {
          break;
        }
        s2.heap[k] = s2.heap[j];
        k = j;
        j <<= 1;
      }
      s2.heap[k] = v;
    }
    function compress_block(s2, ltree, dtree) {
      var dist;
      var lc;
      var lx = 0;
      var code;
      var extra;
      if (s2.last_lit !== 0) {
        do {
          dist = s2.pending_buf[s2.d_buf + lx * 2] << 8 | s2.pending_buf[s2.d_buf + lx * 2 + 1];
          lc = s2.pending_buf[s2.l_buf + lx];
          lx++;
          if (dist === 0) {
            send_code(s2, lc, ltree);
          } else {
            code = _length_code[lc];
            send_code(s2, code + LITERALS + 1, ltree);
            extra = extra_lbits[code];
            if (extra !== 0) {
              lc -= base_length[code];
              send_bits(s2, lc, extra);
            }
            dist--;
            code = d_code(dist);
            send_code(s2, code, dtree);
            extra = extra_dbits[code];
            if (extra !== 0) {
              dist -= base_dist[code];
              send_bits(s2, dist, extra);
            }
          }
        } while (lx < s2.last_lit);
      }
      send_code(s2, END_BLOCK, ltree);
    }
    function build_tree(s2, 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 n2, m;
      var max_code = -1;
      var node;
      s2.heap_len = 0;
      s2.heap_max = HEAP_SIZE;
      for (n2 = 0; n2 < elems; n2++) {
        if (tree[n2 * 2] !== 0) {
          s2.heap[++s2.heap_len] = max_code = n2;
          s2.depth[n2] = 0;
        } else {
          tree[n2 * 2 + 1] = 0;
        }
      }
      while (s2.heap_len < 2) {
        node = s2.heap[++s2.heap_len] = max_code < 2 ? ++max_code : 0;
        tree[node * 2] = 1;
        s2.depth[node] = 0;
        s2.opt_len--;
        if (has_stree) {
          s2.static_len -= stree[node * 2 + 1];
        }
      }
      desc.max_code = max_code;
      for (n2 = s2.heap_len >> 1; n2 >= 1; n2--) {
        pqdownheap(s2, tree, n2);
      }
      node = elems;
      do {
        n2 = s2.heap[
          1
          /*SMALLEST*/
        ];
        s2.heap[
          1
          /*SMALLEST*/
        ] = s2.heap[s2.heap_len--];
        pqdownheap(
          s2,
          tree,
          1
          /*SMALLEST*/
        );
        m = s2.heap[
          1
          /*SMALLEST*/
        ];
        s2.heap[--s2.heap_max] = n2;
        s2.heap[--s2.heap_max] = m;
        tree[node * 2] = tree[n2 * 2] + tree[m * 2];
        s2.depth[node] = (s2.depth[n2] >= s2.depth[m] ? s2.depth[n2] : s2.depth[m]) + 1;
        tree[n2 * 2 + 1] = tree[m * 2 + 1] = node;
        s2.heap[
          1
          /*SMALLEST*/
        ] = node++;
        pqdownheap(
          s2,
          tree,
          1
          /*SMALLEST*/
        );
      } while (s2.heap_len >= 2);
      s2.heap[--s2.heap_max] = s2.heap[
        1
        /*SMALLEST*/
      ];
      gen_bitlen(s2, desc);
      gen_codes(tree, max_code, s2.bl_count);
    }
    function scan_tree(s2, tree, max_code) {
      var n2;
      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 (n2 = 0; n2 <= max_code; n2++) {
        curlen = nextlen;
        nextlen = tree[(n2 + 1) * 2 + 1];
        if (++count < max_count && curlen === nextlen) {
          continue;
        } else if (count < min_count) {
          s2.bl_tree[curlen * 2] += count;
        } else if (curlen !== 0) {
          if (curlen !== prevlen) {
            s2.bl_tree[curlen * 2]++;
          }
          s2.bl_tree[REP_3_6 * 2]++;
        } else if (count <= 10) {
          s2.bl_tree[REPZ_3_10 * 2]++;
        } else {
          s2.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(s2, tree, max_code) {
      var n2;
      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 (n2 = 0; n2 <= max_code; n2++) {
        curlen = nextlen;
        nextlen = tree[(n2 + 1) * 2 + 1];
        if (++count < max_count && curlen === nextlen) {
          continue;
        } else if (count < min_count) {
          do {
            send_code(s2, curlen, s2.bl_tree);
          } while (--count !== 0);
        } else if (curlen !== 0) {
          if (curlen !== prevlen) {
            send_code(s2, curlen, s2.bl_tree);
            count--;
          }
          send_code(s2, REP_3_6, s2.bl_tree);
          send_bits(s2, count - 3, 2);
        } else if (count <= 10) {
          send_code(s2, REPZ_3_10, s2.bl_tree);
          send_bits(s2, count - 3, 3);
        } else {
          send_code(s2, REPZ_11_138, s2.bl_tree);
          send_bits(s2, 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(s2) {
      var max_blindex;
      scan_tree(s2, s2.dyn_ltree, s2.l_desc.max_code);
      scan_tree(s2, s2.dyn_dtree, s2.d_desc.max_code);
      build_tree(s2, s2.bl_desc);
      for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
        if (s2.bl_tree[bl_order[max_blindex] * 2 + 1] !== 0) {
          break;
        }
      }
      s2.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
      return max_blindex;
    }
    function send_all_trees(s2, lcodes, dcodes, blcodes) {
      var rank;
      send_bits(s2, lcodes - 257, 5);
      send_bits(s2, dcodes - 1, 5);
      send_bits(s2, blcodes - 4, 4);
      for (rank = 0; rank < blcodes; rank++) {
        send_bits(s2, s2.bl_tree[bl_order[rank] * 2 + 1], 3);
      }
      send_tree(s2, s2.dyn_ltree, lcodes - 1);
      send_tree(s2, s2.dyn_dtree, dcodes - 1);
    }
    function detect_data_type(s2) {
      var black_mask = 4093624447;
      var n2;
      for (n2 = 0; n2 <= 31; n2++, black_mask >>>= 1) {
        if (black_mask & 1 && s2.dyn_ltree[n2 * 2] !== 0) {
          return Z_BINARY;
        }
      }
      if (s2.dyn_ltree[9 * 2] !== 0 || s2.dyn_ltree[10 * 2] !== 0 || s2.dyn_ltree[13 * 2] !== 0) {
        return Z_TEXT;
      }
      for (n2 = 32; n2 < LITERALS; n2++) {
        if (s2.dyn_ltree[n2 * 2] !== 0) {
          return Z_TEXT;
        }
      }
      return Z_BINARY;
    }
    var static_init_done = false;
    function _tr_init(s2) {
      if (!static_init_done) {
        tr_static_init();
        static_init_done = true;
      }
      s2.l_desc = new TreeDesc(s2.dyn_ltree, static_l_desc);
      s2.d_desc = new TreeDesc(s2.dyn_dtree, static_d_desc);
      s2.bl_desc = new TreeDesc(s2.bl_tree, static_bl_desc);
      s2.bi_buf = 0;
      s2.bi_valid = 0;
      init_block(s2);
    }
    function _tr_stored_block(s2, buf, stored_len, last) {
      send_bits(s2, (STORED_BLOCK << 1) + (last ? 1 : 0), 3);
      copy_block(s2, buf, stored_len, true);
    }
    function _tr_align(s2) {
      send_bits(s2, STATIC_TREES << 1, 3);
      send_code(s2, END_BLOCK, static_ltree);
      bi_flush(s2);
    }
    function _tr_flush_block(s2, buf, stored_len, last) {
      var opt_lenb, static_lenb;
      var max_blindex = 0;
      if (s2.level > 0) {
        if (s2.strm.data_type === Z_UNKNOWN) {
          s2.strm.data_type = detect_data_type(s2);
        }
        build_tree(s2, s2.l_desc);
        build_tree(s2, s2.d_desc);
        max_blindex = build_bl_tree(s2);
        opt_lenb = s2.opt_len + 3 + 7 >>> 3;
        static_lenb = s2.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(s2, buf, stored_len, last);
      } else if (s2.strategy === Z_FIXED || static_lenb === opt_lenb) {
        send_bits(s2, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
        compress_block(s2, static_ltree, static_dtree);
      } else {
        send_bits(s2, (DYN_TREES << 1) + (last ? 1 : 0), 3);
        send_all_trees(s2, s2.l_desc.max_code + 1, s2.d_desc.max_code + 1, max_blindex + 1);
        compress_block(s2, s2.dyn_ltree, s2.dyn_dtree);
      }
      init_block(s2);
      if (last) {
        bi_windup(s2);
      }
    }
    function _tr_tally(s2, dist, lc) {
      s2.pending_buf[s2.d_buf + s2.last_lit * 2] = dist >>> 8 & 255;
      s2.pending_buf[s2.d_buf + s2.last_lit * 2 + 1] = dist & 255;
      s2.pending_buf[s2.l_buf + s2.last_lit] = lc & 255;
      s2.last_lit++;
      if (dist === 0) {
        s2.dyn_ltree[lc * 2]++;
      } else {
        s2.matches++;
        dist--;
        s2.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]++;
        s2.dyn_dtree[d_code(dist) * 2]++;
      }
      return s2.last_lit === s2.lit_bufsize - 1;
    }
    exports._tr_init = _tr_init;
    exports._tr_stored_block = _tr_stored_block;
    exports._tr_flush_block = _tr_flush_block;
    exports._tr_tally = _tr_tally;
    exports._tr_align = _tr_align;
  }
});

// node_modules/pako/lib/zlib/adler32.js
var require_adler32 = __commonJS({
  "node_modules/pako/lib/zlib/adler32.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    function adler32(adler, buf, len, pos) {
      var s1 = adler & 65535 | 0, s2 = adler >>> 16 & 65535 | 0, n2 = 0;
      while (len !== 0) {
        n2 = len > 2e3 ? 2e3 : len;
        len -= n2;
        do {
          s1 = s1 + buf[pos++] | 0;
          s2 = s2 + s1 | 0;
        } while (--n2);
        s1 %= 65521;
        s2 %= 65521;
      }
      return s1 | s2 << 16 | 0;
    }
    module2.exports = adler32;
  }
});

// node_modules/pako/lib/zlib/crc32.js
var require_crc322 = __commonJS({
  "node_modules/pako/lib/zlib/crc32.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    function makeTable() {
      var c, table = [];
      for (var n2 = 0; n2 < 256; n2++) {
        c = n2;
        for (var k = 0; k < 8; k++) {
          c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
        }
        table[n2] = c;
      }
      return table;
    }
    var crcTable = makeTable();
    function crc32(crc, buf, len, pos) {
      var t = crcTable, end = pos + len;
      crc ^= -1;
      for (var i = pos; i < end; i++) {
        crc = crc >>> 8 ^ t[(crc ^ buf[i]) & 255];
      }
      return crc ^ -1;
    }
    module2.exports = crc32;
  }
});

// node_modules/pako/lib/zlib/messages.js
var require_messages = __commonJS({
  "node_modules/pako/lib/zlib/messages.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    module2.exports = {
      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) */
    };
  }
});

// node_modules/pako/lib/zlib/deflate.js
var require_deflate = __commonJS({
  "node_modules/pako/lib/zlib/deflate.js"(exports) {
    "use strict";
    init_esbuild_buffer_shim();
    var utils = require_common();
    var trees = require_trees();
    var adler32 = require_adler32();
    var crc32 = require_crc322();
    var msg = require_messages();
    var Z_NO_FLUSH = 0;
    var Z_PARTIAL_FLUSH = 1;
    var Z_FULL_FLUSH = 3;
    var Z_FINISH = 4;
    var Z_BLOCK = 5;
    var Z_OK = 0;
    var Z_STREAM_END = 1;
    var Z_STREAM_ERROR = -2;
    var Z_DATA_ERROR = -3;
    var Z_BUF_ERROR = -5;
    var Z_DEFAULT_COMPRESSION = -1;
    var Z_FILTERED = 1;
    var Z_HUFFMAN_ONLY = 2;
    var Z_RLE = 3;
    var Z_FIXED = 4;
    var Z_DEFAULT_STRATEGY = 0;
    var Z_UNKNOWN = 2;
    var Z_DEFLATED = 8;
    var MAX_MEM_LEVEL = 9;
    var MAX_WBITS = 15;
    var DEF_MEM_LEVEL = 8;
    var LENGTH_CODES = 29;
    var LITERALS = 256;
    var L_CODES = LITERALS + 1 + LENGTH_CODES;
    var D_CODES = 30;
    var BL_CODES = 19;
    var HEAP_SIZE = 2 * L_CODES + 1;
    var MAX_BITS = 15;
    var MIN_MATCH = 3;
    var MAX_MATCH = 258;
    var MIN_LOOKAHEAD = MAX_MATCH + MIN_MATCH + 1;
    var PRESET_DICT = 32;
    var INIT_STATE = 42;
    var EXTRA_STATE = 69;
    var NAME_STATE = 73;
    var COMMENT_STATE = 91;
    var HCRC_STATE = 103;
    var BUSY_STATE = 113;
    var FINISH_STATE = 666;
    var BS_NEED_MORE = 1;
    var BS_BLOCK_DONE = 2;
    var BS_FINISH_STARTED = 3;
    var BS_FINISH_DONE = 4;
    var OS_CODE = 3;
    function err(strm, errorCode) {
      strm.msg = msg[errorCode];
      return errorCode;
    }
    function rank(f) {
      return (f << 1) - (f > 4 ? 9 : 0);
    }
    function zero(buf) {
      var len = buf.length;
      while (--len >= 0) {
        buf[len] = 0;
      }
    }
    function flush_pending(strm) {
      var s2 = strm.state;
      var len = s2.pending;
      if (len > strm.avail_out) {
        len = strm.avail_out;
      }
      if (len === 0) {
        return;
      }
      utils.arraySet(strm.output, s2.pending_buf, s2.pending_out, len, strm.next_out);
      strm.next_out += len;
      s2.pending_out += len;
      strm.total_out += len;
      strm.avail_out -= len;
      s2.pending -= len;
      if (s2.pending === 0) {
        s2.pending_out = 0;
      }
    }
    function flush_block_only(s2, last) {
      trees._tr_flush_block(s2, s2.block_start >= 0 ? s2.block_start : -1, s2.strstart - s2.block_start, last);
      s2.block_start = s2.strstart;
      flush_pending(s2.strm);
    }
    function put_byte(s2, b) {
      s2.pending_buf[s2.pending++] = b;
    }
    function putShortMSB(s2, b) {
      s2.pending_buf[s2.pending++] = b >>> 8 & 255;
      s2.pending_buf[s2.pending++] = b & 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.arraySet(buf, strm.input, strm.next_in, len, start);
      if (strm.state.wrap === 1) {
        strm.adler = adler32(strm.adler, buf, len, start);
      } else if (strm.state.wrap === 2) {
        strm.adler = crc32(strm.adler, buf, len, start);
      }
      strm.next_in += len;
      strm.total_in += len;
      return len;
    }
    function longest_match(s2, cur_match) {
      var chain_length = s2.max_chain_length;
      var scan = s2.strstart;
      var match2;
      var len;
      var best_len = s2.prev_length;
      var nice_match = s2.nice_match;
      var limit = s2.strstart > s2.w_size - MIN_LOOKAHEAD ? s2.strstart - (s2.w_size - MIN_LOOKAHEAD) : 0;
      var _win = s2.window;
      var wmask = s2.w_mask;
      var prev = s2.prev;
      var strend = s2.strstart + MAX_MATCH;
      var scan_end1 = _win[scan + best_len - 1];
      var scan_end = _win[scan + best_len];
      if (s2.prev_length >= s2.good_match) {
        chain_length >>= 2;
      }
      if (nice_match > s2.lookahead) {
        nice_match = s2.lookahead;
      }
      do {
        match2 = cur_match;
        if (_win[match2 + best_len] !== scan_end || _win[match2 + best_len - 1] !== scan_end1 || _win[match2] !== _win[scan] || _win[++match2] !== _win[scan + 1]) {
          continue;
        }
        scan += 2;
        match2++;
        do {
        } while (_win[++scan] === _win[++match2] && _win[++scan] === _win[++match2] && _win[++scan] === _win[++match2] && _win[++scan] === _win[++match2] && _win[++scan] === _win[++match2] && _win[++scan] === _win[++match2] && _win[++scan] === _win[++match2] && _win[++scan] === _win[++match2] && scan < strend);
        len = MAX_MATCH - (strend - scan);
        scan = strend - MAX_MATCH;
        if (len > best_len) {
          s2.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 <= s2.lookahead) {
        return best_len;
      }
      return s2.lookahead;
    }
    function fill_window(s2) {
      var _w_size = s2.w_size;
      var p, n2, m, more, str;
      do {
        more = s2.window_size - s2.lookahead - s2.strstart;
        if (s2.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
          utils.arraySet(s2.window, s2.window, _w_size, _w_size, 0);
          s2.match_start -= _w_size;
          s2.strstart -= _w_size;
          s2.block_start -= _w_size;
          n2 = s2.hash_size;
          p = n2;
          do {
            m = s2.head[--p];
            s2.head[p] = m >= _w_size ? m - _w_size : 0;
          } while (--n2);
          n2 = _w_size;
          p = n2;
          do {
            m = s2.prev[--p];
            s2.prev[p] = m >= _w_size ? m - _w_size : 0;
          } while (--n2);
          more += _w_size;
        }
        if (s2.strm.avail_in === 0) {
          break;
        }
        n2 = read_buf(s2.strm, s2.window, s2.strstart + s2.lookahead, more);
        s2.lookahead += n2;
        if (s2.lookahead + s2.insert >= MIN_MATCH) {
          str = s2.strstart - s2.insert;
          s2.ins_h = s2.window[str];
          s2.ins_h = (s2.ins_h << s2.hash_shift ^ s2.window[str + 1]) & s2.hash_mask;
          while (s2.insert) {
            s2.ins_h = (s2.ins_h << s2.hash_shift ^ s2.window[str + MIN_MATCH - 1]) & s2.hash_mask;
            s2.prev[str & s2.w_mask] = s2.head[s2.ins_h];
            s2.head[s2.ins_h] = str;
            str++;
            s2.insert--;
            if (s2.lookahead + s2.insert < MIN_MATCH) {
              break;
            }
          }
        }
      } while (s2.lookahead < MIN_LOOKAHEAD && s2.strm.avail_in !== 0);
    }
    function deflate_stored(s2, flush2) {
      var max_block_size = 65535;
      if (max_block_size > s2.pending_buf_size - 5) {
        max_block_size = s2.pending_buf_size - 5;
      }
      for (; ; ) {
        if (s2.lookahead <= 1) {
          fill_window(s2);
          if (s2.lookahead === 0 && flush2 === Z_NO_FLUSH) {
            return BS_NEED_MORE;
          }
          if (s2.lookahead === 0) {
            break;
          }
        }
        s2.strstart += s2.lookahead;
        s2.lookahead = 0;
        var max_start = s2.block_start + max_block_size;
        if (s2.strstart === 0 || s2.strstart >= max_start) {
          s2.lookahead = s2.strstart - max_start;
          s2.strstart = max_start;
          flush_block_only(s2, false);
          if (s2.strm.avail_out === 0) {
            return BS_NEED_MORE;
          }
        }
        if (s2.strstart - s2.block_start >= s2.w_size - MIN_LOOKAHEAD) {
          flush_block_only(s2, false);
          if (s2.strm.avail_out === 0) {
            return BS_NEED_MORE;
          }
        }
      }
      s2.insert = 0;
      if (flush2 === Z_FINISH) {
        flush_block_only(s2, true);
        if (s2.strm.avail_out === 0) {
          return BS_FINISH_STARTED;
        }
        return BS_FINISH_DONE;
      }
      if (s2.strstart > s2.block_start) {
        flush_block_only(s2, false);
        if (s2.strm.avail_out === 0) {
          return BS_NEED_MORE;
        }
      }
      return BS_NEED_MORE;
    }
    function deflate_fast(s2, flush2) {
      var hash_head;
      var bflush;
      for (; ; ) {
        if (s2.lookahead < MIN_LOOKAHEAD) {
          fill_window(s2);
          if (s2.lookahead < MIN_LOOKAHEAD && flush2 === Z_NO_FLUSH) {
            return BS_NEED_MORE;
          }
          if (s2.lookahead === 0) {
            break;
          }
        }
        hash_head = 0;
        if (s2.lookahead >= MIN_MATCH) {
          s2.ins_h = (s2.ins_h << s2.hash_shift ^ s2.window[s2.strstart + MIN_MATCH - 1]) & s2.hash_mask;
          hash_head = s2.prev[s2.strstart & s2.w_mask] = s2.head[s2.ins_h];
          s2.head[s2.ins_h] = s2.strstart;
        }
        if (hash_head !== 0 && s2.strstart - hash_head <= s2.w_size - MIN_LOOKAHEAD) {
          s2.match_length = longest_match(s2, hash_head);
        }
        if (s2.match_length >= MIN_MATCH) {
          bflush = trees._tr_tally(s2, s2.strstart - s2.match_start, s2.match_length - MIN_MATCH);
          s2.lookahead -= s2.match_length;
          if (s2.match_length <= s2.max_lazy_match && s2.lookahead >= MIN_MATCH) {
            s2.match_length--;
            do {
              s2.strstart++;
              s2.ins_h = (s2.ins_h << s2.hash_shift ^ s2.window[s2.strstart + MIN_MATCH - 1]) & s2.hash_mask;
              hash_head = s2.prev[s2.strstart & s2.w_mask] = s2.head[s2.ins_h];
              s2.head[s2.ins_h] = s2.strstart;
            } while (--s2.match_length !== 0);
            s2.strstart++;
          } else {
            s2.strstart += s2.match_length;
            s2.match_length = 0;
            s2.ins_h = s2.window[s2.strstart];
            s2.ins_h = (s2.ins_h << s2.hash_shift ^ s2.window[s2.strstart + 1]) & s2.hash_mask;
          }
        } else {
          bflush = trees._tr_tally(s2, 0, s2.window[s2.strstart]);
          s2.lookahead--;
          s2.strstart++;
        }
        if (bflush) {
          flush_block_only(s2, false);
          if (s2.strm.avail_out === 0) {
            return BS_NEED_MORE;
          }
        }
      }
      s2.insert = s2.strstart < MIN_MATCH - 1 ? s2.strstart : MIN_MATCH - 1;
      if (flush2 === Z_FINISH) {
        flush_block_only(s2, true);
        if (s2.strm.avail_out === 0) {
          return BS_FINISH_STARTED;
        }
        return BS_FINISH_DONE;
      }
      if (s2.last_lit) {
        flush_block_only(s2, false);
        if (s2.strm.avail_out === 0) {
          return BS_NEED_MORE;
        }
      }
      return BS_BLOCK_DONE;
    }
    function deflate_slow(s2, flush2) {
      var hash_head;
      var bflush;
      var max_insert;
      for (; ; ) {
        if (s2.lookahead < MIN_LOOKAHEAD) {
          fill_window(s2);
          if (s2.lookahead < MIN_LOOKAHEAD && flush2 === Z_NO_FLUSH) {
            return BS_NEED_MORE;
          }
          if (s2.lookahead === 0) {
            break;
          }
        }
        hash_head = 0;
        if (s2.lookahead >= MIN_MATCH) {
          s2.ins_h = (s2.ins_h << s2.hash_shift ^ s2.window[s2.strstart + MIN_MATCH - 1]) & s2.hash_mask;
          hash_head = s2.prev[s2.strstart & s2.w_mask] = s2.head[s2.ins_h];
          s2.head[s2.ins_h] = s2.strstart;
        }
        s2.prev_length = s2.match_length;
        s2.prev_match = s2.match_start;
        s2.match_length = MIN_MATCH - 1;
        if (hash_head !== 0 && s2.prev_length < s2.max_lazy_match && s2.strstart - hash_head <= s2.w_size - MIN_LOOKAHEAD) {
          s2.match_length = longest_match(s2, hash_head);
          if (s2.match_length <= 5 && (s2.strategy === Z_FILTERED || s2.match_length === MIN_MATCH && s2.strstart - s2.match_start > 4096)) {
            s2.match_length = MIN_MATCH - 1;
          }
        }
        if (s2.prev_length >= MIN_MATCH && s2.match_length <= s2.prev_length) {
          max_insert = s2.strstart + s2.lookahead - MIN_MATCH;
          bflush = trees._tr_tally(s2, s2.strstart - 1 - s2.prev_match, s2.prev_length - MIN_MATCH);
          s2.lookahead -= s2.prev_length - 1;
          s2.prev_length -= 2;
          do {
            if (++s2.strstart <= max_insert) {
              s2.ins_h = (s2.ins_h << s2.hash_shift ^ s2.window[s2.strstart + MIN_MATCH - 1]) & s2.hash_mask;
              hash_head = s2.prev[s2.strstart & s2.w_mask] = s2.head[s2.ins_h];
              s2.head[s2.ins_h] = s2.strstart;
            }
          } while (--s2.prev_length !== 0);
          s2.match_available = 0;
          s2.match_length = MIN_MATCH - 1;
          s2.strstart++;
          if (bflush) {
            flush_block_only(s2, false);
            if (s2.strm.avail_out === 0) {
              return BS_NEED_MORE;
            }
          }
        } else if (s2.match_available) {
          bflush = trees._tr_tally(s2, 0, s2.window[s2.strstart - 1]);
          if (bflush) {
            flush_block_only(s2, false);
          }
          s2.strstart++;
          s2.lookahead--;
          if (s2.strm.avail_out === 0) {
            return BS_NEED_MORE;
          }
        } else {
          s2.match_available = 1;
          s2.strstart++;
          s2.lookahead--;
        }
      }
      if (s2.match_available) {
        bflush = trees._tr_tally(s2, 0, s2.window[s2.strstart - 1]);
        s2.match_available = 0;
      }
      s2.insert = s2.strstart < MIN_MATCH - 1 ? s2.strstart : MIN_MATCH - 1;
      if (flush2 === Z_FINISH) {
        flush_block_only(s2, true);
        if (s2.strm.avail_out === 0) {
          return BS_FINISH_STARTED;
        }
        return BS_FINISH_DONE;
      }
      if (s2.last_lit) {
        flush_block_only(s2, false);
        if (s2.strm.avail_out === 0) {
          return BS_NEED_MORE;
        }
      }
      return BS_BLOCK_DONE;
    }
    function deflate_rle(s2, flush2) {
      var bflush;
      var prev;
      var scan, strend;
      var _win = s2.window;
      for (; ; ) {
        if (s2.lookahead <= MAX_MATCH) {
          fill_window(s2);
          if (s2.lookahead <= MAX_MATCH && flush2 === Z_NO_FLUSH) {
            return BS_NEED_MORE;
          }
          if (s2.lookahead === 0) {
            break;
          }
        }
        s2.match_length = 0;
        if (s2.lookahead >= MIN_MATCH && s2.strstart > 0) {
          scan = s2.strstart - 1;
          prev = _win[scan];
          if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
            strend = s2.strstart + MAX_MATCH;
            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);
            s2.match_length = MAX_MATCH - (strend - scan);
            if (s2.match_length > s2.lookahead) {
              s2.match_length = s2.lookahead;
            }
          }
        }
        if (s2.match_length >= MIN_MATCH) {
          bflush = trees._tr_tally(s2, 1, s2.match_length - MIN_MATCH);
          s2.lookahead -= s2.match_length;
          s2.strstart += s2.match_length;
          s2.match_length = 0;
        } else {
          bflush = trees._tr_tally(s2, 0, s2.window[s2.strstart]);
          s2.lookahead--;
          s2.strstart++;
        }
        if (bflush) {
          flush_block_only(s2, false);
          if (s2.strm.avail_out === 0) {
            return BS_NEED_MORE;
          }
        }
      }
      s2.insert = 0;
      if (flush2 === Z_FINISH) {
        flush_block_only(s2, true);
        if (s2.strm.avail_out === 0) {
          return BS_FINISH_STARTED;
        }
        return BS_FINISH_DONE;
      }
      if (s2.last_lit) {
        flush_block_only(s2, false);
        if (s2.strm.avail_out === 0) {
          return BS_NEED_MORE;
        }
      }
      return BS_BLOCK_DONE;
    }
    function deflate_huff(s2, flush2) {
      var bflush;
      for (; ; ) {
        if (s2.lookahead === 0) {
          fill_window(s2);
          if (s2.lookahead === 0) {
            if (flush2 === Z_NO_FLUSH) {
              return BS_NEED_MORE;
            }
            break;
          }
        }
        s2.match_length = 0;
        bflush = trees._tr_tally(s2, 0, s2.window[s2.strstart]);
        s2.lookahead--;
        s2.strstart++;
        if (bflush) {
          flush_block_only(s2, false);
          if (s2.strm.avail_out === 0) {
            return BS_NEED_MORE;
          }
        }
      }
      s2.insert = 0;
      if (flush2 === Z_FINISH) {
        flush_block_only(s2, true);
        if (s2.strm.avail_out === 0) {
          return BS_FINISH_STARTED;
        }
        return BS_FINISH_DONE;
      }
      if (s2.last_lit) {
        flush_block_only(s2, false);
        if (s2.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;
    }
    var configuration_table;
    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 */
    ];
    function lm_init(s2) {
      s2.window_size = 2 * s2.w_size;
      zero(s2.head);
      s2.max_lazy_match = configuration_table[s2.level].max_lazy;
      s2.good_match = configuration_table[s2.level].good_length;
      s2.nice_match = configuration_table[s2.level].nice_length;
      s2.max_chain_length = configuration_table[s2.level].max_chain;
      s2.strstart = 0;
      s2.block_start = 0;
      s2.lookahead = 0;
      s2.insert = 0;
      s2.match_length = s2.prev_length = MIN_MATCH - 1;
      s2.match_available = 0;
      s2.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.Buf16(HEAP_SIZE * 2);
      this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2);
      this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2);
      zero(this.dyn_ltree);
      zero(this.dyn_dtree);
      zero(this.bl_tree);
      this.l_desc = null;
      this.d_desc = null;
      this.bl_desc = null;
      this.bl_count = new utils.Buf16(MAX_BITS + 1);
      this.heap = new utils.Buf16(2 * L_CODES + 1);
      zero(this.heap);
      this.heap_len = 0;
      this.heap_max = 0;
      this.depth = new utils.Buf16(2 * L_CODES + 1);
      zero(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 s2;
      if (!strm || !strm.state) {
        return err(strm, Z_STREAM_ERROR);
      }
      strm.total_in = strm.total_out = 0;
      strm.data_type = Z_UNKNOWN;
      s2 = strm.state;
      s2.pending = 0;
      s2.pending_out = 0;
      if (s2.wrap < 0) {
        s2.wrap = -s2.wrap;
      }
      s2.status = s2.wrap ? INIT_STATE : BUSY_STATE;
      strm.adler = s2.wrap === 2 ? 0 : 1;
      s2.last_flush = Z_NO_FLUSH;
      trees._tr_init(s2);
      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) {
        return err(strm, Z_STREAM_ERROR);
      }
      if (windowBits === 8) {
        windowBits = 9;
      }
      var s2 = new DeflateState();
      strm.state = s2;
      s2.strm = strm;
      s2.wrap = wrap;
      s2.gzhead = null;
      s2.w_bits = windowBits;
      s2.w_size = 1 << s2.w_bits;
      s2.w_mask = s2.w_size - 1;
      s2.hash_bits = memLevel + 7;
      s2.hash_size = 1 << s2.hash_bits;
      s2.hash_mask = s2.hash_size - 1;
      s2.hash_shift = ~~((s2.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
      s2.window = new utils.Buf8(s2.w_size * 2);
      s2.head = new utils.Buf16(s2.hash_size);
      s2.prev = new utils.Buf16(s2.w_size);
      s2.lit_bufsize = 1 << memLevel + 6;
      s2.pending_buf_size = s2.lit_bufsize * 4;
      s2.pending_buf = new utils.Buf8(s2.pending_buf_size);
      s2.d_buf = 1 * s2.lit_bufsize;
      s2.l_buf = (1 + 2) * s2.lit_bufsize;
      s2.level = level;
      s2.strategy = strategy;
      s2.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, flush2) {
      var old_flush, s2;
      var beg, val;
      if (!strm || !strm.state || flush2 > Z_BLOCK || flush2 < 0) {
        return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
      }
      s2 = strm.state;
      if (!strm.output || !strm.input && strm.avail_in !== 0 || s2.status === FINISH_STATE && flush2 !== Z_FINISH) {
        return err(strm, strm.avail_out === 0 ? Z_BUF_ERROR : Z_STREAM_ERROR);
      }
      s2.strm = strm;
      old_flush = s2.last_flush;
      s2.last_flush = flush2;
      if (s2.status === INIT_STATE) {
        if (s2.wrap === 2) {
          strm.adler = 0;
          put_byte(s2, 31);
          put_byte(s2, 139);
          put_byte(s2, 8);
          if (!s2.gzhead) {
            put_byte(s2, 0);
            put_byte(s2, 0);
            put_byte(s2, 0);
            put_byte(s2, 0);
            put_byte(s2, 0);
            put_byte(s2, s2.level === 9 ? 2 : s2.strategy >= Z_HUFFMAN_ONLY || s2.level < 2 ? 4 : 0);
            put_byte(s2, OS_CODE);
            s2.status = BUSY_STATE;
          } else {
            put_byte(
              s2,
              (s2.gzhead.text ? 1 : 0) + (s2.gzhead.hcrc ? 2 : 0) + (!s2.gzhead.extra ? 0 : 4) + (!s2.gzhead.name ? 0 : 8) + (!s2.gzhead.comment ? 0 : 16)
            );
            put_byte(s2, s2.gzhead.time & 255);
            put_byte(s2, s2.gzhead.time >> 8 & 255);
            put_byte(s2, s2.gzhead.time >> 16 & 255);
            put_byte(s2, s2.gzhead.time >> 24 & 255);
            put_byte(s2, s2.level === 9 ? 2 : s2.strategy >= Z_HUFFMAN_ONLY || s2.level < 2 ? 4 : 0);
            put_byte(s2, s2.gzhead.os & 255);
            if (s2.gzhead.extra && s2.gzhead.extra.length) {
              put_byte(s2, s2.gzhead.extra.length & 255);
              put_byte(s2, s2.gzhead.extra.length >> 8 & 255);
            }
            if (s2.gzhead.hcrc) {
              strm.adler = crc32(strm.adler, s2.pending_buf, s2.pending, 0);
            }
            s2.gzindex = 0;
            s2.status = EXTRA_STATE;
          }
        } else {
          var header = Z_DEFLATED + (s2.w_bits - 8 << 4) << 8;
          var level_flags = -1;
          if (s2.strategy >= Z_HUFFMAN_ONLY || s2.level < 2) {
            level_flags = 0;
          } else if (s2.level < 6) {
            level_flags = 1;
          } else if (s2.level === 6) {
            level_flags = 2;
          } else {
            level_flags = 3;
          }
          header |= level_flags << 6;
          if (s2.strstart !== 0) {
            header |= PRESET_DICT;
          }
          header += 31 - header % 31;
          s2.status = BUSY_STATE;
          putShortMSB(s2, header);
          if (s2.strstart !== 0) {
            putShortMSB(s2, strm.adler >>> 16);
            putShortMSB(s2, strm.adler & 65535);
          }
          strm.adler = 1;
        }
      }
      if (s2.status === EXTRA_STATE) {
        if (s2.gzhead.extra) {
          beg = s2.pending;
          while (s2.gzindex < (s2.gzhead.extra.length & 65535)) {
            if (s2.pending === s2.pending_buf_size) {
              if (s2.gzhead.hcrc && s2.pending > beg) {
                strm.adler = crc32(strm.adler, s2.pending_buf, s2.pending - beg, beg);
              }
              flush_pending(strm);
              beg = s2.pending;
              if (s2.pending === s2.pending_buf_size) {
                break;
              }
            }
            put_byte(s2, s2.gzhead.extra[s2.gzindex] & 255);
            s2.gzindex++;
          }
          if (s2.gzhead.hcrc && s2.pending > beg) {
            strm.adler = crc32(strm.adler, s2.pending_buf, s2.pending - beg, beg);
          }
          if (s2.gzindex === s2.gzhead.extra.length) {
            s2.gzindex = 0;
            s2.status = NAME_STATE;
          }
        } else {
          s2.status = NAME_STATE;
        }
      }
      if (s2.status === NAME_STATE) {
        if (s2.gzhead.name) {
          beg = s2.pending;
          do {
            if (s2.pending === s2.pending_buf_size) {
              if (s2.gzhead.hcrc && s2.pending > beg) {
                strm.adler = crc32(strm.adler, s2.pending_buf, s2.pending - beg, beg);
              }
              flush_pending(strm);
              beg = s2.pending;
              if (s2.pending === s2.pending_buf_size) {
                val = 1;
                break;
              }
            }
            if (s2.gzindex < s2.gzhead.name.length) {
              val = s2.gzhead.name.charCodeAt(s2.gzindex++) & 255;
            } else {
              val = 0;
            }
            put_byte(s2, val);
          } while (val !== 0);
          if (s2.gzhead.hcrc && s2.pending > beg) {
            strm.adler = crc32(strm.adler, s2.pending_buf, s2.pending - beg, beg);
          }
          if (val === 0) {
            s2.gzindex = 0;
            s2.status = COMMENT_STATE;
          }
        } else {
          s2.status = COMMENT_STATE;
        }
      }
      if (s2.status === COMMENT_STATE) {
        if (s2.gzhead.comment) {
          beg = s2.pending;
          do {
            if (s2.pending === s2.pending_buf_size) {
              if (s2.gzhead.hcrc && s2.pending > beg) {
                strm.adler = crc32(strm.adler, s2.pending_buf, s2.pending - beg, beg);
              }
              flush_pending(strm);
              beg = s2.pending;
              if (s2.pending === s2.pending_buf_size) {
                val = 1;
                break;
              }
            }
            if (s2.gzindex < s2.gzhead.comment.length) {
              val = s2.gzhead.comment.charCodeAt(s2.gzindex++) & 255;
            } else {
              val = 0;
            }
            put_byte(s2, val);
          } while (val !== 0);
          if (s2.gzhead.hcrc && s2.pending > beg) {
            strm.adler = crc32(strm.adler, s2.pending_buf, s2.pending - beg, beg);
          }
          if (val === 0) {
            s2.status = HCRC_STATE;
          }
        } else {
          s2.status = HCRC_STATE;
        }
      }
      if (s2.status === HCRC_STATE) {
        if (s2.gzhead.hcrc) {
          if (s2.pending + 2 > s2.pending_buf_size) {
            flush_pending(strm);
          }
          if (s2.pending + 2 <= s2.pending_buf_size) {
            put_byte(s2, strm.adler & 255);
            put_byte(s2, strm.adler >> 8 & 255);
            strm.adler = 0;
            s2.status = BUSY_STATE;
          }
        } else {
          s2.status = BUSY_STATE;
        }
      }
      if (s2.pending !== 0) {
        flush_pending(strm);
        if (strm.avail_out === 0) {
          s2.last_flush = -1;
          return Z_OK;
        }
      } else if (strm.avail_in === 0 && rank(flush2) <= rank(old_flush) && flush2 !== Z_FINISH) {
        return err(strm, Z_BUF_ERROR);
      }
      if (s2.status === FINISH_STATE && strm.avail_in !== 0) {
        return err(strm, Z_BUF_ERROR);
      }
      if (strm.avail_in !== 0 || s2.lookahead !== 0 || flush2 !== Z_NO_FLUSH && s2.status !== FINISH_STATE) {
        var bstate = s2.strategy === Z_HUFFMAN_ONLY ? deflate_huff(s2, flush2) : s2.strategy === Z_RLE ? deflate_rle(s2, flush2) : configuration_table[s2.level].func(s2, flush2);
        if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
          s2.status = FINISH_STATE;
        }
        if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
          if (strm.avail_out === 0) {
            s2.last_flush = -1;
          }
          return Z_OK;
        }
        if (bstate === BS_BLOCK_DONE) {
          if (flush2 === Z_PARTIAL_FLUSH) {
            trees._tr_align(s2);
          } else if (flush2 !== Z_BLOCK) {
            trees._tr_stored_block(s2, 0, 0, false);
            if (flush2 === Z_FULL_FLUSH) {
              zero(s2.head);
              if (s2.lookahead === 0) {
                s2.strstart = 0;
                s2.block_start = 0;
                s2.insert = 0;
              }
            }
          }
          flush_pending(strm);
          if (strm.avail_out === 0) {
            s2.last_flush = -1;
            return Z_OK;
          }
        }
      }
      if (flush2 !== Z_FINISH) {
        return Z_OK;
      }
      if (s2.wrap <= 0) {
        return Z_STREAM_END;
      }
      if (s2.wrap === 2) {
        put_byte(s2, strm.adler & 255);
        put_byte(s2, strm.adler >> 8 & 255);
        put_byte(s2, strm.adler >> 16 & 255);
        put_byte(s2, strm.adler >> 24 & 255);
        put_byte(s2, strm.total_in & 255);
        put_byte(s2, strm.total_in >> 8 & 255);
        put_byte(s2, strm.total_in >> 16 & 255);
        put_byte(s2, strm.total_in >> 24 & 255);
      } else {
        putShortMSB(s2, strm.adler >>> 16);
        putShortMSB(s2, strm.adler & 65535);
      }
      flush_pending(strm);
      if (s2.wrap > 0) {
        s2.wrap = -s2.wrap;
      }
      return s2.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 s2;
      var str, n2;
      var wrap;
      var avail;
      var next;
      var input;
      var tmpDict;
      if (!strm || !strm.state) {
        return Z_STREAM_ERROR;
      }
      s2 = strm.state;
      wrap = s2.wrap;
      if (wrap === 2 || wrap === 1 && s2.status !== INIT_STATE || s2.lookahead) {
        return Z_STREAM_ERROR;
      }
      if (wrap === 1) {
        strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
      }
      s2.wrap = 0;
      if (dictLength >= s2.w_size) {
        if (wrap === 0) {
          zero(s2.head);
          s2.strstart = 0;
          s2.block_start = 0;
          s2.insert = 0;
        }
        tmpDict = new utils.Buf8(s2.w_size);
        utils.arraySet(tmpDict, dictionary, dictLength - s2.w_size, s2.w_size, 0);
        dictionary = tmpDict;
        dictLength = s2.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(s2);
      while (s2.lookahead >= MIN_MATCH) {
        str = s2.strstart;
        n2 = s2.lookahead - (MIN_MATCH - 1);
        do {
          s2.ins_h = (s2.ins_h << s2.hash_shift ^ s2.window[str + MIN_MATCH - 1]) & s2.hash_mask;
          s2.prev[str & s2.w_mask] = s2.head[s2.ins_h];
          s2.head[s2.ins_h] = str;
          str++;
        } while (--n2);
        s2.strstart = str;
        s2.lookahead = MIN_MATCH - 1;
        fill_window(s2);
      }
      s2.strstart += s2.lookahead;
      s2.block_start = s2.strstart;
      s2.insert = s2.lookahead;
      s2.lookahead = 0;
      s2.match_length = s2.prev_length = MIN_MATCH - 1;
      s2.match_available = 0;
      strm.next_in = next;
      strm.input = input;
      strm.avail_in = avail;
      s2.wrap = wrap;
      return Z_OK;
    }
    exports.deflateInit = deflateInit;
    exports.deflateInit2 = deflateInit2;
    exports.deflateReset = deflateReset;
    exports.deflateResetKeep = deflateResetKeep;
    exports.deflateSetHeader = deflateSetHeader;
    exports.deflate = deflate;
    exports.deflateEnd = deflateEnd;
    exports.deflateSetDictionary = deflateSetDictionary;
    exports.deflateInfo = "pako deflate (from Nodeca project)";
  }
});

// node_modules/pako/lib/utils/strings.js
var require_strings = __commonJS({
  "node_modules/pako/lib/utils/strings.js"(exports) {
    "use strict";
    init_esbuild_buffer_shim();
    var utils = require_common();
    var STR_APPLY_OK = true;
    var 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;
    }
    var _utf8len = new utils.Buf8(256);
    for (q = 0; q < 256; q++) {
      _utf8len[q] = q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1;
    }
    var q;
    _utf8len[254] = _utf8len[254] = 1;
    exports.string2buf = function(str) {
      var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
      for (m_pos = 0; m_pos < str_len; m_pos++) {
        c = str.charCodeAt(m_pos);
        if ((c & 64512) === 55296 && m_pos + 1 < str_len) {
          c2 = str.charCodeAt(m_pos + 1);
          if ((c2 & 64512) === 56320) {
            c = 65536 + (c - 55296 << 10) + (c2 - 56320);
            m_pos++;
          }
        }
        buf_len += c < 128 ? 1 : c < 2048 ? 2 : c < 65536 ? 3 : 4;
      }
      buf = new utils.Buf8(buf_len);
      for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
        c = str.charCodeAt(m_pos);
        if ((c & 64512) === 55296 && m_pos + 1 < str_len) {
          c2 = str.charCodeAt(m_pos + 1);
          if ((c2 & 64512) === 56320) {
            c = 65536 + (c - 55296 << 10) + (c2 - 56320);
            m_pos++;
          }
        }
        if (c < 128) {
          buf[i++] = c;
        } else if (c < 2048) {
          buf[i++] = 192 | c >>> 6;
          buf[i++] = 128 | c & 63;
        } else if (c < 65536) {
          buf[i++] = 224 | c >>> 12;
          buf[i++] = 128 | c >>> 6 & 63;
          buf[i++] = 128 | c & 63;
        } else {
          buf[i++] = 240 | c >>> 18;
          buf[i++] = 128 | c >>> 12 & 63;
          buf[i++] = 128 | c >>> 6 & 63;
          buf[i++] = 128 | c & 63;
        }
      }
      return buf;
    };
    function buf2binstring(buf, len) {
      if (len < 65534) {
        if (buf.subarray && STR_APPLY_UIA_OK || !buf.subarray && STR_APPLY_OK) {
          return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
        }
      }
      var result = "";
      for (var i = 0; i < len; i++) {
        result += String.fromCharCode(buf[i]);
      }
      return result;
    }
    exports.buf2binstring = function(buf) {
      return buf2binstring(buf, buf.length);
    };
    exports.binstring2buf = function(str) {
      var buf = new utils.Buf8(str.length);
      for (var i = 0, len = buf.length; i < len; i++) {
        buf[i] = str.charCodeAt(i);
      }
      return buf;
    };
    exports.buf2string = function(buf, max) {
      var i, out, c, c_len;
      var len = max || buf.length;
      var utf16buf = new Array(len * 2);
      for (out = 0, i = 0; i < len; ) {
        c = buf[i++];
        if (c < 128) {
          utf16buf[out++] = c;
          continue;
        }
        c_len = _utf8len[c];
        if (c_len > 4) {
          utf16buf[out++] = 65533;
          i += c_len - 1;
          continue;
        }
        c &= c_len === 2 ? 31 : c_len === 3 ? 15 : 7;
        while (c_len > 1 && i < len) {
          c = c << 6 | buf[i++] & 63;
          c_len--;
        }
        if (c_len > 1) {
          utf16buf[out++] = 65533;
          continue;
        }
        if (c < 65536) {
          utf16buf[out++] = c;
        } else {
          c -= 65536;
          utf16buf[out++] = 55296 | c >> 10 & 1023;
          utf16buf[out++] = 56320 | c & 1023;
        }
      }
      return buf2binstring(utf16buf, out);
    };
    exports.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;
    };
  }
});

// node_modules/pako/lib/zlib/zstream.js
var require_zstream = __commonJS({
  "node_modules/pako/lib/zlib/zstream.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    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;
    }
    module2.exports = ZStream;
  }
});

// node_modules/pako/lib/deflate.js
var require_deflate2 = __commonJS({
  "node_modules/pako/lib/deflate.js"(exports) {
    "use strict";
    init_esbuild_buffer_shim();
    var zlib_deflate = require_deflate();
    var utils = require_common();
    var strings = require_strings();
    var msg = require_messages();
    var ZStream = require_zstream();
    var toString3 = Object.prototype.toString;
    var Z_NO_FLUSH = 0;
    var Z_FINISH = 4;
    var Z_OK = 0;
    var Z_STREAM_END = 1;
    var Z_SYNC_FLUSH = 2;
    var Z_DEFAULT_COMPRESSION = -1;
    var Z_DEFAULT_STRATEGY = 0;
    var Z_DEFLATED = 8;
    function Deflate(options) {
      if (!(this instanceof Deflate)) return new Deflate(options);
      this.options = utils.assign({
        level: Z_DEFAULT_COMPRESSION,
        method: Z_DEFLATED,
        chunkSize: 16384,
        windowBits: 15,
        memLevel: 8,
        strategy: Z_DEFAULT_STRATEGY,
        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 ZStream();
      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_OK) {
        throw new Error(msg[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 (toString3.call(opt.dictionary) === "[object ArrayBuffer]") {
          dict = new Uint8Array(opt.dictionary);
        } else {
          dict = opt.dictionary;
        }
        status = zlib_deflate.deflateSetDictionary(this.strm, dict);
        if (status !== Z_OK) {
          throw new Error(msg[status]);
        }
        this._dict_set = true;
      }
    }
    Deflate.prototype.push = function(data, 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_FINISH : Z_NO_FLUSH;
      if (typeof data === "string") {
        strm.input = strings.string2buf(data);
      } else if (toString3.call(data) === "[object ArrayBuffer]") {
        strm.input = new Uint8Array(data);
      } else {
        strm.input = data;
      }
      strm.next_in = 0;
      strm.avail_in = strm.input.length;
      do {
        if (strm.avail_out === 0) {
          strm.output = new utils.Buf8(chunkSize);
          strm.next_out = 0;
          strm.avail_out = chunkSize;
        }
        status = zlib_deflate.deflate(strm, _mode);
        if (status !== Z_STREAM_END && status !== Z_OK) {
          this.onEnd(status);
          this.ended = true;
          return false;
        }
        if (strm.avail_out === 0 || strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH)) {
          if (this.options.to === "string") {
            this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
          } else {
            this.onData(utils.shrinkBuf(strm.output, strm.next_out));
          }
        }
      } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
      if (_mode === Z_FINISH) {
        status = zlib_deflate.deflateEnd(this.strm);
        this.onEnd(status);
        this.ended = true;
        return status === Z_OK;
      }
      if (_mode === Z_SYNC_FLUSH) {
        this.onEnd(Z_OK);
        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_OK) {
        if (this.options.to === "string") {
          this.result = this.chunks.join("");
        } else {
          this.result = utils.flattenChunks(this.chunks);
        }
      }
      this.chunks = [];
      this.err = status;
      this.msg = this.strm.msg;
    };
    function deflate(input, options) {
      var deflator = new Deflate(options);
      deflator.push(input, true);
      if (deflator.err) {
        throw deflator.msg || msg[deflator.err];
      }
      return deflator.result;
    }
    function deflateRaw(input, options) {
      options = options || {};
      options.raw = true;
      return deflate(input, options);
    }
    function gzip(input, options) {
      options = options || {};
      options.gzip = true;
      return deflate(input, options);
    }
    exports.Deflate = Deflate;
    exports.deflate = deflate;
    exports.deflateRaw = deflateRaw;
    exports.gzip = gzip;
  }
});

// node_modules/pako/lib/zlib/inffast.js
var require_inffast = __commonJS({
  "node_modules/pako/lib/zlib/inffast.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    var BAD = 30;
    var TYPE = 12;
    module2.exports = function inflate_fast(strm, start) {
      var state;
      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 from2;
      var from_source;
      var input, output;
      state = 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 = state.dmax;
      wsize = state.wsize;
      whave = state.whave;
      wnext = state.wnext;
      s_window = state.window;
      hold = state.hold;
      bits = state.bits;
      lcode = state.lencode;
      dcode = state.distcode;
      lmask = (1 << state.lenbits) - 1;
      dmask = (1 << state.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";
                        state.mode = BAD;
                        break top;
                      }
                      hold >>>= op;
                      bits -= op;
                      op = _out - beg;
                      if (dist > op) {
                        op = dist - op;
                        if (op > whave) {
                          if (state.sane) {
                            strm.msg = "invalid distance too far back";
                            state.mode = BAD;
                            break top;
                          }
                        }
                        from2 = 0;
                        from_source = s_window;
                        if (wnext === 0) {
                          from2 += wsize - op;
                          if (op < len) {
                            len -= op;
                            do {
                              output[_out++] = s_window[from2++];
                            } while (--op);
                            from2 = _out - dist;
                            from_source = output;
                          }
                        } else if (wnext < op) {
                          from2 += wsize + wnext - op;
                          op -= wnext;
                          if (op < len) {
                            len -= op;
                            do {
                              output[_out++] = s_window[from2++];
                            } while (--op);
                            from2 = 0;
                            if (wnext < len) {
                              op = wnext;
                              len -= op;
                              do {
                                output[_out++] = s_window[from2++];
                              } while (--op);
                              from2 = _out - dist;
                              from_source = output;
                            }
                          }
                        } else {
                          from2 += wnext - op;
                          if (op < len) {
                            len -= op;
                            do {
                              output[_out++] = s_window[from2++];
                            } while (--op);
                            from2 = _out - dist;
                            from_source = output;
                          }
                        }
                        while (len > 2) {
                          output[_out++] = from_source[from2++];
                          output[_out++] = from_source[from2++];
                          output[_out++] = from_source[from2++];
                          len -= 3;
                        }
                        if (len) {
                          output[_out++] = from_source[from2++];
                          if (len > 1) {
                            output[_out++] = from_source[from2++];
                          }
                        }
                      } else {
                        from2 = _out - dist;
                        do {
                          output[_out++] = output[from2++];
                          output[_out++] = output[from2++];
                          output[_out++] = output[from2++];
                          len -= 3;
                        } while (len > 2);
                        if (len) {
                          output[_out++] = output[from2++];
                          if (len > 1) {
                            output[_out++] = output[from2++];
                          }
                        }
                      }
                    } else if ((op & 64) === 0) {
                      here = dcode[(here & 65535) + (hold & (1 << op) - 1)];
                      continue dodist;
                    } else {
                      strm.msg = "invalid distance code";
                      state.mode = BAD;
                      break top;
                    }
                    break;
                  }
              } else if ((op & 64) === 0) {
                here = lcode[(here & 65535) + (hold & (1 << op) - 1)];
                continue dolen;
              } else if (op & 32) {
                state.mode = TYPE;
                break top;
              } else {
                strm.msg = "invalid literal/length code";
                state.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);
      state.hold = hold;
      state.bits = bits;
      return;
    };
  }
});

// node_modules/pako/lib/zlib/inftrees.js
var require_inftrees = __commonJS({
  "node_modules/pako/lib/zlib/inftrees.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    var utils = require_common();
    var MAXBITS = 15;
    var ENOUGH_LENS = 852;
    var ENOUGH_DISTS = 592;
    var CODES = 0;
    var LENS = 1;
    var DISTS = 2;
    var 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
    ];
    var 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
    ];
    var 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
    ];
    var 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
    ];
    module2.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) {
      var bits = opts.bits;
      var len = 0;
      var sym = 0;
      var min = 0, max = 0;
      var root = 0;
      var curr = 0;
      var drop = 0;
      var left = 0;
      var used = 0;
      var huff = 0;
      var incr;
      var fill2;
      var low;
      var mask;
      var next;
      var base = null;
      var base_index = 0;
      var end;
      var count = new utils.Buf16(MAXBITS + 1);
      var offs = new utils.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 (min = 1; min < max; min++) {
        if (count[min] !== 0) {
          break;
        }
      }
      if (root < min) {
        root = min;
      }
      left = 1;
      for (len = 1; len <= MAXBITS; len++) {
        left <<= 1;
        left -= count[len];
        if (left < 0) {
          return -1;
        }
      }
      if (left > 0 && (type === 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 (type === CODES) {
        base = extra = work;
        end = 19;
      } else if (type === LENS) {
        base = lbase;
        base_index -= 257;
        extra = lext;
        extra_index -= 257;
        end = 256;
      } else {
        base = dbase;
        extra = dext;
        end = -1;
      }
      huff = 0;
      sym = 0;
      len = min;
      next = table_index;
      curr = root;
      drop = 0;
      low = -1;
      used = 1 << root;
      mask = used - 1;
      if (type === LENS && used > ENOUGH_LENS || type === 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 = base[base_index + work[sym]];
        } else {
          here_op = 32 + 64;
          here_val = 0;
        }
        incr = 1 << len - drop;
        fill2 = 1 << curr;
        min = fill2;
        do {
          fill2 -= incr;
          table[next + (huff >> drop) + fill2] = here_bits << 24 | here_op << 16 | here_val | 0;
        } while (fill2 !== 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 += min;
          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 (type === LENS && used > ENOUGH_LENS || type === 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;
    };
  }
});

// node_modules/pako/lib/zlib/inflate.js
var require_inflate = __commonJS({
  "node_modules/pako/lib/zlib/inflate.js"(exports) {
    "use strict";
    init_esbuild_buffer_shim();
    var utils = require_common();
    var adler32 = require_adler32();
    var crc32 = require_crc322();
    var inflate_fast = require_inffast();
    var inflate_table = require_inftrees();
    var CODES = 0;
    var LENS = 1;
    var DISTS = 2;
    var Z_FINISH = 4;
    var Z_BLOCK = 5;
    var Z_TREES = 6;
    var Z_OK = 0;
    var Z_STREAM_END = 1;
    var Z_NEED_DICT = 2;
    var Z_STREAM_ERROR = -2;
    var Z_DATA_ERROR = -3;
    var Z_MEM_ERROR = -4;
    var Z_BUF_ERROR = -5;
    var Z_DEFLATED = 8;
    var HEAD = 1;
    var FLAGS = 2;
    var TIME = 3;
    var OS = 4;
    var EXLEN = 5;
    var EXTRA = 6;
    var NAME = 7;
    var COMMENT = 8;
    var HCRC = 9;
    var DICTID = 10;
    var DICT = 11;
    var TYPE = 12;
    var TYPEDO = 13;
    var STORED = 14;
    var COPY_ = 15;
    var COPY = 16;
    var TABLE = 17;
    var LENLENS = 18;
    var CODELENS = 19;
    var LEN_ = 20;
    var LEN = 21;
    var LENEXT = 22;
    var DIST = 23;
    var DISTEXT = 24;
    var MATCH = 25;
    var LIT = 26;
    var CHECK = 27;
    var LENGTH = 28;
    var DONE = 29;
    var BAD = 30;
    var MEM = 31;
    var SYNC = 32;
    var ENOUGH_LENS = 852;
    var ENOUGH_DISTS = 592;
    var MAX_WBITS = 15;
    var DEF_WBITS = MAX_WBITS;
    function zswap32(q) {
      return (q >>> 24 & 255) + (q >>> 8 & 65280) + ((q & 65280) << 8) + ((q & 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.Buf16(320);
      this.work = new utils.Buf16(288);
      this.lendyn = null;
      this.distdyn = null;
      this.sane = 0;
      this.back = 0;
      this.was = 0;
    }
    function inflateResetKeep(strm) {
      var state;
      if (!strm || !strm.state) {
        return Z_STREAM_ERROR;
      }
      state = strm.state;
      strm.total_in = strm.total_out = state.total = 0;
      strm.msg = "";
      if (state.wrap) {
        strm.adler = state.wrap & 1;
      }
      state.mode = HEAD;
      state.last = 0;
      state.havedict = 0;
      state.dmax = 32768;
      state.head = null;
      state.hold = 0;
      state.bits = 0;
      state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
      state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
      state.sane = 1;
      state.back = -1;
      return Z_OK;
    }
    function inflateReset(strm) {
      var state;
      if (!strm || !strm.state) {
        return Z_STREAM_ERROR;
      }
      state = strm.state;
      state.wsize = 0;
      state.whave = 0;
      state.wnext = 0;
      return inflateResetKeep(strm);
    }
    function inflateReset2(strm, windowBits) {
      var wrap;
      var state;
      if (!strm || !strm.state) {
        return Z_STREAM_ERROR;
      }
      state = 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_ERROR;
      }
      if (state.window !== null && state.wbits !== windowBits) {
        state.window = null;
      }
      state.wrap = wrap;
      state.wbits = windowBits;
      return inflateReset(strm);
    }
    function inflateInit2(strm, windowBits) {
      var ret;
      var state;
      if (!strm) {
        return Z_STREAM_ERROR;
      }
      state = new InflateState();
      strm.state = state;
      state.window = null;
      ret = inflateReset2(strm, windowBits);
      if (ret !== Z_OK) {
        strm.state = null;
      }
      return ret;
    }
    function inflateInit(strm) {
      return inflateInit2(strm, DEF_WBITS);
    }
    var virgin = true;
    var lenfix;
    var distfix;
    function fixedtables(state) {
      if (virgin) {
        var sym;
        lenfix = new utils.Buf32(512);
        distfix = new utils.Buf32(32);
        sym = 0;
        while (sym < 144) {
          state.lens[sym++] = 8;
        }
        while (sym < 256) {
          state.lens[sym++] = 9;
        }
        while (sym < 280) {
          state.lens[sym++] = 7;
        }
        while (sym < 288) {
          state.lens[sym++] = 8;
        }
        inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });
        sym = 0;
        while (sym < 32) {
          state.lens[sym++] = 5;
        }
        inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });
        virgin = false;
      }
      state.lencode = lenfix;
      state.lenbits = 9;
      state.distcode = distfix;
      state.distbits = 5;
    }
    function updatewindow(strm, src, end, copy2) {
      var dist;
      var state = strm.state;
      if (state.window === null) {
        state.wsize = 1 << state.wbits;
        state.wnext = 0;
        state.whave = 0;
        state.window = new utils.Buf8(state.wsize);
      }
      if (copy2 >= state.wsize) {
        utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);
        state.wnext = 0;
        state.whave = state.wsize;
      } else {
        dist = state.wsize - state.wnext;
        if (dist > copy2) {
          dist = copy2;
        }
        utils.arraySet(state.window, src, end - copy2, dist, state.wnext);
        copy2 -= dist;
        if (copy2) {
          utils.arraySet(state.window, src, end - copy2, copy2, 0);
          state.wnext = copy2;
          state.whave = state.wsize;
        } else {
          state.wnext += dist;
          if (state.wnext === state.wsize) {
            state.wnext = 0;
          }
          if (state.whave < state.wsize) {
            state.whave += dist;
          }
        }
      }
      return 0;
    }
    function inflate(strm, flush2) {
      var state;
      var input, output;
      var next;
      var put;
      var have, left;
      var hold;
      var bits;
      var _in, _out;
      var copy2;
      var from2;
      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.Buf8(4);
      var opts;
      var n2;
      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_ERROR;
      }
      state = strm.state;
      if (state.mode === TYPE) {
        state.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 = state.hold;
      bits = state.bits;
      _in = have;
      _out = left;
      ret = Z_OK;
      inf_leave:
        for (; ; ) {
          switch (state.mode) {
            case HEAD:
              if (state.wrap === 0) {
                state.mode = TYPEDO;
                break;
              }
              while (bits < 16) {
                if (have === 0) {
                  break inf_leave;
                }
                have--;
                hold += input[next++] << bits;
                bits += 8;
              }
              if (state.wrap & 2 && hold === 35615) {
                state.check = 0;
                hbuf[0] = hold & 255;
                hbuf[1] = hold >>> 8 & 255;
                state.check = crc32(state.check, hbuf, 2, 0);
                hold = 0;
                bits = 0;
                state.mode = FLAGS;
                break;
              }
              state.flags = 0;
              if (state.head) {
                state.head.done = false;
              }
              if (!(state.wrap & 1) || /* check if zlib header allowed */
              (((hold & 255) << 8) + (hold >> 8)) % 31) {
                strm.msg = "incorrect header check";
                state.mode = BAD;
                break;
              }
              if ((hold & 15) !== Z_DEFLATED) {
                strm.msg = "unknown compression method";
                state.mode = BAD;
                break;
              }
              hold >>>= 4;
              bits -= 4;
              len = (hold & 15) + 8;
              if (state.wbits === 0) {
                state.wbits = len;
              } else if (len > state.wbits) {
                strm.msg = "invalid window size";
                state.mode = BAD;
                break;
              }
              state.dmax = 1 << len;
              strm.adler = state.check = 1;
              state.mode = hold & 512 ? DICTID : TYPE;
              hold = 0;
              bits = 0;
              break;
            case FLAGS:
              while (bits < 16) {
                if (have === 0) {
                  break inf_leave;
                }
                have--;
                hold += input[next++] << bits;
                bits += 8;
              }
              state.flags = hold;
              if ((state.flags & 255) !== Z_DEFLATED) {
                strm.msg = "unknown compression method";
                state.mode = BAD;
                break;
              }
              if (state.flags & 57344) {
                strm.msg = "unknown header flags set";
                state.mode = BAD;
                break;
              }
              if (state.head) {
                state.head.text = hold >> 8 & 1;
              }
              if (state.flags & 512) {
                hbuf[0] = hold & 255;
                hbuf[1] = hold >>> 8 & 255;
                state.check = crc32(state.check, hbuf, 2, 0);
              }
              hold = 0;
              bits = 0;
              state.mode = TIME;
            /* falls through */
            case TIME:
              while (bits < 32) {
                if (have === 0) {
                  break inf_leave;
                }
                have--;
                hold += input[next++] << bits;
                bits += 8;
              }
              if (state.head) {
                state.head.time = hold;
              }
              if (state.flags & 512) {
                hbuf[0] = hold & 255;
                hbuf[1] = hold >>> 8 & 255;
                hbuf[2] = hold >>> 16 & 255;
                hbuf[3] = hold >>> 24 & 255;
                state.check = crc32(state.check, hbuf, 4, 0);
              }
              hold = 0;
              bits = 0;
              state.mode = OS;
            /* falls through */
            case OS:
              while (bits < 16) {
                if (have === 0) {
                  break inf_leave;
                }
                have--;
                hold += input[next++] << bits;
                bits += 8;
              }
              if (state.head) {
                state.head.xflags = hold & 255;
                state.head.os = hold >> 8;
              }
              if (state.flags & 512) {
                hbuf[0] = hold & 255;
                hbuf[1] = hold >>> 8 & 255;
                state.check = crc32(state.check, hbuf, 2, 0);
              }
              hold = 0;
              bits = 0;
              state.mode = EXLEN;
            /* falls through */
            case EXLEN:
              if (state.flags & 1024) {
                while (bits < 16) {
                  if (have === 0) {
                    break inf_leave;
                  }
                  have--;
                  hold += input[next++] << bits;
                  bits += 8;
                }
                state.length = hold;
                if (state.head) {
                  state.head.extra_len = hold;
                }
                if (state.flags & 512) {
                  hbuf[0] = hold & 255;
                  hbuf[1] = hold >>> 8 & 255;
                  state.check = crc32(state.check, hbuf, 2, 0);
                }
                hold = 0;
                bits = 0;
              } else if (state.head) {
                state.head.extra = null;
              }
              state.mode = EXTRA;
            /* falls through */
            case EXTRA:
              if (state.flags & 1024) {
                copy2 = state.length;
                if (copy2 > have) {
                  copy2 = have;
                }
                if (copy2) {
                  if (state.head) {
                    len = state.head.extra_len - state.length;
                    if (!state.head.extra) {
                      state.head.extra = new Array(state.head.extra_len);
                    }
                    utils.arraySet(
                      state.head.extra,
                      input,
                      next,
                      // extra field is limited to 65536 bytes
                      // - no need for additional size check
                      copy2,
                      /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
                      len
                    );
                  }
                  if (state.flags & 512) {
                    state.check = crc32(state.check, input, copy2, next);
                  }
                  have -= copy2;
                  next += copy2;
                  state.length -= copy2;
                }
                if (state.length) {
                  break inf_leave;
                }
              }
              state.length = 0;
              state.mode = NAME;
            /* falls through */
            case NAME:
              if (state.flags & 2048) {
                if (have === 0) {
                  break inf_leave;
                }
                copy2 = 0;
                do {
                  len = input[next + copy2++];
                  if (state.head && len && state.length < 65536) {
                    state.head.name += String.fromCharCode(len);
                  }
                } while (len && copy2 < have);
                if (state.flags & 512) {
                  state.check = crc32(state.check, input, copy2, next);
                }
                have -= copy2;
                next += copy2;
                if (len) {
                  break inf_leave;
                }
              } else if (state.head) {
                state.head.name = null;
              }
              state.length = 0;
              state.mode = COMMENT;
            /* falls through */
            case COMMENT:
              if (state.flags & 4096) {
                if (have === 0) {
                  break inf_leave;
                }
                copy2 = 0;
                do {
                  len = input[next + copy2++];
                  if (state.head && len && state.length < 65536) {
                    state.head.comment += String.fromCharCode(len);
                  }
                } while (len && copy2 < have);
                if (state.flags & 512) {
                  state.check = crc32(state.check, input, copy2, next);
                }
                have -= copy2;
                next += copy2;
                if (len) {
                  break inf_leave;
                }
              } else if (state.head) {
                state.head.comment = null;
              }
              state.mode = HCRC;
            /* falls through */
            case HCRC:
              if (state.flags & 512) {
                while (bits < 16) {
                  if (have === 0) {
                    break inf_leave;
                  }
                  have--;
                  hold += input[next++] << bits;
                  bits += 8;
                }
                if (hold !== (state.check & 65535)) {
                  strm.msg = "header crc mismatch";
                  state.mode = BAD;
                  break;
                }
                hold = 0;
                bits = 0;
              }
              if (state.head) {
                state.head.hcrc = state.flags >> 9 & 1;
                state.head.done = true;
              }
              strm.adler = state.check = 0;
              state.mode = TYPE;
              break;
            case DICTID:
              while (bits < 32) {
                if (have === 0) {
                  break inf_leave;
                }
                have--;
                hold += input[next++] << bits;
                bits += 8;
              }
              strm.adler = state.check = zswap32(hold);
              hold = 0;
              bits = 0;
              state.mode = DICT;
            /* falls through */
            case DICT:
              if (state.havedict === 0) {
                strm.next_out = put;
                strm.avail_out = left;
                strm.next_in = next;
                strm.avail_in = have;
                state.hold = hold;
                state.bits = bits;
                return Z_NEED_DICT;
              }
              strm.adler = state.check = 1;
              state.mode = TYPE;
            /* falls through */
            case TYPE:
              if (flush2 === Z_BLOCK || flush2 === Z_TREES) {
                break inf_leave;
              }
            /* falls through */
            case TYPEDO:
              if (state.last) {
                hold >>>= bits & 7;
                bits -= bits & 7;
                state.mode = CHECK;
                break;
              }
              while (bits < 3) {
                if (have === 0) {
                  break inf_leave;
                }
                have--;
                hold += input[next++] << bits;
                bits += 8;
              }
              state.last = hold & 1;
              hold >>>= 1;
              bits -= 1;
              switch (hold & 3) {
                case 0:
                  state.mode = STORED;
                  break;
                case 1:
                  fixedtables(state);
                  state.mode = LEN_;
                  if (flush2 === Z_TREES) {
                    hold >>>= 2;
                    bits -= 2;
                    break inf_leave;
                  }
                  break;
                case 2:
                  state.mode = TABLE;
                  break;
                case 3:
                  strm.msg = "invalid block type";
                  state.mode = BAD;
              }
              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";
                state.mode = BAD;
                break;
              }
              state.length = hold & 65535;
              hold = 0;
              bits = 0;
              state.mode = COPY_;
              if (flush2 === Z_TREES) {
                break inf_leave;
              }
            /* falls through */
            case COPY_:
              state.mode = COPY;
            /* falls through */
            case COPY:
              copy2 = state.length;
              if (copy2) {
                if (copy2 > have) {
                  copy2 = have;
                }
                if (copy2 > left) {
                  copy2 = left;
                }
                if (copy2 === 0) {
                  break inf_leave;
                }
                utils.arraySet(output, input, next, copy2, put);
                have -= copy2;
                next += copy2;
                left -= copy2;
                put += copy2;
                state.length -= copy2;
                break;
              }
              state.mode = TYPE;
              break;
            case TABLE:
              while (bits < 14) {
                if (have === 0) {
                  break inf_leave;
                }
                have--;
                hold += input[next++] << bits;
                bits += 8;
              }
              state.nlen = (hold & 31) + 257;
              hold >>>= 5;
              bits -= 5;
              state.ndist = (hold & 31) + 1;
              hold >>>= 5;
              bits -= 5;
              state.ncode = (hold & 15) + 4;
              hold >>>= 4;
              bits -= 4;
              if (state.nlen > 286 || state.ndist > 30) {
                strm.msg = "too many length or distance symbols";
                state.mode = BAD;
                break;
              }
              state.have = 0;
              state.mode = LENLENS;
            /* falls through */
            case LENLENS:
              while (state.have < state.ncode) {
                while (bits < 3) {
                  if (have === 0) {
                    break inf_leave;
                  }
                  have--;
                  hold += input[next++] << bits;
                  bits += 8;
                }
                state.lens[order[state.have++]] = hold & 7;
                hold >>>= 3;
                bits -= 3;
              }
              while (state.have < 19) {
                state.lens[order[state.have++]] = 0;
              }
              state.lencode = state.lendyn;
              state.lenbits = 7;
              opts = { bits: state.lenbits };
              ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
              state.lenbits = opts.bits;
              if (ret) {
                strm.msg = "invalid code lengths set";
                state.mode = BAD;
                break;
              }
              state.have = 0;
              state.mode = CODELENS;
            /* falls through */
            case CODELENS:
              while (state.have < state.nlen + state.ndist) {
                for (; ; ) {
                  here = state.lencode[hold & (1 << state.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;
                  state.lens[state.have++] = here_val;
                } else {
                  if (here_val === 16) {
                    n2 = here_bits + 2;
                    while (bits < n2) {
                      if (have === 0) {
                        break inf_leave;
                      }
                      have--;
                      hold += input[next++] << bits;
                      bits += 8;
                    }
                    hold >>>= here_bits;
                    bits -= here_bits;
                    if (state.have === 0) {
                      strm.msg = "invalid bit length repeat";
                      state.mode = BAD;
                      break;
                    }
                    len = state.lens[state.have - 1];
                    copy2 = 3 + (hold & 3);
                    hold >>>= 2;
                    bits -= 2;
                  } else if (here_val === 17) {
                    n2 = here_bits + 3;
                    while (bits < n2) {
                      if (have === 0) {
                        break inf_leave;
                      }
                      have--;
                      hold += input[next++] << bits;
                      bits += 8;
                    }
                    hold >>>= here_bits;
                    bits -= here_bits;
                    len = 0;
                    copy2 = 3 + (hold & 7);
                    hold >>>= 3;
                    bits -= 3;
                  } else {
                    n2 = here_bits + 7;
                    while (bits < n2) {
                      if (have === 0) {
                        break inf_leave;
                      }
                      have--;
                      hold += input[next++] << bits;
                      bits += 8;
                    }
                    hold >>>= here_bits;
                    bits -= here_bits;
                    len = 0;
                    copy2 = 11 + (hold & 127);
                    hold >>>= 7;
                    bits -= 7;
                  }
                  if (state.have + copy2 > state.nlen + state.ndist) {
                    strm.msg = "invalid bit length repeat";
                    state.mode = BAD;
                    break;
                  }
                  while (copy2--) {
                    state.lens[state.have++] = len;
                  }
                }
              }
              if (state.mode === BAD) {
                break;
              }
              if (state.lens[256] === 0) {
                strm.msg = "invalid code -- missing end-of-block";
                state.mode = BAD;
                break;
              }
              state.lenbits = 9;
              opts = { bits: state.lenbits };
              ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
              state.lenbits = opts.bits;
              if (ret) {
                strm.msg = "invalid literal/lengths set";
                state.mode = BAD;
                break;
              }
              state.distbits = 6;
              state.distcode = state.distdyn;
              opts = { bits: state.distbits };
              ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
              state.distbits = opts.bits;
              if (ret) {
                strm.msg = "invalid distances set";
                state.mode = BAD;
                break;
              }
              state.mode = LEN_;
              if (flush2 === Z_TREES) {
                break inf_leave;
              }
            /* falls through */
            case LEN_:
              state.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;
                state.hold = hold;
                state.bits = bits;
                inflate_fast(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 = state.hold;
                bits = state.bits;
                if (state.mode === TYPE) {
                  state.back = -1;
                }
                break;
              }
              state.back = 0;
              for (; ; ) {
                here = state.lencode[hold & (1 << state.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 = state.lencode[last_val + ((hold & (1 << last_bits + last_op) - 1) >> 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;
                state.back += last_bits;
              }
              hold >>>= here_bits;
              bits -= here_bits;
              state.back += here_bits;
              state.length = here_val;
              if (here_op === 0) {
                state.mode = LIT;
                break;
              }
              if (here_op & 32) {
                state.back = -1;
                state.mode = TYPE;
                break;
              }
              if (here_op & 64) {
                strm.msg = "invalid literal/length code";
                state.mode = BAD;
                break;
              }
              state.extra = here_op & 15;
              state.mode = LENEXT;
            /* falls through */
            case LENEXT:
              if (state.extra) {
                n2 = state.extra;
                while (bits < n2) {
                  if (have === 0) {
                    break inf_leave;
                  }
                  have--;
                  hold += input[next++] << bits;
                  bits += 8;
                }
                state.length += hold & (1 << state.extra) - 1;
                hold >>>= state.extra;
                bits -= state.extra;
                state.back += state.extra;
              }
              state.was = state.length;
              state.mode = DIST;
            /* falls through */
            case DIST:
              for (; ; ) {
                here = state.distcode[hold & (1 << state.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 = state.distcode[last_val + ((hold & (1 << last_bits + last_op) - 1) >> 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;
                state.back += last_bits;
              }
              hold >>>= here_bits;
              bits -= here_bits;
              state.back += here_bits;
              if (here_op & 64) {
                strm.msg = "invalid distance code";
                state.mode = BAD;
                break;
              }
              state.offset = here_val;
              state.extra = here_op & 15;
              state.mode = DISTEXT;
            /* falls through */
            case DISTEXT:
              if (state.extra) {
                n2 = state.extra;
                while (bits < n2) {
                  if (have === 0) {
                    break inf_leave;
                  }
                  have--;
                  hold += input[next++] << bits;
                  bits += 8;
                }
                state.offset += hold & (1 << state.extra) - 1;
                hold >>>= state.extra;
                bits -= state.extra;
                state.back += state.extra;
              }
              if (state.offset > state.dmax) {
                strm.msg = "invalid distance too far back";
                state.mode = BAD;
                break;
              }
              state.mode = MATCH;
            /* falls through */
            case MATCH:
              if (left === 0) {
                break inf_leave;
              }
              copy2 = _out - left;
              if (state.offset > copy2) {
                copy2 = state.offset - copy2;
                if (copy2 > state.whave) {
                  if (state.sane) {
                    strm.msg = "invalid distance too far back";
                    state.mode = BAD;
                    break;
                  }
                }
                if (copy2 > state.wnext) {
                  copy2 -= state.wnext;
                  from2 = state.wsize - copy2;
                } else {
                  from2 = state.wnext - copy2;
                }
                if (copy2 > state.length) {
                  copy2 = state.length;
                }
                from_source = state.window;
              } else {
                from_source = output;
                from2 = put - state.offset;
                copy2 = state.length;
              }
              if (copy2 > left) {
                copy2 = left;
              }
              left -= copy2;
              state.length -= copy2;
              do {
                output[put++] = from_source[from2++];
              } while (--copy2);
              if (state.length === 0) {
                state.mode = LEN;
              }
              break;
            case LIT:
              if (left === 0) {
                break inf_leave;
              }
              output[put++] = state.length;
              left--;
              state.mode = LEN;
              break;
            case CHECK:
              if (state.wrap) {
                while (bits < 32) {
                  if (have === 0) {
                    break inf_leave;
                  }
                  have--;
                  hold |= input[next++] << bits;
                  bits += 8;
                }
                _out -= left;
                strm.total_out += _out;
                state.total += _out;
                if (_out) {
                  strm.adler = state.check = /*UPDATE(state.check, put - _out, _out);*/
                  state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out);
                }
                _out = left;
                if ((state.flags ? hold : zswap32(hold)) !== state.check) {
                  strm.msg = "incorrect data check";
                  state.mode = BAD;
                  break;
                }
                hold = 0;
                bits = 0;
              }
              state.mode = LENGTH;
            /* falls through */
            case LENGTH:
              if (state.wrap && state.flags) {
                while (bits < 32) {
                  if (have === 0) {
                    break inf_leave;
                  }
                  have--;
                  hold += input[next++] << bits;
                  bits += 8;
                }
                if (hold !== (state.total & 4294967295)) {
                  strm.msg = "incorrect length check";
                  state.mode = BAD;
                  break;
                }
                hold = 0;
                bits = 0;
              }
              state.mode = DONE;
            /* falls through */
            case DONE:
              ret = Z_STREAM_END;
              break inf_leave;
            case BAD:
              ret = Z_DATA_ERROR;
              break inf_leave;
            case MEM:
              return Z_MEM_ERROR;
            case SYNC:
            /* falls through */
            default:
              return Z_STREAM_ERROR;
          }
        }
      strm.next_out = put;
      strm.avail_out = left;
      strm.next_in = next;
      strm.avail_in = have;
      state.hold = hold;
      state.bits = bits;
      if (state.wsize || _out !== strm.avail_out && state.mode < BAD && (state.mode < CHECK || flush2 !== Z_FINISH)) {
        if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
          state.mode = MEM;
          return Z_MEM_ERROR;
        }
      }
      _in -= strm.avail_in;
      _out -= strm.avail_out;
      strm.total_in += _in;
      strm.total_out += _out;
      state.total += _out;
      if (state.wrap && _out) {
        strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
        state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out);
      }
      strm.data_type = state.bits + (state.last ? 64 : 0) + (state.mode === TYPE ? 128 : 0) + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
      if ((_in === 0 && _out === 0 || flush2 === Z_FINISH) && ret === Z_OK) {
        ret = Z_BUF_ERROR;
      }
      return ret;
    }
    function inflateEnd(strm) {
      if (!strm || !strm.state) {
        return Z_STREAM_ERROR;
      }
      var state = strm.state;
      if (state.window) {
        state.window = null;
      }
      strm.state = null;
      return Z_OK;
    }
    function inflateGetHeader(strm, head) {
      var state;
      if (!strm || !strm.state) {
        return Z_STREAM_ERROR;
      }
      state = strm.state;
      if ((state.wrap & 2) === 0) {
        return Z_STREAM_ERROR;
      }
      state.head = head;
      head.done = false;
      return Z_OK;
    }
    function inflateSetDictionary(strm, dictionary) {
      var dictLength = dictionary.length;
      var state;
      var dictid;
      var ret;
      if (!strm || !strm.state) {
        return Z_STREAM_ERROR;
      }
      state = strm.state;
      if (state.wrap !== 0 && state.mode !== DICT) {
        return Z_STREAM_ERROR;
      }
      if (state.mode === DICT) {
        dictid = 1;
        dictid = adler32(dictid, dictionary, dictLength, 0);
        if (dictid !== state.check) {
          return Z_DATA_ERROR;
        }
      }
      ret = updatewindow(strm, dictionary, dictLength, dictLength);
      if (ret) {
        state.mode = MEM;
        return Z_MEM_ERROR;
      }
      state.havedict = 1;
      return Z_OK;
    }
    exports.inflateReset = inflateReset;
    exports.inflateReset2 = inflateReset2;
    exports.inflateResetKeep = inflateResetKeep;
    exports.inflateInit = inflateInit;
    exports.inflateInit2 = inflateInit2;
    exports.inflate = inflate;
    exports.inflateEnd = inflateEnd;
    exports.inflateGetHeader = inflateGetHeader;
    exports.inflateSetDictionary = inflateSetDictionary;
    exports.inflateInfo = "pako inflate (from Nodeca project)";
  }
});

// node_modules/pako/lib/zlib/constants.js
var require_constants = __commonJS({
  "node_modules/pako/lib/zlib/constants.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    module2.exports = {
      /* 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
    };
  }
});

// node_modules/pako/lib/zlib/gzheader.js
var require_gzheader = __commonJS({
  "node_modules/pako/lib/zlib/gzheader.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    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;
    }
    module2.exports = GZheader;
  }
});

// node_modules/pako/lib/inflate.js
var require_inflate2 = __commonJS({
  "node_modules/pako/lib/inflate.js"(exports) {
    "use strict";
    init_esbuild_buffer_shim();
    var zlib_inflate = require_inflate();
    var utils = require_common();
    var strings = require_strings();
    var c = require_constants();
    var msg = require_messages();
    var ZStream = require_zstream();
    var GZheader = require_gzheader();
    var toString3 = Object.prototype.toString;
    function Inflate(options) {
      if (!(this instanceof Inflate)) return new Inflate(options);
      this.options = utils.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 ZStream();
      this.strm.avail_out = 0;
      var status = zlib_inflate.inflateInit2(
        this.strm,
        opt.windowBits
      );
      if (status !== c.Z_OK) {
        throw new Error(msg[status]);
      }
      this.header = new GZheader();
      zlib_inflate.inflateGetHeader(this.strm, this.header);
      if (opt.dictionary) {
        if (typeof opt.dictionary === "string") {
          opt.dictionary = strings.string2buf(opt.dictionary);
        } else if (toString3.call(opt.dictionary) === "[object ArrayBuffer]") {
          opt.dictionary = new Uint8Array(opt.dictionary);
        }
        if (opt.raw) {
          status = zlib_inflate.inflateSetDictionary(this.strm, opt.dictionary);
          if (status !== c.Z_OK) {
            throw new Error(msg[status]);
          }
        }
      }
    }
    Inflate.prototype.push = function(data, 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 ? c.Z_FINISH : c.Z_NO_FLUSH;
      if (typeof data === "string") {
        strm.input = strings.binstring2buf(data);
      } else if (toString3.call(data) === "[object ArrayBuffer]") {
        strm.input = new Uint8Array(data);
      } else {
        strm.input = data;
      }
      strm.next_in = 0;
      strm.avail_in = strm.input.length;
      do {
        if (strm.avail_out === 0) {
          strm.output = new utils.Buf8(chunkSize);
          strm.next_out = 0;
          strm.avail_out = chunkSize;
        }
        status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH);
        if (status === c.Z_NEED_DICT && dictionary) {
          status = zlib_inflate.inflateSetDictionary(this.strm, dictionary);
        }
        if (status === c.Z_BUF_ERROR && allowBufError === true) {
          status = c.Z_OK;
          allowBufError = false;
        }
        if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
          this.onEnd(status);
          this.ended = true;
          return false;
        }
        if (strm.next_out) {
          if (strm.avail_out === 0 || status === c.Z_STREAM_END || strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH)) {
            if (this.options.to === "string") {
              next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
              tail = strm.next_out - next_out_utf8;
              utf8str = strings.buf2string(strm.output, next_out_utf8);
              strm.next_out = tail;
              strm.avail_out = chunkSize - tail;
              if (tail) {
                utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0);
              }
              this.onData(utf8str);
            } else {
              this.onData(utils.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 !== c.Z_STREAM_END);
      if (status === c.Z_STREAM_END) {
        _mode = c.Z_FINISH;
      }
      if (_mode === c.Z_FINISH) {
        status = zlib_inflate.inflateEnd(this.strm);
        this.onEnd(status);
        this.ended = true;
        return status === c.Z_OK;
      }
      if (_mode === c.Z_SYNC_FLUSH) {
        this.onEnd(c.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 === c.Z_OK) {
        if (this.options.to === "string") {
          this.result = this.chunks.join("");
        } else {
          this.result = utils.flattenChunks(this.chunks);
        }
      }
      this.chunks = [];
      this.err = status;
      this.msg = this.strm.msg;
    };
    function inflate(input, options) {
      var inflator = new Inflate(options);
      inflator.push(input, true);
      if (inflator.err) {
        throw inflator.msg || msg[inflator.err];
      }
      return inflator.result;
    }
    function inflateRaw(input, options) {
      options = options || {};
      options.raw = true;
      return inflate(input, options);
    }
    exports.Inflate = Inflate;
    exports.inflate = inflate;
    exports.inflateRaw = inflateRaw;
    exports.ungzip = inflate;
  }
});

// node_modules/pako/index.js
var require_pako = __commonJS({
  "node_modules/pako/index.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    var assign = require_common().assign;
    var deflate = require_deflate2();
    var inflate = require_inflate2();
    var constants = require_constants();
    var pako = {};
    assign(pako, deflate, inflate, constants);
    module2.exports = pako;
  }
});

// node_modules/pify/index.js
var require_pify = __commonJS({
  "node_modules/pify/index.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    var processFn = (fn, options) => function(...args) {
      const P = options.promiseModule;
      return new P((resolve, reject) => {
        if (options.multiArgs) {
          args.push((...result) => {
            if (options.errorFirst) {
              if (result[0]) {
                reject(result);
              } else {
                result.shift();
                resolve(result);
              }
            } else {
              resolve(result);
            }
          });
        } else if (options.errorFirst) {
          args.push((error, result) => {
            if (error) {
              reject(error);
            } else {
              resolve(result);
            }
          });
        } else {
          args.push(resolve);
        }
        fn.apply(this, args);
      });
    };
    module2.exports = (input, options) => {
      options = Object.assign({
        exclude: [/.+(Sync|Stream)$/],
        errorFirst: true,
        promiseModule: Promise
      }, options);
      const objType = typeof input;
      if (!(input !== null && (objType === "object" || objType === "function"))) {
        throw new TypeError(`Expected \`input\` to be a \`Function\` or \`Object\`, got \`${input === null ? "null" : objType}\``);
      }
      const filter = (key) => {
        const match2 = (pattern) => typeof pattern === "string" ? key === pattern : pattern.test(key);
        return options.include ? options.include.some(match2) : !options.exclude.some(match2);
      };
      let ret;
      if (objType === "function") {
        ret = function(...args) {
          return options.excludeMain ? input(...args) : processFn(input, options).apply(this, args);
        };
      } else {
        ret = Object.create(Object.getPrototypeOf(input));
      }
      for (const key in input) {
        const property = input[key];
        ret[key] = typeof property === "function" && filter(key) ? processFn(property, options) : property;
      }
      return ret;
    };
  }
});

// node_modules/ignore/index.js
var require_ignore = __commonJS({
  "node_modules/ignore/index.js"(exports, module2) {
    init_esbuild_buffer_shim();
    function makeArray(subject) {
      return Array.isArray(subject) ? subject : [subject];
    }
    var EMPTY = "";
    var SPACE = " ";
    var ESCAPE = "\\";
    var REGEX_TEST_BLANK_LINE = /^\s+$/;
    var REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\]|^)\\$/;
    var REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
    var REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/;
    var REGEX_SPLITALL_CRLF = /\r?\n/g;
    var REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/;
    var SLASH = "/";
    var TMP_KEY_IGNORE = "node-ignore";
    if (typeof Symbol !== "undefined") {
      TMP_KEY_IGNORE = Symbol.for("node-ignore");
    }
    var KEY_IGNORE = TMP_KEY_IGNORE;
    var define2 = (object, key, value) => Object.defineProperty(object, key, { value });
    var REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g;
    var RETURN_FALSE = () => false;
    var sanitizeRange = (range) => range.replace(
      REGEX_REGEXP_RANGE,
      (match2, from2, to) => from2.charCodeAt(0) <= to.charCodeAt(0) ? match2 : EMPTY
    );
    var cleanRangeBackSlash = (slashes) => {
      const { length } = slashes;
      return slashes.slice(0, length - length % 2);
    };
    var REPLACERS = [
      [
        // remove BOM
        // TODO:
        // Other similar zero-width characters?
        /^\uFEFF/,
        () => EMPTY
      ],
      // > Trailing spaces are ignored unless they are quoted with backslash ("\")
      [
        // (a\ ) -> (a )
        // (a  ) -> (a)
        // (a ) -> (a)
        // (a \ ) -> (a  )
        /((?:\\\\)*?)(\\?\s+)$/,
        (_, m1, m2) => m1 + (m2.indexOf("\\") === 0 ? SPACE : EMPTY)
      ],
      // replace (\ ) with ' '
      // (\ ) -> ' '
      // (\\ ) -> '\\ '
      // (\\\ ) -> '\\ '
      [
        /(\\+?)\s/g,
        (_, m1) => {
          const { length } = m1;
          return m1.slice(0, length - length % 2) + SPACE;
        }
      ],
      // Escape metacharacters
      // which is written down by users but means special for regular expressions.
      // > There are 12 characters with special meanings:
      // > - the backslash \,
      // > - the caret ^,
      // > - the dollar sign $,
      // > - the period or dot .,
      // > - the vertical bar or pipe symbol |,
      // > - the question mark ?,
      // > - the asterisk or star *,
      // > - the plus sign +,
      // > - the opening parenthesis (,
      // > - the closing parenthesis ),
      // > - and the opening square bracket [,
      // > - the opening curly brace {,
      // > These special characters are often called "metacharacters".
      [
        /[\\$.|*+(){^]/g,
        (match2) => `\\${match2}`
      ],
      [
        // > a question mark (?) matches a single character
        /(?!\\)\?/g,
        () => "[^/]"
      ],
      // leading slash
      [
        // > A leading slash matches the beginning of the pathname.
        // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".
        // A leading slash matches the beginning of the pathname
        /^\//,
        () => "^"
      ],
      // replace special metacharacter slash after the leading slash
      [
        /\//g,
        () => "\\/"
      ],
      [
        // > A leading "**" followed by a slash means match in all directories.
        // > For example, "**/foo" matches file or directory "foo" anywhere,
        // > the same as pattern "foo".
        // > "**/foo/bar" matches file or directory "bar" anywhere that is directly
        // >   under directory "foo".
        // Notice that the '*'s have been replaced as '\\*'
        /^\^*\\\*\\\*\\\//,
        // '**/foo' <-> 'foo'
        () => "^(?:.*\\/)?"
      ],
      // starting
      [
        // there will be no leading '/'
        //   (which has been replaced by section "leading slash")
        // If starts with '**', adding a '^' to the regular expression also works
        /^(?=[^^])/,
        function startingReplacer() {
          return !/\/(?!$)/.test(this) ? "(?:^|\\/)" : "^";
        }
      ],
      // two globstars
      [
        // Use lookahead assertions so that we could match more than one `'/**'`
        /\\\/\\\*\\\*(?=\\\/|$)/g,
        // Zero, one or several directories
        // should not use '*', or it will be replaced by the next replacer
        // Check if it is not the last `'/**'`
        (_, index, str) => index + 6 < str.length ? "(?:\\/[^\\/]+)*" : "\\/.+"
      ],
      // normal intermediate wildcards
      [
        // Never replace escaped '*'
        // ignore rule '\*' will match the path '*'
        // 'abc.*/' -> go
        // 'abc.*'  -> skip this rule,
        //    coz trailing single wildcard will be handed by [trailing wildcard]
        /(^|[^\\]+)(\\\*)+(?=.+)/g,
        // '*.js' matches '.js'
        // '*.js' doesn't match 'abc'
        (_, p1, p2) => {
          const unescaped = p2.replace(/\\\*/g, "[^\\/]*");
          return p1 + unescaped;
        }
      ],
      [
        // unescape, revert step 3 except for back slash
        // For example, if a user escape a '\\*',
        // after step 3, the result will be '\\\\\\*'
        /\\\\\\(?=[$.|*+(){^])/g,
        () => ESCAPE
      ],
      [
        // '\\\\' -> '\\'
        /\\\\/g,
        () => ESCAPE
      ],
      [
        // > The range notation, e.g. [a-zA-Z],
        // > can be used to match one of the characters in a range.
        // `\` is escaped by step 3
        /(\\)?\[([^\]/]*?)(\\*)($|\])/g,
        (match2, leadEscape, range, endEscape, close) => leadEscape === ESCAPE ? `\\[${range}${cleanRangeBackSlash(endEscape)}${close}` : close === "]" ? endEscape.length % 2 === 0 ? `[${sanitizeRange(range)}${endEscape}]` : "[]" : "[]"
      ],
      // ending
      [
        // 'js' will not match 'js.'
        // 'ab' will not match 'abc'
        /(?:[^*])$/,
        // WTF!
        // https://git-scm.com/docs/gitignore
        // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1)
        // which re-fixes #24, #38
        // > If there is a separator at the end of the pattern then the pattern
        // > will only match directories, otherwise the pattern can match both
        // > files and directories.
        // 'js*' will not match 'a.js'
        // 'js/' will not match 'a.js'
        // 'js' will match 'a.js' and 'a.js/'
        (match2) => /\/$/.test(match2) ? `${match2}$` : `${match2}(?=$|\\/$)`
      ],
      // trailing wildcard
      [
        /(\^|\\\/)?\\\*$/,
        (_, p1) => {
          const prefix = p1 ? `${p1}[^/]+` : "[^/]*";
          return `${prefix}(?=$|\\/$)`;
        }
      ]
    ];
    var regexCache = /* @__PURE__ */ Object.create(null);
    var makeRegex = (pattern, ignoreCase) => {
      let source = regexCache[pattern];
      if (!source) {
        source = REPLACERS.reduce(
          (prev, [matcher, replacer]) => prev.replace(matcher, replacer.bind(pattern)),
          pattern
        );
        regexCache[pattern] = source;
      }
      return ignoreCase ? new RegExp(source, "i") : new RegExp(source);
    };
    var isString2 = (subject) => typeof subject === "string";
    var checkPattern = (pattern) => pattern && isString2(pattern) && !REGEX_TEST_BLANK_LINE.test(pattern) && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern) && pattern.indexOf("#") !== 0;
    var splitPattern = (pattern) => pattern.split(REGEX_SPLITALL_CRLF);
    var IgnoreRule = class {
      constructor(origin, pattern, negative, regex) {
        this.origin = origin;
        this.pattern = pattern;
        this.negative = negative;
        this.regex = regex;
      }
    };
    var createRule = (pattern, ignoreCase) => {
      const origin = pattern;
      let negative = false;
      if (pattern.indexOf("!") === 0) {
        negative = true;
        pattern = pattern.substr(1);
      }
      pattern = pattern.replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, "!").replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, "#");
      const regex = makeRegex(pattern, ignoreCase);
      return new IgnoreRule(
        origin,
        pattern,
        negative,
        regex
      );
    };
    var throwError = (message, Ctor) => {
      throw new Ctor(message);
    };
    var checkPath = (path, originalPath, doThrow) => {
      if (!isString2(path)) {
        return doThrow(
          `path must be a string, but got \`${originalPath}\``,
          TypeError
        );
      }
      if (!path) {
        return doThrow(`path must not be empty`, TypeError);
      }
      if (checkPath.isNotRelative(path)) {
        const r = "`path.relative()`d";
        return doThrow(
          `path should be a ${r} string, but got "${originalPath}"`,
          RangeError
        );
      }
      return true;
    };
    var isNotRelative = (path) => REGEX_TEST_INVALID_PATH.test(path);
    checkPath.isNotRelative = isNotRelative;
    checkPath.convert = (p) => p;
    var Ignore = class {
      constructor({
        ignorecase = true,
        ignoreCase = ignorecase,
        allowRelativePaths = false
      } = {}) {
        define2(this, KEY_IGNORE, true);
        this._rules = [];
        this._ignoreCase = ignoreCase;
        this._allowRelativePaths = allowRelativePaths;
        this._initCache();
      }
      _initCache() {
        this._ignoreCache = /* @__PURE__ */ Object.create(null);
        this._testCache = /* @__PURE__ */ Object.create(null);
      }
      _addPattern(pattern) {
        if (pattern && pattern[KEY_IGNORE]) {
          this._rules = this._rules.concat(pattern._rules);
          this._added = true;
          return;
        }
        if (checkPattern(pattern)) {
          const rule = createRule(pattern, this._ignoreCase);
          this._added = true;
          this._rules.push(rule);
        }
      }
      // @param {Array<string> | string | Ignore} pattern
      add(pattern) {
        this._added = false;
        makeArray(
          isString2(pattern) ? splitPattern(pattern) : pattern
        ).forEach(this._addPattern, this);
        if (this._added) {
          this._initCache();
        }
        return this;
      }
      // legacy
      addPattern(pattern) {
        return this.add(pattern);
      }
      //          |           ignored : unignored
      // negative |   0:0   |   0:1   |   1:0   |   1:1
      // -------- | ------- | ------- | ------- | --------
      //     0    |  TEST   |  TEST   |  SKIP   |    X
      //     1    |  TESTIF |  SKIP   |  TEST   |    X
      // - SKIP: always skip
      // - TEST: always test
      // - TESTIF: only test if checkUnignored
      // - X: that never happen
      // @param {boolean} whether should check if the path is unignored,
      //   setting `checkUnignored` to `false` could reduce additional
      //   path matching.
      // @returns {TestResult} true if a file is ignored
      _testOne(path, checkUnignored) {
        let ignored = false;
        let unignored = false;
        this._rules.forEach((rule) => {
          const { negative } = rule;
          if (unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored) {
            return;
          }
          const matched = rule.regex.test(path);
          if (matched) {
            ignored = !negative;
            unignored = negative;
          }
        });
        return {
          ignored,
          unignored
        };
      }
      // @returns {TestResult}
      _test(originalPath, cache, checkUnignored, slices) {
        const path = originalPath && checkPath.convert(originalPath);
        checkPath(
          path,
          originalPath,
          this._allowRelativePaths ? RETURN_FALSE : throwError
        );
        return this._t(path, cache, checkUnignored, slices);
      }
      _t(path, cache, checkUnignored, slices) {
        if (path in cache) {
          return cache[path];
        }
        if (!slices) {
          slices = path.split(SLASH);
        }
        slices.pop();
        if (!slices.length) {
          return cache[path] = this._testOne(path, checkUnignored);
        }
        const parent = this._t(
          slices.join(SLASH) + SLASH,
          cache,
          checkUnignored,
          slices
        );
        return cache[path] = parent.ignored ? parent : this._testOne(path, checkUnignored);
      }
      ignores(path) {
        return this._test(path, this._ignoreCache, false).ignored;
      }
      createFilter() {
        return (path) => !this.ignores(path);
      }
      filter(paths) {
        return makeArray(paths).filter(this.createFilter());
      }
      // @returns {TestResult}
      test(path) {
        return this._test(path, this._testCache, true);
      }
    };
    var factory = (options) => new Ignore(options);
    var isPathValid = (path) => checkPath(path && checkPath.convert(path), path, RETURN_FALSE);
    factory.isPathValid = isPathValid;
    factory.default = factory;
    module2.exports = factory;
    if (
      // Detect `process` so that it can run in browsers.
      typeof process !== "undefined" && (process.env && process.env.IGNORE_TEST_WIN32 || process.platform === "win32")
    ) {
      const makePosix = (str) => /^\\\\\?\\/.test(str) || /["<>|\u0000-\u001F]+/u.test(str) ? str : str.replace(/\\/g, "/");
      checkPath.convert = makePosix;
      const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i;
      checkPath.isNotRelative = (path) => REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path) || isNotRelative(path);
    }
  }
});

// node_modules/clean-git-ref/lib/index.js
var require_lib3 = __commonJS({
  "node_modules/clean-git-ref/lib/index.js"(exports, module2) {
    "use strict";
    init_esbuild_buffer_shim();
    function escapeRegExp2(string) {
      return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
    }
    function replaceAll(str, search, replacement) {
      search = search instanceof RegExp ? search : new RegExp(escapeRegExp2(search), "g");
      return str.replace(search, replacement);
    }
    var CleanGitRef = {
      clean: function clean(value) {
        if (typeof value !== "string") {
          throw new Error("Expected a string, received: " + value);
        }
        value = replaceAll(value, "./", "/");
        value = replaceAll(value, "..", ".");
        value = replaceAll(value, " ", "-");
        value = replaceAll(value, /^[~^:?*\\\-]/g, "");
        value = replaceAll(value, /[~^:?*\\]/g, "-");
        value = replaceAll(value, /[~^:?*\\\-]$/g, "");
        value = replaceAll(value, "@{", "-");
        value = replaceAll(value, /\.$/g, "");
        value = replaceAll(value, /\/$/g, "");
        value = replaceAll(value, /\.lock$/g, "");
        return value;
      }
    };
    module2.exports = CleanGitRef;
  }
});

// node_modules/diff3/onp.js
var require_onp = __commonJS({
  "node_modules/diff3/onp.js"(exports, module2) {
    init_esbuild_buffer_shim();
    module2.exports = function(a_, b_) {
      var a = a_, b = b_, m = a.length, n2 = b.length, reverse = false, ed = null, offset2 = m + 1, path = [], pathposi = [], ses = [], lcs = "", SES_DELETE = -1, SES_COMMON = 0, SES_ADD = 1;
      var tmp1, tmp2;
      var init3 = function() {
        if (m >= n2) {
          tmp1 = a;
          tmp2 = m;
          a = b;
          b = tmp1;
          m = n2;
          n2 = tmp2;
          reverse = true;
          offset2 = m + 1;
        }
      };
      var P = function(x, y, k) {
        return {
          "x": x,
          "y": y,
          "k": k
        };
      };
      var seselem = function(elem, t) {
        return {
          "elem": elem,
          "t": t
        };
      };
      var snake = function(k, p, pp) {
        var r, x, y;
        if (p > pp) {
          r = path[k - 1 + offset2];
        } else {
          r = path[k + 1 + offset2];
        }
        y = Math.max(p, pp);
        x = y - k;
        while (x < m && y < n2 && a[x] === b[y]) {
          ++x;
          ++y;
        }
        path[k + offset2] = pathposi.length;
        pathposi[pathposi.length] = new P(x, y, r);
        return y;
      };
      var recordseq = function(epc) {
        var x_idx, y_idx, px_idx, py_idx, i;
        x_idx = y_idx = 1;
        px_idx = py_idx = 0;
        for (i = epc.length - 1; i >= 0; --i) {
          while (px_idx < epc[i].x || py_idx < epc[i].y) {
            if (epc[i].y - epc[i].x > py_idx - px_idx) {
              if (reverse) {
                ses[ses.length] = new seselem(b[py_idx], SES_DELETE);
              } else {
                ses[ses.length] = new seselem(b[py_idx], SES_ADD);
              }
              ++y_idx;
              ++py_idx;
            } else if (epc[i].y - epc[i].x < py_idx - px_idx) {
              if (reverse) {
                ses[ses.length] = new seselem(a[px_idx], SES_ADD);
              } else {
                ses[ses.length] = new seselem(a[px_idx], SES_DELETE);
              }
              ++x_idx;
              ++px_idx;
            } else {
              ses[ses.length] = new seselem(a[px_idx], SES_COMMON);
              lcs += a[px_idx];
              ++x_idx;
              ++y_idx;
              ++px_idx;
              ++py_idx;
            }
          }
        }
      };
      init3();
      return {
        SES_DELETE: -1,
        SES_COMMON: 0,
        SES_ADD: 1,
        editdistance: function() {
          return ed;
        },
        getlcs: function() {
          return lcs;
        },
        getses: function() {
          return ses;
        },
        compose: function() {
          var delta, size, fp, p, r, epc, i, k;
          delta = n2 - m;
          size = m + n2 + 3;
          fp = {};
          for (i = 0; i < size; ++i) {
            fp[i] = -1;
            path[i] = -1;
          }
          p = -1;
          do {
            ++p;
            for (k = -p; k <= delta - 1; ++k) {
              fp[k + offset2] = snake(k, fp[k - 1 + offset2] + 1, fp[k + 1 + offset2]);
            }
            for (k = delta + p; k >= delta + 1; --k) {
              fp[k + offset2] = snake(k, fp[k - 1 + offset2] + 1, fp[k + 1 + offset2]);
            }
            fp[delta + offset2] = snake(delta, fp[delta - 1 + offset2] + 1, fp[delta + 1 + offset2]);
          } while (fp[delta + offset2] !== n2);
          ed = delta + 2 * p;
          r = path[delta + offset2];
          epc = [];
          while (r !== -1) {
            epc[epc.length] = new P(pathposi[r].x, pathposi[r].y, null);
            r = pathposi[r].k;
          }
          recordseq(epc);
        }
      };
    };
  }
});

// node_modules/diff3/diff3.js
var require_diff3 = __commonJS({
  "node_modules/diff3/diff3.js"(exports, module2) {
    init_esbuild_buffer_shim();
    var onp = require_onp();
    function longestCommonSubsequence(file1, file2) {
      var diff = new onp(file1, file2);
      diff.compose();
      var ses = diff.getses();
      var root;
      var prev;
      var file1RevIdx = file1.length - 1, file2RevIdx = file2.length - 1;
      for (var i = ses.length - 1; i >= 0; --i) {
        if (ses[i].t === diff.SES_COMMON) {
          if (prev) {
            prev.chain = {
              file1index: file1RevIdx,
              file2index: file2RevIdx,
              chain: null
            };
            prev = prev.chain;
          } else {
            root = {
              file1index: file1RevIdx,
              file2index: file2RevIdx,
              chain: null
            };
            prev = root;
          }
          file1RevIdx--;
          file2RevIdx--;
        } else if (ses[i].t === diff.SES_DELETE) {
          file1RevIdx--;
        } else if (ses[i].t === diff.SES_ADD) {
          file2RevIdx--;
        }
      }
      var tail = {
        file1index: -1,
        file2index: -1,
        chain: null
      };
      if (!prev) {
        return tail;
      }
      prev.chain = tail;
      return root;
    }
    function diffIndices(file1, file2) {
      var result = [];
      var tail1 = file1.length;
      var tail2 = file2.length;
      for (var candidate = longestCommonSubsequence(file1, file2); candidate !== null; candidate = candidate.chain) {
        var mismatchLength1 = tail1 - candidate.file1index - 1;
        var mismatchLength2 = tail2 - candidate.file2index - 1;
        tail1 = candidate.file1index;
        tail2 = candidate.file2index;
        if (mismatchLength1 || mismatchLength2) {
          result.push({
            file1: [tail1 + 1, mismatchLength1],
            file2: [tail2 + 1, mismatchLength2]
          });
        }
      }
      result.reverse();
      return result;
    }
    function diff3MergeIndices(a, o, b) {
      var i;
      var m1 = diffIndices(o, a);
      var m2 = diffIndices(o, b);
      var hunks = [];
      function addHunk(h, side2) {
        hunks.push([h.file1[0], side2, h.file1[1], h.file2[0], h.file2[1]]);
      }
      for (i = 0; i < m1.length; i++) {
        addHunk(m1[i], 0);
      }
      for (i = 0; i < m2.length; i++) {
        addHunk(m2[i], 2);
      }
      hunks.sort(function(x, y) {
        return x[0] - y[0];
      });
      var result = [];
      var commonOffset = 0;
      function copyCommon(targetOffset) {
        if (targetOffset > commonOffset) {
          result.push([1, commonOffset, targetOffset - commonOffset]);
          commonOffset = targetOffset;
        }
      }
      for (var hunkIndex = 0; hunkIndex < hunks.length; hunkIndex++) {
        var firstHunkIndex = hunkIndex;
        var hunk = hunks[hunkIndex];
        var regionLhs = hunk[0];
        var regionRhs = regionLhs + hunk[2];
        while (hunkIndex < hunks.length - 1) {
          var maybeOverlapping = hunks[hunkIndex + 1];
          var maybeLhs = maybeOverlapping[0];
          if (maybeLhs > regionRhs) break;
          regionRhs = Math.max(regionRhs, maybeLhs + maybeOverlapping[2]);
          hunkIndex++;
        }
        copyCommon(regionLhs);
        if (firstHunkIndex == hunkIndex) {
          if (hunk[4] > 0) {
            result.push([hunk[1], hunk[3], hunk[4]]);
          }
        } else {
          var regions = {
            0: [a.length, -1, o.length, -1],
            2: [b.length, -1, o.length, -1]
          };
          for (i = firstHunkIndex; i <= hunkIndex; i++) {
            hunk = hunks[i];
            var side = hunk[1];
            var r = regions[side];
            var oLhs = hunk[0];
            var oRhs = oLhs + hunk[2];
            var abLhs = hunk[3];
            var abRhs = abLhs + hunk[4];
            r[0] = Math.min(abLhs, r[0]);
            r[1] = Math.max(abRhs, r[1]);
            r[2] = Math.min(oLhs, r[2]);
            r[3] = Math.max(oRhs, r[3]);
          }
          var aLhs = regions[0][0] + (regionLhs - regions[0][2]);
          var aRhs = regions[0][1] + (regionRhs - regions[0][3]);
          var bLhs = regions[2][0] + (regionLhs - regions[2][2]);
          var bRhs = regions[2][1] + (regionRhs - regions[2][3]);
          result.push([
            -1,
            aLhs,
            aRhs - aLhs,
            regionLhs,
            regionRhs - regionLhs,
            bLhs,
            bRhs - bLhs
          ]);
        }
        commonOffset = regionRhs;
      }
      copyCommon(o.length);
      return result;
    }
    function diff3Merge(a, o, b) {
      var result = [];
      var files = [a, o, b];
      var indices = diff3MergeIndices(a, o, b);
      var okLines = [];
      function flushOk() {
        if (okLines.length) {
          result.push({
            ok: okLines
          });
        }
        okLines = [];
      }
      function pushOk(xs) {
        for (var j = 0; j < xs.length; j++) {
          okLines.push(xs[j]);
        }
      }
      function isTrueConflict(rec) {
        if (rec[2] != rec[6]) return true;
        var aoff = rec[1];
        var boff = rec[5];
        for (var j = 0; j < rec[2]; j++) {
          if (a[j + aoff] != b[j + boff]) return true;
        }
        return false;
      }
      for (var i = 0; i < indices.length; i++) {
        var x = indices[i];
        var side = x[0];
        if (side == -1) {
          if (!isTrueConflict(x)) {
            pushOk(files[0].slice(x[1], x[1] + x[2]));
          } else {
            flushOk();
            result.push({
              conflict: {
                a: a.slice(x[1], x[1] + x[2]),
                aIndex: x[1],
                o: o.slice(x[3], x[3] + x[4]),
                oIndex: x[3],
                b: b.slice(x[5], x[5] + x[6]),
                bIndex: x[5]
              }
            });
          }
        } else {
          pushOk(files[side].slice(x[1], x[1] + x[2]));
        }
      }
      flushOk();
      return result;
    }
    module2.exports = diff3Merge;
  }
});

// node_modules/isomorphic-git/index.cjs
var require_isomorphic_git = __commonJS({
  "node_modules/isomorphic-git/index.cjs"(exports) {
    "use strict";
    init_esbuild_buffer_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    function _interopDefault(ex) {
      return ex && typeof ex === "object" && "default" in ex ? ex["default"] : ex;
    }
    var AsyncLock = _interopDefault(require_async_lock());
    var Hash = _interopDefault(require_sha12());
    var crc32 = _interopDefault(require_crc32());
    var pako = _interopDefault(require_pako());
    var pify = _interopDefault(require_pify());
    var ignore = _interopDefault(require_ignore());
    var cleanGitRef = _interopDefault(require_lib3());
    var diff3Merge = _interopDefault(require_diff3());
    var BaseError = class _BaseError extends Error {
      constructor(message) {
        super(message);
        this.caller = "";
      }
      toJSON() {
        return {
          code: this.code,
          data: this.data,
          caller: this.caller,
          message: this.message,
          stack: this.stack
        };
      }
      fromJSON(json) {
        const e = new _BaseError(json.message);
        e.code = json.code;
        e.data = json.data;
        e.caller = json.caller;
        e.stack = json.stack;
        return e;
      }
      get isIsomorphicGitError() {
        return true;
      }
    };
    var UnmergedPathsError = class _UnmergedPathsError extends BaseError {
      /**
       * @param {Array<string>} filepaths
       */
      constructor(filepaths) {
        super(
          `Modifying the index is not possible because you have unmerged files: ${filepaths.toString}. Fix them up in the work tree, and then use 'git add/rm as appropriate to mark resolution and make a commit.`
        );
        this.code = this.name = _UnmergedPathsError.code;
        this.data = { filepaths };
      }
    };
    UnmergedPathsError.code = "UnmergedPathsError";
    var InternalError = class _InternalError extends BaseError {
      /**
       * @param {string} message
       */
      constructor(message) {
        super(
          `An internal error caused this command to fail.

If you're not a developer, report the bug to the developers of the application you're using. If this is a bug in isomorphic-git then you should create a proper bug yourselves. The bug should include a minimal reproduction and details about the version and environment.

Please file a bug report at https://github.com/isomorphic-git/isomorphic-git/issues with this error message: ${message}`
        );
        this.code = this.name = _InternalError.code;
        this.data = { message };
      }
    };
    InternalError.code = "InternalError";
    var UnsafeFilepathError = class _UnsafeFilepathError extends BaseError {
      /**
       * @param {string} filepath
       */
      constructor(filepath) {
        super(`The filepath "${filepath}" contains unsafe character sequences`);
        this.code = this.name = _UnsafeFilepathError.code;
        this.data = { filepath };
      }
    };
    UnsafeFilepathError.code = "UnsafeFilepathError";
    var BufferCursor = class {
      constructor(buffer) {
        this.buffer = buffer;
        this._start = 0;
      }
      eof() {
        return this._start >= this.buffer.length;
      }
      tell() {
        return this._start;
      }
      seek(n2) {
        this._start = n2;
      }
      slice(n2) {
        const r = this.buffer.slice(this._start, this._start + n2);
        this._start += n2;
        return r;
      }
      toString(enc, length) {
        const r = this.buffer.toString(enc, this._start, this._start + length);
        this._start += length;
        return r;
      }
      write(value, length, enc) {
        const r = this.buffer.write(value, this._start, length, enc);
        this._start += length;
        return r;
      }
      copy(source, start, end) {
        const r = source.copy(this.buffer, this._start, start, end);
        this._start += r;
        return r;
      }
      readUInt8() {
        const r = this.buffer.readUInt8(this._start);
        this._start += 1;
        return r;
      }
      writeUInt8(value) {
        const r = this.buffer.writeUInt8(value, this._start);
        this._start += 1;
        return r;
      }
      readUInt16BE() {
        const r = this.buffer.readUInt16BE(this._start);
        this._start += 2;
        return r;
      }
      writeUInt16BE(value) {
        const r = this.buffer.writeUInt16BE(value, this._start);
        this._start += 2;
        return r;
      }
      readUInt32BE() {
        const r = this.buffer.readUInt32BE(this._start);
        this._start += 4;
        return r;
      }
      writeUInt32BE(value) {
        const r = this.buffer.writeUInt32BE(value, this._start);
        this._start += 4;
        return r;
      }
    };
    function compareStrings(a, b) {
      return -(a < b) || +(a > b);
    }
    function comparePath(a, b) {
      return compareStrings(a.path, b.path);
    }
    function normalizeMode(mode) {
      let type = mode > 0 ? mode >> 12 : 0;
      if (type !== 4 && type !== 8 && type !== 10 && type !== 14) {
        type = 8;
      }
      let permissions = mode & 511;
      if (permissions & 73) {
        permissions = 493;
      } else {
        permissions = 420;
      }
      if (type !== 8) permissions = 0;
      return (type << 12) + permissions;
    }
    var MAX_UINT32 = 2 ** 32;
    function SecondsNanoseconds(givenSeconds, givenNanoseconds, milliseconds, date) {
      if (givenSeconds !== void 0 && givenNanoseconds !== void 0) {
        return [givenSeconds, givenNanoseconds];
      }
      if (milliseconds === void 0) {
        milliseconds = date.valueOf();
      }
      const seconds = Math.floor(milliseconds / 1e3);
      const nanoseconds = (milliseconds - seconds * 1e3) * 1e6;
      return [seconds, nanoseconds];
    }
    function normalizeStats(e) {
      const [ctimeSeconds, ctimeNanoseconds] = SecondsNanoseconds(
        e.ctimeSeconds,
        e.ctimeNanoseconds,
        e.ctimeMs,
        e.ctime
      );
      const [mtimeSeconds, mtimeNanoseconds] = SecondsNanoseconds(
        e.mtimeSeconds,
        e.mtimeNanoseconds,
        e.mtimeMs,
        e.mtime
      );
      return {
        ctimeSeconds: ctimeSeconds % MAX_UINT32,
        ctimeNanoseconds: ctimeNanoseconds % MAX_UINT32,
        mtimeSeconds: mtimeSeconds % MAX_UINT32,
        mtimeNanoseconds: mtimeNanoseconds % MAX_UINT32,
        dev: e.dev % MAX_UINT32,
        ino: e.ino % MAX_UINT32,
        mode: normalizeMode(e.mode % MAX_UINT32),
        uid: e.uid % MAX_UINT32,
        gid: e.gid % MAX_UINT32,
        // size of -1 happens over a BrowserFS HTTP Backend that doesn't serve Content-Length headers
        // (like the Karma webserver) because BrowserFS HTTP Backend uses HTTP HEAD requests to do fs.stat
        size: e.size > -1 ? e.size % MAX_UINT32 : 0
      };
    }
    function toHex2(buffer) {
      let hex = "";
      for (const byte of new Uint8Array(buffer)) {
        if (byte < 16) hex += "0";
        hex += byte.toString(16);
      }
      return hex;
    }
    var supportsSubtleSHA1 = null;
    async function shasum(buffer) {
      if (supportsSubtleSHA1 === null) {
        supportsSubtleSHA1 = await testSubtleSHA1();
      }
      return supportsSubtleSHA1 ? subtleSHA1(buffer) : shasumSync(buffer);
    }
    function shasumSync(buffer) {
      return new Hash().update(buffer).digest("hex");
    }
    async function subtleSHA1(buffer) {
      const hash = await crypto.subtle.digest("SHA-1", buffer);
      return toHex2(hash);
    }
    async function testSubtleSHA1() {
      try {
        const hash = await subtleSHA1(new Uint8Array([]));
        return hash === "da39a3ee5e6b4b0d3255bfef95601890afd80709";
      } catch (_) {
      }
      return false;
    }
    function parseCacheEntryFlags(bits) {
      return {
        assumeValid: Boolean(bits & 32768),
        extended: Boolean(bits & 16384),
        stage: (bits & 12288) >> 12,
        nameLength: bits & 4095
      };
    }
    function renderCacheEntryFlags(entry) {
      const flags = entry.flags;
      flags.extended = false;
      flags.nameLength = Math.min(Buffer.from(entry.path).length, 4095);
      return (flags.assumeValid ? 32768 : 0) + (flags.extended ? 16384 : 0) + ((flags.stage & 3) << 12) + (flags.nameLength & 4095);
    }
    var GitIndex = class _GitIndex {
      /*::
       _entries: Map<string, CacheEntry>
       _dirty: boolean // Used to determine if index needs to be saved to filesystem
       */
      constructor(entries, unmergedPaths) {
        this._dirty = false;
        this._unmergedPaths = unmergedPaths || /* @__PURE__ */ new Set();
        this._entries = entries || /* @__PURE__ */ new Map();
      }
      _addEntry(entry) {
        if (entry.flags.stage === 0) {
          entry.stages = [entry];
          this._entries.set(entry.path, entry);
          this._unmergedPaths.delete(entry.path);
        } else {
          let existingEntry = this._entries.get(entry.path);
          if (!existingEntry) {
            this._entries.set(entry.path, entry);
            existingEntry = entry;
          }
          existingEntry.stages[entry.flags.stage] = entry;
          this._unmergedPaths.add(entry.path);
        }
      }
      static async from(buffer) {
        if (Buffer.isBuffer(buffer)) {
          return _GitIndex.fromBuffer(buffer);
        } else if (buffer === null) {
          return new _GitIndex(null);
        } else {
          throw new InternalError("invalid type passed to GitIndex.from");
        }
      }
      static async fromBuffer(buffer) {
        if (buffer.length === 0) {
          throw new InternalError("Index file is empty (.git/index)");
        }
        const index2 = new _GitIndex();
        const reader = new BufferCursor(buffer);
        const magic = reader.toString("utf8", 4);
        if (magic !== "DIRC") {
          throw new InternalError(`Invalid dircache magic file number: ${magic}`);
        }
        const shaComputed = await shasum(buffer.slice(0, -20));
        const shaClaimed = buffer.slice(-20).toString("hex");
        if (shaClaimed !== shaComputed) {
          throw new InternalError(
            `Invalid checksum in GitIndex buffer: expected ${shaClaimed} but saw ${shaComputed}`
          );
        }
        const version3 = reader.readUInt32BE();
        if (version3 !== 2) {
          throw new InternalError(`Unsupported dircache version: ${version3}`);
        }
        const numEntries = reader.readUInt32BE();
        let i = 0;
        while (!reader.eof() && i < numEntries) {
          const entry = {};
          entry.ctimeSeconds = reader.readUInt32BE();
          entry.ctimeNanoseconds = reader.readUInt32BE();
          entry.mtimeSeconds = reader.readUInt32BE();
          entry.mtimeNanoseconds = reader.readUInt32BE();
          entry.dev = reader.readUInt32BE();
          entry.ino = reader.readUInt32BE();
          entry.mode = reader.readUInt32BE();
          entry.uid = reader.readUInt32BE();
          entry.gid = reader.readUInt32BE();
          entry.size = reader.readUInt32BE();
          entry.oid = reader.slice(20).toString("hex");
          const flags = reader.readUInt16BE();
          entry.flags = parseCacheEntryFlags(flags);
          const pathlength = buffer.indexOf(0, reader.tell() + 1) - reader.tell();
          if (pathlength < 1) {
            throw new InternalError(`Got a path length of: ${pathlength}`);
          }
          entry.path = reader.toString("utf8", pathlength);
          if (entry.path.includes("..\\") || entry.path.includes("../")) {
            throw new UnsafeFilepathError(entry.path);
          }
          let padding = 8 - (reader.tell() - 12) % 8;
          if (padding === 0) padding = 8;
          while (padding--) {
            const tmp = reader.readUInt8();
            if (tmp !== 0) {
              throw new InternalError(
                `Expected 1-8 null characters but got '${tmp}' after ${entry.path}`
              );
            } else if (reader.eof()) {
              throw new InternalError("Unexpected end of file");
            }
          }
          entry.stages = [];
          index2._addEntry(entry);
          i++;
        }
        return index2;
      }
      get unmergedPaths() {
        return [...this._unmergedPaths];
      }
      get entries() {
        return [...this._entries.values()].sort(comparePath);
      }
      get entriesMap() {
        return this._entries;
      }
      get entriesFlat() {
        return [...this.entries].flatMap((entry) => {
          return entry.stages.length > 1 ? entry.stages.filter((x) => x) : entry;
        });
      }
      *[Symbol.iterator]() {
        for (const entry of this.entries) {
          yield entry;
        }
      }
      insert({ filepath, stats, oid, stage = 0 }) {
        if (!stats) {
          stats = {
            ctimeSeconds: 0,
            ctimeNanoseconds: 0,
            mtimeSeconds: 0,
            mtimeNanoseconds: 0,
            dev: 0,
            ino: 0,
            mode: 0,
            uid: 0,
            gid: 0,
            size: 0
          };
        }
        stats = normalizeStats(stats);
        const bfilepath = Buffer.from(filepath);
        const entry = {
          ctimeSeconds: stats.ctimeSeconds,
          ctimeNanoseconds: stats.ctimeNanoseconds,
          mtimeSeconds: stats.mtimeSeconds,
          mtimeNanoseconds: stats.mtimeNanoseconds,
          dev: stats.dev,
          ino: stats.ino,
          // We provide a fallback value for `mode` here because not all fs
          // implementations assign it, but we use it in GitTree.
          // '100644' is for a "regular non-executable file"
          mode: stats.mode || 33188,
          uid: stats.uid,
          gid: stats.gid,
          size: stats.size,
          path: filepath,
          oid,
          flags: {
            assumeValid: false,
            extended: false,
            stage,
            nameLength: bfilepath.length < 4095 ? bfilepath.length : 4095
          },
          stages: []
        };
        this._addEntry(entry);
        this._dirty = true;
      }
      delete({ filepath }) {
        if (this._entries.has(filepath)) {
          this._entries.delete(filepath);
        } else {
          for (const key of this._entries.keys()) {
            if (key.startsWith(filepath + "/")) {
              this._entries.delete(key);
            }
          }
        }
        if (this._unmergedPaths.has(filepath)) {
          this._unmergedPaths.delete(filepath);
        }
        this._dirty = true;
      }
      clear() {
        this._entries.clear();
        this._dirty = true;
      }
      has({ filepath }) {
        return this._entries.has(filepath);
      }
      render() {
        return this.entries.map((entry) => `${entry.mode.toString(8)} ${entry.oid}    ${entry.path}`).join("\n");
      }
      static async _entryToBuffer(entry) {
        const bpath = Buffer.from(entry.path);
        const length = Math.ceil((62 + bpath.length + 1) / 8) * 8;
        const written = Buffer.alloc(length);
        const writer = new BufferCursor(written);
        const stat = normalizeStats(entry);
        writer.writeUInt32BE(stat.ctimeSeconds);
        writer.writeUInt32BE(stat.ctimeNanoseconds);
        writer.writeUInt32BE(stat.mtimeSeconds);
        writer.writeUInt32BE(stat.mtimeNanoseconds);
        writer.writeUInt32BE(stat.dev);
        writer.writeUInt32BE(stat.ino);
        writer.writeUInt32BE(stat.mode);
        writer.writeUInt32BE(stat.uid);
        writer.writeUInt32BE(stat.gid);
        writer.writeUInt32BE(stat.size);
        writer.write(entry.oid, 20, "hex");
        writer.writeUInt16BE(renderCacheEntryFlags(entry));
        writer.write(entry.path, bpath.length, "utf8");
        return written;
      }
      async toObject() {
        const header = Buffer.alloc(12);
        const writer = new BufferCursor(header);
        writer.write("DIRC", 4, "utf8");
        writer.writeUInt32BE(2);
        writer.writeUInt32BE(this.entriesFlat.length);
        let entryBuffers = [];
        for (const entry of this.entries) {
          entryBuffers.push(_GitIndex._entryToBuffer(entry));
          if (entry.stages.length > 1) {
            for (const stage of entry.stages) {
              if (stage && stage !== entry) {
                entryBuffers.push(_GitIndex._entryToBuffer(stage));
              }
            }
          }
        }
        entryBuffers = await Promise.all(entryBuffers);
        const body = Buffer.concat(entryBuffers);
        const main = Buffer.concat([header, body]);
        const sum = await shasum(main);
        return Buffer.concat([main, Buffer.from(sum, "hex")]);
      }
    };
    function compareStats(entry, stats, filemode = true, trustino = true) {
      const e = normalizeStats(entry);
      const s2 = normalizeStats(stats);
      const staleness = filemode && e.mode !== s2.mode || e.mtimeSeconds !== s2.mtimeSeconds || e.ctimeSeconds !== s2.ctimeSeconds || e.uid !== s2.uid || e.gid !== s2.gid || trustino && e.ino !== s2.ino || e.size !== s2.size;
      return staleness;
    }
    var lock = null;
    var IndexCache = Symbol("IndexCache");
    function createCache() {
      return {
        map: /* @__PURE__ */ new Map(),
        stats: /* @__PURE__ */ new Map()
      };
    }
    async function updateCachedIndexFile(fs2, filepath, cache) {
      const [stat, rawIndexFile] = await Promise.all([
        fs2.lstat(filepath),
        fs2.read(filepath)
      ]);
      const index2 = await GitIndex.from(rawIndexFile);
      cache.map.set(filepath, index2);
      cache.stats.set(filepath, stat);
    }
    async function isIndexStale(fs2, filepath, cache) {
      const savedStats = cache.stats.get(filepath);
      if (savedStats === void 0) return true;
      if (savedStats === null) return false;
      const currStats = await fs2.lstat(filepath);
      if (currStats === null) return false;
      return compareStats(savedStats, currStats);
    }
    var GitIndexManager = class {
      /**
       * Manages access to the Git index file, ensuring thread-safe operations and caching.
       *
       * @param {object} opts - Options for acquiring the Git index.
       * @param {FSClient} opts.fs - A file system implementation.
       * @param {string} opts.gitdir - The path to the `.git` directory.
       * @param {object} opts.cache - A shared cache object for storing index data.
       * @param {boolean} [opts.allowUnmerged=true] - Whether to allow unmerged paths in the index.
       * @param {function(GitIndex): any} closure - A function to execute with the Git index.
       * @returns {Promise<any>} The result of the closure function.
       * @throws {UnmergedPathsError} If unmerged paths exist and `allowUnmerged` is `false`.
       */
      static async acquire({ fs: fs2, gitdir, cache, allowUnmerged = true }, closure) {
        if (!cache[IndexCache]) {
          cache[IndexCache] = createCache();
        }
        const filepath = `${gitdir}/index`;
        if (lock === null) lock = new AsyncLock({ maxPending: Infinity });
        let result;
        let unmergedPaths = [];
        await lock.acquire(filepath, async () => {
          const theIndexCache = cache[IndexCache];
          if (await isIndexStale(fs2, filepath, theIndexCache)) {
            await updateCachedIndexFile(fs2, filepath, theIndexCache);
          }
          const index2 = theIndexCache.map.get(filepath);
          unmergedPaths = index2.unmergedPaths;
          if (unmergedPaths.length && !allowUnmerged)
            throw new UnmergedPathsError(unmergedPaths);
          result = await closure(index2);
          if (index2._dirty) {
            const buffer = await index2.toObject();
            await fs2.write(filepath, buffer);
            theIndexCache.stats.set(filepath, await fs2.lstat(filepath));
            index2._dirty = false;
          }
        });
        return result;
      }
    };
    function basename(path) {
      const last = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
      if (last > -1) {
        path = path.slice(last + 1);
      }
      return path;
    }
    function dirname(path) {
      const last = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
      if (last === -1) return ".";
      if (last === 0) return "/";
      return path.slice(0, last);
    }
    function flatFileListToDirectoryStructure(files) {
      const inodes = /* @__PURE__ */ new Map();
      const mkdir = function(name) {
        if (!inodes.has(name)) {
          const dir = {
            type: "tree",
            fullpath: name,
            basename: basename(name),
            metadata: {},
            children: []
          };
          inodes.set(name, dir);
          dir.parent = mkdir(dirname(name));
          if (dir.parent && dir.parent !== dir) dir.parent.children.push(dir);
        }
        return inodes.get(name);
      };
      const mkfile = function(name, metadata) {
        if (!inodes.has(name)) {
          const file = {
            type: "blob",
            fullpath: name,
            basename: basename(name),
            metadata,
            // This recursively generates any missing parent folders.
            parent: mkdir(dirname(name)),
            children: []
          };
          if (file.parent) file.parent.children.push(file);
          inodes.set(name, file);
        }
        return inodes.get(name);
      };
      mkdir(".");
      for (const file of files) {
        mkfile(file.path, file);
      }
      return inodes;
    }
    function mode2type(mode) {
      switch (mode) {
        case 16384:
          return "tree";
        case 33188:
          return "blob";
        case 33261:
          return "blob";
        case 40960:
          return "blob";
        case 57344:
          return "commit";
      }
      throw new InternalError(`Unexpected GitTree entry mode: ${mode.toString(8)}`);
    }
    var GitWalkerIndex = class {
      constructor({ fs: fs2, gitdir, cache }) {
        this.treePromise = GitIndexManager.acquire(
          { fs: fs2, gitdir, cache },
          async function(index2) {
            return flatFileListToDirectoryStructure(index2.entries);
          }
        );
        const walker = this;
        this.ConstructEntry = class StageEntry {
          constructor(fullpath) {
            this._fullpath = fullpath;
            this._type = false;
            this._mode = false;
            this._stat = false;
            this._oid = false;
          }
          async type() {
            return walker.type(this);
          }
          async mode() {
            return walker.mode(this);
          }
          async stat() {
            return walker.stat(this);
          }
          async content() {
            return walker.content(this);
          }
          async oid() {
            return walker.oid(this);
          }
        };
      }
      async readdir(entry) {
        const filepath = entry._fullpath;
        const tree = await this.treePromise;
        const inode = tree.get(filepath);
        if (!inode) return null;
        if (inode.type === "blob") return null;
        if (inode.type !== "tree") {
          throw new Error(`ENOTDIR: not a directory, scandir '${filepath}'`);
        }
        const names = inode.children.map((inode2) => inode2.fullpath);
        names.sort(compareStrings);
        return names;
      }
      async type(entry) {
        if (entry._type === false) {
          await entry.stat();
        }
        return entry._type;
      }
      async mode(entry) {
        if (entry._mode === false) {
          await entry.stat();
        }
        return entry._mode;
      }
      async stat(entry) {
        if (entry._stat === false) {
          const tree = await this.treePromise;
          const inode = tree.get(entry._fullpath);
          if (!inode) {
            throw new Error(
              `ENOENT: no such file or directory, lstat '${entry._fullpath}'`
            );
          }
          const stats = inode.type === "tree" ? {} : normalizeStats(inode.metadata);
          entry._type = inode.type === "tree" ? "tree" : mode2type(stats.mode);
          entry._mode = stats.mode;
          if (inode.type === "tree") {
            entry._stat = void 0;
          } else {
            entry._stat = stats;
          }
        }
        return entry._stat;
      }
      async content(_entry) {
      }
      async oid(entry) {
        if (entry._oid === false) {
          const tree = await this.treePromise;
          const inode = tree.get(entry._fullpath);
          entry._oid = inode.metadata.oid;
        }
        return entry._oid;
      }
    };
    var GitWalkSymbol = Symbol("GitWalkSymbol");
    function STAGE() {
      const o = /* @__PURE__ */ Object.create(null);
      Object.defineProperty(o, GitWalkSymbol, {
        value: function({ fs: fs2, gitdir, cache }) {
          return new GitWalkerIndex({ fs: fs2, gitdir, cache });
        }
      });
      Object.freeze(o);
      return o;
    }
    var NotFoundError = class _NotFoundError extends BaseError {
      /**
       * @param {string} what
       */
      constructor(what) {
        super(`Could not find ${what}.`);
        this.code = this.name = _NotFoundError.code;
        this.data = { what };
      }
    };
    NotFoundError.code = "NotFoundError";
    var ObjectTypeError = class _ObjectTypeError extends BaseError {
      /**
       * @param {string} oid
       * @param {'blob'|'commit'|'tag'|'tree'} actual
       * @param {'blob'|'commit'|'tag'|'tree'} expected
       * @param {string} [filepath]
       */
      constructor(oid, actual, expected, filepath) {
        super(
          `Object ${oid} ${filepath ? `at ${filepath}` : ""}was anticipated to be a ${expected} but it is a ${actual}.`
        );
        this.code = this.name = _ObjectTypeError.code;
        this.data = { oid, actual, expected, filepath };
      }
    };
    ObjectTypeError.code = "ObjectTypeError";
    var InvalidOidError = class _InvalidOidError extends BaseError {
      /**
       * @param {string} value
       */
      constructor(value) {
        super(`Expected a 40-char hex object id but saw "${value}".`);
        this.code = this.name = _InvalidOidError.code;
        this.data = { value };
      }
    };
    InvalidOidError.code = "InvalidOidError";
    var NoRefspecError = class _NoRefspecError extends BaseError {
      /**
       * @param {string} remote
       */
      constructor(remote) {
        super(`Could not find a fetch refspec for remote "${remote}". Make sure the config file has an entry like the following:
[remote "${remote}"]
	fetch = +refs/heads/*:refs/remotes/origin/*
`);
        this.code = this.name = _NoRefspecError.code;
        this.data = { remote };
      }
    };
    NoRefspecError.code = "NoRefspecError";
    var GitPackedRefs = class _GitPackedRefs {
      constructor(text2) {
        this.refs = /* @__PURE__ */ new Map();
        this.parsedConfig = [];
        if (text2) {
          let key = null;
          this.parsedConfig = text2.trim().split("\n").map((line) => {
            if (/^\s*#/.test(line)) {
              return { line, comment: true };
            }
            const i = line.indexOf(" ");
            if (line.startsWith("^")) {
              const value = line.slice(1);
              this.refs.set(key + "^{}", value);
              return { line, ref: key, peeled: value };
            } else {
              const value = line.slice(0, i);
              key = line.slice(i + 1);
              this.refs.set(key, value);
              return { line, ref: key, oid: value };
            }
          });
        }
        return this;
      }
      static from(text2) {
        return new _GitPackedRefs(text2);
      }
      delete(ref) {
        this.parsedConfig = this.parsedConfig.filter((entry) => entry.ref !== ref);
        this.refs.delete(ref);
      }
      toString() {
        return this.parsedConfig.map(({ line }) => line).join("\n") + "\n";
      }
    };
    var GitRefSpec = class _GitRefSpec {
      constructor({ remotePath, localPath, force, matchPrefix }) {
        Object.assign(this, {
          remotePath,
          localPath,
          force,
          matchPrefix
        });
      }
      static from(refspec) {
        const [forceMatch, remotePath, remoteGlobMatch, localPath, localGlobMatch] = refspec.match(/^(\+?)(.*?)(\*?):(.*?)(\*?)$/).slice(1);
        const force = forceMatch === "+";
        const remoteIsGlob = remoteGlobMatch === "*";
        const localIsGlob = localGlobMatch === "*";
        if (remoteIsGlob !== localIsGlob) {
          throw new InternalError("Invalid refspec");
        }
        return new _GitRefSpec({
          remotePath,
          localPath,
          force,
          matchPrefix: remoteIsGlob
        });
      }
      translate(remoteBranch) {
        if (this.matchPrefix) {
          if (remoteBranch.startsWith(this.remotePath)) {
            return this.localPath + remoteBranch.replace(this.remotePath, "");
          }
        } else {
          if (remoteBranch === this.remotePath) return this.localPath;
        }
        return null;
      }
      reverseTranslate(localBranch) {
        if (this.matchPrefix) {
          if (localBranch.startsWith(this.localPath)) {
            return this.remotePath + localBranch.replace(this.localPath, "");
          }
        } else {
          if (localBranch === this.localPath) return this.remotePath;
        }
        return null;
      }
    };
    var GitRefSpecSet = class _GitRefSpecSet {
      constructor(rules = []) {
        this.rules = rules;
      }
      static from(refspecs) {
        const rules = [];
        for (const refspec of refspecs) {
          rules.push(GitRefSpec.from(refspec));
        }
        return new _GitRefSpecSet(rules);
      }
      add(refspec) {
        const rule = GitRefSpec.from(refspec);
        this.rules.push(rule);
      }
      translate(remoteRefs) {
        const result = [];
        for (const rule of this.rules) {
          for (const remoteRef of remoteRefs) {
            const localRef = rule.translate(remoteRef);
            if (localRef) {
              result.push([remoteRef, localRef]);
            }
          }
        }
        return result;
      }
      translateOne(remoteRef) {
        let result = null;
        for (const rule of this.rules) {
          const localRef = rule.translate(remoteRef);
          if (localRef) {
            result = localRef;
          }
        }
        return result;
      }
      localNamespaces() {
        return this.rules.filter((rule) => rule.matchPrefix).map((rule) => rule.localPath.replace(/\/$/, ""));
      }
    };
    function compareRefNames(a, b) {
      const _a = a.replace(/\^\{\}$/, "");
      const _b = b.replace(/\^\{\}$/, "");
      const tmp = -(_a < _b) || +(_a > _b);
      if (tmp === 0) {
        return a.endsWith("^{}") ? 1 : -1;
      }
      return tmp;
    }
    function normalizeString(path, aar) {
      let res = "";
      let lastSegmentLength = 0;
      let lastSlash = -1;
      let dots = 0;
      let char = "\0";
      for (let i = 0; i <= path.length; ++i) {
        if (i < path.length) char = path[i];
        else if (char === "/") break;
        else char = "/";
        if (char === "/") {
          if (lastSlash === i - 1 || dots === 1) {
          } else if (dots === 2) {
            if (res.length < 2 || lastSegmentLength !== 2 || res.at(-1) !== "." || res.at(-2) !== ".") {
              if (res.length > 2) {
                const lastSlashIndex = res.lastIndexOf("/");
                if (lastSlashIndex === -1) {
                  res = "";
                  lastSegmentLength = 0;
                } else {
                  res = res.slice(0, lastSlashIndex);
                  lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
                }
                lastSlash = i;
                dots = 0;
                continue;
              } else if (res.length !== 0) {
                res = "";
                lastSegmentLength = 0;
                lastSlash = i;
                dots = 0;
                continue;
              }
            }
            if (aar) {
              res += res.length > 0 ? "/.." : "..";
              lastSegmentLength = 2;
            }
          } else {
            if (res.length > 0) res += "/" + path.slice(lastSlash + 1, i);
            else res = path.slice(lastSlash + 1, i);
            lastSegmentLength = i - lastSlash - 1;
          }
          lastSlash = i;
          dots = 0;
        } else if (char === "." && dots !== -1) {
          ++dots;
        } else {
          dots = -1;
        }
      }
      return res;
    }
    function normalize(path) {
      if (!path.length) return ".";
      const isAbsolute = path[0] === "/";
      const trailingSeparator = path.at(-1) === "/";
      path = normalizeString(path, !isAbsolute);
      if (!path.length) {
        if (isAbsolute) return "/";
        return trailingSeparator ? "./" : ".";
      }
      if (trailingSeparator) path += "/";
      return isAbsolute ? `/${path}` : path;
    }
    function join(...args) {
      if (args.length === 0) return ".";
      let joined;
      for (let i = 0; i < args.length; ++i) {
        const arg = args[i];
        if (arg.length > 0) {
          if (joined === void 0) joined = arg;
          else joined += "/" + arg;
        }
      }
      if (joined === void 0) return ".";
      return normalize(joined);
    }
    var num = (val) => {
      if (typeof val === "number") {
        return val;
      }
      val = val.toLowerCase();
      let n2 = parseInt(val);
      if (val.endsWith("k")) n2 *= 1024;
      if (val.endsWith("m")) n2 *= 1024 * 1024;
      if (val.endsWith("g")) n2 *= 1024 * 1024 * 1024;
      return n2;
    };
    var bool = (val) => {
      if (typeof val === "boolean") {
        return val;
      }
      val = val.trim().toLowerCase();
      if (val === "true" || val === "yes" || val === "on") return true;
      if (val === "false" || val === "no" || val === "off") return false;
      throw Error(
        `Expected 'true', 'false', 'yes', 'no', 'on', or 'off', but got ${val}`
      );
    };
    var schema = {
      core: {
        filemode: bool,
        bare: bool,
        logallrefupdates: bool,
        symlinks: bool,
        ignorecase: bool,
        bigFileThreshold: num
      }
    };
    var SECTION_LINE_REGEX = /^\[([A-Za-z0-9-.]+)(?: "(.*)")?\]$/;
    var SECTION_REGEX = /^[A-Za-z0-9-.]+$/;
    var VARIABLE_LINE_REGEX = /^([A-Za-z][A-Za-z-]*)(?: *= *(.*))?$/;
    var VARIABLE_NAME_REGEX = /^[A-Za-z][A-Za-z-]*$/;
    var VARIABLE_VALUE_COMMENT_REGEX = /^(.*?)( *[#;].*)$/;
    var extractSectionLine = (line) => {
      const matches = SECTION_LINE_REGEX.exec(line);
      if (matches != null) {
        const [section, subsection] = matches.slice(1);
        return [section, subsection];
      }
      return null;
    };
    var extractVariableLine = (line) => {
      const matches = VARIABLE_LINE_REGEX.exec(line);
      if (matches != null) {
        const [name, rawValue = "true"] = matches.slice(1);
        const valueWithoutComments = removeComments(rawValue);
        const valueWithoutQuotes = removeQuotes(valueWithoutComments);
        return [name, valueWithoutQuotes];
      }
      return null;
    };
    var removeComments = (rawValue) => {
      const commentMatches = VARIABLE_VALUE_COMMENT_REGEX.exec(rawValue);
      if (commentMatches == null) {
        return rawValue;
      }
      const [valueWithoutComment, comment] = commentMatches.slice(1);
      if (hasOddNumberOfQuotes(valueWithoutComment) && hasOddNumberOfQuotes(comment)) {
        return `${valueWithoutComment}${comment}`;
      }
      return valueWithoutComment;
    };
    var hasOddNumberOfQuotes = (text2) => {
      const numberOfQuotes = (text2.match(/(?:^|[^\\])"/g) || []).length;
      return numberOfQuotes % 2 !== 0;
    };
    var removeQuotes = (text2) => {
      return text2.split("").reduce((newText, c, idx, text3) => {
        const isQuote = c === '"' && text3[idx - 1] !== "\\";
        const isEscapeForQuote = c === "\\" && text3[idx + 1] === '"';
        if (isQuote || isEscapeForQuote) {
          return newText;
        }
        return newText + c;
      }, "");
    };
    var lower = (text2) => {
      return text2 != null ? text2.toLowerCase() : null;
    };
    var getPath = (section, subsection, name) => {
      return [lower(section), subsection, lower(name)].filter((a) => a != null).join(".");
    };
    var normalizePath5 = (path) => {
      const pathSegments = path.split(".");
      const section = pathSegments.shift();
      const name = pathSegments.pop();
      const subsection = pathSegments.length ? pathSegments.join(".") : void 0;
      return {
        section,
        subsection,
        name,
        path: getPath(section, subsection, name),
        sectionPath: getPath(section, subsection, null),
        isSection: !!section
      };
    };
    var findLastIndex = (array, callback) => {
      return array.reduce((lastIndex, item, index2) => {
        return callback(item) ? index2 : lastIndex;
      }, -1);
    };
    var GitConfig = class _GitConfig {
      constructor(text2) {
        let section = null;
        let subsection = null;
        this.parsedConfig = text2 ? text2.split("\n").map((line) => {
          let name = null;
          let value = null;
          const trimmedLine = line.trim();
          const extractedSection = extractSectionLine(trimmedLine);
          const isSection = extractedSection != null;
          if (isSection) {
            ;
            [section, subsection] = extractedSection;
          } else {
            const extractedVariable = extractVariableLine(trimmedLine);
            const isVariable = extractedVariable != null;
            if (isVariable) {
              ;
              [name, value] = extractedVariable;
            }
          }
          const path = getPath(section, subsection, name);
          return { line, isSection, section, subsection, name, value, path };
        }) : [];
      }
      static from(text2) {
        return new _GitConfig(text2);
      }
      async get(path, getall = false) {
        const normalizedPath = normalizePath5(path).path;
        const allValues = this.parsedConfig.filter((config) => config.path === normalizedPath).map(({ section, name, value }) => {
          const fn = schema[section] && schema[section][name];
          return fn ? fn(value) : value;
        });
        return getall ? allValues : allValues.pop();
      }
      async getall(path) {
        return this.get(path, true);
      }
      async getSubsections(section) {
        return this.parsedConfig.filter((config) => config.isSection && config.section === section).map((config) => config.subsection);
      }
      async deleteSection(section, subsection) {
        this.parsedConfig = this.parsedConfig.filter(
          (config) => !(config.section === section && config.subsection === subsection)
        );
      }
      async append(path, value) {
        return this.set(path, value, true);
      }
      async set(path, value, append2 = false) {
        const {
          section,
          subsection,
          name,
          path: normalizedPath,
          sectionPath,
          isSection
        } = normalizePath5(path);
        const configIndex = findLastIndex(
          this.parsedConfig,
          (config) => config.path === normalizedPath
        );
        if (value == null) {
          if (configIndex !== -1) {
            this.parsedConfig.splice(configIndex, 1);
          }
        } else {
          if (configIndex !== -1) {
            const config = this.parsedConfig[configIndex];
            const modifiedConfig = Object.assign({}, config, {
              name,
              value,
              modified: true
            });
            if (append2) {
              this.parsedConfig.splice(configIndex + 1, 0, modifiedConfig);
            } else {
              this.parsedConfig[configIndex] = modifiedConfig;
            }
          } else {
            const sectionIndex = this.parsedConfig.findIndex(
              (config) => config.path === sectionPath
            );
            const newConfig = {
              section,
              subsection,
              name,
              value,
              modified: true,
              path: normalizedPath
            };
            if (SECTION_REGEX.test(section) && VARIABLE_NAME_REGEX.test(name)) {
              if (sectionIndex >= 0) {
                this.parsedConfig.splice(sectionIndex + 1, 0, newConfig);
              } else {
                const newSection = {
                  isSection,
                  section,
                  subsection,
                  modified: true,
                  path: sectionPath
                };
                this.parsedConfig.push(newSection, newConfig);
              }
            }
          }
        }
      }
      toString() {
        return this.parsedConfig.map(({ line, section, subsection, name, value, modified: modified2 = false }) => {
          if (!modified2) {
            return line;
          }
          if (name != null && value != null) {
            if (typeof value === "string" && /[#;]/.test(value)) {
              return `	${name} = "${value}"`;
            }
            return `	${name} = ${value}`;
          }
          if (subsection != null) {
            return `[${section} "${subsection}"]`;
          }
          return `[${section}]`;
        }).join("\n");
      }
    };
    var GitConfigManager = class {
      /**
       * Reads the Git configuration file from the specified `.git` directory.
       *
       * @param {object} opts - Options for reading the Git configuration.
       * @param {FSClient} opts.fs - A file system implementation.
       * @param {string} opts.gitdir - The path to the `.git` directory.
       * @returns {Promise<GitConfig>} A `GitConfig` object representing the parsed configuration.
       */
      static async get({ fs: fs2, gitdir }) {
        const text2 = await fs2.read(`${gitdir}/config`, { encoding: "utf8" });
        return GitConfig.from(text2);
      }
      /**
       * Saves the provided Git configuration to the specified `.git` directory.
       *
       * @param {object} opts - Options for saving the Git configuration.
       * @param {FSClient} opts.fs - A file system implementation.
       * @param {string} opts.gitdir - The path to the `.git` directory.
       * @param {GitConfig} opts.config - The `GitConfig` object to save.
       * @returns {Promise<void>} Resolves when the configuration has been successfully saved.
       */
      static async save({ fs: fs2, gitdir, config }) {
        await fs2.write(`${gitdir}/config`, config.toString(), {
          encoding: "utf8"
        });
      }
    };
    var refpaths = (ref) => [
      `${ref}`,
      `refs/${ref}`,
      `refs/tags/${ref}`,
      `refs/heads/${ref}`,
      `refs/remotes/${ref}`,
      `refs/remotes/${ref}/HEAD`
    ];
    var GIT_FILES = ["config", "description", "index", "shallow", "commondir"];
    var lock$1;
    async function acquireLock(ref, callback) {
      if (lock$1 === void 0) lock$1 = new AsyncLock();
      return lock$1.acquire(ref, callback);
    }
    var GitRefManager = class _GitRefManager {
      /**
       * Updates remote refs based on the provided refspecs and options.
       *
       * @param {Object} args
       * @param {FSClient} args.fs - A file system implementation.
       * @param {string} [args.gitdir=join(dir, '.git')] - [required] The [git directory](dir-vs-gitdir.md) path
       * @param {string} args.remote - The name of the remote.
       * @param {Map<string, string>} args.refs - A map of refs to their object IDs.
       * @param {Map<string, string>} args.symrefs - A map of symbolic refs.
       * @param {boolean} args.tags - Whether to fetch tags.
       * @param {string[]} [args.refspecs = undefined] - The refspecs to use.
       * @param {boolean} [args.prune = false] - Whether to prune stale refs.
       * @param {boolean} [args.pruneTags = false] - Whether to prune tags.
       * @returns {Promise<Object>} - An object containing pruned refs.
       */
      static async updateRemoteRefs({
        fs: fs2,
        gitdir,
        remote,
        refs,
        symrefs,
        tags,
        refspecs = void 0,
        prune = false,
        pruneTags = false
      }) {
        for (const value of refs.values()) {
          if (!value.match(/[0-9a-f]{40}/)) {
            throw new InvalidOidError(value);
          }
        }
        const config = await GitConfigManager.get({ fs: fs2, gitdir });
        if (!refspecs) {
          refspecs = await config.getall(`remote.${remote}.fetch`);
          if (refspecs.length === 0) {
            throw new NoRefspecError(remote);
          }
          refspecs.unshift(`+HEAD:refs/remotes/${remote}/HEAD`);
        }
        const refspec = GitRefSpecSet.from(refspecs);
        const actualRefsToWrite = /* @__PURE__ */ new Map();
        if (pruneTags) {
          const tags2 = await _GitRefManager.listRefs({
            fs: fs2,
            gitdir,
            filepath: "refs/tags"
          });
          await _GitRefManager.deleteRefs({
            fs: fs2,
            gitdir,
            refs: tags2.map((tag2) => `refs/tags/${tag2}`)
          });
        }
        if (tags) {
          for (const serverRef of refs.keys()) {
            if (serverRef.startsWith("refs/tags") && !serverRef.endsWith("^{}")) {
              if (!await _GitRefManager.exists({ fs: fs2, gitdir, ref: serverRef })) {
                const oid = refs.get(serverRef);
                actualRefsToWrite.set(serverRef, oid);
              }
            }
          }
        }
        const refTranslations = refspec.translate([...refs.keys()]);
        for (const [serverRef, translatedRef] of refTranslations) {
          const value = refs.get(serverRef);
          actualRefsToWrite.set(translatedRef, value);
        }
        const symrefTranslations = refspec.translate([...symrefs.keys()]);
        for (const [serverRef, translatedRef] of symrefTranslations) {
          const value = symrefs.get(serverRef);
          const symtarget = refspec.translateOne(value);
          if (symtarget) {
            actualRefsToWrite.set(translatedRef, `ref: ${symtarget}`);
          }
        }
        const pruned = [];
        if (prune) {
          for (const filepath of refspec.localNamespaces()) {
            const refs2 = (await _GitRefManager.listRefs({
              fs: fs2,
              gitdir,
              filepath
            })).map((file) => `${filepath}/${file}`);
            for (const ref of refs2) {
              if (!actualRefsToWrite.has(ref)) {
                pruned.push(ref);
              }
            }
          }
          if (pruned.length > 0) {
            await _GitRefManager.deleteRefs({ fs: fs2, gitdir, refs: pruned });
          }
        }
        for (const [key, value] of actualRefsToWrite) {
          await acquireLock(
            key,
            async () => fs2.write(join(gitdir, key), `${value.trim()}
`, "utf8")
          );
        }
        return { pruned };
      }
      /**
       * Writes a ref to the file system.
       *
       * @param {Object} args
       * @param {FSClient} args.fs - A file system implementation.
       * @param {string} [args.gitdir] - [required] The [git directory](dir-vs-gitdir.md) path
       * @param {string} args.ref - The ref to write.
       * @param {string} args.value - The object ID to write.
       * @returns {Promise<void>}
       */
      // TODO: make this less crude?
      static async writeRef({ fs: fs2, gitdir, ref, value }) {
        if (!value.match(/[0-9a-f]{40}/)) {
          throw new InvalidOidError(value);
        }
        await acquireLock(
          ref,
          async () => fs2.write(join(gitdir, ref), `${value.trim()}
`, "utf8")
        );
      }
      /**
       * Writes a symbolic ref to the file system.
       *
       * @param {Object} args
       * @param {FSClient} args.fs - A file system implementation.
       * @param {string} [args.gitdir] - [required] The [git directory](dir-vs-gitdir.md) path
       * @param {string} args.ref - The ref to write.
       * @param {string} args.value - The target ref.
       * @returns {Promise<void>}
       */
      static async writeSymbolicRef({ fs: fs2, gitdir, ref, value }) {
        await acquireLock(
          ref,
          async () => fs2.write(join(gitdir, ref), `ref: ${value.trim()}
`, "utf8")
        );
      }
      /**
       * Deletes a single ref.
       *
       * @param {Object} args
       * @param {FSClient} args.fs - A file system implementation.
       * @param {string} [args.gitdir] - [required] The [git directory](dir-vs-gitdir.md) path
       * @param {string} args.ref - The ref to delete.
       * @returns {Promise<void>}
       */
      static async deleteRef({ fs: fs2, gitdir, ref }) {
        return _GitRefManager.deleteRefs({ fs: fs2, gitdir, refs: [ref] });
      }
      /**
       * Deletes multiple refs.
       *
       * @param {Object} args
       * @param {FSClient} args.fs - A file system implementation.
       * @param {string} [args.gitdir] - [required] The [git directory](dir-vs-gitdir.md) path
       * @param {string[]} args.refs - The refs to delete.
       * @returns {Promise<void>}
       */
      static async deleteRefs({ fs: fs2, gitdir, refs }) {
        await Promise.all(refs.map((ref) => fs2.rm(join(gitdir, ref))));
        let text2 = await acquireLock(
          "packed-refs",
          async () => fs2.read(`${gitdir}/packed-refs`, { encoding: "utf8" })
        );
        const packed = GitPackedRefs.from(text2);
        const beforeSize = packed.refs.size;
        for (const ref of refs) {
          if (packed.refs.has(ref)) {
            packed.delete(ref);
          }
        }
        if (packed.refs.size < beforeSize) {
          text2 = packed.toString();
          await acquireLock(
            "packed-refs",
            async () => fs2.write(`${gitdir}/packed-refs`, text2, { encoding: "utf8" })
          );
        }
      }
      /**
       * Resolves a ref to its object ID.
       *
       * @param {Object} args
       * @param {FSClient} args.fs - A file system implementation.
       * @param {string} [args.gitdir] - [required] The [git directory](dir-vs-gitdir.md) path
       * @param {string} args.ref - The ref to resolve.
       * @param {number} [args.depth = undefined] - The maximum depth to resolve symbolic refs.
       * @returns {Promise<string>} - The resolved object ID.
       */
      static async resolve({ fs: fs2, gitdir, ref, depth = void 0 }) {
        if (depth !== void 0) {
          depth--;
          if (depth === -1) {
            return ref;
          }
        }
        if (ref.startsWith("ref: ")) {
          ref = ref.slice("ref: ".length);
          return _GitRefManager.resolve({ fs: fs2, gitdir, ref, depth });
        }
        if (ref.length === 40 && /[0-9a-f]{40}/.test(ref)) {
          return ref;
        }
        const packedMap = await _GitRefManager.packedRefs({ fs: fs2, gitdir });
        const allpaths = refpaths(ref).filter((p) => !GIT_FILES.includes(p));
        for (const ref2 of allpaths) {
          const sha = await acquireLock(
            ref2,
            async () => await fs2.read(`${gitdir}/${ref2}`, { encoding: "utf8" }) || packedMap.get(ref2)
          );
          if (sha) {
            return _GitRefManager.resolve({ fs: fs2, gitdir, ref: sha.trim(), depth });
          }
        }
        throw new NotFoundError(ref);
      }
      /**
       * Checks if a ref exists.
       *
       * @param {Object} args
       * @param {FSClient} args.fs - A file system implementation.
       * @param {string} [args.gitdir=join(dir, '.git')] - [required] The [git directory](dir-vs-gitdir.md) path
       * @param {string} args.ref - The ref to check.
       * @returns {Promise<boolean>} - True if the ref exists, false otherwise.
       */
      static async exists({ fs: fs2, gitdir, ref }) {
        try {
          await _GitRefManager.expand({ fs: fs2, gitdir, ref });
          return true;
        } catch (err) {
          return false;
        }
      }
      /**
       * Expands a ref to its full name.
       *
       * @param {Object} args
       * @param {FSClient} args.fs - A file system implementation.
       * @param {string} [args.gitdir=join(dir, '.git')] - [required] The [git directory](dir-vs-gitdir.md) path
       * @param {string} args.ref - The ref to expand.
       * @returns {Promise<string>} - The full ref name.
       */
      static async expand({ fs: fs2, gitdir, ref }) {
        if (ref.length === 40 && /[0-9a-f]{40}/.test(ref)) {
          return ref;
        }
        const packedMap = await _GitRefManager.packedRefs({ fs: fs2, gitdir });
        const allpaths = refpaths(ref);
        for (const ref2 of allpaths) {
          const refExists = await acquireLock(
            ref2,
            async () => fs2.exists(`${gitdir}/${ref2}`)
          );
          if (refExists) return ref2;
          if (packedMap.has(ref2)) return ref2;
        }
        throw new NotFoundError(ref);
      }
      /**
       * Expands a ref against a provided map.
       *
       * @param {Object} args
       * @param {string} args.ref - The ref to expand.
       * @param {Map<string, string>} args.map - The map of refs.
       * @returns {Promise<string>} - The expanded ref.
       */
      static async expandAgainstMap({ ref, map }) {
        const allpaths = refpaths(ref);
        for (const ref2 of allpaths) {
          if (await map.has(ref2)) return ref2;
        }
        throw new NotFoundError(ref);
      }
      /**
       * Resolves a ref against a provided map.
       *
       * @param {Object} args
       * @param {string} args.ref - The ref to resolve.
       * @param {string} [args.fullref = args.ref] - The full ref name.
       * @param {number} [args.depth = undefined] - The maximum depth to resolve symbolic refs.
       * @param {Map<string, string>} args.map - The map of refs.
       * @returns {Object} - An object containing the full ref and its object ID.
       */
      static resolveAgainstMap({ ref, fullref = ref, depth = void 0, map }) {
        if (depth !== void 0) {
          depth--;
          if (depth === -1) {
            return { fullref, oid: ref };
          }
        }
        if (ref.startsWith("ref: ")) {
          ref = ref.slice("ref: ".length);
          return _GitRefManager.resolveAgainstMap({ ref, fullref, depth, map });
        }
        if (ref.length === 40 && /[0-9a-f]{40}/.test(ref)) {
          return { fullref, oid: ref };
        }
        const allpaths = refpaths(ref);
        for (const ref2 of allpaths) {
          const sha = map.get(ref2);
          if (sha) {
            return _GitRefManager.resolveAgainstMap({
              ref: sha.trim(),
              fullref: ref2,
              depth,
              map
            });
          }
        }
        throw new NotFoundError(ref);
      }
      /**
       * Reads the packed refs file and returns a map of refs.
       *
       * @param {Object} args
       * @param {FSClient} args.fs - A file system implementation.
       * @param {string} [args.gitdir=join(dir, '.git')] - [required] The [git directory](dir-vs-gitdir.md) path
       * @returns {Promise<Map<string, string>>} - A map of packed refs.
       */
      static async packedRefs({ fs: fs2, gitdir }) {
        const text2 = await acquireLock(
          "packed-refs",
          async () => fs2.read(`${gitdir}/packed-refs`, { encoding: "utf8" })
        );
        const packed = GitPackedRefs.from(text2);
        return packed.refs;
      }
      /**
       * Lists all refs matching a given filepath prefix.
       *
       * @param {Object} args
       * @param {FSClient} args.fs - A file system implementation.
       * @param {string} [args.gitdir=join(dir, '.git')] - [required] The [git directory](dir-vs-gitdir.md) path
       * @param {string} args.filepath - The filepath prefix to match.
       * @returns {Promise<string[]>} - A sorted list of refs.
       */
      static async listRefs({ fs: fs2, gitdir, filepath }) {
        const packedMap = _GitRefManager.packedRefs({ fs: fs2, gitdir });
        let files = null;
        try {
          files = await fs2.readdirDeep(`${gitdir}/${filepath}`);
          files = files.map((x) => x.replace(`${gitdir}/${filepath}/`, ""));
        } catch (err) {
          files = [];
        }
        for (let key of (await packedMap).keys()) {
          if (key.startsWith(filepath)) {
            key = key.replace(filepath + "/", "");
            if (!files.includes(key)) {
              files.push(key);
            }
          }
        }
        files.sort(compareRefNames);
        return files;
      }
      /**
       * Lists all branches, optionally filtered by remote.
       *
       * @param {Object} args
       * @param {FSClient} args.fs - A file system implementation.
       * @param {string} [args.gitdir=join(dir, '.git')] - [required] The [git directory](dir-vs-gitdir.md) path
       * @param {string} [args.remote] - The remote to filter branches by.
       * @returns {Promise<string[]>} - A list of branch names.
       */
      static async listBranches({ fs: fs2, gitdir, remote }) {
        if (remote) {
          return _GitRefManager.listRefs({
            fs: fs2,
            gitdir,
            filepath: `refs/remotes/${remote}`
          });
        } else {
          return _GitRefManager.listRefs({ fs: fs2, gitdir, filepath: `refs/heads` });
        }
      }
      /**
       * Lists all tags.
       *
       * @param {Object} args
       * @param {FSClient} args.fs - A file system implementation.
       * @param {string} [args.gitdir=join(dir, '.git')] - [required] The [git directory](dir-vs-gitdir.md) path
       * @returns {Promise<string[]>} - A list of tag names.
       */
      static async listTags({ fs: fs2, gitdir }) {
        const tags = await _GitRefManager.listRefs({
          fs: fs2,
          gitdir,
          filepath: `refs/tags`
        });
        return tags.filter((x) => !x.endsWith("^{}"));
      }
    };
    function compareTreeEntryPath(a, b) {
      return compareStrings(appendSlashIfDir(a), appendSlashIfDir(b));
    }
    function appendSlashIfDir(entry) {
      return entry.mode === "040000" ? entry.path + "/" : entry.path;
    }
    function mode2type$1(mode) {
      switch (mode) {
        case "040000":
          return "tree";
        case "100644":
          return "blob";
        case "100755":
          return "blob";
        case "120000":
          return "blob";
        case "160000":
          return "commit";
      }
      throw new InternalError(`Unexpected GitTree entry mode: ${mode}`);
    }
    function parseBuffer(buffer) {
      const _entries = [];
      let cursor = 0;
      while (cursor < buffer.length) {
        const space2 = buffer.indexOf(32, cursor);
        if (space2 === -1) {
          throw new InternalError(
            `GitTree: Error parsing buffer at byte location ${cursor}: Could not find the next space character.`
          );
        }
        const nullchar = buffer.indexOf(0, cursor);
        if (nullchar === -1) {
          throw new InternalError(
            `GitTree: Error parsing buffer at byte location ${cursor}: Could not find the next null character.`
          );
        }
        let mode = buffer.slice(cursor, space2).toString("utf8");
        if (mode === "40000") mode = "040000";
        const type = mode2type$1(mode);
        const path = buffer.slice(space2 + 1, nullchar).toString("utf8");
        if (path.includes("\\") || path.includes("/")) {
          throw new UnsafeFilepathError(path);
        }
        const oid = buffer.slice(nullchar + 1, nullchar + 21).toString("hex");
        cursor = nullchar + 21;
        _entries.push({ mode, path, oid, type });
      }
      return _entries;
    }
    function limitModeToAllowed(mode) {
      if (typeof mode === "number") {
        mode = mode.toString(8);
      }
      if (mode.match(/^0?4.*/)) return "040000";
      if (mode.match(/^1006.*/)) return "100644";
      if (mode.match(/^1007.*/)) return "100755";
      if (mode.match(/^120.*/)) return "120000";
      if (mode.match(/^160.*/)) return "160000";
      throw new InternalError(`Could not understand file mode: ${mode}`);
    }
    function nudgeIntoShape(entry) {
      if (!entry.oid && entry.sha) {
        entry.oid = entry.sha;
      }
      entry.mode = limitModeToAllowed(entry.mode);
      if (!entry.type) {
        entry.type = mode2type$1(entry.mode);
      }
      return entry;
    }
    var GitTree = class _GitTree {
      constructor(entries) {
        if (Buffer.isBuffer(entries)) {
          this._entries = parseBuffer(entries);
        } else if (Array.isArray(entries)) {
          this._entries = entries.map(nudgeIntoShape);
        } else {
          throw new InternalError("invalid type passed to GitTree constructor");
        }
        this._entries.sort(comparePath);
      }
      static from(tree) {
        return new _GitTree(tree);
      }
      render() {
        return this._entries.map((entry) => `${entry.mode} ${entry.type} ${entry.oid}    ${entry.path}`).join("\n");
      }
      toObject() {
        const entries = [...this._entries];
        entries.sort(compareTreeEntryPath);
        return Buffer.concat(
          entries.map((entry) => {
            const mode = Buffer.from(entry.mode.replace(/^0/, ""));
            const space2 = Buffer.from(" ");
            const path = Buffer.from(entry.path, "utf8");
            const nullchar = Buffer.from([0]);
            const oid = Buffer.from(entry.oid, "hex");
            return Buffer.concat([mode, space2, path, nullchar, oid]);
          })
        );
      }
      /**
       * @returns {TreeEntry[]}
       */
      entries() {
        return this._entries;
      }
      *[Symbol.iterator]() {
        for (const entry of this._entries) {
          yield entry;
        }
      }
    };
    var GitObject = class {
      /**
       * Wraps a raw object with a Git header.
       *
       * @param {Object} params - The parameters for wrapping.
       * @param {string} params.type - The type of the Git object (e.g., 'blob', 'tree', 'commit').
       * @param {Uint8Array} params.object - The raw object data to wrap.
       * @returns {Uint8Array} The wrapped Git object as a single buffer.
       */
      static wrap({ type, object }) {
        const header = `${type} ${object.length}\0`;
        const headerLen = header.length;
        const totalLength = headerLen + object.length;
        const wrappedObject = new Uint8Array(totalLength);
        for (let i = 0; i < headerLen; i++) {
          wrappedObject[i] = header.charCodeAt(i);
        }
        wrappedObject.set(object, headerLen);
        return wrappedObject;
      }
      /**
       * Unwraps a Git object buffer into its type and raw object data.
       *
       * @param {Buffer|Uint8Array} buffer - The buffer containing the wrapped Git object.
       * @returns {{ type: string, object: Buffer }} An object containing the type and the raw object data.
       * @throws {InternalError} If the length specified in the header does not match the actual object length.
       */
      static unwrap(buffer) {
        const s2 = buffer.indexOf(32);
        const i = buffer.indexOf(0);
        const type = buffer.slice(0, s2).toString("utf8");
        const length = buffer.slice(s2 + 1, i).toString("utf8");
        const actualLength = buffer.length - (i + 1);
        if (parseInt(length) !== actualLength) {
          throw new InternalError(
            `Length mismatch: expected ${length} bytes but got ${actualLength} instead.`
          );
        }
        return {
          type,
          object: Buffer.from(buffer.slice(i + 1))
        };
      }
    };
    async function readObjectLoose({ fs: fs2, gitdir, oid }) {
      const source = `objects/${oid.slice(0, 2)}/${oid.slice(2)}`;
      const file = await fs2.read(`${gitdir}/${source}`);
      if (!file) {
        return null;
      }
      return { object: file, format: "deflated", source };
    }
    function applyDelta(delta, source) {
      const reader = new BufferCursor(delta);
      const sourceSize = readVarIntLE(reader);
      if (sourceSize !== source.byteLength) {
        throw new InternalError(
          `applyDelta expected source buffer to be ${sourceSize} bytes but the provided buffer was ${source.length} bytes`
        );
      }
      const targetSize = readVarIntLE(reader);
      let target;
      const firstOp = readOp(reader, source);
      if (firstOp.byteLength === targetSize) {
        target = firstOp;
      } else {
        target = Buffer.alloc(targetSize);
        const writer = new BufferCursor(target);
        writer.copy(firstOp);
        while (!reader.eof()) {
          writer.copy(readOp(reader, source));
        }
        const tell = writer.tell();
        if (targetSize !== tell) {
          throw new InternalError(
            `applyDelta expected target buffer to be ${targetSize} bytes but the resulting buffer was ${tell} bytes`
          );
        }
      }
      return target;
    }
    function readVarIntLE(reader) {
      let result = 0;
      let shift = 0;
      let byte = null;
      do {
        byte = reader.readUInt8();
        result |= (byte & 127) << shift;
        shift += 7;
      } while (byte & 128);
      return result;
    }
    function readCompactLE(reader, flags, size) {
      let result = 0;
      let shift = 0;
      while (size--) {
        if (flags & 1) {
          result |= reader.readUInt8() << shift;
        }
        flags >>= 1;
        shift += 8;
      }
      return result;
    }
    function readOp(reader, source) {
      const byte = reader.readUInt8();
      const COPY = 128;
      const OFFS = 15;
      const SIZE = 112;
      if (byte & COPY) {
        const offset2 = readCompactLE(reader, byte & OFFS, 4);
        let size = readCompactLE(reader, (byte & SIZE) >> 4, 3);
        if (size === 0) size = 65536;
        return source.slice(offset2, offset2 + size);
      } else {
        return reader.slice(byte);
      }
    }
    function fromValue(value) {
      let queue = [value];
      return {
        next() {
          return Promise.resolve({ done: queue.length === 0, value: queue.pop() });
        },
        return() {
          queue = [];
          return {};
        },
        [Symbol.asyncIterator]() {
          return this;
        }
      };
    }
    function getIterator(iterable) {
      if (iterable[Symbol.asyncIterator]) {
        return iterable[Symbol.asyncIterator]();
      }
      if (iterable[Symbol.iterator]) {
        return iterable[Symbol.iterator]();
      }
      if (iterable.next) {
        return iterable;
      }
      return fromValue(iterable);
    }
    var StreamReader = class {
      constructor(stream) {
        if (typeof Buffer === "undefined") {
          throw new Error("Missing Buffer dependency");
        }
        this.stream = getIterator(stream);
        this.buffer = null;
        this.cursor = 0;
        this.undoCursor = 0;
        this.started = false;
        this._ended = false;
        this._discardedBytes = 0;
      }
      eof() {
        return this._ended && this.cursor === this.buffer.length;
      }
      tell() {
        return this._discardedBytes + this.cursor;
      }
      async byte() {
        if (this.eof()) return;
        if (!this.started) await this._init();
        if (this.cursor === this.buffer.length) {
          await this._loadnext();
          if (this._ended) return;
        }
        this._moveCursor(1);
        return this.buffer[this.undoCursor];
      }
      async chunk() {
        if (this.eof()) return;
        if (!this.started) await this._init();
        if (this.cursor === this.buffer.length) {
          await this._loadnext();
          if (this._ended) return;
        }
        this._moveCursor(this.buffer.length);
        return this.buffer.slice(this.undoCursor, this.cursor);
      }
      async read(n2) {
        if (this.eof()) return;
        if (!this.started) await this._init();
        if (this.cursor + n2 > this.buffer.length) {
          this._trim();
          await this._accumulate(n2);
        }
        this._moveCursor(n2);
        return this.buffer.slice(this.undoCursor, this.cursor);
      }
      async skip(n2) {
        if (this.eof()) return;
        if (!this.started) await this._init();
        if (this.cursor + n2 > this.buffer.length) {
          this._trim();
          await this._accumulate(n2);
        }
        this._moveCursor(n2);
      }
      async undo() {
        this.cursor = this.undoCursor;
      }
      async _next() {
        this.started = true;
        let { done, value } = await this.stream.next();
        if (done) {
          this._ended = true;
          if (!value) return Buffer.alloc(0);
        }
        if (value) {
          value = Buffer.from(value);
        }
        return value;
      }
      _trim() {
        this.buffer = this.buffer.slice(this.undoCursor);
        this.cursor -= this.undoCursor;
        this._discardedBytes += this.undoCursor;
        this.undoCursor = 0;
      }
      _moveCursor(n2) {
        this.undoCursor = this.cursor;
        this.cursor += n2;
        if (this.cursor > this.buffer.length) {
          this.cursor = this.buffer.length;
        }
      }
      async _accumulate(n2) {
        if (this._ended) return;
        const buffers = [this.buffer];
        while (this.cursor + n2 > lengthBuffers(buffers)) {
          const nextbuffer = await this._next();
          if (this._ended) break;
          buffers.push(nextbuffer);
        }
        this.buffer = Buffer.concat(buffers);
      }
      async _loadnext() {
        this._discardedBytes += this.buffer.length;
        this.undoCursor = 0;
        this.cursor = 0;
        this.buffer = await this._next();
      }
      async _init() {
        this.buffer = await this._next();
      }
    };
    function lengthBuffers(buffers) {
      return buffers.reduce((acc, buffer) => acc + buffer.length, 0);
    }
    async function listpack(stream, onData) {
      const reader = new StreamReader(stream);
      let PACK = await reader.read(4);
      PACK = PACK.toString("utf8");
      if (PACK !== "PACK") {
        throw new InternalError(`Invalid PACK header '${PACK}'`);
      }
      let version3 = await reader.read(4);
      version3 = version3.readUInt32BE(0);
      if (version3 !== 2) {
        throw new InternalError(`Invalid packfile version: ${version3}`);
      }
      let numObjects = await reader.read(4);
      numObjects = numObjects.readUInt32BE(0);
      if (numObjects < 1) return;
      while (!reader.eof() && numObjects--) {
        const offset2 = reader.tell();
        const { type, length, ofs, reference } = await parseHeader(reader);
        const inflator = new pako.Inflate();
        while (!inflator.result) {
          const chunk = await reader.chunk();
          if (!chunk) break;
          inflator.push(chunk, false);
          if (inflator.err) {
            throw new InternalError(`Pako error: ${inflator.msg}`);
          }
          if (inflator.result) {
            if (inflator.result.length !== length) {
              throw new InternalError(
                `Inflated object size is different from that stated in packfile.`
              );
            }
            await reader.undo();
            await reader.read(chunk.length - inflator.strm.avail_in);
            const end = reader.tell();
            await onData({
              data: inflator.result,
              type,
              num: numObjects,
              offset: offset2,
              end,
              reference,
              ofs
            });
          }
        }
      }
    }
    async function parseHeader(reader) {
      let byte = await reader.byte();
      const type = byte >> 4 & 7;
      let length = byte & 15;
      if (byte & 128) {
        let shift = 4;
        do {
          byte = await reader.byte();
          length |= (byte & 127) << shift;
          shift += 7;
        } while (byte & 128);
      }
      let ofs;
      let reference;
      if (type === 6) {
        let shift = 0;
        ofs = 0;
        const bytes = [];
        do {
          byte = await reader.byte();
          ofs |= (byte & 127) << shift;
          shift += 7;
          bytes.push(byte);
        } while (byte & 128);
        reference = Buffer.from(bytes);
      }
      if (type === 7) {
        const buf = await reader.read(20);
        reference = buf;
      }
      return { type, length, ofs, reference };
    }
    var supportsDecompressionStream = false;
    async function inflate(buffer) {
      if (supportsDecompressionStream === null) {
        supportsDecompressionStream = testDecompressionStream();
      }
      return supportsDecompressionStream ? browserInflate(buffer) : pako.inflate(buffer);
    }
    async function browserInflate(buffer) {
      const ds = new DecompressionStream("deflate");
      const d = new Blob([buffer]).stream().pipeThrough(ds);
      return new Uint8Array(await new Response(d).arrayBuffer());
    }
    function testDecompressionStream() {
      try {
        const ds = new DecompressionStream("deflate");
        if (ds) return true;
      } catch (_) {
      }
      return false;
    }
    function decodeVarInt(reader) {
      const bytes = [];
      let byte = 0;
      let multibyte = 0;
      do {
        byte = reader.readUInt8();
        const lastSeven = byte & 127;
        bytes.push(lastSeven);
        multibyte = byte & 128;
      } while (multibyte);
      return bytes.reduce((a, b) => a + 1 << 7 | b, -1);
    }
    function otherVarIntDecode(reader, startWith) {
      let result = startWith;
      let shift = 4;
      let byte = null;
      do {
        byte = reader.readUInt8();
        result |= (byte & 127) << shift;
        shift += 7;
      } while (byte & 128);
      return result;
    }
    var GitPackIndex = class _GitPackIndex {
      constructor(stuff) {
        Object.assign(this, stuff);
        this.offsetCache = {};
      }
      static async fromIdx({ idx, getExternalRefDelta }) {
        const reader = new BufferCursor(idx);
        const magic = reader.slice(4).toString("hex");
        if (magic !== "ff744f63") {
          return;
        }
        const version3 = reader.readUInt32BE();
        if (version3 !== 2) {
          throw new InternalError(
            `Unable to read version ${version3} packfile IDX. (Only version 2 supported)`
          );
        }
        if (idx.byteLength > 2048 * 1024 * 1024) {
          throw new InternalError(
            `To keep implementation simple, I haven't implemented the layer 5 feature needed to support packfiles > 2GB in size.`
          );
        }
        reader.seek(reader.tell() + 4 * 255);
        const size = reader.readUInt32BE();
        const hashes = [];
        for (let i = 0; i < size; i++) {
          const hash = reader.slice(20).toString("hex");
          hashes[i] = hash;
        }
        reader.seek(reader.tell() + 4 * size);
        const offsets = /* @__PURE__ */ new Map();
        for (let i = 0; i < size; i++) {
          offsets.set(hashes[i], reader.readUInt32BE());
        }
        const packfileSha = reader.slice(20).toString("hex");
        return new _GitPackIndex({
          hashes,
          crcs: {},
          offsets,
          packfileSha,
          getExternalRefDelta
        });
      }
      static async fromPack({ pack, getExternalRefDelta, onProgress }) {
        const listpackTypes = {
          1: "commit",
          2: "tree",
          3: "blob",
          4: "tag",
          6: "ofs-delta",
          7: "ref-delta"
        };
        const offsetToObject = {};
        const packfileSha = pack.slice(-20).toString("hex");
        const hashes = [];
        const crcs = {};
        const offsets = /* @__PURE__ */ new Map();
        let totalObjectCount = null;
        let lastPercent = null;
        await listpack([pack], async ({ data, type, reference, offset: offset2, num: num2 }) => {
          if (totalObjectCount === null) totalObjectCount = num2;
          const percent = Math.floor(
            (totalObjectCount - num2) * 100 / totalObjectCount
          );
          if (percent !== lastPercent) {
            if (onProgress) {
              await onProgress({
                phase: "Receiving objects",
                loaded: totalObjectCount - num2,
                total: totalObjectCount
              });
            }
          }
          lastPercent = percent;
          type = listpackTypes[type];
          if (["commit", "tree", "blob", "tag"].includes(type)) {
            offsetToObject[offset2] = {
              type,
              offset: offset2
            };
          } else if (type === "ofs-delta") {
            offsetToObject[offset2] = {
              type,
              offset: offset2
            };
          } else if (type === "ref-delta") {
            offsetToObject[offset2] = {
              type,
              offset: offset2
            };
          }
        });
        const offsetArray = Object.keys(offsetToObject).map(Number);
        for (const [i, start] of offsetArray.entries()) {
          const end = i + 1 === offsetArray.length ? pack.byteLength - 20 : offsetArray[i + 1];
          const o = offsetToObject[start];
          const crc = crc32.buf(pack.slice(start, end)) >>> 0;
          o.end = end;
          o.crc = crc;
        }
        const p = new _GitPackIndex({
          pack: Promise.resolve(pack),
          packfileSha,
          crcs,
          hashes,
          offsets,
          getExternalRefDelta
        });
        lastPercent = null;
        let count = 0;
        const objectsByDepth = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
        for (let offset2 in offsetToObject) {
          offset2 = Number(offset2);
          const percent = Math.floor(count * 100 / totalObjectCount);
          if (percent !== lastPercent) {
            if (onProgress) {
              await onProgress({
                phase: "Resolving deltas",
                loaded: count,
                total: totalObjectCount
              });
            }
          }
          count++;
          lastPercent = percent;
          const o = offsetToObject[offset2];
          if (o.oid) continue;
          try {
            p.readDepth = 0;
            p.externalReadDepth = 0;
            const { type, object } = await p.readSlice({ start: offset2 });
            objectsByDepth[p.readDepth] += 1;
            const oid = await shasum(GitObject.wrap({ type, object }));
            o.oid = oid;
            hashes.push(oid);
            offsets.set(oid, offset2);
            crcs[oid] = o.crc;
          } catch (err) {
            continue;
          }
        }
        hashes.sort();
        return p;
      }
      async toBuffer() {
        const buffers = [];
        const write3 = (str, encoding) => {
          buffers.push(Buffer.from(str, encoding));
        };
        write3("ff744f63", "hex");
        write3("00000002", "hex");
        const fanoutBuffer = new BufferCursor(Buffer.alloc(256 * 4));
        for (let i = 0; i < 256; i++) {
          let count = 0;
          for (const hash of this.hashes) {
            if (parseInt(hash.slice(0, 2), 16) <= i) count++;
          }
          fanoutBuffer.writeUInt32BE(count);
        }
        buffers.push(fanoutBuffer.buffer);
        for (const hash of this.hashes) {
          write3(hash, "hex");
        }
        const crcsBuffer = new BufferCursor(Buffer.alloc(this.hashes.length * 4));
        for (const hash of this.hashes) {
          crcsBuffer.writeUInt32BE(this.crcs[hash]);
        }
        buffers.push(crcsBuffer.buffer);
        const offsetsBuffer = new BufferCursor(Buffer.alloc(this.hashes.length * 4));
        for (const hash of this.hashes) {
          offsetsBuffer.writeUInt32BE(this.offsets.get(hash));
        }
        buffers.push(offsetsBuffer.buffer);
        write3(this.packfileSha, "hex");
        const totalBuffer = Buffer.concat(buffers);
        const sha = await shasum(totalBuffer);
        const shaBuffer = Buffer.alloc(20);
        shaBuffer.write(sha, "hex");
        return Buffer.concat([totalBuffer, shaBuffer]);
      }
      async load({ pack }) {
        this.pack = pack;
      }
      async unload() {
        this.pack = null;
      }
      async read({ oid }) {
        if (!this.offsets.get(oid)) {
          if (this.getExternalRefDelta) {
            this.externalReadDepth++;
            return this.getExternalRefDelta(oid);
          } else {
            throw new InternalError(`Could not read object ${oid} from packfile`);
          }
        }
        const start = this.offsets.get(oid);
        return this.readSlice({ start });
      }
      async readSlice({ start }) {
        if (this.offsetCache[start]) {
          return Object.assign({}, this.offsetCache[start]);
        }
        this.readDepth++;
        const types2 = {
          16: "commit",
          32: "tree",
          48: "blob",
          64: "tag",
          96: "ofs_delta",
          112: "ref_delta"
        };
        if (!this.pack) {
          throw new InternalError(
            "Tried to read from a GitPackIndex with no packfile loaded into memory"
          );
        }
        const raw = (await this.pack).slice(start);
        const reader = new BufferCursor(raw);
        const byte = reader.readUInt8();
        const btype = byte & 112;
        let type = types2[btype];
        if (type === void 0) {
          throw new InternalError("Unrecognized type: 0b" + btype.toString(2));
        }
        const lastFour = byte & 15;
        let length = lastFour;
        const multibyte = byte & 128;
        if (multibyte) {
          length = otherVarIntDecode(reader, lastFour);
        }
        let base = null;
        let object = null;
        if (type === "ofs_delta") {
          const offset2 = decodeVarInt(reader);
          const baseOffset = start - offset2;
          ({ object: base, type } = await this.readSlice({ start: baseOffset }));
        }
        if (type === "ref_delta") {
          const oid = reader.slice(20).toString("hex");
          ({ object: base, type } = await this.read({ oid }));
        }
        const buffer = raw.slice(reader.tell());
        object = Buffer.from(await inflate(buffer));
        if (object.byteLength !== length) {
          throw new InternalError(
            `Packfile told us object would have length ${length} but it had length ${object.byteLength}`
          );
        }
        if (base) {
          object = Buffer.from(applyDelta(object, base));
        }
        if (this.readDepth > 3) {
          this.offsetCache[start] = { type, object };
        }
        return { type, format: "content", object };
      }
    };
    var PackfileCache = Symbol("PackfileCache");
    async function loadPackIndex({
      fs: fs2,
      filename,
      getExternalRefDelta,
      emitter,
      emitterPrefix
    }) {
      const idx = await fs2.read(filename);
      return GitPackIndex.fromIdx({ idx, getExternalRefDelta });
    }
    function readPackIndex({
      fs: fs2,
      cache,
      filename,
      getExternalRefDelta,
      emitter,
      emitterPrefix
    }) {
      if (!cache[PackfileCache]) cache[PackfileCache] = /* @__PURE__ */ new Map();
      let p = cache[PackfileCache].get(filename);
      if (!p) {
        p = loadPackIndex({
          fs: fs2,
          filename,
          getExternalRefDelta,
          emitter,
          emitterPrefix
        });
        cache[PackfileCache].set(filename, p);
      }
      return p;
    }
    async function readObjectPacked({
      fs: fs2,
      cache,
      gitdir,
      oid,
      format = "content",
      getExternalRefDelta
    }) {
      let list = await fs2.readdir(join(gitdir, "objects/pack"));
      list = list.filter((x) => x.endsWith(".idx"));
      for (const filename of list) {
        const indexFile = `${gitdir}/objects/pack/${filename}`;
        const p = await readPackIndex({
          fs: fs2,
          cache,
          filename: indexFile,
          getExternalRefDelta
        });
        if (p.error) throw new InternalError(p.error);
        if (p.offsets.has(oid)) {
          if (!p.pack) {
            const packFile = indexFile.replace(/idx$/, "pack");
            p.pack = fs2.read(packFile);
          }
          const result = await p.read({ oid, getExternalRefDelta });
          result.format = "content";
          result.source = `objects/pack/${filename.replace(/idx$/, "pack")}`;
          return result;
        }
      }
      return null;
    }
    async function _readObject({
      fs: fs2,
      cache,
      gitdir,
      oid,
      format = "content"
    }) {
      const getExternalRefDelta = (oid2) => _readObject({ fs: fs2, cache, gitdir, oid: oid2 });
      let result;
      if (oid === "4b825dc642cb6eb9a060e54bf8d69288fbee4904") {
        result = { format: "wrapped", object: Buffer.from(`tree 0\0`) };
      }
      if (!result) {
        result = await readObjectLoose({ fs: fs2, gitdir, oid });
      }
      if (!result) {
        result = await readObjectPacked({
          fs: fs2,
          cache,
          gitdir,
          oid,
          getExternalRefDelta
        });
        if (!result) {
          throw new NotFoundError(oid);
        }
        return result;
      }
      if (format === "deflated") {
        return result;
      }
      if (result.format === "deflated") {
        result.object = Buffer.from(await inflate(result.object));
        result.format = "wrapped";
      }
      if (format === "wrapped") {
        return result;
      }
      const sha = await shasum(result.object);
      if (sha !== oid) {
        throw new InternalError(
          `SHA check failed! Expected ${oid}, computed ${sha}`
        );
      }
      const { object, type } = GitObject.unwrap(result.object);
      result.type = type;
      result.object = object;
      result.format = "content";
      if (format === "content") {
        return result;
      }
      throw new InternalError(`invalid requested format "${format}"`);
    }
    var AlreadyExistsError = class _AlreadyExistsError extends BaseError {
      /**
       * @param {'note'|'remote'|'tag'|'branch'} noun
       * @param {string} where
       * @param {boolean} canForce
       */
      constructor(noun, where, canForce = true) {
        super(
          `Failed to create ${noun} at ${where} because it already exists.${canForce ? ` (Hint: use 'force: true' parameter to overwrite existing ${noun}.)` : ""}`
        );
        this.code = this.name = _AlreadyExistsError.code;
        this.data = { noun, where, canForce };
      }
    };
    AlreadyExistsError.code = "AlreadyExistsError";
    var AmbiguousError = class _AmbiguousError extends BaseError {
      /**
       * @param {'oids'|'refs'} nouns
       * @param {string} short
       * @param {string[]} matches
       */
      constructor(nouns, short, matches) {
        super(
          `Found multiple ${nouns} matching "${short}" (${matches.join(
            ", "
          )}). Use a longer abbreviation length to disambiguate them.`
        );
        this.code = this.name = _AmbiguousError.code;
        this.data = { nouns, short, matches };
      }
    };
    AmbiguousError.code = "AmbiguousError";
    var CheckoutConflictError = class _CheckoutConflictError extends BaseError {
      /**
       * @param {string[]} filepaths
       */
      constructor(filepaths) {
        super(
          `Your local changes to the following files would be overwritten by checkout: ${filepaths.join(
            ", "
          )}`
        );
        this.code = this.name = _CheckoutConflictError.code;
        this.data = { filepaths };
      }
    };
    CheckoutConflictError.code = "CheckoutConflictError";
    var CommitNotFetchedError = class _CommitNotFetchedError extends BaseError {
      /**
       * @param {string} ref
       * @param {string} oid
       */
      constructor(ref, oid) {
        super(
          `Failed to checkout "${ref}" because commit ${oid} is not available locally. Do a git fetch to make the branch available locally.`
        );
        this.code = this.name = _CommitNotFetchedError.code;
        this.data = { ref, oid };
      }
    };
    CommitNotFetchedError.code = "CommitNotFetchedError";
    var EmptyServerResponseError = class _EmptyServerResponseError extends BaseError {
      constructor() {
        super(`Empty response from git server.`);
        this.code = this.name = _EmptyServerResponseError.code;
        this.data = {};
      }
    };
    EmptyServerResponseError.code = "EmptyServerResponseError";
    var FastForwardError = class _FastForwardError extends BaseError {
      constructor() {
        super(`A simple fast-forward merge was not possible.`);
        this.code = this.name = _FastForwardError.code;
        this.data = {};
      }
    };
    FastForwardError.code = "FastForwardError";
    var GitPushError = class _GitPushError extends BaseError {
      /**
       * @param {string} prettyDetails
       * @param {PushResult} result
       */
      constructor(prettyDetails, result) {
        super(`One or more branches were not updated: ${prettyDetails}`);
        this.code = this.name = _GitPushError.code;
        this.data = { prettyDetails, result };
      }
    };
    GitPushError.code = "GitPushError";
    var HttpError = class _HttpError extends BaseError {
      /**
       * @param {number} statusCode
       * @param {string} statusMessage
       * @param {string} response
       */
      constructor(statusCode, statusMessage, response) {
        super(`HTTP Error: ${statusCode} ${statusMessage}`);
        this.code = this.name = _HttpError.code;
        this.data = { statusCode, statusMessage, response };
      }
    };
    HttpError.code = "HttpError";
    var InvalidFilepathError = class _InvalidFilepathError extends BaseError {
      /**
       * @param {'leading-slash'|'trailing-slash'|'directory'} [reason]
       */
      constructor(reason) {
        let message = "invalid filepath";
        if (reason === "leading-slash" || reason === "trailing-slash") {
          message = `"filepath" parameter should not include leading or trailing directory separators because these can cause problems on some platforms.`;
        } else if (reason === "directory") {
          message = `"filepath" should not be a directory.`;
        }
        super(message);
        this.code = this.name = _InvalidFilepathError.code;
        this.data = { reason };
      }
    };
    InvalidFilepathError.code = "InvalidFilepathError";
    var InvalidRefNameError = class _InvalidRefNameError extends BaseError {
      /**
       * @param {string} ref
       * @param {string} suggestion
       * @param {boolean} canForce
       */
      constructor(ref, suggestion) {
        super(
          `"${ref}" would be an invalid git reference. (Hint: a valid alternative would be "${suggestion}".)`
        );
        this.code = this.name = _InvalidRefNameError.code;
        this.data = { ref, suggestion };
      }
    };
    InvalidRefNameError.code = "InvalidRefNameError";
    var MaxDepthError = class _MaxDepthError extends BaseError {
      /**
       * @param {number} depth
       */
      constructor(depth) {
        super(`Maximum search depth of ${depth} exceeded.`);
        this.code = this.name = _MaxDepthError.code;
        this.data = { depth };
      }
    };
    MaxDepthError.code = "MaxDepthError";
    var MergeNotSupportedError = class _MergeNotSupportedError extends BaseError {
      constructor() {
        super(`Merges with conflicts are not supported yet.`);
        this.code = this.name = _MergeNotSupportedError.code;
        this.data = {};
      }
    };
    MergeNotSupportedError.code = "MergeNotSupportedError";
    var MergeConflictError = class _MergeConflictError extends BaseError {
      /**
       * @param {Array<string>} filepaths
       * @param {Array<string>} bothModified
       * @param {Array<string>} deleteByUs
       * @param {Array<string>} deleteByTheirs
       */
      constructor(filepaths, bothModified, deleteByUs, deleteByTheirs) {
        super(
          `Automatic merge failed with one or more merge conflicts in the following files: ${filepaths.toString()}. Fix conflicts then commit the result.`
        );
        this.code = this.name = _MergeConflictError.code;
        this.data = { filepaths, bothModified, deleteByUs, deleteByTheirs };
      }
    };
    MergeConflictError.code = "MergeConflictError";
    var MissingNameError = class _MissingNameError extends BaseError {
      /**
       * @param {'author'|'committer'|'tagger'} role
       */
      constructor(role) {
        super(
          `No name was provided for ${role} in the argument or in the .git/config file.`
        );
        this.code = this.name = _MissingNameError.code;
        this.data = { role };
      }
    };
    MissingNameError.code = "MissingNameError";
    var MissingParameterError = class _MissingParameterError extends BaseError {
      /**
       * @param {string} parameter
       */
      constructor(parameter) {
        super(
          `The function requires a "${parameter}" parameter but none was provided.`
        );
        this.code = this.name = _MissingParameterError.code;
        this.data = { parameter };
      }
    };
    MissingParameterError.code = "MissingParameterError";
    var MultipleGitError = class _MultipleGitError extends BaseError {
      /**
       * @param {Error[]} errors
       * @param {string} message
       */
      constructor(errors) {
        super(
          `There are multiple errors that were thrown by the method. Please refer to the "errors" property to see more`
        );
        this.code = this.name = _MultipleGitError.code;
        this.data = { errors };
        this.errors = errors;
      }
    };
    MultipleGitError.code = "MultipleGitError";
    var ParseError = class _ParseError extends BaseError {
      /**
       * @param {string} expected
       * @param {string} actual
       */
      constructor(expected, actual) {
        super(`Expected "${expected}" but received "${actual}".`);
        this.code = this.name = _ParseError.code;
        this.data = { expected, actual };
      }
    };
    ParseError.code = "ParseError";
    var PushRejectedError = class _PushRejectedError extends BaseError {
      /**
       * @param {'not-fast-forward'|'tag-exists'} reason
       */
      constructor(reason) {
        let message = "";
        if (reason === "not-fast-forward") {
          message = " because it was not a simple fast-forward";
        } else if (reason === "tag-exists") {
          message = " because tag already exists";
        }
        super(`Push rejected${message}. Use "force: true" to override.`);
        this.code = this.name = _PushRejectedError.code;
        this.data = { reason };
      }
    };
    PushRejectedError.code = "PushRejectedError";
    var RemoteCapabilityError = class _RemoteCapabilityError extends BaseError {
      /**
       * @param {'shallow'|'deepen-since'|'deepen-not'|'deepen-relative'} capability
       * @param {'depth'|'since'|'exclude'|'relative'} parameter
       */
      constructor(capability, parameter) {
        super(
          `Remote does not support the "${capability}" so the "${parameter}" parameter cannot be used.`
        );
        this.code = this.name = _RemoteCapabilityError.code;
        this.data = { capability, parameter };
      }
    };
    RemoteCapabilityError.code = "RemoteCapabilityError";
    var SmartHttpError = class _SmartHttpError extends BaseError {
      /**
       * @param {string} preview
       * @param {string} response
       */
      constructor(preview, response) {
        super(
          `Remote did not reply using the "smart" HTTP protocol. Expected "001e# service=git-upload-pack" but received: ${preview}`
        );
        this.code = this.name = _SmartHttpError.code;
        this.data = { preview, response };
      }
    };
    SmartHttpError.code = "SmartHttpError";
    var UnknownTransportError = class _UnknownTransportError extends BaseError {
      /**
       * @param {string} url
       * @param {string} transport
       * @param {string} [suggestion]
       */
      constructor(url, transport, suggestion) {
        super(
          `Git remote "${url}" uses an unrecognized transport protocol: "${transport}"`
        );
        this.code = this.name = _UnknownTransportError.code;
        this.data = { url, transport, suggestion };
      }
    };
    UnknownTransportError.code = "UnknownTransportError";
    var UrlParseError = class _UrlParseError extends BaseError {
      /**
       * @param {string} url
       */
      constructor(url) {
        super(`Cannot parse remote URL: "${url}"`);
        this.code = this.name = _UrlParseError.code;
        this.data = { url };
      }
    };
    UrlParseError.code = "UrlParseError";
    var UserCanceledError = class _UserCanceledError extends BaseError {
      constructor() {
        super(`The operation was canceled.`);
        this.code = this.name = _UserCanceledError.code;
        this.data = {};
      }
    };
    UserCanceledError.code = "UserCanceledError";
    var IndexResetError = class _IndexResetError extends BaseError {
      /**
       * @param {Array<string>} filepaths
       */
      constructor(filepath) {
        super(
          `Could not merge index: Entry for '${filepath}' is not up to date. Either reset the index entry to HEAD, or stage your unstaged changes.`
        );
        this.code = this.name = _IndexResetError.code;
        this.data = { filepath };
      }
    };
    IndexResetError.code = "IndexResetError";
    var NoCommitError = class _NoCommitError extends BaseError {
      /**
       * @param {string} ref
       */
      constructor(ref) {
        super(
          `"${ref}" does not point to any commit. You're maybe working on a repository with no commits yet. `
        );
        this.code = this.name = _NoCommitError.code;
        this.data = { ref };
      }
    };
    NoCommitError.code = "NoCommitError";
    var Errors = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      AlreadyExistsError,
      AmbiguousError,
      CheckoutConflictError,
      CommitNotFetchedError,
      EmptyServerResponseError,
      FastForwardError,
      GitPushError,
      HttpError,
      InternalError,
      InvalidFilepathError,
      InvalidOidError,
      InvalidRefNameError,
      MaxDepthError,
      MergeNotSupportedError,
      MergeConflictError,
      MissingNameError,
      MissingParameterError,
      MultipleGitError,
      NoRefspecError,
      NotFoundError,
      ObjectTypeError,
      ParseError,
      PushRejectedError,
      RemoteCapabilityError,
      SmartHttpError,
      UnknownTransportError,
      UnsafeFilepathError,
      UrlParseError,
      UserCanceledError,
      UnmergedPathsError,
      IndexResetError,
      NoCommitError
    });
    function formatAuthor({ name, email, timestamp, timezoneOffset }) {
      timezoneOffset = formatTimezoneOffset(timezoneOffset);
      return `${name} <${email}> ${timestamp} ${timezoneOffset}`;
    }
    function formatTimezoneOffset(minutes) {
      const sign = simpleSign(negateExceptForZero(minutes));
      minutes = Math.abs(minutes);
      const hours = Math.floor(minutes / 60);
      minutes -= hours * 60;
      let strHours = String(hours);
      let strMinutes = String(minutes);
      if (strHours.length < 2) strHours = "0" + strHours;
      if (strMinutes.length < 2) strMinutes = "0" + strMinutes;
      return (sign === -1 ? "-" : "+") + strHours + strMinutes;
    }
    function simpleSign(n2) {
      return Math.sign(n2) || (Object.is(n2, -0) ? -1 : 1);
    }
    function negateExceptForZero(n2) {
      return n2 === 0 ? n2 : -n2;
    }
    function normalizeNewlines(str) {
      str = str.replace(/\r/g, "");
      str = str.replace(/^\n+/, "");
      str = str.replace(/\n+$/, "") + "\n";
      return str;
    }
    function parseAuthor(author) {
      const [, name, email, timestamp, offset2] = author.match(
        /^(.*) <(.*)> (.*) (.*)$/
      );
      return {
        name,
        email,
        timestamp: Number(timestamp),
        timezoneOffset: parseTimezoneOffset(offset2)
      };
    }
    function parseTimezoneOffset(offset2) {
      let [, sign, hours, minutes] = offset2.match(/(\+|-)(\d\d)(\d\d)/);
      minutes = (sign === "+" ? 1 : -1) * (Number(hours) * 60 + Number(minutes));
      return negateExceptForZero$1(minutes);
    }
    function negateExceptForZero$1(n2) {
      return n2 === 0 ? n2 : -n2;
    }
    var GitAnnotatedTag = class _GitAnnotatedTag {
      constructor(tag2) {
        if (typeof tag2 === "string") {
          this._tag = tag2;
        } else if (Buffer.isBuffer(tag2)) {
          this._tag = tag2.toString("utf8");
        } else if (typeof tag2 === "object") {
          this._tag = _GitAnnotatedTag.render(tag2);
        } else {
          throw new InternalError(
            "invalid type passed to GitAnnotatedTag constructor"
          );
        }
      }
      static from(tag2) {
        return new _GitAnnotatedTag(tag2);
      }
      static render(obj) {
        return `object ${obj.object}
type ${obj.type}
tag ${obj.tag}
tagger ${formatAuthor(obj.tagger)}

${obj.message}
${obj.gpgsig ? obj.gpgsig : ""}`;
      }
      justHeaders() {
        return this._tag.slice(0, this._tag.indexOf("\n\n"));
      }
      message() {
        const tag2 = this.withoutSignature();
        return tag2.slice(tag2.indexOf("\n\n") + 2);
      }
      parse() {
        return Object.assign(this.headers(), {
          message: this.message(),
          gpgsig: this.gpgsig()
        });
      }
      render() {
        return this._tag;
      }
      headers() {
        const headers = this.justHeaders().split("\n");
        const hs = [];
        for (const h of headers) {
          if (h[0] === " ") {
            hs[hs.length - 1] += "\n" + h.slice(1);
          } else {
            hs.push(h);
          }
        }
        const obj = {};
        for (const h of hs) {
          const key = h.slice(0, h.indexOf(" "));
          const value = h.slice(h.indexOf(" ") + 1);
          if (Array.isArray(obj[key])) {
            obj[key].push(value);
          } else {
            obj[key] = value;
          }
        }
        if (obj.tagger) {
          obj.tagger = parseAuthor(obj.tagger);
        }
        if (obj.committer) {
          obj.committer = parseAuthor(obj.committer);
        }
        return obj;
      }
      withoutSignature() {
        const tag2 = normalizeNewlines(this._tag);
        if (tag2.indexOf("\n-----BEGIN PGP SIGNATURE-----") === -1) return tag2;
        return tag2.slice(0, tag2.lastIndexOf("\n-----BEGIN PGP SIGNATURE-----"));
      }
      gpgsig() {
        if (this._tag.indexOf("\n-----BEGIN PGP SIGNATURE-----") === -1) return;
        const signature = this._tag.slice(
          this._tag.indexOf("-----BEGIN PGP SIGNATURE-----"),
          this._tag.indexOf("-----END PGP SIGNATURE-----") + "-----END PGP SIGNATURE-----".length
        );
        return normalizeNewlines(signature);
      }
      payload() {
        return this.withoutSignature() + "\n";
      }
      toObject() {
        return Buffer.from(this._tag, "utf8");
      }
      static async sign(tag2, sign, secretKey) {
        const payload = tag2.payload();
        let { signature } = await sign({ payload, secretKey });
        signature = normalizeNewlines(signature);
        const signedTag = payload + signature;
        return _GitAnnotatedTag.from(signedTag);
      }
    };
    function indent(str) {
      return str.trim().split("\n").map((x) => " " + x).join("\n") + "\n";
    }
    function outdent(str) {
      return str.split("\n").map((x) => x.replace(/^ /, "")).join("\n");
    }
    var GitCommit = class _GitCommit {
      constructor(commit2) {
        if (typeof commit2 === "string") {
          this._commit = commit2;
        } else if (Buffer.isBuffer(commit2)) {
          this._commit = commit2.toString("utf8");
        } else if (typeof commit2 === "object") {
          this._commit = _GitCommit.render(commit2);
        } else {
          throw new InternalError("invalid type passed to GitCommit constructor");
        }
      }
      static fromPayloadSignature({ payload, signature }) {
        const headers = _GitCommit.justHeaders(payload);
        const message = _GitCommit.justMessage(payload);
        const commit2 = normalizeNewlines(
          headers + "\ngpgsig" + indent(signature) + "\n" + message
        );
        return new _GitCommit(commit2);
      }
      static from(commit2) {
        return new _GitCommit(commit2);
      }
      toObject() {
        return Buffer.from(this._commit, "utf8");
      }
      // Todo: allow setting the headers and message
      headers() {
        return this.parseHeaders();
      }
      // Todo: allow setting the headers and message
      message() {
        return _GitCommit.justMessage(this._commit);
      }
      parse() {
        return Object.assign({ message: this.message() }, this.headers());
      }
      static justMessage(commit2) {
        return normalizeNewlines(commit2.slice(commit2.indexOf("\n\n") + 2));
      }
      static justHeaders(commit2) {
        return commit2.slice(0, commit2.indexOf("\n\n"));
      }
      parseHeaders() {
        const headers = _GitCommit.justHeaders(this._commit).split("\n");
        const hs = [];
        for (const h of headers) {
          if (h[0] === " ") {
            hs[hs.length - 1] += "\n" + h.slice(1);
          } else {
            hs.push(h);
          }
        }
        const obj = {
          parent: []
        };
        for (const h of hs) {
          const key = h.slice(0, h.indexOf(" "));
          const value = h.slice(h.indexOf(" ") + 1);
          if (Array.isArray(obj[key])) {
            obj[key].push(value);
          } else {
            obj[key] = value;
          }
        }
        if (obj.author) {
          obj.author = parseAuthor(obj.author);
        }
        if (obj.committer) {
          obj.committer = parseAuthor(obj.committer);
        }
        return obj;
      }
      static renderHeaders(obj) {
        let headers = "";
        if (obj.tree) {
          headers += `tree ${obj.tree}
`;
        } else {
          headers += `tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904
`;
        }
        if (obj.parent) {
          if (obj.parent.length === void 0) {
            throw new InternalError(`commit 'parent' property should be an array`);
          }
          for (const p of obj.parent) {
            headers += `parent ${p}
`;
          }
        }
        const author = obj.author;
        headers += `author ${formatAuthor(author)}
`;
        const committer = obj.committer || obj.author;
        headers += `committer ${formatAuthor(committer)}
`;
        if (obj.gpgsig) {
          headers += "gpgsig" + indent(obj.gpgsig);
        }
        return headers;
      }
      static render(obj) {
        return _GitCommit.renderHeaders(obj) + "\n" + normalizeNewlines(obj.message);
      }
      render() {
        return this._commit;
      }
      withoutSignature() {
        const commit2 = normalizeNewlines(this._commit);
        if (commit2.indexOf("\ngpgsig") === -1) return commit2;
        const headers = commit2.slice(0, commit2.indexOf("\ngpgsig"));
        const message = commit2.slice(
          commit2.indexOf("-----END PGP SIGNATURE-----\n") + "-----END PGP SIGNATURE-----\n".length
        );
        return normalizeNewlines(headers + "\n" + message);
      }
      isolateSignature() {
        const signature = this._commit.slice(
          this._commit.indexOf("-----BEGIN PGP SIGNATURE-----"),
          this._commit.indexOf("-----END PGP SIGNATURE-----") + "-----END PGP SIGNATURE-----".length
        );
        return outdent(signature);
      }
      static async sign(commit2, sign, secretKey) {
        const payload = commit2.withoutSignature();
        const message = _GitCommit.justMessage(commit2._commit);
        let { signature } = await sign({ payload, secretKey });
        signature = normalizeNewlines(signature);
        const headers = _GitCommit.justHeaders(commit2._commit);
        const signedCommit = headers + "\ngpgsig" + indent(signature) + "\n" + message;
        return _GitCommit.from(signedCommit);
      }
    };
    async function resolveTree({ fs: fs2, cache, gitdir, oid }) {
      if (oid === "4b825dc642cb6eb9a060e54bf8d69288fbee4904") {
        return { tree: GitTree.from([]), oid };
      }
      const { type, object } = await _readObject({ fs: fs2, cache, gitdir, oid });
      if (type === "tag") {
        oid = GitAnnotatedTag.from(object).parse().object;
        return resolveTree({ fs: fs2, cache, gitdir, oid });
      }
      if (type === "commit") {
        oid = GitCommit.from(object).parse().tree;
        return resolveTree({ fs: fs2, cache, gitdir, oid });
      }
      if (type !== "tree") {
        throw new ObjectTypeError(oid, type, "tree");
      }
      return { tree: GitTree.from(object), oid };
    }
    var GitWalkerRepo = class {
      constructor({ fs: fs2, gitdir, ref, cache }) {
        this.fs = fs2;
        this.cache = cache;
        this.gitdir = gitdir;
        this.mapPromise = (async () => {
          const map = /* @__PURE__ */ new Map();
          let oid;
          try {
            oid = await GitRefManager.resolve({ fs: fs2, gitdir, ref });
          } catch (e) {
            if (e instanceof NotFoundError) {
              oid = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
            }
          }
          const tree = await resolveTree({ fs: fs2, cache: this.cache, gitdir, oid });
          tree.type = "tree";
          tree.mode = "40000";
          map.set(".", tree);
          return map;
        })();
        const walker = this;
        this.ConstructEntry = class TreeEntry {
          constructor(fullpath) {
            this._fullpath = fullpath;
            this._type = false;
            this._mode = false;
            this._stat = false;
            this._content = false;
            this._oid = false;
          }
          async type() {
            return walker.type(this);
          }
          async mode() {
            return walker.mode(this);
          }
          async stat() {
            return walker.stat(this);
          }
          async content() {
            return walker.content(this);
          }
          async oid() {
            return walker.oid(this);
          }
        };
      }
      async readdir(entry) {
        const filepath = entry._fullpath;
        const { fs: fs2, cache, gitdir } = this;
        const map = await this.mapPromise;
        const obj = map.get(filepath);
        if (!obj) throw new Error(`No obj for ${filepath}`);
        const oid = obj.oid;
        if (!oid) throw new Error(`No oid for obj ${JSON.stringify(obj)}`);
        if (obj.type !== "tree") {
          return null;
        }
        const { type, object } = await _readObject({ fs: fs2, cache, gitdir, oid });
        if (type !== obj.type) {
          throw new ObjectTypeError(oid, type, obj.type);
        }
        const tree = GitTree.from(object);
        for (const entry2 of tree) {
          map.set(join(filepath, entry2.path), entry2);
        }
        return tree.entries().map((entry2) => join(filepath, entry2.path));
      }
      async type(entry) {
        if (entry._type === false) {
          const map = await this.mapPromise;
          const { type } = map.get(entry._fullpath);
          entry._type = type;
        }
        return entry._type;
      }
      async mode(entry) {
        if (entry._mode === false) {
          const map = await this.mapPromise;
          const { mode } = map.get(entry._fullpath);
          entry._mode = normalizeMode(parseInt(mode, 8));
        }
        return entry._mode;
      }
      async stat(_entry) {
      }
      async content(entry) {
        if (entry._content === false) {
          const map = await this.mapPromise;
          const { fs: fs2, cache, gitdir } = this;
          const obj = map.get(entry._fullpath);
          const oid = obj.oid;
          const { type, object } = await _readObject({ fs: fs2, cache, gitdir, oid });
          if (type !== "blob") {
            entry._content = void 0;
          } else {
            entry._content = new Uint8Array(object);
          }
        }
        return entry._content;
      }
      async oid(entry) {
        if (entry._oid === false) {
          const map = await this.mapPromise;
          const obj = map.get(entry._fullpath);
          entry._oid = obj.oid;
        }
        return entry._oid;
      }
    };
    function TREE({ ref = "HEAD" } = {}) {
      const o = /* @__PURE__ */ Object.create(null);
      Object.defineProperty(o, GitWalkSymbol, {
        value: function({ fs: fs2, gitdir, cache }) {
          return new GitWalkerRepo({ fs: fs2, gitdir, ref, cache });
        }
      });
      Object.freeze(o);
      return o;
    }
    var GitWalkerFs = class {
      constructor({ fs: fs2, dir, gitdir, cache }) {
        this.fs = fs2;
        this.cache = cache;
        this.dir = dir;
        this.gitdir = gitdir;
        this.config = null;
        const walker = this;
        this.ConstructEntry = class WorkdirEntry {
          constructor(fullpath) {
            this._fullpath = fullpath;
            this._type = false;
            this._mode = false;
            this._stat = false;
            this._content = false;
            this._oid = false;
          }
          async type() {
            return walker.type(this);
          }
          async mode() {
            return walker.mode(this);
          }
          async stat() {
            return walker.stat(this);
          }
          async content() {
            return walker.content(this);
          }
          async oid() {
            return walker.oid(this);
          }
        };
      }
      async readdir(entry) {
        const filepath = entry._fullpath;
        const { fs: fs2, dir } = this;
        const names = await fs2.readdir(join(dir, filepath));
        if (names === null) return null;
        return names.map((name) => join(filepath, name));
      }
      async type(entry) {
        if (entry._type === false) {
          await entry.stat();
        }
        return entry._type;
      }
      async mode(entry) {
        if (entry._mode === false) {
          await entry.stat();
        }
        return entry._mode;
      }
      async stat(entry) {
        if (entry._stat === false) {
          const { fs: fs2, dir } = this;
          let stat = await fs2.lstat(`${dir}/${entry._fullpath}`);
          if (!stat) {
            throw new Error(
              `ENOENT: no such file or directory, lstat '${entry._fullpath}'`
            );
          }
          let type = stat.isDirectory() ? "tree" : "blob";
          if (type === "blob" && !stat.isFile() && !stat.isSymbolicLink()) {
            type = "special";
          }
          entry._type = type;
          stat = normalizeStats(stat);
          entry._mode = stat.mode;
          if (stat.size === -1 && entry._actualSize) {
            stat.size = entry._actualSize;
          }
          entry._stat = stat;
        }
        return entry._stat;
      }
      async content(entry) {
        if (entry._content === false) {
          const { fs: fs2, dir, gitdir } = this;
          if (await entry.type() === "tree") {
            entry._content = void 0;
          } else {
            const config = await this._getGitConfig(fs2, gitdir);
            const autocrlf = await config.get("core.autocrlf");
            const content = await fs2.read(`${dir}/${entry._fullpath}`, { autocrlf });
            entry._actualSize = content.length;
            if (entry._stat && entry._stat.size === -1) {
              entry._stat.size = entry._actualSize;
            }
            entry._content = new Uint8Array(content);
          }
        }
        return entry._content;
      }
      async oid(entry) {
        if (entry._oid === false) {
          const self2 = this;
          const { fs: fs2, gitdir, cache } = this;
          let oid;
          await GitIndexManager.acquire(
            { fs: fs2, gitdir, cache },
            async function(index2) {
              const stage = index2.entriesMap.get(entry._fullpath);
              const stats = await entry.stat();
              const config = await self2._getGitConfig(fs2, gitdir);
              const filemode = await config.get("core.filemode");
              const trustino = typeof process !== "undefined" ? !(process.platform === "win32") : true;
              if (!stage || compareStats(stats, stage, filemode, trustino)) {
                const content = await entry.content();
                if (content === void 0) {
                  oid = void 0;
                } else {
                  oid = await shasum(
                    GitObject.wrap({ type: "blob", object: content })
                  );
                  if (stage && oid === stage.oid && (!filemode || stats.mode === stage.mode) && compareStats(stats, stage, filemode, trustino)) {
                    index2.insert({
                      filepath: entry._fullpath,
                      stats,
                      oid
                    });
                  }
                }
              } else {
                oid = stage.oid;
              }
            }
          );
          entry._oid = oid;
        }
        return entry._oid;
      }
      async _getGitConfig(fs2, gitdir) {
        if (this.config) {
          return this.config;
        }
        this.config = await GitConfigManager.get({ fs: fs2, gitdir });
        return this.config;
      }
    };
    function WORKDIR() {
      const o = /* @__PURE__ */ Object.create(null);
      Object.defineProperty(o, GitWalkSymbol, {
        value: function({ fs: fs2, dir, gitdir, cache }) {
          return new GitWalkerFs({ fs: fs2, dir, gitdir, cache });
        }
      });
      Object.freeze(o);
      return o;
    }
    function arrayRange(start, end) {
      const length = end - start;
      return Array.from({ length }, (_, i) => start + i);
    }
    var flat = typeof Array.prototype.flat === "undefined" ? (entries) => entries.reduce((acc, x) => acc.concat(x), []) : (entries) => entries.flat();
    var RunningMinimum = class {
      constructor() {
        this.value = null;
      }
      consider(value) {
        if (value === null || value === void 0) return;
        if (this.value === null) {
          this.value = value;
        } else if (value < this.value) {
          this.value = value;
        }
      }
      reset() {
        this.value = null;
      }
    };
    function* unionOfIterators(sets) {
      const min = new RunningMinimum();
      let minimum;
      const heads = [];
      const numsets = sets.length;
      for (let i = 0; i < numsets; i++) {
        heads[i] = sets[i].next().value;
        if (heads[i] !== void 0) {
          min.consider(heads[i]);
        }
      }
      if (min.value === null) return;
      while (true) {
        const result = [];
        minimum = min.value;
        min.reset();
        for (let i = 0; i < numsets; i++) {
          if (heads[i] !== void 0 && heads[i] === minimum) {
            result[i] = heads[i];
            heads[i] = sets[i].next().value;
          } else {
            result[i] = null;
          }
          if (heads[i] !== void 0) {
            min.consider(heads[i]);
          }
        }
        yield result;
        if (min.value === null) return;
      }
    }
    async function _walk({
      fs: fs2,
      cache,
      dir,
      gitdir,
      trees,
      // @ts-ignore
      map = async (_, entry) => entry,
      // The default reducer is a flatmap that filters out undefineds.
      reduce = async (parent, children2) => {
        const flatten = flat(children2);
        if (parent !== void 0) flatten.unshift(parent);
        return flatten;
      },
      // The default iterate function walks all children concurrently
      iterate = (walk2, children2) => Promise.all([...children2].map(walk2))
    }) {
      const walkers = trees.map(
        (proxy) => proxy[GitWalkSymbol]({ fs: fs2, dir, gitdir, cache })
      );
      const root = new Array(walkers.length).fill(".");
      const range = arrayRange(0, walkers.length);
      const unionWalkerFromReaddir = async (entries) => {
        range.forEach((i) => {
          const entry = entries[i];
          entries[i] = entry && new walkers[i].ConstructEntry(entry);
        });
        const subdirs = await Promise.all(
          range.map((i) => {
            const entry = entries[i];
            return entry ? walkers[i].readdir(entry) : [];
          })
        );
        const iterators = subdirs.map((array) => {
          return (array === null ? [] : array)[Symbol.iterator]();
        });
        return {
          entries,
          children: unionOfIterators(iterators)
        };
      };
      const walk2 = async (root2) => {
        const { entries, children: children2 } = await unionWalkerFromReaddir(root2);
        const fullpath = entries.find((entry) => entry && entry._fullpath)._fullpath;
        const parent = await map(fullpath, entries);
        if (parent !== null) {
          let walkedChildren = await iterate(walk2, children2);
          walkedChildren = walkedChildren.filter((x) => x !== void 0);
          return reduce(parent, walkedChildren);
        }
      };
      return walk2(root);
    }
    async function rmRecursive(fs2, filepath) {
      const entries = await fs2.readdir(filepath);
      if (entries == null) {
        await fs2.rm(filepath);
      } else if (entries.length) {
        await Promise.all(
          entries.map((entry) => {
            const subpath = join(filepath, entry);
            return fs2.lstat(subpath).then((stat) => {
              if (!stat) return;
              return stat.isDirectory() ? rmRecursive(fs2, subpath) : fs2.rm(subpath);
            });
          })
        ).then(() => fs2.rmdir(filepath));
      } else {
        await fs2.rmdir(filepath);
      }
    }
    function isPromiseLike(obj) {
      return isObject(obj) && isFunction(obj.then) && isFunction(obj.catch);
    }
    function isObject(obj) {
      return obj && typeof obj === "object";
    }
    function isFunction(obj) {
      return typeof obj === "function";
    }
    function isPromiseFs(fs2) {
      const test = (targetFs) => {
        try {
          return targetFs.readFile().catch((e) => e);
        } catch (e) {
          return e;
        }
      };
      return isPromiseLike(test(fs2));
    }
    var commands = [
      "readFile",
      "writeFile",
      "mkdir",
      "rmdir",
      "unlink",
      "stat",
      "lstat",
      "readdir",
      "readlink",
      "symlink"
    ];
    function bindFs(target, fs2) {
      if (isPromiseFs(fs2)) {
        for (const command of commands) {
          target[`_${command}`] = fs2[command].bind(fs2);
        }
      } else {
        for (const command of commands) {
          target[`_${command}`] = pify(fs2[command].bind(fs2));
        }
      }
      if (isPromiseFs(fs2)) {
        if (fs2.cp) target._cp = fs2.cp.bind(fs2);
        if (fs2.rm) target._rm = fs2.rm.bind(fs2);
        else if (fs2.rmdir.length > 1) target._rm = fs2.rmdir.bind(fs2);
        else target._rm = rmRecursive.bind(null, target);
      } else {
        if (fs2.cp) target._cp = pify(fs2.cp.bind(fs2));
        if (fs2.rm) target._rm = pify(fs2.rm.bind(fs2));
        else if (fs2.rmdir.length > 2) target._rm = pify(fs2.rmdir.bind(fs2));
        else target._rm = rmRecursive.bind(null, target);
      }
    }
    var FileSystem = class {
      /**
       * Creates an instance of FileSystem.
       *
       * @param {Object} fs - A file system implementation to wrap.
       */
      constructor(fs2) {
        if (typeof fs2._original_unwrapped_fs !== "undefined") return fs2;
        const promises = Object.getOwnPropertyDescriptor(fs2, "promises");
        if (promises && promises.enumerable) {
          bindFs(this, fs2.promises);
        } else {
          bindFs(this, fs2);
        }
        this._original_unwrapped_fs = fs2;
      }
      /**
       * Return true if a file exists, false if it doesn't exist.
       * Rethrows errors that aren't related to file existence.
       *
       * @param {string} filepath - The path to the file.
       * @param {Object} [options] - Additional options.
       * @returns {Promise<boolean>} - `true` if the file exists, `false` otherwise.
       */
      async exists(filepath, options = {}) {
        try {
          await this._stat(filepath);
          return true;
        } catch (err) {
          if (err.code === "ENOENT" || err.code === "ENOTDIR" || (err.code || "").includes("ENS")) {
            return false;
          } else {
            console.log('Unhandled error in "FileSystem.exists()" function', err);
            throw err;
          }
        }
      }
      /**
       * Return the contents of a file if it exists, otherwise returns null.
       *
       * @param {string} filepath - The path to the file.
       * @param {Object} [options] - Options for reading the file.
       * @returns {Promise<Buffer|string|null>} - The file contents, or `null` if the file doesn't exist.
       */
      async read(filepath, options = {}) {
        try {
          let buffer = await this._readFile(filepath, options);
          if (options.autocrlf === "true") {
            try {
              buffer = new TextDecoder("utf8", { fatal: true }).decode(buffer);
              buffer = buffer.replace(/\r\n/g, "\n");
              buffer = new TextEncoder().encode(buffer);
            } catch (error) {
            }
          }
          if (typeof buffer !== "string") {
            buffer = Buffer.from(buffer);
          }
          return buffer;
        } catch (err) {
          return null;
        }
      }
      /**
       * Write a file (creating missing directories if need be) without throwing errors.
       *
       * @param {string} filepath - The path to the file.
       * @param {Buffer|Uint8Array|string} contents - The data to write.
       * @param {Object|string} [options] - Options for writing the file.
       * @returns {Promise<void>}
       */
      async write(filepath, contents, options = {}) {
        try {
          await this._writeFile(filepath, contents, options);
        } catch (err) {
          await this.mkdir(dirname(filepath));
          await this._writeFile(filepath, contents, options);
        }
      }
      /**
       * Make a directory (or series of nested directories) without throwing an error if it already exists.
       *
       * @param {string} filepath - The path to the directory.
       * @param {boolean} [_selfCall=false] - Internal flag to prevent infinite recursion.
       * @returns {Promise<void>}
       */
      async mkdir(filepath, _selfCall = false) {
        try {
          await this._mkdir(filepath);
        } catch (err) {
          if (err === null) return;
          if (err.code === "EEXIST") return;
          if (_selfCall) throw err;
          if (err.code === "ENOENT") {
            const parent = dirname(filepath);
            if (parent === "." || parent === "/" || parent === filepath) throw err;
            await this.mkdir(parent);
            await this.mkdir(filepath, true);
          }
        }
      }
      /**
       * Delete a file without throwing an error if it is already deleted.
       *
       * @param {string} filepath - The path to the file.
       * @returns {Promise<void>}
       */
      async rm(filepath) {
        try {
          await this._unlink(filepath);
        } catch (err) {
          if (err.code !== "ENOENT") throw err;
        }
      }
      /**
       * Delete a directory without throwing an error if it is already deleted.
       *
       * @param {string} filepath - The path to the directory.
       * @param {Object} [opts] - Options for deleting the directory.
       * @returns {Promise<void>}
       */
      async rmdir(filepath, opts) {
        try {
          if (opts && opts.recursive) {
            await this._rm(filepath, opts);
          } else {
            await this._rmdir(filepath);
          }
        } catch (err) {
          if (err.code !== "ENOENT") throw err;
        }
      }
      /**
       * Read a directory without throwing an error is the directory doesn't exist
       *
       * @param {string} filepath - The path to the directory.
       * @returns {Promise<string[]|null>} - An array of file names, or `null` if the path is not a directory.
       */
      async readdir(filepath) {
        try {
          const names = await this._readdir(filepath);
          names.sort(compareStrings);
          return names;
        } catch (err) {
          if (err.code === "ENOTDIR") return null;
          return [];
        }
      }
      /**
       * Return a flat list of all the files nested inside a directory
       *
       * Based on an elegant concurrent recursive solution from SO
       * https://stackoverflow.com/a/45130990/2168416
       *
       * @param {string} dir - The directory to read.
       * @returns {Promise<string[]>} - A flat list of all files in the directory.
       */
      async readdirDeep(dir) {
        const subdirs = await this._readdir(dir);
        const files = await Promise.all(
          subdirs.map(async (subdir) => {
            const res = dir + "/" + subdir;
            return (await this._stat(res)).isDirectory() ? this.readdirDeep(res) : res;
          })
        );
        return files.reduce((a, f) => a.concat(f), []);
      }
      /**
       * Return the Stats of a file/symlink if it exists, otherwise returns null.
       * Rethrows errors that aren't related to file existence.
       *
       * @param {string} filename - The path to the file or symlink.
       * @returns {Promise<Object|null>} - The stats object, or `null` if the file doesn't exist.
       */
      async lstat(filename) {
        try {
          const stats = await this._lstat(filename);
          return stats;
        } catch (err) {
          if (err.code === "ENOENT" || (err.code || "").includes("ENS")) {
            return null;
          }
          throw err;
        }
      }
      /**
       * Reads the contents of a symlink if it exists, otherwise returns null.
       * Rethrows errors that aren't related to file existence.
       *
       * @param {string} filename - The path to the symlink.
       * @param {Object} [opts={ encoding: 'buffer' }] - Options for reading the symlink.
       * @returns {Promise<Buffer|null>} - The symlink target, or `null` if it doesn't exist.
       */
      async readlink(filename, opts = { encoding: "buffer" }) {
        try {
          const link = await this._readlink(filename, opts);
          return Buffer.isBuffer(link) ? link : Buffer.from(link);
        } catch (err) {
          if (err.code === "ENOENT" || (err.code || "").includes("ENS")) {
            return null;
          }
          throw err;
        }
      }
      /**
       * Write the contents of buffer to a symlink.
       *
       * @param {string} filename - The path to the symlink.
       * @param {Buffer} buffer - The symlink target.
       * @returns {Promise<void>}
       */
      async writelink(filename, buffer) {
        return this._symlink(buffer.toString("utf8"), filename);
      }
    };
    function assertParameter(name, value) {
      if (value === void 0) {
        throw new MissingParameterError(name);
      }
    }
    async function discoverGitdir({ fsp, dotgit }) {
      assertParameter("fsp", fsp);
      assertParameter("dotgit", dotgit);
      const dotgitStat = await fsp._stat(dotgit).catch(() => ({ isFile: () => false, isDirectory: () => false }));
      if (dotgitStat.isDirectory()) {
        return dotgit;
      } else if (dotgitStat.isFile()) {
        return fsp._readFile(dotgit, "utf8").then((contents) => contents.trimRight().substr(8)).then((submoduleGitdir) => {
          const gitdir = join(dirname(dotgit), submoduleGitdir);
          return gitdir;
        });
      } else {
        return dotgit;
      }
    }
    async function modified(entry, base) {
      if (!entry && !base) return false;
      if (entry && !base) return true;
      if (!entry && base) return true;
      if (await entry.type() === "tree" && await base.type() === "tree") {
        return false;
      }
      if (await entry.type() === await base.type() && await entry.mode() === await base.mode() && await entry.oid() === await base.oid()) {
        return false;
      }
      return true;
    }
    async function abortMerge({
      fs: _fs,
      dir,
      gitdir = join(dir, ".git"),
      commit: commit2 = "HEAD",
      cache = {}
    }) {
      try {
        assertParameter("fs", _fs);
        assertParameter("dir", dir);
        assertParameter("gitdir", gitdir);
        const fs2 = new FileSystem(_fs);
        const trees = [TREE({ ref: commit2 }), WORKDIR(), STAGE()];
        let unmergedPaths = [];
        const updatedGitdir = await discoverGitdir({ fsp: fs2, dotgit: gitdir });
        await GitIndexManager.acquire(
          { fs: fs2, gitdir: updatedGitdir, cache },
          async function(index2) {
            unmergedPaths = index2.unmergedPaths;
          }
        );
        const results = await _walk({
          fs: fs2,
          cache,
          dir,
          gitdir: updatedGitdir,
          trees,
          map: async function(path, [head, workdir, index2]) {
            const staged = !await modified(workdir, index2);
            const unmerged = unmergedPaths.includes(path);
            const unmodified = !await modified(index2, head);
            if (staged || unmerged) {
              return head ? {
                path,
                mode: await head.mode(),
                oid: await head.oid(),
                type: await head.type(),
                content: await head.content()
              } : void 0;
            }
            if (unmodified) return false;
            else throw new IndexResetError(path);
          }
        });
        await GitIndexManager.acquire(
          { fs: fs2, gitdir: updatedGitdir, cache },
          async function(index2) {
            for (const entry of results) {
              if (entry === false) continue;
              if (!entry) {
                await fs2.rmdir(`${dir}/${entry.path}`, { recursive: true });
                index2.delete({ filepath: entry.path });
                continue;
              }
              if (entry.type === "blob") {
                const content = new TextDecoder().decode(entry.content);
                await fs2.write(`${dir}/${entry.path}`, content, {
                  mode: entry.mode
                });
                index2.insert({
                  filepath: entry.path,
                  oid: entry.oid,
                  stage: 0
                });
              }
            }
          }
        );
      } catch (err) {
        err.caller = "git.abortMerge";
        throw err;
      }
    }
    var GitIgnoreManager = class {
      /**
       * Determines whether a given file is ignored based on `.gitignore` rules and exclusion files.
       *
       * @param {Object} args
       * @param {FSClient} args.fs - A file system implementation.
       * @param {string} args.dir - The working directory.
       * @param {string} [args.gitdir=join(dir, '.git')] - [required] The [git directory](dir-vs-gitdir.md) path
       * @param {string} args.filepath - The path of the file to check.
       * @returns {Promise<boolean>} - `true` if the file is ignored, `false` otherwise.
       */
      static async isIgnored({ fs: fs2, dir, gitdir = join(dir, ".git"), filepath }) {
        if (basename(filepath) === ".git") return true;
        if (filepath === ".") return false;
        let excludes = "";
        const excludesFile = join(gitdir, "info", "exclude");
        if (await fs2.exists(excludesFile)) {
          excludes = await fs2.read(excludesFile, "utf8");
        }
        const pairs = [
          {
            gitignore: join(dir, ".gitignore"),
            filepath
          }
        ];
        const pieces = filepath.split("/").filter(Boolean);
        for (let i = 1; i < pieces.length; i++) {
          const folder = pieces.slice(0, i).join("/");
          const file = pieces.slice(i).join("/");
          pairs.push({
            gitignore: join(dir, folder, ".gitignore"),
            filepath: file
          });
        }
        let ignoredStatus = false;
        for (const p of pairs) {
          let file;
          try {
            file = await fs2.read(p.gitignore, "utf8");
          } catch (err) {
            if (err.code === "NOENT") continue;
          }
          const ign = ignore().add(excludes);
          ign.add(file);
          const parentdir = dirname(p.filepath);
          if (parentdir !== "." && ign.ignores(parentdir)) return true;
          if (ignoredStatus) {
            ignoredStatus = !ign.test(p.filepath).unignored;
          } else {
            ignoredStatus = ign.test(p.filepath).ignored;
          }
        }
        return ignoredStatus;
      }
    };
    async function writeObjectLoose({ fs: fs2, gitdir, object, format, oid }) {
      if (format !== "deflated") {
        throw new InternalError(
          "GitObjectStoreLoose expects objects to write to be in deflated format"
        );
      }
      const source = `objects/${oid.slice(0, 2)}/${oid.slice(2)}`;
      const filepath = `${gitdir}/${source}`;
      if (!await fs2.exists(filepath)) await fs2.write(filepath, object);
    }
    var supportsCompressionStream = null;
    async function deflate(buffer) {
      if (supportsCompressionStream === null) {
        supportsCompressionStream = testCompressionStream();
      }
      return supportsCompressionStream ? browserDeflate(buffer) : pako.deflate(buffer);
    }
    async function browserDeflate(buffer) {
      const cs = new CompressionStream("deflate");
      const c = new Blob([buffer]).stream().pipeThrough(cs);
      return new Uint8Array(await new Response(c).arrayBuffer());
    }
    function testCompressionStream() {
      try {
        const cs = new CompressionStream("deflate");
        cs.writable.close();
        const stream = new Blob([]).stream();
        stream.cancel();
        return true;
      } catch (_) {
        return false;
      }
    }
    async function _writeObject({
      fs: fs2,
      gitdir,
      type,
      object,
      format = "content",
      oid = void 0,
      dryRun = false
    }) {
      if (format !== "deflated") {
        if (format !== "wrapped") {
          object = GitObject.wrap({ type, object });
        }
        oid = await shasum(object);
        object = Buffer.from(await deflate(object));
      }
      if (!dryRun) {
        await writeObjectLoose({ fs: fs2, gitdir, object, format: "deflated", oid });
      }
      return oid;
    }
    function posixifyPathBuffer(buffer) {
      let idx;
      while (~(idx = buffer.indexOf(92))) buffer[idx] = 47;
      return buffer;
    }
    async function add({
      fs: _fs,
      dir,
      gitdir = join(dir, ".git"),
      filepath,
      cache = {},
      force = false,
      parallel = true
    }) {
      try {
        assertParameter("fs", _fs);
        assertParameter("dir", dir);
        assertParameter("gitdir", gitdir);
        assertParameter("filepath", filepath);
        const fs2 = new FileSystem(_fs);
        const updatedGitdir = await discoverGitdir({ fsp: fs2, dotgit: gitdir });
        await GitIndexManager.acquire(
          { fs: fs2, gitdir: updatedGitdir, cache },
          async (index2) => {
            const config = await GitConfigManager.get({ fs: fs2, gitdir: updatedGitdir });
            const autocrlf = await config.get("core.autocrlf");
            return addToIndex({
              dir,
              gitdir: updatedGitdir,
              fs: fs2,
              filepath,
              index: index2,
              force,
              parallel,
              autocrlf
            });
          }
        );
      } catch (err) {
        err.caller = "git.add";
        throw err;
      }
    }
    async function addToIndex({
      dir,
      gitdir,
      fs: fs2,
      filepath,
      index: index2,
      force,
      parallel,
      autocrlf
    }) {
      filepath = Array.isArray(filepath) ? filepath : [filepath];
      const promises = filepath.map(async (currentFilepath) => {
        if (!force) {
          const ignored = await GitIgnoreManager.isIgnored({
            fs: fs2,
            dir,
            gitdir,
            filepath: currentFilepath
          });
          if (ignored) return;
        }
        const stats = await fs2.lstat(join(dir, currentFilepath));
        if (!stats) throw new NotFoundError(currentFilepath);
        if (stats.isDirectory()) {
          const children2 = await fs2.readdir(join(dir, currentFilepath));
          if (parallel) {
            const promises2 = children2.map(
              (child) => addToIndex({
                dir,
                gitdir,
                fs: fs2,
                filepath: [join(currentFilepath, child)],
                index: index2,
                force,
                parallel,
                autocrlf
              })
            );
            await Promise.all(promises2);
          } else {
            for (const child of children2) {
              await addToIndex({
                dir,
                gitdir,
                fs: fs2,
                filepath: [join(currentFilepath, child)],
                index: index2,
                force,
                parallel,
                autocrlf
              });
            }
          }
        } else {
          const object = stats.isSymbolicLink() ? await fs2.readlink(join(dir, currentFilepath)).then(posixifyPathBuffer) : await fs2.read(join(dir, currentFilepath), { autocrlf });
          if (object === null) throw new NotFoundError(currentFilepath);
          const oid = await _writeObject({ fs: fs2, gitdir, type: "blob", object });
          index2.insert({ filepath: currentFilepath, stats, oid });
        }
      });
      const settledPromises = await Promise.allSettled(promises);
      const rejectedPromises = settledPromises.filter((settle) => settle.status === "rejected").map((settle) => settle.reason);
      if (rejectedPromises.length > 1) {
        throw new MultipleGitError(rejectedPromises);
      }
      if (rejectedPromises.length === 1) {
        throw rejectedPromises[0];
      }
      const fulfilledPromises = settledPromises.filter((settle) => settle.status === "fulfilled" && settle.value).map((settle) => settle.value);
      return fulfilledPromises;
    }
    async function _getConfig({ fs: fs2, gitdir, path }) {
      const config = await GitConfigManager.get({ fs: fs2, gitdir });
      return config.get(path);
    }
    function assignDefined(target, ...sources) {
      for (const source of sources) {
        if (source) {
          for (const key of Object.keys(source)) {
            const val = source[key];
            if (val !== void 0) {
              target[key] = val;
            }
          }
        }
      }
      return target;
    }
    async function normalizeAuthorObject({ fs: fs2, gitdir, author, commit: commit2 }) {
      const timestamp = Math.floor(Date.now() / 1e3);
      const defaultAuthor = {
        name: await _getConfig({ fs: fs2, gitdir, path: "user.name" }),
        email: await _getConfig({ fs: fs2, gitdir, path: "user.email" }) || "",
        // author.email is allowed to be empty string
        timestamp,
        timezoneOffset: new Date(timestamp * 1e3).getTimezoneOffset()
      };
      const normalizedAuthor = assignDefined(
        {},
        defaultAuthor,
        commit2 ? commit2.author : void 0,
        author
      );
      if (normalizedAuthor.name === void 0) {
        return void 0;
      }
      return normalizedAuthor;
    }
    async function normalizeCommitterObject({
      fs: fs2,
      gitdir,
      author,
      committer,
      commit: commit2
    }) {
      const timestamp = Math.floor(Date.now() / 1e3);
      const defaultCommitter = {
        name: await _getConfig({ fs: fs2, gitdir, path: "user.name" }),
        email: await _getConfig({ fs: fs2, gitdir, path: "user.email" }) || "",
        // committer.email is allowed to be empty string
        timestamp,
        timezoneOffset: new Date(timestamp * 1e3).getTimezoneOffset()
      };
      const normalizedCommitter = assignDefined(
        {},
        defaultCommitter,
        commit2 ? commit2.committer : void 0,
        author,
        committer
      );
      if (normalizedCommitter.name === void 0) {
        return void 0;
      }
      return normalizedCommitter;
    }
    async function resolveCommit({ fs: fs2, cache, gitdir, oid }) {
      const { type, object } = await _readObject({ fs: fs2, cache, gitdir, oid });
      if (type === "tag") {
        oid = GitAnnotatedTag.from(object).parse().object;
        return resolveCommit({ fs: fs2, cache, gitdir, oid });
      }
      if (type !== "commit") {
        throw new ObjectTypeError(oid, type, "commit");
      }
      return { commit: GitCommit.from(object), oid };
    }
    async function _readCommit({ fs: fs2, cache, gitdir, oid }) {
      const { commit: commit2, oid: commitOid } = await resolveCommit({
        fs: fs2,
        cache,
        gitdir,
        oid
      });
      const result = {
        oid: commitOid,
        commit: commit2.parse(),
        payload: commit2.withoutSignature()
      };
      return result;
    }
    async function _commit({
      fs: fs2,
      cache,
      onSign,
      gitdir,
      message,
      author: _author,
      committer: _committer,
      signingKey,
      amend = false,
      dryRun = false,
      noUpdateBranch = false,
      ref,
      parent,
      tree
    }) {
      let initialCommit = false;
      if (!ref) {
        ref = await GitRefManager.resolve({
          fs: fs2,
          gitdir,
          ref: "HEAD",
          depth: 2
        });
      }
      let refOid, refCommit;
      try {
        refOid = await GitRefManager.resolve({
          fs: fs2,
          gitdir,
          ref
        });
        refCommit = await _readCommit({ fs: fs2, gitdir, oid: refOid, cache: {} });
      } catch {
        initialCommit = true;
      }
      if (amend && initialCommit) {
        throw new NoCommitError(ref);
      }
      const author = !amend ? await normalizeAuthorObject({ fs: fs2, gitdir, author: _author }) : await normalizeAuthorObject({
        fs: fs2,
        gitdir,
        author: _author,
        commit: refCommit.commit
      });
      if (!author) throw new MissingNameError("author");
      const committer = !amend ? await normalizeCommitterObject({
        fs: fs2,
        gitdir,
        author,
        committer: _committer
      }) : await normalizeCommitterObject({
        fs: fs2,
        gitdir,
        author,
        committer: _committer,
        commit: refCommit.commit
      });
      if (!committer) throw new MissingNameError("committer");
      return GitIndexManager.acquire(
        { fs: fs2, gitdir, cache, allowUnmerged: false },
        async function(index2) {
          const inodes = flatFileListToDirectoryStructure(index2.entries);
          const inode = inodes.get(".");
          if (!tree) {
            tree = await constructTree({ fs: fs2, gitdir, inode, dryRun });
          }
          if (!parent) {
            if (!amend) {
              parent = refOid ? [refOid] : [];
            } else {
              parent = refCommit.commit.parent;
            }
          } else {
            parent = await Promise.all(
              parent.map((p) => {
                return GitRefManager.resolve({ fs: fs2, gitdir, ref: p });
              })
            );
          }
          if (!message) {
            if (!amend) {
              throw new MissingParameterError("message");
            } else {
              message = refCommit.commit.message;
            }
          }
          let comm = GitCommit.from({
            tree,
            parent,
            author,
            committer,
            message
          });
          if (signingKey) {
            comm = await GitCommit.sign(comm, onSign, signingKey);
          }
          const oid = await _writeObject({
            fs: fs2,
            gitdir,
            type: "commit",
            object: comm.toObject(),
            dryRun
          });
          if (!noUpdateBranch && !dryRun) {
            await GitRefManager.writeRef({
              fs: fs2,
              gitdir,
              ref,
              value: oid
            });
          }
          return oid;
        }
      );
    }
    async function constructTree({ fs: fs2, gitdir, inode, dryRun }) {
      const children2 = inode.children;
      for (const inode2 of children2) {
        if (inode2.type === "tree") {
          inode2.metadata.mode = "040000";
          inode2.metadata.oid = await constructTree({ fs: fs2, gitdir, inode: inode2, dryRun });
        }
      }
      const entries = children2.map((inode2) => ({
        mode: inode2.metadata.mode,
        path: inode2.basename,
        oid: inode2.metadata.oid,
        type: inode2.type
      }));
      const tree = GitTree.from(entries);
      const oid = await _writeObject({
        fs: fs2,
        gitdir,
        type: "tree",
        object: tree.toObject(),
        dryRun
      });
      return oid;
    }
    async function resolveFilepath({ fs: fs2, cache, gitdir, oid, filepath }) {
      if (filepath.startsWith("/")) {
        throw new InvalidFilepathError("leading-slash");
      } else if (filepath.endsWith("/")) {
        throw new InvalidFilepathError("trailing-slash");
      }
      const _oid = oid;
      const result = await resolveTree({ fs: fs2, cache, gitdir, oid });
      const tree = result.tree;
      if (filepath === "") {
        oid = result.oid;
      } else {
        const pathArray = filepath.split("/");
        oid = await _resolveFilepath({
          fs: fs2,
          cache,
          gitdir,
          tree,
          pathArray,
          oid: _oid,
          filepath
        });
      }
      return oid;
    }
    async function _resolveFilepath({
      fs: fs2,
      cache,
      gitdir,
      tree,
      pathArray,
      oid,
      filepath
    }) {
      const name = pathArray.shift();
      for (const entry of tree) {
        if (entry.path === name) {
          if (pathArray.length === 0) {
            return entry.oid;
          } else {
            const { type, object } = await _readObject({
              fs: fs2,
              cache,
              gitdir,
              oid: entry.oid
            });
            if (type !== "tree") {
              throw new ObjectTypeError(oid, type, "tree", filepath);
            }
            tree = GitTree.from(object);
            return _resolveFilepath({
              fs: fs2,
              cache,
              gitdir,
              tree,
              pathArray,
              oid,
              filepath
            });
          }
        }
      }
      throw new NotFoundError(`file or directory found at "${oid}:${filepath}"`);
    }
    async function _readTree({
      fs: fs2,
      cache,
      gitdir,
      oid,
      filepath = void 0
    }) {
      if (filepath !== void 0) {
        oid = await resolveFilepath({ fs: fs2, cache, gitdir, oid, filepath });
      }
      const { tree, oid: treeOid } = await resolveTree({ fs: fs2, cache, gitdir, oid });
      const result = {
        oid: treeOid,
        tree: tree.entries()
      };
      return result;
    }
    async function _writeTree({ fs: fs2, gitdir, tree }) {
      const object = GitTree.from(tree).toObject();
      const oid = await _writeObject({
        fs: fs2,
        gitdir,
        type: "tree",
        object,
        format: "content"
      });
      return oid;
    }
    async function _addNote({
      fs: fs2,
      cache,
      onSign,
      gitdir,
      ref,
      oid,
      note,
      force,
      author,
      committer,
      signingKey
    }) {
      let parent;
      try {
        parent = await GitRefManager.resolve({ gitdir, fs: fs2, ref });
      } catch (err) {
        if (!(err instanceof NotFoundError)) {
          throw err;
        }
      }
      const result = await _readTree({
        fs: fs2,
        cache,
        gitdir,
        oid: parent || "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
      });
      let tree = result.tree;
      if (force) {
        tree = tree.filter((entry) => entry.path !== oid);
      } else {
        for (const entry of tree) {
          if (entry.path === oid) {
            throw new AlreadyExistsError("note", oid);
          }
        }
      }
      if (typeof note === "string") {
        note = Buffer.from(note, "utf8");
      }
      const noteOid = await _writeObject({
        fs: fs2,
        gitdir,
        type: "blob",
        object: note,
        format: "content"
      });
      tree.push({ mode: "100644", path: oid, oid: noteOid, type: "blob" });
      const treeOid = await _writeTree({
        fs: fs2,
        gitdir,
        tree
      });
      const commitOid = await _commit({
        fs: fs2,
        cache,
        onSign,
        gitdir,
        ref,
        tree: treeOid,
        parent: parent && [parent],
        message: `Note added by 'isomorphic-git addNote'
`,
        author,
        committer,
        signingKey
      });
      return commitOid;
    }
    async function addNote({
      fs: _fs,
      onSign,
      dir,
      gitdir = join(dir, ".git"),
      ref = "refs/notes/commits",
      oid,
      note,
      force,
      author: _author,
      committer: _committer,
      signingKey,
      cache = {}
    }) {
      try {
        assertParameter("fs", _fs);
        assertParameter("gitdir", gitdir);
        assertParameter("oid", oid);
        assertParameter("note", note);
        if (signingKey) {
          assertParameter("onSign", onSign);
        }
        const fs2 = new FileSystem(_fs);
        const author = await normalizeAuthorObject({ fs: fs2, gitdir, author: _author });
        if (!author) throw new MissingNameError("author");
        const committer = await normalizeCommitterObject({
          fs: fs2,
          gitdir,
          author,
          committer: _committer
        });
        if (!committer) throw new MissingNameError("committer");
        const updatedGitdir = await discoverGitdir({ fsp: fs2, dotgit: gitdir });
        return await _addNote({
          fs: fs2,
          cache,
          onSign,
          gitdir: updatedGitdir,
          ref,
          oid,
          note,
          force,
          author,
          committer,
          signingKey
        });
      } catch (err) {
        err.caller = "git.addNote";
        throw err;
      }
    }
    var bad = /(^|[/.])([/.]|$)|^@$|@{|[\x00-\x20\x7f~^:?*[\\]|\.lock(\/|$)/;
    function isValidRef(name, onelevel) {
      if (typeof name !== "string")
        throw new TypeError("Reference name must be a string");
      return !bad.test(name) && (!!onelevel || name.includes("/"));
    }
    async function _addRemote({ fs: fs2, gitdir, remote, url, force }) {
      if (!isValidRef(remote, true)) {
        throw new InvalidRefNameError(remote, cleanGitRef.clean(remote));
      }
      const config = await GitConfigManager.get({ fs: fs2, gitdir });
      if (!force) {
        const remoteNames = await config.getSubsections("remote");
        if (remoteNames.includes(remote)) {
          if (url !== await config.get(`remote.${remote}.url`)) {
            throw new AlreadyExistsError("remote", remote);
          }
        }
      }
      await config.set(`remote.${remote}.url`, url);
      await config.set(
        `remote.${remote}.fetch`,
        `+refs/heads/*:refs/remotes/${remote}/*`
      );
      await GitConfigManager.save({ fs: fs2, gitdir, config });
    }
    async function addRemote({
      fs: fs2,
      dir,
      gitdir = join(dir, ".git"),
      remote,
      url,
      force = false
    }) {
      try {
        assertParameter("fs", fs2);
        assertParameter("gitdir", gitdir);
        assertParameter("remote", remote);
        assertParameter("url", url);
        const fsp = new FileSystem(fs2);
        const updatedGitdir = await discoverGitdir({ fsp, dotgit: gitdir });
        return await _addRemote({
          fs: fsp,
          gitdir: updatedGitdir,
          remote,
          url,
          force
        });
      } catch (err) {
        err.caller = "git.addRemote";
        throw err;
      }
    }
    async function _annotatedTag({
      fs: fs2,
      cache,
      onSign,
      gitdir,
      ref,
      tagger,
      message = ref,
      gpgsig,
      object,
      signingKey,
      force = false
    }) {
      ref = ref.startsWith("refs/tags/") ? ref : `refs/tags/${ref}`;
      if (!force && await GitRefManager.exists({ fs: fs2, gitdir, ref })) {
        throw new AlreadyExistsError("tag", ref);
      }
      const oid = await GitRefManager.resolve({
        fs: fs2,
        gitdir,
        ref: object || "HEAD"
      });
      const { type } = await _readObject({ fs: fs2, cache, gitdir, oid });
      let tagObject = GitAnnotatedTag.from({
        object: oid,
        type,
        tag: ref.replace("refs/tags/", ""),
        tagger,
        message,
        gpgsig
      });
      if (signingKey) {
        tagObject = await GitAnnotatedTag.sign(tagObject, onSign, signingKey);
      }
      const value = await _writeObject({
        fs: fs2,
        gitdir,
        type: "tag",
        object: tagObject.toObject()
      });
      await GitRefManager.writeRef({ fs: fs2, gitdir, ref, value });
    }
    async function annotatedTag({
      fs: _fs,
      onSign,
      dir,
      gitdir = join(dir, ".git"),
      ref,
      tagger: _tagger,
      message = ref,
      gpgsig,
      object,
      signingKey,
      force = false,
      cache = {}
    }) {
      try {
        assertParameter("fs", _fs);
        assertParameter("gitdir", gitdir);
        assertParameter("ref", ref);
        if (signingKey) {
          assertParameter("onSign", onSign);
        }
        const fs2 = new FileSystem(_fs);
        const updatedGitdir = await discoverGitdir({ fsp: fs2, dotgit: gitdir });
        const tagger = await normalizeAuthorObject({
          fs: fs2,
          gitdir: updatedGitdir,
          author: _tagger
        });
        if (!tagger) throw new MissingNameError("tagger");
        return await _annotatedTag({
          fs: fs2,
          cache,
          onSign,
          gitdir: updatedGitdir,
          ref,
          tagger,
          message,
          gpgsig,
          object,
          signingKey,
          force
        });
      } catch (err) {
        err.caller = "git.annotatedTag";
        throw err;
      }
    }
    async function _branch({
      fs: fs2,
      gitdir,
      ref,
      object,
      checkout: checkout2 = false,
      force = false
    }) {
      if (!isValidRef(ref, true)) {
        throw new InvalidRefNameError(ref, cleanGitRef.clean(ref));
      }
      const fullref = `refs/heads/${ref}`;
      if (!force) {
        const exist = await GitRefManager.exists({ fs: fs2, gitdir, ref: fullref });
        if (exist) {
          throw new AlreadyExistsError("branch", ref, false);
        }
      }
      let oid;
      try {
        oid = await GitRefManager.resolve({ fs: fs2, gitdir, ref: object || "HEAD" });
      } catch (e) {
      }
      if (oid) {
        await GitRefManager.writeRef({ fs: fs2, gitdir, ref: fullref, value: oid });
      }
      if (checkout2) {
        await GitRefManager.writeSymbolicRef({
          fs: fs2,
          gitdir,
          ref: "HEAD",
          value: fullref
        });
      }
    }
    async function branch({
      fs: fs2,
      dir,
      gitdir = join(dir, ".git"),
      ref,
      object,
      checkout: checkout2 = false,
      force = false
    }) {
      try {
        assertParameter("fs", fs2);
        assertParameter("gitdir", gitdir);
        assertParameter("ref", ref);
        const fsp = new FileSystem(fs2);
        const updatedGitdir = await discoverGitdir({ fsp, dotgit: gitdir });
        return await _branch({
          fs: fsp,
          gitdir: updatedGitdir,
          ref,
          object,
          checkout: checkout2,
          force
        });
      } catch (err) {
        err.caller = "git.branch";
        throw err;
      }
    }
    var worthWalking = (filepath, root) => {
      if (filepath === "." || root == null || root.length === 0 || root === ".") {
        return true;
      }
      if (root.length >= filepath.length) {
        return root.startsWith(filepath);
      } else {
        return filepath.startsWith(root);
      }
    };
    async function _checkout({
      fs: fs2,
      cache,
      onProgress,
      onPostCheckout,
      dir,
      gitdir,
      remote,
      ref,
      filepaths,
      noCheckout,
      noUpdateHead,
      dryRun,
      force,
      track = true,
      nonBlocking = false,
      batchSize = 100
    }) {
      let oldOid;
      if (onPostCheckout) {
        try {
          oldOid = await GitRefManager.resolve({ fs: fs2, gitdir, ref: "HEAD" });
        } catch (err) {
          oldOid = "0000000000000000000000000000000000000000";
        }
      }
      let oid;
      try {
        oid = await GitRefManager.resolve({ fs: fs2, gitdir, ref });
      } catch (err) {
        if (ref === "HEAD") throw err;
        const remoteRef = `${remote}/${ref}`;
        oid = await GitRefManager.resolve({
          fs: fs2,
          gitdir,
          ref: remoteRef
        });
        if (track) {
          const config = await GitConfigManager.get({ fs: fs2, gitdir });
          await config.set(`branch.${ref}.remote`, remote);
          await config.set(`branch.${ref}.merge`, `refs/heads/${ref}`);
          await GitConfigManager.save({ fs: fs2, gitdir, config });
        }
        await GitRefManager.writeRef({
          fs: fs2,
          gitdir,
          ref: `refs/heads/${ref}`,
          value: oid
        });
      }
      if (!noCheckout) {
        let ops;
        try {
          ops = await analyze({
            fs: fs2,
            cache,
            onProgress,
            dir,
            gitdir,
            ref,
            force,
            filepaths
          });
        } catch (err) {
          if (err instanceof NotFoundError && err.data.what === oid) {
            throw new CommitNotFetchedError(ref, oid);
          } else {
            throw err;
          }
        }
        const conflicts = ops.filter(([method]) => method === "conflict").map(([method, fullpath]) => fullpath);
        if (conflicts.length > 0) {
          throw new CheckoutConflictError(conflicts);
        }
        const errors = ops.filter(([method]) => method === "error").map(([method, fullpath]) => fullpath);
        if (errors.length > 0) {
          throw new InternalError(errors.join(", "));
        }
        if (dryRun) {
          if (onPostCheckout) {
            await onPostCheckout({
              previousHead: oldOid,
              newHead: oid,
              type: filepaths != null && filepaths.length > 0 ? "file" : "branch"
            });
          }
          return;
        }
        let count = 0;
        const total = ops.length;
        await GitIndexManager.acquire(
          { fs: fs2, gitdir, cache },
          async function(index2) {
            await Promise.all(
              ops.filter(
                ([method]) => method === "delete" || method === "delete-index"
              ).map(async function([method, fullpath]) {
                const filepath = `${dir}/${fullpath}`;
                if (method === "delete") {
                  await fs2.rm(filepath);
                }
                index2.delete({ filepath: fullpath });
                if (onProgress) {
                  await onProgress({
                    phase: "Updating workdir",
                    loaded: ++count,
                    total
                  });
                }
              })
            );
          }
        );
        await GitIndexManager.acquire(
          { fs: fs2, gitdir, cache },
          async function(index2) {
            for (const [method, fullpath] of ops) {
              if (method === "rmdir" || method === "rmdir-index") {
                const filepath = `${dir}/${fullpath}`;
                try {
                  if (method === "rmdir") {
                    await fs2.rmdir(filepath);
                  }
                  index2.delete({ filepath: fullpath });
                  if (onProgress) {
                    await onProgress({
                      phase: "Updating workdir",
                      loaded: ++count,
                      total
                    });
                  }
                } catch (e) {
                  if (e.code === "ENOTEMPTY") {
                    console.log(
                      `Did not delete ${fullpath} because directory is not empty`
                    );
                  } else {
                    throw e;
                  }
                }
              }
            }
          }
        );
        await Promise.all(
          ops.filter(([method]) => method === "mkdir" || method === "mkdir-index").map(async function([_, fullpath]) {
            const filepath = `${dir}/${fullpath}`;
            await fs2.mkdir(filepath);
            if (onProgress) {
              await onProgress({
                phase: "Updating workdir",
                loaded: ++count,
                total
              });
            }
          })
        );
        if (nonBlocking) {
          const eligibleOps = ops.filter(
            ([method]) => method === "create" || method === "create-index" || method === "update" || method === "mkdir-index"
          );
          const updateWorkingDirResults = await batchAllSettled(
            "Update Working Dir",
            eligibleOps.map(
              ([method, fullpath, oid2, mode, chmod]) => () => updateWorkingDir({ fs: fs2, cache, gitdir, dir }, [
                method,
                fullpath,
                oid2,
                mode,
                chmod
              ])
            ),
            onProgress,
            batchSize
          );
          await GitIndexManager.acquire(
            { fs: fs2, gitdir, cache, allowUnmerged: true },
            async function(index2) {
              await batchAllSettled(
                "Update Index",
                updateWorkingDirResults.map(
                  ([fullpath, oid2, stats]) => () => updateIndex({ index: index2, fullpath, oid: oid2, stats })
                ),
                onProgress,
                batchSize
              );
            }
          );
        } else {
          await GitIndexManager.acquire(
            { fs: fs2, gitdir, cache, allowUnmerged: true },
            async function(index2) {
              await Promise.all(
                ops.filter(
                  ([method]) => method === "create" || method === "create-index" || method === "update" || method === "mkdir-index"
                ).map(async function([method, fullpath, oid2, mode, chmod]) {
                  const filepath = `${dir}/${fullpath}`;
                  try {
                    if (method !== "create-index" && method !== "mkdir-index") {
                      const { object } = await _readObject({
                        fs: fs2,
                        cache,
                        gitdir,
                        oid: oid2
                      });
                      if (chmod) {
                        await fs2.rm(filepath);
                      }
                      if (mode === 33188) {
                        await fs2.write(filepath, object);
                      } else if (mode === 33261) {
                        await fs2.write(filepath, object, { mode: 511 });
                      } else if (mode === 40960) {
                        await fs2.writelink(filepath, object);
                      } else {
                        throw new InternalError(
                          `Invalid mode 0o${mode.toString(
                            8
                          )} detected in blob ${oid2}`
                        );
                      }
                    }
                    const stats = await fs2.lstat(filepath);
                    if (mode === 33261) {
                      stats.mode = 493;
                    }
                    if (method === "mkdir-index") {
                      stats.mode = 57344;
                    }
                    index2.insert({
                      filepath: fullpath,
                      stats,
                      oid: oid2
                    });
                    if (onProgress) {
                      await onProgress({
                        phase: "Updating workdir",
                        loaded: ++count,
                        total
                      });
                    }
                  } catch (e) {
                    console.log(e);
                  }
                })
              );
            }
          );
        }
        if (onPostCheckout) {
          await onPostCheckout({
            previousHead: oldOid,
            newHead: oid,
            type: filepaths != null && filepaths.length > 0 ? "file" : "branch"
          });
        }
      }
      if (!noUpdateHead) {
        const fullRef = await GitRefManager.expand({ fs: fs2, gitdir, ref });
        if (fullRef.startsWith("refs/heads")) {
          await GitRefManager.writeSymbolicRef({
            fs: fs2,
            gitdir,
            ref: "HEAD",
            value: fullRef
          });
        } else {
          await GitRefManager.writeRef({ fs: fs2, gitdir, ref: "HEAD", value: oid });
        }
      }
    }
    async function analyze({
      fs: fs2,
      cache,
      onProgress,
      dir,
      gitdir,
      ref,
      force,
      filepaths
    }) {
      let count = 0;
      return _walk({
        fs: fs2,
        cache,
        dir,
        gitdir,
        trees: [TREE({ ref }), WORKDIR(), STAGE()],
        map: async function(fullpath, [commit2, workdir, stage]) {
          if (fullpath === ".") return;
          if (filepaths && !filepaths.some((base) => worthWalking(fullpath, base))) {
            return null;
          }
          if (onProgress) {
            await onProgress({ phase: "Analyzing workdir", loaded: ++count });
          }
          const key = [!!stage, !!commit2, !!workdir].map(Number).join("");
          switch (key) {
            // Impossible case.
            case "000":
              return;
            // Ignore workdir files that are not tracked and not part of the new commit.
            case "001":
              if (force && filepaths && filepaths.includes(fullpath)) {
                return ["delete", fullpath];
              }
              return;
            // New entries
            case "010": {
              switch (await commit2.type()) {
                case "tree": {
                  return ["mkdir", fullpath];
                }
                case "blob": {
                  return [
                    "create",
                    fullpath,
                    await commit2.oid(),
                    await commit2.mode()
                  ];
                }
                case "commit": {
                  return [
                    "mkdir-index",
                    fullpath,
                    await commit2.oid(),
                    await commit2.mode()
                  ];
                }
                default: {
                  return [
                    "error",
                    `new entry Unhandled type ${await commit2.type()}`
                  ];
                }
              }
            }
            // New entries but there is already something in the workdir there.
            case "011": {
              switch (`${await commit2.type()}-${await workdir.type()}`) {
                case "tree-tree": {
                  return;
                }
                case "tree-blob":
                case "blob-tree": {
                  return ["conflict", fullpath];
                }
                case "blob-blob": {
                  if (await commit2.oid() !== await workdir.oid()) {
                    if (force) {
                      return [
                        "update",
                        fullpath,
                        await commit2.oid(),
                        await commit2.mode(),
                        await commit2.mode() !== await workdir.mode()
                      ];
                    } else {
                      return ["conflict", fullpath];
                    }
                  } else {
                    if (await commit2.mode() !== await workdir.mode()) {
                      if (force) {
                        return [
                          "update",
                          fullpath,
                          await commit2.oid(),
                          await commit2.mode(),
                          true
                        ];
                      } else {
                        return ["conflict", fullpath];
                      }
                    } else {
                      return [
                        "create-index",
                        fullpath,
                        await commit2.oid(),
                        await commit2.mode()
                      ];
                    }
                  }
                }
                case "commit-tree": {
                  return;
                }
                case "commit-blob": {
                  return ["conflict", fullpath];
                }
                default: {
                  return ["error", `new entry Unhandled type ${commit2.type}`];
                }
              }
            }
            // Something in stage but not in the commit OR the workdir.
            // Note: I verified this behavior against canonical git.
            case "100": {
              return ["delete-index", fullpath];
            }
            // Deleted entries
            // TODO: How to handle if stage type and workdir type mismatch?
            case "101": {
              switch (await stage.type()) {
                case "tree": {
                  return ["rmdir-index", fullpath];
                }
                case "blob": {
                  if (await stage.oid() !== await workdir.oid()) {
                    if (force) {
                      return ["delete", fullpath];
                    } else {
                      return ["conflict", fullpath];
                    }
                  } else {
                    return ["delete", fullpath];
                  }
                }
                case "commit": {
                  return ["rmdir-index", fullpath];
                }
                default: {
                  return [
                    "error",
                    `delete entry Unhandled type ${await stage.type()}`
                  ];
                }
              }
            }
            /* eslint-disable no-fallthrough */
            // File missing from workdir
            case "110":
            // Possibly modified entries
            case "111": {
              switch (`${await stage.type()}-${await commit2.type()}`) {
                case "tree-tree": {
                  return;
                }
                case "blob-blob": {
                  if (await stage.oid() === await commit2.oid() && await stage.mode() === await commit2.mode() && !force) {
                    return;
                  }
                  if (workdir) {
                    if (await workdir.oid() !== await stage.oid() && await workdir.oid() !== await commit2.oid()) {
                      if (force) {
                        return [
                          "update",
                          fullpath,
                          await commit2.oid(),
                          await commit2.mode(),
                          await commit2.mode() !== await workdir.mode()
                        ];
                      } else {
                        return ["conflict", fullpath];
                      }
                    }
                  } else if (force) {
                    return [
                      "update",
                      fullpath,
                      await commit2.oid(),
                      await commit2.mode(),
                      await commit2.mode() !== await stage.mode()
                    ];
                  }
                  if (await commit2.mode() !== await stage.mode()) {
                    return [
                      "update",
                      fullpath,
                      await commit2.oid(),
                      await commit2.mode(),
                      true
                    ];
                  }
                  if (await commit2.oid() !== await stage.oid()) {
                    return [
                      "update",
                      fullpath,
                      await commit2.oid(),
                      await commit2.mode(),
                      false
                    ];
                  } else {
                    return;
                  }
                }
                case "tree-blob": {
                  return ["update-dir-to-blob", fullpath, await commit2.oid()];
                }
                case "blob-tree": {
                  return ["update-blob-to-tree", fullpath];
                }
                case "commit-commit": {
                  return [
                    "mkdir-index",
                    fullpath,
                    await commit2.oid(),
                    await commit2.mode()
                  ];
                }
                default: {
                  return [
                    "error",
                    `update entry Unhandled type ${await stage.type()}-${await commit2.type()}`
                  ];
                }
              }
            }
          }
        },
        // Modify the default flat mapping
        reduce: async function(parent, children2) {
          children2 = flat(children2);
          if (!parent) {
            return children2;
          } else if (parent && parent[0] === "rmdir") {
            children2.push(parent);
            return children2;
          } else {
            children2.unshift(parent);
            return children2;
          }
        }
      });
    }
    async function updateIndex({ index: index2, fullpath, stats, oid }) {
      try {
        index2.insert({
          filepath: fullpath,
          stats,
          oid
        });
      } catch (e) {
        console.warn(`Error inserting ${fullpath} into index:`, e);
      }
    }
    async function updateWorkingDir({ fs: fs2, cache, gitdir, dir }, [method, fullpath, oid, mode, chmod]) {
      const filepath = `${dir}/${fullpath}`;
      if (method !== "create-index" && method !== "mkdir-index") {
        const { object } = await _readObject({ fs: fs2, cache, gitdir, oid });
        if (chmod) {
          await fs2.rm(filepath);
        }
        if (mode === 33188) {
          await fs2.write(filepath, object);
        } else if (mode === 33261) {
          await fs2.write(filepath, object, { mode: 511 });
        } else if (mode === 40960) {
          await fs2.writelink(filepath, object);
        } else {
          throw new InternalError(
            `Invalid mode 0o${mode.toString(8)} detected in blob ${oid}`
          );
        }
      }
      const stats = await fs2.lstat(filepath);
      if (mode === 33261) {
        stats.mode = 493;
      }
      if (method === "mkdir-index") {
        stats.mode = 57344;
      }
      return [fullpath, oid, stats];
    }
    async function batchAllSettled(operationName, tasks, onProgress, batchSize) {
      const results = [];
      try {
        for (let i = 0; i < tasks.length; i += batchSize) {
          const batch = tasks.slice(i, i + batchSize).map((task) => task());
          const batchResults = await Promise.allSettled(batch);
          batchResults.forEach((result) => {
            if (result.status === "fulfilled") results.push(result.value);
          });
          if (onProgress) {
            await onProgress({
              phase: "Updating workdir",
              loaded: i + batch.length,
              total: tasks.length
            });
          }
        }
        return results;
      } catch (error) {
        console.error(`Error during ${operationName}: ${error}`);
      }
      return results;
    }
    async function checkout({
      fs: fs2,
      onProgress,
      onPostCheckout,
      dir,
      gitdir = join(dir, ".git"),
      remote = "origin",
      ref: _ref,
      filepaths,
      noCheckout = false,
      noUpdateHead = _ref === void 0,
      dryRun = false,
      force = false,
      track = true,
      cache = {},
      nonBlocking = false,
      batchSize = 100
    }) {
      try {
        assertParameter("fs", fs2);
        assertParameter("dir", dir);
        assertParameter("gitdir", gitdir);
        const ref = _ref || "HEAD";
        const fsp = new FileSystem(fs2);
        const updatedGitdir = await discoverGitdir({ fsp, dotgit: gitdir });
        return await _checkout({
          fs: fsp,
          cache,
          onProgress,
          onPostCheckout,
          dir,
          gitdir: updatedGitdir,
          remote,
          ref,
          filepaths,
          noCheckout,
          noUpdateHead,
          dryRun,
          force,
          track,
          nonBlocking,
          batchSize
        });
      } catch (err) {
        err.caller = "git.checkout";
        throw err;
      }
    }
    var abbreviateRx = /^refs\/(heads\/|tags\/|remotes\/)?(.*)/;
    function abbreviateRef(ref) {
      const match2 = abbreviateRx.exec(ref);
      if (match2) {
        if (match2[1] === "remotes/" && ref.endsWith("/HEAD")) {
          return match2[2].slice(0, -5);
        } else {
          return match2[2];
        }
      }
      return ref;
    }
    async function _currentBranch({
      fs: fs2,
      gitdir,
      fullname = false,
      test = false
    }) {
      const ref = await GitRefManager.resolve({
        fs: fs2,
        gitdir,
        ref: "HEAD",
        depth: 2
      });
      if (test) {
        try {
          await GitRefManager.resolve({ fs: fs2, gitdir, ref });
        } catch (_) {
          return;
        }
      }
      if (!ref.startsWith("refs/")) return;
      return fullname ? ref : abbreviateRef(ref);
    }
    function translateSSHtoHTTP(url) {
      url = url.replace(/^git@([^:]+):/, "https://$1/");
      url = url.replace(/^ssh:\/\//, "https://");
      return url;
    }
    function calculateBasicAuthHeader({ username = "", password = "" }) {
      return `Basic ${Buffer.from(`${username}:${password}`).toString("base64")}`;
    }
    async function forAwait(iterable, cb) {
      const iter = getIterator(iterable);
      while (true) {
        const { value, done } = await iter.next();
        if (value) await cb(value);
        if (done) break;
      }
      if (iter.return) iter.return();
    }
    async function collect(iterable) {
      let size = 0;
      const buffers = [];
      await forAwait(iterable, (value) => {
        buffers.push(value);
        size += value.byteLength;
      });
      const result = new Uint8Array(size);
      let nextIndex = 0;
      for (const buffer of buffers) {
        result.set(buffer, nextIndex);
        nextIndex += buffer.byteLength;
      }
      return result;
    }
    function extractAuthFromUrl(url) {
      let userpass = url.match(/^https?:\/\/([^/]+)@/);
      if (userpass == null) return { url, auth: {} };
      userpass = userpass[1];
      const [username, password] = userpass.split(":");
      url = url.replace(`${userpass}@`, "");
      return { url, auth: { username, password } };
    }
    function padHex(b, n2) {
      const s2 = n2.toString(16);
      return "0".repeat(b - s2.length) + s2;
    }
    var GitPktLine = class {
      static flush() {
        return Buffer.from("0000", "utf8");
      }
      static delim() {
        return Buffer.from("0001", "utf8");
      }
      static encode(line) {
        if (typeof line === "string") {
          line = Buffer.from(line);
        }
        const length = line.length + 4;
        const hexlength = padHex(4, length);
        return Buffer.concat([Buffer.from(hexlength, "utf8"), line]);
      }
      static streamReader(stream) {
        const reader = new StreamReader(stream);
        return async function read2() {
          try {
            let length = await reader.read(4);
            if (length == null) return true;
            length = parseInt(length.toString("utf8"), 16);
            if (length === 0) return null;
            if (length === 1) return null;
            const buffer = await reader.read(length - 4);
            if (buffer == null) return true;
            return buffer;
          } catch (err) {
            stream.error = err;
            return true;
          }
        };
      }
    };
    async function parseCapabilitiesV2(read2) {
      const capabilities2 = {};
      let line;
      while (true) {
        line = await read2();
        if (line === true) break;
        if (line === null) continue;
        line = line.toString("utf8").replace(/\n$/, "");
        const i = line.indexOf("=");
        if (i > -1) {
          const key = line.slice(0, i);
          const value = line.slice(i + 1);
          capabilities2[key] = value;
        } else {
          capabilities2[line] = true;
        }
      }
      return { protocolVersion: 2, capabilities2 };
    }
    async function parseRefsAdResponse(stream, { service }) {
      const capabilities = /* @__PURE__ */ new Set();
      const refs = /* @__PURE__ */ new Map();
      const symrefs = /* @__PURE__ */ new Map();
      const read2 = GitPktLine.streamReader(stream);
      let lineOne = await read2();
      while (lineOne === null) lineOne = await read2();
      if (lineOne === true) throw new EmptyServerResponseError();
      if (lineOne.includes("version 2")) {
        return parseCapabilitiesV2(read2);
      }
      if (lineOne.toString("utf8").replace(/\n$/, "") !== `# service=${service}`) {
        throw new ParseError(`# service=${service}\\n`, lineOne.toString("utf8"));
      }
      let lineTwo = await read2();
      while (lineTwo === null) lineTwo = await read2();
      if (lineTwo === true) return { capabilities, refs, symrefs };
      lineTwo = lineTwo.toString("utf8");
      if (lineTwo.includes("version 2")) {
        return parseCapabilitiesV2(read2);
      }
      const [firstRef, capabilitiesLine] = splitAndAssert(lineTwo, "\0", "\\x00");
      capabilitiesLine.split(" ").map((x) => capabilities.add(x));
      if (firstRef !== "0000000000000000000000000000000000000000 capabilities^{}") {
        const [ref, name] = splitAndAssert(firstRef, " ", " ");
        refs.set(name, ref);
        while (true) {
          const line = await read2();
          if (line === true) break;
          if (line !== null) {
            const [ref2, name2] = splitAndAssert(line.toString("utf8"), " ", " ");
            refs.set(name2, ref2);
          }
        }
      }
      for (const cap of capabilities) {
        if (cap.startsWith("symref=")) {
          const m = cap.match(/symref=([^:]+):(.*)/);
          if (m.length === 3) {
            symrefs.set(m[1], m[2]);
          }
        }
      }
      return { protocolVersion: 1, capabilities, refs, symrefs };
    }
    function splitAndAssert(line, sep, expected) {
      const split = line.trim().split(sep);
      if (split.length !== 2) {
        throw new ParseError(
          `Two strings separated by '${expected}'`,
          line.toString("utf8")
        );
      }
      return split;
    }
    var corsProxify = (corsProxy, url) => corsProxy.endsWith("?") ? `${corsProxy}${url}` : `${corsProxy}/${url.replace(/^https?:\/\//, "")}`;
    var updateHeaders = (headers, auth) => {
      if (auth.username || auth.password) {
        headers.Authorization = calculateBasicAuthHeader(auth);
      }
      if (auth.headers) {
        Object.assign(headers, auth.headers);
      }
    };
    var stringifyBody = async (res) => {
      try {
        const data = Buffer.from(await collect(res.body));
        const response = data.toString("utf8");
        const preview = response.length < 256 ? response : response.slice(0, 256) + "...";
        return { preview, response, data };
      } catch (e) {
        return {};
      }
    };
    var GitRemoteHTTP = class {
      /**
       * Returns the capabilities of the GitRemoteHTTP class.
       *
       * @returns {Promise<string[]>} - An array of supported capabilities.
       */
      static async capabilities() {
        return ["discover", "connect"];
      }
      /**
       * Discovers references from a remote Git repository.
       *
       * @param {Object} args
       * @param {HttpClient} args.http - The HTTP client to use for requests.
       * @param {ProgressCallback} [args.onProgress] - Callback for progress updates.
       * @param {AuthCallback} [args.onAuth] - Callback for providing authentication credentials.
       * @param {AuthFailureCallback} [args.onAuthFailure] - Callback for handling authentication failures.
       * @param {AuthSuccessCallback} [args.onAuthSuccess] - Callback for handling successful authentication.
       * @param {string} [args.corsProxy] - Optional CORS proxy URL.
       * @param {string} args.service - The Git service (e.g., "git-upload-pack").
       * @param {string} args.url - The URL of the remote repository.
       * @param {Object<string, string>} args.headers - HTTP headers to include in the request.
       * @param {1 | 2} args.protocolVersion - The Git protocol version to use.
       * @returns {Promise<Object>} - The parsed response from the remote repository.
       * @throws {HttpError} - If the HTTP request fails.
       * @throws {SmartHttpError} - If the response cannot be parsed.
       * @throws {UserCanceledError} - If the user cancels the operation.
       */
      static async discover({
        http,
        onProgress,
        onAuth,
        onAuthSuccess,
        onAuthFailure,
        corsProxy,
        service,
        url: _origUrl,
        headers,
        protocolVersion
      }) {
        let { url, auth } = extractAuthFromUrl(_origUrl);
        const proxifiedURL = corsProxy ? corsProxify(corsProxy, url) : url;
        if (auth.username || auth.password) {
          headers.Authorization = calculateBasicAuthHeader(auth);
        }
        if (protocolVersion === 2) {
          headers["Git-Protocol"] = "version=2";
        }
        let res;
        let tryAgain;
        let providedAuthBefore = false;
        do {
          res = await http.request({
            onProgress,
            method: "GET",
            url: `${proxifiedURL}/info/refs?service=${service}`,
            headers
          });
          tryAgain = false;
          if (res.statusCode === 401 || res.statusCode === 203) {
            const getAuth = providedAuthBefore ? onAuthFailure : onAuth;
            if (getAuth) {
              auth = await getAuth(url, {
                ...auth,
                headers: { ...headers }
              });
              if (auth && auth.cancel) {
                throw new UserCanceledError();
              } else if (auth) {
                updateHeaders(headers, auth);
                providedAuthBefore = true;
                tryAgain = true;
              }
            }
          } else if (res.statusCode === 200 && providedAuthBefore && onAuthSuccess) {
            await onAuthSuccess(url, auth);
          }
        } while (tryAgain);
        if (res.statusCode !== 200) {
          const { response } = await stringifyBody(res);
          throw new HttpError(res.statusCode, res.statusMessage, response);
        }
        if (res.headers["content-type"] === `application/x-${service}-advertisement`) {
          const remoteHTTP = await parseRefsAdResponse(res.body, { service });
          remoteHTTP.auth = auth;
          return remoteHTTP;
        } else {
          const { preview, response, data } = await stringifyBody(res);
          try {
            const remoteHTTP = await parseRefsAdResponse([data], { service });
            remoteHTTP.auth = auth;
            return remoteHTTP;
          } catch (e) {
            throw new SmartHttpError(preview, response);
          }
        }
      }
      /**
       * Connects to a remote Git repository and sends a request.
       *
       * @param {Object} args
       * @param {HttpClient} args.http - The HTTP client to use for requests.
       * @param {ProgressCallback} [args.onProgress] - Callback for progress updates.
       * @param {string} [args.corsProxy] - Optional CORS proxy URL.
       * @param {string} args.service - The Git service (e.g., "git-upload-pack").
       * @param {string} args.url - The URL of the remote repository.
       * @param {Object<string, string>} [args.headers] - HTTP headers to include in the request.
       * @param {any} args.body - The request body to send.
       * @param {any} args.auth - Authentication credentials.
       * @returns {Promise<GitHttpResponse>} - The HTTP response from the remote repository.
       * @throws {HttpError} - If the HTTP request fails.
       */
      static async connect({
        http,
        onProgress,
        corsProxy,
        service,
        url,
        auth,
        body,
        headers
      }) {
        const urlAuth = extractAuthFromUrl(url);
        if (urlAuth) url = urlAuth.url;
        if (corsProxy) url = corsProxify(corsProxy, url);
        headers["content-type"] = `application/x-${service}-request`;
        headers.accept = `application/x-${service}-result`;
        updateHeaders(headers, auth);
        const res = await http.request({
          onProgress,
          method: "POST",
          url: `${url}/${service}`,
          body,
          headers
        });
        if (res.statusCode !== 200) {
          const { response } = stringifyBody(res);
          throw new HttpError(res.statusCode, res.statusMessage, response);
        }
        return res;
      }
    };
    var GitRemoteManager = class {
      /**
       * Determines the appropriate remote helper for the given URL.
       *
       * @param {Object} args
       * @param {string} args.url - The URL of the remote repository.
       * @returns {Object} - The remote helper class for the specified transport.
       * @throws {UrlParseError} - If the URL cannot be parsed.
       * @throws {UnknownTransportError} - If the transport is not supported.
       */
      static getRemoteHelperFor({ url }) {
        const remoteHelpers = /* @__PURE__ */ new Map();
        remoteHelpers.set("http", GitRemoteHTTP);
        remoteHelpers.set("https", GitRemoteHTTP);
        const parts = parseRemoteUrl({ url });
        if (!parts) {
          throw new UrlParseError(url);
        }
        if (remoteHelpers.has(parts.transport)) {
          return remoteHelpers.get(parts.transport);
        }
        throw new UnknownTransportError(
          url,
          parts.transport,
          parts.transport === "ssh" ? translateSSHtoHTTP(url) : void 0
        );
      }
    };
    function parseRemoteUrl({ url }) {
      if (url.startsWith("git@")) {
        return {
          transport: "ssh",
          address: url
        };
      }
      const matches = url.match(/(\w+)(:\/\/|::)(.*)/);
      if (matches === null) return;
      if (matches[2] === "://") {
        return {
          transport: matches[1],
          address: matches[0]
        };
      }
      if (matches[2] === "::") {
        return {
          transport: matches[1],
          address: matches[3]
        };
      }
    }
    var lock$2 = null;
    var GitShallowManager = class {
      /**
       * Reads the `shallow` file in the Git repository and returns a set of object IDs (OIDs).
       *
       * @param {Object} args
       * @param {FSClient} args.fs - A file system implementation.
       * @param {string} [args.gitdir] - [required] The [git directory](dir-vs-gitdir.md) path
       * @returns {Promise<Set<string>>} - A set of shallow object IDs.
       */
      static async read({ fs: fs2, gitdir }) {
        if (lock$2 === null) lock$2 = new AsyncLock();
        const filepath = join(gitdir, "shallow");
        const oids = /* @__PURE__ */ new Set();
        await lock$2.acquire(filepath, async function() {
          const text2 = await fs2.read(filepath, { encoding: "utf8" });
          if (text2 === null) return oids;
          if (text2.trim() === "") return oids;
          text2.trim().split("\n").map((oid) => oids.add(oid));
        });
        return oids;
      }
      /**
       * Writes a set of object IDs (OIDs) to the `shallow` file in the Git repository.
       * If the set is empty, the `shallow` file is removed.
       *
       * @param {Object} args
       * @param {FSClient} args.fs - A file system implementation.
       * @param {string} [args.gitdir] - [required] The [git directory](dir-vs-gitdir.md) path
       * @param {Set<string>} args.oids - A set of shallow object IDs to write.
       * @returns {Promise<void>}
       */
      static async write({ fs: fs2, gitdir, oids }) {
        if (lock$2 === null) lock$2 = new AsyncLock();
        const filepath = join(gitdir, "shallow");
        if (oids.size > 0) {
          const text2 = [...oids].join("\n") + "\n";
          await lock$2.acquire(filepath, async function() {
            await fs2.write(filepath, text2, {
              encoding: "utf8"
            });
          });
        } else {
          await lock$2.acquire(filepath, async function() {
            await fs2.rm(filepath);
          });
        }
      }
    };
    async function hasObjectLoose({ fs: fs2, gitdir, oid }) {
      const source = `objects/${oid.slice(0, 2)}/${oid.slice(2)}`;
      return fs2.exists(`${gitdir}/${source}`);
    }
    async function hasObjectPacked({
      fs: fs2,
      cache,
      gitdir,
      oid,
      getExternalRefDelta
    }) {
      let list = await fs2.readdir(join(gitdir, "objects/pack"));
      list = list.filter((x) => x.endsWith(".idx"));
      for (const filename of list) {
        const indexFile = `${gitdir}/objects/pack/${filename}`;
        const p = await readPackIndex({
          fs: fs2,
          cache,
          filename: indexFile,
          getExternalRefDelta
        });
        if (p.error) throw new InternalError(p.error);
        if (p.offsets.has(oid)) {
          return true;
        }
      }
      return false;
    }
    async function hasObject({
      fs: fs2,
      cache,
      gitdir,
      oid,
      format = "content"
    }) {
      const getExternalRefDelta = (oid2) => _readObject({ fs: fs2, cache, gitdir, oid: oid2 });
      let result = await hasObjectLoose({ fs: fs2, gitdir, oid });
      if (!result) {
        result = await hasObjectPacked({
          fs: fs2,
          cache,
          gitdir,
          oid,
          getExternalRefDelta
        });
      }
      return result;
    }
    function emptyPackfile(pack) {
      const pheader = "5041434b";
      const version3 = "00000002";
      const obCount = "00000000";
      const header = pheader + version3 + obCount;
      return pack.slice(0, 12).toString("hex") === header;
    }
    function filterCapabilities(server, client) {
      const serverNames = server.map((cap) => cap.split("=", 1)[0]);
      return client.filter((cap) => {
        const name = cap.split("=", 1)[0];
        return serverNames.includes(name);
      });
    }
    var pkg = {
      name: "isomorphic-git",
      version: "1.36.1",
      agent: "git/isomorphic-git@1.36.1"
    };
    var FIFO = class {
      constructor() {
        this._queue = [];
      }
      write(chunk) {
        if (this._ended) {
          throw Error("You cannot write to a FIFO that has already been ended!");
        }
        if (this._waiting) {
          const resolve = this._waiting;
          this._waiting = null;
          resolve({ value: chunk });
        } else {
          this._queue.push(chunk);
        }
      }
      end() {
        this._ended = true;
        if (this._waiting) {
          const resolve = this._waiting;
          this._waiting = null;
          resolve({ done: true });
        }
      }
      destroy(err) {
        this.error = err;
        this.end();
      }
      async next() {
        if (this._queue.length > 0) {
          return { value: this._queue.shift() };
        }
        if (this._ended) {
          return { done: true };
        }
        if (this._waiting) {
          throw Error(
            "You cannot call read until the previous call to read has returned!"
          );
        }
        return new Promise((resolve) => {
          this._waiting = resolve;
        });
      }
    };
    function findSplit(str) {
      const r = str.indexOf("\r");
      const n2 = str.indexOf("\n");
      if (r === -1 && n2 === -1) return -1;
      if (r === -1) return n2 + 1;
      if (n2 === -1) return r + 1;
      if (n2 === r + 1) return n2 + 1;
      return Math.min(r, n2) + 1;
    }
    function splitLines(input) {
      const output = new FIFO();
      let tmp = "";
      (async () => {
        await forAwait(input, (chunk) => {
          chunk = chunk.toString("utf8");
          tmp += chunk;
          while (true) {
            const i = findSplit(tmp);
            if (i === -1) break;
            output.write(tmp.slice(0, i));
            tmp = tmp.slice(i);
          }
        });
        if (tmp.length > 0) {
          output.write(tmp);
        }
        output.end();
      })();
      return output;
    }
    var GitSideBand = class {
      static demux(input) {
        const read2 = GitPktLine.streamReader(input);
        const packetlines = new FIFO();
        const packfile = new FIFO();
        const progress = new FIFO();
        const nextBit = async function() {
          const line = await read2();
          if (line === null) return nextBit();
          if (line === true) {
            packetlines.end();
            progress.end();
            input.error ? packfile.destroy(input.error) : packfile.end();
            return;
          }
          switch (line[0]) {
            case 1: {
              packfile.write(line.slice(1));
              break;
            }
            case 2: {
              progress.write(line.slice(1));
              break;
            }
            case 3: {
              const error = line.slice(1);
              progress.write(error);
              packetlines.end();
              progress.end();
              packfile.destroy(new Error(error.toString("utf8")));
              return;
            }
            default: {
              packetlines.write(line);
            }
          }
          nextBit();
        };
        nextBit();
        return {
          packetlines,
          packfile,
          progress
        };
      }
      // static mux ({
      //   protocol, // 'side-band' or 'side-band-64k'
      //   packetlines,
      //   packfile,
      //   progress,
      //   error
      // }) {
      //   const MAX_PACKET_LENGTH = protocol === 'side-band-64k' ? 999 : 65519
      //   let output = new PassThrough()
      //   packetlines.on('data', data => {
      //     if (data === null) {
      //       output.write(GitPktLine.flush())
      //     } else {
      //       output.write(GitPktLine.encode(data))
      //     }
      //   })
      //   let packfileWasEmpty = true
      //   let packfileEnded = false
      //   let progressEnded = false
      //   let errorEnded = false
      //   let goodbye = Buffer.concat([
      //     GitPktLine.encode(Buffer.from('010A', 'hex')),
      //     GitPktLine.flush()
      //   ])
      //   packfile
      //     .on('data', data => {
      //       packfileWasEmpty = false
      //       const buffers = splitBuffer(data, MAX_PACKET_LENGTH)
      //       for (const buffer of buffers) {
      //         output.write(
      //           GitPktLine.encode(Buffer.concat([Buffer.from('01', 'hex'), buffer]))
      //         )
      //       }
      //     })
      //     .on('end', () => {
      //       packfileEnded = true
      //       if (!packfileWasEmpty) output.write(goodbye)
      //       if (progressEnded && errorEnded) output.end()
      //     })
      //   progress
      //     .on('data', data => {
      //       const buffers = splitBuffer(data, MAX_PACKET_LENGTH)
      //       for (const buffer of buffers) {
      //         output.write(
      //           GitPktLine.encode(Buffer.concat([Buffer.from('02', 'hex'), buffer]))
      //         )
      //       }
      //     })
      //     .on('end', () => {
      //       progressEnded = true
      //       if (packfileEnded && errorEnded) output.end()
      //     })
      //   error
      //     .on('data', data => {
      //       const buffers = splitBuffer(data, MAX_PACKET_LENGTH)
      //       for (const buffer of buffers) {
      //         output.write(
      //           GitPktLine.encode(Buffer.concat([Buffer.from('03', 'hex'), buffer]))
      //         )
      //       }
      //     })
      //     .on('end', () => {
      //       errorEnded = true
      //       if (progressEnded && packfileEnded) output.end()
      //     })
      //   return output
      // }
    };
    async function parseUploadPackResponse(stream) {
      const { packetlines, packfile, progress } = GitSideBand.demux(stream);
      const shallows = [];
      const unshallows = [];
      const acks = [];
      let nak = false;
      let done = false;
      return new Promise((resolve, reject) => {
        forAwait(packetlines, (data) => {
          const line = data.toString("utf8").trim();
          if (line.startsWith("shallow")) {
            const oid = line.slice(-41).trim();
            if (oid.length !== 40) {
              reject(new InvalidOidError(oid));
            }
            shallows.push(oid);
          } else if (line.startsWith("unshallow")) {
            const oid = line.slice(-41).trim();
            if (oid.length !== 40) {
              reject(new InvalidOidError(oid));
            }
            unshallows.push(oid);
          } else if (line.startsWith("ACK")) {
            const [, oid, status2] = line.split(" ");
            acks.push({ oid, status: status2 });
            if (!status2) done = true;
          } else if (line.startsWith("NAK")) {
            nak = true;
            done = true;
          } else {
            done = true;
            nak = true;
          }
          if (done) {
            stream.error ? reject(stream.error) : resolve({ shallows, unshallows, acks, nak, packfile, progress });
          }
        }).finally(() => {
          if (!done) {
            stream.error ? reject(stream.error) : resolve({ shallows, unshallows, acks, nak, packfile, progress });
          }
        });
      });
    }
    function writeUploadPackRequest({
      capabilities = [],
      wants = [],
      haves = [],
      shallows = [],
      depth = null,
      since = null,
      exclude = []
    }) {
      const packstream = [];
      wants = [...new Set(wants)];
      let firstLineCapabilities = ` ${capabilities.join(" ")}`;
      for (const oid of wants) {
        packstream.push(GitPktLine.encode(`want ${oid}${firstLineCapabilities}
`));
        firstLineCapabilities = "";
      }
      for (const oid of shallows) {
        packstream.push(GitPktLine.encode(`shallow ${oid}
`));
      }
      if (depth !== null) {
        packstream.push(GitPktLine.encode(`deepen ${depth}
`));
      }
      if (since !== null) {
        packstream.push(
          GitPktLine.encode(`deepen-since ${Math.floor(since.valueOf() / 1e3)}
`)
        );
      }
      for (const oid of exclude) {
        packstream.push(GitPktLine.encode(`deepen-not ${oid}
`));
      }
      packstream.push(GitPktLine.flush());
      for (const oid of haves) {
        packstream.push(GitPktLine.encode(`have ${oid}
`));
      }
      packstream.push(GitPktLine.encode(`done
`));
      return packstream;
    }
    async function _fetch({
      fs: fs2,
      cache,
      http,
      onProgress,
      onMessage,
      onAuth,
      onAuthSuccess,
      onAuthFailure,
      gitdir,
      ref: _ref,
      remoteRef: _remoteRef,
      remote: _remote,
      url: _url,
      corsProxy,
      depth = null,
      since = null,
      exclude = [],
      relative = false,
      tags = false,
      singleBranch = false,
      headers = {},
      prune = false,
      pruneTags = false
    }) {
      const ref = _ref || await _currentBranch({ fs: fs2, gitdir, test: true });
      const config = await GitConfigManager.get({ fs: fs2, gitdir });
      const remote = _remote || ref && await config.get(`branch.${ref}.remote`) || "origin";
      const url = _url || await config.get(`remote.${remote}.url`);
      if (typeof url === "undefined") {
        throw new MissingParameterError("remote OR url");
      }
      const remoteRef = _remoteRef || ref && await config.get(`branch.${ref}.merge`) || _ref || "HEAD";
      if (corsProxy === void 0) {
        corsProxy = await config.get("http.corsProxy");
      }
      const GitRemoteHTTP2 = GitRemoteManager.getRemoteHelperFor({ url });
      const remoteHTTP = await GitRemoteHTTP2.discover({
        http,
        onAuth,
        onAuthSuccess,
        onAuthFailure,
        corsProxy,
        service: "git-upload-pack",
        url,
        headers,
        protocolVersion: 1
      });
      const auth = remoteHTTP.auth;
      const remoteRefs = remoteHTTP.refs;
      if (remoteRefs.size === 0) {
        return {
          defaultBranch: null,
          fetchHead: null,
          fetchHeadDescription: null
        };
      }
      if (depth !== null && !remoteHTTP.capabilities.has("shallow")) {
        throw new RemoteCapabilityError("shallow", "depth");
      }
      if (since !== null && !remoteHTTP.capabilities.has("deepen-since")) {
        throw new RemoteCapabilityError("deepen-since", "since");
      }
      if (exclude.length > 0 && !remoteHTTP.capabilities.has("deepen-not")) {
        throw new RemoteCapabilityError("deepen-not", "exclude");
      }
      if (relative === true && !remoteHTTP.capabilities.has("deepen-relative")) {
        throw new RemoteCapabilityError("deepen-relative", "relative");
      }
      const { oid, fullref } = GitRefManager.resolveAgainstMap({
        ref: remoteRef,
        map: remoteRefs
      });
      for (const remoteRef2 of remoteRefs.keys()) {
        if (remoteRef2 === fullref || remoteRef2 === "HEAD" || remoteRef2.startsWith("refs/heads/") || tags && remoteRef2.startsWith("refs/tags/")) {
          continue;
        }
        remoteRefs.delete(remoteRef2);
      }
      const capabilities = filterCapabilities(
        [...remoteHTTP.capabilities],
        [
          "multi_ack_detailed",
          "no-done",
          "side-band-64k",
          // Note: I removed 'thin-pack' option since our code doesn't "fatten" packfiles,
          // which is necessary for compatibility with git. It was the cause of mysterious
          // 'fatal: pack has [x] unresolved deltas' errors that plagued us for some time.
          // isomorphic-git is perfectly happy with thin packfiles in .git/objects/pack but
          // canonical git it turns out is NOT.
          "ofs-delta",
          `agent=${pkg.agent}`
        ]
      );
      if (relative) capabilities.push("deepen-relative");
      const wants = singleBranch ? [oid] : remoteRefs.values();
      const haveRefs = singleBranch ? [ref] : await GitRefManager.listRefs({
        fs: fs2,
        gitdir,
        filepath: `refs`
      });
      let haves = [];
      for (let ref2 of haveRefs) {
        try {
          ref2 = await GitRefManager.expand({ fs: fs2, gitdir, ref: ref2 });
          const oid2 = await GitRefManager.resolve({ fs: fs2, gitdir, ref: ref2 });
          if (await hasObject({ fs: fs2, cache, gitdir, oid: oid2 })) {
            haves.push(oid2);
          }
        } catch (err) {
        }
      }
      haves = [...new Set(haves)];
      const oids = await GitShallowManager.read({ fs: fs2, gitdir });
      const shallows = remoteHTTP.capabilities.has("shallow") ? [...oids] : [];
      const packstream = writeUploadPackRequest({
        capabilities,
        wants,
        haves,
        shallows,
        depth,
        since,
        exclude
      });
      const packbuffer = Buffer.from(await collect(packstream));
      const raw = await GitRemoteHTTP2.connect({
        http,
        onProgress,
        corsProxy,
        service: "git-upload-pack",
        url,
        auth,
        body: [packbuffer],
        headers
      });
      const response = await parseUploadPackResponse(raw.body);
      if (raw.headers) {
        response.headers = raw.headers;
      }
      for (const oid2 of response.shallows) {
        if (!oids.has(oid2)) {
          try {
            const { object } = await _readObject({ fs: fs2, cache, gitdir, oid: oid2 });
            const commit2 = new GitCommit(object);
            const hasParents = await Promise.all(
              commit2.headers().parent.map((oid3) => hasObject({ fs: fs2, cache, gitdir, oid: oid3 }))
            );
            const haveAllParents = hasParents.length === 0 || hasParents.every((has) => has);
            if (!haveAllParents) {
              oids.add(oid2);
            }
          } catch (err) {
            oids.add(oid2);
          }
        }
      }
      for (const oid2 of response.unshallows) {
        oids.delete(oid2);
      }
      await GitShallowManager.write({ fs: fs2, gitdir, oids });
      if (singleBranch) {
        const refs = /* @__PURE__ */ new Map([[fullref, oid]]);
        const symrefs = /* @__PURE__ */ new Map();
        let bail = 10;
        let key = fullref;
        while (bail--) {
          const value = remoteHTTP.symrefs.get(key);
          if (value === void 0) break;
          symrefs.set(key, value);
          key = value;
        }
        const realRef = remoteRefs.get(key);
        if (realRef) {
          refs.set(key, realRef);
        }
        const { pruned } = await GitRefManager.updateRemoteRefs({
          fs: fs2,
          gitdir,
          remote,
          refs,
          symrefs,
          tags,
          prune
        });
        if (prune) {
          response.pruned = pruned;
        }
      } else {
        const { pruned } = await GitRefManager.updateRemoteRefs({
          fs: fs2,
          gitdir,
          remote,
          refs: remoteRefs,
          symrefs: remoteHTTP.symrefs,
          tags,
          prune,
          pruneTags
        });
        if (prune) {
          response.pruned = pruned;
        }
      }
      response.HEAD = remoteHTTP.symrefs.get("HEAD");
      if (response.HEAD === void 0) {
        const { oid: oid2 } = GitRefManager.resolveAgainstMap({
          ref: "HEAD",
          map: remoteRefs
        });
        for (const [key, value] of remoteRefs.entries()) {
          if (key !== "HEAD" && value === oid2) {
            response.HEAD = key;
            break;
          }
        }
      }
      const noun = fullref.startsWith("refs/tags") ? "tag" : "branch";
      response.FETCH_HEAD = {
        oid,
        description: `${noun} '${abbreviateRef(fullref)}' of ${url}`
      };
      if (onProgress || onMessage) {
        const lines = splitLines(response.progress);
        forAwait(lines, async (line) => {
          if (onMessage) await onMessage(line);
          if (onProgress) {
            const matches = line.match(/([^:]*).*\((\d+?)\/(\d+?)\)/);
            if (matches) {
              await onProgress({
                phase: matches[1].trim(),
                loaded: parseInt(matches[2], 10),
                total: parseInt(matches[3], 10)
              });
            }
          }
        });
      }
      const packfile = Buffer.from(await collect(response.packfile));
      if (raw.body.error) throw raw.body.error;
      const packfileSha = packfile.slice(-20).toString("hex");
      const res = {
        defaultBranch: response.HEAD,
        fetchHead: response.FETCH_HEAD.oid,
        fetchHeadDescription: response.FETCH_HEAD.description
      };
      if (response.headers) {
        res.headers = response.headers;
      }
      if (prune) {
        res.pruned = response.pruned;
      }
      if (packfileSha !== "" && !emptyPackfile(packfile)) {
        res.packfile = `objects/pack/pack-${packfileSha}.pack`;
        const fullpath = join(gitdir, res.packfile);
        await fs2.write(fullpath, packfile);
        const getExternalRefDelta = (oid2) => _readObject({ fs: fs2, cache, gitdir, oid: oid2 });
        const idx = await GitPackIndex.fromPack({
          pack: packfile,
          getExternalRefDelta,
          onProgress
        });
        await fs2.write(fullpath.replace(/\.pack$/, ".idx"), await idx.toBuffer());
      }
      return res;
    }
    async function _init({
      fs: fs2,
      bare = false,
      dir,
      gitdir = bare ? dir : join(dir, ".git"),
      defaultBranch = "master"
    }) {
      if (await fs2.exists(gitdir + "/config")) return;
      let folders = [
        "hooks",
        "info",
        "objects/info",
        "objects/pack",
        "refs/heads",
        "refs/tags"
      ];
      folders = folders.map((dir2) => gitdir + "/" + dir2);
      for (const folder of folders) {
        await fs2.mkdir(folder);
      }
      await fs2.write(
        gitdir + "/config",
        `[core]
	repositoryformatversion = 0
	filemode = false
	bare = ${bare}
` + (bare ? "" : "	logallrefupdates = true\n") + "	symlinks = false\n	ignorecase = true\n"
      );
      await fs2.write(gitdir + "/HEAD", `ref: refs/heads/${defaultBranch}
`);
    }
    async function _clone({
      fs: fs2,
      cache,
      http,
      onProgress,
      onMessage,
      onAuth,
      onAuthSuccess,
      onAuthFailure,
      onPostCheckout,
      dir,
      gitdir,
      url,
      corsProxy,
      ref,
      remote,
      depth,
      since,
      exclude,
      relative,
      singleBranch,
      noCheckout,
      noTags,
      headers,
      nonBlocking,
      batchSize = 100
    }) {
      try {
        await _init({ fs: fs2, gitdir });
        await _addRemote({ fs: fs2, gitdir, remote, url, force: false });
        if (corsProxy) {
          const config = await GitConfigManager.get({ fs: fs2, gitdir });
          await config.set(`http.corsProxy`, corsProxy);
          await GitConfigManager.save({ fs: fs2, gitdir, config });
        }
        const { defaultBranch, fetchHead } = await _fetch({
          fs: fs2,
          cache,
          http,
          onProgress,
          onMessage,
          onAuth,
          onAuthSuccess,
          onAuthFailure,
          gitdir,
          ref,
          remote,
          corsProxy,
          depth,
          since,
          exclude,
          relative,
          singleBranch,
          headers,
          tags: !noTags
        });
        if (fetchHead === null) return;
        ref = ref || defaultBranch;
        ref = ref.replace("refs/heads/", "");
        await _checkout({
          fs: fs2,
          cache,
          onProgress,
          onPostCheckout,
          dir,
          gitdir,
          ref,
          remote,
          noCheckout,
          nonBlocking,
          batchSize
        });
      } catch (err) {
        await fs2.rmdir(gitdir, { recursive: true, maxRetries: 10 }).catch(() => void 0);
        throw err;
      }
    }
    async function clone3({
      fs: fs2,
      http,
      onProgress,
      onMessage,
      onAuth,
      onAuthSuccess,
      onAuthFailure,
      onPostCheckout,
      dir,
      gitdir = join(dir, ".git"),
      url,
      corsProxy = void 0,
      ref = void 0,
      remote = "origin",
      depth = void 0,
      since = void 0,
      exclude = [],
      relative = false,
      singleBranch = false,
      noCheckout = false,
      noTags = false,
      headers = {},
      cache = {},
      nonBlocking = false,
      batchSize = 100
    }) {
      try {
        assertParameter("fs", fs2);
        assertParameter("http", http);
        assertParameter("gitdir", gitdir);
        if (!noCheckout) {
          assertParameter("dir", dir);
        }
        assertParameter("url", url);
        const fsp = new FileSystem(fs2);
        const updatedGitdir = await discoverGitdir({ fsp, dotgit: gitdir });
        return await _clone({
          fs: fsp,
          cache,
          http,
          onProgress,
          onMessage,
          onAuth,
          onAuthSuccess,
          onAuthFailure,
          onPostCheckout,
          dir,
          gitdir: updatedGitdir,
          url,
          corsProxy,
          ref,
          remote,
          depth,
          since,
          exclude,
          relative,
          singleBranch,
          noCheckout,
          noTags,
          headers,
          nonBlocking,
          batchSize
        });
      } catch (err) {
        err.caller = "git.clone";
        throw err;
      }
    }
    async function commit({
      fs: _fs,
      onSign,
      dir,
      gitdir = join(dir, ".git"),
      message,
      author,
      committer,
      signingKey,
      amend = false,
      dryRun = false,
      noUpdateBranch = false,
      ref,
      parent,
      tree,
      cache = {}
    }) {
      try {
        assertParameter("fs", _fs);
        if (!amend) {
          assertParameter("message", message);
        }
        if (signingKey) {
          assertParameter("onSign", onSign);
        }
        const fs2 = new FileSystem(_fs);
        const updatedGitdir = await discoverGitdir({ fsp: fs2, dotgit: gitdir });
        return await _commit({
          fs: fs2,
          cache,
          onSign,
          gitdir: updatedGitdir,
          message,
          author,
          committer,
          signingKey,
          amend,
          dryRun,
          noUpdateBranch,
          ref,
          parent,
          tree
        });
      } catch (err) {
        err.caller = "git.commit";
        throw err;
      }
    }
    async function currentBranch({
      fs: fs2,
      dir,
      gitdir = join(dir, ".git"),
      fullname = false,
      test = false
    }) {
      try {
        assertParameter("fs", fs2);
        assertParameter("gitdir", gitdir);
        const fsp = new FileSystem(fs2);
        const updatedGitdir = await discoverGitdir({ fsp, dotgit: gitdir });
        return await _currentBranch({
          fs: fsp,
          gitdir: updatedGitdir,
          fullname,
          test
        });
      } catch (err) {
        err.caller = "git.currentBranch";
        throw err;
      }
    }
    async function _deleteBranch({ fs: fs2, gitdir, ref }) {
      ref = ref.startsWith("refs/heads/") ? ref : `refs/heads/${ref}`;
      const exist = await GitRefManager.exists({ fs: fs2, gitdir, ref });
      if (!exist) {
        throw new NotFoundError(ref);
      }
      const fullRef = await GitRefManager.expand({ fs: fs2, gitdir, ref });
      const currentRef = await _currentBranch({ fs: fs2, gitdir, fullname: true });
      if (fullRef === currentRef) {
        const value = await GitRefManager.resolve({ fs: fs2, gitdir, ref: fullRef });
        await GitRefManager.writeRef({ fs: fs2, gitdir, ref: "HEAD", value });
      }
      await GitRefManager.deleteRef({ fs: fs2, gitdir, ref: fullRef });
      const abbrevRef = abbreviateRef(ref);
      const config = await GitConfigManager.get({ fs: fs2, gitdir });
      await config.deleteSection("branch", abbrevRef);
      await GitConfigManager.save({ fs: fs2, gitdir, config });
    }
    async function deleteBranch({
      fs: fs2,
      dir,
      gitdir = join(dir, ".git"),
      ref
    }) {
      try {
        assertParameter("fs", fs2);
        assertParameter("ref", ref);
        const fsp = new FileSystem(fs2);
        const updatedGitdir = await discoverGitdir({ fsp, dotgit: gitdir });
        return await _deleteBranch({
          fs: fsp,
          gitdir: updatedGitdir,
          ref
        });
      } catch (err) {
        err.caller = "git.deleteBranch";
        throw err;
      }
    }
    async function deleteRef({ fs: fs2, dir, gitdir = join(dir, ".git"), ref }) {
      try {
        assertParameter("fs", fs2);
        assertParameter("ref", ref);
        const fsp = new FileSystem(fs2);
        const updatedGitdir = await discoverGitdir({ fsp, dotgit: gitdir });
        await GitRefManager.deleteRef({ fs: fsp, gitdir: updatedGitdir, ref });
      } catch (err) {
        err.caller = "git.deleteRef";
        throw err;
      }
    }
    async function _deleteRemote({ fs: fs2, gitdir, remote }) {
      const config = await GitConfigManager.get({ fs: fs2, gitdir });
      await config.deleteSection("remote", remote);
      await GitConfigManager.save({ fs: fs2, gitdir, config });
    }
    async function deleteRemote({
      fs: fs2,
      dir,
      gitdir = join(dir, ".git"),
      remote
    }) {
      try {
        assertParameter("fs", fs2);
        assertParameter("remote", remote);
        const fsp = new FileSystem(fs2);
        const updatedGitdir = await discoverGitdir({ fsp, dotgit: gitdir });
        return await _deleteRemote({
          fs: fsp,
          gitdir: updatedGitdir,
          remote
        });
      } catch (err) {
        err.caller = "git.deleteRemote";
        throw err;
      }
    }
    async function _deleteTag({ fs: fs2, gitdir, ref }) {
      ref = ref.startsWith("refs/tags/") ? ref : `refs/tags/${ref}`;
      await GitRefManager.deleteRef({ fs: fs2, gitdir, ref });
    }
    async function deleteTag({ fs: fs2, dir, gitdir = join(dir, ".git"), ref }) {
      try {
        assertParameter("fs", fs2);
        assertParameter("ref", ref);
        const fsp = new FileSystem(fs2);
        const updatedGitdir = await discoverGitdir({ fsp, dotgit: gitdir });
        return await _deleteTag({
          fs: fsp,
          gitdir: updatedGitdir,
          ref
        });
      } catch (err) {
        err.caller = "git.deleteTag";
        throw err;
      }
    }
    async function expandOidLoose({ fs: fs2, gitdir, oid: short }) {
      const prefix = short.slice(0, 2);
      const objectsSuffixes = await fs2.readdir(`${gitdir}/objects/${prefix}`);
      return objectsSuffixes.map((suffix) => `${prefix}${suffix}`).filter((_oid) => _oid.startsWith(short));
    }
    async function expandOidPacked({
      fs: fs2,
      cache,
      gitdir,
      oid: short,
      getExternalRefDelta
    }) {
      const results = [];
      let list = await fs2.readdir(join(gitdir, "objects/pack"));
      list = list.filter((x) => x.endsWith(".idx"));
      for (const filename of list) {
        const indexFile = `${gitdir}/objects/pack/${filename}`;
        const p = await readPackIndex({
          fs: fs2,
          cache,
          filename: indexFile,
          getExternalRefDelta
        });
        if (p.error) throw new InternalError(p.error);
        for (const oid of p.offsets.keys()) {
          if (oid.startsWith(short)) results.push(oid);
        }
      }
      return results;
    }
    async function _expandOid({ fs: fs2, cache, gitdir, oid: short }) {
      const getExternalRefDelta = (oid) => _readObject({ fs: fs2, cache, gitdir, oid });
      const results = await expandOidLoose({ fs: fs2, gitdir, oid: short });
      const packedOids = await expandOidPacked({
        fs: fs2,
        cache,
        gitdir,
        oid: short,
        getExternalRefDelta
      });
      for (const packedOid of packedOids) {
        if (results.indexOf(packedOid) === -1) {
          results.push(packedOid);
        }
      }
      if (results.length === 1) {
        return results[0];
      }
      if (results.length > 1) {
        throw new AmbiguousError("oids", short, results);
      }
      throw new NotFoundError(`an object matching "${short}"`);
    }
    async function expandOid({
      fs: fs2,
      dir,
      gitdir = join(dir, ".git"),
      oid,
      cache = {}
    }) {
      try {
        assertParameter("fs", fs2);
        assertParameter("gitdir", gitdir);
        assertParameter("oid", oid);
        const fsp = new FileSystem(fs2);
        const updatedGitdir = await discoverGitdir({ fsp, dotgit: gitdir });
        return await _expandOid({
          fs: fsp,
          cache,
          gitdir: updatedGitdir,
          oid
        });
      } catch (err) {
        err.caller = "git.expandOid";
        throw err;
      }
    }
    async function expandRef({ fs: fs2, dir, gitdir = join(dir, ".git"), ref }) {
      try {
        assertParameter("fs", fs2);
        assertParameter("gitdir", gitdir);
        assertParameter("ref", ref);
        const fsp = new FileSystem(fs2);
        const updatedGitdir = await discoverGitdir({ fsp, dotgit: gitdir });
        return await GitRefManager.expand({
          fs: fsp,
          gitdir: updatedGitdir,
          ref
        });
      } catch (err) {
        err.caller = "git.expandRef";
        throw err;
      }
    }
    async function _findMergeBase({ fs: fs2, cache, gitdir, oids }) {
      const visits = {};
      const passes = oids.length;
      let heads = oids.map((oid, index2) => ({ index: index2, oid }));
      while (heads.length) {
        const result = /* @__PURE__ */ new Set();
        for (const { oid, index: index2 } of heads) {
          if (!visits[oid]) visits[oid] = /* @__PURE__ */ new Set();
          visits[oid].add(index2);
          if (visits[oid].size === passes) {
            result.add(oid);
          }
        }
        if (result.size > 0) {
          return [...result];
        }
        const newheads = /* @__PURE__ */ new Map();
        for (const { oid, index: index2 } of heads) {
          try {
            const { object } = await _readObject({ fs: fs2, cache, gitdir, oid });
            const commit2 = GitCommit.from(object);
            const { parent } = commit2.parseHeaders();
            for (const oid2 of parent) {
              if (!visits[oid2] || !visits[oid2].has(index2)) {
                newheads.set(oid2 + ":" + index2, { oid: oid2, index: index2 });
              }
            }
          } catch (err) {
          }
        }
        heads = Array.from(newheads.values());
      }
      return [];
    }
    var LINEBREAKS = /^.*(\r?\n|$)/gm;
    function mergeFile({ branches, contents }) {
      const ourName = branches[1];
      const theirName = branches[2];
      const baseContent = contents[0];
      const ourContent = contents[1];
      const theirContent = contents[2];
      const ours = ourContent.match(LINEBREAKS);
      const base = baseContent.match(LINEBREAKS);
      const theirs = theirContent.match(LINEBREAKS);
      const result = diff3Merge(ours, base, theirs);
      const markerSize = 7;
      let mergedText = "";
      let cleanMerge = true;
      for (const item of result) {
        if (item.ok) {
          mergedText += item.ok.join("");
        }
        if (item.conflict) {
          cleanMerge = false;
          mergedText += `${"<".repeat(markerSize)} ${ourName}
`;
          mergedText += item.conflict.a.join("");
          mergedText += `${"=".repeat(markerSize)}
`;
          mergedText += item.conflict.b.join("");
          mergedText += `${">".repeat(markerSize)} ${theirName}
`;
        }
      }
      return { cleanMerge, mergedText };
    }
    async function mergeTree({
      fs: fs2,
      cache,
      dir,
      gitdir = join(dir, ".git"),
      index: index2,
      ourOid,
      baseOid,
      theirOid,
      ourName = "ours",
      baseName = "base",
      theirName = "theirs",
      dryRun = false,
      abortOnConflict = true,
      mergeDriver
    }) {
      const ourTree = TREE({ ref: ourOid });
      const baseTree = TREE({ ref: baseOid });
      const theirTree = TREE({ ref: theirOid });
      const unmergedFiles = [];
      const bothModified = [];
      const deleteByUs = [];
      const deleteByTheirs = [];
      const results = await _walk({
        fs: fs2,
        cache,
        dir,
        gitdir,
        trees: [ourTree, baseTree, theirTree],
        map: async function(filepath, [ours, base, theirs]) {
          const path = basename(filepath);
          const ourChange = await modified(ours, base);
          const theirChange = await modified(theirs, base);
          switch (`${ourChange}-${theirChange}`) {
            case "false-false": {
              return {
                mode: await base.mode(),
                path,
                oid: await base.oid(),
                type: await base.type()
              };
            }
            case "false-true": {
              if (!theirs && await ours.type() === "tree") {
                return {
                  mode: await ours.mode(),
                  path,
                  oid: await ours.oid(),
                  type: await ours.type()
                };
              }
              return theirs ? {
                mode: await theirs.mode(),
                path,
                oid: await theirs.oid(),
                type: await theirs.type()
              } : void 0;
            }
            case "true-false": {
              if (!ours && await theirs.type() === "tree") {
                return {
                  mode: await theirs.mode(),
                  path,
                  oid: await theirs.oid(),
                  type: await theirs.type()
                };
              }
              return ours ? {
                mode: await ours.mode(),
                path,
                oid: await ours.oid(),
                type: await ours.type()
              } : void 0;
            }
            case "true-true": {
              if (ours && theirs && await ours.type() === "tree" && await theirs.type() === "tree") {
                return {
                  mode: await ours.mode(),
                  path,
                  oid: await ours.oid(),
                  type: "tree"
                };
              }
              if (ours && theirs && await ours.type() === "blob" && await theirs.type() === "blob") {
                return mergeBlobs({
                  fs: fs2,
                  gitdir,
                  path,
                  ours,
                  base,
                  theirs,
                  ourName,
                  baseName,
                  theirName,
                  mergeDriver
                }).then(async (r) => {
                  if (!r.cleanMerge) {
                    unmergedFiles.push(filepath);
                    bothModified.push(filepath);
                    if (!abortOnConflict) {
                      let baseOid2 = "";
                      if (base && await base.type() === "blob") {
                        baseOid2 = await base.oid();
                      }
                      const ourOid2 = await ours.oid();
                      const theirOid2 = await theirs.oid();
                      index2.delete({ filepath });
                      if (baseOid2) {
                        index2.insert({ filepath, oid: baseOid2, stage: 1 });
                      }
                      index2.insert({ filepath, oid: ourOid2, stage: 2 });
                      index2.insert({ filepath, oid: theirOid2, stage: 3 });
                    }
                  } else if (!abortOnConflict) {
                    index2.insert({ filepath, oid: r.mergeResult.oid, stage: 0 });
                  }
                  return r.mergeResult;
                });
              }
              if (base && !ours && theirs && await base.type() === "blob" && await theirs.type() === "blob") {
                unmergedFiles.push(filepath);
                deleteByUs.push(filepath);
                if (!abortOnConflict) {
                  const baseOid2 = await base.oid();
                  const theirOid2 = await theirs.oid();
                  index2.delete({ filepath });
                  index2.insert({ filepath, oid: baseOid2, stage: 1 });
                  index2.insert({ filepath, oid: theirOid2, stage: 3 });
                }
                return {
                  mode: await theirs.mode(),
                  oid: await theirs.oid(),
                  type: "blob",
                  path
                };
              }
              if (base && ours && !theirs && await base.type() === "blob" && await ours.type() === "blob") {
                unmergedFiles.push(filepath);
                deleteByTheirs.push(filepath);
                if (!abortOnConflict) {
                  const baseOid2 = await base.oid();
                  const ourOid2 = await ours.oid();
                  index2.delete({ filepath });
                  index2.insert({ filepath, oid: baseOid2, stage: 1 });
                  index2.insert({ filepath, oid: ourOid2, stage: 2 });
                }
                return {
                  mode: await ours.mode(),
                  oid: await ours.oid(),
                  type: "blob",
                  path
                };
              }
              if (base && !ours && !theirs && (await base.type() === "blob" || await base.type() === "tree")) {
                return void 0;
              }
              throw new MergeNotSupportedError();
            }
          }
        },
        /**
         * @param {TreeEntry} [parent]
         * @param {Array<TreeEntry>} children
         */
        reduce: unmergedFiles.length !== 0 && (!dir || abortOnConflict) ? void 0 : async (parent, children2) => {
          const entries = children2.filter(Boolean);
          if (!parent) return;
          if (parent && parent.type === "tree" && entries.length === 0 && parent.path !== ".")
            return;
          if (entries.length > 0 || parent.path === "." && entries.length === 0) {
            const tree = new GitTree(entries);
            const object = tree.toObject();
            const oid = await _writeObject({
              fs: fs2,
              gitdir,
              type: "tree",
              object,
              dryRun
            });
            parent.oid = oid;
          }
          return parent;
        }
      });
      if (unmergedFiles.length !== 0) {
        if (dir && !abortOnConflict) {
          await _walk({
            fs: fs2,
            cache,
            dir,
            gitdir,
            trees: [TREE({ ref: results.oid })],
            map: async function(filepath, [entry]) {
              const path = `${dir}/${filepath}`;
              if (await entry.type() === "blob") {
                const mode = await entry.mode();
                const content = new TextDecoder().decode(await entry.content());
                await fs2.write(path, content, { mode });
              }
              return true;
            }
          });
        }
        return new MergeConflictError(
          unmergedFiles,
          bothModified,
          deleteByUs,
          deleteByTheirs
        );
      }
      return results.oid;
    }
    async function mergeBlobs({
      fs: fs2,
      gitdir,
      path,
      ours,
      base,
      theirs,
      ourName,
      theirName,
      baseName,
      dryRun,
      mergeDriver = mergeFile
    }) {
      const type = "blob";
      let baseMode = "100755";
      let baseOid = "";
      let baseContent = "";
      if (base && await base.type() === "blob") {
        baseMode = await base.mode();
        baseOid = await base.oid();
        baseContent = Buffer.from(await base.content()).toString("utf8");
      }
      const mode = baseMode === await ours.mode() ? await theirs.mode() : await ours.mode();
      if (await ours.oid() === await theirs.oid()) {
        return {
          cleanMerge: true,
          mergeResult: { mode, path, oid: await ours.oid(), type }
        };
      }
      if (await ours.oid() === baseOid) {
        return {
          cleanMerge: true,
          mergeResult: { mode, path, oid: await theirs.oid(), type }
        };
      }
      if (await theirs.oid() === baseOid) {
        return {
          cleanMerge: true,
          mergeResult: { mode, path, oid: await ours.oid(), type }
        };
      }
      const ourContent = Buffer.from(await ours.content()).toString("utf8");
      const theirContent = Buffer.from(await theirs.content()).toString("utf8");
      const { mergedText, cleanMerge } = await mergeDriver({
        branches: [baseName, ourName, theirName],
        contents: [baseContent, ourContent, theirContent],
        path
      });
      const oid = await _writeObject({
        fs: fs2,
        gitdir,
        type: "blob",
        object: Buffer.from(mergedText, "utf8"),
        dryRun
      });
      return { cleanMerge, mergeResult: { mode, path, oid, type } };
    }
    async function _merge({
      fs: fs2,
      cache,
      dir,
      gitdir,
      ours,
      theirs,
      fastForward: fastForward2 = true,
      fastForwardOnly = false,
      dryRun = false,
      noUpdateBranch = false,
      abortOnConflict = true,
      message,
      author,
      committer,
      signingKey,
      onSign,
      mergeDriver,
      allowUnrelatedHistories = false
    }) {
      if (ours === void 0) {
        ours = await _currentBranch({ fs: fs2, gitdir, fullname: true });
      }
      ours = await GitRefManager.expand({
        fs: fs2,
        gitdir,
        ref: ours
      });
      theirs = await GitRefManager.expand({
        fs: fs2,
        gitdir,
        ref: theirs
      });
      const ourOid = await GitRefManager.resolve({
        fs: fs2,
        gitdir,
        ref: ours
      });
      const theirOid = await GitRefManager.resolve({
        fs: fs2,
        gitdir,
        ref: theirs
      });
      const baseOids = await _findMergeBase({
        fs: fs2,
        cache,
        gitdir,
        oids: [ourOid, theirOid]
      });
      if (baseOids.length !== 1) {
        if (baseOids.length === 0 && allowUnrelatedHistories) {
          baseOids.push("4b825dc642cb6eb9a060e54bf8d69288fbee4904");
        } else {
          throw new MergeNotSupportedError();
        }
      }
      const baseOid = baseOids[0];
      if (baseOid === theirOid) {
        return {
          oid: ourOid,
          alreadyMerged: true
        };
      }
      if (fastForward2 && baseOid === ourOid) {
        if (!dryRun && !noUpdateBranch) {
          await GitRefManager.writeRef({ fs: fs2, gitdir, ref: ours, value: theirOid });
        }
        return {
          oid: theirOid,
          fastForward: true
        };
      } else {
        if (fastForwardOnly) {
          throw new FastForwardError();
        }
        const tree = await GitIndexManager.acquire(
          { fs: fs2, gitdir, cache, allowUnmerged: false },
          async (index2) => {
            return mergeTree({
              fs: fs2,
              cache,
              dir,
              gitdir,
              index: index2,
              ourOid,
              theirOid,
              baseOid,
              ourName: abbreviateRef(ours),
              baseName: "base",
              theirName: abbreviateRef(theirs),
              dryRun,
              abortOnConflict,
              mergeDriver
            });
          }
        );
        if (tree instanceof MergeConflictError) throw tree;
        if (!message) {
          message = `Merge branch '${abbreviateRef(theirs)}' into ${abbreviateRef(
            ours
          )}`;
        }
        const oid = await _commit({
          fs: fs2,
          cache,
          gitdir,
          message,
          ref: ours,
          tree,
          parent: [ourOid, theirOid],
          author,
          committer,
          signingKey,
          onSign,
          dryRun,
          noUpdateBranch
        });
        return {
          oid,
          tree,
          mergeCommit: true
        };
      }
    }
    async function _pull({
      fs: fs2,
      cache,
      http,
      onProgress,
      onMessage,
      onAuth,
      onAuthSuccess,
      onAuthFailure,
      dir,
      gitdir,
      ref,
      url,
      remote,
      remoteRef,
      prune,
      pruneTags,
      fastForward: fastForward2,
      fastForwardOnly,
      corsProxy,
      singleBranch,
      headers,
      author,
      committer,
      signingKey
    }) {
      try {
        if (!ref) {
          const head = await _currentBranch({ fs: fs2, gitdir });
          if (!head) {
            throw new MissingParameterError("ref");
          }
          ref = head;
        }
        const { fetchHead, fetchHeadDescription } = await _fetch({
          fs: fs2,
          cache,
          http,
          onProgress,
          onMessage,
          onAuth,
          onAuthSuccess,
          onAuthFailure,
          gitdir,
          corsProxy,
          ref,
          url,
          remote,
          remoteRef,
          singleBranch,
          headers,
          prune,
          pruneTags
        });
        await _merge({
          fs: fs2,
          cache,
          gitdir,
          ours: ref,
          theirs: fetchHead,
          fastForward: fastForward2,
          fastForwardOnly,
          message: `Merge ${fetchHeadDescription}`,
          author,
          committer,
          signingKey,
          dryRun: false,
          noUpdateBranch: false
        });
        await _checkout({
          fs: fs2,
          cache,
          onProgress,
          dir,
          gitdir,
          ref,
          remote,
          noCheckout: false
        });
      } catch (err) {
        err.caller = "git.pull";
        throw err;
      }
    }
    async function fastForward({
      fs: fs2,
      http,
      onProgress,
      onMessage,
      onAuth,
      onAuthSuccess,
      onAuthFailure,
      dir,
      gitdir = join(dir, ".git"),
      ref,
      url,
      remote,
      remoteRef,
      corsProxy,
      singleBranch,
      headers = {},
      cache = {}
    }) {
      try {
        assertParameter("fs", fs2);
        assertParameter("http", http);
        assertParameter("gitdir", gitdir);
        const thisWillNotBeUsed = {
          name: "",
          email: "",
          timestamp: Date.now(),
          timezoneOffset: 0
        };
        const fsp = new FileSystem(fs2);
        const updatedGitdir = await discoverGitdir({ fsp, dotgit: gitdir });
        return await _pull({
          fs: fsp,
          cache,
          http,
          onProgress,
          onMessage,
          onAuth,
          onAuthSuccess,
          onAuthFailure,
          dir,
          gitdir: updatedGitdir,
          ref,
          url,
          remote,
          remoteRef,
          fastForwardOnly: true,
          corsProxy,
          singleBranch,
          headers,
          author: thisWillNotBeUsed,
          committer: thisWillNotBeUsed
        });
      } catch (err) {
        err.caller = "git.fastForward";
        throw err;
      }
    }
    async function fetch2({
      fs: fs2,
      http,
      onProgress,
      onMessage,
      onAuth,
      onAuthSuccess,
      onAuthFailure,
      dir,
      gitdir = join(dir, ".git"),
      ref,
      remote,
      remoteRef,
      url,
      corsProxy,
      depth = null,
      since = null,
      exclude = [],
      relative = false,
      tags = false,
      singleBranch = false,
      headers = {},
      prune = false,
      pruneTags = false,
      cache = {}
    }) {
      try {
        assertParameter("fs", fs2);
        assertParameter("http", http);
        assertParameter("gitdir", gitdir);
        const fsp = new FileSystem(fs2);
        const updatedGitdir = await discoverGitdir({ fsp, dotgit: gitdir });
        return await _fetch({
          fs: fsp,
          cache,
          http,
          onProgress,
          onMessage,
          onAuth,
          onAuthSuccess,
          onAuthFailure,
          gitdir: updatedGitdir,
          ref,
          remote,
          remoteRef,
          url,
          corsProxy,
          depth,
          since,
          exclude,
          relative,
          tags,
          singleBranch,
          headers,
          prune,
          pruneTags
        });
      } catch (err) {
        err.caller = "git.fetch";
        throw err;
      }
    }
    async function findMergeBase({
      fs: fs2,
      dir,
      gitdir = join(dir, ".git"),
      oids,
      cache = {}
    }) {
      try {
        assertParameter("fs", fs2);
        assertParameter("gitdir", gitdir);
        assertParameter("oids", oids);
        const fsp = new FileSystem(fs2);
        const updatedGitdir = await discoverGitdir({ fsp, dotgit: gitdir });
        return await _findMergeBase({
          fs: fsp,
          cache,
          gitdir: updatedGitdir,
          oids
        });
      } catch (err) {
        err.caller = "git.findMergeBase";
        throw err;
      }
    }
    async function _findRoot({ fs: fs2, filepath }) {
      if (await fs2.exists(join(filepath, ".git"))) {
        return filepath;
      } else {
        const parent = dirname(filepath);
        if (parent === filepath) {
          throw new NotFoundError(`git root for ${filepath}`);
        }
        return _findRoot({ fs: fs2, filepath: parent });
      }
    }
    async function findRoot({ fs: fs2, filepath }) {
      try {
        assertParameter("fs", fs2);
        assertParameter("filepath", filepath);
        return await _findRoot({ fs: new FileSystem(fs2), filepath });
      } catch (err) {
        err.caller = "git.findRoot";
        throw err;
      }
    }
    async function getConfig({ fs: fs2, dir, gitdir = join(dir, ".git"), path }) {
      try {
        assertParameter("fs", fs2);
        assertParameter("gitdir", gitdir);
        assertParameter("path", path);
        const fsp = new FileSystem(fs2);
        const updatedGitdir = await discoverGitdir({ fsp, dotgit: gitdir });
        return await _getConfig({
          fs: fsp,
          gitdir: updatedGitdir,
          path
        });
      } catch (err) {
        err.caller = "git.getConfig";
        throw err;
      }
    }
    async function _getConfigAll({ fs: fs2, gitdir, path }) {
      const config = await GitConfigManager.get({ fs: fs2, gitdir });
      return config.getall(path);
    }
    async function getConfigAll({
      fs: fs2,
      dir,
      gitdir = join(dir, ".git"),
      path
    }) {
      try {
        assertParameter("fs", fs2);
        assertParameter("gitdir", gitdir);
        assertParameter("path", path);
        const fsp = new FileSystem(fs2);
        const updatedGitdir = await discoverGitdir({ fsp, dotgit: gitdir });
        return await _getConfigAll({
          fs: fsp,
          gitdir: updatedGitdir,
          path
        });
      } catch (err) {
        err.caller = "git.getConfigAll";
        throw err;
      }
    }
    async function getRemoteInfo({
      http,
      onAuth,
      onAuthSuccess,
      onAuthFailure,
      corsProxy,
      url,
      headers = {},
      forPush = false
    }) {
      try {
        assertParameter("http", http);
        assertParameter("url", url);
        const GitRemoteHTTP2 = GitRemoteManager.getRemoteHelperFor({ url });
        const remote = await GitRemoteHTTP2.discover({
          http,
          onAuth,
          onAuthSuccess,
          onAuthFailure,
          corsProxy,
          service: forPush ? "git-receive-pack" : "git-upload-pack",
          url,
          headers,
          protocolVersion: 1
        });
        const result = {
          capabilities: [...remote.capabilities]
        };
        for (const [ref, oid] of remote.refs) {
          const parts = ref.split("/");
          const last = parts.pop();
          let o = result;
          for (const part of parts) {
            o[part] = o[part] || {};
            o = o[part];
          }
          o[last] = oid;
        }
        for (const [symref, ref] of remote.symrefs) {
          const parts = symref.split("/");
          const last = parts.pop();
          let o = result;
          for (const part of parts) {
            o[part] = o[part] || {};
            o = o[part];
          }
          o[last] = ref;
        }
        return result;
      } catch (err) {
        err.caller = "git.getRemoteInfo";
        throw err;
      }
    }
    function formatInfoRefs(remote, prefix, symrefs, peelTags) {
      const refs = [];
      for (const [key, value] of remote.refs) {
        if (prefix && !key.startsWith(prefix)) continue;
        if (key.endsWith("^{}")) {
          if (peelTags) {
            const _key = key.replace("^{}", "");
            const last = refs[refs.length - 1];
            const r = last.ref === _key ? last : refs.find((x) => x.ref === _key);
            if (r === void 0) {
              throw new Error("I did not expect this to happen");
            }
            r.peeled = value;
          }
          continue;
        }
        const ref = { ref: key, oid: value };
        if (symrefs) {
          if (remote.symrefs.has(key)) {
            ref.target = remote.symrefs.get(key);
          }
        }
        refs.push(ref);
      }
      return refs;
    }
    async function getRemoteInfo2({
      http,
      onAuth,
      onAuthSuccess,
      onAuthFailure,
      corsProxy,
      url,
      headers = {},
      forPush = false,
      protocolVersion = 2
    }) {
      try {
        assertParameter("http", http);
        assertParameter("url", url);
        const GitRemoteHTTP2 = GitRemoteManager.getRemoteHelperFor({ url });
        const remote = await GitRemoteHTTP2.discover({
          http,
          onAuth,
          onAuthSuccess,
          onAuthFailure,
          corsProxy,
          service: forPush ? "git-receive-pack" : "git-upload-pack",
          url,
          headers,
          protocolVersion
        });
        if (remote.protocolVersion === 2) {
          return {
            protocolVersion: remote.protocolVersion,
            capabilities: remote.capabilities2
          };
        }
        const capabilities = {};
        for (const cap of remote.capabilities) {
          const [key, value] = cap.split("=");
          if (value) {
            capabilities[key] = value;
          } else {
            capabilities[key] = true;
          }
        }
        return {
          protocolVersion: 1,
          capabilities,
          refs: formatInfoRefs(remote, void 0, true, true)
        };
      } catch (err) {
        err.caller = "git.getRemoteInfo2";
        throw err;
      }
    }
    async function hashObject({
      type,
      object,
      format = "content",
      oid = void 0
    }) {
      if (format !== "deflated") {
        if (format !== "wrapped") {
          object = GitObject.wrap({ type, object });
        }
        oid = await shasum(object);
      }
      return { oid, object };
    }
    async function hashBlob({ object }) {
      try {
        assertParameter("object", object);
        if (typeof object === "string") {
          object = Buffer.from(object, "utf8");
        } else if (!(object instanceof Uint8Array)) {
          object = new Uint8Array(object);
        }
        const type = "blob";
        const { oid, object: _object } = await hashObject({
          type,
          format: "content",
          object
        });
        return { oid, type, object: _object, format: "wrapped" };
      } catch (err) {
        err.caller = "git.hashBlob";
        throw err;
      }
    }
    async function _indexPack({
      fs: fs2,
      cache,
      onProgress,
      dir,
      gitdir,
      filepath
    }) {
      try {
        filepath = join(dir, filepath);
        const pack = await fs2.read(filepath);
        const getExternalRefDelta = (oid) => _readObject({ fs: fs2, cache, gitdir, oid });
        const idx = await GitPackIndex.fromPack({
          pack,
          getExternalRefDelta,
          onProgress
        });
        await fs2.write(filepath.replace(/\.pack$/, ".idx"), await idx.toBuffer());
        return {
          oids: [...idx.hashes]
        };
      } catch (err) {
        err.caller = "git.indexPack";
        throw err;
      }
    }
    async function indexPack({
      fs: fs2,
      onProgress,
      dir,
      gitdir = join(dir, ".git"),
      filepath,
      cache = {}
    }) {
      try {
        assertParameter("fs", fs2);
        assertParameter("dir", dir);
        assertParameter("gitdir", dir);
        assertParameter("filepath", filepath);
        const fsp = new FileSystem(fs2);
        const updatedGitdir = await discoverGitdir({ fsp, dotgit: gitdir });
        return await _indexPack({
          fs: fsp,
          cache,
          onProgress,
          dir,
          gitdir: updatedGitdir,
          filepath
        });
      } catch (err) {
        err.caller = "git.indexPack";
        throw err;
      }
    }
    async function init3({
      fs: fs2,
      bare = false,
      dir,
      gitdir = bare ? dir : join(dir, ".git"),
      defaultBranch = "master"
    }) {
      try {
        assertParameter("fs", fs2);
        assertParameter("gitdir", gitdir);
        if (!bare) {
          assertParameter("dir", dir);
        }
        const fsp = new FileSystem(fs2);
        const updatedGitdir = await discoverGitdir({ fsp, dotgit: gitdir });
        return await _init({
          fs: fsp,
          bare,
          dir,
          gitdir: updatedGitdir,
          defaultBranch
        });
      } catch (err) {
        err.caller = "git.init";
        throw err;
      }
    }
    async function _isDescendent({
      fs: fs2,
      cache,
      gitdir,
      oid,
      ancestor,
      depth
    }) {
      const shallows = await GitShallowManager.read({ fs: fs2, gitdir });
      if (!oid) {
        throw new MissingParameterError("oid");
      }
      if (!ancestor) {
        throw new MissingParameterError("ancestor");
      }
      if (oid === ancestor) return false;
      const queue = [oid];
      const visited = /* @__PURE__ */ new Set();
      let searchdepth = 0;
      while (queue.length) {
        if (searchdepth++ === depth) {
          throw new MaxDepthError(depth);
        }
        const oid2 = queue.shift();
        const { type, object } = await _readObject({
          fs: fs2,
          cache,
          gitdir,
          oid: oid2
        });
        if (type !== "commit") {
          throw new ObjectTypeError(oid2, type, "commit");
        }
        const commit2 = GitCommit.from(object).parse();
        for (const parent of commit2.parent) {
          if (parent === ancestor) return true;
        }
        if (!shallows.has(oid2)) {
          for (const parent of commit2.parent) {
            if (!visited.has(parent)) {
              queue.push(parent);
              visited.add(parent);
            }
          }
        }
      }
      return false;
    }
    async function isDescendent({
      fs: fs2,
      dir,
      gitdir = join(dir, ".git"),
      oid,
      ancestor,
      depth = -1,
      cache = {}
    }) {
      try {
        assertParameter("fs", fs2);
        assertParameter("gitdir", gitdir);
        assertParameter("oid", oid);
        assertParameter("ancestor", ancestor);
        const fsp = new FileSystem(fs2);
        const updatedGitdir = await discoverGitdir({ fsp, dotgit: gitdir });
        return await _isDescendent({
          fs: fsp,
          cache,
          gitdir: updatedGitdir,
          oid,
          ancestor,
          depth
        });
      } catch (err) {
        err.caller = "git.isDescendent";
        throw err;
      }
    }
    async function isIgnored({
      fs: fs2,
      dir,
      gitdir = join(dir, ".git"),
      filepath
    }) {
      try {
        assertParameter("fs", fs2);
        assertParameter("dir", dir);
        assertParameter("gitdir", gitdir);
        assertParameter("filepath", filepath);
        const fsp = new FileSystem(fs2);
        const updatedGitdir = await discoverGitdir({ fsp, dotgit: gitdir });
        return GitIgnoreManager.isIgnored({
          fs: fsp,
          dir,
          gitdir: updatedGitdir,
          filepath
        });
      } catch (err) {
        err.caller = "git.isIgnored";
        throw err;
      }
    }
    async function listBranches({
      fs: fs2,
      dir,
      gitdir = join(dir, ".git"),
      remote
    }) {
      try {
        assertParameter("fs", fs2);
        assertParameter("gitdir", gitdir);
        const fsp = new FileSystem(fs2);
        const updatedGitdir = await discoverGitdir({ fsp, dotgit: gitdir });
        return GitRefManager.listBranches({
          fs: fsp,
          gitdir: updatedGitdir,
          remote
        });
      } catch (err) {
        err.caller = "git.listBranches";
        throw err;
      }
    }
    async function _listFiles({ fs: fs2, gitdir, ref, cache }) {
      if (ref) {
        const oid = await GitRefManager.resolve({ gitdir, fs: fs2, ref });
        const filenames = [];
        await accumulateFilesFromOid({
          fs: fs2,
          cache,
          gitdir,
          oid,
          filenames,
          prefix: ""
        });
        return filenames;
      } else {
        return GitIndexManager.acquire(
          { fs: fs2, gitdir, cache },
          async function(index2) {
            return index2.entries.map((x) => x.path);
          }
        );
      }
    }
    async function accumulateFilesFromOid({
      fs: fs2,
      cache,
      gitdir,
      oid,
      filenames,
      prefix
    }) {
      const { tree } = await _readTree({ fs: fs2, cache, gitdir, oid });
      for (const entry of tree) {
        if (entry.type === "tree") {
          await accumulateFilesFromOid({
            fs: fs2,
            cache,
            gitdir,
            oid: entry.oid,
            filenames,
            prefix: join(prefix, entry.path)
          });
        } else {
          filenames.push(join(prefix, entry.path));
        }
      }
    }
    async function listFiles({
      fs: fs2,
      dir,
      gitdir = join(dir, ".git"),
      ref,
      cache = {}
    }) {
      try {
        assertParameter("fs", fs2);
        assertParameter("gitdir", gitdir);
        const fsp = new FileSystem(fs2);
        const updatedGitdir = await discoverGitdir({ fsp, dotgit: gitdir });
        return await _listFiles({
          fs: fsp,
          cache,
          gitdir: updatedGitdir,
          ref
        });
      } catch (err) {
        err.caller = "git.listFiles";
        throw err;
      }
    }
    async function _listNotes({ fs: fs2, cache, gitdir, ref }) {
      let parent;
      try {
        parent = await GitRefManager.resolve({ gitdir, fs: fs2, ref });
      } catch (err) {
        if (err instanceof NotFoundError) {
          return [];
        }
      }
      const result = await _readTree({
        fs: fs2,
        cache,
        gitdir,
        oid: parent
      });
      const notes = result.tree.map((entry) => ({
        target: entry.path,
        note: entry.oid
      }));
      return notes;
    }
    async function listNotes({
      fs: fs2,
      dir,
      gitdir = join(dir, ".git"),
      ref = "refs/notes/commits",
      cache = {}
    }) {
      try {
        assertParameter("fs", fs2);
        assertParameter("gitdir", gitdir);
        assertParameter("ref", ref);
        const fsp = new FileSystem(fs2);
        const updatedGitdir = await discoverGitdir({ fsp, dotgit: gitdir });
        return await _listNotes({
          fs: fsp,
          cache,
          gitdir: updatedGitdir,
          ref
        });
      } catch (err) {
        err.caller = "git.listNotes";
        throw err;
      }
    }
    async function listRefs({
      fs: fs2,
      dir,
      gitdir = join(dir, ".git"),
      filepath
    }) {
      try {
        assertParameter("fs", fs2);
        assertParameter("gitdir", gitdir);
        const fsp = new FileSystem(fs2);
        const updatedGitdir = await discoverGitdir({ fsp, dotgit: gitdir });
        return GitRefManager.listRefs({ fs: fsp, gitdir: updatedGitdir, filepath });
      } catch (err) {
        err.caller = "git.listRefs";
        throw err;
      }
    }
    async function _listRemotes({ fs: fs2, gitdir }) {
      const config = await GitConfigManager.get({ fs: fs2, gitdir });
      const remoteNames = await config.getSubsections("remote");
      const remotes = Promise.all(
        remoteNames.map(async (remote) => {
          const url = await config.get(`remote.${remote}.url`);
          return { remote, url };
        })
      );
      return remotes;
    }
    async function listRemotes({ fs: fs2, dir, gitdir = join(dir, ".git") }) {
      try {
        assertParameter("fs", fs2);
        assertParameter("gitdir", gitdir);
        const fsp = new FileSystem(fs2);
        const updatedGitdir = await discoverGitdir({ fsp, dotgit: gitdir });
        return await _listRemotes({
          fs: fsp,
          gitdir: updatedGitdir
        });
      } catch (err) {
        err.caller = "git.listRemotes";
        throw err;
      }
    }
    async function parseListRefsResponse(stream) {
      const read2 = GitPktLine.streamReader(stream);
      const refs = [];
      let line;
      while (true) {
        line = await read2();
        if (line === true) break;
        if (line === null) continue;
        line = line.toString("utf8").replace(/\n$/, "");
        const [oid, ref, ...attrs] = line.split(" ");
        const r = { ref, oid };
        for (const attr2 of attrs) {
          const [name, value] = attr2.split(":");
          if (name === "symref-target") {
            r.target = value;
          } else if (name === "peeled") {
            r.peeled = value;
          }
        }
        refs.push(r);
      }
      return refs;
    }
    async function writeListRefsRequest({ prefix, symrefs, peelTags }) {
      const packstream = [];
      packstream.push(GitPktLine.encode("command=ls-refs\n"));
      packstream.push(GitPktLine.encode(`agent=${pkg.agent}
`));
      if (peelTags || symrefs || prefix) {
        packstream.push(GitPktLine.delim());
      }
      if (peelTags) packstream.push(GitPktLine.encode("peel"));
      if (symrefs) packstream.push(GitPktLine.encode("symrefs"));
      if (prefix) packstream.push(GitPktLine.encode(`ref-prefix ${prefix}`));
      packstream.push(GitPktLine.flush());
      return packstream;
    }
    async function listServerRefs({
      http,
      onAuth,
      onAuthSuccess,
      onAuthFailure,
      corsProxy,
      url,
      headers = {},
      forPush = false,
      protocolVersion = 2,
      prefix,
      symrefs,
      peelTags
    }) {
      try {
        assertParameter("http", http);
        assertParameter("url", url);
        const remote = await GitRemoteHTTP.discover({
          http,
          onAuth,
          onAuthSuccess,
          onAuthFailure,
          corsProxy,
          service: forPush ? "git-receive-pack" : "git-upload-pack",
          url,
          headers,
          protocolVersion
        });
        if (remote.protocolVersion === 1) {
          return formatInfoRefs(remote, prefix, symrefs, peelTags);
        }
        const body = await writeListRefsRequest({ prefix, symrefs, peelTags });
        const res = await GitRemoteHTTP.connect({
          http,
          auth: remote.auth,
          headers,
          corsProxy,
          service: forPush ? "git-receive-pack" : "git-upload-pack",
          url,
          body
        });
        return parseListRefsResponse(res.body);
      } catch (err) {
        err.caller = "git.listServerRefs";
        throw err;
      }
    }
    async function listTags({ fs: fs2, dir, gitdir = join(dir, ".git") }) {
      try {
        assertParameter("fs", fs2);
        assertParameter("gitdir", gitdir);
        const fsp = new FileSystem(fs2);
        const updatedGitdir = await discoverGitdir({ fsp, dotgit: gitdir });
        return GitRefManager.listTags({ fs: fsp, gitdir: updatedGitdir });
      } catch (err) {
        err.caller = "git.listTags";
        throw err;
      }
    }
    function compareAge(a, b) {
      return a.committer.timestamp - b.committer.timestamp;
    }
    var EMPTY_OID = "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391";
    async function resolveFileIdInTree({ fs: fs2, cache, gitdir, oid, fileId }) {
      if (fileId === EMPTY_OID) return;
      const _oid = oid;
      let filepath;
      const result = await resolveTree({ fs: fs2, cache, gitdir, oid });
      const tree = result.tree;
      if (fileId === result.oid) {
        filepath = result.path;
      } else {
        filepath = await _resolveFileId({
          fs: fs2,
          cache,
          gitdir,
          tree,
          fileId,
          oid: _oid
        });
        if (Array.isArray(filepath)) {
          if (filepath.length === 0) filepath = void 0;
          else if (filepath.length === 1) filepath = filepath[0];
        }
      }
      return filepath;
    }
    async function _resolveFileId({
      fs: fs2,
      cache,
      gitdir,
      tree,
      fileId,
      oid,
      filepaths = [],
      parentPath = ""
    }) {
      const walks = tree.entries().map(function(entry) {
        let result;
        if (entry.oid === fileId) {
          result = join(parentPath, entry.path);
          filepaths.push(result);
        } else if (entry.type === "tree") {
          result = _readObject({
            fs: fs2,
            cache,
            gitdir,
            oid: entry.oid
          }).then(function({ object }) {
            return _resolveFileId({
              fs: fs2,
              cache,
              gitdir,
              tree: GitTree.from(object),
              fileId,
              oid,
              filepaths,
              parentPath: join(parentPath, entry.path)
            });
          });
        }
        return result;
      });
      await Promise.all(walks);
      return filepaths;
    }
    async function _log({
      fs: fs2,
      cache,
      gitdir,
      filepath,
      ref,
      depth,
      since,
      force,
      follow
    }) {
      const sinceTimestamp = typeof since === "undefined" ? void 0 : Math.floor(since.valueOf() / 1e3);
      const commits = [];
      const shallowCommits = await GitShallowManager.read({ fs: fs2, gitdir });
      const oid = await GitRefManager.resolve({ fs: fs2, gitdir, ref });
      const tips = [await _readCommit({ fs: fs2, cache, gitdir, oid })];
      let lastFileOid;
      let lastCommit;
      let isOk;
      function endCommit(commit2) {
        if (isOk && filepath) commits.push(commit2);
      }
      while (tips.length > 0) {
        const commit2 = tips.pop();
        if (sinceTimestamp !== void 0 && commit2.commit.committer.timestamp <= sinceTimestamp) {
          break;
        }
        if (filepath) {
          let vFileOid;
          try {
            vFileOid = await resolveFilepath({
              fs: fs2,
              cache,
              gitdir,
              oid: commit2.commit.tree,
              filepath
            });
            if (lastCommit && lastFileOid !== vFileOid) {
              commits.push(lastCommit);
            }
            lastFileOid = vFileOid;
            lastCommit = commit2;
            isOk = true;
          } catch (e) {
            if (e instanceof NotFoundError) {
              let found = follow && lastFileOid;
              if (found) {
                found = await resolveFileIdInTree({
                  fs: fs2,
                  cache,
                  gitdir,
                  oid: commit2.commit.tree,
                  fileId: lastFileOid
                });
                if (found) {
                  if (Array.isArray(found)) {
                    if (lastCommit) {
                      const lastFound = await resolveFileIdInTree({
                        fs: fs2,
                        cache,
                        gitdir,
                        oid: lastCommit.commit.tree,
                        fileId: lastFileOid
                      });
                      if (Array.isArray(lastFound)) {
                        found = found.filter((p) => lastFound.indexOf(p) === -1);
                        if (found.length === 1) {
                          found = found[0];
                          filepath = found;
                          if (lastCommit) commits.push(lastCommit);
                        } else {
                          found = false;
                          if (lastCommit) commits.push(lastCommit);
                          break;
                        }
                      }
                    }
                  } else {
                    filepath = found;
                    if (lastCommit) commits.push(lastCommit);
                  }
                }
              }
              if (!found) {
                if (isOk && lastFileOid) {
                  commits.push(lastCommit);
                  if (!force) break;
                }
                if (!force && !follow) throw e;
              }
              lastCommit = commit2;
              isOk = false;
            } else throw e;
          }
        } else {
          commits.push(commit2);
        }
        if (depth !== void 0 && commits.length === depth) {
          endCommit(commit2);
          break;
        }
        if (!shallowCommits.has(commit2.oid)) {
          for (const oid2 of commit2.commit.parent) {
            const commit3 = await _readCommit({ fs: fs2, cache, gitdir, oid: oid2 });
            if (!tips.map((commit4) => commit4.oid).includes(commit3.oid)) {
              tips.push(commit3);
            }
          }
        }
        if (tips.length === 0) {
          endCommit(commit2);
        }
        tips.sort((a, b) => compareAge(a.commit, b.commit));
      }
      return commits;
    }
    async function log({
      fs: fs2,
      dir,
      gitdir = join(dir, ".git"),
      filepath,
      ref = "HEAD",
      depth,
      since,
      // Date
      force,
      follow,
      cache = {}
    }) {
      try {
        assertParameter("fs", fs2);
        assertParameter("gitdir", gitdir);
        assertParameter("ref", ref);
        const fsp = new FileSystem(fs2);
        const updatedGitdir = await discoverGitdir({ fsp, dotgit: gitdir });
        return await _log({
          fs: fsp,
          cache,
          gitdir: updatedGitdir,
          filepath,
          ref,
          depth,
          since,
          force,
          follow
        });
      } catch (err) {
        err.caller = "git.log";
        throw err;
      }
    }
    async function merge({
      fs: _fs,
      onSign,
      dir,
      gitdir = join(dir, ".git"),
      ours,
      theirs,
      fastForward: fastForward2 = true,
      fastForwardOnly = false,
      dryRun = false,
      noUpdateBranch = false,
      abortOnConflict = true,
      message,
      author: _author,
      committer: _committer,
      signingKey,
      cache = {},
      mergeDriver,
      allowUnrelatedHistories = false
    }) {
      try {
        assertParameter("fs", _fs);
        if (signingKey) {
          assertParameter("onSign", onSign);
        }
        const fs2 = new FileSystem(_fs);
        const updatedGitdir = await discoverGitdir({ fsp: fs2, dotgit: gitdir });
        const author = await normalizeAuthorObject({
          fs: fs2,
          gitdir: updatedGitdir,
          author: _author
        });
        if (!author && (!fastForwardOnly || !fastForward2)) {
          throw new MissingNameError("author");
        }
        const committer = await normalizeCommitterObject({
          fs: fs2,
          gitdir: updatedGitdir,
          author,
          committer: _committer
        });
        if (!committer && (!fastForwardOnly || !fastForward2)) {
          throw new MissingNameError("committer");
        }
        return await _merge({
          fs: fs2,
          cache,
          dir,
          gitdir: updatedGitdir,
          ours,
          theirs,
          fastForward: fastForward2,
          fastForwardOnly,
          dryRun,
          noUpdateBranch,
          abortOnConflict,
          message,
          author,
          committer,
          signingKey,
          onSign,
          mergeDriver,
          allowUnrelatedHistories
        });
      } catch (err) {
        err.caller = "git.merge";
        throw err;
      }
    }
    var types = {
      commit: 16,
      tree: 32,
      blob: 48,
      tag: 64,
      ofs_delta: 96,
      ref_delta: 112
    };
    async function _pack({
      fs: fs2,
      cache,
      dir,
      gitdir = join(dir, ".git"),
      oids
    }) {
      const hash = new Hash();
      const outputStream = [];
      function write3(chunk, enc) {
        const buff = Buffer.from(chunk, enc);
        outputStream.push(buff);
        hash.update(buff);
      }
      async function writeObject2({ stype, object }) {
        const type = types[stype];
        let length = object.length;
        let multibyte = length > 15 ? 128 : 0;
        const lastFour = length & 15;
        length = length >>> 4;
        let byte = (multibyte | type | lastFour).toString(16);
        write3(byte, "hex");
        while (multibyte) {
          multibyte = length > 127 ? 128 : 0;
          byte = multibyte | length & 127;
          write3(padHex(2, byte), "hex");
          length = length >>> 7;
        }
        write3(Buffer.from(await deflate(object)));
      }
      write3("PACK");
      write3("00000002", "hex");
      write3(padHex(8, oids.length), "hex");
      for (const oid of oids) {
        const { type, object } = await _readObject({ fs: fs2, cache, gitdir, oid });
        await writeObject2({ write: write3, object, stype: type });
      }
      const digest = hash.digest();
      outputStream.push(digest);
      return outputStream;
    }
    async function _packObjects({ fs: fs2, cache, gitdir, oids, write: write3 }) {
      const buffers = await _pack({ fs: fs2, cache, gitdir, oids });
      const packfile = Buffer.from(await collect(buffers));
      const packfileSha = packfile.slice(-20).toString("hex");
      const filename = `pack-${packfileSha}.pack`;
      if (write3) {
        await fs2.write(join(gitdir, `objects/pack/${filename}`), packfile);
        return { filename };
      }
      return {
        filename,
        packfile: new Uint8Array(packfile)
      };
    }
    async function packObjects({
      fs: fs2,
      dir,
      gitdir = join(dir, ".git"),
      oids,
      write: write3 = false,
      cache = {}
    }) {
      try {
        assertParameter("fs", fs2);
        assertParameter("gitdir", gitdir);
        assertParameter("oids", oids);
        const fsp = new FileSystem(fs2);
        const updatedGitdir = await discoverGitdir({ fsp, dotgit: gitdir });
        return await _packObjects({
          fs: fsp,
          cache,
          gitdir: updatedGitdir,
          oids,
          write: write3
        });
      } catch (err) {
        err.caller = "git.packObjects";
        throw err;
      }
    }
    async function pull({
      fs: _fs,
      http,
      onProgress,
      onMessage,
      onAuth,
      onAuthSuccess,
      onAuthFailure,
      dir,
      gitdir = join(dir, ".git"),
      ref,
      url,
      remote,
      remoteRef,
      prune = false,
      pruneTags = false,
      fastForward: fastForward2 = true,
      fastForwardOnly = false,
      corsProxy,
      singleBranch,
      headers = {},
      author: _author,
      committer: _committer,
      signingKey,
      cache = {}
    }) {
      try {
        assertParameter("fs", _fs);
        assertParameter("gitdir", gitdir);
        const fs2 = new FileSystem(_fs);
        const updatedGitdir = await discoverGitdir({ fsp: fs2, dotgit: gitdir });
        const author = await normalizeAuthorObject({
          fs: fs2,
          gitdir: updatedGitdir,
          author: _author
        });
        if (!author) throw new MissingNameError("author");
        const committer = await normalizeCommitterObject({
          fs: fs2,
          gitdir: updatedGitdir,
          author,
          committer: _committer
        });
        if (!committer) throw new MissingNameError("committer");
        return await _pull({
          fs: fs2,
          cache,
          http,
          onProgress,
          onMessage,
          onAuth,
          onAuthSuccess,
          onAuthFailure,
          dir,
          gitdir: updatedGitdir,
          ref,
          url,
          remote,
          remoteRef,
          fastForward: fastForward2,
          fastForwardOnly,
          corsProxy,
          singleBranch,
          headers,
          author,
          committer,
          signingKey,
          prune,
          pruneTags
        });
      } catch (err) {
        err.caller = "git.pull";
        throw err;
      }
    }
    async function listCommitsAndTags({
      fs: fs2,
      cache,
      dir,
      gitdir = join(dir, ".git"),
      start,
      finish
    }) {
      const shallows = await GitShallowManager.read({ fs: fs2, gitdir });
      const startingSet = /* @__PURE__ */ new Set();
      const finishingSet = /* @__PURE__ */ new Set();
      for (const ref of start) {
        startingSet.add(await GitRefManager.resolve({ fs: fs2, gitdir, ref }));
      }
      for (const ref of finish) {
        try {
          const oid = await GitRefManager.resolve({ fs: fs2, gitdir, ref });
          finishingSet.add(oid);
        } catch (err) {
        }
      }
      const visited = /* @__PURE__ */ new Set();
      async function walk2(oid) {
        visited.add(oid);
        const { type, object } = await _readObject({ fs: fs2, cache, gitdir, oid });
        if (type === "tag") {
          const tag2 = GitAnnotatedTag.from(object);
          const commit2 = tag2.headers().object;
          return walk2(commit2);
        }
        if (type !== "commit") {
          throw new ObjectTypeError(oid, type, "commit");
        }
        if (!shallows.has(oid)) {
          const commit2 = GitCommit.from(object);
          const parents = commit2.headers().parent;
          for (oid of parents) {
            if (!finishingSet.has(oid) && !visited.has(oid)) {
              await walk2(oid);
            }
          }
        }
      }
      for (const oid of startingSet) {
        await walk2(oid);
      }
      return visited;
    }
    async function listObjects({
      fs: fs2,
      cache,
      dir,
      gitdir = join(dir, ".git"),
      oids
    }) {
      const visited = /* @__PURE__ */ new Set();
      async function walk2(oid) {
        if (visited.has(oid)) return;
        visited.add(oid);
        const { type, object } = await _readObject({ fs: fs2, cache, gitdir, oid });
        if (type === "tag") {
          const tag2 = GitAnnotatedTag.from(object);
          const obj = tag2.headers().object;
          await walk2(obj);
        } else if (type === "commit") {
          const commit2 = GitCommit.from(object);
          const tree = commit2.headers().tree;
          await walk2(tree);
        } else if (type === "tree") {
          const tree = GitTree.from(object);
          for (const entry of tree) {
            if (entry.type === "blob") {
              visited.add(entry.oid);
            }
            if (entry.type === "tree") {
              await walk2(entry.oid);
            }
          }
        }
      }
      for (const oid of oids) {
        await walk2(oid);
      }
      return visited;
    }
    async function parseReceivePackResponse(packfile) {
      const result = {};
      let response = "";
      const read2 = GitPktLine.streamReader(packfile);
      let line = await read2();
      while (line !== true) {
        if (line !== null) response += line.toString("utf8") + "\n";
        line = await read2();
      }
      const lines = response.toString("utf8").split("\n");
      line = lines.shift();
      if (!line.startsWith("unpack ")) {
        throw new ParseError('unpack ok" or "unpack [error message]', line);
      }
      result.ok = line === "unpack ok";
      if (!result.ok) {
        result.error = line.slice("unpack ".length);
      }
      result.refs = {};
      for (const line2 of lines) {
        if (line2.trim() === "") continue;
        const status2 = line2.slice(0, 2);
        const refAndMessage = line2.slice(3);
        let space2 = refAndMessage.indexOf(" ");
        if (space2 === -1) space2 = refAndMessage.length;
        const ref = refAndMessage.slice(0, space2);
        const error = refAndMessage.slice(space2 + 1);
        result.refs[ref] = {
          ok: status2 === "ok",
          error
        };
      }
      return result;
    }
    async function writeReceivePackRequest({
      capabilities = [],
      triplets = []
    }) {
      const packstream = [];
      let capsFirstLine = `\0 ${capabilities.join(" ")}`;
      for (const trip of triplets) {
        packstream.push(
          GitPktLine.encode(
            `${trip.oldoid} ${trip.oid} ${trip.fullRef}${capsFirstLine}
`
          )
        );
        capsFirstLine = "";
      }
      packstream.push(GitPktLine.flush());
      return packstream;
    }
    async function _push({
      fs: fs2,
      cache,
      http,
      onProgress,
      onMessage,
      onAuth,
      onAuthSuccess,
      onAuthFailure,
      onPrePush,
      gitdir,
      ref: _ref,
      remoteRef: _remoteRef,
      remote,
      url: _url,
      force = false,
      delete: _delete = false,
      corsProxy,
      headers = {}
    }) {
      const ref = _ref || await _currentBranch({ fs: fs2, gitdir });
      if (typeof ref === "undefined") {
        throw new MissingParameterError("ref");
      }
      const config = await GitConfigManager.get({ fs: fs2, gitdir });
      remote = remote || await config.get(`branch.${ref}.pushRemote`) || await config.get("remote.pushDefault") || await config.get(`branch.${ref}.remote`) || "origin";
      const url = _url || await config.get(`remote.${remote}.pushurl`) || await config.get(`remote.${remote}.url`);
      if (typeof url === "undefined") {
        throw new MissingParameterError("remote OR url");
      }
      const remoteRef = _remoteRef || await config.get(`branch.${ref}.merge`);
      if (typeof url === "undefined") {
        throw new MissingParameterError("remoteRef");
      }
      if (corsProxy === void 0) {
        corsProxy = await config.get("http.corsProxy");
      }
      const fullRef = await GitRefManager.expand({ fs: fs2, gitdir, ref });
      const oid = _delete ? "0000000000000000000000000000000000000000" : await GitRefManager.resolve({ fs: fs2, gitdir, ref: fullRef });
      const GitRemoteHTTP2 = GitRemoteManager.getRemoteHelperFor({ url });
      const httpRemote = await GitRemoteHTTP2.discover({
        http,
        onAuth,
        onAuthSuccess,
        onAuthFailure,
        corsProxy,
        service: "git-receive-pack",
        url,
        headers,
        protocolVersion: 1
      });
      const auth = httpRemote.auth;
      let fullRemoteRef;
      if (!remoteRef) {
        fullRemoteRef = fullRef;
      } else {
        try {
          fullRemoteRef = await GitRefManager.expandAgainstMap({
            ref: remoteRef,
            map: httpRemote.refs
          });
        } catch (err) {
          if (err instanceof NotFoundError) {
            fullRemoteRef = remoteRef.startsWith("refs/") ? remoteRef : `refs/heads/${remoteRef}`;
          } else {
            throw err;
          }
        }
      }
      const oldoid = httpRemote.refs.get(fullRemoteRef) || "0000000000000000000000000000000000000000";
      if (onPrePush) {
        const hookCancel = await onPrePush({
          remote,
          url,
          localRef: { ref: _delete ? "(delete)" : fullRef, oid },
          remoteRef: { ref: fullRemoteRef, oid: oldoid }
        });
        if (!hookCancel) throw new UserCanceledError();
      }
      const thinPack = !httpRemote.capabilities.has("no-thin");
      let objects = /* @__PURE__ */ new Set();
      if (!_delete) {
        const finish = [...httpRemote.refs.values()];
        let skipObjects = /* @__PURE__ */ new Set();
        if (oldoid !== "0000000000000000000000000000000000000000") {
          const mergebase = await _findMergeBase({
            fs: fs2,
            cache,
            gitdir,
            oids: [oid, oldoid]
          });
          for (const oid2 of mergebase) finish.push(oid2);
          if (thinPack) {
            skipObjects = await listObjects({ fs: fs2, cache, gitdir, oids: mergebase });
          }
        }
        if (!finish.includes(oid)) {
          const commits = await listCommitsAndTags({
            fs: fs2,
            cache,
            gitdir,
            start: [oid],
            finish
          });
          objects = await listObjects({ fs: fs2, cache, gitdir, oids: commits });
        }
        if (thinPack) {
          try {
            const ref2 = await GitRefManager.resolve({
              fs: fs2,
              gitdir,
              ref: `refs/remotes/${remote}/HEAD`,
              depth: 2
            });
            const { oid: oid2 } = await GitRefManager.resolveAgainstMap({
              ref: ref2.replace(`refs/remotes/${remote}/`, ""),
              fullref: ref2,
              map: httpRemote.refs
            });
            const oids = [oid2];
            for (const oid3 of await listObjects({ fs: fs2, cache, gitdir, oids })) {
              skipObjects.add(oid3);
            }
          } catch (e) {
          }
          for (const oid2 of skipObjects) {
            objects.delete(oid2);
          }
        }
        if (oid === oldoid) force = true;
        if (!force) {
          if (fullRef.startsWith("refs/tags") && oldoid !== "0000000000000000000000000000000000000000") {
            throw new PushRejectedError("tag-exists");
          }
          if (oid !== "0000000000000000000000000000000000000000" && oldoid !== "0000000000000000000000000000000000000000" && !await _isDescendent({
            fs: fs2,
            cache,
            gitdir,
            oid,
            ancestor: oldoid,
            depth: -1
          })) {
            throw new PushRejectedError("not-fast-forward");
          }
        }
      }
      const capabilities = filterCapabilities(
        [...httpRemote.capabilities],
        ["report-status", "side-band-64k", `agent=${pkg.agent}`]
      );
      const packstream1 = await writeReceivePackRequest({
        capabilities,
        triplets: [{ oldoid, oid, fullRef: fullRemoteRef }]
      });
      const packstream2 = _delete ? [] : await _pack({
        fs: fs2,
        cache,
        gitdir,
        oids: [...objects]
      });
      const res = await GitRemoteHTTP2.connect({
        http,
        onProgress,
        corsProxy,
        service: "git-receive-pack",
        url,
        auth,
        headers,
        body: [...packstream1, ...packstream2]
      });
      const { packfile, progress } = await GitSideBand.demux(res.body);
      if (onMessage) {
        const lines = splitLines(progress);
        forAwait(lines, async (line) => {
          await onMessage(line);
        });
      }
      const result = await parseReceivePackResponse(packfile);
      if (res.headers) {
        result.headers = res.headers;
      }
      if (remote && result.ok && result.refs[fullRemoteRef].ok && !fullRef.startsWith("refs/tags")) {
        const ref2 = `refs/remotes/${remote}/${fullRemoteRef.replace(
          "refs/heads",
          ""
        )}`;
        if (_delete) {
          await GitRefManager.deleteRef({ fs: fs2, gitdir, ref: ref2 });
        } else {
          await GitRefManager.writeRef({ fs: fs2, gitdir, ref: ref2, value: oid });
        }
      }
      if (result.ok && Object.values(result.refs).every((result2) => result2.ok)) {
        return result;
      } else {
        const prettyDetails = Object.entries(result.refs).filter(([k, v]) => !v.ok).map(([k, v]) => `
  - ${k}: ${v.error}`).join("");
        throw new GitPushError(prettyDetails, result);
      }
    }
    async function push({
      fs: fs2,
      http,
      onProgress,
      onMessage,
      onAuth,
      onAuthSuccess,
      onAuthFailure,
      onPrePush,
      dir,
      gitdir = join(dir, ".git"),
      ref,
      remoteRef,
      remote = "origin",
      url,
      force = false,
      delete: _delete = false,
      corsProxy,
      headers = {},
      cache = {}
    }) {
      try {
        assertParameter("fs", fs2);
        assertParameter("http", http);
        assertParameter("gitdir", gitdir);
        const fsp = new FileSystem(fs2);
        const updatedGitdir = await discoverGitdir({ fsp, dotgit: gitdir });
        return await _push({
          fs: fsp,
          cache,
          http,
          onProgress,
          onMessage,
          onAuth,
          onAuthSuccess,
          onAuthFailure,
          onPrePush,
          gitdir: updatedGitdir,
          ref,
          remoteRef,
          remote,
          url,
          force,
          delete: _delete,
          corsProxy,
          headers
        });
      } catch (err) {
        err.caller = "git.push";
        throw err;
      }
    }
    async function resolveBlob({ fs: fs2, cache, gitdir, oid }) {
      const { type, object } = await _readObject({ fs: fs2, cache, gitdir, oid });
      if (type === "tag") {
        oid = GitAnnotatedTag.from(object).parse().object;
        return resolveBlob({ fs: fs2, cache, gitdir, oid });
      }
      if (type !== "blob") {
        throw new ObjectTypeError(oid, type, "blob");
      }
      return { oid, blob: new Uint8Array(object) };
    }
    async function _readBlob({
      fs: fs2,
      cache,
      gitdir,
      oid,
      filepath = void 0
    }) {
      if (filepath !== void 0) {
        oid = await resolveFilepath({ fs: fs2, cache, gitdir, oid, filepath });
      }
      const blob = await resolveBlob({
        fs: fs2,
        cache,
        gitdir,
        oid
      });
      return blob;
    }
    async function readBlob({
      fs: fs2,
      dir,
      gitdir = join(dir, ".git"),
      oid,
      filepath,
      cache = {}
    }) {
      try {
        assertParameter("fs", fs2);
        assertParameter("gitdir", gitdir);
        assertParameter("oid", oid);
        const fsp = new FileSystem(fs2);
        const updatedGitdir = await discoverGitdir({ fsp, dotgit: gitdir });
        return await _readBlob({
          fs: fsp,
          cache,
          gitdir: updatedGitdir,
          oid,
          filepath
        });
      } catch (err) {
        err.caller = "git.readBlob";
        throw err;
      }
    }
    async function readCommit({
      fs: fs2,
      dir,
      gitdir = join(dir, ".git"),
      oid,
      cache = {}
    }) {
      try {
        assertParameter("fs", fs2);
        assertParameter("gitdir", gitdir);
        assertParameter("oid", oid);
        const fsp = new FileSystem(fs2);
        const updatedGitdir = await discoverGitdir({ fsp, dotgit: gitdir });
        return await _readCommit({
          fs: fsp,
          cache,
          gitdir: updatedGitdir,
          oid
        });
      } catch (err) {
        err.caller = "git.readCommit";
        throw err;
      }
    }
    async function _readNote({
      fs: fs2,
      cache,
      gitdir,
      ref = "refs/notes/commits",
      oid
    }) {
      const parent = await GitRefManager.resolve({ gitdir, fs: fs2, ref });
      const { blob } = await _readBlob({
        fs: fs2,
        cache,
        gitdir,
        oid: parent,
        filepath: oid
      });
      return blob;
    }
    async function readNote({
      fs: fs2,
      dir,
      gitdir = join(dir, ".git"),
      ref = "refs/notes/commits",
      oid,
      cache = {}
    }) {
      try {
        assertParameter("fs", fs2);
        assertParameter("gitdir", gitdir);
        assertParameter("ref", ref);
        assertParameter("oid", oid);
        const fsp = new FileSystem(fs2);
        const updatedGitdir = await discoverGitdir({ fsp, dotgit: gitdir });
        return await _readNote({
          fs: fsp,
          cache,
          gitdir: updatedGitdir,
          ref,
          oid
        });
      } catch (err) {
        err.caller = "git.readNote";
        throw err;
      }
    }
    async function readObject({
      fs: _fs,
      dir,
      gitdir = join(dir, ".git"),
      oid,
      format = "parsed",
      filepath = void 0,
      encoding = void 0,
      cache = {}
    }) {
      try {
        assertParameter("fs", _fs);
        assertParameter("gitdir", gitdir);
        assertParameter("oid", oid);
        const fs2 = new FileSystem(_fs);
        const updatedGitdir = await discoverGitdir({ fsp: fs2, dotgit: gitdir });
        if (filepath !== void 0) {
          oid = await resolveFilepath({
            fs: fs2,
            cache,
            gitdir: updatedGitdir,
            oid,
            filepath
          });
        }
        const _format = format === "parsed" ? "content" : format;
        const result = await _readObject({
          fs: fs2,
          cache,
          gitdir: updatedGitdir,
          oid,
          format: _format
        });
        result.oid = oid;
        if (format === "parsed") {
          result.format = "parsed";
          switch (result.type) {
            case "commit":
              result.object = GitCommit.from(result.object).parse();
              break;
            case "tree":
              result.object = GitTree.from(result.object).entries();
              break;
            case "blob":
              if (encoding) {
                result.object = result.object.toString(encoding);
              } else {
                result.object = new Uint8Array(result.object);
                result.format = "content";
              }
              break;
            case "tag":
              result.object = GitAnnotatedTag.from(result.object).parse();
              break;
            default:
              throw new ObjectTypeError(
                result.oid,
                result.type,
                "blob|commit|tag|tree"
              );
          }
        } else if (result.format === "deflated" || result.format === "wrapped") {
          result.type = result.format;
        }
        return result;
      } catch (err) {
        err.caller = "git.readObject";
        throw err;
      }
    }
    async function _readTag({ fs: fs2, cache, gitdir, oid }) {
      const { type, object } = await _readObject({
        fs: fs2,
        cache,
        gitdir,
        oid,
        format: "content"
      });
      if (type !== "tag") {
        throw new ObjectTypeError(oid, type, "tag");
      }
      const tag2 = GitAnnotatedTag.from(object);
      const result = {
        oid,
        tag: tag2.parse(),
        payload: tag2.payload()
      };
      return result;
    }
    async function readTag({
      fs: fs2,
      dir,
      gitdir = join(dir, ".git"),
      oid,
      cache = {}
    }) {
      try {
        assertParameter("fs", fs2);
        assertParameter("gitdir", gitdir);
        assertParameter("oid", oid);
        const fsp = new FileSystem(fs2);
        const updatedGitdir = await discoverGitdir({ fsp, dotgit: gitdir });
        return await _readTag({
          fs: fsp,
          cache,
          gitdir: updatedGitdir,
          oid
        });
      } catch (err) {
        err.caller = "git.readTag";
        throw err;
      }
    }
    async function readTree({
      fs: fs2,
      dir,
      gitdir = join(dir, ".git"),
      oid,
      filepath = void 0,
      cache = {}
    }) {
      try {
        assertParameter("fs", fs2);
        assertParameter("gitdir", gitdir);
        assertParameter("oid", oid);
        const fsp = new FileSystem(fs2);
        const updatedGitdir = await discoverGitdir({ fsp, dotgit: gitdir });
        return await _readTree({
          fs: fsp,
          cache,
          gitdir: updatedGitdir,
          oid,
          filepath
        });
      } catch (err) {
        err.caller = "git.readTree";
        throw err;
      }
    }
    async function remove({
      fs: _fs,
      dir,
      gitdir = join(dir, ".git"),
      filepath,
      cache = {}
    }) {
      try {
        assertParameter("fs", _fs);
        assertParameter("gitdir", gitdir);
        assertParameter("filepath", filepath);
        const fsp = new FileSystem(_fs);
        const updatedGitdir = await discoverGitdir({ fsp, dotgit: gitdir });
        await GitIndexManager.acquire(
          { fs: fsp, gitdir: updatedGitdir, cache },
          async function(index2) {
            index2.delete({ filepath });
          }
        );
      } catch (err) {
        err.caller = "git.remove";
        throw err;
      }
    }
    async function _removeNote({
      fs: fs2,
      cache,
      onSign,
      gitdir,
      ref = "refs/notes/commits",
      oid,
      author,
      committer,
      signingKey
    }) {
      let parent;
      try {
        parent = await GitRefManager.resolve({ gitdir, fs: fs2, ref });
      } catch (err) {
        if (!(err instanceof NotFoundError)) {
          throw err;
        }
      }
      const result = await _readTree({
        fs: fs2,
        cache,
        gitdir,
        oid: parent || "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
      });
      let tree = result.tree;
      tree = tree.filter((entry) => entry.path !== oid);
      const treeOid = await _writeTree({
        fs: fs2,
        gitdir,
        tree
      });
      const commitOid = await _commit({
        fs: fs2,
        cache,
        onSign,
        gitdir,
        ref,
        tree: treeOid,
        parent: parent && [parent],
        message: `Note removed by 'isomorphic-git removeNote'
`,
        author,
        committer,
        signingKey
      });
      return commitOid;
    }
    async function removeNote({
      fs: _fs,
      onSign,
      dir,
      gitdir = join(dir, ".git"),
      ref = "refs/notes/commits",
      oid,
      author: _author,
      committer: _committer,
      signingKey,
      cache = {}
    }) {
      try {
        assertParameter("fs", _fs);
        assertParameter("gitdir", gitdir);
        assertParameter("oid", oid);
        const fs2 = new FileSystem(_fs);
        const updatedGitdir = await discoverGitdir({ fsp: fs2, dotgit: gitdir });
        const author = await normalizeAuthorObject({
          fs: fs2,
          gitdir: updatedGitdir,
          author: _author
        });
        if (!author) throw new MissingNameError("author");
        const committer = await normalizeCommitterObject({
          fs: fs2,
          gitdir: updatedGitdir,
          author,
          committer: _committer
        });
        if (!committer) throw new MissingNameError("committer");
        return await _removeNote({
          fs: fs2,
          cache,
          onSign,
          gitdir: updatedGitdir,
          ref,
          oid,
          author,
          committer,
          signingKey
        });
      } catch (err) {
        err.caller = "git.removeNote";
        throw err;
      }
    }
    async function _renameBranch({
      fs: fs2,
      gitdir,
      oldref,
      ref,
      checkout: checkout2 = false
    }) {
      if (!isValidRef(ref, true)) {
        throw new InvalidRefNameError(ref, cleanGitRef.clean(ref));
      }
      if (!isValidRef(oldref, true)) {
        throw new InvalidRefNameError(oldref, cleanGitRef.clean(oldref));
      }
      const fulloldref = `refs/heads/${oldref}`;
      const fullnewref = `refs/heads/${ref}`;
      const newexist = await GitRefManager.exists({ fs: fs2, gitdir, ref: fullnewref });
      if (newexist) {
        throw new AlreadyExistsError("branch", ref, false);
      }
      const value = await GitRefManager.resolve({
        fs: fs2,
        gitdir,
        ref: fulloldref,
        depth: 1
      });
      await GitRefManager.writeRef({ fs: fs2, gitdir, ref: fullnewref, value });
      await GitRefManager.deleteRef({ fs: fs2, gitdir, ref: fulloldref });
      const fullCurrentBranchRef = await _currentBranch({
        fs: fs2,
        gitdir,
        fullname: true
      });
      const isCurrentBranch = fullCurrentBranchRef === fulloldref;
      if (checkout2 || isCurrentBranch) {
        await GitRefManager.writeSymbolicRef({
          fs: fs2,
          gitdir,
          ref: "HEAD",
          value: fullnewref
        });
      }
    }
    async function renameBranch({
      fs: fs2,
      dir,
      gitdir = join(dir, ".git"),
      ref,
      oldref,
      checkout: checkout2 = false
    }) {
      try {
        assertParameter("fs", fs2);
        assertParameter("gitdir", gitdir);
        assertParameter("ref", ref);
        assertParameter("oldref", oldref);
        const fsp = new FileSystem(fs2);
        const updatedGitdir = await discoverGitdir({ fsp, dotgit: gitdir });
        return await _renameBranch({
          fs: fsp,
          gitdir: updatedGitdir,
          ref,
          oldref,
          checkout: checkout2
        });
      } catch (err) {
        err.caller = "git.renameBranch";
        throw err;
      }
    }
    async function hashObject$1({ gitdir, type, object }) {
      return shasum(GitObject.wrap({ type, object }));
    }
    async function resetIndex({
      fs: _fs,
      dir,
      gitdir = join(dir, ".git"),
      filepath,
      ref,
      cache = {}
    }) {
      try {
        assertParameter("fs", _fs);
        assertParameter("gitdir", gitdir);
        assertParameter("filepath", filepath);
        const fs2 = new FileSystem(_fs);
        const updatedGitdir = await discoverGitdir({ fsp: fs2, dotgit: gitdir });
        let oid;
        let workdirOid;
        try {
          oid = await GitRefManager.resolve({
            fs: fs2,
            gitdir: updatedGitdir,
            ref: ref || "HEAD"
          });
        } catch (e) {
          if (ref) {
            throw e;
          }
        }
        if (oid) {
          try {
            oid = await resolveFilepath({
              fs: fs2,
              cache,
              gitdir: updatedGitdir,
              oid,
              filepath
            });
          } catch (e) {
            oid = null;
          }
        }
        let stats = {
          ctime: /* @__PURE__ */ new Date(0),
          mtime: /* @__PURE__ */ new Date(0),
          dev: 0,
          ino: 0,
          mode: 0,
          uid: 0,
          gid: 0,
          size: 0
        };
        const object = dir && await fs2.read(join(dir, filepath));
        if (object) {
          workdirOid = await hashObject$1({
            gitdir: updatedGitdir,
            type: "blob",
            object
          });
          if (oid === workdirOid) {
            stats = await fs2.lstat(join(dir, filepath));
          }
        }
        await GitIndexManager.acquire(
          { fs: fs2, gitdir: updatedGitdir, cache },
          async function(index2) {
            index2.delete({ filepath });
            if (oid) {
              index2.insert({ filepath, stats, oid });
            }
          }
        );
      } catch (err) {
        err.caller = "git.reset";
        throw err;
      }
    }
    async function resolveRef({
      fs: fs2,
      dir,
      gitdir = join(dir, ".git"),
      ref,
      depth
    }) {
      try {
        assertParameter("fs", fs2);
        assertParameter("gitdir", gitdir);
        assertParameter("ref", ref);
        const fsp = new FileSystem(fs2);
        const updatedGitdir = await discoverGitdir({ fsp, dotgit: gitdir });
        const oid = await GitRefManager.resolve({
          fs: fsp,
          gitdir: updatedGitdir,
          ref,
          depth
        });
        return oid;
      } catch (err) {
        err.caller = "git.resolveRef";
        throw err;
      }
    }
    async function setConfig({
      fs: _fs,
      dir,
      gitdir = join(dir, ".git"),
      path,
      value,
      append: append2 = false
    }) {
      try {
        assertParameter("fs", _fs);
        assertParameter("gitdir", gitdir);
        assertParameter("path", path);
        const fs2 = new FileSystem(_fs);
        const updatedGitdir = await discoverGitdir({ fsp: fs2, dotgit: gitdir });
        const config = await GitConfigManager.get({ fs: fs2, gitdir: updatedGitdir });
        if (append2) {
          await config.append(path, value);
        } else {
          await config.set(path, value);
        }
        await GitConfigManager.save({ fs: fs2, gitdir: updatedGitdir, config });
      } catch (err) {
        err.caller = "git.setConfig";
        throw err;
      }
    }
    async function _writeCommit({ fs: fs2, gitdir, commit: commit2 }) {
      const object = GitCommit.from(commit2).toObject();
      const oid = await _writeObject({
        fs: fs2,
        gitdir,
        type: "commit",
        object,
        format: "content"
      });
      return oid;
    }
    var GitRefStash = class _GitRefStash {
      // constructor removed
      static get timezoneOffsetForRefLogEntry() {
        const offsetMinutes = (/* @__PURE__ */ new Date()).getTimezoneOffset();
        const offsetHours = Math.abs(Math.floor(offsetMinutes / 60));
        const offsetMinutesFormatted = Math.abs(offsetMinutes % 60).toString().padStart(2, "0");
        const sign = offsetMinutes > 0 ? "-" : "+";
        return `${sign}${offsetHours.toString().padStart(2, "0")}${offsetMinutesFormatted}`;
      }
      static createStashReflogEntry(author, stashCommit, message) {
        const nameNoSpace = author.name.replace(/\s/g, "");
        const z40 = "0000000000000000000000000000000000000000";
        const timestamp = Math.floor(Date.now() / 1e3);
        const timezoneOffset = _GitRefStash.timezoneOffsetForRefLogEntry;
        return `${z40} ${stashCommit} ${nameNoSpace} ${author.email} ${timestamp} ${timezoneOffset}	${message}
`;
      }
      static getStashReflogEntry(reflogString, parsed = false) {
        const reflogLines = reflogString.split("\n");
        const entries = reflogLines.filter((l2) => l2).reverse().map(
          (line, idx) => parsed ? `stash@{${idx}}: ${line.split("	")[1]}` : line
        );
        return entries;
      }
    };
    var _TreeMap = {
      stage: STAGE,
      workdir: WORKDIR
    };
    var lock$3;
    async function acquireLock$1(ref, callback) {
      if (lock$3 === void 0) lock$3 = new AsyncLock();
      return lock$3.acquire(ref, callback);
    }
    async function checkAndWriteBlob(fs2, gitdir, dir, filepath, oid = null) {
      const currentFilepath = join(dir, filepath);
      const stats = await fs2.lstat(currentFilepath);
      if (!stats) throw new NotFoundError(currentFilepath);
      if (stats.isDirectory())
        throw new InternalError(
          `${currentFilepath}: file expected, but found directory`
        );
      const objContent = oid ? await readObjectLoose({ fs: fs2, gitdir, oid }) : void 0;
      let retOid = objContent ? oid : void 0;
      if (!objContent) {
        await acquireLock$1({ fs: fs2, gitdir, currentFilepath }, async () => {
          const object = stats.isSymbolicLink() ? await fs2.readlink(currentFilepath).then(posixifyPathBuffer) : await fs2.read(currentFilepath);
          if (object === null) throw new NotFoundError(currentFilepath);
          retOid = await _writeObject({ fs: fs2, gitdir, type: "blob", object });
        });
      }
      return retOid;
    }
    async function processTreeEntries({ fs: fs2, dir, gitdir, entries }) {
      async function processTreeEntry(entry) {
        if (entry.type === "tree") {
          if (!entry.oid) {
            const children2 = await Promise.all(entry.children.map(processTreeEntry));
            entry.oid = await _writeTree({
              fs: fs2,
              gitdir,
              tree: children2
            });
            entry.mode = 16384;
          }
        } else if (entry.type === "blob") {
          entry.oid = await checkAndWriteBlob(
            fs2,
            gitdir,
            dir,
            entry.path,
            entry.oid
          );
          entry.mode = 33188;
        }
        entry.path = entry.path.split("/").pop();
        return entry;
      }
      return Promise.all(entries.map(processTreeEntry));
    }
    async function writeTreeChanges({
      fs: fs2,
      dir,
      gitdir,
      treePair
      // [TREE({ ref: 'HEAD' }), 'STAGE'] would be the equivalent of `git write-tree`
    }) {
      const isStage = treePair[1] === "stage";
      const trees = treePair.map((t) => typeof t === "string" ? _TreeMap[t]() : t);
      const changedEntries = [];
      const map = async (filepath, [head, stage]) => {
        if (filepath === "." || await GitIgnoreManager.isIgnored({ fs: fs2, dir, gitdir, filepath })) {
          return;
        }
        if (stage) {
          if (!head || await head.oid() !== await stage.oid() && await stage.oid() !== void 0) {
            changedEntries.push([head, stage]);
          }
          return {
            mode: await stage.mode(),
            path: filepath,
            oid: await stage.oid(),
            type: await stage.type()
          };
        }
      };
      const reduce = async (parent, children2) => {
        children2 = children2.filter(Boolean);
        if (!parent) {
          return children2.length > 0 ? children2 : void 0;
        } else {
          parent.children = children2;
          return parent;
        }
      };
      const iterate = async (walk2, children2) => {
        const filtered = [];
        for (const child of children2) {
          const [head, stage] = child;
          if (isStage) {
            if (stage) {
              if (await fs2.exists(`${dir}/${stage.toString()}`)) {
                filtered.push(child);
              } else {
                changedEntries.push([null, stage]);
              }
            }
          } else if (head) {
            if (!stage) {
              changedEntries.push([head, null]);
            } else {
              filtered.push(child);
            }
          }
        }
        return filtered.length ? Promise.all(filtered.map(walk2)) : [];
      };
      const entries = await _walk({
        fs: fs2,
        cache: {},
        dir,
        gitdir,
        trees,
        map,
        reduce,
        iterate
      });
      if (changedEntries.length === 0 || entries.length === 0) {
        return null;
      }
      const processedEntries = await processTreeEntries({
        fs: fs2,
        dir,
        gitdir,
        entries
      });
      const treeEntries = processedEntries.filter(Boolean).map((entry) => ({
        mode: entry.mode,
        path: entry.path,
        oid: entry.oid,
        type: entry.type
      }));
      return _writeTree({ fs: fs2, gitdir, tree: treeEntries });
    }
    async function applyTreeChanges({
      fs: fs2,
      dir,
      gitdir,
      stashCommit,
      parentCommit,
      wasStaged
    }) {
      const dirRemoved = [];
      const stageUpdated = [];
      const ops = await _walk({
        fs: fs2,
        cache: {},
        dir,
        gitdir,
        trees: [TREE({ ref: parentCommit }), TREE({ ref: stashCommit })],
        map: async (filepath, [parent, stash2]) => {
          if (filepath === "." || await GitIgnoreManager.isIgnored({ fs: fs2, dir, gitdir, filepath })) {
            return;
          }
          const type = stash2 ? await stash2.type() : await parent.type();
          if (type !== "tree" && type !== "blob") {
            return;
          }
          if (!stash2 && parent) {
            const method = type === "tree" ? "rmdir" : "rm";
            if (type === "tree") dirRemoved.push(filepath);
            if (type === "blob" && wasStaged)
              stageUpdated.push({ filepath, oid: await parent.oid() });
            return { method, filepath };
          }
          const oid = await stash2.oid();
          if (!parent || await parent.oid() !== oid) {
            if (type === "tree") {
              return { method: "mkdir", filepath };
            } else {
              if (wasStaged)
                stageUpdated.push({
                  filepath,
                  oid,
                  stats: await fs2.lstat(join(dir, filepath))
                });
              return {
                method: "write",
                filepath,
                oid
              };
            }
          }
        }
      });
      await acquireLock$1({ fs: fs2, gitdir, dirRemoved, ops }, async () => {
        for (const op of ops) {
          const currentFilepath = join(dir, op.filepath);
          switch (op.method) {
            case "rmdir":
              await fs2.rmdir(currentFilepath);
              break;
            case "mkdir":
              await fs2.mkdir(currentFilepath);
              break;
            case "rm":
              await fs2.rm(currentFilepath);
              break;
            case "write":
              if (!dirRemoved.some(
                (removedDir) => currentFilepath.startsWith(removedDir)
              )) {
                const { object } = await _readObject({
                  fs: fs2,
                  cache: {},
                  gitdir,
                  oid: op.oid
                });
                if (await fs2.exists(currentFilepath)) {
                  await fs2.rm(currentFilepath);
                }
                await fs2.write(currentFilepath, object);
              }
              break;
          }
        }
      });
      await GitIndexManager.acquire({ fs: fs2, gitdir, cache: {} }, async (index2) => {
        stageUpdated.forEach(({ filepath, stats, oid }) => {
          index2.insert({ filepath, stats, oid });
        });
      });
    }
    var GitStashManager = class _GitStashManager {
      /**
       * Creates an instance of GitStashManager.
       *
       * @param {Object} args
       * @param {FSClient} args.fs - A file system implementation.
       * @param {string} args.dir - The working directory.
       * @param {string}[args.gitdir=join(dir, '.git')] - [required] The [git directory](dir-vs-gitdir.md) path
       */
      constructor({ fs: fs2, dir, gitdir = join(dir, ".git") }) {
        Object.assign(this, {
          fs: fs2,
          dir,
          gitdir,
          _author: null
        });
      }
      /**
       * Gets the reference name for the stash.
       *
       * @returns {string} - The stash reference name.
       */
      static get refStash() {
        return "refs/stash";
      }
      /**
       * Gets the reference name for the stash reflogs.
       *
       * @returns {string} - The stash reflogs reference name.
       */
      static get refLogsStash() {
        return "logs/refs/stash";
      }
      /**
       * Gets the file path for the stash reference.
       *
       * @returns {string} - The file path for the stash reference.
       */
      get refStashPath() {
        return join(this.gitdir, _GitStashManager.refStash);
      }
      /**
       * Gets the file path for the stash reflogs.
       *
       * @returns {string} - The file path for the stash reflogs.
       */
      get refLogsStashPath() {
        return join(this.gitdir, _GitStashManager.refLogsStash);
      }
      /**
       * Retrieves the author information for the stash.
       *
       * @returns {Promise<Object>} - The author object.
       * @throws {MissingNameError} - If the author name is missing.
       */
      async getAuthor() {
        if (!this._author) {
          this._author = await normalizeAuthorObject({
            fs: this.fs,
            gitdir: this.gitdir,
            author: {}
          });
          if (!this._author) throw new MissingNameError("author");
        }
        return this._author;
      }
      /**
       * Gets the SHA of a stash entry by its index.
       *
       * @param {number} refIdx - The index of the stash entry.
       * @param {string[]} [stashEntries] - Optional preloaded stash entries.
       * @returns {Promise<string|null>} - The SHA of the stash entry or `null` if not found.
       */
      async getStashSHA(refIdx, stashEntries) {
        if (!await this.fs.exists(this.refStashPath)) {
          return null;
        }
        const entries = stashEntries || await this.readStashReflogs({ parsed: false });
        return entries[refIdx].split(" ")[1];
      }
      /**
       * Writes a stash commit to the repository.
       *
       * @param {Object} args
       * @param {string} args.message - The commit message.
       * @param {string} args.tree - The tree object ID.
       * @param {string[]} args.parent - The parent commit object IDs.
       * @returns {Promise<string>} - The object ID of the written commit.
       */
      async writeStashCommit({ message, tree, parent }) {
        return _writeCommit({
          fs: this.fs,
          gitdir: this.gitdir,
          commit: {
            message,
            tree,
            parent,
            author: await this.getAuthor(),
            committer: await this.getAuthor()
          }
        });
      }
      /**
       * Reads a stash commit by its index.
       *
       * @param {number} refIdx - The index of the stash entry.
       * @returns {Promise<Object>} - The stash commit object.
       * @throws {InvalidRefNameError} - If the index is invalid.
       */
      async readStashCommit(refIdx) {
        const stashEntries = await this.readStashReflogs({ parsed: false });
        if (refIdx !== 0) {
          if (refIdx < 0 || refIdx > stashEntries.length - 1) {
            throw new InvalidRefNameError(
              `stash@${refIdx}`,
              "number that is in range of [0, num of stash pushed]"
            );
          }
        }
        const stashSHA = await this.getStashSHA(refIdx, stashEntries);
        if (!stashSHA) {
          return {};
        }
        return _readCommit({
          fs: this.fs,
          cache: {},
          gitdir: this.gitdir,
          oid: stashSHA
        });
      }
      /**
       * Writes a stash reference to the repository.
       *
       * @param {string} stashCommit - The object ID of the stash commit.
       * @returns {Promise<void>}
       */
      async writeStashRef(stashCommit) {
        return GitRefManager.writeRef({
          fs: this.fs,
          gitdir: this.gitdir,
          ref: _GitStashManager.refStash,
          value: stashCommit
        });
      }
      /**
       * Writes a reflog entry for a stash commit.
       *
       * @param {Object} args
       * @param {string} args.stashCommit - The object ID of the stash commit.
       * @param {string} args.message - The reflog message.
       * @returns {Promise<void>}
       */
      async writeStashReflogEntry({ stashCommit, message }) {
        const author = await this.getAuthor();
        const entry = GitRefStash.createStashReflogEntry(
          author,
          stashCommit,
          message
        );
        const filepath = this.refLogsStashPath;
        await acquireLock$1({ filepath, entry }, async () => {
          const appendTo = await this.fs.exists(filepath) ? await this.fs.read(filepath, "utf8") : "";
          await this.fs.write(filepath, appendTo + entry, "utf8");
        });
      }
      /**
       * Reads the stash reflogs.
       *
       * @param {Object} args
       * @param {boolean} [args.parsed=false] - Whether to parse the reflog entries.
       * @returns {Promise<string[]|Object[]>} - The reflog entries as strings or parsed objects.
       */
      async readStashReflogs({ parsed = false }) {
        if (!await this.fs.exists(this.refLogsStashPath)) {
          return [];
        }
        const reflogString = await this.fs.read(this.refLogsStashPath, "utf8");
        return GitRefStash.getStashReflogEntry(reflogString, parsed);
      }
    };
    async function _createStashCommit({ fs: fs2, dir, gitdir, message = "" }) {
      const stashMgr = new GitStashManager({ fs: fs2, dir, gitdir });
      await stashMgr.getAuthor();
      const branch2 = await _currentBranch({
        fs: fs2,
        gitdir,
        fullname: false
      });
      const headCommit = await GitRefManager.resolve({
        fs: fs2,
        gitdir,
        ref: "HEAD"
      });
      const headCommitObj = await readCommit({ fs: fs2, dir, gitdir, oid: headCommit });
      const headMsg = headCommitObj.commit.message;
      const stashCommitParents = [headCommit];
      let stashCommitTree = null;
      let workDirCompareBase = TREE({ ref: "HEAD" });
      const indexTree = await writeTreeChanges({
        fs: fs2,
        dir,
        gitdir,
        treePair: [TREE({ ref: "HEAD" }), "stage"]
      });
      if (indexTree) {
        const stashCommitOne = await stashMgr.writeStashCommit({
          message: `stash-Index: WIP on ${branch2} - ${(/* @__PURE__ */ new Date()).toISOString()}`,
          tree: indexTree,
          parent: stashCommitParents
        });
        stashCommitParents.push(stashCommitOne);
        stashCommitTree = indexTree;
        workDirCompareBase = STAGE();
      }
      const workingTree = await writeTreeChanges({
        fs: fs2,
        dir,
        gitdir,
        treePair: [workDirCompareBase, "workdir"]
      });
      if (workingTree) {
        const workingHeadCommit = await stashMgr.writeStashCommit({
          message: `stash-WorkDir: WIP on ${branch2} - ${(/* @__PURE__ */ new Date()).toISOString()}`,
          tree: workingTree,
          parent: [stashCommitParents[stashCommitParents.length - 1]]
        });
        stashCommitParents.push(workingHeadCommit);
        stashCommitTree = workingTree;
      }
      if (!stashCommitTree || !indexTree && !workingTree) {
        throw new NotFoundError("changes, nothing to stash");
      }
      const stashMsg = (message.trim() || `WIP on ${branch2}`) + `: ${headCommit.substring(0, 7)} ${headMsg}`;
      const stashCommit = await stashMgr.writeStashCommit({
        message: stashMsg,
        tree: stashCommitTree,
        parent: stashCommitParents
      });
      return { stashCommit, stashMsg, branch: branch2, stashMgr };
    }
    async function _stashPush({ fs: fs2, dir, gitdir, message = "" }) {
      const { stashCommit, stashMsg, branch: branch2, stashMgr } = await _createStashCommit({
        fs: fs2,
        dir,
        gitdir,
        message
      });
      await stashMgr.writeStashRef(stashCommit);
      await stashMgr.writeStashReflogEntry({
        stashCommit,
        message: stashMsg
      });
      await checkout({
        fs: fs2,
        dir,
        gitdir,
        ref: branch2,
        track: false,
        force: true
        // force checkout to discard changes
      });
      return stashCommit;
    }
    async function _stashCreate({ fs: fs2, dir, gitdir, message = "" }) {
      const { stashCommit } = await _createStashCommit({
        fs: fs2,
        dir,
        gitdir,
        message
      });
      return stashCommit;
    }
    async function _stashApply({ fs: fs2, dir, gitdir, refIdx = 0 }) {
      const stashMgr = new GitStashManager({ fs: fs2, dir, gitdir });
      const stashCommit = await stashMgr.readStashCommit(refIdx);
      const { parent: stashParents = null } = stashCommit.commit ? stashCommit.commit : {};
      if (!stashParents || !Array.isArray(stashParents)) {
        return;
      }
      for (let i = 0; i < stashParents.length - 1; i++) {
        const applyingCommit = await _readCommit({
          fs: fs2,
          cache: {},
          gitdir,
          oid: stashParents[i + 1]
        });
        const wasStaged = applyingCommit.commit.message.startsWith("stash-Index");
        await applyTreeChanges({
          fs: fs2,
          dir,
          gitdir,
          stashCommit: stashParents[i + 1],
          parentCommit: stashParents[i],
          wasStaged
        });
      }
    }
    async function _stashDrop({ fs: fs2, dir, gitdir, refIdx = 0 }) {
      const stashMgr = new GitStashManager({ fs: fs2, dir, gitdir });
      const stashCommit = await stashMgr.readStashCommit(refIdx);
      if (!stashCommit.commit) {
        return;
      }
      const stashRefPath = stashMgr.refStashPath;
      await acquireLock$1(stashRefPath, async () => {
        if (await fs2.exists(stashRefPath)) {
          await fs2.rm(stashRefPath);
        }
      });
      const reflogEntries = await stashMgr.readStashReflogs({ parsed: false });
      if (!reflogEntries.length) {
        return;
      }
      reflogEntries.splice(refIdx, 1);
      const stashReflogPath = stashMgr.refLogsStashPath;
      await acquireLock$1({ reflogEntries, stashReflogPath, stashMgr }, async () => {
        if (reflogEntries.length) {
          await fs2.write(
            stashReflogPath,
            reflogEntries.reverse().join("\n") + "\n",
            "utf8"
          );
          const lastStashCommit = reflogEntries[reflogEntries.length - 1].split(" ")[1];
          await stashMgr.writeStashRef(lastStashCommit);
        } else {
          await fs2.rm(stashReflogPath);
        }
      });
    }
    async function _stashList({ fs: fs2, dir, gitdir }) {
      const stashMgr = new GitStashManager({ fs: fs2, dir, gitdir });
      return stashMgr.readStashReflogs({ parsed: true });
    }
    async function _stashClear({ fs: fs2, dir, gitdir }) {
      const stashMgr = new GitStashManager({ fs: fs2, dir, gitdir });
      const stashRefPath = [stashMgr.refStashPath, stashMgr.refLogsStashPath];
      await acquireLock$1(stashRefPath, async () => {
        await Promise.all(
          stashRefPath.map(async (path) => {
            if (await fs2.exists(path)) {
              return fs2.rm(path);
            }
          })
        );
      });
    }
    async function _stashPop({ fs: fs2, dir, gitdir, refIdx = 0 }) {
      await _stashApply({ fs: fs2, dir, gitdir, refIdx });
      await _stashDrop({ fs: fs2, dir, gitdir, refIdx });
    }
    async function stash({
      fs: fs2,
      dir,
      gitdir = join(dir, ".git"),
      op = "push",
      message = "",
      refIdx = 0
    }) {
      assertParameter("fs", fs2);
      assertParameter("dir", dir);
      assertParameter("gitdir", gitdir);
      assertParameter("op", op);
      const stashMap = {
        push: _stashPush,
        apply: _stashApply,
        drop: _stashDrop,
        list: _stashList,
        clear: _stashClear,
        pop: _stashPop,
        create: _stashCreate
      };
      const opsNeedRefIdx = ["apply", "drop", "pop"];
      try {
        const _fs = new FileSystem(fs2);
        const updatedGitdir = await discoverGitdir({ fsp: _fs, dotgit: gitdir });
        const folders = ["refs", "logs", "logs/refs"];
        folders.map((f) => join(updatedGitdir, f)).forEach(async (folder) => {
          if (!await _fs.exists(folder)) {
            await _fs.mkdir(folder);
          }
        });
        const opFunc = stashMap[op];
        if (opFunc) {
          if (opsNeedRefIdx.includes(op) && refIdx < 0) {
            throw new InvalidRefNameError(
              `stash@${refIdx}`,
              "number that is in range of [0, num of stash pushed]"
            );
          }
          return await opFunc({
            fs: _fs,
            dir,
            gitdir: updatedGitdir,
            message,
            refIdx
          });
        }
        throw new Error(`To be implemented: ${op}`);
      } catch (err) {
        err.caller = "git.stash";
        throw err;
      }
    }
    async function status({
      fs: _fs,
      dir,
      gitdir = join(dir, ".git"),
      filepath,
      cache = {}
    }) {
      try {
        assertParameter("fs", _fs);
        assertParameter("gitdir", gitdir);
        assertParameter("filepath", filepath);
        const fs2 = new FileSystem(_fs);
        const updatedGitdir = await discoverGitdir({ fsp: fs2, dotgit: gitdir });
        const ignored = await GitIgnoreManager.isIgnored({
          fs: fs2,
          gitdir: updatedGitdir,
          dir,
          filepath
        });
        if (ignored) {
          return "ignored";
        }
        const headTree = await getHeadTree({ fs: fs2, cache, gitdir: updatedGitdir });
        const treeOid = await getOidAtPath({
          fs: fs2,
          cache,
          gitdir: updatedGitdir,
          tree: headTree,
          path: filepath
        });
        const indexEntry = await GitIndexManager.acquire(
          { fs: fs2, gitdir: updatedGitdir, cache },
          async function(index2) {
            for (const entry of index2) {
              if (entry.path === filepath) return entry;
            }
            return null;
          }
        );
        const stats = await fs2.lstat(join(dir, filepath));
        const H = treeOid !== null;
        const I = indexEntry !== null;
        const W = stats !== null;
        const getWorkdirOid = async () => {
          if (I && !compareStats(indexEntry, stats)) {
            return indexEntry.oid;
          } else {
            const object = await fs2.read(join(dir, filepath));
            const workdirOid = await hashObject$1({
              gitdir: updatedGitdir,
              type: "blob",
              object
            });
            if (I && indexEntry.oid === workdirOid) {
              if (stats.size !== -1) {
                GitIndexManager.acquire(
                  { fs: fs2, gitdir: updatedGitdir, cache },
                  async function(index2) {
                    index2.insert({ filepath, stats, oid: workdirOid });
                  }
                );
              }
            }
            return workdirOid;
          }
        };
        if (!H && !W && !I) return "absent";
        if (!H && !W && I) return "*absent";
        if (!H && W && !I) return "*added";
        if (!H && W && I) {
          const workdirOid = await getWorkdirOid();
          return workdirOid === indexEntry.oid ? "added" : "*added";
        }
        if (H && !W && !I) return "deleted";
        if (H && !W && I) {
          return treeOid === indexEntry.oid ? "*deleted" : "*deleted";
        }
        if (H && W && !I) {
          const workdirOid = await getWorkdirOid();
          return workdirOid === treeOid ? "*undeleted" : "*undeletemodified";
        }
        if (H && W && I) {
          const workdirOid = await getWorkdirOid();
          if (workdirOid === treeOid) {
            return workdirOid === indexEntry.oid ? "unmodified" : "*unmodified";
          } else {
            return workdirOid === indexEntry.oid ? "modified" : "*modified";
          }
        }
      } catch (err) {
        err.caller = "git.status";
        throw err;
      }
    }
    async function getOidAtPath({ fs: fs2, cache, gitdir: updatedGitdir, tree, path }) {
      if (typeof path === "string") path = path.split("/");
      const dirname2 = path.shift();
      for (const entry of tree) {
        if (entry.path === dirname2) {
          if (path.length === 0) {
            return entry.oid;
          }
          const { type, object } = await _readObject({
            fs: fs2,
            cache,
            gitdir: updatedGitdir,
            oid: entry.oid
          });
          if (type === "tree") {
            const tree2 = GitTree.from(object);
            return getOidAtPath({ fs: fs2, cache, gitdir: updatedGitdir, tree: tree2, path });
          }
          if (type === "blob") {
            throw new ObjectTypeError(entry.oid, type, "blob", path.join("/"));
          }
        }
      }
      return null;
    }
    async function getHeadTree({ fs: fs2, cache, gitdir: updatedGitdir }) {
      let oid;
      try {
        oid = await GitRefManager.resolve({
          fs: fs2,
          gitdir: updatedGitdir,
          ref: "HEAD"
        });
      } catch (e) {
        if (e instanceof NotFoundError) {
          return [];
        }
      }
      const { tree } = await _readTree({ fs: fs2, cache, gitdir: updatedGitdir, oid });
      return tree;
    }
    async function statusMatrix({
      fs: _fs,
      dir,
      gitdir = join(dir, ".git"),
      ref = "HEAD",
      filepaths = ["."],
      filter,
      cache = {},
      ignored: shouldIgnore = false
    }) {
      try {
        assertParameter("fs", _fs);
        assertParameter("gitdir", gitdir);
        assertParameter("ref", ref);
        const fs2 = new FileSystem(_fs);
        const updatedGitdir = await discoverGitdir({ fsp: fs2, dotgit: gitdir });
        return await _walk({
          fs: fs2,
          cache,
          dir,
          gitdir: updatedGitdir,
          trees: [TREE({ ref }), WORKDIR(), STAGE()],
          map: async function(filepath, [head, workdir, stage]) {
            if (!head && !stage && workdir) {
              if (!shouldIgnore) {
                const isIgnored2 = await GitIgnoreManager.isIgnored({
                  fs: fs2,
                  dir,
                  filepath
                });
                if (isIgnored2) {
                  return null;
                }
              }
            }
            if (!filepaths.some((base) => worthWalking(filepath, base))) {
              return null;
            }
            if (filter) {
              if (!filter(filepath)) return;
            }
            const [headType, workdirType, stageType] = await Promise.all([
              head && head.type(),
              workdir && workdir.type(),
              stage && stage.type()
            ]);
            const isBlob = [headType, workdirType, stageType].includes("blob");
            if ((headType === "tree" || headType === "special") && !isBlob) return;
            if (headType === "commit") return null;
            if ((workdirType === "tree" || workdirType === "special") && !isBlob)
              return;
            if (stageType === "commit") return null;
            if ((stageType === "tree" || stageType === "special") && !isBlob) return;
            const headOid = headType === "blob" ? await head.oid() : void 0;
            const stageOid = stageType === "blob" ? await stage.oid() : void 0;
            let workdirOid;
            if (headType !== "blob" && workdirType === "blob" && stageType !== "blob") {
              workdirOid = "42";
            } else if (workdirType === "blob") {
              workdirOid = await workdir.oid();
            }
            const entry = [void 0, headOid, workdirOid, stageOid];
            const result = entry.map((value) => entry.indexOf(value));
            result.shift();
            return [filepath, ...result];
          }
        });
      } catch (err) {
        err.caller = "git.statusMatrix";
        throw err;
      }
    }
    async function tag({
      fs: _fs,
      dir,
      gitdir = join(dir, ".git"),
      ref,
      object,
      force = false
    }) {
      try {
        assertParameter("fs", _fs);
        assertParameter("gitdir", gitdir);
        assertParameter("ref", ref);
        const fs2 = new FileSystem(_fs);
        if (ref === void 0) {
          throw new MissingParameterError("ref");
        }
        ref = ref.startsWith("refs/tags/") ? ref : `refs/tags/${ref}`;
        const updatedGitdir = await discoverGitdir({ fsp: fs2, dotgit: gitdir });
        const value = await GitRefManager.resolve({
          fs: fs2,
          gitdir: updatedGitdir,
          ref: object || "HEAD"
        });
        if (!force && await GitRefManager.exists({ fs: fs2, gitdir: updatedGitdir, ref })) {
          throw new AlreadyExistsError("tag", ref);
        }
        await GitRefManager.writeRef({ fs: fs2, gitdir: updatedGitdir, ref, value });
      } catch (err) {
        err.caller = "git.tag";
        throw err;
      }
    }
    async function updateIndex$1({
      fs: _fs,
      dir,
      gitdir = join(dir, ".git"),
      cache = {},
      filepath,
      oid,
      mode,
      add: add2,
      remove: remove2,
      force
    }) {
      try {
        assertParameter("fs", _fs);
        assertParameter("gitdir", gitdir);
        assertParameter("filepath", filepath);
        const fs2 = new FileSystem(_fs);
        const updatedGitdir = await discoverGitdir({ fsp: fs2, dotgit: gitdir });
        if (remove2) {
          return await GitIndexManager.acquire(
            { fs: fs2, gitdir: updatedGitdir, cache },
            async function(index2) {
              if (!force) {
                const fileStats2 = await fs2.lstat(join(dir, filepath));
                if (fileStats2) {
                  if (fileStats2.isDirectory()) {
                    throw new InvalidFilepathError("directory");
                  }
                  return;
                }
              }
              if (index2.has({ filepath })) {
                index2.delete({
                  filepath
                });
              }
            }
          );
        }
        let fileStats;
        if (!oid) {
          fileStats = await fs2.lstat(join(dir, filepath));
          if (!fileStats) {
            throw new NotFoundError(
              `file at "${filepath}" on disk and "remove" not set`
            );
          }
          if (fileStats.isDirectory()) {
            throw new InvalidFilepathError("directory");
          }
        }
        return await GitIndexManager.acquire(
          { fs: fs2, gitdir: updatedGitdir, cache },
          async function(index2) {
            if (!add2 && !index2.has({ filepath })) {
              throw new NotFoundError(
                `file at "${filepath}" in index and "add" not set`
              );
            }
            let stats;
            if (!oid) {
              stats = fileStats;
              const object = stats.isSymbolicLink() ? await fs2.readlink(join(dir, filepath)) : await fs2.read(join(dir, filepath));
              oid = await _writeObject({
                fs: fs2,
                gitdir: updatedGitdir,
                type: "blob",
                format: "content",
                object
              });
            } else {
              stats = {
                ctime: /* @__PURE__ */ new Date(0),
                mtime: /* @__PURE__ */ new Date(0),
                dev: 0,
                ino: 0,
                mode,
                uid: 0,
                gid: 0,
                size: 0
              };
            }
            index2.insert({
              filepath,
              oid,
              stats
            });
            return oid;
          }
        );
      } catch (err) {
        err.caller = "git.updateIndex";
        throw err;
      }
    }
    function version2() {
      try {
        return pkg.version;
      } catch (err) {
        err.caller = "git.version";
        throw err;
      }
    }
    async function walk({
      fs: fs2,
      dir,
      gitdir = join(dir, ".git"),
      trees,
      map,
      reduce,
      iterate,
      cache = {}
    }) {
      try {
        assertParameter("fs", fs2);
        assertParameter("gitdir", gitdir);
        assertParameter("trees", trees);
        const fsp = new FileSystem(fs2);
        const updatedGitdir = await discoverGitdir({ fsp, dotgit: gitdir });
        return await _walk({
          fs: fsp,
          cache,
          dir,
          gitdir: updatedGitdir,
          trees,
          map,
          reduce,
          iterate
        });
      } catch (err) {
        err.caller = "git.walk";
        throw err;
      }
    }
    async function writeBlob({ fs: fs2, dir, gitdir = join(dir, ".git"), blob }) {
      try {
        assertParameter("fs", fs2);
        assertParameter("gitdir", gitdir);
        assertParameter("blob", blob);
        const fsp = new FileSystem(fs2);
        const updatedGitdir = await discoverGitdir({ fsp, dotgit: gitdir });
        return await _writeObject({
          fs: fsp,
          gitdir: updatedGitdir,
          type: "blob",
          object: blob,
          format: "content"
        });
      } catch (err) {
        err.caller = "git.writeBlob";
        throw err;
      }
    }
    async function writeCommit({
      fs: fs2,
      dir,
      gitdir = join(dir, ".git"),
      commit: commit2
    }) {
      try {
        assertParameter("fs", fs2);
        assertParameter("gitdir", gitdir);
        assertParameter("commit", commit2);
        const fsp = new FileSystem(fs2);
        const updatedGitdir = await discoverGitdir({ fsp, dotgit: gitdir });
        return await _writeCommit({
          fs: fsp,
          gitdir: updatedGitdir,
          commit: commit2
        });
      } catch (err) {
        err.caller = "git.writeCommit";
        throw err;
      }
    }
    async function writeObject({
      fs: _fs,
      dir,
      gitdir = join(dir, ".git"),
      type,
      object,
      format = "parsed",
      oid,
      encoding = void 0
    }) {
      try {
        const fs2 = new FileSystem(_fs);
        const updatedGitdir = await discoverGitdir({ fsp: fs2, dotgit: gitdir });
        if (format === "parsed") {
          switch (type) {
            case "commit":
              object = GitCommit.from(object).toObject();
              break;
            case "tree":
              object = GitTree.from(object).toObject();
              break;
            case "blob":
              object = Buffer.from(object, encoding);
              break;
            case "tag":
              object = GitAnnotatedTag.from(object).toObject();
              break;
            default:
              throw new ObjectTypeError(oid || "", type, "blob|commit|tag|tree");
          }
          format = "content";
        }
        oid = await _writeObject({
          fs: fs2,
          gitdir: updatedGitdir,
          type,
          object,
          oid,
          format
        });
        return oid;
      } catch (err) {
        err.caller = "git.writeObject";
        throw err;
      }
    }
    async function writeRef({
      fs: _fs,
      dir,
      gitdir = join(dir, ".git"),
      ref,
      value,
      force = false,
      symbolic = false
    }) {
      try {
        assertParameter("fs", _fs);
        assertParameter("gitdir", gitdir);
        assertParameter("ref", ref);
        assertParameter("value", value);
        const fs2 = new FileSystem(_fs);
        if (!isValidRef(ref, true)) {
          throw new InvalidRefNameError(ref, cleanGitRef.clean(ref));
        }
        const updatedGitdir = await discoverGitdir({ fsp: fs2, dotgit: gitdir });
        if (!force && await GitRefManager.exists({ fs: fs2, gitdir: updatedGitdir, ref })) {
          throw new AlreadyExistsError("ref", ref);
        }
        if (symbolic) {
          await GitRefManager.writeSymbolicRef({
            fs: fs2,
            gitdir: updatedGitdir,
            ref,
            value
          });
        } else {
          value = await GitRefManager.resolve({
            fs: fs2,
            gitdir: updatedGitdir,
            ref: value
          });
          await GitRefManager.writeRef({
            fs: fs2,
            gitdir: updatedGitdir,
            ref,
            value
          });
        }
      } catch (err) {
        err.caller = "git.writeRef";
        throw err;
      }
    }
    async function _writeTag({ fs: fs2, gitdir, tag: tag2 }) {
      const object = GitAnnotatedTag.from(tag2).toObject();
      const oid = await _writeObject({
        fs: fs2,
        gitdir,
        type: "tag",
        object,
        format: "content"
      });
      return oid;
    }
    async function writeTag({ fs: fs2, dir, gitdir = join(dir, ".git"), tag: tag2 }) {
      try {
        assertParameter("fs", fs2);
        assertParameter("gitdir", gitdir);
        assertParameter("tag", tag2);
        const fsp = new FileSystem(fs2);
        const updatedGitdir = await discoverGitdir({ fsp, dotgit: gitdir });
        return await _writeTag({
          fs: fsp,
          gitdir: updatedGitdir,
          tag: tag2
        });
      } catch (err) {
        err.caller = "git.writeTag";
        throw err;
      }
    }
    async function writeTree({ fs: fs2, dir, gitdir = join(dir, ".git"), tree }) {
      try {
        assertParameter("fs", fs2);
        assertParameter("gitdir", gitdir);
        assertParameter("tree", tree);
        const fsp = new FileSystem(fs2);
        const updatedGitdir = await discoverGitdir({ fsp, dotgit: gitdir });
        return await _writeTree({
          fs: fsp,
          gitdir: updatedGitdir,
          tree
        });
      } catch (err) {
        err.caller = "git.writeTree";
        throw err;
      }
    }
    var index = {
      Errors,
      STAGE,
      TREE,
      WORKDIR,
      add,
      abortMerge,
      addNote,
      addRemote,
      annotatedTag,
      branch,
      checkout,
      clone: clone3,
      commit,
      getConfig,
      getConfigAll,
      setConfig,
      currentBranch,
      deleteBranch,
      deleteRef,
      deleteRemote,
      deleteTag,
      expandOid,
      expandRef,
      fastForward,
      fetch: fetch2,
      findMergeBase,
      findRoot,
      getRemoteInfo,
      getRemoteInfo2,
      hashBlob,
      indexPack,
      init: init3,
      isDescendent,
      isIgnored,
      listBranches,
      listFiles,
      listNotes,
      listRefs,
      listRemotes,
      listServerRefs,
      listTags,
      log,
      merge,
      packObjects,
      pull,
      push,
      readBlob,
      readCommit,
      readNote,
      readObject,
      readTag,
      readTree,
      remove,
      removeNote,
      renameBranch,
      resetIndex,
      updateIndex: updateIndex$1,
      resolveRef,
      status,
      statusMatrix,
      tag,
      version: version2,
      walk,
      writeBlob,
      writeCommit,
      writeObject,
      writeRef,
      writeTag,
      writeTree,
      stash
    };
    exports.Errors = Errors;
    exports.STAGE = STAGE;
    exports.TREE = TREE;
    exports.WORKDIR = WORKDIR;
    exports.abortMerge = abortMerge;
    exports.add = add;
    exports.addNote = addNote;
    exports.addRemote = addRemote;
    exports.annotatedTag = annotatedTag;
    exports.branch = branch;
    exports.checkout = checkout;
    exports.clone = clone3;
    exports.commit = commit;
    exports.currentBranch = currentBranch;
    exports.default = index;
    exports.deleteBranch = deleteBranch;
    exports.deleteRef = deleteRef;
    exports.deleteRemote = deleteRemote;
    exports.deleteTag = deleteTag;
    exports.expandOid = expandOid;
    exports.expandRef = expandRef;
    exports.fastForward = fastForward;
    exports.fetch = fetch2;
    exports.findMergeBase = findMergeBase;
    exports.findRoot = findRoot;
    exports.getConfig = getConfig;
    exports.getConfigAll = getConfigAll;
    exports.getRemoteInfo = getRemoteInfo;
    exports.getRemoteInfo2 = getRemoteInfo2;
    exports.hashBlob = hashBlob;
    exports.indexPack = indexPack;
    exports.init = init3;
    exports.isDescendent = isDescendent;
    exports.isIgnored = isIgnored;
    exports.listBranches = listBranches;
    exports.listFiles = listFiles;
    exports.listNotes = listNotes;
    exports.listRefs = listRefs;
    exports.listRemotes = listRemotes;
    exports.listServerRefs = listServerRefs;
    exports.listTags = listTags;
    exports.log = log;
    exports.merge = merge;
    exports.packObjects = packObjects;
    exports.pull = pull;
    exports.push = push;
    exports.readBlob = readBlob;
    exports.readCommit = readCommit;
    exports.readNote = readNote;
    exports.readObject = readObject;
    exports.readTag = readTag;
    exports.readTree = readTree;
    exports.remove = remove;
    exports.removeNote = removeNote;
    exports.renameBranch = renameBranch;
    exports.resetIndex = resetIndex;
    exports.resolveRef = resolveRef;
    exports.setConfig = setConfig;
    exports.stash = stash;
    exports.status = status;
    exports.statusMatrix = statusMatrix;
    exports.tag = tag;
    exports.updateIndex = updateIndex$1;
    exports.version = version2;
    exports.walk = walk;
    exports.writeBlob = writeBlob;
    exports.writeCommit = writeCommit;
    exports.writeObject = writeObject;
    exports.writeRef = writeRef;
    exports.writeTag = writeTag;
    exports.writeTree = writeTree;
  }
});

// node_modules/just-once/index.js
var require_just_once = __commonJS({
  "node_modules/just-once/index.js"(exports, module2) {
    init_esbuild_buffer_shim();
    module2.exports = once;
    function once(fn) {
      var called, value;
      if (typeof fn !== "function") {
        throw new Error("expected a function but got " + fn);
      }
      return function wrap() {
        if (called) {
          return value;
        }
        called = true;
        value = fn.apply(this, arguments);
        return value;
      };
    }
  }
});

// node_modules/fast-text-encoding/text.min.js
var require_text_min = __commonJS({
  "node_modules/fast-text-encoding/text.min.js"(exports) {
    init_esbuild_buffer_shim();
    (function(scope) {
      "use strict";
      function B(r, e) {
        var f;
        return r instanceof Buffer ? f = r : f = Buffer.from(r.buffer, r.byteOffset, r.byteLength), f.toString(e);
      }
      var w = function(r) {
        return Buffer.from(r);
      };
      function h(r) {
        for (var e = 0, f = Math.min(256 * 256, r.length + 1), n2 = new Uint16Array(f), i = [], o = 0; ; ) {
          var t = e < r.length;
          if (!t || o >= f - 1) {
            var s2 = n2.subarray(0, o), m = s2;
            if (i.push(String.fromCharCode.apply(null, m)), !t) return i.join("");
            r = r.subarray(e), e = 0, o = 0;
          }
          var a = r[e++];
          if ((a & 128) === 0) n2[o++] = a;
          else if ((a & 224) === 192) {
            var d = r[e++] & 63;
            n2[o++] = (a & 31) << 6 | d;
          } else if ((a & 240) === 224) {
            var d = r[e++] & 63, l2 = r[e++] & 63;
            n2[o++] = (a & 31) << 12 | d << 6 | l2;
          } else if ((a & 248) === 240) {
            var d = r[e++] & 63, l2 = r[e++] & 63, R = r[e++] & 63, c = (a & 7) << 18 | d << 12 | l2 << 6 | R;
            c > 65535 && (c -= 65536, n2[o++] = c >>> 10 & 1023 | 55296, c = 56320 | c & 1023), n2[o++] = c;
          }
        }
      }
      function F(r) {
        for (var e = 0, f = r.length, n2 = 0, i = Math.max(32, f + (f >>> 1) + 7), o = new Uint8Array(i >>> 3 << 3); e < f; ) {
          var t = r.charCodeAt(e++);
          if (t >= 55296 && t <= 56319) {
            if (e < f) {
              var s2 = r.charCodeAt(e);
              (s2 & 64512) === 56320 && (++e, t = ((t & 1023) << 10) + (s2 & 1023) + 65536);
            }
            if (t >= 55296 && t <= 56319) continue;
          }
          if (n2 + 4 > o.length) {
            i += 8, i *= 1 + e / r.length * 2, i = i >>> 3 << 3;
            var m = new Uint8Array(i);
            m.set(o), o = m;
          }
          if ((t & 4294967168) === 0) {
            o[n2++] = t;
            continue;
          } else if ((t & 4294965248) === 0) o[n2++] = t >>> 6 & 31 | 192;
          else if ((t & 4294901760) === 0) o[n2++] = t >>> 12 & 15 | 224, o[n2++] = t >>> 6 & 63 | 128;
          else if ((t & 4292870144) === 0) o[n2++] = t >>> 18 & 7 | 240, o[n2++] = t >>> 12 & 63 | 128, o[n2++] = t >>> 6 & 63 | 128;
          else continue;
          o[n2++] = t & 63 | 128;
        }
        return o.slice ? o.slice(0, n2) : o.subarray(0, n2);
      }
      var u = "Failed to ", p = function(r, e, f) {
        if (r) throw new Error("".concat(u).concat(e, ": the '").concat(f, "' option is unsupported."));
      };
      var x = typeof Buffer == "function" && Buffer.from;
      var A = x ? w : F;
      function v() {
        this.encoding = "utf-8";
      }
      v.prototype.encode = function(r, e) {
        return p(e && e.stream, "encode", "stream"), A(r);
      };
      function U(r) {
        var e;
        try {
          var f = new Blob([r], { type: "text/plain;charset=UTF-8" });
          e = URL.createObjectURL(f);
          var n2 = new XMLHttpRequest();
          return n2.open("GET", e, false), n2.send(), n2.responseText;
        } finally {
          e && URL.revokeObjectURL(e);
        }
      }
      var O = !x && typeof Blob == "function" && typeof URL == "function" && typeof URL.createObjectURL == "function", S = ["utf-8", "utf8", "unicode-1-1-utf-8"], T = h;
      x ? T = B : O && (T = function(r) {
        try {
          return U(r);
        } catch (e) {
          return h(r);
        }
      });
      var y = "construct 'TextDecoder'", E = "".concat(u, " ").concat(y, ": the ");
      function g(r, e) {
        p(e && e.fatal, y, "fatal"), r = r || "utf-8";
        var f;
        if (x ? f = Buffer.isEncoding(r) : f = S.indexOf(r.toLowerCase()) !== -1, !f) throw new RangeError("".concat(E, " encoding label provided ('").concat(r, "') is invalid."));
        this.encoding = r, this.fatal = false, this.ignoreBOM = false;
      }
      g.prototype.decode = function(r, e) {
        p(e && e.stream, "decode", "stream");
        var f;
        return r instanceof Uint8Array ? f = r : r.buffer instanceof ArrayBuffer ? f = new Uint8Array(r.buffer) : f = new Uint8Array(r), T(f, this.encoding);
      };
      scope.TextEncoder = scope.TextEncoder || v;
      scope.TextDecoder = scope.TextDecoder || g;
    })(typeof window !== "undefined" ? window : typeof globalThis !== "undefined" ? globalThis : exports);
  }
});

// node_modules/isomorphic-textencoder/browser.js
var require_browser = __commonJS({
  "node_modules/isomorphic-textencoder/browser.js"(exports, module2) {
    init_esbuild_buffer_shim();
    require_text_min();
    module2.exports = {
      encode: (string) => new TextEncoder().encode(string),
      decode: (buffer) => new TextDecoder().decode(buffer)
    };
  }
});

// node_modules/just-debounce-it/index.js
var require_just_debounce_it = __commonJS({
  "node_modules/just-debounce-it/index.js"(exports, module2) {
    init_esbuild_buffer_shim();
    module2.exports = debounce2;
    function debounce2(fn, wait, callFirst) {
      var timeout;
      return function() {
        if (!wait) {
          return fn.apply(this, arguments);
        }
        var context = this;
        var args = arguments;
        var callNow = callFirst && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(function() {
          timeout = null;
          if (!callNow) {
            return fn.apply(context, args);
          }
        }, wait);
        if (callNow) {
          return fn.apply(this, arguments);
        }
      };
    }
  }
});

// node_modules/@isomorphic-git/lightning-fs/src/path.js
var require_path = __commonJS({
  "node_modules/@isomorphic-git/lightning-fs/src/path.js"(exports, module2) {
    init_esbuild_buffer_shim();
    function normalizePath5(path) {
      if (path.length === 0) {
        return ".";
      }
      let parts = splitPath(path);
      parts = parts.reduce(reducer, []);
      return joinPath(...parts);
    }
    function resolvePath(...paths) {
      let result = "";
      for (let path of paths) {
        if (path.startsWith("/")) {
          result = path;
        } else {
          result = normalizePath5(joinPath(result, path));
        }
      }
      return result;
    }
    function joinPath(...parts) {
      if (parts.length === 0) return "";
      let path = parts.join("/");
      path = path.replace(/\/{2,}/g, "/");
      return path;
    }
    function splitPath(path) {
      if (path.length === 0) return [];
      if (path === "/") return ["/"];
      let parts = path.split("/");
      if (parts[parts.length - 1] === "") {
        parts.pop();
      }
      if (path[0] === "/") {
        parts[0] = "/";
      } else {
        if (parts[0] !== ".") {
          parts.unshift(".");
        }
      }
      return parts;
    }
    function dirname(path) {
      const last = path.lastIndexOf("/");
      if (last === -1) throw new Error(`Cannot get dirname of "${path}"`);
      if (last === 0) return "/";
      return path.slice(0, last);
    }
    function basename(path) {
      if (path === "/") throw new Error(`Cannot get basename of "${path}"`);
      const last = path.lastIndexOf("/");
      if (last === -1) return path;
      return path.slice(last + 1);
    }
    function reducer(ancestors, current) {
      if (ancestors.length === 0) {
        ancestors.push(current);
        return ancestors;
      }
      if (current === ".") return ancestors;
      if (current === "..") {
        if (ancestors.length === 1) {
          if (ancestors[0] === "/") {
            throw new Error("Unable to normalize path - traverses above root directory");
          }
          if (ancestors[0] === ".") {
            ancestors.push(current);
            return ancestors;
          }
        }
        if (ancestors[ancestors.length - 1] === "..") {
          ancestors.push("..");
          return ancestors;
        } else {
          ancestors.pop();
          return ancestors;
        }
      }
      ancestors.push(current);
      return ancestors;
    }
    module2.exports = {
      join: joinPath,
      normalize: normalizePath5,
      split: splitPath,
      basename,
      dirname,
      resolve: resolvePath
    };
  }
});

// node_modules/@isomorphic-git/lightning-fs/src/errors.js
var require_errors = __commonJS({
  "node_modules/@isomorphic-git/lightning-fs/src/errors.js"(exports, module2) {
    init_esbuild_buffer_shim();
    function Err(name) {
      return class extends Error {
        constructor(...args) {
          super(...args);
          this.code = name;
          if (this.message) {
            this.message = name + ": " + this.message;
          } else {
            this.message = name;
          }
        }
      };
    }
    var EEXIST = Err("EEXIST");
    var ENOENT = Err("ENOENT");
    var ENOTDIR = Err("ENOTDIR");
    var ENOTEMPTY = Err("ENOTEMPTY");
    var ETIMEDOUT = Err("ETIMEDOUT");
    var EISDIR = Err("EISDIR");
    module2.exports = { EEXIST, ENOENT, ENOTDIR, ENOTEMPTY, ETIMEDOUT, EISDIR };
  }
});

// node_modules/@isomorphic-git/lightning-fs/src/CacheFS.js
var require_CacheFS = __commonJS({
  "node_modules/@isomorphic-git/lightning-fs/src/CacheFS.js"(exports, module2) {
    init_esbuild_buffer_shim();
    var path = require_path();
    var { EEXIST, ENOENT, ENOTDIR, ENOTEMPTY, EISDIR } = require_errors();
    var STAT = 0;
    module2.exports = class CacheFS {
      constructor() {
      }
      _makeRoot(root = /* @__PURE__ */ new Map()) {
        root.set(STAT, { mode: 511, type: "dir", size: 0, ino: 0, mtimeMs: Date.now() });
        return root;
      }
      activate(superblock = null) {
        if (superblock === null) {
          this._root = /* @__PURE__ */ new Map([["/", this._makeRoot()]]);
        } else if (typeof superblock === "string") {
          this._root = /* @__PURE__ */ new Map([["/", this._makeRoot(this.parse(superblock))]]);
        } else {
          this._root = superblock;
        }
      }
      get activated() {
        return !!this._root;
      }
      deactivate() {
        this._root = void 0;
      }
      size() {
        return this._countInodes(this._root.get("/")) - 1;
      }
      _countInodes(map) {
        let count = 1;
        for (let [key, val] of map) {
          if (key === STAT) continue;
          count += this._countInodes(val);
        }
        return count;
      }
      autoinc() {
        let val = this._maxInode(this._root.get("/")) + 1;
        return val;
      }
      _maxInode(map) {
        let max = map.get(STAT).ino;
        for (let [key, val] of map) {
          if (key === STAT) continue;
          max = Math.max(max, this._maxInode(val));
        }
        return max;
      }
      print(root = this._root.get("/")) {
        let str = "";
        const printTree = (root2, indent) => {
          for (let [file, node] of root2) {
            if (file === 0) continue;
            let stat = node.get(STAT);
            let mode = stat.mode.toString(8);
            str += `${"	".repeat(indent)}${file}	${mode}`;
            if (stat.type === "file") {
              str += `	${stat.size}	${stat.mtimeMs}
`;
            } else {
              str += `
`;
              printTree(node, indent + 1);
            }
          }
        };
        printTree(root, 0);
        return str;
      }
      parse(print) {
        let autoinc = 0;
        function mk(stat) {
          const ino = ++autoinc;
          const type = stat.length === 1 ? "dir" : "file";
          let [mode, size, mtimeMs] = stat;
          mode = parseInt(mode, 8);
          size = size ? parseInt(size) : 0;
          mtimeMs = mtimeMs ? parseInt(mtimeMs) : Date.now();
          return /* @__PURE__ */ new Map([[STAT, { mode, type, size, mtimeMs, ino }]]);
        }
        let lines = print.trim().split("\n");
        let _root = this._makeRoot();
        let stack = [
          { indent: -1, node: _root },
          { indent: 0, node: null }
        ];
        for (let line of lines) {
          let prefix = line.match(/^\t*/)[0];
          let indent = prefix.length;
          line = line.slice(indent);
          let [filename, ...stat] = line.split("	");
          let node = mk(stat);
          if (indent <= stack[stack.length - 1].indent) {
            while (indent <= stack[stack.length - 1].indent) {
              stack.pop();
            }
          }
          stack.push({ indent, node });
          let cd = stack[stack.length - 2].node;
          cd.set(filename, node);
        }
        return _root;
      }
      _lookup(filepath, follow = true) {
        let dir = this._root;
        let partialPath = "/";
        let parts = path.split(filepath);
        for (let i = 0; i < parts.length; ++i) {
          let part = parts[i];
          dir = dir.get(part);
          if (!dir) throw new ENOENT(filepath);
          if (follow || i < parts.length - 1) {
            const stat = dir.get(STAT);
            if (stat.type === "symlink") {
              let target = path.resolve(partialPath, stat.target);
              dir = this._lookup(target);
            }
            if (!partialPath) {
              partialPath = part;
            } else {
              partialPath = path.join(partialPath, part);
            }
          }
        }
        return dir;
      }
      mkdir(filepath, { mode }) {
        if (filepath === "/") throw new EEXIST();
        let dir = this._lookup(path.dirname(filepath));
        let basename = path.basename(filepath);
        if (dir.has(basename)) {
          throw new EEXIST();
        }
        let entry = /* @__PURE__ */ new Map();
        let stat = {
          mode,
          type: "dir",
          size: 0,
          mtimeMs: Date.now(),
          ino: this.autoinc()
        };
        entry.set(STAT, stat);
        dir.set(basename, entry);
      }
      rmdir(filepath) {
        let dir = this._lookup(filepath);
        if (dir.get(STAT).type !== "dir") throw new ENOTDIR();
        if (dir.size > 1) throw new ENOTEMPTY();
        let parent = this._lookup(path.dirname(filepath));
        let basename = path.basename(filepath);
        parent.delete(basename);
      }
      readdir(filepath) {
        let dir = this._lookup(filepath);
        if (dir.get(STAT).type !== "dir") throw new ENOTDIR();
        return [...dir.keys()].filter((key) => typeof key === "string");
      }
      writeStat(filepath, size, { mode }) {
        let ino;
        let oldStat;
        try {
          oldStat = this.stat(filepath);
        } catch (err) {
        }
        if (oldStat !== void 0) {
          if (oldStat.type === "dir") {
            throw new EISDIR();
          }
          if (mode == null) {
            mode = oldStat.mode;
          }
          ino = oldStat.ino;
        }
        if (mode == null) {
          mode = 438;
        }
        if (ino == null) {
          ino = this.autoinc();
        }
        let dir = this._lookup(path.dirname(filepath));
        let basename = path.basename(filepath);
        let stat = {
          mode,
          type: "file",
          size,
          mtimeMs: Date.now(),
          ino
        };
        let entry = /* @__PURE__ */ new Map();
        entry.set(STAT, stat);
        dir.set(basename, entry);
        return stat;
      }
      unlink(filepath) {
        let parent = this._lookup(path.dirname(filepath));
        let basename = path.basename(filepath);
        parent.delete(basename);
      }
      rename(oldFilepath, newFilepath) {
        let basename = path.basename(newFilepath);
        let entry = this._lookup(oldFilepath);
        let destDir = this._lookup(path.dirname(newFilepath));
        destDir.set(basename, entry);
        this.unlink(oldFilepath);
      }
      stat(filepath) {
        return this._lookup(filepath).get(STAT);
      }
      lstat(filepath) {
        return this._lookup(filepath, false).get(STAT);
      }
      readlink(filepath) {
        return this._lookup(filepath, false).get(STAT).target;
      }
      symlink(target, filepath) {
        let ino, mode;
        try {
          let oldStat = this.stat(filepath);
          if (mode === null) {
            mode = oldStat.mode;
          }
          ino = oldStat.ino;
        } catch (err) {
        }
        if (mode == null) {
          mode = 40960;
        }
        if (ino == null) {
          ino = this.autoinc();
        }
        let dir = this._lookup(path.dirname(filepath));
        let basename = path.basename(filepath);
        let stat = {
          mode,
          type: "symlink",
          target,
          size: 0,
          mtimeMs: Date.now(),
          ino
        };
        let entry = /* @__PURE__ */ new Map();
        entry.set(STAT, stat);
        dir.set(basename, entry);
        return stat;
      }
      _du(dir) {
        let size = 0;
        for (const [name, entry] of dir.entries()) {
          if (name === STAT) {
            size += entry.size;
          } else {
            size += this._du(entry);
          }
        }
        return size;
      }
      du(filepath) {
        let dir = this._lookup(filepath);
        return this._du(dir);
      }
    };
  }
});

// node_modules/@isomorphic-git/idb-keyval/dist/idb-keyval-cjs.js
var require_idb_keyval_cjs = __commonJS({
  "node_modules/@isomorphic-git/idb-keyval/dist/idb-keyval-cjs.js"(exports) {
    "use strict";
    init_esbuild_buffer_shim();
    Object.defineProperty(exports, "__esModule", { value: true });
    var Store = class {
      constructor(dbName = "keyval-store", storeName = "keyval") {
        this.storeName = storeName;
        this._dbName = dbName;
        this._storeName = storeName;
        this._init();
      }
      _init() {
        if (this._dbp) {
          return;
        }
        this._dbp = new Promise((resolve, reject) => {
          const openreq = indexedDB.open(this._dbName);
          openreq.onerror = () => reject(openreq.error);
          openreq.onsuccess = () => resolve(openreq.result);
          openreq.onupgradeneeded = () => {
            openreq.result.createObjectStore(this._storeName);
          };
        });
      }
      _withIDBStore(type, callback) {
        this._init();
        return this._dbp.then((db) => new Promise((resolve, reject) => {
          const transaction = db.transaction(this.storeName, type);
          transaction.oncomplete = () => resolve();
          transaction.onabort = transaction.onerror = () => reject(transaction.error);
          callback(transaction.objectStore(this.storeName));
        }));
      }
      _close() {
        this._init();
        return this._dbp.then((db) => {
          db.close();
          this._dbp = void 0;
        });
      }
    };
    var store;
    function getDefaultStore() {
      if (!store)
        store = new Store();
      return store;
    }
    function get(key, store2 = getDefaultStore()) {
      let req;
      return store2._withIDBStore("readwrite", (store3) => {
        req = store3.get(key);
      }).then(() => req.result);
    }
    function set(key, value, store2 = getDefaultStore()) {
      return store2._withIDBStore("readwrite", (store3) => {
        store3.put(value, key);
      });
    }
    function update2(key, updater, store2 = getDefaultStore()) {
      return store2._withIDBStore("readwrite", (store3) => {
        const req = store3.get(key);
        req.onsuccess = () => {
          store3.put(updater(req.result), key);
        };
      });
    }
    function del(key, store2 = getDefaultStore()) {
      return store2._withIDBStore("readwrite", (store3) => {
        store3.delete(key);
      });
    }
    function clear(store2 = getDefaultStore()) {
      return store2._withIDBStore("readwrite", (store3) => {
        store3.clear();
      });
    }
    function keys(store2 = getDefaultStore()) {
      const keys2 = [];
      return store2._withIDBStore("readwrite", (store3) => {
        (store3.openKeyCursor || store3.openCursor).call(store3).onsuccess = function() {
          if (!this.result)
            return;
          keys2.push(this.result.key);
          this.result.continue();
        };
      }).then(() => keys2);
    }
    function close(store2 = getDefaultStore()) {
      return store2._close();
    }
    exports.Store = Store;
    exports.get = get;
    exports.set = set;
    exports.update = update2;
    exports.del = del;
    exports.clear = clear;
    exports.keys = keys;
    exports.close = close;
  }
});

// node_modules/@isomorphic-git/lightning-fs/src/IdbBackend.js
var require_IdbBackend = __commonJS({
  "node_modules/@isomorphic-git/lightning-fs/src/IdbBackend.js"(exports, module2) {
    init_esbuild_buffer_shim();
    var idb = require_idb_keyval_cjs();
    module2.exports = class IdbBackend {
      constructor(dbname, storename) {
        this._database = dbname;
        this._storename = storename;
        this._store = new idb.Store(this._database, this._storename);
      }
      saveSuperblock(superblock) {
        return idb.set("!root", superblock, this._store);
      }
      loadSuperblock() {
        return idb.get("!root", this._store);
      }
      readFile(inode) {
        return idb.get(inode, this._store);
      }
      writeFile(inode, data) {
        return idb.set(inode, data, this._store);
      }
      unlink(inode) {
        return idb.del(inode, this._store);
      }
      wipe() {
        return idb.clear(this._store);
      }
      close() {
        return idb.close(this._store);
      }
    };
  }
});

// node_modules/@isomorphic-git/lightning-fs/src/HttpBackend.js
var require_HttpBackend = __commonJS({
  "node_modules/@isomorphic-git/lightning-fs/src/HttpBackend.js"(exports, module2) {
    init_esbuild_buffer_shim();
    module2.exports = class HttpBackend {
      constructor(url) {
        this._url = url;
      }
      loadSuperblock() {
        return fetch(this._url + "/.superblock.txt").then((res) => res.ok ? res.text() : null);
      }
      async readFile(filepath) {
        const res = await fetch(this._url + filepath);
        if (res.status === 200) {
          return res.arrayBuffer();
        } else {
          throw new Error("ENOENT");
        }
      }
      async sizeFile(filepath) {
        const res = await fetch(this._url + filepath, { method: "HEAD" });
        if (res.status === 200) {
          return res.headers.get("content-length");
        } else {
          throw new Error("ENOENT");
        }
      }
    };
  }
});

// node_modules/@isomorphic-git/lightning-fs/src/Mutex.js
var require_Mutex = __commonJS({
  "node_modules/@isomorphic-git/lightning-fs/src/Mutex.js"(exports, module2) {
    init_esbuild_buffer_shim();
    var idb = require_idb_keyval_cjs();
    var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
    module2.exports = class Mutex {
      constructor(dbname, storename) {
        this._id = Math.random();
        this._database = dbname;
        this._storename = storename;
        this._store = new idb.Store(this._database, this._storename);
        this._lock = null;
      }
      async has({ margin = 2e3 } = {}) {
        if (this._lock && this._lock.holder === this._id) {
          const now3 = Date.now();
          if (this._lock.expires > now3 + margin) {
            return true;
          } else {
            return await this.renew();
          }
        } else {
          return false;
        }
      }
      // Returns true if successful
      async renew({ ttl = 5e3 } = {}) {
        let success;
        await idb.update("lock", (current) => {
          const now3 = Date.now();
          const expires = now3 + ttl;
          success = current && current.holder === this._id;
          this._lock = success ? { holder: this._id, expires } : current;
          return this._lock;
        }, this._store);
        return success;
      }
      // Returns true if successful
      async acquire({ ttl = 5e3 } = {}) {
        let success;
        let expired;
        let doubleLock;
        await idb.update("lock", (current) => {
          const now3 = Date.now();
          const expires = now3 + ttl;
          expired = current && current.expires < now3;
          success = current === void 0 || expired;
          doubleLock = current && current.holder === this._id;
          this._lock = success ? { holder: this._id, expires } : current;
          return this._lock;
        }, this._store);
        if (doubleLock) {
          throw new Error("Mutex double-locked");
        }
        return success;
      }
      // check at 10Hz, give up after 10 minutes
      async wait({ interval = 100, limit = 6e3, ttl } = {}) {
        while (limit--) {
          if (await this.acquire({ ttl })) return true;
          await sleep(interval);
        }
        throw new Error("Mutex timeout");
      }
      // Returns true if successful
      async release({ force = false } = {}) {
        let success;
        let doubleFree;
        let someoneElseHasIt;
        await idb.update("lock", (current) => {
          success = force || current && current.holder === this._id;
          doubleFree = current === void 0;
          someoneElseHasIt = current && current.holder !== this._id;
          this._lock = success ? void 0 : current;
          return this._lock;
        }, this._store);
        await idb.close(this._store);
        if (!success && !force) {
          if (doubleFree) throw new Error("Mutex double-freed");
          if (someoneElseHasIt) throw new Error("Mutex lost ownership");
        }
        return success;
      }
    };
  }
});

// node_modules/@isomorphic-git/lightning-fs/src/Mutex2.js
var require_Mutex2 = __commonJS({
  "node_modules/@isomorphic-git/lightning-fs/src/Mutex2.js"(exports, module2) {
    init_esbuild_buffer_shim();
    module2.exports = class Mutex {
      constructor(name) {
        this._id = Math.random();
        this._database = name;
        this._has = false;
        this._release = null;
      }
      async has() {
        return this._has;
      }
      // Returns true if successful
      async acquire() {
        return new Promise((resolve) => {
          navigator.locks.request(this._database + "_lock", { ifAvailable: true }, (lock) => {
            this._has = !!lock;
            resolve(!!lock);
            return new Promise((resolve2) => {
              this._release = resolve2;
            });
          });
        });
      }
      // Returns true if successful, gives up after 10 minutes
      async wait({ timeout = 6e5 } = {}) {
        return new Promise((resolve, reject) => {
          const controller = new AbortController();
          setTimeout(() => {
            controller.abort();
            reject(new Error("Mutex timeout"));
          }, timeout);
          navigator.locks.request(this._database + "_lock", { signal: controller.signal }, (lock) => {
            this._has = !!lock;
            resolve(!!lock);
            return new Promise((resolve2) => {
              this._release = resolve2;
            });
          });
        });
      }
      // Returns true if successful
      async release({ force = false } = {}) {
        this._has = false;
        if (this._release) {
          this._release();
        } else if (force) {
          navigator.locks.request(this._database + "_lock", { steal: true }, (lock) => true);
        }
      }
    };
  }
});

// node_modules/@isomorphic-git/lightning-fs/src/DefaultBackend.js
var require_DefaultBackend = __commonJS({
  "node_modules/@isomorphic-git/lightning-fs/src/DefaultBackend.js"(exports, module2) {
    init_esbuild_buffer_shim();
    var { encode: encode2, decode: decode2 } = require_browser();
    var debounce2 = require_just_debounce_it();
    var CacheFS = require_CacheFS();
    var { ENOENT, ENOTEMPTY, ETIMEDOUT } = require_errors();
    var IdbBackend = require_IdbBackend();
    var HttpBackend = require_HttpBackend();
    var Mutex = require_Mutex();
    var Mutex2 = require_Mutex2();
    var path = require_path();
    module2.exports = class DefaultBackend {
      constructor() {
        this.saveSuperblock = debounce2(() => {
          this.flush();
        }, 500);
      }
      async init(name, {
        wipe,
        url,
        urlauto,
        fileDbName = name,
        db = null,
        fileStoreName = name + "_files",
        lockDbName = name + "_lock",
        lockStoreName = name + "_lock"
      } = {}) {
        this._name = name;
        this._idb = db || new IdbBackend(fileDbName, fileStoreName);
        this._mutex = navigator.locks ? new Mutex2(name) : new Mutex(lockDbName, lockStoreName);
        this._cache = new CacheFS(name);
        this._opts = { wipe, url };
        this._needsWipe = !!wipe;
        if (url) {
          this._http = new HttpBackend(url);
          this._urlauto = !!urlauto;
        }
      }
      async activate() {
        if (this._cache.activated) return;
        if (this._needsWipe) {
          this._needsWipe = false;
          await this._idb.wipe();
          await this._mutex.release({ force: true });
        }
        if (!await this._mutex.has()) await this._mutex.wait();
        const root = await this._idb.loadSuperblock();
        if (root) {
          this._cache.activate(root);
        } else if (this._http) {
          const text2 = await this._http.loadSuperblock();
          this._cache.activate(text2);
          await this._saveSuperblock();
        } else {
          this._cache.activate();
        }
        if (await this._mutex.has()) {
          return;
        } else {
          throw new ETIMEDOUT();
        }
      }
      async deactivate() {
        if (await this._mutex.has()) {
          await this._saveSuperblock();
        }
        this._cache.deactivate();
        try {
          await this._mutex.release();
        } catch (e) {
          console.log(e);
        }
        await this._idb.close();
      }
      async _saveSuperblock() {
        if (this._cache.activated) {
          this._lastSavedAt = Date.now();
          await this._idb.saveSuperblock(this._cache._root);
        }
      }
      _writeStat(filepath, size, opts) {
        let dirparts = path.split(path.dirname(filepath));
        let dir = dirparts.shift();
        for (let dirpart of dirparts) {
          dir = path.join(dir, dirpart);
          try {
            this._cache.mkdir(dir, { mode: 511 });
          } catch (e) {
          }
        }
        return this._cache.writeStat(filepath, size, opts);
      }
      async readFile(filepath, opts) {
        const encoding = typeof opts === "string" ? opts : opts && opts.encoding;
        if (encoding && encoding !== "utf8") throw new Error('Only "utf8" encoding is supported in readFile');
        let data = null, stat = null;
        try {
          stat = this._cache.stat(filepath);
          data = await this._idb.readFile(stat.ino);
        } catch (e) {
          if (!this._urlauto) throw e;
        }
        if (!data && this._http) {
          let lstat = this._cache.lstat(filepath);
          while (lstat.type === "symlink") {
            filepath = path.resolve(path.dirname(filepath), lstat.target);
            lstat = this._cache.lstat(filepath);
          }
          data = await this._http.readFile(filepath);
        }
        if (data) {
          if (!stat || stat.size != data.byteLength) {
            stat = await this._writeStat(filepath, data.byteLength, { mode: stat ? stat.mode : 438 });
            this.saveSuperblock();
          }
          if (encoding === "utf8") {
            data = decode2(data);
          } else {
            data.toString = () => decode2(data);
          }
        }
        if (!stat) throw new ENOENT(filepath);
        return data;
      }
      async writeFile(filepath, data, opts) {
        const { mode, encoding = "utf8" } = opts;
        if (typeof data === "string") {
          if (encoding !== "utf8") {
            throw new Error('Only "utf8" encoding is supported in writeFile');
          }
          data = encode2(data);
        }
        const stat = await this._cache.writeStat(filepath, data.byteLength, { mode });
        await this._idb.writeFile(stat.ino, data);
      }
      async unlink(filepath, opts) {
        const stat = this._cache.lstat(filepath);
        this._cache.unlink(filepath);
        if (stat.type !== "symlink") {
          await this._idb.unlink(stat.ino);
        }
      }
      readdir(filepath, opts) {
        return this._cache.readdir(filepath);
      }
      mkdir(filepath, opts) {
        const { mode = 511 } = opts;
        this._cache.mkdir(filepath, { mode });
      }
      rmdir(filepath, opts) {
        if (filepath === "/") {
          throw new ENOTEMPTY();
        }
        this._cache.rmdir(filepath);
      }
      rename(oldFilepath, newFilepath) {
        this._cache.rename(oldFilepath, newFilepath);
      }
      stat(filepath, opts) {
        return this._cache.stat(filepath);
      }
      lstat(filepath, opts) {
        return this._cache.lstat(filepath);
      }
      readlink(filepath, opts) {
        return this._cache.readlink(filepath);
      }
      symlink(target, filepath) {
        this._cache.symlink(target, filepath);
      }
      async backFile(filepath, opts) {
        let size = await this._http.sizeFile(filepath);
        await this._writeStat(filepath, size, opts);
      }
      du(filepath) {
        return this._cache.du(filepath);
      }
      flush() {
        return this._saveSuperblock();
      }
    };
  }
});

// node_modules/@isomorphic-git/lightning-fs/src/Stat.js
var require_Stat = __commonJS({
  "node_modules/@isomorphic-git/lightning-fs/src/Stat.js"(exports, module2) {
    init_esbuild_buffer_shim();
    module2.exports = class Stat {
      constructor(stats) {
        this.type = stats.type;
        this.mode = stats.mode;
        this.size = stats.size;
        this.ino = stats.ino;
        this.mtimeMs = stats.mtimeMs;
        this.ctimeMs = stats.ctimeMs || stats.mtimeMs;
        this.uid = 1;
        this.gid = 1;
        this.dev = 1;
      }
      isFile() {
        return this.type === "file";
      }
      isDirectory() {
        return this.type === "dir";
      }
      isSymbolicLink() {
        return this.type === "symlink";
      }
    };
  }
});

// node_modules/@isomorphic-git/lightning-fs/src/PromisifiedFS.js
var require_PromisifiedFS = __commonJS({
  "node_modules/@isomorphic-git/lightning-fs/src/PromisifiedFS.js"(exports, module2) {
    init_esbuild_buffer_shim();
    var DefaultBackend = require_DefaultBackend();
    var Stat = require_Stat();
    var path = require_path();
    function cleanParamsFilepathOpts(filepath, opts, ...rest) {
      filepath = path.normalize(filepath);
      if (typeof opts === "undefined" || typeof opts === "function") {
        opts = {};
      }
      if (typeof opts === "string") {
        opts = {
          encoding: opts
        };
      }
      return [filepath, opts, ...rest];
    }
    function cleanParamsFilepathDataOpts(filepath, data, opts, ...rest) {
      filepath = path.normalize(filepath);
      if (typeof opts === "undefined" || typeof opts === "function") {
        opts = {};
      }
      if (typeof opts === "string") {
        opts = {
          encoding: opts
        };
      }
      return [filepath, data, opts, ...rest];
    }
    function cleanParamsFilepathFilepath(oldFilepath, newFilepath, ...rest) {
      return [path.normalize(oldFilepath), path.normalize(newFilepath), ...rest];
    }
    module2.exports = class PromisifiedFS {
      constructor(name, options = {}) {
        this.init = this.init.bind(this);
        this.readFile = this._wrap(this.readFile, cleanParamsFilepathOpts, false);
        this.writeFile = this._wrap(this.writeFile, cleanParamsFilepathDataOpts, true);
        this.unlink = this._wrap(this.unlink, cleanParamsFilepathOpts, true);
        this.readdir = this._wrap(this.readdir, cleanParamsFilepathOpts, false);
        this.mkdir = this._wrap(this.mkdir, cleanParamsFilepathOpts, true);
        this.rmdir = this._wrap(this.rmdir, cleanParamsFilepathOpts, true);
        this.rename = this._wrap(this.rename, cleanParamsFilepathFilepath, true);
        this.stat = this._wrap(this.stat, cleanParamsFilepathOpts, false);
        this.lstat = this._wrap(this.lstat, cleanParamsFilepathOpts, false);
        this.readlink = this._wrap(this.readlink, cleanParamsFilepathOpts, false);
        this.symlink = this._wrap(this.symlink, cleanParamsFilepathFilepath, true);
        this.backFile = this._wrap(this.backFile, cleanParamsFilepathOpts, true);
        this.du = this._wrap(this.du, cleanParamsFilepathOpts, false);
        this._deactivationPromise = null;
        this._deactivationTimeout = null;
        this._activationPromise = null;
        this._operations = /* @__PURE__ */ new Set();
        if (name) {
          this.init(name, options);
        }
      }
      async init(...args) {
        if (this._initPromiseResolve) await this._initPromise;
        this._initPromise = this._init(...args);
        return this._initPromise;
      }
      async _init(name, options = {}) {
        await this._gracefulShutdown();
        if (this._activationPromise) await this._deactivate();
        if (this._backend && this._backend.destroy) {
          await this._backend.destroy();
        }
        this._backend = options.backend || new DefaultBackend();
        if (this._backend.init) {
          await this._backend.init(name, options);
        }
        if (this._initPromiseResolve) {
          this._initPromiseResolve();
          this._initPromiseResolve = null;
        }
        if (!options.defer) {
          this.stat("/");
        }
      }
      async _gracefulShutdown() {
        if (this._operations.size > 0) {
          this._isShuttingDown = true;
          await new Promise((resolve) => this._gracefulShutdownResolve = resolve);
          this._isShuttingDown = false;
          this._gracefulShutdownResolve = null;
        }
      }
      _wrap(fn, paramCleaner, mutating) {
        return async (...args) => {
          args = paramCleaner(...args);
          let op = {
            name: fn.name,
            args
          };
          this._operations.add(op);
          try {
            await this._activate();
            return await fn.apply(this, args);
          } finally {
            this._operations.delete(op);
            if (mutating) this._backend.saveSuperblock();
            if (this._operations.size === 0) {
              if (!this._deactivationTimeout) clearTimeout(this._deactivationTimeout);
              this._deactivationTimeout = setTimeout(this._deactivate.bind(this), 500);
            }
          }
        };
      }
      async _activate() {
        if (!this._initPromise) console.warn(new Error(`Attempted to use LightningFS ${this._name} before it was initialized.`));
        await this._initPromise;
        if (this._deactivationTimeout) {
          clearTimeout(this._deactivationTimeout);
          this._deactivationTimeout = null;
        }
        if (this._deactivationPromise) await this._deactivationPromise;
        this._deactivationPromise = null;
        if (!this._activationPromise) {
          this._activationPromise = this._backend.activate ? this._backend.activate() : Promise.resolve();
        }
        await this._activationPromise;
      }
      async _deactivate() {
        if (this._activationPromise) await this._activationPromise;
        if (!this._deactivationPromise) {
          this._deactivationPromise = this._backend.deactivate ? this._backend.deactivate() : Promise.resolve();
        }
        this._activationPromise = null;
        if (this._gracefulShutdownResolve) this._gracefulShutdownResolve();
        return this._deactivationPromise;
      }
      async readFile(filepath, opts) {
        return this._backend.readFile(filepath, opts);
      }
      async writeFile(filepath, data, opts) {
        await this._backend.writeFile(filepath, data, opts);
        return null;
      }
      async unlink(filepath, opts) {
        await this._backend.unlink(filepath, opts);
        return null;
      }
      async readdir(filepath, opts) {
        return this._backend.readdir(filepath, opts);
      }
      async mkdir(filepath, opts) {
        await this._backend.mkdir(filepath, opts);
        return null;
      }
      async rmdir(filepath, opts) {
        await this._backend.rmdir(filepath, opts);
        return null;
      }
      async rename(oldFilepath, newFilepath) {
        await this._backend.rename(oldFilepath, newFilepath);
        return null;
      }
      async stat(filepath, opts) {
        const data = await this._backend.stat(filepath, opts);
        return new Stat(data);
      }
      async lstat(filepath, opts) {
        const data = await this._backend.lstat(filepath, opts);
        return new Stat(data);
      }
      async readlink(filepath, opts) {
        return this._backend.readlink(filepath, opts);
      }
      async symlink(target, filepath) {
        await this._backend.symlink(target, filepath);
        return null;
      }
      async backFile(filepath, opts) {
        await this._backend.backFile(filepath, opts);
        return null;
      }
      async du(filepath) {
        return this._backend.du(filepath);
      }
      async flush() {
        return this._backend.flush();
      }
    };
  }
});

// node_modules/@isomorphic-git/lightning-fs/src/index.js
var require_src = __commonJS({
  "node_modules/@isomorphic-git/lightning-fs/src/index.js"(exports, module2) {
    init_esbuild_buffer_shim();
    var once = require_just_once();
    var PromisifiedFS = require_PromisifiedFS();
    function wrapCallback(opts, cb) {
      if (typeof opts === "function") {
        cb = opts;
      }
      cb = once(cb);
      const resolve = (...args) => cb(null, ...args);
      return [resolve, cb];
    }
    module2.exports = class FS {
      constructor(...args) {
        this.promises = new PromisifiedFS(...args);
        this.init = this.init.bind(this);
        this.readFile = this.readFile.bind(this);
        this.writeFile = this.writeFile.bind(this);
        this.unlink = this.unlink.bind(this);
        this.readdir = this.readdir.bind(this);
        this.mkdir = this.mkdir.bind(this);
        this.rmdir = this.rmdir.bind(this);
        this.rename = this.rename.bind(this);
        this.stat = this.stat.bind(this);
        this.lstat = this.lstat.bind(this);
        this.readlink = this.readlink.bind(this);
        this.symlink = this.symlink.bind(this);
        this.backFile = this.backFile.bind(this);
        this.du = this.du.bind(this);
        this.flush = this.flush.bind(this);
      }
      init(name, options) {
        return this.promises.init(name, options);
      }
      readFile(filepath, opts, cb) {
        const [resolve, reject] = wrapCallback(opts, cb);
        this.promises.readFile(filepath, opts).then(resolve).catch(reject);
      }
      writeFile(filepath, data, opts, cb) {
        const [resolve, reject] = wrapCallback(opts, cb);
        this.promises.writeFile(filepath, data, opts).then(resolve).catch(reject);
      }
      unlink(filepath, opts, cb) {
        const [resolve, reject] = wrapCallback(opts, cb);
        this.promises.unlink(filepath, opts).then(resolve).catch(reject);
      }
      readdir(filepath, opts, cb) {
        const [resolve, reject] = wrapCallback(opts, cb);
        this.promises.readdir(filepath, opts).then(resolve).catch(reject);
      }
      mkdir(filepath, opts, cb) {
        const [resolve, reject] = wrapCallback(opts, cb);
        this.promises.mkdir(filepath, opts).then(resolve).catch(reject);
      }
      rmdir(filepath, opts, cb) {
        const [resolve, reject] = wrapCallback(opts, cb);
        this.promises.rmdir(filepath, opts).then(resolve).catch(reject);
      }
      rename(oldFilepath, newFilepath, cb) {
        const [resolve, reject] = wrapCallback(cb);
        this.promises.rename(oldFilepath, newFilepath).then(resolve).catch(reject);
      }
      stat(filepath, opts, cb) {
        const [resolve, reject] = wrapCallback(opts, cb);
        this.promises.stat(filepath).then(resolve).catch(reject);
      }
      lstat(filepath, opts, cb) {
        const [resolve, reject] = wrapCallback(opts, cb);
        this.promises.lstat(filepath).then(resolve).catch(reject);
      }
      readlink(filepath, opts, cb) {
        const [resolve, reject] = wrapCallback(opts, cb);
        this.promises.readlink(filepath).then(resolve).catch(reject);
      }
      symlink(target, filepath, cb) {
        const [resolve, reject] = wrapCallback(cb);
        this.promises.symlink(target, filepath).then(resolve).catch(reject);
      }
      backFile(filepath, opts, cb) {
        const [resolve, reject] = wrapCallback(opts, cb);
        this.promises.backFile(filepath, opts).then(resolve).catch(reject);
      }
      du(filepath, cb) {
        const [resolve, reject] = wrapCallback(cb);
        this.promises.du(filepath).then(resolve).catch(reject);
      }
      flush(cb) {
        const [resolve, reject] = wrapCallback(cb);
        this.promises.flush().then(resolve).catch(reject);
      }
    };
  }
});

// node_modules/localforage/dist/localforage.js
var require_localforage = __commonJS({
  "node_modules/localforage/dist/localforage.js"(exports, module2) {
    init_esbuild_buffer_shim();
    (function(f) {
      if (typeof exports === "object" && typeof module2 !== "undefined") {
        module2.exports = f();
      } else if (typeof define === "function" && define.amd) {
        define([], f);
      } else {
        var g;
        if (typeof window !== "undefined") {
          g = window;
        } else if (typeof globalThis !== "undefined") {
          g = globalThis;
        } else if (typeof self !== "undefined") {
          g = self;
        } else {
          g = this;
        }
        g.localforage = f();
      }
    })(function() {
      var define2, module3, exports2;
      return function e(t, n2, r) {
        function s2(o2, u) {
          if (!n2[o2]) {
            if (!t[o2]) {
              var a = typeof require == "function" && require;
              if (!u && a) return a(o2, true);
              if (i) return i(o2, true);
              var f = new Error("Cannot find module '" + o2 + "'");
              throw f.code = "MODULE_NOT_FOUND", f;
            }
            var l2 = n2[o2] = { exports: {} };
            t[o2][0].call(l2.exports, function(e2) {
              var n3 = t[o2][1][e2];
              return s2(n3 ? n3 : e2);
            }, l2, l2.exports, e, t, n2, r);
          }
          return n2[o2].exports;
        }
        var i = typeof require == "function" && require;
        for (var o = 0; o < r.length; o++) s2(r[o]);
        return s2;
      }({ 1: [function(_dereq_, module4, exports3) {
        (function(global2) {
          "use strict";
          var Mutation = global2.MutationObserver || global2.WebKitMutationObserver;
          var scheduleDrain;
          {
            if (Mutation) {
              var called = 0;
              var observer = new Mutation(nextTick);
              var element2 = global2.document.createTextNode("");
              observer.observe(element2, {
                characterData: true
              });
              scheduleDrain = function() {
                element2.data = called = ++called % 2;
              };
            } else if (!global2.setImmediate && typeof global2.MessageChannel !== "undefined") {
              var channel = new global2.MessageChannel();
              channel.port1.onmessage = nextTick;
              scheduleDrain = function() {
                channel.port2.postMessage(0);
              };
            } else if ("document" in global2 && "onreadystatechange" in global2.document.createElement("script")) {
              scheduleDrain = function() {
                var scriptEl = global2.document.createElement("script");
                scriptEl.onreadystatechange = function() {
                  nextTick();
                  scriptEl.onreadystatechange = null;
                  scriptEl.parentNode.removeChild(scriptEl);
                  scriptEl = null;
                };
                global2.document.documentElement.appendChild(scriptEl);
              };
            } else {
              scheduleDrain = function() {
                setTimeout(nextTick, 0);
              };
            }
          }
          var draining;
          var queue = [];
          function nextTick() {
            draining = true;
            var i, oldQueue;
            var len = queue.length;
            while (len) {
              oldQueue = queue;
              queue = [];
              i = -1;
              while (++i < len) {
                oldQueue[i]();
              }
              len = queue.length;
            }
            draining = false;
          }
          module4.exports = immediate;
          function immediate(task) {
            if (queue.push(task) === 1 && !draining) {
              scheduleDrain();
            }
          }
        }).call(this, typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {});
      }, {}], 2: [function(_dereq_, module4, exports3) {
        "use strict";
        var immediate = _dereq_(1);
        function INTERNAL() {
        }
        var handlers = {};
        var REJECTED = ["REJECTED"];
        var FULFILLED = ["FULFILLED"];
        var PENDING = ["PENDING"];
        module4.exports = Promise2;
        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);
          }
        }
        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;
            unwrap2(promise, resolver, this.outcome);
          } else {
            this.queue.push(new QueueItem(promise, onFulfilled, onRejected));
          }
          return promise;
        };
        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;
          }
        }
        QueueItem.prototype.callFulfilled = function(value) {
          handlers.resolve(this.promise, value);
        };
        QueueItem.prototype.otherCallFulfilled = function(value) {
          unwrap2(this.promise, this.onFulfilled, value);
        };
        QueueItem.prototype.callRejected = function(value) {
          handlers.reject(this.promise, value);
        };
        QueueItem.prototype.otherCallRejected = function(value) {
          unwrap2(this.promise, this.onRejected, value);
        };
        function unwrap2(promise, func, value) {
          immediate(function() {
            var returnValue;
            try {
              returnValue = func(value);
            } catch (e) {
              return handlers.reject(promise, e);
            }
            if (returnValue === promise) {
              handlers.reject(promise, new TypeError("Cannot resolve promise with itself"));
            } else {
              handlers.resolve(promise, returnValue);
            }
          });
        }
        handlers.resolve = function(self2, value) {
          var result = tryCatch(getThen, value);
          if (result.status === "error") {
            return handlers.reject(self2, result.value);
          }
          var thenable = result.value;
          if (thenable) {
            safelyResolveThenable(self2, thenable);
          } else {
            self2.state = FULFILLED;
            self2.outcome = value;
            var i = -1;
            var len = self2.queue.length;
            while (++i < len) {
              self2.queue[i].callFulfilled(value);
            }
          }
          return self2;
        };
        handlers.reject = function(self2, error) {
          self2.state = REJECTED;
          self2.outcome = error;
          var i = -1;
          var len = self2.queue.length;
          while (++i < len) {
            self2.queue[i].callRejected(error);
          }
          return self2;
        };
        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 result = tryCatch(tryToUnwrap);
          if (result.status === "error") {
            onError(result.value);
          }
        }
        function tryCatch(func, value) {
          var out = {};
          try {
            out.value = func(value);
            out.status = "success";
          } catch (e) {
            out.status = "error";
            out.value = e;
          }
          return out;
        }
        Promise2.resolve = resolve;
        function resolve(value) {
          if (value instanceof this) {
            return value;
          }
          return handlers.resolve(new this(INTERNAL), value);
        }
        Promise2.reject = reject;
        function reject(reason) {
          var promise = new this(INTERNAL);
          return handlers.reject(promise, reason);
        }
        Promise2.all = all;
        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 i = -1;
          var promise = new this(INTERNAL);
          while (++i < len) {
            allResolver(iterable[i], i);
          }
          return promise;
          function allResolver(value, i2) {
            self2.resolve(value).then(resolveFromAll, function(error) {
              if (!called) {
                called = true;
                handlers.reject(promise, error);
              }
            });
            function resolveFromAll(outValue) {
              values[i2] = outValue;
              if (++resolved === len && !called) {
                called = true;
                handlers.resolve(promise, values);
              }
            }
          }
        }
        Promise2.race = race;
        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 i = -1;
          var promise = new this(INTERNAL);
          while (++i < len) {
            resolver(iterable[i]);
          }
          return promise;
          function resolver(value) {
            self2.resolve(value).then(function(response) {
              if (!called) {
                called = true;
                handlers.resolve(promise, response);
              }
            }, function(error) {
              if (!called) {
                called = true;
                handlers.reject(promise, error);
              }
            });
          }
        }
      }, { "1": 1 }], 3: [function(_dereq_, module4, exports3) {
        (function(global2) {
          "use strict";
          if (typeof global2.Promise !== "function") {
            global2.Promise = _dereq_(2);
          }
        }).call(this, typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {});
      }, { "2": 2 }], 4: [function(_dereq_, module4, exports3) {
        "use strict";
        var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function(obj) {
          return typeof obj;
        } : function(obj) {
          return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
        };
        function _classCallCheck(instance6, Constructor) {
          if (!(instance6 instanceof Constructor)) {
            throw new TypeError("Cannot call a class as a function");
          }
        }
        function getIDB() {
          try {
            if (typeof indexedDB !== "undefined") {
              return indexedDB;
            }
            if (typeof webkitIndexedDB !== "undefined") {
              return webkitIndexedDB;
            }
            if (typeof mozIndexedDB !== "undefined") {
              return mozIndexedDB;
            }
            if (typeof OIndexedDB !== "undefined") {
              return OIndexedDB;
            }
            if (typeof msIndexedDB !== "undefined") {
              return msIndexedDB;
            }
          } catch (e) {
            return;
          }
        }
        var idb = getIDB();
        function isIndexedDBValid() {
          try {
            if (!idb || !idb.open) {
              return false;
            }
            var isSafari = typeof openDatabase !== "undefined" && /(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent) && !/BlackBerry/.test(navigator.platform);
            var hasFetch = typeof fetch === "function" && fetch.toString().indexOf("[native code") !== -1;
            return (!isSafari || hasFetch) && typeof indexedDB !== "undefined" && // some outdated implementations of IDB that appear on Samsung
            // and HTC Android devices <4.4 are missing IDBKeyRange
            // See: https://github.com/mozilla/localForage/issues/128
            // See: https://github.com/mozilla/localForage/issues/272
            typeof IDBKeyRange !== "undefined";
          } catch (e) {
            return false;
          }
        }
        function createBlob(parts, properties) {
          parts = parts || [];
          properties = properties || {};
          try {
            return new Blob(parts, properties);
          } catch (e) {
            if (e.name !== "TypeError") {
              throw e;
            }
            var Builder = typeof BlobBuilder !== "undefined" ? BlobBuilder : typeof MSBlobBuilder !== "undefined" ? MSBlobBuilder : typeof MozBlobBuilder !== "undefined" ? MozBlobBuilder : WebKitBlobBuilder;
            var builder = new Builder();
            for (var i = 0; i < parts.length; i += 1) {
              builder.append(parts[i]);
            }
            return builder.getBlob(properties.type);
          }
        }
        if (typeof Promise === "undefined") {
          _dereq_(3);
        }
        var Promise$1 = Promise;
        function executeCallback(promise, callback) {
          if (callback) {
            promise.then(function(result) {
              callback(null, result);
            }, function(error) {
              callback(error);
            });
          }
        }
        function executeTwoCallbacks(promise, callback, errorCallback) {
          if (typeof callback === "function") {
            promise.then(callback);
          }
          if (typeof errorCallback === "function") {
            promise["catch"](errorCallback);
          }
        }
        function normalizeKey(key2) {
          if (typeof key2 !== "string") {
            console.warn(key2 + " used as a key, but it is not a string.");
            key2 = String(key2);
          }
          return key2;
        }
        function getCallback() {
          if (arguments.length && typeof arguments[arguments.length - 1] === "function") {
            return arguments[arguments.length - 1];
          }
        }
        var DETECT_BLOB_SUPPORT_STORE = "local-forage-detect-blob-support";
        var supportsBlobs = void 0;
        var dbContexts = {};
        var toString3 = Object.prototype.toString;
        var READ_ONLY = "readonly";
        var READ_WRITE = "readwrite";
        function _binStringToArrayBuffer(bin) {
          var length2 = bin.length;
          var buf = new ArrayBuffer(length2);
          var arr = new Uint8Array(buf);
          for (var i = 0; i < length2; i++) {
            arr[i] = bin.charCodeAt(i);
          }
          return buf;
        }
        function _checkBlobSupportWithoutCaching(idb2) {
          return new Promise$1(function(resolve) {
            var txn = idb2.transaction(DETECT_BLOB_SUPPORT_STORE, READ_WRITE);
            var blob = createBlob([""]);
            txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, "key");
            txn.onabort = function(e) {
              e.preventDefault();
              e.stopPropagation();
              resolve(false);
            };
            txn.oncomplete = function() {
              var matchedChrome = navigator.userAgent.match(/Chrome\/(\d+)/);
              var matchedEdge = navigator.userAgent.match(/Edge\//);
              resolve(matchedEdge || !matchedChrome || parseInt(matchedChrome[1], 10) >= 43);
            };
          })["catch"](function() {
            return false;
          });
        }
        function _checkBlobSupport(idb2) {
          if (typeof supportsBlobs === "boolean") {
            return Promise$1.resolve(supportsBlobs);
          }
          return _checkBlobSupportWithoutCaching(idb2).then(function(value) {
            supportsBlobs = value;
            return supportsBlobs;
          });
        }
        function _deferReadiness(dbInfo) {
          var dbContext = dbContexts[dbInfo.name];
          var deferredOperation = {};
          deferredOperation.promise = new Promise$1(function(resolve, reject) {
            deferredOperation.resolve = resolve;
            deferredOperation.reject = reject;
          });
          dbContext.deferredOperations.push(deferredOperation);
          if (!dbContext.dbReady) {
            dbContext.dbReady = deferredOperation.promise;
          } else {
            dbContext.dbReady = dbContext.dbReady.then(function() {
              return deferredOperation.promise;
            });
          }
        }
        function _advanceReadiness(dbInfo) {
          var dbContext = dbContexts[dbInfo.name];
          var deferredOperation = dbContext.deferredOperations.pop();
          if (deferredOperation) {
            deferredOperation.resolve();
            return deferredOperation.promise;
          }
        }
        function _rejectReadiness(dbInfo, err) {
          var dbContext = dbContexts[dbInfo.name];
          var deferredOperation = dbContext.deferredOperations.pop();
          if (deferredOperation) {
            deferredOperation.reject(err);
            return deferredOperation.promise;
          }
        }
        function _getConnection(dbInfo, upgradeNeeded) {
          return new Promise$1(function(resolve, reject) {
            dbContexts[dbInfo.name] = dbContexts[dbInfo.name] || createDbContext();
            if (dbInfo.db) {
              if (upgradeNeeded) {
                _deferReadiness(dbInfo);
                dbInfo.db.close();
              } else {
                return resolve(dbInfo.db);
              }
            }
            var dbArgs = [dbInfo.name];
            if (upgradeNeeded) {
              dbArgs.push(dbInfo.version);
            }
            var openreq = idb.open.apply(idb, dbArgs);
            if (upgradeNeeded) {
              openreq.onupgradeneeded = function(e) {
                var db = openreq.result;
                try {
                  db.createObjectStore(dbInfo.storeName);
                  if (e.oldVersion <= 1) {
                    db.createObjectStore(DETECT_BLOB_SUPPORT_STORE);
                  }
                } catch (ex) {
                  if (ex.name === "ConstraintError") {
                    console.warn('The database "' + dbInfo.name + '" has been upgraded from version ' + e.oldVersion + " to version " + e.newVersion + ', but the storage "' + dbInfo.storeName + '" already exists.');
                  } else {
                    throw ex;
                  }
                }
              };
            }
            openreq.onerror = function(e) {
              e.preventDefault();
              reject(openreq.error);
            };
            openreq.onsuccess = function() {
              var db = openreq.result;
              db.onversionchange = function(e) {
                e.target.close();
              };
              resolve(db);
              _advanceReadiness(dbInfo);
            };
          });
        }
        function _getOriginalConnection(dbInfo) {
          return _getConnection(dbInfo, false);
        }
        function _getUpgradedConnection(dbInfo) {
          return _getConnection(dbInfo, true);
        }
        function _isUpgradeNeeded(dbInfo, defaultVersion) {
          if (!dbInfo.db) {
            return true;
          }
          var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName);
          var isDowngrade = dbInfo.version < dbInfo.db.version;
          var isUpgrade = dbInfo.version > dbInfo.db.version;
          if (isDowngrade) {
            if (dbInfo.version !== defaultVersion) {
              console.warn('The database "' + dbInfo.name + `" can't be downgraded from version ` + dbInfo.db.version + " to version " + dbInfo.version + ".");
            }
            dbInfo.version = dbInfo.db.version;
          }
          if (isUpgrade || isNewStore) {
            if (isNewStore) {
              var incVersion = dbInfo.db.version + 1;
              if (incVersion > dbInfo.version) {
                dbInfo.version = incVersion;
              }
            }
            return true;
          }
          return false;
        }
        function _encodeBlob(blob) {
          return new Promise$1(function(resolve, reject) {
            var reader = new FileReader();
            reader.onerror = reject;
            reader.onloadend = function(e) {
              var base64 = btoa(e.target.result || "");
              resolve({
                __local_forage_encoded_blob: true,
                data: base64,
                type: blob.type
              });
            };
            reader.readAsBinaryString(blob);
          });
        }
        function _decodeBlob(encodedBlob) {
          var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data));
          return createBlob([arrayBuff], { type: encodedBlob.type });
        }
        function _isEncodedBlob(value) {
          return value && value.__local_forage_encoded_blob;
        }
        function _fullyReady(callback) {
          var self2 = this;
          var promise = self2._initReady().then(function() {
            var dbContext = dbContexts[self2._dbInfo.name];
            if (dbContext && dbContext.dbReady) {
              return dbContext.dbReady;
            }
          });
          executeTwoCallbacks(promise, callback, callback);
          return promise;
        }
        function _tryReconnect(dbInfo) {
          _deferReadiness(dbInfo);
          var dbContext = dbContexts[dbInfo.name];
          var forages = dbContext.forages;
          for (var i = 0; i < forages.length; i++) {
            var forage = forages[i];
            if (forage._dbInfo.db) {
              forage._dbInfo.db.close();
              forage._dbInfo.db = null;
            }
          }
          dbInfo.db = null;
          return _getOriginalConnection(dbInfo).then(function(db) {
            dbInfo.db = db;
            if (_isUpgradeNeeded(dbInfo)) {
              return _getUpgradedConnection(dbInfo);
            }
            return db;
          }).then(function(db) {
            dbInfo.db = dbContext.db = db;
            for (var i2 = 0; i2 < forages.length; i2++) {
              forages[i2]._dbInfo.db = db;
            }
          })["catch"](function(err) {
            _rejectReadiness(dbInfo, err);
            throw err;
          });
        }
        function createTransaction(dbInfo, mode, callback, retries) {
          if (retries === void 0) {
            retries = 1;
          }
          try {
            var tx = dbInfo.db.transaction(dbInfo.storeName, mode);
            callback(null, tx);
          } catch (err) {
            if (retries > 0 && (!dbInfo.db || err.name === "InvalidStateError" || err.name === "NotFoundError")) {
              return Promise$1.resolve().then(function() {
                if (!dbInfo.db || err.name === "NotFoundError" && !dbInfo.db.objectStoreNames.contains(dbInfo.storeName) && dbInfo.version <= dbInfo.db.version) {
                  if (dbInfo.db) {
                    dbInfo.version = dbInfo.db.version + 1;
                  }
                  return _getUpgradedConnection(dbInfo);
                }
              }).then(function() {
                return _tryReconnect(dbInfo).then(function() {
                  createTransaction(dbInfo, mode, callback, retries - 1);
                });
              })["catch"](callback);
            }
            callback(err);
          }
        }
        function createDbContext() {
          return {
            // Running localForages sharing a database.
            forages: [],
            // Shared database.
            db: null,
            // Database readiness (promise).
            dbReady: null,
            // Deferred operations on the database.
            deferredOperations: []
          };
        }
        function _initStorage(options) {
          var self2 = this;
          var dbInfo = {
            db: null
          };
          if (options) {
            for (var i in options) {
              dbInfo[i] = options[i];
            }
          }
          var dbContext = dbContexts[dbInfo.name];
          if (!dbContext) {
            dbContext = createDbContext();
            dbContexts[dbInfo.name] = dbContext;
          }
          dbContext.forages.push(self2);
          if (!self2._initReady) {
            self2._initReady = self2.ready;
            self2.ready = _fullyReady;
          }
          var initPromises = [];
          function ignoreErrors() {
            return Promise$1.resolve();
          }
          for (var j = 0; j < dbContext.forages.length; j++) {
            var forage = dbContext.forages[j];
            if (forage !== self2) {
              initPromises.push(forage._initReady()["catch"](ignoreErrors));
            }
          }
          var forages = dbContext.forages.slice(0);
          return Promise$1.all(initPromises).then(function() {
            dbInfo.db = dbContext.db;
            return _getOriginalConnection(dbInfo);
          }).then(function(db) {
            dbInfo.db = db;
            if (_isUpgradeNeeded(dbInfo, self2._defaultConfig.version)) {
              return _getUpgradedConnection(dbInfo);
            }
            return db;
          }).then(function(db) {
            dbInfo.db = dbContext.db = db;
            self2._dbInfo = dbInfo;
            for (var k = 0; k < forages.length; k++) {
              var forage2 = forages[k];
              if (forage2 !== self2) {
                forage2._dbInfo.db = dbInfo.db;
                forage2._dbInfo.version = dbInfo.version;
              }
            }
          });
        }
        function getItem(key2, callback) {
          var self2 = this;
          key2 = normalizeKey(key2);
          var promise = new Promise$1(function(resolve, reject) {
            self2.ready().then(function() {
              createTransaction(self2._dbInfo, READ_ONLY, function(err, transaction) {
                if (err) {
                  return reject(err);
                }
                try {
                  var store = transaction.objectStore(self2._dbInfo.storeName);
                  var req = store.get(key2);
                  req.onsuccess = function() {
                    var value = req.result;
                    if (value === void 0) {
                      value = null;
                    }
                    if (_isEncodedBlob(value)) {
                      value = _decodeBlob(value);
                    }
                    resolve(value);
                  };
                  req.onerror = function() {
                    reject(req.error);
                  };
                } catch (e) {
                  reject(e);
                }
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function iterate(iterator, callback) {
          var self2 = this;
          var promise = new Promise$1(function(resolve, reject) {
            self2.ready().then(function() {
              createTransaction(self2._dbInfo, READ_ONLY, function(err, transaction) {
                if (err) {
                  return reject(err);
                }
                try {
                  var store = transaction.objectStore(self2._dbInfo.storeName);
                  var req = store.openCursor();
                  var iterationNumber = 1;
                  req.onsuccess = function() {
                    var cursor = req.result;
                    if (cursor) {
                      var value = cursor.value;
                      if (_isEncodedBlob(value)) {
                        value = _decodeBlob(value);
                      }
                      var result = iterator(value, cursor.key, iterationNumber++);
                      if (result !== void 0) {
                        resolve(result);
                      } else {
                        cursor["continue"]();
                      }
                    } else {
                      resolve();
                    }
                  };
                  req.onerror = function() {
                    reject(req.error);
                  };
                } catch (e) {
                  reject(e);
                }
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function setItem(key2, value, callback) {
          var self2 = this;
          key2 = normalizeKey(key2);
          var promise = new Promise$1(function(resolve, reject) {
            var dbInfo;
            self2.ready().then(function() {
              dbInfo = self2._dbInfo;
              if (toString3.call(value) === "[object Blob]") {
                return _checkBlobSupport(dbInfo.db).then(function(blobSupport) {
                  if (blobSupport) {
                    return value;
                  }
                  return _encodeBlob(value);
                });
              }
              return value;
            }).then(function(value2) {
              createTransaction(self2._dbInfo, READ_WRITE, function(err, transaction) {
                if (err) {
                  return reject(err);
                }
                try {
                  var store = transaction.objectStore(self2._dbInfo.storeName);
                  if (value2 === null) {
                    value2 = void 0;
                  }
                  var req = store.put(value2, key2);
                  transaction.oncomplete = function() {
                    if (value2 === void 0) {
                      value2 = null;
                    }
                    resolve(value2);
                  };
                  transaction.onabort = transaction.onerror = function() {
                    var err2 = req.error ? req.error : req.transaction.error;
                    reject(err2);
                  };
                } catch (e) {
                  reject(e);
                }
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function removeItem(key2, callback) {
          var self2 = this;
          key2 = normalizeKey(key2);
          var promise = new Promise$1(function(resolve, reject) {
            self2.ready().then(function() {
              createTransaction(self2._dbInfo, READ_WRITE, function(err, transaction) {
                if (err) {
                  return reject(err);
                }
                try {
                  var store = transaction.objectStore(self2._dbInfo.storeName);
                  var req = store["delete"](key2);
                  transaction.oncomplete = function() {
                    resolve();
                  };
                  transaction.onerror = function() {
                    reject(req.error);
                  };
                  transaction.onabort = function() {
                    var err2 = req.error ? req.error : req.transaction.error;
                    reject(err2);
                  };
                } catch (e) {
                  reject(e);
                }
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function clear(callback) {
          var self2 = this;
          var promise = new Promise$1(function(resolve, reject) {
            self2.ready().then(function() {
              createTransaction(self2._dbInfo, READ_WRITE, function(err, transaction) {
                if (err) {
                  return reject(err);
                }
                try {
                  var store = transaction.objectStore(self2._dbInfo.storeName);
                  var req = store.clear();
                  transaction.oncomplete = function() {
                    resolve();
                  };
                  transaction.onabort = transaction.onerror = function() {
                    var err2 = req.error ? req.error : req.transaction.error;
                    reject(err2);
                  };
                } catch (e) {
                  reject(e);
                }
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function length(callback) {
          var self2 = this;
          var promise = new Promise$1(function(resolve, reject) {
            self2.ready().then(function() {
              createTransaction(self2._dbInfo, READ_ONLY, function(err, transaction) {
                if (err) {
                  return reject(err);
                }
                try {
                  var store = transaction.objectStore(self2._dbInfo.storeName);
                  var req = store.count();
                  req.onsuccess = function() {
                    resolve(req.result);
                  };
                  req.onerror = function() {
                    reject(req.error);
                  };
                } catch (e) {
                  reject(e);
                }
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function key(n2, callback) {
          var self2 = this;
          var promise = new Promise$1(function(resolve, reject) {
            if (n2 < 0) {
              resolve(null);
              return;
            }
            self2.ready().then(function() {
              createTransaction(self2._dbInfo, READ_ONLY, function(err, transaction) {
                if (err) {
                  return reject(err);
                }
                try {
                  var store = transaction.objectStore(self2._dbInfo.storeName);
                  var advanced = false;
                  var req = store.openKeyCursor();
                  req.onsuccess = function() {
                    var cursor = req.result;
                    if (!cursor) {
                      resolve(null);
                      return;
                    }
                    if (n2 === 0) {
                      resolve(cursor.key);
                    } else {
                      if (!advanced) {
                        advanced = true;
                        cursor.advance(n2);
                      } else {
                        resolve(cursor.key);
                      }
                    }
                  };
                  req.onerror = function() {
                    reject(req.error);
                  };
                } catch (e) {
                  reject(e);
                }
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function keys(callback) {
          var self2 = this;
          var promise = new Promise$1(function(resolve, reject) {
            self2.ready().then(function() {
              createTransaction(self2._dbInfo, READ_ONLY, function(err, transaction) {
                if (err) {
                  return reject(err);
                }
                try {
                  var store = transaction.objectStore(self2._dbInfo.storeName);
                  var req = store.openKeyCursor();
                  var keys2 = [];
                  req.onsuccess = function() {
                    var cursor = req.result;
                    if (!cursor) {
                      resolve(keys2);
                      return;
                    }
                    keys2.push(cursor.key);
                    cursor["continue"]();
                  };
                  req.onerror = function() {
                    reject(req.error);
                  };
                } catch (e) {
                  reject(e);
                }
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function dropInstance(options, callback) {
          callback = getCallback.apply(this, arguments);
          var currentConfig = this.config();
          options = typeof options !== "function" && options || {};
          if (!options.name) {
            options.name = options.name || currentConfig.name;
            options.storeName = options.storeName || currentConfig.storeName;
          }
          var self2 = this;
          var promise;
          if (!options.name) {
            promise = Promise$1.reject("Invalid arguments");
          } else {
            var isCurrentDb = options.name === currentConfig.name && self2._dbInfo.db;
            var dbPromise = isCurrentDb ? Promise$1.resolve(self2._dbInfo.db) : _getOriginalConnection(options).then(function(db) {
              var dbContext = dbContexts[options.name];
              var forages = dbContext.forages;
              dbContext.db = db;
              for (var i = 0; i < forages.length; i++) {
                forages[i]._dbInfo.db = db;
              }
              return db;
            });
            if (!options.storeName) {
              promise = dbPromise.then(function(db) {
                _deferReadiness(options);
                var dbContext = dbContexts[options.name];
                var forages = dbContext.forages;
                db.close();
                for (var i = 0; i < forages.length; i++) {
                  var forage = forages[i];
                  forage._dbInfo.db = null;
                }
                var dropDBPromise = new Promise$1(function(resolve, reject) {
                  var req = idb.deleteDatabase(options.name);
                  req.onerror = function() {
                    var db2 = req.result;
                    if (db2) {
                      db2.close();
                    }
                    reject(req.error);
                  };
                  req.onblocked = function() {
                    console.warn('dropInstance blocked for database "' + options.name + '" until all open connections are closed');
                  };
                  req.onsuccess = function() {
                    var db2 = req.result;
                    if (db2) {
                      db2.close();
                    }
                    resolve(db2);
                  };
                });
                return dropDBPromise.then(function(db2) {
                  dbContext.db = db2;
                  for (var i2 = 0; i2 < forages.length; i2++) {
                    var _forage = forages[i2];
                    _advanceReadiness(_forage._dbInfo);
                  }
                })["catch"](function(err) {
                  (_rejectReadiness(options, err) || Promise$1.resolve())["catch"](function() {
                  });
                  throw err;
                });
              });
            } else {
              promise = dbPromise.then(function(db) {
                if (!db.objectStoreNames.contains(options.storeName)) {
                  return;
                }
                var newVersion = db.version + 1;
                _deferReadiness(options);
                var dbContext = dbContexts[options.name];
                var forages = dbContext.forages;
                db.close();
                for (var i = 0; i < forages.length; i++) {
                  var forage = forages[i];
                  forage._dbInfo.db = null;
                  forage._dbInfo.version = newVersion;
                }
                var dropObjectPromise = new Promise$1(function(resolve, reject) {
                  var req = idb.open(options.name, newVersion);
                  req.onerror = function(err) {
                    var db2 = req.result;
                    db2.close();
                    reject(err);
                  };
                  req.onupgradeneeded = function() {
                    var db2 = req.result;
                    db2.deleteObjectStore(options.storeName);
                  };
                  req.onsuccess = function() {
                    var db2 = req.result;
                    db2.close();
                    resolve(db2);
                  };
                });
                return dropObjectPromise.then(function(db2) {
                  dbContext.db = db2;
                  for (var j = 0; j < forages.length; j++) {
                    var _forage2 = forages[j];
                    _forage2._dbInfo.db = db2;
                    _advanceReadiness(_forage2._dbInfo);
                  }
                })["catch"](function(err) {
                  (_rejectReadiness(options, err) || Promise$1.resolve())["catch"](function() {
                  });
                  throw err;
                });
              });
            }
          }
          executeCallback(promise, callback);
          return promise;
        }
        var asyncStorage = {
          _driver: "asyncStorage",
          _initStorage,
          _support: isIndexedDBValid(),
          iterate,
          getItem,
          setItem,
          removeItem,
          clear,
          length,
          key,
          keys,
          dropInstance
        };
        function isWebSQLValid() {
          return typeof openDatabase === "function";
        }
        var BASE_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        var BLOB_TYPE_PREFIX = "~~local_forage_type~";
        var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/;
        var SERIALIZED_MARKER = "__lfsc__:";
        var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length;
        var TYPE_ARRAYBUFFER = "arbf";
        var TYPE_BLOB = "blob";
        var TYPE_INT8ARRAY = "si08";
        var TYPE_UINT8ARRAY = "ui08";
        var TYPE_UINT8CLAMPEDARRAY = "uic8";
        var TYPE_INT16ARRAY = "si16";
        var TYPE_INT32ARRAY = "si32";
        var TYPE_UINT16ARRAY = "ur16";
        var TYPE_UINT32ARRAY = "ui32";
        var TYPE_FLOAT32ARRAY = "fl32";
        var TYPE_FLOAT64ARRAY = "fl64";
        var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length;
        var toString$1 = Object.prototype.toString;
        function stringToBuffer(serializedString) {
          var bufferLength = serializedString.length * 0.75;
          var len = serializedString.length;
          var i;
          var p = 0;
          var encoded1, encoded2, encoded3, encoded4;
          if (serializedString[serializedString.length - 1] === "=") {
            bufferLength--;
            if (serializedString[serializedString.length - 2] === "=") {
              bufferLength--;
            }
          }
          var buffer = new ArrayBuffer(bufferLength);
          var bytes = new Uint8Array(buffer);
          for (i = 0; i < len; i += 4) {
            encoded1 = BASE_CHARS.indexOf(serializedString[i]);
            encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]);
            encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]);
            encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]);
            bytes[p++] = encoded1 << 2 | encoded2 >> 4;
            bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
            bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
          }
          return buffer;
        }
        function bufferToString(buffer) {
          var bytes = new Uint8Array(buffer);
          var base64String = "";
          var i;
          for (i = 0; i < bytes.length; i += 3) {
            base64String += BASE_CHARS[bytes[i] >> 2];
            base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4];
            base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6];
            base64String += BASE_CHARS[bytes[i + 2] & 63];
          }
          if (bytes.length % 3 === 2) {
            base64String = base64String.substring(0, base64String.length - 1) + "=";
          } else if (bytes.length % 3 === 1) {
            base64String = base64String.substring(0, base64String.length - 2) + "==";
          }
          return base64String;
        }
        function serialize(value, callback) {
          var valueType = "";
          if (value) {
            valueType = toString$1.call(value);
          }
          if (value && (valueType === "[object ArrayBuffer]" || value.buffer && toString$1.call(value.buffer) === "[object ArrayBuffer]")) {
            var buffer;
            var marker = SERIALIZED_MARKER;
            if (value instanceof ArrayBuffer) {
              buffer = value;
              marker += TYPE_ARRAYBUFFER;
            } else {
              buffer = value.buffer;
              if (valueType === "[object Int8Array]") {
                marker += TYPE_INT8ARRAY;
              } else if (valueType === "[object Uint8Array]") {
                marker += TYPE_UINT8ARRAY;
              } else if (valueType === "[object Uint8ClampedArray]") {
                marker += TYPE_UINT8CLAMPEDARRAY;
              } else if (valueType === "[object Int16Array]") {
                marker += TYPE_INT16ARRAY;
              } else if (valueType === "[object Uint16Array]") {
                marker += TYPE_UINT16ARRAY;
              } else if (valueType === "[object Int32Array]") {
                marker += TYPE_INT32ARRAY;
              } else if (valueType === "[object Uint32Array]") {
                marker += TYPE_UINT32ARRAY;
              } else if (valueType === "[object Float32Array]") {
                marker += TYPE_FLOAT32ARRAY;
              } else if (valueType === "[object Float64Array]") {
                marker += TYPE_FLOAT64ARRAY;
              } else {
                callback(new Error("Failed to get type for BinaryArray"));
              }
            }
            callback(marker + bufferToString(buffer));
          } else if (valueType === "[object Blob]") {
            var fileReader = new FileReader();
            fileReader.onload = function() {
              var str = BLOB_TYPE_PREFIX + value.type + "~" + bufferToString(this.result);
              callback(SERIALIZED_MARKER + TYPE_BLOB + str);
            };
            fileReader.readAsArrayBuffer(value);
          } else {
            try {
              callback(JSON.stringify(value));
            } catch (e) {
              console.error("Couldn't convert value into a JSON string: ", value);
              callback(null, e);
            }
          }
        }
        function deserialize(value) {
          if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) {
            return JSON.parse(value);
          }
          var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH);
          var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH);
          var blobType;
          if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) {
            var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX);
            blobType = matcher[1];
            serializedString = serializedString.substring(matcher[0].length);
          }
          var buffer = stringToBuffer(serializedString);
          switch (type) {
            case TYPE_ARRAYBUFFER:
              return buffer;
            case TYPE_BLOB:
              return createBlob([buffer], { type: blobType });
            case TYPE_INT8ARRAY:
              return new Int8Array(buffer);
            case TYPE_UINT8ARRAY:
              return new Uint8Array(buffer);
            case TYPE_UINT8CLAMPEDARRAY:
              return new Uint8ClampedArray(buffer);
            case TYPE_INT16ARRAY:
              return new Int16Array(buffer);
            case TYPE_UINT16ARRAY:
              return new Uint16Array(buffer);
            case TYPE_INT32ARRAY:
              return new Int32Array(buffer);
            case TYPE_UINT32ARRAY:
              return new Uint32Array(buffer);
            case TYPE_FLOAT32ARRAY:
              return new Float32Array(buffer);
            case TYPE_FLOAT64ARRAY:
              return new Float64Array(buffer);
            default:
              throw new Error("Unkown type: " + type);
          }
        }
        var localforageSerializer = {
          serialize,
          deserialize,
          stringToBuffer,
          bufferToString
        };
        function createDbTable(t, dbInfo, callback, errorCallback) {
          t.executeSql("CREATE TABLE IF NOT EXISTS " + dbInfo.storeName + " (id INTEGER PRIMARY KEY, key unique, value)", [], callback, errorCallback);
        }
        function _initStorage$1(options) {
          var self2 = this;
          var dbInfo = {
            db: null
          };
          if (options) {
            for (var i in options) {
              dbInfo[i] = typeof options[i] !== "string" ? options[i].toString() : options[i];
            }
          }
          var dbInfoPromise = new Promise$1(function(resolve, reject) {
            try {
              dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size);
            } catch (e) {
              return reject(e);
            }
            dbInfo.db.transaction(function(t) {
              createDbTable(t, dbInfo, function() {
                self2._dbInfo = dbInfo;
                resolve();
              }, function(t2, error) {
                reject(error);
              });
            }, reject);
          });
          dbInfo.serializer = localforageSerializer;
          return dbInfoPromise;
        }
        function tryExecuteSql(t, dbInfo, sqlStatement, args, callback, errorCallback) {
          t.executeSql(sqlStatement, args, callback, function(t2, error) {
            if (error.code === error.SYNTAX_ERR) {
              t2.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name = ?", [dbInfo.storeName], function(t3, results) {
                if (!results.rows.length) {
                  createDbTable(t3, dbInfo, function() {
                    t3.executeSql(sqlStatement, args, callback, errorCallback);
                  }, errorCallback);
                } else {
                  errorCallback(t3, error);
                }
              }, errorCallback);
            } else {
              errorCallback(t2, error);
            }
          }, errorCallback);
        }
        function getItem$1(key2, callback) {
          var self2 = this;
          key2 = normalizeKey(key2);
          var promise = new Promise$1(function(resolve, reject) {
            self2.ready().then(function() {
              var dbInfo = self2._dbInfo;
              dbInfo.db.transaction(function(t) {
                tryExecuteSql(t, dbInfo, "SELECT * FROM " + dbInfo.storeName + " WHERE key = ? LIMIT 1", [key2], function(t2, results) {
                  var result = results.rows.length ? results.rows.item(0).value : null;
                  if (result) {
                    result = dbInfo.serializer.deserialize(result);
                  }
                  resolve(result);
                }, function(t2, error) {
                  reject(error);
                });
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function iterate$1(iterator, callback) {
          var self2 = this;
          var promise = new Promise$1(function(resolve, reject) {
            self2.ready().then(function() {
              var dbInfo = self2._dbInfo;
              dbInfo.db.transaction(function(t) {
                tryExecuteSql(t, dbInfo, "SELECT * FROM " + dbInfo.storeName, [], function(t2, results) {
                  var rows = results.rows;
                  var length2 = rows.length;
                  for (var i = 0; i < length2; i++) {
                    var item = rows.item(i);
                    var result = item.value;
                    if (result) {
                      result = dbInfo.serializer.deserialize(result);
                    }
                    result = iterator(result, item.key, i + 1);
                    if (result !== void 0) {
                      resolve(result);
                      return;
                    }
                  }
                  resolve();
                }, function(t2, error) {
                  reject(error);
                });
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function _setItem(key2, value, callback, retriesLeft) {
          var self2 = this;
          key2 = normalizeKey(key2);
          var promise = new Promise$1(function(resolve, reject) {
            self2.ready().then(function() {
              if (value === void 0) {
                value = null;
              }
              var originalValue = value;
              var dbInfo = self2._dbInfo;
              dbInfo.serializer.serialize(value, function(value2, error) {
                if (error) {
                  reject(error);
                } else {
                  dbInfo.db.transaction(function(t) {
                    tryExecuteSql(t, dbInfo, "INSERT OR REPLACE INTO " + dbInfo.storeName + " (key, value) VALUES (?, ?)", [key2, value2], function() {
                      resolve(originalValue);
                    }, function(t2, error2) {
                      reject(error2);
                    });
                  }, function(sqlError) {
                    if (sqlError.code === sqlError.QUOTA_ERR) {
                      if (retriesLeft > 0) {
                        resolve(_setItem.apply(self2, [key2, originalValue, callback, retriesLeft - 1]));
                        return;
                      }
                      reject(sqlError);
                    }
                  });
                }
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function setItem$1(key2, value, callback) {
          return _setItem.apply(this, [key2, value, callback, 1]);
        }
        function removeItem$1(key2, callback) {
          var self2 = this;
          key2 = normalizeKey(key2);
          var promise = new Promise$1(function(resolve, reject) {
            self2.ready().then(function() {
              var dbInfo = self2._dbInfo;
              dbInfo.db.transaction(function(t) {
                tryExecuteSql(t, dbInfo, "DELETE FROM " + dbInfo.storeName + " WHERE key = ?", [key2], function() {
                  resolve();
                }, function(t2, error) {
                  reject(error);
                });
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function clear$1(callback) {
          var self2 = this;
          var promise = new Promise$1(function(resolve, reject) {
            self2.ready().then(function() {
              var dbInfo = self2._dbInfo;
              dbInfo.db.transaction(function(t) {
                tryExecuteSql(t, dbInfo, "DELETE FROM " + dbInfo.storeName, [], function() {
                  resolve();
                }, function(t2, error) {
                  reject(error);
                });
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function length$1(callback) {
          var self2 = this;
          var promise = new Promise$1(function(resolve, reject) {
            self2.ready().then(function() {
              var dbInfo = self2._dbInfo;
              dbInfo.db.transaction(function(t) {
                tryExecuteSql(t, dbInfo, "SELECT COUNT(key) as c FROM " + dbInfo.storeName, [], function(t2, results) {
                  var result = results.rows.item(0).c;
                  resolve(result);
                }, function(t2, error) {
                  reject(error);
                });
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function key$1(n2, callback) {
          var self2 = this;
          var promise = new Promise$1(function(resolve, reject) {
            self2.ready().then(function() {
              var dbInfo = self2._dbInfo;
              dbInfo.db.transaction(function(t) {
                tryExecuteSql(t, dbInfo, "SELECT key FROM " + dbInfo.storeName + " WHERE id = ? LIMIT 1", [n2 + 1], function(t2, results) {
                  var result = results.rows.length ? results.rows.item(0).key : null;
                  resolve(result);
                }, function(t2, error) {
                  reject(error);
                });
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function keys$1(callback) {
          var self2 = this;
          var promise = new Promise$1(function(resolve, reject) {
            self2.ready().then(function() {
              var dbInfo = self2._dbInfo;
              dbInfo.db.transaction(function(t) {
                tryExecuteSql(t, dbInfo, "SELECT key FROM " + dbInfo.storeName, [], function(t2, results) {
                  var keys2 = [];
                  for (var i = 0; i < results.rows.length; i++) {
                    keys2.push(results.rows.item(i).key);
                  }
                  resolve(keys2);
                }, function(t2, error) {
                  reject(error);
                });
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function getAllStoreNames(db) {
          return new Promise$1(function(resolve, reject) {
            db.transaction(function(t) {
              t.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'", [], function(t2, results) {
                var storeNames = [];
                for (var i = 0; i < results.rows.length; i++) {
                  storeNames.push(results.rows.item(i).name);
                }
                resolve({
                  db,
                  storeNames
                });
              }, function(t2, error) {
                reject(error);
              });
            }, function(sqlError) {
              reject(sqlError);
            });
          });
        }
        function dropInstance$1(options, callback) {
          callback = getCallback.apply(this, arguments);
          var currentConfig = this.config();
          options = typeof options !== "function" && options || {};
          if (!options.name) {
            options.name = options.name || currentConfig.name;
            options.storeName = options.storeName || currentConfig.storeName;
          }
          var self2 = this;
          var promise;
          if (!options.name) {
            promise = Promise$1.reject("Invalid arguments");
          } else {
            promise = new Promise$1(function(resolve) {
              var db;
              if (options.name === currentConfig.name) {
                db = self2._dbInfo.db;
              } else {
                db = openDatabase(options.name, "", "", 0);
              }
              if (!options.storeName) {
                resolve(getAllStoreNames(db));
              } else {
                resolve({
                  db,
                  storeNames: [options.storeName]
                });
              }
            }).then(function(operationInfo) {
              return new Promise$1(function(resolve, reject) {
                operationInfo.db.transaction(function(t) {
                  function dropTable(storeName) {
                    return new Promise$1(function(resolve2, reject2) {
                      t.executeSql("DROP TABLE IF EXISTS " + storeName, [], function() {
                        resolve2();
                      }, function(t2, error) {
                        reject2(error);
                      });
                    });
                  }
                  var operations = [];
                  for (var i = 0, len = operationInfo.storeNames.length; i < len; i++) {
                    operations.push(dropTable(operationInfo.storeNames[i]));
                  }
                  Promise$1.all(operations).then(function() {
                    resolve();
                  })["catch"](function(e) {
                    reject(e);
                  });
                }, function(sqlError) {
                  reject(sqlError);
                });
              });
            });
          }
          executeCallback(promise, callback);
          return promise;
        }
        var webSQLStorage = {
          _driver: "webSQLStorage",
          _initStorage: _initStorage$1,
          _support: isWebSQLValid(),
          iterate: iterate$1,
          getItem: getItem$1,
          setItem: setItem$1,
          removeItem: removeItem$1,
          clear: clear$1,
          length: length$1,
          key: key$1,
          keys: keys$1,
          dropInstance: dropInstance$1
        };
        function isLocalStorageValid() {
          try {
            return typeof localStorage !== "undefined" && "setItem" in localStorage && // in IE8 typeof localStorage.setItem === 'object'
            !!localStorage.setItem;
          } catch (e) {
            return false;
          }
        }
        function _getKeyPrefix(options, defaultConfig) {
          var keyPrefix = options.name + "/";
          if (options.storeName !== defaultConfig.storeName) {
            keyPrefix += options.storeName + "/";
          }
          return keyPrefix;
        }
        function checkIfLocalStorageThrows() {
          var localStorageTestKey = "_localforage_support_test";
          try {
            localStorage.setItem(localStorageTestKey, true);
            localStorage.removeItem(localStorageTestKey);
            return false;
          } catch (e) {
            return true;
          }
        }
        function _isLocalStorageUsable() {
          return !checkIfLocalStorageThrows() || localStorage.length > 0;
        }
        function _initStorage$2(options) {
          var self2 = this;
          var dbInfo = {};
          if (options) {
            for (var i in options) {
              dbInfo[i] = options[i];
            }
          }
          dbInfo.keyPrefix = _getKeyPrefix(options, self2._defaultConfig);
          if (!_isLocalStorageUsable()) {
            return Promise$1.reject();
          }
          self2._dbInfo = dbInfo;
          dbInfo.serializer = localforageSerializer;
          return Promise$1.resolve();
        }
        function clear$2(callback) {
          var self2 = this;
          var promise = self2.ready().then(function() {
            var keyPrefix = self2._dbInfo.keyPrefix;
            for (var i = localStorage.length - 1; i >= 0; i--) {
              var key2 = localStorage.key(i);
              if (key2.indexOf(keyPrefix) === 0) {
                localStorage.removeItem(key2);
              }
            }
          });
          executeCallback(promise, callback);
          return promise;
        }
        function getItem$2(key2, callback) {
          var self2 = this;
          key2 = normalizeKey(key2);
          var promise = self2.ready().then(function() {
            var dbInfo = self2._dbInfo;
            var result = localStorage.getItem(dbInfo.keyPrefix + key2);
            if (result) {
              result = dbInfo.serializer.deserialize(result);
            }
            return result;
          });
          executeCallback(promise, callback);
          return promise;
        }
        function iterate$2(iterator, callback) {
          var self2 = this;
          var promise = self2.ready().then(function() {
            var dbInfo = self2._dbInfo;
            var keyPrefix = dbInfo.keyPrefix;
            var keyPrefixLength = keyPrefix.length;
            var length2 = localStorage.length;
            var iterationNumber = 1;
            for (var i = 0; i < length2; i++) {
              var key2 = localStorage.key(i);
              if (key2.indexOf(keyPrefix) !== 0) {
                continue;
              }
              var value = localStorage.getItem(key2);
              if (value) {
                value = dbInfo.serializer.deserialize(value);
              }
              value = iterator(value, key2.substring(keyPrefixLength), iterationNumber++);
              if (value !== void 0) {
                return value;
              }
            }
          });
          executeCallback(promise, callback);
          return promise;
        }
        function key$2(n2, callback) {
          var self2 = this;
          var promise = self2.ready().then(function() {
            var dbInfo = self2._dbInfo;
            var result;
            try {
              result = localStorage.key(n2);
            } catch (error) {
              result = null;
            }
            if (result) {
              result = result.substring(dbInfo.keyPrefix.length);
            }
            return result;
          });
          executeCallback(promise, callback);
          return promise;
        }
        function keys$2(callback) {
          var self2 = this;
          var promise = self2.ready().then(function() {
            var dbInfo = self2._dbInfo;
            var length2 = localStorage.length;
            var keys2 = [];
            for (var i = 0; i < length2; i++) {
              var itemKey = localStorage.key(i);
              if (itemKey.indexOf(dbInfo.keyPrefix) === 0) {
                keys2.push(itemKey.substring(dbInfo.keyPrefix.length));
              }
            }
            return keys2;
          });
          executeCallback(promise, callback);
          return promise;
        }
        function length$2(callback) {
          var self2 = this;
          var promise = self2.keys().then(function(keys2) {
            return keys2.length;
          });
          executeCallback(promise, callback);
          return promise;
        }
        function removeItem$2(key2, callback) {
          var self2 = this;
          key2 = normalizeKey(key2);
          var promise = self2.ready().then(function() {
            var dbInfo = self2._dbInfo;
            localStorage.removeItem(dbInfo.keyPrefix + key2);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function setItem$2(key2, value, callback) {
          var self2 = this;
          key2 = normalizeKey(key2);
          var promise = self2.ready().then(function() {
            if (value === void 0) {
              value = null;
            }
            var originalValue = value;
            return new Promise$1(function(resolve, reject) {
              var dbInfo = self2._dbInfo;
              dbInfo.serializer.serialize(value, function(value2, error) {
                if (error) {
                  reject(error);
                } else {
                  try {
                    localStorage.setItem(dbInfo.keyPrefix + key2, value2);
                    resolve(originalValue);
                  } catch (e) {
                    if (e.name === "QuotaExceededError" || e.name === "NS_ERROR_DOM_QUOTA_REACHED") {
                      reject(e);
                    }
                    reject(e);
                  }
                }
              });
            });
          });
          executeCallback(promise, callback);
          return promise;
        }
        function dropInstance$2(options, callback) {
          callback = getCallback.apply(this, arguments);
          options = typeof options !== "function" && options || {};
          if (!options.name) {
            var currentConfig = this.config();
            options.name = options.name || currentConfig.name;
            options.storeName = options.storeName || currentConfig.storeName;
          }
          var self2 = this;
          var promise;
          if (!options.name) {
            promise = Promise$1.reject("Invalid arguments");
          } else {
            promise = new Promise$1(function(resolve) {
              if (!options.storeName) {
                resolve(options.name + "/");
              } else {
                resolve(_getKeyPrefix(options, self2._defaultConfig));
              }
            }).then(function(keyPrefix) {
              for (var i = localStorage.length - 1; i >= 0; i--) {
                var key2 = localStorage.key(i);
                if (key2.indexOf(keyPrefix) === 0) {
                  localStorage.removeItem(key2);
                }
              }
            });
          }
          executeCallback(promise, callback);
          return promise;
        }
        var localStorageWrapper = {
          _driver: "localStorageWrapper",
          _initStorage: _initStorage$2,
          _support: isLocalStorageValid(),
          iterate: iterate$2,
          getItem: getItem$2,
          setItem: setItem$2,
          removeItem: removeItem$2,
          clear: clear$2,
          length: length$2,
          key: key$2,
          keys: keys$2,
          dropInstance: dropInstance$2
        };
        var sameValue = function sameValue2(x, y) {
          return x === y || typeof x === "number" && typeof y === "number" && isNaN(x) && isNaN(y);
        };
        var includes2 = function includes3(array, searchElement) {
          var len = array.length;
          var i = 0;
          while (i < len) {
            if (sameValue(array[i], searchElement)) {
              return true;
            }
            i++;
          }
          return false;
        };
        var isArray = Array.isArray || function(arg) {
          return Object.prototype.toString.call(arg) === "[object Array]";
        };
        var DefinedDrivers = {};
        var DriverSupport = {};
        var DefaultDrivers = {
          INDEXEDDB: asyncStorage,
          WEBSQL: webSQLStorage,
          LOCALSTORAGE: localStorageWrapper
        };
        var DefaultDriverOrder = [DefaultDrivers.INDEXEDDB._driver, DefaultDrivers.WEBSQL._driver, DefaultDrivers.LOCALSTORAGE._driver];
        var OptionalDriverMethods = ["dropInstance"];
        var LibraryMethods = ["clear", "getItem", "iterate", "key", "keys", "length", "removeItem", "setItem"].concat(OptionalDriverMethods);
        var DefaultConfig = {
          description: "",
          driver: DefaultDriverOrder.slice(),
          name: "localforage",
          // Default DB size is _JUST UNDER_ 5MB, as it's the highest size
          // we can use without a prompt.
          size: 4980736,
          storeName: "keyvaluepairs",
          version: 1
        };
        function callWhenReady(localForageInstance, libraryMethod) {
          localForageInstance[libraryMethod] = function() {
            var _args = arguments;
            return localForageInstance.ready().then(function() {
              return localForageInstance[libraryMethod].apply(localForageInstance, _args);
            });
          };
        }
        function extend() {
          for (var i = 1; i < arguments.length; i++) {
            var arg = arguments[i];
            if (arg) {
              for (var _key in arg) {
                if (arg.hasOwnProperty(_key)) {
                  if (isArray(arg[_key])) {
                    arguments[0][_key] = arg[_key].slice();
                  } else {
                    arguments[0][_key] = arg[_key];
                  }
                }
              }
            }
          }
          return arguments[0];
        }
        var LocalForage = function() {
          function LocalForage2(options) {
            _classCallCheck(this, LocalForage2);
            for (var driverTypeKey in DefaultDrivers) {
              if (DefaultDrivers.hasOwnProperty(driverTypeKey)) {
                var driver = DefaultDrivers[driverTypeKey];
                var driverName = driver._driver;
                this[driverTypeKey] = driverName;
                if (!DefinedDrivers[driverName]) {
                  this.defineDriver(driver);
                }
              }
            }
            this._defaultConfig = extend({}, DefaultConfig);
            this._config = extend({}, this._defaultConfig, options);
            this._driverSet = null;
            this._initDriver = null;
            this._ready = false;
            this._dbInfo = null;
            this._wrapLibraryMethodsWithReady();
            this.setDriver(this._config.driver)["catch"](function() {
            });
          }
          LocalForage2.prototype.config = function config(options) {
            if ((typeof options === "undefined" ? "undefined" : _typeof(options)) === "object") {
              if (this._ready) {
                return new Error("Can't call config() after localforage has been used.");
              }
              for (var i in options) {
                if (i === "storeName") {
                  options[i] = options[i].replace(/\W/g, "_");
                }
                if (i === "version" && typeof options[i] !== "number") {
                  return new Error("Database version must be a number.");
                }
                this._config[i] = options[i];
              }
              if ("driver" in options && options.driver) {
                return this.setDriver(this._config.driver);
              }
              return true;
            } else if (typeof options === "string") {
              return this._config[options];
            } else {
              return this._config;
            }
          };
          LocalForage2.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) {
            var promise = new Promise$1(function(resolve, reject) {
              try {
                var driverName = driverObject._driver;
                var complianceError = new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver");
                if (!driverObject._driver) {
                  reject(complianceError);
                  return;
                }
                var driverMethods = LibraryMethods.concat("_initStorage");
                for (var i = 0, len = driverMethods.length; i < len; i++) {
                  var driverMethodName = driverMethods[i];
                  var isRequired = !includes2(OptionalDriverMethods, driverMethodName);
                  if ((isRequired || driverObject[driverMethodName]) && typeof driverObject[driverMethodName] !== "function") {
                    reject(complianceError);
                    return;
                  }
                }
                var configureMissingMethods = function configureMissingMethods2() {
                  var methodNotImplementedFactory = function methodNotImplementedFactory2(methodName) {
                    return function() {
                      var error = new Error("Method " + methodName + " is not implemented by the current driver");
                      var promise2 = Promise$1.reject(error);
                      executeCallback(promise2, arguments[arguments.length - 1]);
                      return promise2;
                    };
                  };
                  for (var _i = 0, _len = OptionalDriverMethods.length; _i < _len; _i++) {
                    var optionalDriverMethod = OptionalDriverMethods[_i];
                    if (!driverObject[optionalDriverMethod]) {
                      driverObject[optionalDriverMethod] = methodNotImplementedFactory(optionalDriverMethod);
                    }
                  }
                };
                configureMissingMethods();
                var setDriverSupport = function setDriverSupport2(support) {
                  if (DefinedDrivers[driverName]) {
                    console.info("Redefining LocalForage driver: " + driverName);
                  }
                  DefinedDrivers[driverName] = driverObject;
                  DriverSupport[driverName] = support;
                  resolve();
                };
                if ("_support" in driverObject) {
                  if (driverObject._support && typeof driverObject._support === "function") {
                    driverObject._support().then(setDriverSupport, reject);
                  } else {
                    setDriverSupport(!!driverObject._support);
                  }
                } else {
                  setDriverSupport(true);
                }
              } catch (e) {
                reject(e);
              }
            });
            executeTwoCallbacks(promise, callback, errorCallback);
            return promise;
          };
          LocalForage2.prototype.driver = function driver() {
            return this._driver || null;
          };
          LocalForage2.prototype.getDriver = function getDriver(driverName, callback, errorCallback) {
            var getDriverPromise = DefinedDrivers[driverName] ? Promise$1.resolve(DefinedDrivers[driverName]) : Promise$1.reject(new Error("Driver not found."));
            executeTwoCallbacks(getDriverPromise, callback, errorCallback);
            return getDriverPromise;
          };
          LocalForage2.prototype.getSerializer = function getSerializer(callback) {
            var serializerPromise = Promise$1.resolve(localforageSerializer);
            executeTwoCallbacks(serializerPromise, callback);
            return serializerPromise;
          };
          LocalForage2.prototype.ready = function ready(callback) {
            var self2 = this;
            var promise = self2._driverSet.then(function() {
              if (self2._ready === null) {
                self2._ready = self2._initDriver();
              }
              return self2._ready;
            });
            executeTwoCallbacks(promise, callback, callback);
            return promise;
          };
          LocalForage2.prototype.setDriver = function setDriver(drivers, callback, errorCallback) {
            var self2 = this;
            if (!isArray(drivers)) {
              drivers = [drivers];
            }
            var supportedDrivers = this._getSupportedDrivers(drivers);
            function setDriverToConfig() {
              self2._config.driver = self2.driver();
            }
            function extendSelfWithDriver(driver) {
              self2._extend(driver);
              setDriverToConfig();
              self2._ready = self2._initStorage(self2._config);
              return self2._ready;
            }
            function initDriver(supportedDrivers2) {
              return function() {
                var currentDriverIndex = 0;
                function driverPromiseLoop() {
                  while (currentDriverIndex < supportedDrivers2.length) {
                    var driverName = supportedDrivers2[currentDriverIndex];
                    currentDriverIndex++;
                    self2._dbInfo = null;
                    self2._ready = null;
                    return self2.getDriver(driverName).then(extendSelfWithDriver)["catch"](driverPromiseLoop);
                  }
                  setDriverToConfig();
                  var error = new Error("No available storage method found.");
                  self2._driverSet = Promise$1.reject(error);
                  return self2._driverSet;
                }
                return driverPromiseLoop();
              };
            }
            var oldDriverSetDone = this._driverSet !== null ? this._driverSet["catch"](function() {
              return Promise$1.resolve();
            }) : Promise$1.resolve();
            this._driverSet = oldDriverSetDone.then(function() {
              var driverName = supportedDrivers[0];
              self2._dbInfo = null;
              self2._ready = null;
              return self2.getDriver(driverName).then(function(driver) {
                self2._driver = driver._driver;
                setDriverToConfig();
                self2._wrapLibraryMethodsWithReady();
                self2._initDriver = initDriver(supportedDrivers);
              });
            })["catch"](function() {
              setDriverToConfig();
              var error = new Error("No available storage method found.");
              self2._driverSet = Promise$1.reject(error);
              return self2._driverSet;
            });
            executeTwoCallbacks(this._driverSet, callback, errorCallback);
            return this._driverSet;
          };
          LocalForage2.prototype.supports = function supports(driverName) {
            return !!DriverSupport[driverName];
          };
          LocalForage2.prototype._extend = function _extend(libraryMethodsAndProperties) {
            extend(this, libraryMethodsAndProperties);
          };
          LocalForage2.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) {
            var supportedDrivers = [];
            for (var i = 0, len = drivers.length; i < len; i++) {
              var driverName = drivers[i];
              if (this.supports(driverName)) {
                supportedDrivers.push(driverName);
              }
            }
            return supportedDrivers;
          };
          LocalForage2.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() {
            for (var i = 0, len = LibraryMethods.length; i < len; i++) {
              callWhenReady(this, LibraryMethods[i]);
            }
          };
          LocalForage2.prototype.createInstance = function createInstance(options) {
            return new LocalForage2(options);
          };
          return LocalForage2;
        }();
        var localforage_js = new LocalForage();
        module4.exports = localforage_js;
      }, { "3": 3 }] }, {}, [4])(4);
    });
  }
});

// src/test/snapshot/generateSyncerSnapshot.ts
var generateSyncerSnapshot_exports = {};
__export(generateSyncerSnapshot_exports, {
  generateSyncerSnapshot: () => generateSyncerSnapshot
});
var import_obsidian26, import_promises, SNAPSHOT_PATH, generateSyncerSnapshot;
var init_generateSyncerSnapshot = __esm({
  "src/test/snapshot/generateSyncerSnapshot.ts"() {
    "use strict";
    init_esbuild_buffer_shim();
    import_obsidian26 = require("obsidian");
    import_promises = __toESM(require("fs/promises"));
    SNAPSHOT_PATH = "src/test/snapshot/snapshot.md";
    generateSyncerSnapshot = async (settings, publisher) => {
      const devPluginPath = settings.devPluginPath;
      if (!devPluginPath) {
        new import_obsidian26.Notice("devPluginPath missing, run generateSyncerSettings.mjs");
        return;
      }
      const marked = await publisher.getFilesMarkedForPublishing();
      let fileString = "IMAGES: \n";
      fileString += marked.blobs.map((path) => `${path}
`);
      const assetPaths = /* @__PURE__ */ new Set();
      for (const file of marked.notes) {
        fileString += "==========\n";
        fileString += `${file.getPath()}
`;
        fileString += "==========\n";
        const [content, assets] = await publisher.compiler.generateMarkdown(file);
        assets.blobs.map((blob) => assetPaths.add(blob.path));
        fileString += `${content}
`;
        fileString += Array.from(assetPaths).map((path) => `${path}
`);
      }
      fileString += "==========\n";
      const fullSnapshotPath = `${devPluginPath}/${SNAPSHOT_PATH}`;
      if (import_obsidian26.Platform.isDesktop) {
        await import_promises.default.writeFile(fullSnapshotPath, fileString);
      }
      new import_obsidian26.Notice(`Snapshot written to ${fullSnapshotPath}`);
      new import_obsidian26.Notice(`Check snapshot to make sure nothing has accidentally changed`);
    };
  }
});

// main.ts
var main_exports = {};
__export(main_exports, {
  default: () => QuartzSyncer
});
module.exports = __toCommonJS(main_exports);
init_esbuild_buffer_shim();
var import_obsidian27 = require("obsidian");

// src/publisher/Publisher.ts
init_esbuild_buffer_shim();

// src/utils/utils.ts
init_esbuild_buffer_shim();
var import_slugify = __toESM(require_slugify());
var import_sha1 = __toESM(require_sha1());
var import_obsidian = require("obsidian");
function generateUrlPath(filePath, slugifyPath = true) {
  if (!filePath) {
    return filePath;
  }
  const extensionLessPath = filePath.contains(".") ? filePath.substring(0, filePath.lastIndexOf(".")) : filePath;
  if (!slugifyPath) {
    return extensionLessPath + "/";
  }
  return extensionLessPath.split("/").map((x) => (0, import_slugify.default)(x, { separator: "-", lowercase: false })).join("/") + "/";
}
function generateBlobHash(content) {
  const byteLength2 = new TextEncoder().encode(content).byteLength;
  const header = `blob ${byteLength2}\0`;
  const gitBlob = header + content;
  return (0, import_sha1.default)(gitBlob).toString();
}
function getRewriteRules(vaultPath) {
  return { from: vaultPath, to: "/" };
}
function getSyncerPathForNote(vaultPath, rules) {
  const { from: from2, to } = rules;
  if (vaultPath && vaultPath.startsWith(from2)) {
    const newPath = vaultPath.replace(from2, to);
    if (newPath.startsWith("/")) {
      return newPath.replace("/", "");
    }
    return newPath;
  }
  return vaultPath;
}
function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function fixSvgForXmlSerializer(svgElement) {
  const styles = svgElement.getElementsByTagName("style");
  if (styles.length > 0) {
    for (let i = 0; i < styles.length; i++) {
      const style = styles[i];
      if (!style.textContent?.trim()) {
        style.textContent = "/**/";
      }
    }
  }
}
function sanitizePermalink(permalink) {
  if (permalink.endsWith("/")) {
    permalink.slice(0, -1);
  }
  if (!permalink.startsWith("/")) {
    permalink = "/" + permalink;
  }
  return permalink;
}
function isPluginEnabled(pluginId) {
  const plugins = app.plugins.enabledPlugins;
  return plugins.has(pluginId) || plugins.has(pluginId.toLowerCase());
}
function cleanQueryResult(markdown) {
  markdown = decodeURI(markdown);
  markdown = markdown.replace(
    /\[#([^\]]+)\]\(#([^)]+)\)/g,
    `<a href="tags/$2" class="tag-link">$1</a>`
  );
  markdown = markdown.replace(
    /#([\w\\/]+)/g,
    `<a href="tags/$1" class="tag-link">$1</a>`
  );
  markdown = markdown.replace(/(\[.*?\]\()(.+?)\.md(\))/g, "$1$2$3");
  markdown = markdown.replace(/\[([^\]]+)\]\(([^)]+)\)/g, "[[$2|$1]]");
  return markdown.trim();
}
function renderPromise(div, selector, timeout = 5e3, interval = 500) {
  return new Promise((resolve, reject) => {
    let intervalTimer;
    const observer = new MutationObserver(() => {
      clearTimeout(intervalTimer);
      intervalTimer = setTimeout(() => {
        cleanUp();
        resolve();
      }, interval);
    });
    const cleanUp = () => {
      observer.disconnect();
      clearTimeout(intervalTimer);
      clearTimeout(timeoutTimer);
    };
    observer.observe(div, { childList: true, subtree: true });
    const timeoutTimer = setTimeout(() => {
      cleanUp();
      reject(new import_obsidian.Notice(`Timeout waiting for selector: ${selector}`));
    }, timeout);
  });
}
function surroundWithCalloutBlock(input, depth = 1) {
  const tmp = input.split("\n");
  const calloutSymbol = "> ".repeat(depth);
  return " " + tmp.join(`
${calloutSymbol}`);
}
function sanitizeQuery(query) {
  let isInsideCalloutDepth = 0;
  const parts = query.split("\n");
  const sanitized = [];
  for (const part of parts) {
    let depthPivot = 0;
    if (part.startsWith(">")) {
      depthPivot += 1;
      let intermediate = part.substring(1).trim();
      while (intermediate.startsWith(">")) {
        intermediate = intermediate.substring(1).trim();
        depthPivot += 1;
      }
      sanitized.push(intermediate);
    } else {
      sanitized.push(part);
    }
    isInsideCalloutDepth = Math.max(isInsideCalloutDepth, depthPivot);
  }
  let finalQuery = query;
  if (isInsideCalloutDepth > 0) {
    finalQuery = sanitized.join("\n");
  }
  return { isInsideCalloutDepth, finalQuery };
}
function sanitizeHTMLToString(div, serializer) {
  const styleTags = div.querySelectorAll("style");
  const sanitizedHtml = (0, import_obsidian.sanitizeHTMLToDom)(div.innerHTML);
  let container = document.createElement("div");
  container.appendChild(sanitizedHtml);
  removeUnwantedElements(container, "script, link, meta, title");
  const internalLinks = container.querySelectorAll(
    "a.internal-link, a.tag, a:not(.external-link):not(.internal-link):not(.tag)"
  );
  if (internalLinks.length > 0) {
    cleanAnchorLinks(container);
  }
  container = convertCallouts(container);
  container = unwrap(container);
  const classes = container.classList;
  const markdownableClasses = ["datacore-table", "datacore-list"];
  const markdownableTagNames = [
    "p",
    //"blockquote",
    "h1",
    "h2",
    "h3",
    "h4",
    "h5",
    "h6",
    "ul",
    "ol",
    "li",
    "table",
    "thead",
    "tbody",
    "tr",
    "td",
    "th"
  ];
  if (classes.length > 0 && Array.from(classes).some(
    (cls) => markdownableClasses.includes(cls)
  ) || markdownableTagNames.includes(container.tagName.toLowerCase())) {
    const result = (0, import_obsidian.htmlToMarkdown)(container) || "";
    return cleanQueryResult(result);
  }
  styleTags.forEach((styleTag) => {
    container.append(styleTag);
  });
  cleanDatacoreAttributes(container);
  const serializedHtml = serializer.serializeToString(container);
  return serializedHtml.replace(' xmlns="http://www.w3.org/1999/xhtml"', "");
}
function cleanDatacoreAttributes(container) {
  const datacoreAttributes = ["__source", "__self"];
  const elements = container.querySelectorAll(
    `${datacoreAttributes.map((attr2) => `[${attr2}]`).join(", ")}`
  );
  elements.forEach((element2) => {
    datacoreAttributes.forEach((attr2) => {
      element2.removeAttribute(attr2);
    });
  });
}
function convertCallouts(container) {
  const callouts = container.querySelectorAll(".callout");
  if (callouts.length === 0) {
    return container;
  }
  callouts.forEach((callout) => {
    const blockquote = document.createElement(
      "blockquote"
    );
    if (callout.hasAttribute("data-callout-fold")) {
      if (callout.getAttribute("data-callout-fold") === "-") {
        blockquote.classList.add("is-collapsed");
      }
      callout.setAttribute("data-callout-fold", "");
    }
    if (!callout.hasAttribute("data-callout")) {
      callout.setAttribute("data-callout", "note");
    }
    for (let index = 0; index < callout.attributes.length; index++) {
      if (callout.attributes.item(index) !== null) {
        blockquote.setAttribute(
          callout.attributes.item(index).name,
          callout.attributes.item(index).value || ""
        );
      }
    }
    blockquote.innerHTML = callout.innerHTML;
    blockquote.classList.remove("datacore");
    const calloutContent = blockquote.querySelector(".callout-content");
    if (calloutContent) {
      const innerWrapper = document.createElement("div");
      innerWrapper.classList.add("callout-content-inner");
      innerWrapper.innerHTML = calloutContent.innerHTML;
      calloutContent.innerHTML = "";
      calloutContent.appendChild(innerWrapper);
    }
    const calloutFold = blockquote.querySelector(".callout-fold");
    if (calloutFold) {
      calloutFold.classList.replace("callout-fold", "fold-callout-icon");
      const innerSVG = calloutFold.querySelector("svg");
      if (innerSVG) {
        calloutFold.removeChild(innerSVG);
      }
    }
    const calloutTitle = blockquote.querySelector(".callout-title");
    if (calloutTitle && calloutTitle.children && !calloutTitle.children[0].classList.contains("callout-icon")) {
      const icon = document.createElement("div");
      icon.classList.add("callout-icon");
      calloutTitle.prepend(icon);
    }
    callout.replaceWith(blockquote);
  });
  return container;
}
function cleanAnchorLinks(container) {
  const internalLinks = container.querySelectorAll(
    "a.internal-link, a.tag, a:not(.external-link):not(.internal-link):not(.tag)"
  );
  internalLinks.forEach((link) => {
    link.removeAttribute("target");
    link.removeAttribute("rel");
    link.removeAttribute("data-href");
    if (link.hasAttribute("href")) {
      if (link.getAttribute("href")?.startsWith("http")) {
        link.classList.add("external-link");
      } else {
        link.classList.add("internal-link");
      }
    }
  });
}
function removeUnwantedElements(container, selector) {
  const elements = container.querySelectorAll(selector);
  elements.forEach((element2) => {
    element2.remove();
  });
}
function unwrap(container) {
  while (container.attributes.length === 0 && container.children.length === 1) {
    const child = container.firstElementChild;
    if (child) {
      container.replaceWith(child);
      container = child;
    } else {
      break;
    }
  }
  return container;
}
function svgToData(svgElement) {
  const serializer = new XMLSerializer();
  const svgString = serializer.serializeToString(svgElement);
  const encodedData = btoa(unescape(encodeURIComponent(svgString)));
  return `data:image/svg+xml;base64,${encodedData}`;
}

// src/publishFile/Validator.ts
init_esbuild_buffer_shim();
var import_obsidian2 = require("obsidian");
var hasPublishFlag = (flag, frontMatter, override = false) => !!frontMatter?.[flag] || override;
function isPublishFrontmatterValid(flag, frontMatter, override = false) {
  if (!hasPublishFlag(flag, frontMatter, override)) {
    new import_obsidian2.Notice(
      "Quartz Syncer: Note does not have the publish: true set. Please add this and try again."
    );
    return false;
  }
  return true;
}

// src/compiler/SyncerPageCompiler.ts
init_esbuild_buffer_shim();
var import_obsidian10 = require("obsidian");
var import_slugify2 = __toESM(require_slugify());

// src/utils/regexes.ts
init_esbuild_buffer_shim();
var FRONTMATTER_REGEX = /^\s*?---\n([\s\S]*?)\n---/g;
var BLOCKREF_REGEX = /(\^\w+(\n|$))/g;
var CODE_FENCE_REGEX = /`(.*?)`/g;
var CODEBLOCK_REGEX = /```.*?\n[\s\S]+?```/g;
var EXCALIDRAW_REGEX = /:\[\[(\d*?,\d*?)\],.*?\]\]/g;
var TRANSCLUDED_SVG_REGEX = /!\[\[(.*?)(\.(svg))\|(.*?)\]\]|!\[\[(.*?)(\.(svg))\]\]/g;
var DATAVIEW_LINK_TARGET_BLANK_REGEX = /target=["']_blank["'] rel=["']noopener["']/g;
var DATAVIEW_FIELD_REGEX = /^([^:]+)::\s(.*?)$/gm;
var DATAVIEW_INLINE_FIELD_REGEX = /\[([^:\][]+)::\s(.*?)\]|\(([^:)(]+)::\s(.*?)\)/g;
var TRANSCLUDED_FILE_REGEX = /!\[\[(.*?)(\.(png|jpg|jpeg|gif|webp|mp4|mkv|mov|avi|mp3|wav|ogg|pdf))\|(.*?)\]\]|!\[\[(.*?)(\.(png|jpg|jpeg|gif|webp|mp4|mkv|mov|avi|mp3|wav|ogg|pdf))\]\]/g;
var FILE_REGEX = /!\[(.*?)\]\((.*?)(\.(png|jpg|jpeg|gif|webp|mp4|mkv|mov|avi|mp3|wav|ogg|pdf))\)/g;

// src/compiler/SyncerPageCompiler.ts
var import_js_logger7 = __toESM(require_logger());

// src/publishFile/PublishFile.ts
init_esbuild_buffer_shim();

// src/compiler/FrontmatterCompiler.ts
init_esbuild_buffer_shim();
var import_obsidian3 = require("obsidian");
var FrontmatterCompiler = class {
  settings;
  constructor(settings) {
    this.settings = settings;
  }
  /**
   * Compiles the frontmatter of a file.
   * It adds the permalink, default pass-throughs, timestamps, tags, CSS classes, and social image to the frontmatter.
   *
   * @param file - The file to compile the frontmatter for.
   * @param frontmatter - The frontmatter of the file.
   * @returns The compiled frontmatter as a string.
   */
  compile(file, frontmatter) {
    const fileFrontMatter = { ...frontmatter };
    delete fileFrontMatter["position"];
    let publishedFrontMatter = {
      publish: true
    };
    publishedFrontMatter = this.addPermalink(file)(
      fileFrontMatter,
      publishedFrontMatter
    );
    publishedFrontMatter = this.addDefaultPassThrough(
      fileFrontMatter,
      publishedFrontMatter
    );
    publishedFrontMatter = this.addTimestampsFrontmatter(file)(
      fileFrontMatter,
      publishedFrontMatter
    );
    publishedFrontMatter = this.addTags(
      fileFrontMatter,
      publishedFrontMatter
    );
    publishedFrontMatter = this.addCSSClasses(
      fileFrontMatter,
      publishedFrontMatter
    );
    publishedFrontMatter = this.addSocialImage(
      fileFrontMatter,
      publishedFrontMatter
    );
    const fullFrontMatter = this.settings.includeAllFrontmatter ? { ...publishedFrontMatter, ...fileFrontMatter } : publishedFrontMatter;
    const frontMatterString = this.settings.frontmatterFormat === "json" ? JSON.stringify(fullFrontMatter) + "\n" : (0, import_obsidian3.stringifyYaml)(fullFrontMatter);
    return `---
${frontMatterString}---
`;
  }
  addPermalink = (file) => (baseFrontMatter, newFrontMatter) => {
    const publishedFrontMatter = { ...newFrontMatter };
    if (baseFrontMatter) {
      if (baseFrontMatter["permalink"]) {
        publishedFrontMatter["permalink"] = baseFrontMatter["permalink"];
      } else if (this.settings.usePermalink) {
        publishedFrontMatter["permalink"] = sanitizePermalink(
          baseFrontMatter["permalink"] ?? file.getVaultPath()
        );
      }
      if (baseFrontMatter["aliases"] || baseFrontMatter["alias"]) {
        publishedFrontMatter["aliases"] = "";
        if (typeof baseFrontMatter["aliases"] === "string") {
          publishedFrontMatter["aliases"] = baseFrontMatter["aliases"].split(/,?\s*/).join(" ");
        }
        if (Array.isArray(baseFrontMatter["aliases"])) {
          publishedFrontMatter["aliases"] = baseFrontMatter["aliases"].join(" ");
        }
        if (typeof baseFrontMatter["alias"] === "string") {
          publishedFrontMatter["aliases"] += ` ${baseFrontMatter["alias"]}`;
        } else if (Array.isArray(baseFrontMatter["alias"])) {
          publishedFrontMatter["aliases"] += ` ${baseFrontMatter["alias"].join(" ")}`;
        }
      }
    }
    return publishedFrontMatter;
  };
  addDefaultPassThrough(baseFrontMatter, newFrontMatter) {
    const publishedFrontMatter = { ...newFrontMatter };
    if (baseFrontMatter) {
      if (baseFrontMatter["title"]) {
        publishedFrontMatter["title"] = baseFrontMatter["title"];
      }
      if (baseFrontMatter["description"]) {
        publishedFrontMatter["description"] = baseFrontMatter["description"];
      }
      if (baseFrontMatter["draft"]) {
        publishedFrontMatter["draft"] = baseFrontMatter["draft"];
      }
      if (baseFrontMatter["comments"]) {
        publishedFrontMatter["comments"] = baseFrontMatter["comments"];
      }
      if (baseFrontMatter["lang"]) {
        publishedFrontMatter["lang"] = baseFrontMatter["lang"];
      }
      if (baseFrontMatter["enableToc"]) {
        publishedFrontMatter["enableToc"] = baseFrontMatter["enableToc"];
      }
    }
    return publishedFrontMatter;
  }
  addTags(fileFrontMatter, publishedFrontMatterWithoutTags) {
    const publishedFrontMatter = { ...publishedFrontMatterWithoutTags };
    if (fileFrontMatter) {
      const tags = (typeof fileFrontMatter["tags"] === "string" ? fileFrontMatter["tags"].split(/,?\s*/) : fileFrontMatter["tags"]) || [];
      if (tags.length > 0) {
        publishedFrontMatter["tags"] = tags;
      }
      if (fileFrontMatter["tag"] !== void 0) {
        if (typeof fileFrontMatter["tag"] === "string") {
          publishedFrontMatter["tags"] = [
            ...publishedFrontMatter["tags"] ?? [],
            fileFrontMatter["tag"]
          ];
        } else if (Array.isArray(fileFrontMatter["tag"])) {
          publishedFrontMatter["tags"] = [
            ...publishedFrontMatter["tags"] ?? [],
            ...fileFrontMatter["tag"]
          ];
        }
      }
    }
    return publishedFrontMatter;
  }
  addCSSClasses(baseFrontMatter, newFrontMatter) {
    const publishedFrontMatter = { ...newFrontMatter };
    publishedFrontMatter["cssclasses"] = publishedFrontMatter["cssclasses"] ?? "";
    if (baseFrontMatter) {
      if (baseFrontMatter["cssclasses"] !== void 0) {
        if (typeof baseFrontMatter["cssclasses"] === "string") {
          publishedFrontMatter["cssclasses"] += baseFrontMatter["cssclasses"];
        } else if (Array.isArray(baseFrontMatter["cssclasses"])) {
          publishedFrontMatter["cssclasses"] += baseFrontMatter["cssclasses"].join(" ");
        }
      }
      if (baseFrontMatter["cssclass"] !== void 0) {
        if (typeof baseFrontMatter["cssclass"] === "string") {
          publishedFrontMatter["cssclasses"] += baseFrontMatter["cssclass"];
        } else if (Array.isArray(baseFrontMatter["cssclass"])) {
          publishedFrontMatter["cssclasses"] += baseFrontMatter["cssclass"].join(" ");
        }
      }
    }
    if (publishedFrontMatter["cssclasses"]) {
      if (typeof publishedFrontMatter["cssclasses"] === "string") {
        publishedFrontMatter["cssclasses"] = publishedFrontMatter["cssclasses"].split(" ");
      }
      if (Array.isArray(publishedFrontMatter["cssclasses"])) {
        publishedFrontMatter["cssclasses"] = [
          ...new Set(publishedFrontMatter["cssclasses"])
        ];
      }
    }
    if (typeof publishedFrontMatter["cssclasses"] !== "string") {
      if (Array.isArray(publishedFrontMatter["cssclasses"])) {
        publishedFrontMatter["cssclasses"] = publishedFrontMatter["cssclasses"].join(" ");
      }
    }
    return publishedFrontMatter;
  }
  addSocialImage(baseFrontMatter, newFrontMatter) {
    const publishedFrontMatter = { ...newFrontMatter };
    if (baseFrontMatter) {
      const socialImage = baseFrontMatter["socialImage"] ?? baseFrontMatter["image"] ?? baseFrontMatter["cover"] ?? "";
      const socialDescription = baseFrontMatter["socialDescription"] ?? "";
      if (socialImage && socialImage !== "") {
        publishedFrontMatter["socialImage"] = socialImage;
      }
      if (socialDescription && socialDescription !== "") {
        publishedFrontMatter["socialDescription"] = socialDescription;
      }
    }
    return publishedFrontMatter;
  }
  addTimestampsFrontmatter = (file) => (baseFrontMatter, newFrontMatter) => {
    const {
      showCreatedTimestamp,
      showUpdatedTimestamp,
      showPublishedTimestamp
    } = this.settings;
    const overridden = this.settings.includeAllFrontmatter;
    const createdAt = file.meta.getCreatedAt();
    const updatedAt = file.meta.getUpdatedAt();
    const publishedAt = file.meta.getPublishedAt();
    if (createdAt && (showCreatedTimestamp || overridden)) {
      newFrontMatter["created"] = overridden ? baseFrontMatter["created"] ?? baseFrontMatter["date"] ?? createdAt : createdAt;
    }
    if (updatedAt && (showUpdatedTimestamp || overridden)) {
      newFrontMatter["modified"] = overridden ? baseFrontMatter["modified"] ?? baseFrontMatter["lastmod"] ?? baseFrontMatter["updated"] ?? baseFrontMatter["last-modified"] ?? updatedAt : updatedAt;
    }
    if (publishedAt && (showPublishedTimestamp || overridden)) {
      newFrontMatter["published"] = overridden ? baseFrontMatter["published"] ?? baseFrontMatter["publishDate"] ?? baseFrontMatter["date"] ?? publishedAt : publishedAt;
    }
    return newFrontMatter;
  };
};

// src/publishFile/FileMetaDataManager.ts
init_esbuild_buffer_shim();

// node_modules/luxon/src/luxon.js
init_esbuild_buffer_shim();

// node_modules/luxon/src/datetime.js
init_esbuild_buffer_shim();

// node_modules/luxon/src/duration.js
init_esbuild_buffer_shim();

// node_modules/luxon/src/errors.js
init_esbuild_buffer_shim();
var LuxonError = class extends Error {
};
var InvalidDateTimeError = class extends LuxonError {
  constructor(reason) {
    super(`Invalid DateTime: ${reason.toMessage()}`);
  }
};
var InvalidIntervalError = class extends LuxonError {
  constructor(reason) {
    super(`Invalid Interval: ${reason.toMessage()}`);
  }
};
var InvalidDurationError = class extends LuxonError {
  constructor(reason) {
    super(`Invalid Duration: ${reason.toMessage()}`);
  }
};
var ConflictingSpecificationError = class extends LuxonError {
};
var InvalidUnitError = class extends LuxonError {
  constructor(unit) {
    super(`Invalid unit ${unit}`);
  }
};
var InvalidArgumentError = class extends LuxonError {
};
var ZoneIsAbstractError = class extends LuxonError {
  constructor() {
    super("Zone is an abstract class");
  }
};

// node_modules/luxon/src/impl/formatter.js
init_esbuild_buffer_shim();

// node_modules/luxon/src/impl/english.js
init_esbuild_buffer_shim();

// node_modules/luxon/src/impl/formats.js
init_esbuild_buffer_shim();
var n = "numeric";
var s = "short";
var l = "long";
var DATE_SHORT = {
  year: n,
  month: n,
  day: n
};
var DATE_MED = {
  year: n,
  month: s,
  day: n
};
var DATE_MED_WITH_WEEKDAY = {
  year: n,
  month: s,
  day: n,
  weekday: s
};
var DATE_FULL = {
  year: n,
  month: l,
  day: n
};
var DATE_HUGE = {
  year: n,
  month: l,
  day: n,
  weekday: l
};
var TIME_SIMPLE = {
  hour: n,
  minute: n
};
var TIME_WITH_SECONDS = {
  hour: n,
  minute: n,
  second: n
};
var TIME_WITH_SHORT_OFFSET = {
  hour: n,
  minute: n,
  second: n,
  timeZoneName: s
};
var TIME_WITH_LONG_OFFSET = {
  hour: n,
  minute: n,
  second: n,
  timeZoneName: l
};
var TIME_24_SIMPLE = {
  hour: n,
  minute: n,
  hourCycle: "h23"
};
var TIME_24_WITH_SECONDS = {
  hour: n,
  minute: n,
  second: n,
  hourCycle: "h23"
};
var TIME_24_WITH_SHORT_OFFSET = {
  hour: n,
  minute: n,
  second: n,
  hourCycle: "h23",
  timeZoneName: s
};
var TIME_24_WITH_LONG_OFFSET = {
  hour: n,
  minute: n,
  second: n,
  hourCycle: "h23",
  timeZoneName: l
};
var DATETIME_SHORT = {
  year: n,
  month: n,
  day: n,
  hour: n,
  minute: n
};
var DATETIME_SHORT_WITH_SECONDS = {
  year: n,
  month: n,
  day: n,
  hour: n,
  minute: n,
  second: n
};
var DATETIME_MED = {
  year: n,
  month: s,
  day: n,
  hour: n,
  minute: n
};
var DATETIME_MED_WITH_SECONDS = {
  year: n,
  month: s,
  day: n,
  hour: n,
  minute: n,
  second: n
};
var DATETIME_MED_WITH_WEEKDAY = {
  year: n,
  month: s,
  day: n,
  weekday: s,
  hour: n,
  minute: n
};
var DATETIME_FULL = {
  year: n,
  month: l,
  day: n,
  hour: n,
  minute: n,
  timeZoneName: s
};
var DATETIME_FULL_WITH_SECONDS = {
  year: n,
  month: l,
  day: n,
  hour: n,
  minute: n,
  second: n,
  timeZoneName: s
};
var DATETIME_HUGE = {
  year: n,
  month: l,
  day: n,
  weekday: l,
  hour: n,
  minute: n,
  timeZoneName: l
};
var DATETIME_HUGE_WITH_SECONDS = {
  year: n,
  month: l,
  day: n,
  weekday: l,
  hour: n,
  minute: n,
  second: n,
  timeZoneName: l
};

// node_modules/luxon/src/impl/util.js
init_esbuild_buffer_shim();

// node_modules/luxon/src/settings.js
init_esbuild_buffer_shim();

// node_modules/luxon/src/zones/systemZone.js
init_esbuild_buffer_shim();

// node_modules/luxon/src/zone.js
init_esbuild_buffer_shim();
var Zone = class {
  /**
   * The type of zone
   * @abstract
   * @type {string}
   */
  get type() {
    throw new ZoneIsAbstractError();
  }
  /**
   * The name of this zone.
   * @abstract
   * @type {string}
   */
  get name() {
    throw new ZoneIsAbstractError();
  }
  /**
   * The IANA name of this zone.
   * Defaults to `name` if not overwritten by a subclass.
   * @abstract
   * @type {string}
   */
  get ianaName() {
    return this.name;
  }
  /**
   * Returns whether the offset is known to be fixed for the whole year.
   * @abstract
   * @type {boolean}
   */
  get isUniversal() {
    throw new ZoneIsAbstractError();
  }
  /**
   * Returns the offset's common name (such as EST) at the specified timestamp
   * @abstract
   * @param {number} ts - Epoch milliseconds for which to get the name
   * @param {Object} opts - Options to affect the format
   * @param {string} opts.format - What style of offset to return. Accepts 'long' or 'short'.
   * @param {string} opts.locale - What locale to return the offset name in.
   * @return {string}
   */
  offsetName(ts, opts) {
    throw new ZoneIsAbstractError();
  }
  /**
   * Returns the offset's value as a string
   * @abstract
   * @param {number} ts - Epoch milliseconds for which to get the offset
   * @param {string} format - What style of offset to return.
   *                          Accepts 'narrow', 'short', or 'techie'. Returning '+6', '+06:00', or '+0600' respectively
   * @return {string}
   */
  formatOffset(ts, format) {
    throw new ZoneIsAbstractError();
  }
  /**
   * Return the offset in minutes for this zone at the specified timestamp.
   * @abstract
   * @param {number} ts - Epoch milliseconds for which to compute the offset
   * @return {number}
   */
  offset(ts) {
    throw new ZoneIsAbstractError();
  }
  /**
   * Return whether this Zone is equal to another zone
   * @abstract
   * @param {Zone} otherZone - the zone to compare
   * @return {boolean}
   */
  equals(otherZone) {
    throw new ZoneIsAbstractError();
  }
  /**
   * Return whether this Zone is valid.
   * @abstract
   * @type {boolean}
   */
  get isValid() {
    throw new ZoneIsAbstractError();
  }
};

// node_modules/luxon/src/zones/systemZone.js
var singleton = null;
var SystemZone = class _SystemZone extends Zone {
  /**
   * Get a singleton instance of the local zone
   * @return {SystemZone}
   */
  static get instance() {
    if (singleton === null) {
      singleton = new _SystemZone();
    }
    return singleton;
  }
  /** @override **/
  get type() {
    return "system";
  }
  /** @override **/
  get name() {
    return new Intl.DateTimeFormat().resolvedOptions().timeZone;
  }
  /** @override **/
  get isUniversal() {
    return false;
  }
  /** @override **/
  offsetName(ts, { format, locale }) {
    return parseZoneInfo(ts, format, locale);
  }
  /** @override **/
  formatOffset(ts, format) {
    return formatOffset(this.offset(ts), format);
  }
  /** @override **/
  offset(ts) {
    return -new Date(ts).getTimezoneOffset();
  }
  /** @override **/
  equals(otherZone) {
    return otherZone.type === "system";
  }
  /** @override **/
  get isValid() {
    return true;
  }
};

// node_modules/luxon/src/zones/IANAZone.js
init_esbuild_buffer_shim();
var dtfCache = /* @__PURE__ */ new Map();
function makeDTF(zoneName) {
  let dtf = dtfCache.get(zoneName);
  if (dtf === void 0) {
    dtf = new Intl.DateTimeFormat("en-US", {
      hour12: false,
      timeZone: zoneName,
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
      second: "2-digit",
      era: "short"
    });
    dtfCache.set(zoneName, dtf);
  }
  return dtf;
}
var typeToPos = {
  year: 0,
  month: 1,
  day: 2,
  era: 3,
  hour: 4,
  minute: 5,
  second: 6
};
function hackyOffset(dtf, date) {
  const formatted = dtf.format(date).replace(/\u200E/g, ""), parsed = /(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(formatted), [, fMonth, fDay, fYear, fadOrBc, fHour, fMinute, fSecond] = parsed;
  return [fYear, fMonth, fDay, fadOrBc, fHour, fMinute, fSecond];
}
function partsOffset(dtf, date) {
  const formatted = dtf.formatToParts(date);
  const filled = [];
  for (let i = 0; i < formatted.length; i++) {
    const { type, value } = formatted[i];
    const pos = typeToPos[type];
    if (type === "era") {
      filled[pos] = value;
    } else if (!isUndefined(pos)) {
      filled[pos] = parseInt(value, 10);
    }
  }
  return filled;
}
var ianaZoneCache = /* @__PURE__ */ new Map();
var IANAZone = class _IANAZone extends Zone {
  /**
   * @param {string} name - Zone name
   * @return {IANAZone}
   */
  static create(name) {
    let zone = ianaZoneCache.get(name);
    if (zone === void 0) {
      ianaZoneCache.set(name, zone = new _IANAZone(name));
    }
    return zone;
  }
  /**
   * Reset local caches. Should only be necessary in testing scenarios.
   * @return {void}
   */
  static resetCache() {
    ianaZoneCache.clear();
    dtfCache.clear();
  }
  /**
   * Returns whether the provided string is a valid specifier. This only checks the string's format, not that the specifier identifies a known zone; see isValidZone for that.
   * @param {string} s - The string to check validity on
   * @example IANAZone.isValidSpecifier("America/New_York") //=> true
   * @example IANAZone.isValidSpecifier("Sport~~blorp") //=> false
   * @deprecated For backward compatibility, this forwards to isValidZone, better use `isValidZone()` directly instead.
   * @return {boolean}
   */
  static isValidSpecifier(s2) {
    return this.isValidZone(s2);
  }
  /**
   * Returns whether the provided string identifies a real zone
   * @param {string} zone - The string to check
   * @example IANAZone.isValidZone("America/New_York") //=> true
   * @example IANAZone.isValidZone("Fantasia/Castle") //=> false
   * @example IANAZone.isValidZone("Sport~~blorp") //=> false
   * @return {boolean}
   */
  static isValidZone(zone) {
    if (!zone) {
      return false;
    }
    try {
      new Intl.DateTimeFormat("en-US", { timeZone: zone }).format();
      return true;
    } catch (e) {
      return false;
    }
  }
  constructor(name) {
    super();
    this.zoneName = name;
    this.valid = _IANAZone.isValidZone(name);
  }
  /**
   * The type of zone. `iana` for all instances of `IANAZone`.
   * @override
   * @type {string}
   */
  get type() {
    return "iana";
  }
  /**
   * The name of this zone (i.e. the IANA zone name).
   * @override
   * @type {string}
   */
  get name() {
    return this.zoneName;
  }
  /**
   * Returns whether the offset is known to be fixed for the whole year:
   * Always returns false for all IANA zones.
   * @override
   * @type {boolean}
   */
  get isUniversal() {
    return false;
  }
  /**
   * Returns the offset's common name (such as EST) at the specified timestamp
   * @override
   * @param {number} ts - Epoch milliseconds for which to get the name
   * @param {Object} opts - Options to affect the format
   * @param {string} opts.format - What style of offset to return. Accepts 'long' or 'short'.
   * @param {string} opts.locale - What locale to return the offset name in.
   * @return {string}
   */
  offsetName(ts, { format, locale }) {
    return parseZoneInfo(ts, format, locale, this.name);
  }
  /**
   * Returns the offset's value as a string
   * @override
   * @param {number} ts - Epoch milliseconds for which to get the offset
   * @param {string} format - What style of offset to return.
   *                          Accepts 'narrow', 'short', or 'techie'. Returning '+6', '+06:00', or '+0600' respectively
   * @return {string}
   */
  formatOffset(ts, format) {
    return formatOffset(this.offset(ts), format);
  }
  /**
   * Return the offset in minutes for this zone at the specified timestamp.
   * @override
   * @param {number} ts - Epoch milliseconds for which to compute the offset
   * @return {number}
   */
  offset(ts) {
    if (!this.valid) return NaN;
    const date = new Date(ts);
    if (isNaN(date)) return NaN;
    const dtf = makeDTF(this.name);
    let [year, month, day, adOrBc, hour, minute, second] = dtf.formatToParts ? partsOffset(dtf, date) : hackyOffset(dtf, date);
    if (adOrBc === "BC") {
      year = -Math.abs(year) + 1;
    }
    const adjustedHour = hour === 24 ? 0 : hour;
    const asUTC = objToLocalTS({
      year,
      month,
      day,
      hour: adjustedHour,
      minute,
      second,
      millisecond: 0
    });
    let asTS = +date;
    const over = asTS % 1e3;
    asTS -= over >= 0 ? over : 1e3 + over;
    return (asUTC - asTS) / (60 * 1e3);
  }
  /**
   * Return whether this Zone is equal to another zone
   * @override
   * @param {Zone} otherZone - the zone to compare
   * @return {boolean}
   */
  equals(otherZone) {
    return otherZone.type === "iana" && otherZone.name === this.name;
  }
  /**
   * Return whether this Zone is valid.
   * @override
   * @type {boolean}
   */
  get isValid() {
    return this.valid;
  }
};

// node_modules/luxon/src/impl/locale.js
init_esbuild_buffer_shim();
var intlLFCache = {};
function getCachedLF(locString, opts = {}) {
  const key = JSON.stringify([locString, opts]);
  let dtf = intlLFCache[key];
  if (!dtf) {
    dtf = new Intl.ListFormat(locString, opts);
    intlLFCache[key] = dtf;
  }
  return dtf;
}
var intlDTCache = /* @__PURE__ */ new Map();
function getCachedDTF(locString, opts = {}) {
  const key = JSON.stringify([locString, opts]);
  let dtf = intlDTCache.get(key);
  if (dtf === void 0) {
    dtf = new Intl.DateTimeFormat(locString, opts);
    intlDTCache.set(key, dtf);
  }
  return dtf;
}
var intlNumCache = /* @__PURE__ */ new Map();
function getCachedINF(locString, opts = {}) {
  const key = JSON.stringify([locString, opts]);
  let inf = intlNumCache.get(key);
  if (inf === void 0) {
    inf = new Intl.NumberFormat(locString, opts);
    intlNumCache.set(key, inf);
  }
  return inf;
}
var intlRelCache = /* @__PURE__ */ new Map();
function getCachedRTF(locString, opts = {}) {
  const { base, ...cacheKeyOpts } = opts;
  const key = JSON.stringify([locString, cacheKeyOpts]);
  let inf = intlRelCache.get(key);
  if (inf === void 0) {
    inf = new Intl.RelativeTimeFormat(locString, opts);
    intlRelCache.set(key, inf);
  }
  return inf;
}
var sysLocaleCache = null;
function systemLocale() {
  if (sysLocaleCache) {
    return sysLocaleCache;
  } else {
    sysLocaleCache = new Intl.DateTimeFormat().resolvedOptions().locale;
    return sysLocaleCache;
  }
}
var intlResolvedOptionsCache = /* @__PURE__ */ new Map();
function getCachedIntResolvedOptions(locString) {
  let opts = intlResolvedOptionsCache.get(locString);
  if (opts === void 0) {
    opts = new Intl.DateTimeFormat(locString).resolvedOptions();
    intlResolvedOptionsCache.set(locString, opts);
  }
  return opts;
}
var weekInfoCache = /* @__PURE__ */ new Map();
function getCachedWeekInfo(locString) {
  let data = weekInfoCache.get(locString);
  if (!data) {
    const locale = new Intl.Locale(locString);
    data = "getWeekInfo" in locale ? locale.getWeekInfo() : locale.weekInfo;
    if (!("minimalDays" in data)) {
      data = { ...fallbackWeekSettings, ...data };
    }
    weekInfoCache.set(locString, data);
  }
  return data;
}
function parseLocaleString(localeStr) {
  const xIndex = localeStr.indexOf("-x-");
  if (xIndex !== -1) {
    localeStr = localeStr.substring(0, xIndex);
  }
  const uIndex = localeStr.indexOf("-u-");
  if (uIndex === -1) {
    return [localeStr];
  } else {
    let options;
    let selectedStr;
    try {
      options = getCachedDTF(localeStr).resolvedOptions();
      selectedStr = localeStr;
    } catch (e) {
      const smaller = localeStr.substring(0, uIndex);
      options = getCachedDTF(smaller).resolvedOptions();
      selectedStr = smaller;
    }
    const { numberingSystem, calendar } = options;
    return [selectedStr, numberingSystem, calendar];
  }
}
function intlConfigString(localeStr, numberingSystem, outputCalendar) {
  if (outputCalendar || numberingSystem) {
    if (!localeStr.includes("-u-")) {
      localeStr += "-u";
    }
    if (outputCalendar) {
      localeStr += `-ca-${outputCalendar}`;
    }
    if (numberingSystem) {
      localeStr += `-nu-${numberingSystem}`;
    }
    return localeStr;
  } else {
    return localeStr;
  }
}
function mapMonths(f) {
  const ms = [];
  for (let i = 1; i <= 12; i++) {
    const dt = DateTime.utc(2009, i, 1);
    ms.push(f(dt));
  }
  return ms;
}
function mapWeekdays(f) {
  const ms = [];
  for (let i = 1; i <= 7; i++) {
    const dt = DateTime.utc(2016, 11, 13 + i);
    ms.push(f(dt));
  }
  return ms;
}
function listStuff(loc, length, englishFn, intlFn) {
  const mode = loc.listingMode();
  if (mode === "error") {
    return null;
  } else if (mode === "en") {
    return englishFn(length);
  } else {
    return intlFn(length);
  }
}
function supportsFastNumbers(loc) {
  if (loc.numberingSystem && loc.numberingSystem !== "latn") {
    return false;
  } else {
    return loc.numberingSystem === "latn" || !loc.locale || loc.locale.startsWith("en") || getCachedIntResolvedOptions(loc.locale).numberingSystem === "latn";
  }
}
var PolyNumberFormatter = class {
  constructor(intl, forceSimple, opts) {
    this.padTo = opts.padTo || 0;
    this.floor = opts.floor || false;
    const { padTo, floor, ...otherOpts } = opts;
    if (!forceSimple || Object.keys(otherOpts).length > 0) {
      const intlOpts = { useGrouping: false, ...opts };
      if (opts.padTo > 0) intlOpts.minimumIntegerDigits = opts.padTo;
      this.inf = getCachedINF(intl, intlOpts);
    }
  }
  format(i) {
    if (this.inf) {
      const fixed = this.floor ? Math.floor(i) : i;
      return this.inf.format(fixed);
    } else {
      const fixed = this.floor ? Math.floor(i) : roundTo(i, 3);
      return padStart(fixed, this.padTo);
    }
  }
};
var PolyDateFormatter = class {
  constructor(dt, intl, opts) {
    this.opts = opts;
    this.originalZone = void 0;
    let z = void 0;
    if (this.opts.timeZone) {
      this.dt = dt;
    } else if (dt.zone.type === "fixed") {
      const gmtOffset = -1 * (dt.offset / 60);
      const offsetZ = gmtOffset >= 0 ? `Etc/GMT+${gmtOffset}` : `Etc/GMT${gmtOffset}`;
      if (dt.offset !== 0 && IANAZone.create(offsetZ).valid) {
        z = offsetZ;
        this.dt = dt;
      } else {
        z = "UTC";
        this.dt = dt.offset === 0 ? dt : dt.setZone("UTC").plus({ minutes: dt.offset });
        this.originalZone = dt.zone;
      }
    } else if (dt.zone.type === "system") {
      this.dt = dt;
    } else if (dt.zone.type === "iana") {
      this.dt = dt;
      z = dt.zone.name;
    } else {
      z = "UTC";
      this.dt = dt.setZone("UTC").plus({ minutes: dt.offset });
      this.originalZone = dt.zone;
    }
    const intlOpts = { ...this.opts };
    intlOpts.timeZone = intlOpts.timeZone || z;
    this.dtf = getCachedDTF(intl, intlOpts);
  }
  format() {
    if (this.originalZone) {
      return this.formatToParts().map(({ value }) => value).join("");
    }
    return this.dtf.format(this.dt.toJSDate());
  }
  formatToParts() {
    const parts = this.dtf.formatToParts(this.dt.toJSDate());
    if (this.originalZone) {
      return parts.map((part) => {
        if (part.type === "timeZoneName") {
          const offsetName = this.originalZone.offsetName(this.dt.ts, {
            locale: this.dt.locale,
            format: this.opts.timeZoneName
          });
          return {
            ...part,
            value: offsetName
          };
        } else {
          return part;
        }
      });
    }
    return parts;
  }
  resolvedOptions() {
    return this.dtf.resolvedOptions();
  }
};
var PolyRelFormatter = class {
  constructor(intl, isEnglish, opts) {
    this.opts = { style: "long", ...opts };
    if (!isEnglish && hasRelative()) {
      this.rtf = getCachedRTF(intl, opts);
    }
  }
  format(count, unit) {
    if (this.rtf) {
      return this.rtf.format(count, unit);
    } else {
      return formatRelativeTime(unit, count, this.opts.numeric, this.opts.style !== "long");
    }
  }
  formatToParts(count, unit) {
    if (this.rtf) {
      return this.rtf.formatToParts(count, unit);
    } else {
      return [];
    }
  }
};
var fallbackWeekSettings = {
  firstDay: 1,
  minimalDays: 4,
  weekend: [6, 7]
};
var Locale = class _Locale {
  static fromOpts(opts) {
    return _Locale.create(
      opts.locale,
      opts.numberingSystem,
      opts.outputCalendar,
      opts.weekSettings,
      opts.defaultToEN
    );
  }
  static create(locale, numberingSystem, outputCalendar, weekSettings, defaultToEN = false) {
    const specifiedLocale = locale || Settings.defaultLocale;
    const localeR = specifiedLocale || (defaultToEN ? "en-US" : systemLocale());
    const numberingSystemR = numberingSystem || Settings.defaultNumberingSystem;
    const outputCalendarR = outputCalendar || Settings.defaultOutputCalendar;
    const weekSettingsR = validateWeekSettings(weekSettings) || Settings.defaultWeekSettings;
    return new _Locale(localeR, numberingSystemR, outputCalendarR, weekSettingsR, specifiedLocale);
  }
  static resetCache() {
    sysLocaleCache = null;
    intlDTCache.clear();
    intlNumCache.clear();
    intlRelCache.clear();
    intlResolvedOptionsCache.clear();
    weekInfoCache.clear();
  }
  static fromObject({ locale, numberingSystem, outputCalendar, weekSettings } = {}) {
    return _Locale.create(locale, numberingSystem, outputCalendar, weekSettings);
  }
  constructor(locale, numbering, outputCalendar, weekSettings, specifiedLocale) {
    const [parsedLocale, parsedNumberingSystem, parsedOutputCalendar] = parseLocaleString(locale);
    this.locale = parsedLocale;
    this.numberingSystem = numbering || parsedNumberingSystem || null;
    this.outputCalendar = outputCalendar || parsedOutputCalendar || null;
    this.weekSettings = weekSettings;
    this.intl = intlConfigString(this.locale, this.numberingSystem, this.outputCalendar);
    this.weekdaysCache = { format: {}, standalone: {} };
    this.monthsCache = { format: {}, standalone: {} };
    this.meridiemCache = null;
    this.eraCache = {};
    this.specifiedLocale = specifiedLocale;
    this.fastNumbersCached = null;
  }
  get fastNumbers() {
    if (this.fastNumbersCached == null) {
      this.fastNumbersCached = supportsFastNumbers(this);
    }
    return this.fastNumbersCached;
  }
  listingMode() {
    const isActuallyEn = this.isEnglish();
    const hasNoWeirdness = (this.numberingSystem === null || this.numberingSystem === "latn") && (this.outputCalendar === null || this.outputCalendar === "gregory");
    return isActuallyEn && hasNoWeirdness ? "en" : "intl";
  }
  clone(alts) {
    if (!alts || Object.getOwnPropertyNames(alts).length === 0) {
      return this;
    } else {
      return _Locale.create(
        alts.locale || this.specifiedLocale,
        alts.numberingSystem || this.numberingSystem,
        alts.outputCalendar || this.outputCalendar,
        validateWeekSettings(alts.weekSettings) || this.weekSettings,
        alts.defaultToEN || false
      );
    }
  }
  redefaultToEN(alts = {}) {
    return this.clone({ ...alts, defaultToEN: true });
  }
  redefaultToSystem(alts = {}) {
    return this.clone({ ...alts, defaultToEN: false });
  }
  months(length, format = false) {
    return listStuff(this, length, months, () => {
      const intl = format ? { month: length, day: "numeric" } : { month: length }, formatStr = format ? "format" : "standalone";
      if (!this.monthsCache[formatStr][length]) {
        this.monthsCache[formatStr][length] = mapMonths((dt) => this.extract(dt, intl, "month"));
      }
      return this.monthsCache[formatStr][length];
    });
  }
  weekdays(length, format = false) {
    return listStuff(this, length, weekdays, () => {
      const intl = format ? { weekday: length, year: "numeric", month: "long", day: "numeric" } : { weekday: length }, formatStr = format ? "format" : "standalone";
      if (!this.weekdaysCache[formatStr][length]) {
        this.weekdaysCache[formatStr][length] = mapWeekdays(
          (dt) => this.extract(dt, intl, "weekday")
        );
      }
      return this.weekdaysCache[formatStr][length];
    });
  }
  meridiems() {
    return listStuff(
      this,
      void 0,
      () => meridiems,
      () => {
        if (!this.meridiemCache) {
          const intl = { hour: "numeric", hourCycle: "h12" };
          this.meridiemCache = [DateTime.utc(2016, 11, 13, 9), DateTime.utc(2016, 11, 13, 19)].map(
            (dt) => this.extract(dt, intl, "dayperiod")
          );
        }
        return this.meridiemCache;
      }
    );
  }
  eras(length) {
    return listStuff(this, length, eras, () => {
      const intl = { era: length };
      if (!this.eraCache[length]) {
        this.eraCache[length] = [DateTime.utc(-40, 1, 1), DateTime.utc(2017, 1, 1)].map(
          (dt) => this.extract(dt, intl, "era")
        );
      }
      return this.eraCache[length];
    });
  }
  extract(dt, intlOpts, field) {
    const df = this.dtFormatter(dt, intlOpts), results = df.formatToParts(), matching = results.find((m) => m.type.toLowerCase() === field);
    return matching ? matching.value : null;
  }
  numberFormatter(opts = {}) {
    return new PolyNumberFormatter(this.intl, opts.forceSimple || this.fastNumbers, opts);
  }
  dtFormatter(dt, intlOpts = {}) {
    return new PolyDateFormatter(dt, this.intl, intlOpts);
  }
  relFormatter(opts = {}) {
    return new PolyRelFormatter(this.intl, this.isEnglish(), opts);
  }
  listFormatter(opts = {}) {
    return getCachedLF(this.intl, opts);
  }
  isEnglish() {
    return this.locale === "en" || this.locale.toLowerCase() === "en-us" || getCachedIntResolvedOptions(this.intl).locale.startsWith("en-us");
  }
  getWeekSettings() {
    if (this.weekSettings) {
      return this.weekSettings;
    } else if (!hasLocaleWeekInfo()) {
      return fallbackWeekSettings;
    } else {
      return getCachedWeekInfo(this.locale);
    }
  }
  getStartOfWeek() {
    return this.getWeekSettings().firstDay;
  }
  getMinDaysInFirstWeek() {
    return this.getWeekSettings().minimalDays;
  }
  getWeekendDays() {
    return this.getWeekSettings().weekend;
  }
  equals(other) {
    return this.locale === other.locale && this.numberingSystem === other.numberingSystem && this.outputCalendar === other.outputCalendar;
  }
  toString() {
    return `Locale(${this.locale}, ${this.numberingSystem}, ${this.outputCalendar})`;
  }
};

// node_modules/luxon/src/impl/zoneUtil.js
init_esbuild_buffer_shim();

// node_modules/luxon/src/zones/fixedOffsetZone.js
init_esbuild_buffer_shim();
var singleton2 = null;
var FixedOffsetZone = class _FixedOffsetZone extends Zone {
  /**
   * Get a singleton instance of UTC
   * @return {FixedOffsetZone}
   */
  static get utcInstance() {
    if (singleton2 === null) {
      singleton2 = new _FixedOffsetZone(0);
    }
    return singleton2;
  }
  /**
   * Get an instance with a specified offset
   * @param {number} offset - The offset in minutes
   * @return {FixedOffsetZone}
   */
  static instance(offset2) {
    return offset2 === 0 ? _FixedOffsetZone.utcInstance : new _FixedOffsetZone(offset2);
  }
  /**
   * Get an instance of FixedOffsetZone from a UTC offset string, like "UTC+6"
   * @param {string} s - The offset string to parse
   * @example FixedOffsetZone.parseSpecifier("UTC+6")
   * @example FixedOffsetZone.parseSpecifier("UTC+06")
   * @example FixedOffsetZone.parseSpecifier("UTC-6:00")
   * @return {FixedOffsetZone}
   */
  static parseSpecifier(s2) {
    if (s2) {
      const r = s2.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);
      if (r) {
        return new _FixedOffsetZone(signedOffset(r[1], r[2]));
      }
    }
    return null;
  }
  constructor(offset2) {
    super();
    this.fixed = offset2;
  }
  /**
   * The type of zone. `fixed` for all instances of `FixedOffsetZone`.
   * @override
   * @type {string}
   */
  get type() {
    return "fixed";
  }
  /**
   * The name of this zone.
   * All fixed zones' names always start with "UTC" (plus optional offset)
   * @override
   * @type {string}
   */
  get name() {
    return this.fixed === 0 ? "UTC" : `UTC${formatOffset(this.fixed, "narrow")}`;
  }
  /**
   * The IANA name of this zone, i.e. `Etc/UTC` or `Etc/GMT+/-nn`
   *
   * @override
   * @type {string}
   */
  get ianaName() {
    if (this.fixed === 0) {
      return "Etc/UTC";
    } else {
      return `Etc/GMT${formatOffset(-this.fixed, "narrow")}`;
    }
  }
  /**
   * Returns the offset's common name at the specified timestamp.
   *
   * For fixed offset zones this equals to the zone name.
   * @override
   */
  offsetName() {
    return this.name;
  }
  /**
   * Returns the offset's value as a string
   * @override
   * @param {number} ts - Epoch milliseconds for which to get the offset
   * @param {string} format - What style of offset to return.
   *                          Accepts 'narrow', 'short', or 'techie'. Returning '+6', '+06:00', or '+0600' respectively
   * @return {string}
   */
  formatOffset(ts, format) {
    return formatOffset(this.fixed, format);
  }
  /**
   * Returns whether the offset is known to be fixed for the whole year:
   * Always returns true for all fixed offset zones.
   * @override
   * @type {boolean}
   */
  get isUniversal() {
    return true;
  }
  /**
   * Return the offset in minutes for this zone at the specified timestamp.
   *
   * For fixed offset zones, this is constant and does not depend on a timestamp.
   * @override
   * @return {number}
   */
  offset() {
    return this.fixed;
  }
  /**
   * Return whether this Zone is equal to another zone (i.e. also fixed and same offset)
   * @override
   * @param {Zone} otherZone - the zone to compare
   * @return {boolean}
   */
  equals(otherZone) {
    return otherZone.type === "fixed" && otherZone.fixed === this.fixed;
  }
  /**
   * Return whether this Zone is valid:
   * All fixed offset zones are valid.
   * @override
   * @type {boolean}
   */
  get isValid() {
    return true;
  }
};

// node_modules/luxon/src/zones/invalidZone.js
init_esbuild_buffer_shim();
var InvalidZone = class extends Zone {
  constructor(zoneName) {
    super();
    this.zoneName = zoneName;
  }
  /** @override **/
  get type() {
    return "invalid";
  }
  /** @override **/
  get name() {
    return this.zoneName;
  }
  /** @override **/
  get isUniversal() {
    return false;
  }
  /** @override **/
  offsetName() {
    return null;
  }
  /** @override **/
  formatOffset() {
    return "";
  }
  /** @override **/
  offset() {
    return NaN;
  }
  /** @override **/
  equals() {
    return false;
  }
  /** @override **/
  get isValid() {
    return false;
  }
};

// node_modules/luxon/src/impl/zoneUtil.js
function normalizeZone(input, defaultZone2) {
  let offset2;
  if (isUndefined(input) || input === null) {
    return defaultZone2;
  } else if (input instanceof Zone) {
    return input;
  } else if (isString(input)) {
    const lowered = input.toLowerCase();
    if (lowered === "default") return defaultZone2;
    else if (lowered === "local" || lowered === "system") return SystemZone.instance;
    else if (lowered === "utc" || lowered === "gmt") return FixedOffsetZone.utcInstance;
    else return FixedOffsetZone.parseSpecifier(lowered) || IANAZone.create(input);
  } else if (isNumber(input)) {
    return FixedOffsetZone.instance(input);
  } else if (typeof input === "object" && "offset" in input && typeof input.offset === "function") {
    return input;
  } else {
    return new InvalidZone(input);
  }
}

// node_modules/luxon/src/impl/digits.js
init_esbuild_buffer_shim();
var numberingSystems = {
  arab: "[\u0660-\u0669]",
  arabext: "[\u06F0-\u06F9]",
  bali: "[\u1B50-\u1B59]",
  beng: "[\u09E6-\u09EF]",
  deva: "[\u0966-\u096F]",
  fullwide: "[\uFF10-\uFF19]",
  gujr: "[\u0AE6-\u0AEF]",
  hanidec: "[\u3007|\u4E00|\u4E8C|\u4E09|\u56DB|\u4E94|\u516D|\u4E03|\u516B|\u4E5D]",
  khmr: "[\u17E0-\u17E9]",
  knda: "[\u0CE6-\u0CEF]",
  laoo: "[\u0ED0-\u0ED9]",
  limb: "[\u1946-\u194F]",
  mlym: "[\u0D66-\u0D6F]",
  mong: "[\u1810-\u1819]",
  mymr: "[\u1040-\u1049]",
  orya: "[\u0B66-\u0B6F]",
  tamldec: "[\u0BE6-\u0BEF]",
  telu: "[\u0C66-\u0C6F]",
  thai: "[\u0E50-\u0E59]",
  tibt: "[\u0F20-\u0F29]",
  latn: "\\d"
};
var numberingSystemsUTF16 = {
  arab: [1632, 1641],
  arabext: [1776, 1785],
  bali: [6992, 7001],
  beng: [2534, 2543],
  deva: [2406, 2415],
  fullwide: [65296, 65303],
  gujr: [2790, 2799],
  khmr: [6112, 6121],
  knda: [3302, 3311],
  laoo: [3792, 3801],
  limb: [6470, 6479],
  mlym: [3430, 3439],
  mong: [6160, 6169],
  mymr: [4160, 4169],
  orya: [2918, 2927],
  tamldec: [3046, 3055],
  telu: [3174, 3183],
  thai: [3664, 3673],
  tibt: [3872, 3881]
};
var hanidecChars = numberingSystems.hanidec.replace(/[\[|\]]/g, "").split("");
function parseDigits(str) {
  let value = parseInt(str, 10);
  if (isNaN(value)) {
    value = "";
    for (let i = 0; i < str.length; i++) {
      const code = str.charCodeAt(i);
      if (str[i].search(numberingSystems.hanidec) !== -1) {
        value += hanidecChars.indexOf(str[i]);
      } else {
        for (const key in numberingSystemsUTF16) {
          const [min, max] = numberingSystemsUTF16[key];
          if (code >= min && code <= max) {
            value += code - min;
          }
        }
      }
    }
    return parseInt(value, 10);
  } else {
    return value;
  }
}
var digitRegexCache = /* @__PURE__ */ new Map();
function resetDigitRegexCache() {
  digitRegexCache.clear();
}
function digitRegex({ numberingSystem }, append2 = "") {
  const ns = numberingSystem || "latn";
  let appendCache = digitRegexCache.get(ns);
  if (appendCache === void 0) {
    appendCache = /* @__PURE__ */ new Map();
    digitRegexCache.set(ns, appendCache);
  }
  let regex = appendCache.get(append2);
  if (regex === void 0) {
    regex = new RegExp(`${numberingSystems[ns]}${append2}`);
    appendCache.set(append2, regex);
  }
  return regex;
}

// node_modules/luxon/src/settings.js
var now = () => Date.now();
var defaultZone = "system";
var defaultLocale = null;
var defaultNumberingSystem = null;
var defaultOutputCalendar = null;
var twoDigitCutoffYear = 60;
var throwOnInvalid;
var defaultWeekSettings = null;
var Settings = class {
  /**
   * Get the callback for returning the current timestamp.
   * @type {function}
   */
  static get now() {
    return now;
  }
  /**
   * Set the callback for returning the current timestamp.
   * The function should return a number, which will be interpreted as an Epoch millisecond count
   * @type {function}
   * @example Settings.now = () => Date.now() + 3000 // pretend it is 3 seconds in the future
   * @example Settings.now = () => 0 // always pretend it's Jan 1, 1970 at midnight in UTC time
   */
  static set now(n2) {
    now = n2;
  }
  /**
   * Set the default time zone to create DateTimes in. Does not affect existing instances.
   * Use the value "system" to reset this value to the system's time zone.
   * @type {string}
   */
  static set defaultZone(zone) {
    defaultZone = zone;
  }
  /**
   * Get the default time zone object currently used to create DateTimes. Does not affect existing instances.
   * The default value is the system's time zone (the one set on the machine that runs this code).
   * @type {Zone}
   */
  static get defaultZone() {
    return normalizeZone(defaultZone, SystemZone.instance);
  }
  /**
   * Get the default locale to create DateTimes with. Does not affect existing instances.
   * @type {string}
   */
  static get defaultLocale() {
    return defaultLocale;
  }
  /**
   * Set the default locale to create DateTimes with. Does not affect existing instances.
   * @type {string}
   */
  static set defaultLocale(locale) {
    defaultLocale = locale;
  }
  /**
   * Get the default numbering system to create DateTimes with. Does not affect existing instances.
   * @type {string}
   */
  static get defaultNumberingSystem() {
    return defaultNumberingSystem;
  }
  /**
   * Set the default numbering system to create DateTimes with. Does not affect existing instances.
   * @type {string}
   */
  static set defaultNumberingSystem(numberingSystem) {
    defaultNumberingSystem = numberingSystem;
  }
  /**
   * Get the default output calendar to create DateTimes with. Does not affect existing instances.
   * @type {string}
   */
  static get defaultOutputCalendar() {
    return defaultOutputCalendar;
  }
  /**
   * Set the default output calendar to create DateTimes with. Does not affect existing instances.
   * @type {string}
   */
  static set defaultOutputCalendar(outputCalendar) {
    defaultOutputCalendar = outputCalendar;
  }
  /**
   * @typedef {Object} WeekSettings
   * @property {number} firstDay
   * @property {number} minimalDays
   * @property {number[]} weekend
   */
  /**
   * @return {WeekSettings|null}
   */
  static get defaultWeekSettings() {
    return defaultWeekSettings;
  }
  /**
   * Allows overriding the default locale week settings, i.e. the start of the week, the weekend and
   * how many days are required in the first week of a year.
   * Does not affect existing instances.
   *
   * @param {WeekSettings|null} weekSettings
   */
  static set defaultWeekSettings(weekSettings) {
    defaultWeekSettings = validateWeekSettings(weekSettings);
  }
  /**
   * Get the cutoff year for whether a 2-digit year string is interpreted in the current or previous century. Numbers higher than the cutoff will be considered to mean 19xx and numbers lower or equal to the cutoff will be considered 20xx.
   * @type {number}
   */
  static get twoDigitCutoffYear() {
    return twoDigitCutoffYear;
  }
  /**
   * Set the cutoff year for whether a 2-digit year string is interpreted in the current or previous century. Numbers higher than the cutoff will be considered to mean 19xx and numbers lower or equal to the cutoff will be considered 20xx.
   * @type {number}
   * @example Settings.twoDigitCutoffYear = 0 // all 'yy' are interpreted as 20th century
   * @example Settings.twoDigitCutoffYear = 99 // all 'yy' are interpreted as 21st century
   * @example Settings.twoDigitCutoffYear = 50 // '49' -> 2049; '50' -> 1950
   * @example Settings.twoDigitCutoffYear = 1950 // interpreted as 50
   * @example Settings.twoDigitCutoffYear = 2050 // ALSO interpreted as 50
   */
  static set twoDigitCutoffYear(cutoffYear) {
    twoDigitCutoffYear = cutoffYear % 100;
  }
  /**
   * Get whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals
   * @type {boolean}
   */
  static get throwOnInvalid() {
    return throwOnInvalid;
  }
  /**
   * Set whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals
   * @type {boolean}
   */
  static set throwOnInvalid(t) {
    throwOnInvalid = t;
  }
  /**
   * Reset Luxon's global caches. Should only be necessary in testing scenarios.
   * @return {void}
   */
  static resetCaches() {
    Locale.resetCache();
    IANAZone.resetCache();
    DateTime.resetCache();
    resetDigitRegexCache();
  }
};

// node_modules/luxon/src/impl/conversions.js
init_esbuild_buffer_shim();

// node_modules/luxon/src/impl/invalid.js
init_esbuild_buffer_shim();
var Invalid = class {
  constructor(reason, explanation) {
    this.reason = reason;
    this.explanation = explanation;
  }
  toMessage() {
    if (this.explanation) {
      return `${this.reason}: ${this.explanation}`;
    } else {
      return this.reason;
    }
  }
};

// node_modules/luxon/src/impl/conversions.js
var nonLeapLadder = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
var leapLadder = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335];
function unitOutOfRange(unit, value) {
  return new Invalid(
    "unit out of range",
    `you specified ${value} (of type ${typeof value}) as a ${unit}, which is invalid`
  );
}
function dayOfWeek(year, month, day) {
  const d = new Date(Date.UTC(year, month - 1, day));
  if (year < 100 && year >= 0) {
    d.setUTCFullYear(d.getUTCFullYear() - 1900);
  }
  const js = d.getUTCDay();
  return js === 0 ? 7 : js;
}
function computeOrdinal(year, month, day) {
  return day + (isLeapYear(year) ? leapLadder : nonLeapLadder)[month - 1];
}
function uncomputeOrdinal(year, ordinal) {
  const table = isLeapYear(year) ? leapLadder : nonLeapLadder, month0 = table.findIndex((i) => i < ordinal), day = ordinal - table[month0];
  return { month: month0 + 1, day };
}
function isoWeekdayToLocal(isoWeekday, startOfWeek) {
  return (isoWeekday - startOfWeek + 7) % 7 + 1;
}
function gregorianToWeek(gregObj, minDaysInFirstWeek = 4, startOfWeek = 1) {
  const { year, month, day } = gregObj, ordinal = computeOrdinal(year, month, day), weekday = isoWeekdayToLocal(dayOfWeek(year, month, day), startOfWeek);
  let weekNumber = Math.floor((ordinal - weekday + 14 - minDaysInFirstWeek) / 7), weekYear;
  if (weekNumber < 1) {
    weekYear = year - 1;
    weekNumber = weeksInWeekYear(weekYear, minDaysInFirstWeek, startOfWeek);
  } else if (weekNumber > weeksInWeekYear(year, minDaysInFirstWeek, startOfWeek)) {
    weekYear = year + 1;
    weekNumber = 1;
  } else {
    weekYear = year;
  }
  return { weekYear, weekNumber, weekday, ...timeObject(gregObj) };
}
function weekToGregorian(weekData, minDaysInFirstWeek = 4, startOfWeek = 1) {
  const { weekYear, weekNumber, weekday } = weekData, weekdayOfJan4 = isoWeekdayToLocal(dayOfWeek(weekYear, 1, minDaysInFirstWeek), startOfWeek), yearInDays = daysInYear(weekYear);
  let ordinal = weekNumber * 7 + weekday - weekdayOfJan4 - 7 + minDaysInFirstWeek, year;
  if (ordinal < 1) {
    year = weekYear - 1;
    ordinal += daysInYear(year);
  } else if (ordinal > yearInDays) {
    year = weekYear + 1;
    ordinal -= daysInYear(weekYear);
  } else {
    year = weekYear;
  }
  const { month, day } = uncomputeOrdinal(year, ordinal);
  return { year, month, day, ...timeObject(weekData) };
}
function gregorianToOrdinal(gregData) {
  const { year, month, day } = gregData;
  const ordinal = computeOrdinal(year, month, day);
  return { year, ordinal, ...timeObject(gregData) };
}
function ordinalToGregorian(ordinalData) {
  const { year, ordinal } = ordinalData;
  const { month, day } = uncomputeOrdinal(year, ordinal);
  return { year, month, day, ...timeObject(ordinalData) };
}
function usesLocalWeekValues(obj, loc) {
  const hasLocaleWeekData = !isUndefined(obj.localWeekday) || !isUndefined(obj.localWeekNumber) || !isUndefined(obj.localWeekYear);
  if (hasLocaleWeekData) {
    const hasIsoWeekData = !isUndefined(obj.weekday) || !isUndefined(obj.weekNumber) || !isUndefined(obj.weekYear);
    if (hasIsoWeekData) {
      throw new ConflictingSpecificationError(
        "Cannot mix locale-based week fields with ISO-based week fields"
      );
    }
    if (!isUndefined(obj.localWeekday)) obj.weekday = obj.localWeekday;
    if (!isUndefined(obj.localWeekNumber)) obj.weekNumber = obj.localWeekNumber;
    if (!isUndefined(obj.localWeekYear)) obj.weekYear = obj.localWeekYear;
    delete obj.localWeekday;
    delete obj.localWeekNumber;
    delete obj.localWeekYear;
    return {
      minDaysInFirstWeek: loc.getMinDaysInFirstWeek(),
      startOfWeek: loc.getStartOfWeek()
    };
  } else {
    return { minDaysInFirstWeek: 4, startOfWeek: 1 };
  }
}
function hasInvalidWeekData(obj, minDaysInFirstWeek = 4, startOfWeek = 1) {
  const validYear = isInteger(obj.weekYear), validWeek = integerBetween(
    obj.weekNumber,
    1,
    weeksInWeekYear(obj.weekYear, minDaysInFirstWeek, startOfWeek)
  ), validWeekday = integerBetween(obj.weekday, 1, 7);
  if (!validYear) {
    return unitOutOfRange("weekYear", obj.weekYear);
  } else if (!validWeek) {
    return unitOutOfRange("week", obj.weekNumber);
  } else if (!validWeekday) {
    return unitOutOfRange("weekday", obj.weekday);
  } else return false;
}
function hasInvalidOrdinalData(obj) {
  const validYear = isInteger(obj.year), validOrdinal = integerBetween(obj.ordinal, 1, daysInYear(obj.year));
  if (!validYear) {
    return unitOutOfRange("year", obj.year);
  } else if (!validOrdinal) {
    return unitOutOfRange("ordinal", obj.ordinal);
  } else return false;
}
function hasInvalidGregorianData(obj) {
  const validYear = isInteger(obj.year), validMonth = integerBetween(obj.month, 1, 12), validDay = integerBetween(obj.day, 1, daysInMonth(obj.year, obj.month));
  if (!validYear) {
    return unitOutOfRange("year", obj.year);
  } else if (!validMonth) {
    return unitOutOfRange("month", obj.month);
  } else if (!validDay) {
    return unitOutOfRange("day", obj.day);
  } else return false;
}
function hasInvalidTimeData(obj) {
  const { hour, minute, second, millisecond } = obj;
  const validHour = integerBetween(hour, 0, 23) || hour === 24 && minute === 0 && second === 0 && millisecond === 0, validMinute = integerBetween(minute, 0, 59), validSecond = integerBetween(second, 0, 59), validMillisecond = integerBetween(millisecond, 0, 999);
  if (!validHour) {
    return unitOutOfRange("hour", hour);
  } else if (!validMinute) {
    return unitOutOfRange("minute", minute);
  } else if (!validSecond) {
    return unitOutOfRange("second", second);
  } else if (!validMillisecond) {
    return unitOutOfRange("millisecond", millisecond);
  } else return false;
}

// node_modules/luxon/src/impl/util.js
function isUndefined(o) {
  return typeof o === "undefined";
}
function isNumber(o) {
  return typeof o === "number";
}
function isInteger(o) {
  return typeof o === "number" && o % 1 === 0;
}
function isString(o) {
  return typeof o === "string";
}
function isDate(o) {
  return Object.prototype.toString.call(o) === "[object Date]";
}
function hasRelative() {
  try {
    return typeof Intl !== "undefined" && !!Intl.RelativeTimeFormat;
  } catch (e) {
    return false;
  }
}
function hasLocaleWeekInfo() {
  try {
    return typeof Intl !== "undefined" && !!Intl.Locale && ("weekInfo" in Intl.Locale.prototype || "getWeekInfo" in Intl.Locale.prototype);
  } catch (e) {
    return false;
  }
}
function maybeArray(thing) {
  return Array.isArray(thing) ? thing : [thing];
}
function bestBy(arr, by, compare3) {
  if (arr.length === 0) {
    return void 0;
  }
  return arr.reduce((best, next) => {
    const pair = [by(next), next];
    if (!best) {
      return pair;
    } else if (compare3(best[0], pair[0]) === best[0]) {
      return best;
    } else {
      return pair;
    }
  }, null)[1];
}
function pick(obj, keys) {
  return keys.reduce((a, k) => {
    a[k] = obj[k];
    return a;
  }, {});
}
function hasOwnProperty(obj, prop) {
  return Object.prototype.hasOwnProperty.call(obj, prop);
}
function validateWeekSettings(settings) {
  if (settings == null) {
    return null;
  } else if (typeof settings !== "object") {
    throw new InvalidArgumentError("Week settings must be an object");
  } else {
    if (!integerBetween(settings.firstDay, 1, 7) || !integerBetween(settings.minimalDays, 1, 7) || !Array.isArray(settings.weekend) || settings.weekend.some((v) => !integerBetween(v, 1, 7))) {
      throw new InvalidArgumentError("Invalid week settings");
    }
    return {
      firstDay: settings.firstDay,
      minimalDays: settings.minimalDays,
      weekend: Array.from(settings.weekend)
    };
  }
}
function integerBetween(thing, bottom, top) {
  return isInteger(thing) && thing >= bottom && thing <= top;
}
function floorMod(x, n2) {
  return x - n2 * Math.floor(x / n2);
}
function padStart(input, n2 = 2) {
  const isNeg = input < 0;
  let padded;
  if (isNeg) {
    padded = "-" + ("" + -input).padStart(n2, "0");
  } else {
    padded = ("" + input).padStart(n2, "0");
  }
  return padded;
}
function parseInteger(string) {
  if (isUndefined(string) || string === null || string === "") {
    return void 0;
  } else {
    return parseInt(string, 10);
  }
}
function parseFloating(string) {
  if (isUndefined(string) || string === null || string === "") {
    return void 0;
  } else {
    return parseFloat(string);
  }
}
function parseMillis(fraction) {
  if (isUndefined(fraction) || fraction === null || fraction === "") {
    return void 0;
  } else {
    const f = parseFloat("0." + fraction) * 1e3;
    return Math.floor(f);
  }
}
function roundTo(number, digits, towardZero = false) {
  const factor = 10 ** digits, rounder = towardZero ? Math.trunc : Math.round;
  return rounder(number * factor) / factor;
}
function isLeapYear(year) {
  return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
}
function daysInYear(year) {
  return isLeapYear(year) ? 366 : 365;
}
function daysInMonth(year, month) {
  const modMonth = floorMod(month - 1, 12) + 1, modYear = year + (month - modMonth) / 12;
  if (modMonth === 2) {
    return isLeapYear(modYear) ? 29 : 28;
  } else {
    return [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][modMonth - 1];
  }
}
function objToLocalTS(obj) {
  let d = Date.UTC(
    obj.year,
    obj.month - 1,
    obj.day,
    obj.hour,
    obj.minute,
    obj.second,
    obj.millisecond
  );
  if (obj.year < 100 && obj.year >= 0) {
    d = new Date(d);
    d.setUTCFullYear(obj.year, obj.month - 1, obj.day);
  }
  return +d;
}
function firstWeekOffset(year, minDaysInFirstWeek, startOfWeek) {
  const fwdlw = isoWeekdayToLocal(dayOfWeek(year, 1, minDaysInFirstWeek), startOfWeek);
  return -fwdlw + minDaysInFirstWeek - 1;
}
function weeksInWeekYear(weekYear, minDaysInFirstWeek = 4, startOfWeek = 1) {
  const weekOffset = firstWeekOffset(weekYear, minDaysInFirstWeek, startOfWeek);
  const weekOffsetNext = firstWeekOffset(weekYear + 1, minDaysInFirstWeek, startOfWeek);
  return (daysInYear(weekYear) - weekOffset + weekOffsetNext) / 7;
}
function untruncateYear(year) {
  if (year > 99) {
    return year;
  } else return year > Settings.twoDigitCutoffYear ? 1900 + year : 2e3 + year;
}
function parseZoneInfo(ts, offsetFormat, locale, timeZone = null) {
  const date = new Date(ts), intlOpts = {
    hourCycle: "h23",
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit"
  };
  if (timeZone) {
    intlOpts.timeZone = timeZone;
  }
  const modified = { timeZoneName: offsetFormat, ...intlOpts };
  const parsed = new Intl.DateTimeFormat(locale, modified).formatToParts(date).find((m) => m.type.toLowerCase() === "timezonename");
  return parsed ? parsed.value : null;
}
function signedOffset(offHourStr, offMinuteStr) {
  let offHour = parseInt(offHourStr, 10);
  if (Number.isNaN(offHour)) {
    offHour = 0;
  }
  const offMin = parseInt(offMinuteStr, 10) || 0, offMinSigned = offHour < 0 || Object.is(offHour, -0) ? -offMin : offMin;
  return offHour * 60 + offMinSigned;
}
function asNumber(value) {
  const numericValue = Number(value);
  if (typeof value === "boolean" || value === "" || Number.isNaN(numericValue))
    throw new InvalidArgumentError(`Invalid unit value ${value}`);
  return numericValue;
}
function normalizeObject(obj, normalizer) {
  const normalized = {};
  for (const u in obj) {
    if (hasOwnProperty(obj, u)) {
      const v = obj[u];
      if (v === void 0 || v === null) continue;
      normalized[normalizer(u)] = asNumber(v);
    }
  }
  return normalized;
}
function formatOffset(offset2, format) {
  const hours = Math.trunc(Math.abs(offset2 / 60)), minutes = Math.trunc(Math.abs(offset2 % 60)), sign = offset2 >= 0 ? "+" : "-";
  switch (format) {
    case "short":
      return `${sign}${padStart(hours, 2)}:${padStart(minutes, 2)}`;
    case "narrow":
      return `${sign}${hours}${minutes > 0 ? `:${minutes}` : ""}`;
    case "techie":
      return `${sign}${padStart(hours, 2)}${padStart(minutes, 2)}`;
    default:
      throw new RangeError(`Value format ${format} is out of range for property format`);
  }
}
function timeObject(obj) {
  return pick(obj, ["hour", "minute", "second", "millisecond"]);
}

// node_modules/luxon/src/impl/english.js
var monthsLong = [
  "January",
  "February",
  "March",
  "April",
  "May",
  "June",
  "July",
  "August",
  "September",
  "October",
  "November",
  "December"
];
var monthsShort = [
  "Jan",
  "Feb",
  "Mar",
  "Apr",
  "May",
  "Jun",
  "Jul",
  "Aug",
  "Sep",
  "Oct",
  "Nov",
  "Dec"
];
var monthsNarrow = ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"];
function months(length) {
  switch (length) {
    case "narrow":
      return [...monthsNarrow];
    case "short":
      return [...monthsShort];
    case "long":
      return [...monthsLong];
    case "numeric":
      return ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"];
    case "2-digit":
      return ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];
    default:
      return null;
  }
}
var weekdaysLong = [
  "Monday",
  "Tuesday",
  "Wednesday",
  "Thursday",
  "Friday",
  "Saturday",
  "Sunday"
];
var weekdaysShort = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
var weekdaysNarrow = ["M", "T", "W", "T", "F", "S", "S"];
function weekdays(length) {
  switch (length) {
    case "narrow":
      return [...weekdaysNarrow];
    case "short":
      return [...weekdaysShort];
    case "long":
      return [...weekdaysLong];
    case "numeric":
      return ["1", "2", "3", "4", "5", "6", "7"];
    default:
      return null;
  }
}
var meridiems = ["AM", "PM"];
var erasLong = ["Before Christ", "Anno Domini"];
var erasShort = ["BC", "AD"];
var erasNarrow = ["B", "A"];
function eras(length) {
  switch (length) {
    case "narrow":
      return [...erasNarrow];
    case "short":
      return [...erasShort];
    case "long":
      return [...erasLong];
    default:
      return null;
  }
}
function meridiemForDateTime(dt) {
  return meridiems[dt.hour < 12 ? 0 : 1];
}
function weekdayForDateTime(dt, length) {
  return weekdays(length)[dt.weekday - 1];
}
function monthForDateTime(dt, length) {
  return months(length)[dt.month - 1];
}
function eraForDateTime(dt, length) {
  return eras(length)[dt.year < 0 ? 0 : 1];
}
function formatRelativeTime(unit, count, numeric = "always", narrow = false) {
  const units = {
    years: ["year", "yr."],
    quarters: ["quarter", "qtr."],
    months: ["month", "mo."],
    weeks: ["week", "wk."],
    days: ["day", "day", "days"],
    hours: ["hour", "hr."],
    minutes: ["minute", "min."],
    seconds: ["second", "sec."]
  };
  const lastable = ["hours", "minutes", "seconds"].indexOf(unit) === -1;
  if (numeric === "auto" && lastable) {
    const isDay = unit === "days";
    switch (count) {
      case 1:
        return isDay ? "tomorrow" : `next ${units[unit][0]}`;
      case -1:
        return isDay ? "yesterday" : `last ${units[unit][0]}`;
      case 0:
        return isDay ? "today" : `this ${units[unit][0]}`;
      default:
    }
  }
  const isInPast = Object.is(count, -0) || count < 0, fmtValue = Math.abs(count), singular = fmtValue === 1, lilUnits = units[unit], fmtUnit = narrow ? singular ? lilUnits[1] : lilUnits[2] || lilUnits[1] : singular ? units[unit][0] : unit;
  return isInPast ? `${fmtValue} ${fmtUnit} ago` : `in ${fmtValue} ${fmtUnit}`;
}

// node_modules/luxon/src/impl/formatter.js
function stringifyTokens(splits, tokenToString) {
  let s2 = "";
  for (const token of splits) {
    if (token.literal) {
      s2 += token.val;
    } else {
      s2 += tokenToString(token.val);
    }
  }
  return s2;
}
var macroTokenToFormatOpts = {
  D: DATE_SHORT,
  DD: DATE_MED,
  DDD: DATE_FULL,
  DDDD: DATE_HUGE,
  t: TIME_SIMPLE,
  tt: TIME_WITH_SECONDS,
  ttt: TIME_WITH_SHORT_OFFSET,
  tttt: TIME_WITH_LONG_OFFSET,
  T: TIME_24_SIMPLE,
  TT: TIME_24_WITH_SECONDS,
  TTT: TIME_24_WITH_SHORT_OFFSET,
  TTTT: TIME_24_WITH_LONG_OFFSET,
  f: DATETIME_SHORT,
  ff: DATETIME_MED,
  fff: DATETIME_FULL,
  ffff: DATETIME_HUGE,
  F: DATETIME_SHORT_WITH_SECONDS,
  FF: DATETIME_MED_WITH_SECONDS,
  FFF: DATETIME_FULL_WITH_SECONDS,
  FFFF: DATETIME_HUGE_WITH_SECONDS
};
var Formatter = class _Formatter {
  static create(locale, opts = {}) {
    return new _Formatter(locale, opts);
  }
  static parseFormat(fmt) {
    let current = null, currentFull = "", bracketed = false;
    const splits = [];
    for (let i = 0; i < fmt.length; i++) {
      const c = fmt.charAt(i);
      if (c === "'") {
        if (currentFull.length > 0) {
          splits.push({ literal: bracketed || /^\s+$/.test(currentFull), val: currentFull });
        }
        current = null;
        currentFull = "";
        bracketed = !bracketed;
      } else if (bracketed) {
        currentFull += c;
      } else if (c === current) {
        currentFull += c;
      } else {
        if (currentFull.length > 0) {
          splits.push({ literal: /^\s+$/.test(currentFull), val: currentFull });
        }
        currentFull = c;
        current = c;
      }
    }
    if (currentFull.length > 0) {
      splits.push({ literal: bracketed || /^\s+$/.test(currentFull), val: currentFull });
    }
    return splits;
  }
  static macroTokenToFormatOpts(token) {
    return macroTokenToFormatOpts[token];
  }
  constructor(locale, formatOpts) {
    this.opts = formatOpts;
    this.loc = locale;
    this.systemLoc = null;
  }
  formatWithSystemDefault(dt, opts) {
    if (this.systemLoc === null) {
      this.systemLoc = this.loc.redefaultToSystem();
    }
    const df = this.systemLoc.dtFormatter(dt, { ...this.opts, ...opts });
    return df.format();
  }
  dtFormatter(dt, opts = {}) {
    return this.loc.dtFormatter(dt, { ...this.opts, ...opts });
  }
  formatDateTime(dt, opts) {
    return this.dtFormatter(dt, opts).format();
  }
  formatDateTimeParts(dt, opts) {
    return this.dtFormatter(dt, opts).formatToParts();
  }
  formatInterval(interval, opts) {
    const df = this.dtFormatter(interval.start, opts);
    return df.dtf.formatRange(interval.start.toJSDate(), interval.end.toJSDate());
  }
  resolvedOptions(dt, opts) {
    return this.dtFormatter(dt, opts).resolvedOptions();
  }
  num(n2, p = 0) {
    if (this.opts.forceSimple) {
      return padStart(n2, p);
    }
    const opts = { ...this.opts };
    if (p > 0) {
      opts.padTo = p;
    }
    return this.loc.numberFormatter(opts).format(n2);
  }
  formatDateTimeFromString(dt, fmt) {
    const knownEnglish = this.loc.listingMode() === "en", useDateTimeFormatter = this.loc.outputCalendar && this.loc.outputCalendar !== "gregory", string = (opts, extract) => this.loc.extract(dt, opts, extract), formatOffset2 = (opts) => {
      if (dt.isOffsetFixed && dt.offset === 0 && opts.allowZ) {
        return "Z";
      }
      return dt.isValid ? dt.zone.formatOffset(dt.ts, opts.format) : "";
    }, meridiem = () => knownEnglish ? meridiemForDateTime(dt) : string({ hour: "numeric", hourCycle: "h12" }, "dayperiod"), month = (length, standalone) => knownEnglish ? monthForDateTime(dt, length) : string(standalone ? { month: length } : { month: length, day: "numeric" }, "month"), weekday = (length, standalone) => knownEnglish ? weekdayForDateTime(dt, length) : string(
      standalone ? { weekday: length } : { weekday: length, month: "long", day: "numeric" },
      "weekday"
    ), maybeMacro = (token) => {
      const formatOpts = _Formatter.macroTokenToFormatOpts(token);
      if (formatOpts) {
        return this.formatWithSystemDefault(dt, formatOpts);
      } else {
        return token;
      }
    }, era = (length) => knownEnglish ? eraForDateTime(dt, length) : string({ era: length }, "era"), tokenToString = (token) => {
      switch (token) {
        // ms
        case "S":
          return this.num(dt.millisecond);
        case "u":
        // falls through
        case "SSS":
          return this.num(dt.millisecond, 3);
        // seconds
        case "s":
          return this.num(dt.second);
        case "ss":
          return this.num(dt.second, 2);
        // fractional seconds
        case "uu":
          return this.num(Math.floor(dt.millisecond / 10), 2);
        case "uuu":
          return this.num(Math.floor(dt.millisecond / 100));
        // minutes
        case "m":
          return this.num(dt.minute);
        case "mm":
          return this.num(dt.minute, 2);
        // hours
        case "h":
          return this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12);
        case "hh":
          return this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12, 2);
        case "H":
          return this.num(dt.hour);
        case "HH":
          return this.num(dt.hour, 2);
        // offset
        case "Z":
          return formatOffset2({ format: "narrow", allowZ: this.opts.allowZ });
        case "ZZ":
          return formatOffset2({ format: "short", allowZ: this.opts.allowZ });
        case "ZZZ":
          return formatOffset2({ format: "techie", allowZ: this.opts.allowZ });
        case "ZZZZ":
          return dt.zone.offsetName(dt.ts, { format: "short", locale: this.loc.locale });
        case "ZZZZZ":
          return dt.zone.offsetName(dt.ts, { format: "long", locale: this.loc.locale });
        // zone
        case "z":
          return dt.zoneName;
        // meridiems
        case "a":
          return meridiem();
        // dates
        case "d":
          return useDateTimeFormatter ? string({ day: "numeric" }, "day") : this.num(dt.day);
        case "dd":
          return useDateTimeFormatter ? string({ day: "2-digit" }, "day") : this.num(dt.day, 2);
        // weekdays - standalone
        case "c":
          return this.num(dt.weekday);
        case "ccc":
          return weekday("short", true);
        case "cccc":
          return weekday("long", true);
        case "ccccc":
          return weekday("narrow", true);
        // weekdays - format
        case "E":
          return this.num(dt.weekday);
        case "EEE":
          return weekday("short", false);
        case "EEEE":
          return weekday("long", false);
        case "EEEEE":
          return weekday("narrow", false);
        // months - standalone
        case "L":
          return useDateTimeFormatter ? string({ month: "numeric", day: "numeric" }, "month") : this.num(dt.month);
        case "LL":
          return useDateTimeFormatter ? string({ month: "2-digit", day: "numeric" }, "month") : this.num(dt.month, 2);
        case "LLL":
          return month("short", true);
        case "LLLL":
          return month("long", true);
        case "LLLLL":
          return month("narrow", true);
        // months - format
        case "M":
          return useDateTimeFormatter ? string({ month: "numeric" }, "month") : this.num(dt.month);
        case "MM":
          return useDateTimeFormatter ? string({ month: "2-digit" }, "month") : this.num(dt.month, 2);
        case "MMM":
          return month("short", false);
        case "MMMM":
          return month("long", false);
        case "MMMMM":
          return month("narrow", false);
        // years
        case "y":
          return useDateTimeFormatter ? string({ year: "numeric" }, "year") : this.num(dt.year);
        case "yy":
          return useDateTimeFormatter ? string({ year: "2-digit" }, "year") : this.num(dt.year.toString().slice(-2), 2);
        case "yyyy":
          return useDateTimeFormatter ? string({ year: "numeric" }, "year") : this.num(dt.year, 4);
        case "yyyyyy":
          return useDateTimeFormatter ? string({ year: "numeric" }, "year") : this.num(dt.year, 6);
        // eras
        case "G":
          return era("short");
        case "GG":
          return era("long");
        case "GGGGG":
          return era("narrow");
        case "kk":
          return this.num(dt.weekYear.toString().slice(-2), 2);
        case "kkkk":
          return this.num(dt.weekYear, 4);
        case "W":
          return this.num(dt.weekNumber);
        case "WW":
          return this.num(dt.weekNumber, 2);
        case "n":
          return this.num(dt.localWeekNumber);
        case "nn":
          return this.num(dt.localWeekNumber, 2);
        case "ii":
          return this.num(dt.localWeekYear.toString().slice(-2), 2);
        case "iiii":
          return this.num(dt.localWeekYear, 4);
        case "o":
          return this.num(dt.ordinal);
        case "ooo":
          return this.num(dt.ordinal, 3);
        case "q":
          return this.num(dt.quarter);
        case "qq":
          return this.num(dt.quarter, 2);
        case "X":
          return this.num(Math.floor(dt.ts / 1e3));
        case "x":
          return this.num(dt.ts);
        default:
          return maybeMacro(token);
      }
    };
    return stringifyTokens(_Formatter.parseFormat(fmt), tokenToString);
  }
  formatDurationFromString(dur, fmt) {
    const tokenToField = (token) => {
      switch (token[0]) {
        case "S":
          return "millisecond";
        case "s":
          return "second";
        case "m":
          return "minute";
        case "h":
          return "hour";
        case "d":
          return "day";
        case "w":
          return "week";
        case "M":
          return "month";
        case "y":
          return "year";
        default:
          return null;
      }
    }, tokenToString = (lildur) => (token) => {
      const mapped = tokenToField(token);
      if (mapped) {
        return this.num(lildur.get(mapped), token.length);
      } else {
        return token;
      }
    }, tokens = _Formatter.parseFormat(fmt), realTokens = tokens.reduce(
      (found, { literal, val }) => literal ? found : found.concat(val),
      []
    ), collapsed = dur.shiftTo(...realTokens.map(tokenToField).filter((t) => t));
    return stringifyTokens(tokens, tokenToString(collapsed));
  }
};

// node_modules/luxon/src/impl/regexParser.js
init_esbuild_buffer_shim();
var ianaRegex = /[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;
function combineRegexes(...regexes) {
  const full = regexes.reduce((f, r) => f + r.source, "");
  return RegExp(`^${full}$`);
}
function combineExtractors(...extractors) {
  return (m) => extractors.reduce(
    ([mergedVals, mergedZone, cursor], ex) => {
      const [val, zone, next] = ex(m, cursor);
      return [{ ...mergedVals, ...val }, zone || mergedZone, next];
    },
    [{}, null, 1]
  ).slice(0, 2);
}
function parse(s2, ...patterns) {
  if (s2 == null) {
    return [null, null];
  }
  for (const [regex, extractor] of patterns) {
    const m = regex.exec(s2);
    if (m) {
      return extractor(m);
    }
  }
  return [null, null];
}
function simpleParse(...keys) {
  return (match2, cursor) => {
    const ret = {};
    let i;
    for (i = 0; i < keys.length; i++) {
      ret[keys[i]] = parseInteger(match2[cursor + i]);
    }
    return [ret, null, cursor + i];
  };
}
var offsetRegex = /(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/;
var isoExtendedZone = `(?:${offsetRegex.source}?(?:\\[(${ianaRegex.source})\\])?)?`;
var isoTimeBaseRegex = /(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/;
var isoTimeRegex = RegExp(`${isoTimeBaseRegex.source}${isoExtendedZone}`);
var isoTimeExtensionRegex = RegExp(`(?:T${isoTimeRegex.source})?`);
var isoYmdRegex = /([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/;
var isoWeekRegex = /(\d{4})-?W(\d\d)(?:-?(\d))?/;
var isoOrdinalRegex = /(\d{4})-?(\d{3})/;
var extractISOWeekData = simpleParse("weekYear", "weekNumber", "weekDay");
var extractISOOrdinalData = simpleParse("year", "ordinal");
var sqlYmdRegex = /(\d{4})-(\d\d)-(\d\d)/;
var sqlTimeRegex = RegExp(
  `${isoTimeBaseRegex.source} ?(?:${offsetRegex.source}|(${ianaRegex.source}))?`
);
var sqlTimeExtensionRegex = RegExp(`(?: ${sqlTimeRegex.source})?`);
function int(match2, pos, fallback) {
  const m = match2[pos];
  return isUndefined(m) ? fallback : parseInteger(m);
}
function extractISOYmd(match2, cursor) {
  const item = {
    year: int(match2, cursor),
    month: int(match2, cursor + 1, 1),
    day: int(match2, cursor + 2, 1)
  };
  return [item, null, cursor + 3];
}
function extractISOTime(match2, cursor) {
  const item = {
    hours: int(match2, cursor, 0),
    minutes: int(match2, cursor + 1, 0),
    seconds: int(match2, cursor + 2, 0),
    milliseconds: parseMillis(match2[cursor + 3])
  };
  return [item, null, cursor + 4];
}
function extractISOOffset(match2, cursor) {
  const local = !match2[cursor] && !match2[cursor + 1], fullOffset = signedOffset(match2[cursor + 1], match2[cursor + 2]), zone = local ? null : FixedOffsetZone.instance(fullOffset);
  return [{}, zone, cursor + 3];
}
function extractIANAZone(match2, cursor) {
  const zone = match2[cursor] ? IANAZone.create(match2[cursor]) : null;
  return [{}, zone, cursor + 1];
}
var isoTimeOnly = RegExp(`^T?${isoTimeBaseRegex.source}$`);
var isoDuration = /^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/;
function extractISODuration(match2) {
  const [s2, yearStr, monthStr, weekStr, dayStr, hourStr, minuteStr, secondStr, millisecondsStr] = match2;
  const hasNegativePrefix = s2[0] === "-";
  const negativeSeconds = secondStr && secondStr[0] === "-";
  const maybeNegate = (num, force = false) => num !== void 0 && (force || num && hasNegativePrefix) ? -num : num;
  return [
    {
      years: maybeNegate(parseFloating(yearStr)),
      months: maybeNegate(parseFloating(monthStr)),
      weeks: maybeNegate(parseFloating(weekStr)),
      days: maybeNegate(parseFloating(dayStr)),
      hours: maybeNegate(parseFloating(hourStr)),
      minutes: maybeNegate(parseFloating(minuteStr)),
      seconds: maybeNegate(parseFloating(secondStr), secondStr === "-0"),
      milliseconds: maybeNegate(parseMillis(millisecondsStr), negativeSeconds)
    }
  ];
}
var obsOffsets = {
  GMT: 0,
  EDT: -4 * 60,
  EST: -5 * 60,
  CDT: -5 * 60,
  CST: -6 * 60,
  MDT: -6 * 60,
  MST: -7 * 60,
  PDT: -7 * 60,
  PST: -8 * 60
};
function fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) {
  const result = {
    year: yearStr.length === 2 ? untruncateYear(parseInteger(yearStr)) : parseInteger(yearStr),
    month: monthsShort.indexOf(monthStr) + 1,
    day: parseInteger(dayStr),
    hour: parseInteger(hourStr),
    minute: parseInteger(minuteStr)
  };
  if (secondStr) result.second = parseInteger(secondStr);
  if (weekdayStr) {
    result.weekday = weekdayStr.length > 3 ? weekdaysLong.indexOf(weekdayStr) + 1 : weekdaysShort.indexOf(weekdayStr) + 1;
  }
  return result;
}
var rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/;
function extractRFC2822(match2) {
  const [
    ,
    weekdayStr,
    dayStr,
    monthStr,
    yearStr,
    hourStr,
    minuteStr,
    secondStr,
    obsOffset,
    milOffset,
    offHourStr,
    offMinuteStr
  ] = match2, result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);
  let offset2;
  if (obsOffset) {
    offset2 = obsOffsets[obsOffset];
  } else if (milOffset) {
    offset2 = 0;
  } else {
    offset2 = signedOffset(offHourStr, offMinuteStr);
  }
  return [result, new FixedOffsetZone(offset2)];
}
function preprocessRFC2822(s2) {
  return s2.replace(/\([^()]*\)|[\n\t]/g, " ").replace(/(\s\s+)/g, " ").trim();
}
var rfc1123 = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/;
var rfc850 = /^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/;
var ascii = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;
function extractRFC1123Or850(match2) {
  const [, weekdayStr, dayStr, monthStr, yearStr, hourStr, minuteStr, secondStr] = match2, result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);
  return [result, FixedOffsetZone.utcInstance];
}
function extractASCII(match2) {
  const [, weekdayStr, monthStr, dayStr, hourStr, minuteStr, secondStr, yearStr] = match2, result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);
  return [result, FixedOffsetZone.utcInstance];
}
var isoYmdWithTimeExtensionRegex = combineRegexes(isoYmdRegex, isoTimeExtensionRegex);
var isoWeekWithTimeExtensionRegex = combineRegexes(isoWeekRegex, isoTimeExtensionRegex);
var isoOrdinalWithTimeExtensionRegex = combineRegexes(isoOrdinalRegex, isoTimeExtensionRegex);
var isoTimeCombinedRegex = combineRegexes(isoTimeRegex);
var extractISOYmdTimeAndOffset = combineExtractors(
  extractISOYmd,
  extractISOTime,
  extractISOOffset,
  extractIANAZone
);
var extractISOWeekTimeAndOffset = combineExtractors(
  extractISOWeekData,
  extractISOTime,
  extractISOOffset,
  extractIANAZone
);
var extractISOOrdinalDateAndTime = combineExtractors(
  extractISOOrdinalData,
  extractISOTime,
  extractISOOffset,
  extractIANAZone
);
var extractISOTimeAndOffset = combineExtractors(
  extractISOTime,
  extractISOOffset,
  extractIANAZone
);
function parseISODate(s2) {
  return parse(
    s2,
    [isoYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset],
    [isoWeekWithTimeExtensionRegex, extractISOWeekTimeAndOffset],
    [isoOrdinalWithTimeExtensionRegex, extractISOOrdinalDateAndTime],
    [isoTimeCombinedRegex, extractISOTimeAndOffset]
  );
}
function parseRFC2822Date(s2) {
  return parse(preprocessRFC2822(s2), [rfc2822, extractRFC2822]);
}
function parseHTTPDate(s2) {
  return parse(
    s2,
    [rfc1123, extractRFC1123Or850],
    [rfc850, extractRFC1123Or850],
    [ascii, extractASCII]
  );
}
function parseISODuration(s2) {
  return parse(s2, [isoDuration, extractISODuration]);
}
var extractISOTimeOnly = combineExtractors(extractISOTime);
function parseISOTimeOnly(s2) {
  return parse(s2, [isoTimeOnly, extractISOTimeOnly]);
}
var sqlYmdWithTimeExtensionRegex = combineRegexes(sqlYmdRegex, sqlTimeExtensionRegex);
var sqlTimeCombinedRegex = combineRegexes(sqlTimeRegex);
var extractISOTimeOffsetAndIANAZone = combineExtractors(
  extractISOTime,
  extractISOOffset,
  extractIANAZone
);
function parseSQL(s2) {
  return parse(
    s2,
    [sqlYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset],
    [sqlTimeCombinedRegex, extractISOTimeOffsetAndIANAZone]
  );
}

// node_modules/luxon/src/duration.js
var INVALID = "Invalid Duration";
var lowOrderMatrix = {
  weeks: {
    days: 7,
    hours: 7 * 24,
    minutes: 7 * 24 * 60,
    seconds: 7 * 24 * 60 * 60,
    milliseconds: 7 * 24 * 60 * 60 * 1e3
  },
  days: {
    hours: 24,
    minutes: 24 * 60,
    seconds: 24 * 60 * 60,
    milliseconds: 24 * 60 * 60 * 1e3
  },
  hours: { minutes: 60, seconds: 60 * 60, milliseconds: 60 * 60 * 1e3 },
  minutes: { seconds: 60, milliseconds: 60 * 1e3 },
  seconds: { milliseconds: 1e3 }
};
var casualMatrix = {
  years: {
    quarters: 4,
    months: 12,
    weeks: 52,
    days: 365,
    hours: 365 * 24,
    minutes: 365 * 24 * 60,
    seconds: 365 * 24 * 60 * 60,
    milliseconds: 365 * 24 * 60 * 60 * 1e3
  },
  quarters: {
    months: 3,
    weeks: 13,
    days: 91,
    hours: 91 * 24,
    minutes: 91 * 24 * 60,
    seconds: 91 * 24 * 60 * 60,
    milliseconds: 91 * 24 * 60 * 60 * 1e3
  },
  months: {
    weeks: 4,
    days: 30,
    hours: 30 * 24,
    minutes: 30 * 24 * 60,
    seconds: 30 * 24 * 60 * 60,
    milliseconds: 30 * 24 * 60 * 60 * 1e3
  },
  ...lowOrderMatrix
};
var daysInYearAccurate = 146097 / 400;
var daysInMonthAccurate = 146097 / 4800;
var accurateMatrix = {
  years: {
    quarters: 4,
    months: 12,
    weeks: daysInYearAccurate / 7,
    days: daysInYearAccurate,
    hours: daysInYearAccurate * 24,
    minutes: daysInYearAccurate * 24 * 60,
    seconds: daysInYearAccurate * 24 * 60 * 60,
    milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1e3
  },
  quarters: {
    months: 3,
    weeks: daysInYearAccurate / 28,
    days: daysInYearAccurate / 4,
    hours: daysInYearAccurate * 24 / 4,
    minutes: daysInYearAccurate * 24 * 60 / 4,
    seconds: daysInYearAccurate * 24 * 60 * 60 / 4,
    milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1e3 / 4
  },
  months: {
    weeks: daysInMonthAccurate / 7,
    days: daysInMonthAccurate,
    hours: daysInMonthAccurate * 24,
    minutes: daysInMonthAccurate * 24 * 60,
    seconds: daysInMonthAccurate * 24 * 60 * 60,
    milliseconds: daysInMonthAccurate * 24 * 60 * 60 * 1e3
  },
  ...lowOrderMatrix
};
var orderedUnits = [
  "years",
  "quarters",
  "months",
  "weeks",
  "days",
  "hours",
  "minutes",
  "seconds",
  "milliseconds"
];
var reverseUnits = orderedUnits.slice(0).reverse();
function clone(dur, alts, clear = false) {
  const conf = {
    values: clear ? alts.values : { ...dur.values, ...alts.values || {} },
    loc: dur.loc.clone(alts.loc),
    conversionAccuracy: alts.conversionAccuracy || dur.conversionAccuracy,
    matrix: alts.matrix || dur.matrix
  };
  return new Duration(conf);
}
function durationToMillis(matrix, vals) {
  let sum = vals.milliseconds ?? 0;
  for (const unit of reverseUnits.slice(1)) {
    if (vals[unit]) {
      sum += vals[unit] * matrix[unit]["milliseconds"];
    }
  }
  return sum;
}
function normalizeValues(matrix, vals) {
  const factor = durationToMillis(matrix, vals) < 0 ? -1 : 1;
  orderedUnits.reduceRight((previous, current) => {
    if (!isUndefined(vals[current])) {
      if (previous) {
        const previousVal = vals[previous] * factor;
        const conv = matrix[current][previous];
        const rollUp = Math.floor(previousVal / conv);
        vals[current] += rollUp * factor;
        vals[previous] -= rollUp * conv * factor;
      }
      return current;
    } else {
      return previous;
    }
  }, null);
  orderedUnits.reduce((previous, current) => {
    if (!isUndefined(vals[current])) {
      if (previous) {
        const fraction = vals[previous] % 1;
        vals[previous] -= fraction;
        vals[current] += fraction * matrix[previous][current];
      }
      return current;
    } else {
      return previous;
    }
  }, null);
}
function removeZeroes(vals) {
  const newVals = {};
  for (const [key, value] of Object.entries(vals)) {
    if (value !== 0) {
      newVals[key] = value;
    }
  }
  return newVals;
}
var Duration = class _Duration {
  /**
   * @private
   */
  constructor(config) {
    const accurate = config.conversionAccuracy === "longterm" || false;
    let matrix = accurate ? accurateMatrix : casualMatrix;
    if (config.matrix) {
      matrix = config.matrix;
    }
    this.values = config.values;
    this.loc = config.loc || Locale.create();
    this.conversionAccuracy = accurate ? "longterm" : "casual";
    this.invalid = config.invalid || null;
    this.matrix = matrix;
    this.isLuxonDuration = true;
  }
  /**
   * Create Duration from a number of milliseconds.
   * @param {number} count of milliseconds
   * @param {Object} opts - options for parsing
   * @param {string} [opts.locale='en-US'] - the locale to use
   * @param {string} opts.numberingSystem - the numbering system to use
   * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
   * @return {Duration}
   */
  static fromMillis(count, opts) {
    return _Duration.fromObject({ milliseconds: count }, opts);
  }
  /**
   * Create a Duration from a JavaScript object with keys like 'years' and 'hours'.
   * If this object is empty then a zero milliseconds duration is returned.
   * @param {Object} obj - the object to create the DateTime from
   * @param {number} obj.years
   * @param {number} obj.quarters
   * @param {number} obj.months
   * @param {number} obj.weeks
   * @param {number} obj.days
   * @param {number} obj.hours
   * @param {number} obj.minutes
   * @param {number} obj.seconds
   * @param {number} obj.milliseconds
   * @param {Object} [opts=[]] - options for creating this Duration
   * @param {string} [opts.locale='en-US'] - the locale to use
   * @param {string} opts.numberingSystem - the numbering system to use
   * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use
   * @param {string} [opts.matrix=Object] - the custom conversion system to use
   * @return {Duration}
   */
  static fromObject(obj, opts = {}) {
    if (obj == null || typeof obj !== "object") {
      throw new InvalidArgumentError(
        `Duration.fromObject: argument expected to be an object, got ${obj === null ? "null" : typeof obj}`
      );
    }
    return new _Duration({
      values: normalizeObject(obj, _Duration.normalizeUnit),
      loc: Locale.fromObject(opts),
      conversionAccuracy: opts.conversionAccuracy,
      matrix: opts.matrix
    });
  }
  /**
   * Create a Duration from DurationLike.
   *
   * @param {Object | number | Duration} durationLike
   * One of:
   * - object with keys like 'years' and 'hours'.
   * - number representing milliseconds
   * - Duration instance
   * @return {Duration}
   */
  static fromDurationLike(durationLike) {
    if (isNumber(durationLike)) {
      return _Duration.fromMillis(durationLike);
    } else if (_Duration.isDuration(durationLike)) {
      return durationLike;
    } else if (typeof durationLike === "object") {
      return _Duration.fromObject(durationLike);
    } else {
      throw new InvalidArgumentError(
        `Unknown duration argument ${durationLike} of type ${typeof durationLike}`
      );
    }
  }
  /**
   * Create a Duration from an ISO 8601 duration string.
   * @param {string} text - text to parse
   * @param {Object} opts - options for parsing
   * @param {string} [opts.locale='en-US'] - the locale to use
   * @param {string} opts.numberingSystem - the numbering system to use
   * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use
   * @param {string} [opts.matrix=Object] - the preset conversion system to use
   * @see https://en.wikipedia.org/wiki/ISO_8601#Durations
   * @example Duration.fromISO('P3Y6M1W4DT12H30M5S').toObject() //=> { years: 3, months: 6, weeks: 1, days: 4, hours: 12, minutes: 30, seconds: 5 }
   * @example Duration.fromISO('PT23H').toObject() //=> { hours: 23 }
   * @example Duration.fromISO('P5Y3M').toObject() //=> { years: 5, months: 3 }
   * @return {Duration}
   */
  static fromISO(text2, opts) {
    const [parsed] = parseISODuration(text2);
    if (parsed) {
      return _Duration.fromObject(parsed, opts);
    } else {
      return _Duration.invalid("unparsable", `the input "${text2}" can't be parsed as ISO 8601`);
    }
  }
  /**
   * Create a Duration from an ISO 8601 time string.
   * @param {string} text - text to parse
   * @param {Object} opts - options for parsing
   * @param {string} [opts.locale='en-US'] - the locale to use
   * @param {string} opts.numberingSystem - the numbering system to use
   * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use
   * @param {string} [opts.matrix=Object] - the conversion system to use
   * @see https://en.wikipedia.org/wiki/ISO_8601#Times
   * @example Duration.fromISOTime('11:22:33.444').toObject() //=> { hours: 11, minutes: 22, seconds: 33, milliseconds: 444 }
   * @example Duration.fromISOTime('11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }
   * @example Duration.fromISOTime('T11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }
   * @example Duration.fromISOTime('1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }
   * @example Duration.fromISOTime('T1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }
   * @return {Duration}
   */
  static fromISOTime(text2, opts) {
    const [parsed] = parseISOTimeOnly(text2);
    if (parsed) {
      return _Duration.fromObject(parsed, opts);
    } else {
      return _Duration.invalid("unparsable", `the input "${text2}" can't be parsed as ISO 8601`);
    }
  }
  /**
   * Create an invalid Duration.
   * @param {string} reason - simple string of why this datetime is invalid. Should not contain parameters or anything else data-dependent
   * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information
   * @return {Duration}
   */
  static invalid(reason, explanation = null) {
    if (!reason) {
      throw new InvalidArgumentError("need to specify a reason the Duration is invalid");
    }
    const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
    if (Settings.throwOnInvalid) {
      throw new InvalidDurationError(invalid);
    } else {
      return new _Duration({ invalid });
    }
  }
  /**
   * @private
   */
  static normalizeUnit(unit) {
    const normalized = {
      year: "years",
      years: "years",
      quarter: "quarters",
      quarters: "quarters",
      month: "months",
      months: "months",
      week: "weeks",
      weeks: "weeks",
      day: "days",
      days: "days",
      hour: "hours",
      hours: "hours",
      minute: "minutes",
      minutes: "minutes",
      second: "seconds",
      seconds: "seconds",
      millisecond: "milliseconds",
      milliseconds: "milliseconds"
    }[unit ? unit.toLowerCase() : unit];
    if (!normalized) throw new InvalidUnitError(unit);
    return normalized;
  }
  /**
   * Check if an object is a Duration. Works across context boundaries
   * @param {object} o
   * @return {boolean}
   */
  static isDuration(o) {
    return o && o.isLuxonDuration || false;
  }
  /**
   * Get  the locale of a Duration, such 'en-GB'
   * @type {string}
   */
  get locale() {
    return this.isValid ? this.loc.locale : null;
  }
  /**
   * Get the numbering system of a Duration, such 'beng'. The numbering system is used when formatting the Duration
   *
   * @type {string}
   */
  get numberingSystem() {
    return this.isValid ? this.loc.numberingSystem : null;
  }
  /**
   * Returns a string representation of this Duration formatted according to the specified format string. You may use these tokens:
   * * `S` for milliseconds
   * * `s` for seconds
   * * `m` for minutes
   * * `h` for hours
   * * `d` for days
   * * `w` for weeks
   * * `M` for months
   * * `y` for years
   * Notes:
   * * Add padding by repeating the token, e.g. "yy" pads the years to two digits, "hhhh" pads the hours out to four digits
   * * Tokens can be escaped by wrapping with single quotes.
   * * The duration will be converted to the set of units in the format string using {@link Duration#shiftTo} and the Durations's conversion accuracy setting.
   * @param {string} fmt - the format string
   * @param {Object} opts - options
   * @param {boolean} [opts.floor=true] - floor numerical values
   * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("y d s") //=> "1 6 2"
   * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("yy dd sss") //=> "01 06 002"
   * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("M S") //=> "12 518402000"
   * @return {string}
   */
  toFormat(fmt, opts = {}) {
    const fmtOpts = {
      ...opts,
      floor: opts.round !== false && opts.floor !== false
    };
    return this.isValid ? Formatter.create(this.loc, fmtOpts).formatDurationFromString(this, fmt) : INVALID;
  }
  /**
   * Returns a string representation of a Duration with all units included.
   * To modify its behavior, use `listStyle` and any Intl.NumberFormat option, though `unitDisplay` is especially relevant.
   * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#options
   * @param {Object} opts - Formatting options. Accepts the same keys as the options parameter of the native `Intl.NumberFormat` constructor, as well as `listStyle`.
   * @param {string} [opts.listStyle='narrow'] - How to format the merged list. Corresponds to the `style` property of the options parameter of the native `Intl.ListFormat` constructor.
   * @example
   * ```js
   * var dur = Duration.fromObject({ days: 1, hours: 5, minutes: 6 })
   * dur.toHuman() //=> '1 day, 5 hours, 6 minutes'
   * dur.toHuman({ listStyle: "long" }) //=> '1 day, 5 hours, and 6 minutes'
   * dur.toHuman({ unitDisplay: "short" }) //=> '1 day, 5 hr, 6 min'
   * ```
   */
  toHuman(opts = {}) {
    if (!this.isValid) return INVALID;
    const l2 = orderedUnits.map((unit) => {
      const val = this.values[unit];
      if (isUndefined(val)) {
        return null;
      }
      return this.loc.numberFormatter({ style: "unit", unitDisplay: "long", ...opts, unit: unit.slice(0, -1) }).format(val);
    }).filter((n2) => n2);
    return this.loc.listFormatter({ type: "conjunction", style: opts.listStyle || "narrow", ...opts }).format(l2);
  }
  /**
   * Returns a JavaScript object with this Duration's values.
   * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toObject() //=> { years: 1, days: 6, seconds: 2 }
   * @return {Object}
   */
  toObject() {
    if (!this.isValid) return {};
    return { ...this.values };
  }
  /**
   * Returns an ISO 8601-compliant string representation of this Duration.
   * @see https://en.wikipedia.org/wiki/ISO_8601#Durations
   * @example Duration.fromObject({ years: 3, seconds: 45 }).toISO() //=> 'P3YT45S'
   * @example Duration.fromObject({ months: 4, seconds: 45 }).toISO() //=> 'P4MT45S'
   * @example Duration.fromObject({ months: 5 }).toISO() //=> 'P5M'
   * @example Duration.fromObject({ minutes: 5 }).toISO() //=> 'PT5M'
   * @example Duration.fromObject({ milliseconds: 6 }).toISO() //=> 'PT0.006S'
   * @return {string}
   */
  toISO() {
    if (!this.isValid) return null;
    let s2 = "P";
    if (this.years !== 0) s2 += this.years + "Y";
    if (this.months !== 0 || this.quarters !== 0) s2 += this.months + this.quarters * 3 + "M";
    if (this.weeks !== 0) s2 += this.weeks + "W";
    if (this.days !== 0) s2 += this.days + "D";
    if (this.hours !== 0 || this.minutes !== 0 || this.seconds !== 0 || this.milliseconds !== 0)
      s2 += "T";
    if (this.hours !== 0) s2 += this.hours + "H";
    if (this.minutes !== 0) s2 += this.minutes + "M";
    if (this.seconds !== 0 || this.milliseconds !== 0)
      s2 += roundTo(this.seconds + this.milliseconds / 1e3, 3) + "S";
    if (s2 === "P") s2 += "T0S";
    return s2;
  }
  /**
   * Returns an ISO 8601-compliant string representation of this Duration, formatted as a time of day.
   * Note that this will return null if the duration is invalid, negative, or equal to or greater than 24 hours.
   * @see https://en.wikipedia.org/wiki/ISO_8601#Times
   * @param {Object} opts - options
   * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0
   * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0
   * @param {boolean} [opts.includePrefix=false] - include the `T` prefix
   * @param {string} [opts.format='extended'] - choose between the basic and extended format
   * @example Duration.fromObject({ hours: 11 }).toISOTime() //=> '11:00:00.000'
   * @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressMilliseconds: true }) //=> '11:00:00'
   * @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressSeconds: true }) //=> '11:00'
   * @example Duration.fromObject({ hours: 11 }).toISOTime({ includePrefix: true }) //=> 'T11:00:00.000'
   * @example Duration.fromObject({ hours: 11 }).toISOTime({ format: 'basic' }) //=> '110000.000'
   * @return {string}
   */
  toISOTime(opts = {}) {
    if (!this.isValid) return null;
    const millis = this.toMillis();
    if (millis < 0 || millis >= 864e5) return null;
    opts = {
      suppressMilliseconds: false,
      suppressSeconds: false,
      includePrefix: false,
      format: "extended",
      ...opts,
      includeOffset: false
    };
    const dateTime = DateTime.fromMillis(millis, { zone: "UTC" });
    return dateTime.toISOTime(opts);
  }
  /**
   * Returns an ISO 8601 representation of this Duration appropriate for use in JSON.
   * @return {string}
   */
  toJSON() {
    return this.toISO();
  }
  /**
   * Returns an ISO 8601 representation of this Duration appropriate for use in debugging.
   * @return {string}
   */
  toString() {
    return this.toISO();
  }
  /**
   * Returns a string representation of this Duration appropriate for the REPL.
   * @return {string}
   */
  [Symbol.for("nodejs.util.inspect.custom")]() {
    if (this.isValid) {
      return `Duration { values: ${JSON.stringify(this.values)} }`;
    } else {
      return `Duration { Invalid, reason: ${this.invalidReason} }`;
    }
  }
  /**
   * Returns an milliseconds value of this Duration.
   * @return {number}
   */
  toMillis() {
    if (!this.isValid) return NaN;
    return durationToMillis(this.matrix, this.values);
  }
  /**
   * Returns an milliseconds value of this Duration. Alias of {@link toMillis}
   * @return {number}
   */
  valueOf() {
    return this.toMillis();
  }
  /**
   * Make this Duration longer by the specified amount. Return a newly-constructed Duration.
   * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
   * @return {Duration}
   */
  plus(duration) {
    if (!this.isValid) return this;
    const dur = _Duration.fromDurationLike(duration), result = {};
    for (const k of orderedUnits) {
      if (hasOwnProperty(dur.values, k) || hasOwnProperty(this.values, k)) {
        result[k] = dur.get(k) + this.get(k);
      }
    }
    return clone(this, { values: result }, true);
  }
  /**
   * Make this Duration shorter by the specified amount. Return a newly-constructed Duration.
   * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
   * @return {Duration}
   */
  minus(duration) {
    if (!this.isValid) return this;
    const dur = _Duration.fromDurationLike(duration);
    return this.plus(dur.negate());
  }
  /**
   * Scale this Duration by the specified amount. Return a newly-constructed Duration.
   * @param {function} fn - The function to apply to each unit. Arity is 1 or 2: the value of the unit and, optionally, the unit name. Must return a number.
   * @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnits(x => x * 2) //=> { hours: 2, minutes: 60 }
   * @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnits((x, u) => u === "hours" ? x * 2 : x) //=> { hours: 2, minutes: 30 }
   * @return {Duration}
   */
  mapUnits(fn) {
    if (!this.isValid) return this;
    const result = {};
    for (const k of Object.keys(this.values)) {
      result[k] = asNumber(fn(this.values[k], k));
    }
    return clone(this, { values: result }, true);
  }
  /**
   * Get the value of unit.
   * @param {string} unit - a unit such as 'minute' or 'day'
   * @example Duration.fromObject({years: 2, days: 3}).get('years') //=> 2
   * @example Duration.fromObject({years: 2, days: 3}).get('months') //=> 0
   * @example Duration.fromObject({years: 2, days: 3}).get('days') //=> 3
   * @return {number}
   */
  get(unit) {
    return this[_Duration.normalizeUnit(unit)];
  }
  /**
   * "Set" the values of specified units. Return a newly-constructed Duration.
   * @param {Object} values - a mapping of units to numbers
   * @example dur.set({ years: 2017 })
   * @example dur.set({ hours: 8, minutes: 30 })
   * @return {Duration}
   */
  set(values) {
    if (!this.isValid) return this;
    const mixed = { ...this.values, ...normalizeObject(values, _Duration.normalizeUnit) };
    return clone(this, { values: mixed });
  }
  /**
   * "Set" the locale and/or numberingSystem.  Returns a newly-constructed Duration.
   * @example dur.reconfigure({ locale: 'en-GB' })
   * @return {Duration}
   */
  reconfigure({ locale, numberingSystem, conversionAccuracy, matrix } = {}) {
    const loc = this.loc.clone({ locale, numberingSystem });
    const opts = { loc, matrix, conversionAccuracy };
    return clone(this, opts);
  }
  /**
   * Return the length of the duration in the specified unit.
   * @param {string} unit - a unit such as 'minutes' or 'days'
   * @example Duration.fromObject({years: 1}).as('days') //=> 365
   * @example Duration.fromObject({years: 1}).as('months') //=> 12
   * @example Duration.fromObject({hours: 60}).as('days') //=> 2.5
   * @return {number}
   */
  as(unit) {
    return this.isValid ? this.shiftTo(unit).get(unit) : NaN;
  }
  /**
   * Reduce this Duration to its canonical representation in its current units.
   * Assuming the overall value of the Duration is positive, this means:
   * - excessive values for lower-order units are converted to higher-order units (if possible, see first and second example)
   * - negative lower-order units are converted to higher order units (there must be such a higher order unit, otherwise
   *   the overall value would be negative, see third example)
   * - fractional values for higher-order units are converted to lower-order units (if possible, see fourth example)
   *
   * If the overall value is negative, the result of this method is equivalent to `this.negate().normalize().negate()`.
   * @example Duration.fromObject({ years: 2, days: 5000 }).normalize().toObject() //=> { years: 15, days: 255 }
   * @example Duration.fromObject({ days: 5000 }).normalize().toObject() //=> { days: 5000 }
   * @example Duration.fromObject({ hours: 12, minutes: -45 }).normalize().toObject() //=> { hours: 11, minutes: 15 }
   * @example Duration.fromObject({ years: 2.5, days: 0, hours: 0 }).normalize().toObject() //=> { years: 2, days: 182, hours: 12 }
   * @return {Duration}
   */
  normalize() {
    if (!this.isValid) return this;
    const vals = this.toObject();
    normalizeValues(this.matrix, vals);
    return clone(this, { values: vals }, true);
  }
  /**
   * Rescale units to its largest representation
   * @example Duration.fromObject({ milliseconds: 90000 }).rescale().toObject() //=> { minutes: 1, seconds: 30 }
   * @return {Duration}
   */
  rescale() {
    if (!this.isValid) return this;
    const vals = removeZeroes(this.normalize().shiftToAll().toObject());
    return clone(this, { values: vals }, true);
  }
  /**
   * Convert this Duration into its representation in a different set of units.
   * @example Duration.fromObject({ hours: 1, seconds: 30 }).shiftTo('minutes', 'milliseconds').toObject() //=> { minutes: 60, milliseconds: 30000 }
   * @return {Duration}
   */
  shiftTo(...units) {
    if (!this.isValid) return this;
    if (units.length === 0) {
      return this;
    }
    units = units.map((u) => _Duration.normalizeUnit(u));
    const built = {}, accumulated = {}, vals = this.toObject();
    let lastUnit;
    for (const k of orderedUnits) {
      if (units.indexOf(k) >= 0) {
        lastUnit = k;
        let own = 0;
        for (const ak in accumulated) {
          own += this.matrix[ak][k] * accumulated[ak];
          accumulated[ak] = 0;
        }
        if (isNumber(vals[k])) {
          own += vals[k];
        }
        const i = Math.trunc(own);
        built[k] = i;
        accumulated[k] = (own * 1e3 - i * 1e3) / 1e3;
      } else if (isNumber(vals[k])) {
        accumulated[k] = vals[k];
      }
    }
    for (const key in accumulated) {
      if (accumulated[key] !== 0) {
        built[lastUnit] += key === lastUnit ? accumulated[key] : accumulated[key] / this.matrix[lastUnit][key];
      }
    }
    normalizeValues(this.matrix, built);
    return clone(this, { values: built }, true);
  }
  /**
   * Shift this Duration to all available units.
   * Same as shiftTo("years", "months", "weeks", "days", "hours", "minutes", "seconds", "milliseconds")
   * @return {Duration}
   */
  shiftToAll() {
    if (!this.isValid) return this;
    return this.shiftTo(
      "years",
      "months",
      "weeks",
      "days",
      "hours",
      "minutes",
      "seconds",
      "milliseconds"
    );
  }
  /**
   * Return the negative of this Duration.
   * @example Duration.fromObject({ hours: 1, seconds: 30 }).negate().toObject() //=> { hours: -1, seconds: -30 }
   * @return {Duration}
   */
  negate() {
    if (!this.isValid) return this;
    const negated = {};
    for (const k of Object.keys(this.values)) {
      negated[k] = this.values[k] === 0 ? 0 : -this.values[k];
    }
    return clone(this, { values: negated }, true);
  }
  /**
   * Get the years.
   * @type {number}
   */
  get years() {
    return this.isValid ? this.values.years || 0 : NaN;
  }
  /**
   * Get the quarters.
   * @type {number}
   */
  get quarters() {
    return this.isValid ? this.values.quarters || 0 : NaN;
  }
  /**
   * Get the months.
   * @type {number}
   */
  get months() {
    return this.isValid ? this.values.months || 0 : NaN;
  }
  /**
   * Get the weeks
   * @type {number}
   */
  get weeks() {
    return this.isValid ? this.values.weeks || 0 : NaN;
  }
  /**
   * Get the days.
   * @type {number}
   */
  get days() {
    return this.isValid ? this.values.days || 0 : NaN;
  }
  /**
   * Get the hours.
   * @type {number}
   */
  get hours() {
    return this.isValid ? this.values.hours || 0 : NaN;
  }
  /**
   * Get the minutes.
   * @type {number}
   */
  get minutes() {
    return this.isValid ? this.values.minutes || 0 : NaN;
  }
  /**
   * Get the seconds.
   * @return {number}
   */
  get seconds() {
    return this.isValid ? this.values.seconds || 0 : NaN;
  }
  /**
   * Get the milliseconds.
   * @return {number}
   */
  get milliseconds() {
    return this.isValid ? this.values.milliseconds || 0 : NaN;
  }
  /**
   * Returns whether the Duration is invalid. Invalid durations are returned by diff operations
   * on invalid DateTimes or Intervals.
   * @return {boolean}
   */
  get isValid() {
    return this.invalid === null;
  }
  /**
   * Returns an error code if this Duration became invalid, or null if the Duration is valid
   * @return {string}
   */
  get invalidReason() {
    return this.invalid ? this.invalid.reason : null;
  }
  /**
   * Returns an explanation of why this Duration became invalid, or null if the Duration is valid
   * @type {string}
   */
  get invalidExplanation() {
    return this.invalid ? this.invalid.explanation : null;
  }
  /**
   * Equality check
   * Two Durations are equal iff they have the same units and the same values for each unit.
   * @param {Duration} other
   * @return {boolean}
   */
  equals(other) {
    if (!this.isValid || !other.isValid) {
      return false;
    }
    if (!this.loc.equals(other.loc)) {
      return false;
    }
    function eq(v1, v2) {
      if (v1 === void 0 || v1 === 0) return v2 === void 0 || v2 === 0;
      return v1 === v2;
    }
    for (const u of orderedUnits) {
      if (!eq(this.values[u], other.values[u])) {
        return false;
      }
    }
    return true;
  }
};

// node_modules/luxon/src/interval.js
init_esbuild_buffer_shim();
var INVALID2 = "Invalid Interval";
function validateStartEnd(start, end) {
  if (!start || !start.isValid) {
    return Interval.invalid("missing or invalid start");
  } else if (!end || !end.isValid) {
    return Interval.invalid("missing or invalid end");
  } else if (end < start) {
    return Interval.invalid(
      "end before start",
      `The end of an interval must be after its start, but you had start=${start.toISO()} and end=${end.toISO()}`
    );
  } else {
    return null;
  }
}
var Interval = class _Interval {
  /**
   * @private
   */
  constructor(config) {
    this.s = config.start;
    this.e = config.end;
    this.invalid = config.invalid || null;
    this.isLuxonInterval = true;
  }
  /**
   * Create an invalid Interval.
   * @param {string} reason - simple string of why this Interval is invalid. Should not contain parameters or anything else data-dependent
   * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information
   * @return {Interval}
   */
  static invalid(reason, explanation = null) {
    if (!reason) {
      throw new InvalidArgumentError("need to specify a reason the Interval is invalid");
    }
    const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
    if (Settings.throwOnInvalid) {
      throw new InvalidIntervalError(invalid);
    } else {
      return new _Interval({ invalid });
    }
  }
  /**
   * Create an Interval from a start DateTime and an end DateTime. Inclusive of the start but not the end.
   * @param {DateTime|Date|Object} start
   * @param {DateTime|Date|Object} end
   * @return {Interval}
   */
  static fromDateTimes(start, end) {
    const builtStart = friendlyDateTime(start), builtEnd = friendlyDateTime(end);
    const validateError = validateStartEnd(builtStart, builtEnd);
    if (validateError == null) {
      return new _Interval({
        start: builtStart,
        end: builtEnd
      });
    } else {
      return validateError;
    }
  }
  /**
   * Create an Interval from a start DateTime and a Duration to extend to.
   * @param {DateTime|Date|Object} start
   * @param {Duration|Object|number} duration - the length of the Interval.
   * @return {Interval}
   */
  static after(start, duration) {
    const dur = Duration.fromDurationLike(duration), dt = friendlyDateTime(start);
    return _Interval.fromDateTimes(dt, dt.plus(dur));
  }
  /**
   * Create an Interval from an end DateTime and a Duration to extend backwards to.
   * @param {DateTime|Date|Object} end
   * @param {Duration|Object|number} duration - the length of the Interval.
   * @return {Interval}
   */
  static before(end, duration) {
    const dur = Duration.fromDurationLike(duration), dt = friendlyDateTime(end);
    return _Interval.fromDateTimes(dt.minus(dur), dt);
  }
  /**
   * Create an Interval from an ISO 8601 string.
   * Accepts `<start>/<end>`, `<start>/<duration>`, and `<duration>/<end>` formats.
   * @param {string} text - the ISO string to parse
   * @param {Object} [opts] - options to pass {@link DateTime#fromISO} and optionally {@link Duration#fromISO}
   * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals
   * @return {Interval}
   */
  static fromISO(text2, opts) {
    const [s2, e] = (text2 || "").split("/", 2);
    if (s2 && e) {
      let start, startIsValid;
      try {
        start = DateTime.fromISO(s2, opts);
        startIsValid = start.isValid;
      } catch (e2) {
        startIsValid = false;
      }
      let end, endIsValid;
      try {
        end = DateTime.fromISO(e, opts);
        endIsValid = end.isValid;
      } catch (e2) {
        endIsValid = false;
      }
      if (startIsValid && endIsValid) {
        return _Interval.fromDateTimes(start, end);
      }
      if (startIsValid) {
        const dur = Duration.fromISO(e, opts);
        if (dur.isValid) {
          return _Interval.after(start, dur);
        }
      } else if (endIsValid) {
        const dur = Duration.fromISO(s2, opts);
        if (dur.isValid) {
          return _Interval.before(end, dur);
        }
      }
    }
    return _Interval.invalid("unparsable", `the input "${text2}" can't be parsed as ISO 8601`);
  }
  /**
   * Check if an object is an Interval. Works across context boundaries
   * @param {object} o
   * @return {boolean}
   */
  static isInterval(o) {
    return o && o.isLuxonInterval || false;
  }
  /**
   * Returns the start of the Interval
   * @type {DateTime}
   */
  get start() {
    return this.isValid ? this.s : null;
  }
  /**
   * Returns the end of the Interval
   * @type {DateTime}
   */
  get end() {
    return this.isValid ? this.e : null;
  }
  /**
   * Returns the last DateTime included in the interval (since end is not part of the interval)
   * @type {DateTime}
   */
  get lastDateTime() {
    return this.isValid ? this.e ? this.e.minus(1) : null : null;
  }
  /**
   * Returns whether this Interval's end is at least its start, meaning that the Interval isn't 'backwards'.
   * @type {boolean}
   */
  get isValid() {
    return this.invalidReason === null;
  }
  /**
   * Returns an error code if this Interval is invalid, or null if the Interval is valid
   * @type {string}
   */
  get invalidReason() {
    return this.invalid ? this.invalid.reason : null;
  }
  /**
   * Returns an explanation of why this Interval became invalid, or null if the Interval is valid
   * @type {string}
   */
  get invalidExplanation() {
    return this.invalid ? this.invalid.explanation : null;
  }
  /**
   * Returns the length of the Interval in the specified unit.
   * @param {string} unit - the unit (such as 'hours' or 'days') to return the length in.
   * @return {number}
   */
  length(unit = "milliseconds") {
    return this.isValid ? this.toDuration(...[unit]).get(unit) : NaN;
  }
  /**
   * Returns the count of minutes, hours, days, months, or years included in the Interval, even in part.
   * Unlike {@link Interval#length} this counts sections of the calendar, not periods of time, e.g. specifying 'day'
   * asks 'what dates are included in this interval?', not 'how many days long is this interval?'
   * @param {string} [unit='milliseconds'] - the unit of time to count.
   * @param {Object} opts - options
   * @param {boolean} [opts.useLocaleWeeks=false] - If true, use weeks based on the locale, i.e. use the locale-dependent start of the week; this operation will always use the locale of the start DateTime
   * @return {number}
   */
  count(unit = "milliseconds", opts) {
    if (!this.isValid) return NaN;
    const start = this.start.startOf(unit, opts);
    let end;
    if (opts?.useLocaleWeeks) {
      end = this.end.reconfigure({ locale: start.locale });
    } else {
      end = this.end;
    }
    end = end.startOf(unit, opts);
    return Math.floor(end.diff(start, unit).get(unit)) + (end.valueOf() !== this.end.valueOf());
  }
  /**
   * Returns whether this Interval's start and end are both in the same unit of time
   * @param {string} unit - the unit of time to check sameness on
   * @return {boolean}
   */
  hasSame(unit) {
    return this.isValid ? this.isEmpty() || this.e.minus(1).hasSame(this.s, unit) : false;
  }
  /**
   * Return whether this Interval has the same start and end DateTimes.
   * @return {boolean}
   */
  isEmpty() {
    return this.s.valueOf() === this.e.valueOf();
  }
  /**
   * Return whether this Interval's start is after the specified DateTime.
   * @param {DateTime} dateTime
   * @return {boolean}
   */
  isAfter(dateTime) {
    if (!this.isValid) return false;
    return this.s > dateTime;
  }
  /**
   * Return whether this Interval's end is before the specified DateTime.
   * @param {DateTime} dateTime
   * @return {boolean}
   */
  isBefore(dateTime) {
    if (!this.isValid) return false;
    return this.e <= dateTime;
  }
  /**
   * Return whether this Interval contains the specified DateTime.
   * @param {DateTime} dateTime
   * @return {boolean}
   */
  contains(dateTime) {
    if (!this.isValid) return false;
    return this.s <= dateTime && this.e > dateTime;
  }
  /**
   * "Sets" the start and/or end dates. Returns a newly-constructed Interval.
   * @param {Object} values - the values to set
   * @param {DateTime} values.start - the starting DateTime
   * @param {DateTime} values.end - the ending DateTime
   * @return {Interval}
   */
  set({ start, end } = {}) {
    if (!this.isValid) return this;
    return _Interval.fromDateTimes(start || this.s, end || this.e);
  }
  /**
   * Split this Interval at each of the specified DateTimes
   * @param {...DateTime} dateTimes - the unit of time to count.
   * @return {Array}
   */
  splitAt(...dateTimes) {
    if (!this.isValid) return [];
    const sorted = dateTimes.map(friendlyDateTime).filter((d) => this.contains(d)).sort((a, b) => a.toMillis() - b.toMillis()), results = [];
    let { s: s2 } = this, i = 0;
    while (s2 < this.e) {
      const added = sorted[i] || this.e, next = +added > +this.e ? this.e : added;
      results.push(_Interval.fromDateTimes(s2, next));
      s2 = next;
      i += 1;
    }
    return results;
  }
  /**
   * Split this Interval into smaller Intervals, each of the specified length.
   * Left over time is grouped into a smaller interval
   * @param {Duration|Object|number} duration - The length of each resulting interval.
   * @return {Array}
   */
  splitBy(duration) {
    const dur = Duration.fromDurationLike(duration);
    if (!this.isValid || !dur.isValid || dur.as("milliseconds") === 0) {
      return [];
    }
    let { s: s2 } = this, idx = 1, next;
    const results = [];
    while (s2 < this.e) {
      const added = this.start.plus(dur.mapUnits((x) => x * idx));
      next = +added > +this.e ? this.e : added;
      results.push(_Interval.fromDateTimes(s2, next));
      s2 = next;
      idx += 1;
    }
    return results;
  }
  /**
   * Split this Interval into the specified number of smaller intervals.
   * @param {number} numberOfParts - The number of Intervals to divide the Interval into.
   * @return {Array}
   */
  divideEqually(numberOfParts) {
    if (!this.isValid) return [];
    return this.splitBy(this.length() / numberOfParts).slice(0, numberOfParts);
  }
  /**
   * Return whether this Interval overlaps with the specified Interval
   * @param {Interval} other
   * @return {boolean}
   */
  overlaps(other) {
    return this.e > other.s && this.s < other.e;
  }
  /**
   * Return whether this Interval's end is adjacent to the specified Interval's start.
   * @param {Interval} other
   * @return {boolean}
   */
  abutsStart(other) {
    if (!this.isValid) return false;
    return +this.e === +other.s;
  }
  /**
   * Return whether this Interval's start is adjacent to the specified Interval's end.
   * @param {Interval} other
   * @return {boolean}
   */
  abutsEnd(other) {
    if (!this.isValid) return false;
    return +other.e === +this.s;
  }
  /**
   * Returns true if this Interval fully contains the specified Interval, specifically if the intersect (of this Interval and the other Interval) is equal to the other Interval; false otherwise.
   * @param {Interval} other
   * @return {boolean}
   */
  engulfs(other) {
    if (!this.isValid) return false;
    return this.s <= other.s && this.e >= other.e;
  }
  /**
   * Return whether this Interval has the same start and end as the specified Interval.
   * @param {Interval} other
   * @return {boolean}
   */
  equals(other) {
    if (!this.isValid || !other.isValid) {
      return false;
    }
    return this.s.equals(other.s) && this.e.equals(other.e);
  }
  /**
   * Return an Interval representing the intersection of this Interval and the specified Interval.
   * Specifically, the resulting Interval has the maximum start time and the minimum end time of the two Intervals.
   * Returns null if the intersection is empty, meaning, the intervals don't intersect.
   * @param {Interval} other
   * @return {Interval}
   */
  intersection(other) {
    if (!this.isValid) return this;
    const s2 = this.s > other.s ? this.s : other.s, e = this.e < other.e ? this.e : other.e;
    if (s2 >= e) {
      return null;
    } else {
      return _Interval.fromDateTimes(s2, e);
    }
  }
  /**
   * Return an Interval representing the union of this Interval and the specified Interval.
   * Specifically, the resulting Interval has the minimum start time and the maximum end time of the two Intervals.
   * @param {Interval} other
   * @return {Interval}
   */
  union(other) {
    if (!this.isValid) return this;
    const s2 = this.s < other.s ? this.s : other.s, e = this.e > other.e ? this.e : other.e;
    return _Interval.fromDateTimes(s2, e);
  }
  /**
   * Merge an array of Intervals into an equivalent minimal set of Intervals.
   * Combines overlapping and adjacent Intervals.
   * The resulting array will contain the Intervals in ascending order, that is, starting with the earliest Interval
   * and ending with the latest.
   *
   * @param {Array} intervals
   * @return {Array}
   */
  static merge(intervals) {
    const [found, final] = intervals.sort((a, b) => a.s - b.s).reduce(
      ([sofar, current], item) => {
        if (!current) {
          return [sofar, item];
        } else if (current.overlaps(item) || current.abutsStart(item)) {
          return [sofar, current.union(item)];
        } else {
          return [sofar.concat([current]), item];
        }
      },
      [[], null]
    );
    if (final) {
      found.push(final);
    }
    return found;
  }
  /**
   * Return an array of Intervals representing the spans of time that only appear in one of the specified Intervals.
   * @param {Array} intervals
   * @return {Array}
   */
  static xor(intervals) {
    let start = null, currentCount = 0;
    const results = [], ends = intervals.map((i) => [
      { time: i.s, type: "s" },
      { time: i.e, type: "e" }
    ]), flattened = Array.prototype.concat(...ends), arr = flattened.sort((a, b) => a.time - b.time);
    for (const i of arr) {
      currentCount += i.type === "s" ? 1 : -1;
      if (currentCount === 1) {
        start = i.time;
      } else {
        if (start && +start !== +i.time) {
          results.push(_Interval.fromDateTimes(start, i.time));
        }
        start = null;
      }
    }
    return _Interval.merge(results);
  }
  /**
   * Return an Interval representing the span of time in this Interval that doesn't overlap with any of the specified Intervals.
   * @param {...Interval} intervals
   * @return {Array}
   */
  difference(...intervals) {
    return _Interval.xor([this].concat(intervals)).map((i) => this.intersection(i)).filter((i) => i && !i.isEmpty());
  }
  /**
   * Returns a string representation of this Interval appropriate for debugging.
   * @return {string}
   */
  toString() {
    if (!this.isValid) return INVALID2;
    return `[${this.s.toISO()} \u2013 ${this.e.toISO()})`;
  }
  /**
   * Returns a string representation of this Interval appropriate for the REPL.
   * @return {string}
   */
  [Symbol.for("nodejs.util.inspect.custom")]() {
    if (this.isValid) {
      return `Interval { start: ${this.s.toISO()}, end: ${this.e.toISO()} }`;
    } else {
      return `Interval { Invalid, reason: ${this.invalidReason} }`;
    }
  }
  /**
   * Returns a localized string representing this Interval. Accepts the same options as the
   * Intl.DateTimeFormat constructor and any presets defined by Luxon, such as
   * {@link DateTime.DATE_FULL} or {@link DateTime.TIME_SIMPLE}. The exact behavior of this method
   * is browser-specific, but in general it will return an appropriate representation of the
   * Interval in the assigned locale. Defaults to the system's locale if no locale has been
   * specified.
   * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
   * @param {Object} [formatOpts=DateTime.DATE_SHORT] - Either a DateTime preset or
   * Intl.DateTimeFormat constructor options.
   * @param {Object} opts - Options to override the configuration of the start DateTime.
   * @example Interval.fromISO('2022-11-07T09:00Z/2022-11-08T09:00Z').toLocaleString(); //=> 11/7/2022 – 11/8/2022
   * @example Interval.fromISO('2022-11-07T09:00Z/2022-11-08T09:00Z').toLocaleString(DateTime.DATE_FULL); //=> November 7 – 8, 2022
   * @example Interval.fromISO('2022-11-07T09:00Z/2022-11-08T09:00Z').toLocaleString(DateTime.DATE_FULL, { locale: 'fr-FR' }); //=> 7–8 novembre 2022
   * @example Interval.fromISO('2022-11-07T17:00Z/2022-11-07T19:00Z').toLocaleString(DateTime.TIME_SIMPLE); //=> 6:00 – 8:00 PM
   * @example Interval.fromISO('2022-11-07T17:00Z/2022-11-07T19:00Z').toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }); //=> Mon, Nov 07, 6:00 – 8:00 p
   * @return {string}
   */
  toLocaleString(formatOpts = DATE_SHORT, opts = {}) {
    return this.isValid ? Formatter.create(this.s.loc.clone(opts), formatOpts).formatInterval(this) : INVALID2;
  }
  /**
   * Returns an ISO 8601-compliant string representation of this Interval.
   * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals
   * @param {Object} opts - The same options as {@link DateTime#toISO}
   * @return {string}
   */
  toISO(opts) {
    if (!this.isValid) return INVALID2;
    return `${this.s.toISO(opts)}/${this.e.toISO(opts)}`;
  }
  /**
   * Returns an ISO 8601-compliant string representation of date of this Interval.
   * The time components are ignored.
   * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals
   * @return {string}
   */
  toISODate() {
    if (!this.isValid) return INVALID2;
    return `${this.s.toISODate()}/${this.e.toISODate()}`;
  }
  /**
   * Returns an ISO 8601-compliant string representation of time of this Interval.
   * The date components are ignored.
   * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals
   * @param {Object} opts - The same options as {@link DateTime#toISO}
   * @return {string}
   */
  toISOTime(opts) {
    if (!this.isValid) return INVALID2;
    return `${this.s.toISOTime(opts)}/${this.e.toISOTime(opts)}`;
  }
  /**
   * Returns a string representation of this Interval formatted according to the specified format
   * string. **You may not want this.** See {@link Interval#toLocaleString} for a more flexible
   * formatting tool.
   * @param {string} dateFormat - The format string. This string formats the start and end time.
   * See {@link DateTime#toFormat} for details.
   * @param {Object} opts - Options.
   * @param {string} [opts.separator =  ' – '] - A separator to place between the start and end
   * representations.
   * @return {string}
   */
  toFormat(dateFormat, { separator = " \u2013 " } = {}) {
    if (!this.isValid) return INVALID2;
    return `${this.s.toFormat(dateFormat)}${separator}${this.e.toFormat(dateFormat)}`;
  }
  /**
   * Return a Duration representing the time spanned by this interval.
   * @param {string|string[]} [unit=['milliseconds']] - the unit or units (such as 'hours' or 'days') to include in the duration.
   * @param {Object} opts - options that affect the creation of the Duration
   * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
   * @example Interval.fromDateTimes(dt1, dt2).toDuration().toObject() //=> { milliseconds: 88489257 }
   * @example Interval.fromDateTimes(dt1, dt2).toDuration('days').toObject() //=> { days: 1.0241812152777778 }
   * @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes']).toObject() //=> { hours: 24, minutes: 34.82095 }
   * @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes', 'seconds']).toObject() //=> { hours: 24, minutes: 34, seconds: 49.257 }
   * @example Interval.fromDateTimes(dt1, dt2).toDuration('seconds').toObject() //=> { seconds: 88489.257 }
   * @return {Duration}
   */
  toDuration(unit, opts) {
    if (!this.isValid) {
      return Duration.invalid(this.invalidReason);
    }
    return this.e.diff(this.s, unit, opts);
  }
  /**
   * Run mapFn on the interval start and end, returning a new Interval from the resulting DateTimes
   * @param {function} mapFn
   * @return {Interval}
   * @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.toUTC())
   * @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.plus({ hours: 2 }))
   */
  mapEndpoints(mapFn) {
    return _Interval.fromDateTimes(mapFn(this.s), mapFn(this.e));
  }
};

// node_modules/luxon/src/info.js
init_esbuild_buffer_shim();
var Info = class {
  /**
   * Return whether the specified zone contains a DST.
   * @param {string|Zone} [zone='local'] - Zone to check. Defaults to the environment's local zone.
   * @return {boolean}
   */
  static hasDST(zone = Settings.defaultZone) {
    const proto = DateTime.now().setZone(zone).set({ month: 12 });
    return !zone.isUniversal && proto.offset !== proto.set({ month: 6 }).offset;
  }
  /**
   * Return whether the specified zone is a valid IANA specifier.
   * @param {string} zone - Zone to check
   * @return {boolean}
   */
  static isValidIANAZone(zone) {
    return IANAZone.isValidZone(zone);
  }
  /**
   * Converts the input into a {@link Zone} instance.
   *
   * * If `input` is already a Zone instance, it is returned unchanged.
   * * If `input` is a string containing a valid time zone name, a Zone instance
   *   with that name is returned.
   * * If `input` is a string that doesn't refer to a known time zone, a Zone
   *   instance with {@link Zone#isValid} == false is returned.
   * * If `input is a number, a Zone instance with the specified fixed offset
   *   in minutes is returned.
   * * If `input` is `null` or `undefined`, the default zone is returned.
   * @param {string|Zone|number} [input] - the value to be converted
   * @return {Zone}
   */
  static normalizeZone(input) {
    return normalizeZone(input, Settings.defaultZone);
  }
  /**
   * Get the weekday on which the week starts according to the given locale.
   * @param {Object} opts - options
   * @param {string} [opts.locale] - the locale code
   * @param {string} [opts.locObj=null] - an existing locale object to use
   * @returns {number} the start of the week, 1 for Monday through 7 for Sunday
   */
  static getStartOfWeek({ locale = null, locObj = null } = {}) {
    return (locObj || Locale.create(locale)).getStartOfWeek();
  }
  /**
   * Get the minimum number of days necessary in a week before it is considered part of the next year according
   * to the given locale.
   * @param {Object} opts - options
   * @param {string} [opts.locale] - the locale code
   * @param {string} [opts.locObj=null] - an existing locale object to use
   * @returns {number}
   */
  static getMinimumDaysInFirstWeek({ locale = null, locObj = null } = {}) {
    return (locObj || Locale.create(locale)).getMinDaysInFirstWeek();
  }
  /**
   * Get the weekdays, which are considered the weekend according to the given locale
   * @param {Object} opts - options
   * @param {string} [opts.locale] - the locale code
   * @param {string} [opts.locObj=null] - an existing locale object to use
   * @returns {number[]} an array of weekdays, 1 for Monday through 7 for Sunday
   */
  static getWeekendWeekdays({ locale = null, locObj = null } = {}) {
    return (locObj || Locale.create(locale)).getWeekendDays().slice();
  }
  /**
   * Return an array of standalone month names.
   * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
   * @param {string} [length='long'] - the length of the month representation, such as "numeric", "2-digit", "narrow", "short", "long"
   * @param {Object} opts - options
   * @param {string} [opts.locale] - the locale code
   * @param {string} [opts.numberingSystem=null] - the numbering system
   * @param {string} [opts.locObj=null] - an existing locale object to use
   * @param {string} [opts.outputCalendar='gregory'] - the calendar
   * @example Info.months()[0] //=> 'January'
   * @example Info.months('short')[0] //=> 'Jan'
   * @example Info.months('numeric')[0] //=> '1'
   * @example Info.months('short', { locale: 'fr-CA' } )[0] //=> 'janv.'
   * @example Info.months('numeric', { locale: 'ar' })[0] //=> '١'
   * @example Info.months('long', { outputCalendar: 'islamic' })[0] //=> 'Rabiʻ I'
   * @return {Array}
   */
  static months(length = "long", { locale = null, numberingSystem = null, locObj = null, outputCalendar = "gregory" } = {}) {
    return (locObj || Locale.create(locale, numberingSystem, outputCalendar)).months(length);
  }
  /**
   * Return an array of format month names.
   * Format months differ from standalone months in that they're meant to appear next to the day of the month. In some languages, that
   * changes the string.
   * See {@link Info#months}
   * @param {string} [length='long'] - the length of the month representation, such as "numeric", "2-digit", "narrow", "short", "long"
   * @param {Object} opts - options
   * @param {string} [opts.locale] - the locale code
   * @param {string} [opts.numberingSystem=null] - the numbering system
   * @param {string} [opts.locObj=null] - an existing locale object to use
   * @param {string} [opts.outputCalendar='gregory'] - the calendar
   * @return {Array}
   */
  static monthsFormat(length = "long", { locale = null, numberingSystem = null, locObj = null, outputCalendar = "gregory" } = {}) {
    return (locObj || Locale.create(locale, numberingSystem, outputCalendar)).months(length, true);
  }
  /**
   * Return an array of standalone week names.
   * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
   * @param {string} [length='long'] - the length of the weekday representation, such as "narrow", "short", "long".
   * @param {Object} opts - options
   * @param {string} [opts.locale] - the locale code
   * @param {string} [opts.numberingSystem=null] - the numbering system
   * @param {string} [opts.locObj=null] - an existing locale object to use
   * @example Info.weekdays()[0] //=> 'Monday'
   * @example Info.weekdays('short')[0] //=> 'Mon'
   * @example Info.weekdays('short', { locale: 'fr-CA' })[0] //=> 'lun.'
   * @example Info.weekdays('short', { locale: 'ar' })[0] //=> 'الاثنين'
   * @return {Array}
   */
  static weekdays(length = "long", { locale = null, numberingSystem = null, locObj = null } = {}) {
    return (locObj || Locale.create(locale, numberingSystem, null)).weekdays(length);
  }
  /**
   * Return an array of format week names.
   * Format weekdays differ from standalone weekdays in that they're meant to appear next to more date information. In some languages, that
   * changes the string.
   * See {@link Info#weekdays}
   * @param {string} [length='long'] - the length of the month representation, such as "narrow", "short", "long".
   * @param {Object} opts - options
   * @param {string} [opts.locale=null] - the locale code
   * @param {string} [opts.numberingSystem=null] - the numbering system
   * @param {string} [opts.locObj=null] - an existing locale object to use
   * @return {Array}
   */
  static weekdaysFormat(length = "long", { locale = null, numberingSystem = null, locObj = null } = {}) {
    return (locObj || Locale.create(locale, numberingSystem, null)).weekdays(length, true);
  }
  /**
   * Return an array of meridiems.
   * @param {Object} opts - options
   * @param {string} [opts.locale] - the locale code
   * @example Info.meridiems() //=> [ 'AM', 'PM' ]
   * @example Info.meridiems({ locale: 'my' }) //=> [ 'နံနက်', 'ညနေ' ]
   * @return {Array}
   */
  static meridiems({ locale = null } = {}) {
    return Locale.create(locale).meridiems();
  }
  /**
   * Return an array of eras, such as ['BC', 'AD']. The locale can be specified, but the calendar system is always Gregorian.
   * @param {string} [length='short'] - the length of the era representation, such as "short" or "long".
   * @param {Object} opts - options
   * @param {string} [opts.locale] - the locale code
   * @example Info.eras() //=> [ 'BC', 'AD' ]
   * @example Info.eras('long') //=> [ 'Before Christ', 'Anno Domini' ]
   * @example Info.eras('long', { locale: 'fr' }) //=> [ 'avant Jésus-Christ', 'après Jésus-Christ' ]
   * @return {Array}
   */
  static eras(length = "short", { locale = null } = {}) {
    return Locale.create(locale, null, "gregory").eras(length);
  }
  /**
   * Return the set of available features in this environment.
   * Some features of Luxon are not available in all environments. For example, on older browsers, relative time formatting support is not available. Use this function to figure out if that's the case.
   * Keys:
   * * `relative`: whether this environment supports relative time formatting
   * * `localeWeek`: whether this environment supports different weekdays for the start of the week based on the locale
   * @example Info.features() //=> { relative: false, localeWeek: true }
   * @return {Object}
   */
  static features() {
    return { relative: hasRelative(), localeWeek: hasLocaleWeekInfo() };
  }
};

// node_modules/luxon/src/impl/diff.js
init_esbuild_buffer_shim();
function dayDiff(earlier, later) {
  const utcDayStart = (dt) => dt.toUTC(0, { keepLocalTime: true }).startOf("day").valueOf(), ms = utcDayStart(later) - utcDayStart(earlier);
  return Math.floor(Duration.fromMillis(ms).as("days"));
}
function highOrderDiffs(cursor, later, units) {
  const differs = [
    ["years", (a, b) => b.year - a.year],
    ["quarters", (a, b) => b.quarter - a.quarter + (b.year - a.year) * 4],
    ["months", (a, b) => b.month - a.month + (b.year - a.year) * 12],
    [
      "weeks",
      (a, b) => {
        const days = dayDiff(a, b);
        return (days - days % 7) / 7;
      }
    ],
    ["days", dayDiff]
  ];
  const results = {};
  const earlier = cursor;
  let lowestOrder, highWater;
  for (const [unit, differ] of differs) {
    if (units.indexOf(unit) >= 0) {
      lowestOrder = unit;
      results[unit] = differ(cursor, later);
      highWater = earlier.plus(results);
      if (highWater > later) {
        results[unit]--;
        cursor = earlier.plus(results);
        if (cursor > later) {
          highWater = cursor;
          results[unit]--;
          cursor = earlier.plus(results);
        }
      } else {
        cursor = highWater;
      }
    }
  }
  return [cursor, results, highWater, lowestOrder];
}
function diff_default(earlier, later, units, opts) {
  let [cursor, results, highWater, lowestOrder] = highOrderDiffs(earlier, later, units);
  const remainingMillis = later - cursor;
  const lowerOrderUnits = units.filter(
    (u) => ["hours", "minutes", "seconds", "milliseconds"].indexOf(u) >= 0
  );
  if (lowerOrderUnits.length === 0) {
    if (highWater < later) {
      highWater = cursor.plus({ [lowestOrder]: 1 });
    }
    if (highWater !== cursor) {
      results[lowestOrder] = (results[lowestOrder] || 0) + remainingMillis / (highWater - cursor);
    }
  }
  const duration = Duration.fromObject(results, opts);
  if (lowerOrderUnits.length > 0) {
    return Duration.fromMillis(remainingMillis, opts).shiftTo(...lowerOrderUnits).plus(duration);
  } else {
    return duration;
  }
}

// node_modules/luxon/src/impl/tokenParser.js
init_esbuild_buffer_shim();
var MISSING_FTP = "missing Intl.DateTimeFormat.formatToParts support";
function intUnit(regex, post = (i) => i) {
  return { regex, deser: ([s2]) => post(parseDigits(s2)) };
}
var NBSP = String.fromCharCode(160);
var spaceOrNBSP = `[ ${NBSP}]`;
var spaceOrNBSPRegExp = new RegExp(spaceOrNBSP, "g");
function fixListRegex(s2) {
  return s2.replace(/\./g, "\\.?").replace(spaceOrNBSPRegExp, spaceOrNBSP);
}
function stripInsensitivities(s2) {
  return s2.replace(/\./g, "").replace(spaceOrNBSPRegExp, " ").toLowerCase();
}
function oneOf(strings, startIndex) {
  if (strings === null) {
    return null;
  } else {
    return {
      regex: RegExp(strings.map(fixListRegex).join("|")),
      deser: ([s2]) => strings.findIndex((i) => stripInsensitivities(s2) === stripInsensitivities(i)) + startIndex
    };
  }
}
function offset(regex, groups) {
  return { regex, deser: ([, h, m]) => signedOffset(h, m), groups };
}
function simple(regex) {
  return { regex, deser: ([s2]) => s2 };
}
function escapeToken(value) {
  return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
}
function unitForToken(token, loc) {
  const one = digitRegex(loc), two = digitRegex(loc, "{2}"), three = digitRegex(loc, "{3}"), four = digitRegex(loc, "{4}"), six = digitRegex(loc, "{6}"), oneOrTwo = digitRegex(loc, "{1,2}"), oneToThree = digitRegex(loc, "{1,3}"), oneToSix = digitRegex(loc, "{1,6}"), oneToNine = digitRegex(loc, "{1,9}"), twoToFour = digitRegex(loc, "{2,4}"), fourToSix = digitRegex(loc, "{4,6}"), literal = (t) => ({ regex: RegExp(escapeToken(t.val)), deser: ([s2]) => s2, literal: true }), unitate = (t) => {
    if (token.literal) {
      return literal(t);
    }
    switch (t.val) {
      // era
      case "G":
        return oneOf(loc.eras("short"), 0);
      case "GG":
        return oneOf(loc.eras("long"), 0);
      // years
      case "y":
        return intUnit(oneToSix);
      case "yy":
        return intUnit(twoToFour, untruncateYear);
      case "yyyy":
        return intUnit(four);
      case "yyyyy":
        return intUnit(fourToSix);
      case "yyyyyy":
        return intUnit(six);
      // months
      case "M":
        return intUnit(oneOrTwo);
      case "MM":
        return intUnit(two);
      case "MMM":
        return oneOf(loc.months("short", true), 1);
      case "MMMM":
        return oneOf(loc.months("long", true), 1);
      case "L":
        return intUnit(oneOrTwo);
      case "LL":
        return intUnit(two);
      case "LLL":
        return oneOf(loc.months("short", false), 1);
      case "LLLL":
        return oneOf(loc.months("long", false), 1);
      // dates
      case "d":
        return intUnit(oneOrTwo);
      case "dd":
        return intUnit(two);
      // ordinals
      case "o":
        return intUnit(oneToThree);
      case "ooo":
        return intUnit(three);
      // time
      case "HH":
        return intUnit(two);
      case "H":
        return intUnit(oneOrTwo);
      case "hh":
        return intUnit(two);
      case "h":
        return intUnit(oneOrTwo);
      case "mm":
        return intUnit(two);
      case "m":
        return intUnit(oneOrTwo);
      case "q":
        return intUnit(oneOrTwo);
      case "qq":
        return intUnit(two);
      case "s":
        return intUnit(oneOrTwo);
      case "ss":
        return intUnit(two);
      case "S":
        return intUnit(oneToThree);
      case "SSS":
        return intUnit(three);
      case "u":
        return simple(oneToNine);
      case "uu":
        return simple(oneOrTwo);
      case "uuu":
        return intUnit(one);
      // meridiem
      case "a":
        return oneOf(loc.meridiems(), 0);
      // weekYear (k)
      case "kkkk":
        return intUnit(four);
      case "kk":
        return intUnit(twoToFour, untruncateYear);
      // weekNumber (W)
      case "W":
        return intUnit(oneOrTwo);
      case "WW":
        return intUnit(two);
      // weekdays
      case "E":
      case "c":
        return intUnit(one);
      case "EEE":
        return oneOf(loc.weekdays("short", false), 1);
      case "EEEE":
        return oneOf(loc.weekdays("long", false), 1);
      case "ccc":
        return oneOf(loc.weekdays("short", true), 1);
      case "cccc":
        return oneOf(loc.weekdays("long", true), 1);
      // offset/zone
      case "Z":
      case "ZZ":
        return offset(new RegExp(`([+-]${oneOrTwo.source})(?::(${two.source}))?`), 2);
      case "ZZZ":
        return offset(new RegExp(`([+-]${oneOrTwo.source})(${two.source})?`), 2);
      // we don't support ZZZZ (PST) or ZZZZZ (Pacific Standard Time) in parsing
      // because we don't have any way to figure out what they are
      case "z":
        return simple(/[a-z_+-/]{1,256}?/i);
      // this special-case "token" represents a place where a macro-token expanded into a white-space literal
      // in this case we accept any non-newline white-space
      case " ":
        return simple(/[^\S\n\r]/);
      default:
        return literal(t);
    }
  };
  const unit = unitate(token) || {
    invalidReason: MISSING_FTP
  };
  unit.token = token;
  return unit;
}
var partTypeStyleToTokenVal = {
  year: {
    "2-digit": "yy",
    numeric: "yyyyy"
  },
  month: {
    numeric: "M",
    "2-digit": "MM",
    short: "MMM",
    long: "MMMM"
  },
  day: {
    numeric: "d",
    "2-digit": "dd"
  },
  weekday: {
    short: "EEE",
    long: "EEEE"
  },
  dayperiod: "a",
  dayPeriod: "a",
  hour12: {
    numeric: "h",
    "2-digit": "hh"
  },
  hour24: {
    numeric: "H",
    "2-digit": "HH"
  },
  minute: {
    numeric: "m",
    "2-digit": "mm"
  },
  second: {
    numeric: "s",
    "2-digit": "ss"
  },
  timeZoneName: {
    long: "ZZZZZ",
    short: "ZZZ"
  }
};
function tokenForPart(part, formatOpts, resolvedOpts) {
  const { type, value } = part;
  if (type === "literal") {
    const isSpace = /^\s+$/.test(value);
    return {
      literal: !isSpace,
      val: isSpace ? " " : value
    };
  }
  const style = formatOpts[type];
  let actualType = type;
  if (type === "hour") {
    if (formatOpts.hour12 != null) {
      actualType = formatOpts.hour12 ? "hour12" : "hour24";
    } else if (formatOpts.hourCycle != null) {
      if (formatOpts.hourCycle === "h11" || formatOpts.hourCycle === "h12") {
        actualType = "hour12";
      } else {
        actualType = "hour24";
      }
    } else {
      actualType = resolvedOpts.hour12 ? "hour12" : "hour24";
    }
  }
  let val = partTypeStyleToTokenVal[actualType];
  if (typeof val === "object") {
    val = val[style];
  }
  if (val) {
    return {
      literal: false,
      val
    };
  }
  return void 0;
}
function buildRegex(units) {
  const re = units.map((u) => u.regex).reduce((f, r) => `${f}(${r.source})`, "");
  return [`^${re}$`, units];
}
function match(input, regex, handlers) {
  const matches = input.match(regex);
  if (matches) {
    const all = {};
    let matchIndex = 1;
    for (const i in handlers) {
      if (hasOwnProperty(handlers, i)) {
        const h = handlers[i], groups = h.groups ? h.groups + 1 : 1;
        if (!h.literal && h.token) {
          all[h.token.val[0]] = h.deser(matches.slice(matchIndex, matchIndex + groups));
        }
        matchIndex += groups;
      }
    }
    return [matches, all];
  } else {
    return [matches, {}];
  }
}
function dateTimeFromMatches(matches) {
  const toField = (token) => {
    switch (token) {
      case "S":
        return "millisecond";
      case "s":
        return "second";
      case "m":
        return "minute";
      case "h":
      case "H":
        return "hour";
      case "d":
        return "day";
      case "o":
        return "ordinal";
      case "L":
      case "M":
        return "month";
      case "y":
        return "year";
      case "E":
      case "c":
        return "weekday";
      case "W":
        return "weekNumber";
      case "k":
        return "weekYear";
      case "q":
        return "quarter";
      default:
        return null;
    }
  };
  let zone = null;
  let specificOffset;
  if (!isUndefined(matches.z)) {
    zone = IANAZone.create(matches.z);
  }
  if (!isUndefined(matches.Z)) {
    if (!zone) {
      zone = new FixedOffsetZone(matches.Z);
    }
    specificOffset = matches.Z;
  }
  if (!isUndefined(matches.q)) {
    matches.M = (matches.q - 1) * 3 + 1;
  }
  if (!isUndefined(matches.h)) {
    if (matches.h < 12 && matches.a === 1) {
      matches.h += 12;
    } else if (matches.h === 12 && matches.a === 0) {
      matches.h = 0;
    }
  }
  if (matches.G === 0 && matches.y) {
    matches.y = -matches.y;
  }
  if (!isUndefined(matches.u)) {
    matches.S = parseMillis(matches.u);
  }
  const vals = Object.keys(matches).reduce((r, k) => {
    const f = toField(k);
    if (f) {
      r[f] = matches[k];
    }
    return r;
  }, {});
  return [vals, zone, specificOffset];
}
var dummyDateTimeCache = null;
function getDummyDateTime() {
  if (!dummyDateTimeCache) {
    dummyDateTimeCache = DateTime.fromMillis(1555555555555);
  }
  return dummyDateTimeCache;
}
function maybeExpandMacroToken(token, locale) {
  if (token.literal) {
    return token;
  }
  const formatOpts = Formatter.macroTokenToFormatOpts(token.val);
  const tokens = formatOptsToTokens(formatOpts, locale);
  if (tokens == null || tokens.includes(void 0)) {
    return token;
  }
  return tokens;
}
function expandMacroTokens(tokens, locale) {
  return Array.prototype.concat(...tokens.map((t) => maybeExpandMacroToken(t, locale)));
}
var TokenParser = class {
  constructor(locale, format) {
    this.locale = locale;
    this.format = format;
    this.tokens = expandMacroTokens(Formatter.parseFormat(format), locale);
    this.units = this.tokens.map((t) => unitForToken(t, locale));
    this.disqualifyingUnit = this.units.find((t) => t.invalidReason);
    if (!this.disqualifyingUnit) {
      const [regexString, handlers] = buildRegex(this.units);
      this.regex = RegExp(regexString, "i");
      this.handlers = handlers;
    }
  }
  explainFromTokens(input) {
    if (!this.isValid) {
      return { input, tokens: this.tokens, invalidReason: this.invalidReason };
    } else {
      const [rawMatches, matches] = match(input, this.regex, this.handlers), [result, zone, specificOffset] = matches ? dateTimeFromMatches(matches) : [null, null, void 0];
      if (hasOwnProperty(matches, "a") && hasOwnProperty(matches, "H")) {
        throw new ConflictingSpecificationError(
          "Can't include meridiem when specifying 24-hour format"
        );
      }
      return {
        input,
        tokens: this.tokens,
        regex: this.regex,
        rawMatches,
        matches,
        result,
        zone,
        specificOffset
      };
    }
  }
  get isValid() {
    return !this.disqualifyingUnit;
  }
  get invalidReason() {
    return this.disqualifyingUnit ? this.disqualifyingUnit.invalidReason : null;
  }
};
function explainFromTokens(locale, input, format) {
  const parser = new TokenParser(locale, format);
  return parser.explainFromTokens(input);
}
function parseFromTokens(locale, input, format) {
  const { result, zone, specificOffset, invalidReason } = explainFromTokens(locale, input, format);
  return [result, zone, specificOffset, invalidReason];
}
function formatOptsToTokens(formatOpts, locale) {
  if (!formatOpts) {
    return null;
  }
  const formatter = Formatter.create(locale, formatOpts);
  const df = formatter.dtFormatter(getDummyDateTime());
  const parts = df.formatToParts();
  const resolvedOpts = df.resolvedOptions();
  return parts.map((p) => tokenForPart(p, formatOpts, resolvedOpts));
}

// node_modules/luxon/src/datetime.js
var INVALID3 = "Invalid DateTime";
var MAX_DATE = 864e13;
function unsupportedZone(zone) {
  return new Invalid("unsupported zone", `the zone "${zone.name}" is not supported`);
}
function possiblyCachedWeekData(dt) {
  if (dt.weekData === null) {
    dt.weekData = gregorianToWeek(dt.c);
  }
  return dt.weekData;
}
function possiblyCachedLocalWeekData(dt) {
  if (dt.localWeekData === null) {
    dt.localWeekData = gregorianToWeek(
      dt.c,
      dt.loc.getMinDaysInFirstWeek(),
      dt.loc.getStartOfWeek()
    );
  }
  return dt.localWeekData;
}
function clone2(inst, alts) {
  const current = {
    ts: inst.ts,
    zone: inst.zone,
    c: inst.c,
    o: inst.o,
    loc: inst.loc,
    invalid: inst.invalid
  };
  return new DateTime({ ...current, ...alts, old: current });
}
function fixOffset(localTS, o, tz) {
  let utcGuess = localTS - o * 60 * 1e3;
  const o2 = tz.offset(utcGuess);
  if (o === o2) {
    return [utcGuess, o];
  }
  utcGuess -= (o2 - o) * 60 * 1e3;
  const o3 = tz.offset(utcGuess);
  if (o2 === o3) {
    return [utcGuess, o2];
  }
  return [localTS - Math.min(o2, o3) * 60 * 1e3, Math.max(o2, o3)];
}
function tsToObj(ts, offset2) {
  ts += offset2 * 60 * 1e3;
  const d = new Date(ts);
  return {
    year: d.getUTCFullYear(),
    month: d.getUTCMonth() + 1,
    day: d.getUTCDate(),
    hour: d.getUTCHours(),
    minute: d.getUTCMinutes(),
    second: d.getUTCSeconds(),
    millisecond: d.getUTCMilliseconds()
  };
}
function objToTS(obj, offset2, zone) {
  return fixOffset(objToLocalTS(obj), offset2, zone);
}
function adjustTime(inst, dur) {
  const oPre = inst.o, year = inst.c.year + Math.trunc(dur.years), month = inst.c.month + Math.trunc(dur.months) + Math.trunc(dur.quarters) * 3, c = {
    ...inst.c,
    year,
    month,
    day: Math.min(inst.c.day, daysInMonth(year, month)) + Math.trunc(dur.days) + Math.trunc(dur.weeks) * 7
  }, millisToAdd = Duration.fromObject({
    years: dur.years - Math.trunc(dur.years),
    quarters: dur.quarters - Math.trunc(dur.quarters),
    months: dur.months - Math.trunc(dur.months),
    weeks: dur.weeks - Math.trunc(dur.weeks),
    days: dur.days - Math.trunc(dur.days),
    hours: dur.hours,
    minutes: dur.minutes,
    seconds: dur.seconds,
    milliseconds: dur.milliseconds
  }).as("milliseconds"), localTS = objToLocalTS(c);
  let [ts, o] = fixOffset(localTS, oPre, inst.zone);
  if (millisToAdd !== 0) {
    ts += millisToAdd;
    o = inst.zone.offset(ts);
  }
  return { ts, o };
}
function parseDataToDateTime(parsed, parsedZone, opts, format, text2, specificOffset) {
  const { setZone, zone } = opts;
  if (parsed && Object.keys(parsed).length !== 0 || parsedZone) {
    const interpretationZone = parsedZone || zone, inst = DateTime.fromObject(parsed, {
      ...opts,
      zone: interpretationZone,
      specificOffset
    });
    return setZone ? inst : inst.setZone(zone);
  } else {
    return DateTime.invalid(
      new Invalid("unparsable", `the input "${text2}" can't be parsed as ${format}`)
    );
  }
}
function toTechFormat(dt, format, allowZ = true) {
  return dt.isValid ? Formatter.create(Locale.create("en-US"), {
    allowZ,
    forceSimple: true
  }).formatDateTimeFromString(dt, format) : null;
}
function toISODate(o, extended) {
  const longFormat = o.c.year > 9999 || o.c.year < 0;
  let c = "";
  if (longFormat && o.c.year >= 0) c += "+";
  c += padStart(o.c.year, longFormat ? 6 : 4);
  if (extended) {
    c += "-";
    c += padStart(o.c.month);
    c += "-";
    c += padStart(o.c.day);
  } else {
    c += padStart(o.c.month);
    c += padStart(o.c.day);
  }
  return c;
}
function toISOTime(o, extended, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone) {
  let c = padStart(o.c.hour);
  if (extended) {
    c += ":";
    c += padStart(o.c.minute);
    if (o.c.millisecond !== 0 || o.c.second !== 0 || !suppressSeconds) {
      c += ":";
    }
  } else {
    c += padStart(o.c.minute);
  }
  if (o.c.millisecond !== 0 || o.c.second !== 0 || !suppressSeconds) {
    c += padStart(o.c.second);
    if (o.c.millisecond !== 0 || !suppressMilliseconds) {
      c += ".";
      c += padStart(o.c.millisecond, 3);
    }
  }
  if (includeOffset) {
    if (o.isOffsetFixed && o.offset === 0 && !extendedZone) {
      c += "Z";
    } else if (o.o < 0) {
      c += "-";
      c += padStart(Math.trunc(-o.o / 60));
      c += ":";
      c += padStart(Math.trunc(-o.o % 60));
    } else {
      c += "+";
      c += padStart(Math.trunc(o.o / 60));
      c += ":";
      c += padStart(Math.trunc(o.o % 60));
    }
  }
  if (extendedZone) {
    c += "[" + o.zone.ianaName + "]";
  }
  return c;
}
var defaultUnitValues = {
  month: 1,
  day: 1,
  hour: 0,
  minute: 0,
  second: 0,
  millisecond: 0
};
var defaultWeekUnitValues = {
  weekNumber: 1,
  weekday: 1,
  hour: 0,
  minute: 0,
  second: 0,
  millisecond: 0
};
var defaultOrdinalUnitValues = {
  ordinal: 1,
  hour: 0,
  minute: 0,
  second: 0,
  millisecond: 0
};
var orderedUnits2 = ["year", "month", "day", "hour", "minute", "second", "millisecond"];
var orderedWeekUnits = [
  "weekYear",
  "weekNumber",
  "weekday",
  "hour",
  "minute",
  "second",
  "millisecond"
];
var orderedOrdinalUnits = ["year", "ordinal", "hour", "minute", "second", "millisecond"];
function normalizeUnit(unit) {
  const normalized = {
    year: "year",
    years: "year",
    month: "month",
    months: "month",
    day: "day",
    days: "day",
    hour: "hour",
    hours: "hour",
    minute: "minute",
    minutes: "minute",
    quarter: "quarter",
    quarters: "quarter",
    second: "second",
    seconds: "second",
    millisecond: "millisecond",
    milliseconds: "millisecond",
    weekday: "weekday",
    weekdays: "weekday",
    weeknumber: "weekNumber",
    weeksnumber: "weekNumber",
    weeknumbers: "weekNumber",
    weekyear: "weekYear",
    weekyears: "weekYear",
    ordinal: "ordinal"
  }[unit.toLowerCase()];
  if (!normalized) throw new InvalidUnitError(unit);
  return normalized;
}
function normalizeUnitWithLocalWeeks(unit) {
  switch (unit.toLowerCase()) {
    case "localweekday":
    case "localweekdays":
      return "localWeekday";
    case "localweeknumber":
    case "localweeknumbers":
      return "localWeekNumber";
    case "localweekyear":
    case "localweekyears":
      return "localWeekYear";
    default:
      return normalizeUnit(unit);
  }
}
function guessOffsetForZone(zone) {
  if (zoneOffsetTs === void 0) {
    zoneOffsetTs = Settings.now();
  }
  if (zone.type !== "iana") {
    return zone.offset(zoneOffsetTs);
  }
  const zoneName = zone.name;
  let offsetGuess = zoneOffsetGuessCache.get(zoneName);
  if (offsetGuess === void 0) {
    offsetGuess = zone.offset(zoneOffsetTs);
    zoneOffsetGuessCache.set(zoneName, offsetGuess);
  }
  return offsetGuess;
}
function quickDT(obj, opts) {
  const zone = normalizeZone(opts.zone, Settings.defaultZone);
  if (!zone.isValid) {
    return DateTime.invalid(unsupportedZone(zone));
  }
  const loc = Locale.fromObject(opts);
  let ts, o;
  if (!isUndefined(obj.year)) {
    for (const u of orderedUnits2) {
      if (isUndefined(obj[u])) {
        obj[u] = defaultUnitValues[u];
      }
    }
    const invalid = hasInvalidGregorianData(obj) || hasInvalidTimeData(obj);
    if (invalid) {
      return DateTime.invalid(invalid);
    }
    const offsetProvis = guessOffsetForZone(zone);
    [ts, o] = objToTS(obj, offsetProvis, zone);
  } else {
    ts = Settings.now();
  }
  return new DateTime({ ts, zone, loc, o });
}
function diffRelative(start, end, opts) {
  const round = isUndefined(opts.round) ? true : opts.round, format = (c, unit) => {
    c = roundTo(c, round || opts.calendary ? 0 : 2, true);
    const formatter = end.loc.clone(opts).relFormatter(opts);
    return formatter.format(c, unit);
  }, differ = (unit) => {
    if (opts.calendary) {
      if (!end.hasSame(start, unit)) {
        return end.startOf(unit).diff(start.startOf(unit), unit).get(unit);
      } else return 0;
    } else {
      return end.diff(start, unit).get(unit);
    }
  };
  if (opts.unit) {
    return format(differ(opts.unit), opts.unit);
  }
  for (const unit of opts.units) {
    const count = differ(unit);
    if (Math.abs(count) >= 1) {
      return format(count, unit);
    }
  }
  return format(start > end ? -0 : 0, opts.units[opts.units.length - 1]);
}
function lastOpts(argList) {
  let opts = {}, args;
  if (argList.length > 0 && typeof argList[argList.length - 1] === "object") {
    opts = argList[argList.length - 1];
    args = Array.from(argList).slice(0, argList.length - 1);
  } else {
    args = Array.from(argList);
  }
  return [opts, args];
}
var zoneOffsetTs;
var zoneOffsetGuessCache = /* @__PURE__ */ new Map();
var DateTime = class _DateTime {
  /**
   * @access private
   */
  constructor(config) {
    const zone = config.zone || Settings.defaultZone;
    let invalid = config.invalid || (Number.isNaN(config.ts) ? new Invalid("invalid input") : null) || (!zone.isValid ? unsupportedZone(zone) : null);
    this.ts = isUndefined(config.ts) ? Settings.now() : config.ts;
    let c = null, o = null;
    if (!invalid) {
      const unchanged = config.old && config.old.ts === this.ts && config.old.zone.equals(zone);
      if (unchanged) {
        [c, o] = [config.old.c, config.old.o];
      } else {
        const ot = isNumber(config.o) && !config.old ? config.o : zone.offset(this.ts);
        c = tsToObj(this.ts, ot);
        invalid = Number.isNaN(c.year) ? new Invalid("invalid input") : null;
        c = invalid ? null : c;
        o = invalid ? null : ot;
      }
    }
    this._zone = zone;
    this.loc = config.loc || Locale.create();
    this.invalid = invalid;
    this.weekData = null;
    this.localWeekData = null;
    this.c = c;
    this.o = o;
    this.isLuxonDateTime = true;
  }
  // CONSTRUCT
  /**
   * Create a DateTime for the current instant, in the system's time zone.
   *
   * Use Settings to override these default values if needed.
   * @example DateTime.now().toISO() //~> now in the ISO format
   * @return {DateTime}
   */
  static now() {
    return new _DateTime({});
  }
  /**
   * Create a local DateTime
   * @param {number} [year] - The calendar year. If omitted (as in, call `local()` with no arguments), the current time will be used
   * @param {number} [month=1] - The month, 1-indexed
   * @param {number} [day=1] - The day of the month, 1-indexed
   * @param {number} [hour=0] - The hour of the day, in 24-hour time
   * @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59
   * @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59
   * @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999
   * @example DateTime.local()                                  //~> now
   * @example DateTime.local({ zone: "America/New_York" })      //~> now, in US east coast time
   * @example DateTime.local(2017)                              //~> 2017-01-01T00:00:00
   * @example DateTime.local(2017, 3)                           //~> 2017-03-01T00:00:00
   * @example DateTime.local(2017, 3, 12, { locale: "fr" })     //~> 2017-03-12T00:00:00, with a French locale
   * @example DateTime.local(2017, 3, 12, 5)                    //~> 2017-03-12T05:00:00
   * @example DateTime.local(2017, 3, 12, 5, { zone: "utc" })   //~> 2017-03-12T05:00:00, in UTC
   * @example DateTime.local(2017, 3, 12, 5, 45)                //~> 2017-03-12T05:45:00
   * @example DateTime.local(2017, 3, 12, 5, 45, 10)            //~> 2017-03-12T05:45:10
   * @example DateTime.local(2017, 3, 12, 5, 45, 10, 765)       //~> 2017-03-12T05:45:10.765
   * @return {DateTime}
   */
  static local() {
    const [opts, args] = lastOpts(arguments), [year, month, day, hour, minute, second, millisecond] = args;
    return quickDT({ year, month, day, hour, minute, second, millisecond }, opts);
  }
  /**
   * Create a DateTime in UTC
   * @param {number} [year] - The calendar year. If omitted (as in, call `utc()` with no arguments), the current time will be used
   * @param {number} [month=1] - The month, 1-indexed
   * @param {number} [day=1] - The day of the month
   * @param {number} [hour=0] - The hour of the day, in 24-hour time
   * @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59
   * @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59
   * @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999
   * @param {Object} options - configuration options for the DateTime
   * @param {string} [options.locale] - a locale to set on the resulting DateTime instance
   * @param {string} [options.outputCalendar] - the output calendar to set on the resulting DateTime instance
   * @param {string} [options.numberingSystem] - the numbering system to set on the resulting DateTime instance
   * @param {string} [options.weekSettings] - the week settings to set on the resulting DateTime instance
   * @example DateTime.utc()                                              //~> now
   * @example DateTime.utc(2017)                                          //~> 2017-01-01T00:00:00Z
   * @example DateTime.utc(2017, 3)                                       //~> 2017-03-01T00:00:00Z
   * @example DateTime.utc(2017, 3, 12)                                   //~> 2017-03-12T00:00:00Z
   * @example DateTime.utc(2017, 3, 12, 5)                                //~> 2017-03-12T05:00:00Z
   * @example DateTime.utc(2017, 3, 12, 5, 45)                            //~> 2017-03-12T05:45:00Z
   * @example DateTime.utc(2017, 3, 12, 5, 45, { locale: "fr" })          //~> 2017-03-12T05:45:00Z with a French locale
   * @example DateTime.utc(2017, 3, 12, 5, 45, 10)                        //~> 2017-03-12T05:45:10Z
   * @example DateTime.utc(2017, 3, 12, 5, 45, 10, 765, { locale: "fr" }) //~> 2017-03-12T05:45:10.765Z with a French locale
   * @return {DateTime}
   */
  static utc() {
    const [opts, args] = lastOpts(arguments), [year, month, day, hour, minute, second, millisecond] = args;
    opts.zone = FixedOffsetZone.utcInstance;
    return quickDT({ year, month, day, hour, minute, second, millisecond }, opts);
  }
  /**
   * Create a DateTime from a JavaScript Date object. Uses the default zone.
   * @param {Date} date - a JavaScript Date object
   * @param {Object} options - configuration options for the DateTime
   * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into
   * @return {DateTime}
   */
  static fromJSDate(date, options = {}) {
    const ts = isDate(date) ? date.valueOf() : NaN;
    if (Number.isNaN(ts)) {
      return _DateTime.invalid("invalid input");
    }
    const zoneToUse = normalizeZone(options.zone, Settings.defaultZone);
    if (!zoneToUse.isValid) {
      return _DateTime.invalid(unsupportedZone(zoneToUse));
    }
    return new _DateTime({
      ts,
      zone: zoneToUse,
      loc: Locale.fromObject(options)
    });
  }
  /**
   * Create a DateTime from a number of milliseconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone.
   * @param {number} milliseconds - a number of milliseconds since 1970 UTC
   * @param {Object} options - configuration options for the DateTime
   * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into
   * @param {string} [options.locale] - a locale to set on the resulting DateTime instance
   * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance
   * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance
   * @param {string} options.weekSettings - the week settings to set on the resulting DateTime instance
   * @return {DateTime}
   */
  static fromMillis(milliseconds, options = {}) {
    if (!isNumber(milliseconds)) {
      throw new InvalidArgumentError(
        `fromMillis requires a numerical input, but received a ${typeof milliseconds} with value ${milliseconds}`
      );
    } else if (milliseconds < -MAX_DATE || milliseconds > MAX_DATE) {
      return _DateTime.invalid("Timestamp out of range");
    } else {
      return new _DateTime({
        ts: milliseconds,
        zone: normalizeZone(options.zone, Settings.defaultZone),
        loc: Locale.fromObject(options)
      });
    }
  }
  /**
   * Create a DateTime from a number of seconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone.
   * @param {number} seconds - a number of seconds since 1970 UTC
   * @param {Object} options - configuration options for the DateTime
   * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into
   * @param {string} [options.locale] - a locale to set on the resulting DateTime instance
   * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance
   * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance
   * @param {string} options.weekSettings - the week settings to set on the resulting DateTime instance
   * @return {DateTime}
   */
  static fromSeconds(seconds, options = {}) {
    if (!isNumber(seconds)) {
      throw new InvalidArgumentError("fromSeconds requires a numerical input");
    } else {
      return new _DateTime({
        ts: seconds * 1e3,
        zone: normalizeZone(options.zone, Settings.defaultZone),
        loc: Locale.fromObject(options)
      });
    }
  }
  /**
   * Create a DateTime from a JavaScript object with keys like 'year' and 'hour' with reasonable defaults.
   * @param {Object} obj - the object to create the DateTime from
   * @param {number} obj.year - a year, such as 1987
   * @param {number} obj.month - a month, 1-12
   * @param {number} obj.day - a day of the month, 1-31, depending on the month
   * @param {number} obj.ordinal - day of the year, 1-365 or 366
   * @param {number} obj.weekYear - an ISO week year
   * @param {number} obj.weekNumber - an ISO week number, between 1 and 52 or 53, depending on the year
   * @param {number} obj.weekday - an ISO weekday, 1-7, where 1 is Monday and 7 is Sunday
   * @param {number} obj.localWeekYear - a week year, according to the locale
   * @param {number} obj.localWeekNumber - a week number, between 1 and 52 or 53, depending on the year, according to the locale
   * @param {number} obj.localWeekday - a weekday, 1-7, where 1 is the first and 7 is the last day of the week, according to the locale
   * @param {number} obj.hour - hour of the day, 0-23
   * @param {number} obj.minute - minute of the hour, 0-59
   * @param {number} obj.second - second of the minute, 0-59
   * @param {number} obj.millisecond - millisecond of the second, 0-999
   * @param {Object} opts - options for creating this DateTime
   * @param {string|Zone} [opts.zone='local'] - interpret the numbers in the context of a particular zone. Can take any value taken as the first argument to setZone()
   * @param {string} [opts.locale='system\'s locale'] - a locale to set on the resulting DateTime instance
   * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
   * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance
   * @param {string} opts.weekSettings - the week settings to set on the resulting DateTime instance
   * @example DateTime.fromObject({ year: 1982, month: 5, day: 25}).toISODate() //=> '1982-05-25'
   * @example DateTime.fromObject({ year: 1982 }).toISODate() //=> '1982-01-01'
   * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }) //~> today at 10:26:06
   * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'utc' }),
   * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'local' })
   * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'America/New_York' })
   * @example DateTime.fromObject({ weekYear: 2016, weekNumber: 2, weekday: 3 }).toISODate() //=> '2016-01-13'
   * @example DateTime.fromObject({ localWeekYear: 2022, localWeekNumber: 1, localWeekday: 1 }, { locale: "en-US" }).toISODate() //=> '2021-12-26'
   * @return {DateTime}
   */
  static fromObject(obj, opts = {}) {
    obj = obj || {};
    const zoneToUse = normalizeZone(opts.zone, Settings.defaultZone);
    if (!zoneToUse.isValid) {
      return _DateTime.invalid(unsupportedZone(zoneToUse));
    }
    const loc = Locale.fromObject(opts);
    const normalized = normalizeObject(obj, normalizeUnitWithLocalWeeks);
    const { minDaysInFirstWeek, startOfWeek } = usesLocalWeekValues(normalized, loc);
    const tsNow = Settings.now(), offsetProvis = !isUndefined(opts.specificOffset) ? opts.specificOffset : zoneToUse.offset(tsNow), containsOrdinal = !isUndefined(normalized.ordinal), containsGregorYear = !isUndefined(normalized.year), containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day), containsGregor = containsGregorYear || containsGregorMD, definiteWeekDef = normalized.weekYear || normalized.weekNumber;
    if ((containsGregor || containsOrdinal) && definiteWeekDef) {
      throw new ConflictingSpecificationError(
        "Can't mix weekYear/weekNumber units with year/month/day or ordinals"
      );
    }
    if (containsGregorMD && containsOrdinal) {
      throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day");
    }
    const useWeekData = definiteWeekDef || normalized.weekday && !containsGregor;
    let units, defaultValues, objNow = tsToObj(tsNow, offsetProvis);
    if (useWeekData) {
      units = orderedWeekUnits;
      defaultValues = defaultWeekUnitValues;
      objNow = gregorianToWeek(objNow, minDaysInFirstWeek, startOfWeek);
    } else if (containsOrdinal) {
      units = orderedOrdinalUnits;
      defaultValues = defaultOrdinalUnitValues;
      objNow = gregorianToOrdinal(objNow);
    } else {
      units = orderedUnits2;
      defaultValues = defaultUnitValues;
    }
    let foundFirst = false;
    for (const u of units) {
      const v = normalized[u];
      if (!isUndefined(v)) {
        foundFirst = true;
      } else if (foundFirst) {
        normalized[u] = defaultValues[u];
      } else {
        normalized[u] = objNow[u];
      }
    }
    const higherOrderInvalid = useWeekData ? hasInvalidWeekData(normalized, minDaysInFirstWeek, startOfWeek) : containsOrdinal ? hasInvalidOrdinalData(normalized) : hasInvalidGregorianData(normalized), invalid = higherOrderInvalid || hasInvalidTimeData(normalized);
    if (invalid) {
      return _DateTime.invalid(invalid);
    }
    const gregorian = useWeekData ? weekToGregorian(normalized, minDaysInFirstWeek, startOfWeek) : containsOrdinal ? ordinalToGregorian(normalized) : normalized, [tsFinal, offsetFinal] = objToTS(gregorian, offsetProvis, zoneToUse), inst = new _DateTime({
      ts: tsFinal,
      zone: zoneToUse,
      o: offsetFinal,
      loc
    });
    if (normalized.weekday && containsGregor && obj.weekday !== inst.weekday) {
      return _DateTime.invalid(
        "mismatched weekday",
        `you can't specify both a weekday of ${normalized.weekday} and a date of ${inst.toISO()}`
      );
    }
    if (!inst.isValid) {
      return _DateTime.invalid(inst.invalid);
    }
    return inst;
  }
  /**
   * Create a DateTime from an ISO 8601 string
   * @param {string} text - the ISO string
   * @param {Object} opts - options to affect the creation
   * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the time to this zone
   * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one
   * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance
   * @param {string} [opts.outputCalendar] - the output calendar to set on the resulting DateTime instance
   * @param {string} [opts.numberingSystem] - the numbering system to set on the resulting DateTime instance
   * @param {string} [opts.weekSettings] - the week settings to set on the resulting DateTime instance
   * @example DateTime.fromISO('2016-05-25T09:08:34.123')
   * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00')
   * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00', {setZone: true})
   * @example DateTime.fromISO('2016-05-25T09:08:34.123', {zone: 'utc'})
   * @example DateTime.fromISO('2016-W05-4')
   * @return {DateTime}
   */
  static fromISO(text2, opts = {}) {
    const [vals, parsedZone] = parseISODate(text2);
    return parseDataToDateTime(vals, parsedZone, opts, "ISO 8601", text2);
  }
  /**
   * Create a DateTime from an RFC 2822 string
   * @param {string} text - the RFC 2822 string
   * @param {Object} opts - options to affect the creation
   * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since the offset is always specified in the string itself, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in.
   * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one
   * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance
   * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
   * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance
   * @param {string} opts.weekSettings - the week settings to set on the resulting DateTime instance
   * @example DateTime.fromRFC2822('25 Nov 2016 13:23:12 GMT')
   * @example DateTime.fromRFC2822('Fri, 25 Nov 2016 13:23:12 +0600')
   * @example DateTime.fromRFC2822('25 Nov 2016 13:23 Z')
   * @return {DateTime}
   */
  static fromRFC2822(text2, opts = {}) {
    const [vals, parsedZone] = parseRFC2822Date(text2);
    return parseDataToDateTime(vals, parsedZone, opts, "RFC 2822", text2);
  }
  /**
   * Create a DateTime from an HTTP header date
   * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1
   * @param {string} text - the HTTP header date
   * @param {Object} opts - options to affect the creation
   * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since HTTP dates are always in UTC, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in.
   * @param {boolean} [opts.setZone=false] - override the zone with the fixed-offset zone specified in the string. For HTTP dates, this is always UTC, so this option is equivalent to setting the `zone` option to 'utc', but this option is included for consistency with similar methods.
   * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance
   * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
   * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance
   * @param {string} opts.weekSettings - the week settings to set on the resulting DateTime instance
   * @example DateTime.fromHTTP('Sun, 06 Nov 1994 08:49:37 GMT')
   * @example DateTime.fromHTTP('Sunday, 06-Nov-94 08:49:37 GMT')
   * @example DateTime.fromHTTP('Sun Nov  6 08:49:37 1994')
   * @return {DateTime}
   */
  static fromHTTP(text2, opts = {}) {
    const [vals, parsedZone] = parseHTTPDate(text2);
    return parseDataToDateTime(vals, parsedZone, opts, "HTTP", opts);
  }
  /**
   * Create a DateTime from an input string and format string.
   * Defaults to en-US if no locale has been specified, regardless of the system's locale. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/#/parsing?id=table-of-tokens).
   * @param {string} text - the string to parse
   * @param {string} fmt - the format the string is expected to be in (see the link below for the formats)
   * @param {Object} opts - options to affect the creation
   * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone
   * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one
   * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale
   * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system
   * @param {string} opts.weekSettings - the week settings to set on the resulting DateTime instance
   * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
   * @return {DateTime}
   */
  static fromFormat(text2, fmt, opts = {}) {
    if (isUndefined(text2) || isUndefined(fmt)) {
      throw new InvalidArgumentError("fromFormat requires an input string and a format");
    }
    const { locale = null, numberingSystem = null } = opts, localeToUse = Locale.fromOpts({
      locale,
      numberingSystem,
      defaultToEN: true
    }), [vals, parsedZone, specificOffset, invalid] = parseFromTokens(localeToUse, text2, fmt);
    if (invalid) {
      return _DateTime.invalid(invalid);
    } else {
      return parseDataToDateTime(vals, parsedZone, opts, `format ${fmt}`, text2, specificOffset);
    }
  }
  /**
   * @deprecated use fromFormat instead
   */
  static fromString(text2, fmt, opts = {}) {
    return _DateTime.fromFormat(text2, fmt, opts);
  }
  /**
   * Create a DateTime from a SQL date, time, or datetime
   * Defaults to en-US if no locale has been specified, regardless of the system's locale
   * @param {string} text - the string to parse
   * @param {Object} opts - options to affect the creation
   * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone
   * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one
   * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale
   * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system
   * @param {string} opts.weekSettings - the week settings to set on the resulting DateTime instance
   * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
   * @example DateTime.fromSQL('2017-05-15')
   * @example DateTime.fromSQL('2017-05-15 09:12:34')
   * @example DateTime.fromSQL('2017-05-15 09:12:34.342')
   * @example DateTime.fromSQL('2017-05-15 09:12:34.342+06:00')
   * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles')
   * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles', { setZone: true })
   * @example DateTime.fromSQL('2017-05-15 09:12:34.342', { zone: 'America/Los_Angeles' })
   * @example DateTime.fromSQL('09:12:34.342')
   * @return {DateTime}
   */
  static fromSQL(text2, opts = {}) {
    const [vals, parsedZone] = parseSQL(text2);
    return parseDataToDateTime(vals, parsedZone, opts, "SQL", text2);
  }
  /**
   * Create an invalid DateTime.
   * @param {string} reason - simple string of why this DateTime is invalid. Should not contain parameters or anything else data-dependent.
   * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information
   * @return {DateTime}
   */
  static invalid(reason, explanation = null) {
    if (!reason) {
      throw new InvalidArgumentError("need to specify a reason the DateTime is invalid");
    }
    const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
    if (Settings.throwOnInvalid) {
      throw new InvalidDateTimeError(invalid);
    } else {
      return new _DateTime({ invalid });
    }
  }
  /**
   * Check if an object is an instance of DateTime. Works across context boundaries
   * @param {object} o
   * @return {boolean}
   */
  static isDateTime(o) {
    return o && o.isLuxonDateTime || false;
  }
  /**
   * Produce the format string for a set of options
   * @param formatOpts
   * @param localeOpts
   * @returns {string}
   */
  static parseFormatForOpts(formatOpts, localeOpts = {}) {
    const tokenList = formatOptsToTokens(formatOpts, Locale.fromObject(localeOpts));
    return !tokenList ? null : tokenList.map((t) => t ? t.val : null).join("");
  }
  /**
   * Produce the the fully expanded format token for the locale
   * Does NOT quote characters, so quoted tokens will not round trip correctly
   * @param fmt
   * @param localeOpts
   * @returns {string}
   */
  static expandFormat(fmt, localeOpts = {}) {
    const expanded = expandMacroTokens(Formatter.parseFormat(fmt), Locale.fromObject(localeOpts));
    return expanded.map((t) => t.val).join("");
  }
  static resetCache() {
    zoneOffsetTs = void 0;
    zoneOffsetGuessCache.clear();
  }
  // INFO
  /**
   * Get the value of unit.
   * @param {string} unit - a unit such as 'minute' or 'day'
   * @example DateTime.local(2017, 7, 4).get('month'); //=> 7
   * @example DateTime.local(2017, 7, 4).get('day'); //=> 4
   * @return {number}
   */
  get(unit) {
    return this[unit];
  }
  /**
   * Returns whether the DateTime is valid. Invalid DateTimes occur when:
   * * The DateTime was created from invalid calendar information, such as the 13th month or February 30
   * * The DateTime was created by an operation on another invalid date
   * @type {boolean}
   */
  get isValid() {
    return this.invalid === null;
  }
  /**
   * Returns an error code if this DateTime is invalid, or null if the DateTime is valid
   * @type {string}
   */
  get invalidReason() {
    return this.invalid ? this.invalid.reason : null;
  }
  /**
   * Returns an explanation of why this DateTime became invalid, or null if the DateTime is valid
   * @type {string}
   */
  get invalidExplanation() {
    return this.invalid ? this.invalid.explanation : null;
  }
  /**
   * Get the locale of a DateTime, such 'en-GB'. The locale is used when formatting the DateTime
   *
   * @type {string}
   */
  get locale() {
    return this.isValid ? this.loc.locale : null;
  }
  /**
   * Get the numbering system of a DateTime, such 'beng'. The numbering system is used when formatting the DateTime
   *
   * @type {string}
   */
  get numberingSystem() {
    return this.isValid ? this.loc.numberingSystem : null;
  }
  /**
   * Get the output calendar of a DateTime, such 'islamic'. The output calendar is used when formatting the DateTime
   *
   * @type {string}
   */
  get outputCalendar() {
    return this.isValid ? this.loc.outputCalendar : null;
  }
  /**
   * Get the time zone associated with this DateTime.
   * @type {Zone}
   */
  get zone() {
    return this._zone;
  }
  /**
   * Get the name of the time zone.
   * @type {string}
   */
  get zoneName() {
    return this.isValid ? this.zone.name : null;
  }
  /**
   * Get the year
   * @example DateTime.local(2017, 5, 25).year //=> 2017
   * @type {number}
   */
  get year() {
    return this.isValid ? this.c.year : NaN;
  }
  /**
   * Get the quarter
   * @example DateTime.local(2017, 5, 25).quarter //=> 2
   * @type {number}
   */
  get quarter() {
    return this.isValid ? Math.ceil(this.c.month / 3) : NaN;
  }
  /**
   * Get the month (1-12).
   * @example DateTime.local(2017, 5, 25).month //=> 5
   * @type {number}
   */
  get month() {
    return this.isValid ? this.c.month : NaN;
  }
  /**
   * Get the day of the month (1-30ish).
   * @example DateTime.local(2017, 5, 25).day //=> 25
   * @type {number}
   */
  get day() {
    return this.isValid ? this.c.day : NaN;
  }
  /**
   * Get the hour of the day (0-23).
   * @example DateTime.local(2017, 5, 25, 9).hour //=> 9
   * @type {number}
   */
  get hour() {
    return this.isValid ? this.c.hour : NaN;
  }
  /**
   * Get the minute of the hour (0-59).
   * @example DateTime.local(2017, 5, 25, 9, 30).minute //=> 30
   * @type {number}
   */
  get minute() {
    return this.isValid ? this.c.minute : NaN;
  }
  /**
   * Get the second of the minute (0-59).
   * @example DateTime.local(2017, 5, 25, 9, 30, 52).second //=> 52
   * @type {number}
   */
  get second() {
    return this.isValid ? this.c.second : NaN;
  }
  /**
   * Get the millisecond of the second (0-999).
   * @example DateTime.local(2017, 5, 25, 9, 30, 52, 654).millisecond //=> 654
   * @type {number}
   */
  get millisecond() {
    return this.isValid ? this.c.millisecond : NaN;
  }
  /**
   * Get the week year
   * @see https://en.wikipedia.org/wiki/ISO_week_date
   * @example DateTime.local(2014, 12, 31).weekYear //=> 2015
   * @type {number}
   */
  get weekYear() {
    return this.isValid ? possiblyCachedWeekData(this).weekYear : NaN;
  }
  /**
   * Get the week number of the week year (1-52ish).
   * @see https://en.wikipedia.org/wiki/ISO_week_date
   * @example DateTime.local(2017, 5, 25).weekNumber //=> 21
   * @type {number}
   */
  get weekNumber() {
    return this.isValid ? possiblyCachedWeekData(this).weekNumber : NaN;
  }
  /**
   * Get the day of the week.
   * 1 is Monday and 7 is Sunday
   * @see https://en.wikipedia.org/wiki/ISO_week_date
   * @example DateTime.local(2014, 11, 31).weekday //=> 4
   * @type {number}
   */
  get weekday() {
    return this.isValid ? possiblyCachedWeekData(this).weekday : NaN;
  }
  /**
   * Returns true if this date is on a weekend according to the locale, false otherwise
   * @returns {boolean}
   */
  get isWeekend() {
    return this.isValid && this.loc.getWeekendDays().includes(this.weekday);
  }
  /**
   * Get the day of the week according to the locale.
   * 1 is the first day of the week and 7 is the last day of the week.
   * If the locale assigns Sunday as the first day of the week, then a date which is a Sunday will return 1,
   * @returns {number}
   */
  get localWeekday() {
    return this.isValid ? possiblyCachedLocalWeekData(this).weekday : NaN;
  }
  /**
   * Get the week number of the week year according to the locale. Different locales assign week numbers differently,
   * because the week can start on different days of the week (see localWeekday) and because a different number of days
   * is required for a week to count as the first week of a year.
   * @returns {number}
   */
  get localWeekNumber() {
    return this.isValid ? possiblyCachedLocalWeekData(this).weekNumber : NaN;
  }
  /**
   * Get the week year according to the locale. Different locales assign week numbers (and therefor week years)
   * differently, see localWeekNumber.
   * @returns {number}
   */
  get localWeekYear() {
    return this.isValid ? possiblyCachedLocalWeekData(this).weekYear : NaN;
  }
  /**
   * Get the ordinal (meaning the day of the year)
   * @example DateTime.local(2017, 5, 25).ordinal //=> 145
   * @type {number|DateTime}
   */
  get ordinal() {
    return this.isValid ? gregorianToOrdinal(this.c).ordinal : NaN;
  }
  /**
   * Get the human readable short month name, such as 'Oct'.
   * Defaults to the system's locale if no locale has been specified
   * @example DateTime.local(2017, 10, 30).monthShort //=> Oct
   * @type {string}
   */
  get monthShort() {
    return this.isValid ? Info.months("short", { locObj: this.loc })[this.month - 1] : null;
  }
  /**
   * Get the human readable long month name, such as 'October'.
   * Defaults to the system's locale if no locale has been specified
   * @example DateTime.local(2017, 10, 30).monthLong //=> October
   * @type {string}
   */
  get monthLong() {
    return this.isValid ? Info.months("long", { locObj: this.loc })[this.month - 1] : null;
  }
  /**
   * Get the human readable short weekday, such as 'Mon'.
   * Defaults to the system's locale if no locale has been specified
   * @example DateTime.local(2017, 10, 30).weekdayShort //=> Mon
   * @type {string}
   */
  get weekdayShort() {
    return this.isValid ? Info.weekdays("short", { locObj: this.loc })[this.weekday - 1] : null;
  }
  /**
   * Get the human readable long weekday, such as 'Monday'.
   * Defaults to the system's locale if no locale has been specified
   * @example DateTime.local(2017, 10, 30).weekdayLong //=> Monday
   * @type {string}
   */
  get weekdayLong() {
    return this.isValid ? Info.weekdays("long", { locObj: this.loc })[this.weekday - 1] : null;
  }
  /**
   * Get the UTC offset of this DateTime in minutes
   * @example DateTime.now().offset //=> -240
   * @example DateTime.utc().offset //=> 0
   * @type {number}
   */
  get offset() {
    return this.isValid ? +this.o : NaN;
  }
  /**
   * Get the short human name for the zone's current offset, for example "EST" or "EDT".
   * Defaults to the system's locale if no locale has been specified
   * @type {string}
   */
  get offsetNameShort() {
    if (this.isValid) {
      return this.zone.offsetName(this.ts, {
        format: "short",
        locale: this.locale
      });
    } else {
      return null;
    }
  }
  /**
   * Get the long human name for the zone's current offset, for example "Eastern Standard Time" or "Eastern Daylight Time".
   * Defaults to the system's locale if no locale has been specified
   * @type {string}
   */
  get offsetNameLong() {
    if (this.isValid) {
      return this.zone.offsetName(this.ts, {
        format: "long",
        locale: this.locale
      });
    } else {
      return null;
    }
  }
  /**
   * Get whether this zone's offset ever changes, as in a DST.
   * @type {boolean}
   */
  get isOffsetFixed() {
    return this.isValid ? this.zone.isUniversal : null;
  }
  /**
   * Get whether the DateTime is in a DST.
   * @type {boolean}
   */
  get isInDST() {
    if (this.isOffsetFixed) {
      return false;
    } else {
      return this.offset > this.set({ month: 1, day: 1 }).offset || this.offset > this.set({ month: 5 }).offset;
    }
  }
  /**
   * Get those DateTimes which have the same local time as this DateTime, but a different offset from UTC
   * in this DateTime's zone. During DST changes local time can be ambiguous, for example
   * `2023-10-29T02:30:00` in `Europe/Berlin` can have offset `+01:00` or `+02:00`.
   * This method will return both possible DateTimes if this DateTime's local time is ambiguous.
   * @returns {DateTime[]}
   */
  getPossibleOffsets() {
    if (!this.isValid || this.isOffsetFixed) {
      return [this];
    }
    const dayMs = 864e5;
    const minuteMs = 6e4;
    const localTS = objToLocalTS(this.c);
    const oEarlier = this.zone.offset(localTS - dayMs);
    const oLater = this.zone.offset(localTS + dayMs);
    const o1 = this.zone.offset(localTS - oEarlier * minuteMs);
    const o2 = this.zone.offset(localTS - oLater * minuteMs);
    if (o1 === o2) {
      return [this];
    }
    const ts1 = localTS - o1 * minuteMs;
    const ts2 = localTS - o2 * minuteMs;
    const c1 = tsToObj(ts1, o1);
    const c2 = tsToObj(ts2, o2);
    if (c1.hour === c2.hour && c1.minute === c2.minute && c1.second === c2.second && c1.millisecond === c2.millisecond) {
      return [clone2(this, { ts: ts1 }), clone2(this, { ts: ts2 })];
    }
    return [this];
  }
  /**
   * Returns true if this DateTime is in a leap year, false otherwise
   * @example DateTime.local(2016).isInLeapYear //=> true
   * @example DateTime.local(2013).isInLeapYear //=> false
   * @type {boolean}
   */
  get isInLeapYear() {
    return isLeapYear(this.year);
  }
  /**
   * Returns the number of days in this DateTime's month
   * @example DateTime.local(2016, 2).daysInMonth //=> 29
   * @example DateTime.local(2016, 3).daysInMonth //=> 31
   * @type {number}
   */
  get daysInMonth() {
    return daysInMonth(this.year, this.month);
  }
  /**
   * Returns the number of days in this DateTime's year
   * @example DateTime.local(2016).daysInYear //=> 366
   * @example DateTime.local(2013).daysInYear //=> 365
   * @type {number}
   */
  get daysInYear() {
    return this.isValid ? daysInYear(this.year) : NaN;
  }
  /**
   * Returns the number of weeks in this DateTime's year
   * @see https://en.wikipedia.org/wiki/ISO_week_date
   * @example DateTime.local(2004).weeksInWeekYear //=> 53
   * @example DateTime.local(2013).weeksInWeekYear //=> 52
   * @type {number}
   */
  get weeksInWeekYear() {
    return this.isValid ? weeksInWeekYear(this.weekYear) : NaN;
  }
  /**
   * Returns the number of weeks in this DateTime's local week year
   * @example DateTime.local(2020, 6, {locale: 'en-US'}).weeksInLocalWeekYear //=> 52
   * @example DateTime.local(2020, 6, {locale: 'de-DE'}).weeksInLocalWeekYear //=> 53
   * @type {number}
   */
  get weeksInLocalWeekYear() {
    return this.isValid ? weeksInWeekYear(
      this.localWeekYear,
      this.loc.getMinDaysInFirstWeek(),
      this.loc.getStartOfWeek()
    ) : NaN;
  }
  /**
   * Returns the resolved Intl options for this DateTime.
   * This is useful in understanding the behavior of formatting methods
   * @param {Object} opts - the same options as toLocaleString
   * @return {Object}
   */
  resolvedLocaleOptions(opts = {}) {
    const { locale, numberingSystem, calendar } = Formatter.create(
      this.loc.clone(opts),
      opts
    ).resolvedOptions(this);
    return { locale, numberingSystem, outputCalendar: calendar };
  }
  // TRANSFORM
  /**
   * "Set" the DateTime's zone to UTC. Returns a newly-constructed DateTime.
   *
   * Equivalent to {@link DateTime#setZone}('utc')
   * @param {number} [offset=0] - optionally, an offset from UTC in minutes
   * @param {Object} [opts={}] - options to pass to `setZone()`
   * @return {DateTime}
   */
  toUTC(offset2 = 0, opts = {}) {
    return this.setZone(FixedOffsetZone.instance(offset2), opts);
  }
  /**
   * "Set" the DateTime's zone to the host's local zone. Returns a newly-constructed DateTime.
   *
   * Equivalent to `setZone('local')`
   * @return {DateTime}
   */
  toLocal() {
    return this.setZone(Settings.defaultZone);
  }
  /**
   * "Set" the DateTime's zone to specified zone. Returns a newly-constructed DateTime.
   *
   * By default, the setter keeps the underlying time the same (as in, the same timestamp), but the new instance will report different local times and consider DSTs when making computations, as with {@link DateTime#plus}. You may wish to use {@link DateTime#toLocal} and {@link DateTime#toUTC} which provide simple convenience wrappers for commonly used zones.
   * @param {string|Zone} [zone='local'] - a zone identifier. As a string, that can be any IANA zone supported by the host environment, or a fixed-offset name of the form 'UTC+3', or the strings 'local' or 'utc'. You may also supply an instance of a {@link DateTime#Zone} class.
   * @param {Object} opts - options
   * @param {boolean} [opts.keepLocalTime=false] - If true, adjust the underlying time so that the local time stays the same, but in the target zone. You should rarely need this.
   * @return {DateTime}
   */
  setZone(zone, { keepLocalTime = false, keepCalendarTime = false } = {}) {
    zone = normalizeZone(zone, Settings.defaultZone);
    if (zone.equals(this.zone)) {
      return this;
    } else if (!zone.isValid) {
      return _DateTime.invalid(unsupportedZone(zone));
    } else {
      let newTS = this.ts;
      if (keepLocalTime || keepCalendarTime) {
        const offsetGuess = zone.offset(this.ts);
        const asObj = this.toObject();
        [newTS] = objToTS(asObj, offsetGuess, zone);
      }
      return clone2(this, { ts: newTS, zone });
    }
  }
  /**
   * "Set" the locale, numberingSystem, or outputCalendar. Returns a newly-constructed DateTime.
   * @param {Object} properties - the properties to set
   * @example DateTime.local(2017, 5, 25).reconfigure({ locale: 'en-GB' })
   * @return {DateTime}
   */
  reconfigure({ locale, numberingSystem, outputCalendar } = {}) {
    const loc = this.loc.clone({ locale, numberingSystem, outputCalendar });
    return clone2(this, { loc });
  }
  /**
   * "Set" the locale. Returns a newly-constructed DateTime.
   * Just a convenient alias for reconfigure({ locale })
   * @example DateTime.local(2017, 5, 25).setLocale('en-GB')
   * @return {DateTime}
   */
  setLocale(locale) {
    return this.reconfigure({ locale });
  }
  /**
   * "Set" the values of specified units. Returns a newly-constructed DateTime.
   * You can only set units with this method; for "setting" metadata, see {@link DateTime#reconfigure} and {@link DateTime#setZone}.
   *
   * This method also supports setting locale-based week units, i.e. `localWeekday`, `localWeekNumber` and `localWeekYear`.
   * They cannot be mixed with ISO-week units like `weekday`.
   * @param {Object} values - a mapping of units to numbers
   * @example dt.set({ year: 2017 })
   * @example dt.set({ hour: 8, minute: 30 })
   * @example dt.set({ weekday: 5 })
   * @example dt.set({ year: 2005, ordinal: 234 })
   * @return {DateTime}
   */
  set(values) {
    if (!this.isValid) return this;
    const normalized = normalizeObject(values, normalizeUnitWithLocalWeeks);
    const { minDaysInFirstWeek, startOfWeek } = usesLocalWeekValues(normalized, this.loc);
    const settingWeekStuff = !isUndefined(normalized.weekYear) || !isUndefined(normalized.weekNumber) || !isUndefined(normalized.weekday), containsOrdinal = !isUndefined(normalized.ordinal), containsGregorYear = !isUndefined(normalized.year), containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day), containsGregor = containsGregorYear || containsGregorMD, definiteWeekDef = normalized.weekYear || normalized.weekNumber;
    if ((containsGregor || containsOrdinal) && definiteWeekDef) {
      throw new ConflictingSpecificationError(
        "Can't mix weekYear/weekNumber units with year/month/day or ordinals"
      );
    }
    if (containsGregorMD && containsOrdinal) {
      throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day");
    }
    let mixed;
    if (settingWeekStuff) {
      mixed = weekToGregorian(
        { ...gregorianToWeek(this.c, minDaysInFirstWeek, startOfWeek), ...normalized },
        minDaysInFirstWeek,
        startOfWeek
      );
    } else if (!isUndefined(normalized.ordinal)) {
      mixed = ordinalToGregorian({ ...gregorianToOrdinal(this.c), ...normalized });
    } else {
      mixed = { ...this.toObject(), ...normalized };
      if (isUndefined(normalized.day)) {
        mixed.day = Math.min(daysInMonth(mixed.year, mixed.month), mixed.day);
      }
    }
    const [ts, o] = objToTS(mixed, this.o, this.zone);
    return clone2(this, { ts, o });
  }
  /**
   * Add a period of time to this DateTime and return the resulting DateTime
   *
   * Adding hours, minutes, seconds, or milliseconds increases the timestamp by the right number of milliseconds. Adding days, months, or years shifts the calendar, accounting for DSTs and leap years along the way. Thus, `dt.plus({ hours: 24 })` may result in a different time than `dt.plus({ days: 1 })` if there's a DST shift in between.
   * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
   * @example DateTime.now().plus(123) //~> in 123 milliseconds
   * @example DateTime.now().plus({ minutes: 15 }) //~> in 15 minutes
   * @example DateTime.now().plus({ days: 1 }) //~> this time tomorrow
   * @example DateTime.now().plus({ days: -1 }) //~> this time yesterday
   * @example DateTime.now().plus({ hours: 3, minutes: 13 }) //~> in 3 hr, 13 min
   * @example DateTime.now().plus(Duration.fromObject({ hours: 3, minutes: 13 })) //~> in 3 hr, 13 min
   * @return {DateTime}
   */
  plus(duration) {
    if (!this.isValid) return this;
    const dur = Duration.fromDurationLike(duration);
    return clone2(this, adjustTime(this, dur));
  }
  /**
   * Subtract a period of time to this DateTime and return the resulting DateTime
   * See {@link DateTime#plus}
   * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
   @return {DateTime}
   */
  minus(duration) {
    if (!this.isValid) return this;
    const dur = Duration.fromDurationLike(duration).negate();
    return clone2(this, adjustTime(this, dur));
  }
  /**
   * "Set" this DateTime to the beginning of a unit of time.
   * @param {string} unit - The unit to go to the beginning of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'.
   * @param {Object} opts - options
   * @param {boolean} [opts.useLocaleWeeks=false] - If true, use weeks based on the locale, i.e. use the locale-dependent start of the week
   * @example DateTime.local(2014, 3, 3).startOf('month').toISODate(); //=> '2014-03-01'
   * @example DateTime.local(2014, 3, 3).startOf('year').toISODate(); //=> '2014-01-01'
   * @example DateTime.local(2014, 3, 3).startOf('week').toISODate(); //=> '2014-03-03', weeks always start on Mondays
   * @example DateTime.local(2014, 3, 3, 5, 30).startOf('day').toISOTime(); //=> '00:00.000-05:00'
   * @example DateTime.local(2014, 3, 3, 5, 30).startOf('hour').toISOTime(); //=> '05:00:00.000-05:00'
   * @return {DateTime}
   */
  startOf(unit, { useLocaleWeeks = false } = {}) {
    if (!this.isValid) return this;
    const o = {}, normalizedUnit = Duration.normalizeUnit(unit);
    switch (normalizedUnit) {
      case "years":
        o.month = 1;
      // falls through
      case "quarters":
      case "months":
        o.day = 1;
      // falls through
      case "weeks":
      case "days":
        o.hour = 0;
      // falls through
      case "hours":
        o.minute = 0;
      // falls through
      case "minutes":
        o.second = 0;
      // falls through
      case "seconds":
        o.millisecond = 0;
        break;
      case "milliseconds":
        break;
    }
    if (normalizedUnit === "weeks") {
      if (useLocaleWeeks) {
        const startOfWeek = this.loc.getStartOfWeek();
        const { weekday } = this;
        if (weekday < startOfWeek) {
          o.weekNumber = this.weekNumber - 1;
        }
        o.weekday = startOfWeek;
      } else {
        o.weekday = 1;
      }
    }
    if (normalizedUnit === "quarters") {
      const q = Math.ceil(this.month / 3);
      o.month = (q - 1) * 3 + 1;
    }
    return this.set(o);
  }
  /**
   * "Set" this DateTime to the end (meaning the last millisecond) of a unit of time
   * @param {string} unit - The unit to go to the end of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'.
   * @param {Object} opts - options
   * @param {boolean} [opts.useLocaleWeeks=false] - If true, use weeks based on the locale, i.e. use the locale-dependent start of the week
   * @example DateTime.local(2014, 3, 3).endOf('month').toISO(); //=> '2014-03-31T23:59:59.999-05:00'
   * @example DateTime.local(2014, 3, 3).endOf('year').toISO(); //=> '2014-12-31T23:59:59.999-05:00'
   * @example DateTime.local(2014, 3, 3).endOf('week').toISO(); // => '2014-03-09T23:59:59.999-05:00', weeks start on Mondays
   * @example DateTime.local(2014, 3, 3, 5, 30).endOf('day').toISO(); //=> '2014-03-03T23:59:59.999-05:00'
   * @example DateTime.local(2014, 3, 3, 5, 30).endOf('hour').toISO(); //=> '2014-03-03T05:59:59.999-05:00'
   * @return {DateTime}
   */
  endOf(unit, opts) {
    return this.isValid ? this.plus({ [unit]: 1 }).startOf(unit, opts).minus(1) : this;
  }
  // OUTPUT
  /**
   * Returns a string representation of this DateTime formatted according to the specified format string.
   * **You may not want this.** See {@link DateTime#toLocaleString} for a more flexible formatting tool. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/#/formatting?id=table-of-tokens).
   * Defaults to en-US if no locale has been specified, regardless of the system's locale.
   * @param {string} fmt - the format string
   * @param {Object} opts - opts to override the configuration options on this DateTime
   * @example DateTime.now().toFormat('yyyy LLL dd') //=> '2017 Apr 22'
   * @example DateTime.now().setLocale('fr').toFormat('yyyy LLL dd') //=> '2017 avr. 22'
   * @example DateTime.now().toFormat('yyyy LLL dd', { locale: "fr" }) //=> '2017 avr. 22'
   * @example DateTime.now().toFormat("HH 'hours and' mm 'minutes'") //=> '20 hours and 55 minutes'
   * @return {string}
   */
  toFormat(fmt, opts = {}) {
    return this.isValid ? Formatter.create(this.loc.redefaultToEN(opts)).formatDateTimeFromString(this, fmt) : INVALID3;
  }
  /**
   * Returns a localized string representing this date. Accepts the same options as the Intl.DateTimeFormat constructor and any presets defined by Luxon, such as `DateTime.DATE_FULL` or `DateTime.TIME_SIMPLE`.
   * The exact behavior of this method is browser-specific, but in general it will return an appropriate representation
   * of the DateTime in the assigned locale.
   * Defaults to the system's locale if no locale has been specified
   * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
   * @param formatOpts {Object} - Intl.DateTimeFormat constructor options and configuration options
   * @param {Object} opts - opts to override the configuration options on this DateTime
   * @example DateTime.now().toLocaleString(); //=> 4/20/2017
   * @example DateTime.now().setLocale('en-gb').toLocaleString(); //=> '20/04/2017'
   * @example DateTime.now().toLocaleString(DateTime.DATE_FULL); //=> 'April 20, 2017'
   * @example DateTime.now().toLocaleString(DateTime.DATE_FULL, { locale: 'fr' }); //=> '28 août 2022'
   * @example DateTime.now().toLocaleString(DateTime.TIME_SIMPLE); //=> '11:32 AM'
   * @example DateTime.now().toLocaleString(DateTime.DATETIME_SHORT); //=> '4/20/2017, 11:32 AM'
   * @example DateTime.now().toLocaleString({ weekday: 'long', month: 'long', day: '2-digit' }); //=> 'Thursday, April 20'
   * @example DateTime.now().toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }); //=> 'Thu, Apr 20, 11:27 AM'
   * @example DateTime.now().toLocaleString({ hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }); //=> '11:32'
   * @return {string}
   */
  toLocaleString(formatOpts = DATE_SHORT, opts = {}) {
    return this.isValid ? Formatter.create(this.loc.clone(opts), formatOpts).formatDateTime(this) : INVALID3;
  }
  /**
   * Returns an array of format "parts", meaning individual tokens along with metadata. This is allows callers to post-process individual sections of the formatted output.
   * Defaults to the system's locale if no locale has been specified
   * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/formatToParts
   * @param opts {Object} - Intl.DateTimeFormat constructor options, same as `toLocaleString`.
   * @example DateTime.now().toLocaleParts(); //=> [
   *                                   //=>   { type: 'day', value: '25' },
   *                                   //=>   { type: 'literal', value: '/' },
   *                                   //=>   { type: 'month', value: '05' },
   *                                   //=>   { type: 'literal', value: '/' },
   *                                   //=>   { type: 'year', value: '1982' }
   *                                   //=> ]
   */
  toLocaleParts(opts = {}) {
    return this.isValid ? Formatter.create(this.loc.clone(opts), opts).formatDateTimeParts(this) : [];
  }
  /**
   * Returns an ISO 8601-compliant string representation of this DateTime
   * @param {Object} opts - options
   * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0
   * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0
   * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'
   * @param {boolean} [opts.extendedZone=false] - add the time zone format extension
   * @param {string} [opts.format='extended'] - choose between the basic and extended format
   * @example DateTime.utc(1983, 5, 25).toISO() //=> '1982-05-25T00:00:00.000Z'
   * @example DateTime.now().toISO() //=> '2017-04-22T20:47:05.335-04:00'
   * @example DateTime.now().toISO({ includeOffset: false }) //=> '2017-04-22T20:47:05.335'
   * @example DateTime.now().toISO({ format: 'basic' }) //=> '20170422T204705.335-0400'
   * @return {string|null}
   */
  toISO({
    format = "extended",
    suppressSeconds = false,
    suppressMilliseconds = false,
    includeOffset = true,
    extendedZone = false
  } = {}) {
    if (!this.isValid) {
      return null;
    }
    const ext = format === "extended";
    let c = toISODate(this, ext);
    c += "T";
    c += toISOTime(this, ext, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone);
    return c;
  }
  /**
   * Returns an ISO 8601-compliant string representation of this DateTime's date component
   * @param {Object} opts - options
   * @param {string} [opts.format='extended'] - choose between the basic and extended format
   * @example DateTime.utc(1982, 5, 25).toISODate() //=> '1982-05-25'
   * @example DateTime.utc(1982, 5, 25).toISODate({ format: 'basic' }) //=> '19820525'
   * @return {string|null}
   */
  toISODate({ format = "extended" } = {}) {
    if (!this.isValid) {
      return null;
    }
    return toISODate(this, format === "extended");
  }
  /**
   * Returns an ISO 8601-compliant string representation of this DateTime's week date
   * @example DateTime.utc(1982, 5, 25).toISOWeekDate() //=> '1982-W21-2'
   * @return {string}
   */
  toISOWeekDate() {
    return toTechFormat(this, "kkkk-'W'WW-c");
  }
  /**
   * Returns an ISO 8601-compliant string representation of this DateTime's time component
   * @param {Object} opts - options
   * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0
   * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0
   * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'
   * @param {boolean} [opts.extendedZone=true] - add the time zone format extension
   * @param {boolean} [opts.includePrefix=false] - include the `T` prefix
   * @param {string} [opts.format='extended'] - choose between the basic and extended format
   * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime() //=> '07:34:19.361Z'
   * @example DateTime.utc().set({ hour: 7, minute: 34, seconds: 0, milliseconds: 0 }).toISOTime({ suppressSeconds: true }) //=> '07:34Z'
   * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ format: 'basic' }) //=> '073419.361Z'
   * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ includePrefix: true }) //=> 'T07:34:19.361Z'
   * @return {string}
   */
  toISOTime({
    suppressMilliseconds = false,
    suppressSeconds = false,
    includeOffset = true,
    includePrefix = false,
    extendedZone = false,
    format = "extended"
  } = {}) {
    if (!this.isValid) {
      return null;
    }
    let c = includePrefix ? "T" : "";
    return c + toISOTime(
      this,
      format === "extended",
      suppressSeconds,
      suppressMilliseconds,
      includeOffset,
      extendedZone
    );
  }
  /**
   * Returns an RFC 2822-compatible string representation of this DateTime
   * @example DateTime.utc(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 +0000'
   * @example DateTime.local(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 -0400'
   * @return {string}
   */
  toRFC2822() {
    return toTechFormat(this, "EEE, dd LLL yyyy HH:mm:ss ZZZ", false);
  }
  /**
   * Returns a string representation of this DateTime appropriate for use in HTTP headers. The output is always expressed in GMT.
   * Specifically, the string conforms to RFC 1123.
   * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1
   * @example DateTime.utc(2014, 7, 13).toHTTP() //=> 'Sun, 13 Jul 2014 00:00:00 GMT'
   * @example DateTime.utc(2014, 7, 13, 19).toHTTP() //=> 'Sun, 13 Jul 2014 19:00:00 GMT'
   * @return {string}
   */
  toHTTP() {
    return toTechFormat(this.toUTC(), "EEE, dd LLL yyyy HH:mm:ss 'GMT'");
  }
  /**
   * Returns a string representation of this DateTime appropriate for use in SQL Date
   * @example DateTime.utc(2014, 7, 13).toSQLDate() //=> '2014-07-13'
   * @return {string|null}
   */
  toSQLDate() {
    if (!this.isValid) {
      return null;
    }
    return toISODate(this, true);
  }
  /**
   * Returns a string representation of this DateTime appropriate for use in SQL Time
   * @param {Object} opts - options
   * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset.
   * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'
   * @param {boolean} [opts.includeOffsetSpace=true] - include the space between the time and the offset, such as '05:15:16.345 -04:00'
   * @example DateTime.utc().toSQL() //=> '05:15:16.345'
   * @example DateTime.now().toSQL() //=> '05:15:16.345 -04:00'
   * @example DateTime.now().toSQL({ includeOffset: false }) //=> '05:15:16.345'
   * @example DateTime.now().toSQL({ includeZone: false }) //=> '05:15:16.345 America/New_York'
   * @return {string}
   */
  toSQLTime({ includeOffset = true, includeZone = false, includeOffsetSpace = true } = {}) {
    let fmt = "HH:mm:ss.SSS";
    if (includeZone || includeOffset) {
      if (includeOffsetSpace) {
        fmt += " ";
      }
      if (includeZone) {
        fmt += "z";
      } else if (includeOffset) {
        fmt += "ZZ";
      }
    }
    return toTechFormat(this, fmt, true);
  }
  /**
   * Returns a string representation of this DateTime appropriate for use in SQL DateTime
   * @param {Object} opts - options
   * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset.
   * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'
   * @param {boolean} [opts.includeOffsetSpace=true] - include the space between the time and the offset, such as '05:15:16.345 -04:00'
   * @example DateTime.utc(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 Z'
   * @example DateTime.local(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 -04:00'
   * @example DateTime.local(2014, 7, 13).toSQL({ includeOffset: false }) //=> '2014-07-13 00:00:00.000'
   * @example DateTime.local(2014, 7, 13).toSQL({ includeZone: true }) //=> '2014-07-13 00:00:00.000 America/New_York'
   * @return {string}
   */
  toSQL(opts = {}) {
    if (!this.isValid) {
      return null;
    }
    return `${this.toSQLDate()} ${this.toSQLTime(opts)}`;
  }
  /**
   * Returns a string representation of this DateTime appropriate for debugging
   * @return {string}
   */
  toString() {
    return this.isValid ? this.toISO() : INVALID3;
  }
  /**
   * Returns a string representation of this DateTime appropriate for the REPL.
   * @return {string}
   */
  [Symbol.for("nodejs.util.inspect.custom")]() {
    if (this.isValid) {
      return `DateTime { ts: ${this.toISO()}, zone: ${this.zone.name}, locale: ${this.locale} }`;
    } else {
      return `DateTime { Invalid, reason: ${this.invalidReason} }`;
    }
  }
  /**
   * Returns the epoch milliseconds of this DateTime. Alias of {@link DateTime#toMillis}
   * @return {number}
   */
  valueOf() {
    return this.toMillis();
  }
  /**
   * Returns the epoch milliseconds of this DateTime.
   * @return {number}
   */
  toMillis() {
    return this.isValid ? this.ts : NaN;
  }
  /**
   * Returns the epoch seconds (including milliseconds in the fractional part) of this DateTime.
   * @return {number}
   */
  toSeconds() {
    return this.isValid ? this.ts / 1e3 : NaN;
  }
  /**
   * Returns the epoch seconds (as a whole number) of this DateTime.
   * @return {number}
   */
  toUnixInteger() {
    return this.isValid ? Math.floor(this.ts / 1e3) : NaN;
  }
  /**
   * Returns an ISO 8601 representation of this DateTime appropriate for use in JSON.
   * @return {string}
   */
  toJSON() {
    return this.toISO();
  }
  /**
   * Returns a BSON serializable equivalent to this DateTime.
   * @return {Date}
   */
  toBSON() {
    return this.toJSDate();
  }
  /**
   * Returns a JavaScript object with this DateTime's year, month, day, and so on.
   * @param opts - options for generating the object
   * @param {boolean} [opts.includeConfig=false] - include configuration attributes in the output
   * @example DateTime.now().toObject() //=> { year: 2017, month: 4, day: 22, hour: 20, minute: 49, second: 42, millisecond: 268 }
   * @return {Object}
   */
  toObject(opts = {}) {
    if (!this.isValid) return {};
    const base = { ...this.c };
    if (opts.includeConfig) {
      base.outputCalendar = this.outputCalendar;
      base.numberingSystem = this.loc.numberingSystem;
      base.locale = this.loc.locale;
    }
    return base;
  }
  /**
   * Returns a JavaScript Date equivalent to this DateTime.
   * @return {Date}
   */
  toJSDate() {
    return new Date(this.isValid ? this.ts : NaN);
  }
  // COMPARE
  /**
   * Return the difference between two DateTimes as a Duration.
   * @param {DateTime} otherDateTime - the DateTime to compare this one to
   * @param {string|string[]} [unit=['milliseconds']] - the unit or array of units (such as 'hours' or 'days') to include in the duration.
   * @param {Object} opts - options that affect the creation of the Duration
   * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
   * @example
   * var i1 = DateTime.fromISO('1982-05-25T09:45'),
   *     i2 = DateTime.fromISO('1983-10-14T10:30');
   * i2.diff(i1).toObject() //=> { milliseconds: 43807500000 }
   * i2.diff(i1, 'hours').toObject() //=> { hours: 12168.75 }
   * i2.diff(i1, ['months', 'days']).toObject() //=> { months: 16, days: 19.03125 }
   * i2.diff(i1, ['months', 'days', 'hours']).toObject() //=> { months: 16, days: 19, hours: 0.75 }
   * @return {Duration}
   */
  diff(otherDateTime, unit = "milliseconds", opts = {}) {
    if (!this.isValid || !otherDateTime.isValid) {
      return Duration.invalid("created by diffing an invalid DateTime");
    }
    const durOpts = { locale: this.locale, numberingSystem: this.numberingSystem, ...opts };
    const units = maybeArray(unit).map(Duration.normalizeUnit), otherIsLater = otherDateTime.valueOf() > this.valueOf(), earlier = otherIsLater ? this : otherDateTime, later = otherIsLater ? otherDateTime : this, diffed = diff_default(earlier, later, units, durOpts);
    return otherIsLater ? diffed.negate() : diffed;
  }
  /**
   * Return the difference between this DateTime and right now.
   * See {@link DateTime#diff}
   * @param {string|string[]} [unit=['milliseconds']] - the unit or units units (such as 'hours' or 'days') to include in the duration
   * @param {Object} opts - options that affect the creation of the Duration
   * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
   * @return {Duration}
   */
  diffNow(unit = "milliseconds", opts = {}) {
    return this.diff(_DateTime.now(), unit, opts);
  }
  /**
   * Return an Interval spanning between this DateTime and another DateTime
   * @param {DateTime} otherDateTime - the other end point of the Interval
   * @return {Interval|DateTime}
   */
  until(otherDateTime) {
    return this.isValid ? Interval.fromDateTimes(this, otherDateTime) : this;
  }
  /**
   * Return whether this DateTime is in the same unit of time as another DateTime.
   * Higher-order units must also be identical for this function to return `true`.
   * Note that time zones are **ignored** in this comparison, which compares the **local** calendar time. Use {@link DateTime#setZone} to convert one of the dates if needed.
   * @param {DateTime} otherDateTime - the other DateTime
   * @param {string} unit - the unit of time to check sameness on
   * @param {Object} opts - options
   * @param {boolean} [opts.useLocaleWeeks=false] - If true, use weeks based on the locale, i.e. use the locale-dependent start of the week; only the locale of this DateTime is used
   * @example DateTime.now().hasSame(otherDT, 'day'); //~> true if otherDT is in the same current calendar day
   * @return {boolean}
   */
  hasSame(otherDateTime, unit, opts) {
    if (!this.isValid) return false;
    const inputMs = otherDateTime.valueOf();
    const adjustedToZone = this.setZone(otherDateTime.zone, { keepLocalTime: true });
    return adjustedToZone.startOf(unit, opts) <= inputMs && inputMs <= adjustedToZone.endOf(unit, opts);
  }
  /**
   * Equality check
   * Two DateTimes are equal if and only if they represent the same millisecond, have the same zone and location, and are both valid.
   * To compare just the millisecond values, use `+dt1 === +dt2`.
   * @param {DateTime} other - the other DateTime
   * @return {boolean}
   */
  equals(other) {
    return this.isValid && other.isValid && this.valueOf() === other.valueOf() && this.zone.equals(other.zone) && this.loc.equals(other.loc);
  }
  /**
   * Returns a string representation of a this time relative to now, such as "in two days". Can only internationalize if your
   * platform supports Intl.RelativeTimeFormat. Rounds down by default.
   * @param {Object} options - options that affect the output
   * @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now.
   * @param {string} [options.style="long"] - the style of units, must be "long", "short", or "narrow"
   * @param {string|string[]} options.unit - use a specific unit or array of units; if omitted, or an array, the method will pick the best unit. Use an array or one of "years", "quarters", "months", "weeks", "days", "hours", "minutes", or "seconds"
   * @param {boolean} [options.round=true] - whether to round the numbers in the output.
   * @param {number} [options.padding=0] - padding in milliseconds. This allows you to round up the result if it fits inside the threshold. Don't use in combination with {round: false} because the decimal output will include the padding.
   * @param {string} options.locale - override the locale of this DateTime
   * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this
   * @example DateTime.now().plus({ days: 1 }).toRelative() //=> "in 1 day"
   * @example DateTime.now().setLocale("es").toRelative({ days: 1 }) //=> "dentro de 1 día"
   * @example DateTime.now().plus({ days: 1 }).toRelative({ locale: "fr" }) //=> "dans 23 heures"
   * @example DateTime.now().minus({ days: 2 }).toRelative() //=> "2 days ago"
   * @example DateTime.now().minus({ days: 2 }).toRelative({ unit: "hours" }) //=> "48 hours ago"
   * @example DateTime.now().minus({ hours: 36 }).toRelative({ round: false }) //=> "1.5 days ago"
   */
  toRelative(options = {}) {
    if (!this.isValid) return null;
    const base = options.base || _DateTime.fromObject({}, { zone: this.zone }), padding = options.padding ? this < base ? -options.padding : options.padding : 0;
    let units = ["years", "months", "days", "hours", "minutes", "seconds"];
    let unit = options.unit;
    if (Array.isArray(options.unit)) {
      units = options.unit;
      unit = void 0;
    }
    return diffRelative(base, this.plus(padding), {
      ...options,
      numeric: "always",
      units,
      unit
    });
  }
  /**
   * Returns a string representation of this date relative to today, such as "yesterday" or "next month".
   * Only internationalizes on platforms that supports Intl.RelativeTimeFormat.
   * @param {Object} options - options that affect the output
   * @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now.
   * @param {string} options.locale - override the locale of this DateTime
   * @param {string} options.unit - use a specific unit; if omitted, the method will pick the unit. Use one of "years", "quarters", "months", "weeks", or "days"
   * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this
   * @example DateTime.now().plus({ days: 1 }).toRelativeCalendar() //=> "tomorrow"
   * @example DateTime.now().setLocale("es").plus({ days: 1 }).toRelative() //=> ""mañana"
   * @example DateTime.now().plus({ days: 1 }).toRelativeCalendar({ locale: "fr" }) //=> "demain"
   * @example DateTime.now().minus({ days: 2 }).toRelativeCalendar() //=> "2 days ago"
   */
  toRelativeCalendar(options = {}) {
    if (!this.isValid) return null;
    return diffRelative(options.base || _DateTime.fromObject({}, { zone: this.zone }), this, {
      ...options,
      numeric: "auto",
      units: ["years", "months", "days"],
      calendary: true
    });
  }
  /**
   * Return the min of several date times
   * @param {...DateTime} dateTimes - the DateTimes from which to choose the minimum
   * @return {DateTime} the min DateTime, or undefined if called with no argument
   */
  static min(...dateTimes) {
    if (!dateTimes.every(_DateTime.isDateTime)) {
      throw new InvalidArgumentError("min requires all arguments be DateTimes");
    }
    return bestBy(dateTimes, (i) => i.valueOf(), Math.min);
  }
  /**
   * Return the max of several date times
   * @param {...DateTime} dateTimes - the DateTimes from which to choose the maximum
   * @return {DateTime} the max DateTime, or undefined if called with no argument
   */
  static max(...dateTimes) {
    if (!dateTimes.every(_DateTime.isDateTime)) {
      throw new InvalidArgumentError("max requires all arguments be DateTimes");
    }
    return bestBy(dateTimes, (i) => i.valueOf(), Math.max);
  }
  // MISC
  /**
   * Explain how a string would be parsed by fromFormat()
   * @param {string} text - the string to parse
   * @param {string} fmt - the format the string is expected to be in (see description)
   * @param {Object} options - options taken by fromFormat()
   * @return {Object}
   */
  static fromFormatExplain(text2, fmt, options = {}) {
    const { locale = null, numberingSystem = null } = options, localeToUse = Locale.fromOpts({
      locale,
      numberingSystem,
      defaultToEN: true
    });
    return explainFromTokens(localeToUse, text2, fmt);
  }
  /**
   * @deprecated use fromFormatExplain instead
   */
  static fromStringExplain(text2, fmt, options = {}) {
    return _DateTime.fromFormatExplain(text2, fmt, options);
  }
  /**
   * Build a parser for `fmt` using the given locale. This parser can be passed
   * to {@link DateTime.fromFormatParser} to a parse a date in this format. This
   * can be used to optimize cases where many dates need to be parsed in a
   * specific format.
   *
   * @param {String} fmt - the format the string is expected to be in (see
   * description)
   * @param {Object} options - options used to set locale and numberingSystem
   * for parser
   * @returns {TokenParser} - opaque object to be used
   */
  static buildFormatParser(fmt, options = {}) {
    const { locale = null, numberingSystem = null } = options, localeToUse = Locale.fromOpts({
      locale,
      numberingSystem,
      defaultToEN: true
    });
    return new TokenParser(localeToUse, fmt);
  }
  /**
   * Create a DateTime from an input string and format parser.
   *
   * The format parser must have been created with the same locale as this call.
   *
   * @param {String} text - the string to parse
   * @param {TokenParser} formatParser - parser from {@link DateTime.buildFormatParser}
   * @param {Object} opts - options taken by fromFormat()
   * @returns {DateTime}
   */
  static fromFormatParser(text2, formatParser, opts = {}) {
    if (isUndefined(text2) || isUndefined(formatParser)) {
      throw new InvalidArgumentError(
        "fromFormatParser requires an input string and a format parser"
      );
    }
    const { locale = null, numberingSystem = null } = opts, localeToUse = Locale.fromOpts({
      locale,
      numberingSystem,
      defaultToEN: true
    });
    if (!localeToUse.equals(formatParser.locale)) {
      throw new InvalidArgumentError(
        `fromFormatParser called with a locale of ${localeToUse}, but the format parser was created for ${formatParser.locale}`
      );
    }
    const { result, zone, specificOffset, invalidReason } = formatParser.explainFromTokens(text2);
    if (invalidReason) {
      return _DateTime.invalid(invalidReason);
    } else {
      return parseDataToDateTime(
        result,
        zone,
        opts,
        `format ${formatParser.format}`,
        text2,
        specificOffset
      );
    }
  }
  // FORMAT PRESETS
  /**
   * {@link DateTime#toLocaleString} format like 10/14/1983
   * @type {Object}
   */
  static get DATE_SHORT() {
    return DATE_SHORT;
  }
  /**
   * {@link DateTime#toLocaleString} format like 'Oct 14, 1983'
   * @type {Object}
   */
  static get DATE_MED() {
    return DATE_MED;
  }
  /**
   * {@link DateTime#toLocaleString} format like 'Fri, Oct 14, 1983'
   * @type {Object}
   */
  static get DATE_MED_WITH_WEEKDAY() {
    return DATE_MED_WITH_WEEKDAY;
  }
  /**
   * {@link DateTime#toLocaleString} format like 'October 14, 1983'
   * @type {Object}
   */
  static get DATE_FULL() {
    return DATE_FULL;
  }
  /**
   * {@link DateTime#toLocaleString} format like 'Tuesday, October 14, 1983'
   * @type {Object}
   */
  static get DATE_HUGE() {
    return DATE_HUGE;
  }
  /**
   * {@link DateTime#toLocaleString} format like '09:30 AM'. Only 12-hour if the locale is.
   * @type {Object}
   */
  static get TIME_SIMPLE() {
    return TIME_SIMPLE;
  }
  /**
   * {@link DateTime#toLocaleString} format like '09:30:23 AM'. Only 12-hour if the locale is.
   * @type {Object}
   */
  static get TIME_WITH_SECONDS() {
    return TIME_WITH_SECONDS;
  }
  /**
   * {@link DateTime#toLocaleString} format like '09:30:23 AM EDT'. Only 12-hour if the locale is.
   * @type {Object}
   */
  static get TIME_WITH_SHORT_OFFSET() {
    return TIME_WITH_SHORT_OFFSET;
  }
  /**
   * {@link DateTime#toLocaleString} format like '09:30:23 AM Eastern Daylight Time'. Only 12-hour if the locale is.
   * @type {Object}
   */
  static get TIME_WITH_LONG_OFFSET() {
    return TIME_WITH_LONG_OFFSET;
  }
  /**
   * {@link DateTime#toLocaleString} format like '09:30', always 24-hour.
   * @type {Object}
   */
  static get TIME_24_SIMPLE() {
    return TIME_24_SIMPLE;
  }
  /**
   * {@link DateTime#toLocaleString} format like '09:30:23', always 24-hour.
   * @type {Object}
   */
  static get TIME_24_WITH_SECONDS() {
    return TIME_24_WITH_SECONDS;
  }
  /**
   * {@link DateTime#toLocaleString} format like '09:30:23 EDT', always 24-hour.
   * @type {Object}
   */
  static get TIME_24_WITH_SHORT_OFFSET() {
    return TIME_24_WITH_SHORT_OFFSET;
  }
  /**
   * {@link DateTime#toLocaleString} format like '09:30:23 Eastern Daylight Time', always 24-hour.
   * @type {Object}
   */
  static get TIME_24_WITH_LONG_OFFSET() {
    return TIME_24_WITH_LONG_OFFSET;
  }
  /**
   * {@link DateTime#toLocaleString} format like '10/14/1983, 9:30 AM'. Only 12-hour if the locale is.
   * @type {Object}
   */
  static get DATETIME_SHORT() {
    return DATETIME_SHORT;
  }
  /**
   * {@link DateTime#toLocaleString} format like '10/14/1983, 9:30:33 AM'. Only 12-hour if the locale is.
   * @type {Object}
   */
  static get DATETIME_SHORT_WITH_SECONDS() {
    return DATETIME_SHORT_WITH_SECONDS;
  }
  /**
   * {@link DateTime#toLocaleString} format like 'Oct 14, 1983, 9:30 AM'. Only 12-hour if the locale is.
   * @type {Object}
   */
  static get DATETIME_MED() {
    return DATETIME_MED;
  }
  /**
   * {@link DateTime#toLocaleString} format like 'Oct 14, 1983, 9:30:33 AM'. Only 12-hour if the locale is.
   * @type {Object}
   */
  static get DATETIME_MED_WITH_SECONDS() {
    return DATETIME_MED_WITH_SECONDS;
  }
  /**
   * {@link DateTime#toLocaleString} format like 'Fri, 14 Oct 1983, 9:30 AM'. Only 12-hour if the locale is.
   * @type {Object}
   */
  static get DATETIME_MED_WITH_WEEKDAY() {
    return DATETIME_MED_WITH_WEEKDAY;
  }
  /**
   * {@link DateTime#toLocaleString} format like 'October 14, 1983, 9:30 AM EDT'. Only 12-hour if the locale is.
   * @type {Object}
   */
  static get DATETIME_FULL() {
    return DATETIME_FULL;
  }
  /**
   * {@link DateTime#toLocaleString} format like 'October 14, 1983, 9:30:33 AM EDT'. Only 12-hour if the locale is.
   * @type {Object}
   */
  static get DATETIME_FULL_WITH_SECONDS() {
    return DATETIME_FULL_WITH_SECONDS;
  }
  /**
   * {@link DateTime#toLocaleString} format like 'Friday, October 14, 1983, 9:30 AM Eastern Daylight Time'. Only 12-hour if the locale is.
   * @type {Object}
   */
  static get DATETIME_HUGE() {
    return DATETIME_HUGE;
  }
  /**
   * {@link DateTime#toLocaleString} format like 'Friday, October 14, 1983, 9:30:33 AM Eastern Daylight Time'. Only 12-hour if the locale is.
   * @type {Object}
   */
  static get DATETIME_HUGE_WITH_SECONDS() {
    return DATETIME_HUGE_WITH_SECONDS;
  }
};
function friendlyDateTime(dateTimeish) {
  if (DateTime.isDateTime(dateTimeish)) {
    return dateTimeish;
  } else if (dateTimeish && dateTimeish.valueOf && isNumber(dateTimeish.valueOf())) {
    return DateTime.fromJSDate(dateTimeish);
  } else if (dateTimeish && typeof dateTimeish === "object") {
    return DateTime.fromObject(dateTimeish);
  } else {
    throw new InvalidArgumentError(
      `Unknown datetime argument: ${dateTimeish}, of type ${typeof dateTimeish}`
    );
  }
}

// src/publishFile/FileMetaDataManager.ts
var FileMetadataManager = class {
  file;
  frontmatter;
  settings;
  constructor(file, frontmatter, settings) {
    this.file = file;
    this.frontmatter = frontmatter;
    this.settings = settings;
  }
  /**
   * Returns the created date of the file.
   * If a custom created date is specified in the frontmatter, it returns that.
   * Otherwise, it returns the file's creation time.
   *
   * @returns The created date as an ISO string.
   */
  getCreatedAt() {
    const createdKeys = this.settings.createdTimestampKey.split(",");
    for (const key of createdKeys) {
      const customCreatedDate = this.frontmatter[key.trim()];
      if (customCreatedDate) {
        return customCreatedDate;
      }
    }
    return DateTime.fromMillis(this.file.stat.ctime).toISO();
  }
  /**
   * Returns the updated date of the file.
   * If a custom updated date is specified in the frontmatter, it returns that.
   * Otherwise, it returns the file's last modified time.
   *
   * @returns The updated date as an ISO string.
   */
  getUpdatedAt() {
    const updatedKeys = this.settings.updatedTimestampKey.split(",");
    for (const key of updatedKeys) {
      const customUpdatedDate = this.frontmatter[key.trim()];
      if (customUpdatedDate) {
        return customUpdatedDate;
      }
    }
    return DateTime.fromMillis(this.file.stat.mtime).toISO();
  }
  /**
   * Returns the published date of the file.
   * If a custom published date is specified in the frontmatter, it returns that.
   * Otherwise, it returns the file's last modified time.
   *
   * @returns The published date as an ISO string.
   */
  getPublishedAt() {
    const publishedKeys = this.settings.publishedTimestampKey.split(",");
    for (const key of publishedKeys) {
      const customPublishedDate = this.frontmatter[key.trim()];
      if (customPublishedDate) {
        return customPublishedDate;
      }
    }
    return DateTime.fromMillis(this.file.stat.mtime).toISO();
  }
};

// src/utils/dynamicContent.ts
init_esbuild_buffer_shim();
var import_obsidian_dataview = __toESM(require_lib());
function hasDynamicContent(text2) {
  if (/```dataview\s/ms.test(text2)) return true;
  if (/```datacorejs\s/ms.test(text2)) return true;
  if (/```datacorejsx\s/ms.test(text2)) return true;
  if (/```datacorets\s/ms.test(text2)) return true;
  if (/```datacoretsx\s/ms.test(text2)) return true;
  const dvApi = (0, import_obsidian_dataview.getAPI)();
  if (dvApi) {
    const dataviewJsPrefix = dvApi.settings.dataviewJsKeyword;
    const dataViewJsRegex = new RegExp(
      "```" + escapeRegExp(dataviewJsPrefix) + "\\s",
      "ms"
    );
    if (dataViewJsRegex.test(text2)) return true;
    const inlineQueryPrefix = dvApi.settings.inlineQueryPrefix;
    const inlineDataViewRegex = new RegExp(
      "`" + escapeRegExp(inlineQueryPrefix) + ".+?`",
      "ms"
    );
    if (inlineDataViewRegex.test(text2)) return true;
    const inlineJsQueryPrefix = dvApi.settings.inlineJsQueryPrefix;
    const inlineJsDataViewRegex = new RegExp(
      "`" + escapeRegExp(inlineJsQueryPrefix) + ".+?`",
      "ms"
    );
    if (inlineJsDataViewRegex.test(text2)) return true;
  }
  return false;
}

// src/publishFile/PublishFile.ts
var PublishFile = class {
  file;
  compiler;
  vault;
  compiledFile;
  metadataCache;
  frontmatter;
  settings;
  // Access props and other file metadata
  meta;
  datastore;
  constructor({
    file,
    compiler,
    metadataCache,
    vault,
    settings,
    datastore
  }) {
    this.compiler = compiler;
    this.metadataCache = metadataCache;
    this.file = file;
    this.settings = settings;
    this.vault = vault;
    this.frontmatter = this.getFrontmatter();
    this.datastore = datastore;
    this.meta = new FileMetadataManager(file, this.frontmatter, settings);
  }
  /**
   * Compiles the file for publishing.
   * Uses caching when enabled, detecting dynamic content for proper cache invalidation.
   *
   * @returns A promise that resolves to a CompiledPublishFile instance.
   */
  async compile() {
    let compiledFile;
    if (this.settings.useCache) {
      const cachedFile = await this.datastore.loadLocalFile(
        this.file.path
      );
      const outdated = cachedFile ? await this.datastore.isLocalFileOutdated(
        this.file.path,
        this.file.stat.mtime
      ) : true;
      let storedFile = null;
      if (cachedFile && !outdated) {
        storedFile = cachedFile;
      } else {
        const rawContent = await this.vault.cachedRead(this.file);
        const isDynamic = hasDynamicContent(rawContent);
        storedFile = await this.compiler.generateMarkdown(this);
        if (!storedFile) {
          throw new Error(
            `Failed to compile file: ${this.file.path}. Compiler returned null.`
          );
        }
        const localHash = generateBlobHash(storedFile[0]);
        await this.datastore.storeLocalFile(
          this.file.path,
          this.file.stat.mtime,
          storedFile,
          isDynamic
        );
        await this.datastore.storeLocalHash(
          this.file.path,
          this.file.stat.mtime,
          localHash
        );
      }
      compiledFile = storedFile;
    } else {
      compiledFile = await this.compiler.generateMarkdown(this);
    }
    return new CompiledPublishFile(
      {
        file: this.file,
        compiler: this.compiler,
        metadataCache: this.metadataCache,
        vault: this.vault,
        settings: this.settings,
        datastore: this.datastore
      },
      compiledFile
    );
  }
  /**
   * Returns the type of the file based on its extension.
   *
   * @returns The file type: "excalidraw" or "markdown".
   */
  getType() {
    if (this.file.name.endsWith(".excalidraw")) {
      return "excalidraw";
    }
    return "markdown";
  }
  /**
   * Checks if the file should be published based on the publish flag in the frontmatter.
   *
   * @returns true if the file should be published, false otherwise.
   */
  shouldPublish() {
    return hasPublishFlag(
      this.settings.publishFrontmatterKey,
      this.frontmatter,
      this.settings.allNotesPublishableByDefault
    );
  }
  /**
   * Retrieves the blob links from the compiled file.
   *
   * @returns An array of blob links.
   */
  async getBlobLinks() {
    return this.compiler.extractBlobLinks(this);
  }
  /**
   * Reads the file content from the vault.
   *
   * @returns The content of the file as a string.
   */
  async cachedRead() {
    return this.vault.cachedRead(this.file);
  }
  /**
   * Retrieves the metadata cache for the file.
   *
   * @returns The metadata cache for the file.
   */
  getMetadata() {
    return this.metadataCache.getCache(this.file.path) ?? {};
  }
  /**
   * Retrieves the block metadata for a specific block ID.
   *
   * @param blockId - The ID of the block to retrieve metadata for.
   * @returns The metadata for the specified block, or undefined if not found.
   */
  getBlock(blockId) {
    return this.getMetadata().blocks?.[blockId];
  }
  /**
   * Retrieves the frontmatter metadata for the file.
   *
   * @returns The frontmatter metadata as an object.
   */
  getFrontmatter() {
    return this.metadataCache.getCache(this.file.path)?.frontmatter ?? {};
  }
  /**
   * Compares this PublishFile with another PublishFile based on the file path.
   *
   * @param other - The other PublishFile to compare with.
   * @returns A negative number if this file's path comes before the other file's path, a positive number if it comes after, and zero if they are equal.
   */
  compare(other) {
    return this.file.path.localeCompare(other.file.path);
  }
  /**
   * Returns the path of the file.
   *
   * @returns The path of the file as a string.
   */
  getPath = () => this.file.path;
  /**
   * Returns the vault path of the file.
   * If the vault path is not set or the file path does not start with the vault path, it returns the file path.
   *
   * @returns The vault path of the file as a string.
   */
  getVaultPath = () => {
    if (this.settings.vaultPath !== "/" && this.file.path.startsWith(this.settings.vaultPath)) {
      return this.file.path.replace(this.settings.vaultPath, "");
    }
    return this.file.path;
  };
  /**
   * Retrieves the compiled frontmatter for the file.
   * It uses the FrontmatterCompiler to compile the frontmatter metadata.
   *
   * @param text - The text content of the file, used for compilation.
   * @returns The compiled frontmatter as an object.
   */
  getCompiledFrontmatter(text2) {
    const convertDataviewFields = !!this.settings.useDataview;
    const frontmatterCompiler = new FrontmatterCompiler(this.settings);
    const metadata = this.metadataCache.getCache(this.file.path)?.frontmatter ?? {};
    if (convertDataviewFields) {
      const fieldMatches = text2.matchAll(DATAVIEW_FIELD_REGEX);
      const inlineFieldMatches = text2.matchAll(
        DATAVIEW_INLINE_FIELD_REGEX
      );
      for (const match2 of fieldMatches) {
        if (match2[1] && match2[2]) {
          metadata[match2[1]] = match2[2];
        }
      }
      for (const match2 of inlineFieldMatches) {
        if (match2[1] && match2[2]) {
          metadata[match2[1]] = match2[2];
        } else if (match2[3] && match2[4]) {
          metadata[match2[3]] = match2[4];
        }
      }
    }
    return frontmatterCompiler.compile(this, metadata);
  }
};
var CompiledPublishFile = class extends PublishFile {
  compiledFile;
  remoteHash;
  constructor(props, compiledFile) {
    super(props);
    this.compiledFile = compiledFile;
  }
  /**
   * Returns the compiled file content.
   *
   * @returns The compiled file as a TCompiledFile object.
   */
  getCompiledFile() {
    return this.compiledFile;
  }
  /**
   * Sets the remote hash for the compiled file.
   *
   * @param hash - The SHA hash of the remote file.
   */
  setRemoteHash(hash) {
    this.remoteHash = hash;
  }
};

// src/compiler/PluginCompiler.ts
init_esbuild_buffer_shim();

// src/compiler/integrations/index.ts
init_esbuild_buffer_shim();

// src/compiler/integrations/types.ts
init_esbuild_buffer_shim();

// src/compiler/integrations/registry.ts
init_esbuild_buffer_shim();
var IntegrationRegistry = class {
  integrations = [];
  register(integration) {
    this.integrations.push(integration);
  }
  getAll() {
    return [...this.integrations];
  }
  getEnabled(settings) {
    return this.integrations.filter((i) => settings[i.settingKey] && i.isAvailable()).sort((a, b) => a.priority - b.priority);
  }
  getAvailable() {
    return this.integrations.filter((i) => i.isAvailable());
  }
  getAllPatterns(settings) {
    return this.getEnabled(settings).flatMap((i) => i.getPatterns());
  }
  getCollectedAssets(settings) {
    const assets = /* @__PURE__ */ new Map();
    for (const integration of this.getEnabled(settings)) {
      if (integration.assets.scss) {
        assets.set(integration.id, integration.assets);
      }
    }
    return assets;
  }
  getById(id) {
    return this.integrations.find((i) => i.id === id);
  }
};
var integrationRegistry = new IntegrationRegistry();

// src/compiler/integrations/AssetSyncer.ts
init_esbuild_buffer_shim();
var import_obsidian4 = require("obsidian");
var import_js_logger = __toESM(require_logger());
var SYNCER_STYLES_DIR = "quartz/styles/syncer";
var INDEX_FILE = "_index.scss";
var CUSTOM_SCSS_PATH = "quartz/styles/custom.scss";
var SYNCER_IMPORT = '@use "./syncer";';
var AssetSyncer = class {
  settings;
  constructor(settings) {
    this.settings = settings;
  }
  async collectAssets(connection) {
    const result = {
      success: false,
      filesToStage: /* @__PURE__ */ new Map(),
      filesToDelete: []
    };
    try {
      if (!this.settings.manageSyncerStyles) {
        const cleanup = await this.collectCleanup(connection);
        result.filesToDelete = cleanup.filesToDelete;
        if (cleanup.customScssUpdate) {
          result.filesToStage.set(
            CUSTOM_SCSS_PATH,
            cleanup.customScssUpdate
          );
        }
        if (result.filesToDelete.length > 0 || result.filesToStage.size > 0) {
          import_js_logger.default.info(
            `Will remove ${result.filesToDelete.length} syncer style files`
          );
        }
        result.success = true;
        return result;
      }
      const scssFiles = this.getScssFiles();
      if (scssFiles.size > 0) {
        for (const [path, content] of scssFiles) {
          result.filesToStage.set(path, content);
        }
        const customScssUpdate = await this.getCustomScssUpdate(connection);
        if (customScssUpdate) {
          result.filesToStage.set(CUSTOM_SCSS_PATH, customScssUpdate);
          import_js_logger.default.info("Will add syncer import to custom.scss");
        }
        import_js_logger.default.info(
          `Collected ${result.filesToStage.size} integration style files`
        );
      }
      result.success = true;
    } catch (error) {
      import_js_logger.default.error("Failed to collect integration assets", error);
      new import_obsidian4.Notice(
        "Quartz Syncer: Failed to collect integration styles. Check console for details.",
        1e4
      );
      result.success = false;
    }
    return result;
  }
  async collectCleanup(connection) {
    const filesToDelete = [];
    let customScssUpdate = null;
    try {
      const repoContent = await connection.getContent();
      if (repoContent) {
        const syncerFiles = repoContent.tree.filter(
          (entry) => entry.path.startsWith(SYNCER_STYLES_DIR) && entry.type === "blob"
        );
        for (const file of syncerFiles) {
          filesToDelete.push(file.path);
        }
      }
    } catch (error) {
      import_js_logger.default.debug(
        "Could not list syncer style files for cleanup",
        error
      );
    }
    try {
      const customScss = await connection.getRawFile(CUSTOM_SCSS_PATH);
      if (customScss) {
        const content = Buffer.from(
          customScss.content,
          "base64"
        ).toString("utf-8");
        if (content.includes(SYNCER_IMPORT)) {
          customScssUpdate = this.removeSyncerImport(content);
        }
      }
    } catch {
      import_js_logger.default.debug("custom.scss not found, no cleanup needed");
    }
    return { filesToDelete, customScssUpdate };
  }
  async getCustomScssUpdate(connection) {
    try {
      let content = "";
      try {
        const customScss = await connection.getRawFile(CUSTOM_SCSS_PATH);
        if (customScss) {
          content = Buffer.from(
            customScss.content,
            "base64"
          ).toString("utf-8");
        }
      } catch {
        import_js_logger.default.debug("custom.scss not found, will create with import");
      }
      if (!content.includes(SYNCER_IMPORT)) {
        return this.insertSyncerImport(content);
      }
      return null;
    } catch (error) {
      import_js_logger.default.error("Failed to check custom.scss", error);
      throw error;
    }
  }
  insertSyncerImport(content) {
    if (!content.trim()) {
      return `${SYNCER_IMPORT}
`;
    }
    const baseImportPattern = /@use\s+["']\.\/base(?:\.scss)?["'];?/;
    const match2 = content.match(baseImportPattern);
    if (match2) {
      const insertPosition = match2.index + match2[0].length;
      const before = content.slice(0, insertPosition);
      const after = content.slice(insertPosition);
      return `${before}
${SYNCER_IMPORT}${after}`;
    }
    return `${SYNCER_IMPORT}

${content}`;
  }
  removeSyncerImport(content) {
    const importPattern = new RegExp(
      `\\n?${SYNCER_IMPORT.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\n?`,
      "g"
    );
    return content.replace(importPattern, "\n").replace(/^\n+/, "");
  }
  getScssFiles() {
    const files = /* @__PURE__ */ new Map();
    const assets = integrationRegistry.getCollectedAssets(this.settings);
    const indexImports = [];
    for (const [integrationId, integrationAssets] of assets) {
      if (integrationAssets.scss) {
        const filename = `_${integrationId}.scss`;
        const filepath = `${SYNCER_STYLES_DIR}/${filename}`;
        files.set(filepath, integrationAssets.scss);
        indexImports.push(`@use "./${integrationId}";`);
      }
    }
    if (indexImports.length > 0) {
      const indexContent = `// Quartz Syncer Integration Styles
// This file is auto-generated. Do not edit manually.

${indexImports.join("\n")}
`;
      files.set(`${SYNCER_STYLES_DIR}/${INDEX_FILE}`, indexContent);
    }
    return files;
  }
};

// src/compiler/integrations/dataview.ts
init_esbuild_buffer_shim();
var import_obsidian5 = require("obsidian");
var import_obsidian_dataview2 = __toESM(require_lib());
var import_js_logger2 = __toESM(require_logger());
function getDataviewApi() {
  return (0, import_obsidian_dataview2.getAPI)();
}
function tryDVEvaluate(query, filePath, dvApi) {
  let result = "";
  try {
    const dataviewResult = dvApi.tryEvaluate(query.trim(), {
      this: dvApi.page(filePath) ?? {}
    });
    result = dataviewResult?.toString() ?? "";
  } catch (e) {
    import_js_logger2.default.warn("dvapi.tryEvaluate did not yield any result", e);
  }
  return result;
}
function tryEval(query) {
  let result = "";
  try {
    result = (0, eval)("const dv = DataviewAPI;" + query);
  } catch (e) {
    import_js_logger2.default.warn("eval did not yield any result", e);
  }
  return result;
}
async function tryExecuteJs(query, filePath, dvApi) {
  const div = createEl("div");
  const component = new import_obsidian5.Component();
  component.load();
  await dvApi.executeJs(query, div, component, filePath);
  await renderPromise(div, "[data-tag-name]");
  const markdown = (0, import_obsidian5.htmlToMarkdown)(div) || "";
  return cleanQueryResult(markdown);
}
var DataviewIntegration = {
  id: "dataview",
  name: "Dataview",
  settingKey: "useDataview",
  priority: 100,
  assets: {},
  isAvailable() {
    return !!getDataviewApi();
  },
  getPatterns() {
    const dvApi = getDataviewApi();
    const patterns = [
      {
        id: "dv-block",
        pattern: /```dataview\s(.+?)```/gms,
        type: "block"
      }
    ];
    if (dvApi) {
      const jsKeyword = dvApi.settings.dataviewJsKeyword || "dataviewjs";
      const inlinePrefix = dvApi.settings.inlineQueryPrefix || "=";
      const inlineJsPrefix = dvApi.settings.inlineJsQueryPrefix || "$=";
      patterns.push(
        {
          id: "dv-js-block",
          pattern: new RegExp(
            "```" + escapeRegExp(jsKeyword) + "\\s(.+?)```",
            "gms"
          ),
          type: "block"
        },
        {
          id: "dv-inline",
          pattern: new RegExp(
            "`" + escapeRegExp(inlinePrefix) + "(.+?)`",
            "gms"
          ),
          type: "inline"
        },
        {
          id: "dv-inline-js",
          pattern: new RegExp(
            "`" + escapeRegExp(inlineJsPrefix) + "(.+?)`",
            "gms"
          ),
          type: "inline"
        }
      );
    }
    return patterns;
  },
  async compile(match2, context) {
    const dvApi = getDataviewApi();
    if (!dvApi) return match2.fullMatch;
    const filePath = context.file.getPath();
    const query = match2.captures[0];
    const { isInsideCalloutDepth, finalQuery } = sanitizeQuery(query);
    try {
      let result = "";
      switch (match2.descriptor.id) {
        case "dv-block": {
          let markdown = await dvApi.tryQueryMarkdown(
            finalQuery,
            filePath
          );
          if (isInsideCalloutDepth > 0) {
            markdown = surroundWithCalloutBlock(
              markdown,
              isInsideCalloutDepth
            );
          }
          return markdown;
        }
        case "dv-js-block": {
          return await tryExecuteJs(finalQuery, filePath, dvApi) ?? "";
        }
        case "dv-inline": {
          result = tryDVEvaluate(query.trim(), filePath, dvApi);
          return result?.toString() ?? "";
        }
        case "dv-inline-js": {
          result = tryDVEvaluate(query, filePath, dvApi);
          if (!result) {
            result = tryEval(query);
          }
          if (!result) {
            result = await tryExecuteJs(query, filePath, dvApi);
          }
          return result ?? "Unable to render query";
        }
        default:
          return match2.fullMatch;
      }
    } catch (e) {
      import_js_logger2.default.error(e);
      new import_obsidian5.Notice(
        "Quartz Syncer: Unable to render dataview query. Please update the dataview plugin to the latest version."
      );
      return match2.fullMatch;
    }
  }
};

// src/compiler/integrations/datacore.ts
init_esbuild_buffer_shim();
var import_obsidian6 = require("obsidian");
var import_js_logger3 = __toESM(require_logger());

// src/ui/suggest/constants.ts
init_esbuild_buffer_shim();
var quartzSyncerIcon = `<?xml version="1.0" encoding="UTF-8"?><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100px" height="100px" viewBox="0 0 100 100" version="1.1"><g id="surface1"><path style=" stroke:none;fill-rule:nonzero;fill:currentColor;fill-opacity:1;" d="M 53.113281 52.53125 L 57.699219 54.550781 L 63.097656 68.074219 L 59.71875 81.945312 L 43.515625 81.671875 L 35.589844 78.5625 L 33.105469 68.734375 L 37.222656 63.136719 Z M 53.113281 52.53125 "/><path style=" stroke:none;fill-rule:nonzero;fill:currentColor;fill-opacity:1;" d="M 51.832031 49.734375 L 51.792969 28.945312 L 64.691406 30.773438 L 66.050781 18.417969 L 53.347656 7.265625 L 27.390625 23.933594 L 34.464844 51.597656 L 41.109375 57.269531 Z M 51.832031 49.734375 "/><path style=" stroke:none;fill-rule:nonzero;fill:currentColor;fill-opacity:1;" d="M 30.65625 45.847656 L 32.519531 53.152344 L 39.125 58.980469 L 35.242188 61.972656 L 30.773438 68.34375 L 33.066406 76.386719 L 19.894531 57.582031 L 24.4375 44.800781 Z M 30.65625 45.847656 "/><path style=" stroke:none;fill-rule:nonzero;fill:currentColor;fill-opacity:1;" d="M 54.511719 31.628906 L 66.710938 33.414062 L 68.074219 23.738281 L 76.117188 27.78125 L 80.3125 40.449219 L 70.171875 73.472656 L 63.992188 74.210938 L 65.78125 67.179688 L 59.71875 52.570312 L 54.550781 49.964844 Z M 54.511719 31.628906 "/><path style=" stroke:none;fill-rule:nonzero;fill:currentColor;fill-opacity:1;" d="M 63.761719 76.621094 L 70.871094 75.726562 L 77.515625 77.980469 L 75.921875 82.175781 L 69.589844 85.867188 L 61.855469 82.566406 Z M 63.761719 76.621094 "/><path style=" stroke:none;fill-rule:nonzero;fill:currentColor;fill-opacity:1;" d="M 60.691406 84.390625 L 67.800781 88.277344 L 66.597656 92.628906 L 61.777344 95.152344 L 54.863281 93.753906 Z M 60.691406 84.390625 "/><path style=" stroke:none;fill-rule:nonzero;fill:currentColor;fill-opacity:1;" d="M 44.800781 84.742188 L 57.777344 84.546875 L 52.375 93.210938 L 43.363281 94.609375 L 41.652344 93.25 Z M 44.800781 84.742188 "/><path style=" stroke:none;fill-rule:nonzero;fill:currentColor;fill-opacity:1;" d="M 35.628906 81.789062 L 42.699219 84.351562 L 39.398438 92.824219 L 32.871094 91.578125 Z M 35.628906 81.789062 "/><path style=" stroke:none;fill-rule:nonzero;fill:currentColor;fill-opacity:1;" d="M 31.742188 77.320312 L 34.191406 80.46875 L 32.367188 86.449219 L 29.023438 81.90625 Z M 31.742188 77.320312 "/></g></svg>`;
var AUTO_CARD_LINK_PLUGIN_ID = "auto-card-link";
var EXCALIDRAW_PLUGIN_ID = "obsidian-excalidraw-plugin";
var DATACORE_PLUGIN_ID = "datacore";
var FANTASY_STATBLOCKS_PLUGIN_ID = "obsidian-5e-statblocks";

// src/compiler/integrations/datacore.ts
var datacoreScss = `
/* Card styles */
.datacore-card {
  display: flex;
  flex-direction: column;
  padding: 1.2rem;
  border-radius: 0.5em;
  background-color: var(--background-secondary);
  min-width: 89%;
  border: 2px solid var(--table-border-color);
  overflow-y: scroll;
  transition: all 0.3s cubic-bezier(0.65, 0.05, 0.36, 1);
}

.datacore-card-title {
  margin-bottom: 0.6em;
  display: flex;
  justify-content: space-between;
  font-size: 1.8em;
}

.datacore-card-title.centered {
  justify-content: center !important;
}

.datacore-card-content,
.datacore-card-inner {
  transition: all 0.3s cubic-bezier(0.65, 0.05, 0.36, 1);
}

.datacore-card-inner {
  overflow-y: scroll;
  overflow-x: hidden;
  max-height: 500px;
  display: flex;
}

.datacore-card .datacore-card-collapser,
.datacore-card.is-collapsed .datacore-card-collapser {
  transition: all 0.5s cubic-bezier(0.65, 0.05, 0.36, 1);
}

.datacore-card-content {
  flex-grow: 1;
}

.datacore-card:not(.datacore-card.is-collapsed) .datacore-card-collapser {
  transform: rotate(180deg);
}

.datacore-card.is-collapsed .datacore-card-collapser {
  transform: rotate(0deg) !important;
}

.datacore-card-collapse,
.datacore-card-collapser svg {
  min-width: 1em;
  min-height: 1em;
  fill: currentColor;
  vertical-align: middle;
}

.datacore-card .datacore-card-footer {
  font-size: 0.7em;
  text-align: right;
  padding: 0;
}

/* Table styles */
.datacore-table {
  width: 100%;
}

.datacore-table > thead > tr,
.datacore-table > tbody > tr {
  margin-top: 1em;
  margin-bottom: 1em;
  text-align: left;
}

.datacore-table > tbody > tr:hover {
  background-color: var(--text-selection) !important;
}

.datacore-table > thead > tr > th {
  font-weight: 700;
  font-size: larger;
  border-top: none;
  border-left: none;
  border-right: none;
  border-bottom: solid;
  max-width: 100%;
}

.datacore-table > tbody > tr > td {
  text-align: left;
  border: none;
  font-weight: 400;
  max-width: 100%;
}

.datacore-table ul,
.datacore-table ol {
  margin-block-start: 0.2em !important;
  margin-block-end: 0.2em !important;
}

.datacore-table-header-cell-content {
  width: auto;
  display: inline-flex;
  flex-direction: row;
}

.datacore-table-sort {
  flex-grow: 0;
  margin-right: 0.25em;
  align-items: center;
}

.datacore-table-header-title {
  align-items: center;
  flex-grow: 1;
}

/* Layout styles */
.dc-stack {
  display: flex;
  flex-direction: column;
  margin: 4px;
}

.dc-group {
  display: flex;
  flex-direction: row;
  margin: 4px;
}

/* Basic UI elements */
.dc-button {
  padding: 4px;
  margin-left: 4px;
  margin-right: 4px;
  margin-top: 2px;
  margin-bottom: 2px;
}

.dc-intent-error {
  background-color: var(--color-red) !important;
}

.dc-intent-warn {
  background-color: var(--color-orange) !important;
}

.dc-intent-info {
  background-color: var(--color-blue) !important;
}

.dc-intent-success {
  background-color: var(--color-green) !important;
}

.dc-textbox {
  padding: 4px;
  margin-left: 4px;
  margin-right: 4px;
  margin-top: 2px;
  margin-bottom: 2px;
}

.dc-checkbox {
  display: inline-flex;
  align-items: center;
  cursor: pointer;
  margin: 4px 0;
  font-size: 16px;
}

.dc-checkbox input[type="checkbox"] {
  width: 16px;
  height: 16px;
  cursor: pointer;
}

.dc-checkbox:hover {
  opacity: 0.8;
}

.dc-checkbox input[type="checkbox"]:focus {
  outline: none;
  box-shadow: var(--shadow-s);
}

.dc-checkbox-disabled {
  cursor: not-allowed;
  opacity: 0.6;
}

.dc-checkbox-disabled input[type="checkbox"] {
  cursor: not-allowed;
}

.dc-slider {
  -webkit-appearance: none;
  appearance: none;
  transition: background 0.3s;
}

.dc-switch.dc-switch-disabled {
  cursor: not-allowed;
  opacity: 0.6;
}

.dc-icon {
  display: inline-flex;
  align-items: center;
}

/* Paging controls */
.dc-paging-control {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 10px;
  margin-bottom: 10px;
  gap: 10px;
}

button.dc-paging-control-page {
  width: var(--input-height);
  height: var(--input-height);
  padding: 0;
  cursor: pointer;
  background-color: unset;
  box-shadow: none;
}

button.dc-paging-control-page:hover {
  background-color: var(--text-selection);
}

button.dc-paging-control-page-active {
  background-color: var(--text-selection);
}

button.dc-paging-control-page[disabled] {
  cursor: inherit;
  opacity: 0.5;
}

button.dc-paging-control-page[disabled]:hover {
  background-color: unset;
  box-shadow: none;
}

.dc-paging-control-separator:hover > .dc-paging-control-ellipsis {
  display: none;
}

.dc-paging-control-separator > .dc-paging-control-leap-left,
.dc-paging-control-separator > .dc-paging-control-leap-right {
  display: none;
}

.dc-paging-control-separator:hover > .dc-paging-control-leap-left,
.dc-paging-control-separator:hover > .dc-paging-control-leap-right {
  display: flex;
}

.dc-paging-control-separator > .dc-paging-control-leap-left {
  transform: rotate(180deg);
}

/* Callout styles */
.datacore .callout-content,
.datacore.callout {
  transition: all 100ms cubic-bezier(0.02, 0.01, 0.47, 1);
  margin-top: 10px;
  margin-bottom: 10px;
}

.datacore .callout-fold {
  align-self: center;
}

/* Embed styles */
.datacore-span-embed {
  position: relative;
  padding: 1px 8px 1px 8px;
  margin: 4px 0px 4px 0px;
  background-color: var(--color-base-25);
}

.datacore-embed-source {
  position: absolute;
  top: 4px;
  right: 4px;
  padding-left: 4px;
  padding-right: 4px;
  background-color: var(--background-secondary-alt);
  color: var(--text-faint);
  font-size: var(--font-smallest);
}

/* Error and loading styles */
.datacore-error-retry {
  margin-top: 1em;
  text-align: center;
}

.datacore-error-box {
  width: 100%;
  min-height: 150px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: 4px dashed var(--background-secondary);
}

.datacore-error-title {
  text-align: center;
}

.datacore-error-message {
  color: var(--text-muted);
  text-align: center;
}

.datacore-loading-boundary {
  width: 100%;
  min-height: 150px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: 4px dashed var(--background-secondary);
}

.datacore-loading-title {
  text-align: center;
}

.datacore-loading-content {
  color: var(--text-muted);
  text-align: center;
}

/* Language block styles */
.block-language-datacore li.selected,
.block-language-datacorejs li.selected {
  background: var(--text-accent);
  padding: 0.2em;
  border-radius: 50%;
  width: 2em;
  height: 2em;
}

.block-language-datacore li.selected a,
.block-language-datacorejs li.selected a {
  color: var(--text-on-accent-inverted);
  display: block;
  text-align: center;
  font-weight: bold;
}

.block-language-datacore .datacore-pager,
.block-language-datacorejs .datacore-pager {
  display: flex;
  justify-content: space-between;
  list-style: none;
  min-width: 90%;
  margin-right: 1.7em;
}

.block-language-datacore li.previous,
.block-language-datacore li.next,
.block-language-datacorejs li.previous,
.block-language-datacorejs li.next {
  min-height: 1.4em;
  min-width: 1.4em;
}

.block-language-datacore li.previous svg,
.block-language-datacore li.next svg,
.block-language-datacorejs li.previous svg,
.block-language-datacorejs li.next svg {
  color: currentColor;
  fill: currentColor !important;
}
`;
function getDatacoreApi() {
  if (isPluginEnabled(DATACORE_PLUGIN_ID)) {
    return window.datacore;
  }
  return void 0;
}
async function tryExecuteJs2(query, filePath, dcApi) {
  const div = createEl("div");
  const component = new import_obsidian6.Component();
  try {
    dcApi.executeJs(query, div, component, filePath);
  } catch (error) {
    import_js_logger3.default.error(error);
    new import_obsidian6.Notice(
      `Quartz Syncer: DatacoreJS execution error: ${error}, trying JSX...`
    );
    return tryExecuteJsx(query, filePath, dcApi);
  }
  component.load();
  await renderPromise(
    div,
    '[class*=datacore], [__self="[Object object]"], [__source="[Object object]"]'
  );
  return div;
}
async function tryExecuteJsx(query, filePath, dcApi) {
  const div = createEl("div");
  const component = new import_obsidian6.Component();
  try {
    dcApi.executeJsx(query, div, component, filePath);
  } catch (error) {
    import_js_logger3.default.error(error);
    new import_obsidian6.Notice(`Quartz Syncer: DatacoreJSX execution error: ${error}`);
    return div;
  }
  component.load();
  await renderPromise(
    div,
    '[class*=datacore], [__self="[Object object]"], [__source="[Object object]"]'
  );
  return div;
}
async function tryExecuteTs(query, filePath, dcApi) {
  const div = createEl("div");
  const component = new import_obsidian6.Component();
  try {
    dcApi.executeTs(query, div, component, filePath);
  } catch (error) {
    import_js_logger3.default.error(error);
    new import_obsidian6.Notice(
      `Quartz Syncer: DatacoreTS execution error: ${error}, trying TSX...`
    );
    return tryExecuteTsx(query, filePath, dcApi);
  }
  component.load();
  await renderPromise(
    div,
    '[class*=datacore], [__self="[Object object]"], [__source="[Object object]"]'
  );
  return div;
}
async function tryExecuteTsx(query, filePath, dcApi) {
  const div = createEl("div");
  const component = new import_obsidian6.Component();
  try {
    dcApi.executeTsx(query, div, component, filePath);
  } catch (error) {
    import_js_logger3.default.error(error);
    new import_obsidian6.Notice(`Quartz Syncer: DatacoreTSX execution error: ${error}`);
    return div;
  }
  component.load();
  await renderPromise(
    div,
    '[class*=datacore], [__self="[Object object]"], [__source="[Object object]"]'
  );
  return div;
}
var DatacoreIntegration = {
  id: "datacore",
  name: "Datacore",
  settingKey: "useDatacore",
  priority: 100,
  assets: {
    scss: datacoreScss
  },
  isAvailable() {
    return !!getDatacoreApi();
  },
  getPatterns() {
    return [
      {
        id: "dc-js",
        pattern: /```datacorejs\s(.+?)```/gms,
        type: "block"
      },
      {
        id: "dc-jsx",
        pattern: /```datacorejsx\s(.+?)```/gms,
        type: "block"
      },
      {
        id: "dc-ts",
        pattern: /```datacorets\s(.+?)```/gms,
        type: "block"
      },
      {
        id: "dc-tsx",
        pattern: /```datacoretsx\s(.+?)```/gms,
        type: "block"
      }
    ];
  },
  async compile(match2, context) {
    const dcApi = getDatacoreApi();
    if (!dcApi) return match2.fullMatch;
    const filePath = context.file.getPath();
    const query = match2.captures[0];
    const { isInsideCalloutDepth, finalQuery } = sanitizeQuery(query);
    const serializer = new XMLSerializer();
    try {
      let queryResult;
      switch (match2.descriptor.id) {
        case "dc-js":
          queryResult = await tryExecuteJs2(
            finalQuery,
            filePath,
            dcApi
          );
          break;
        case "dc-jsx":
          queryResult = await tryExecuteJsx(
            finalQuery,
            filePath,
            dcApi
          );
          break;
        case "dc-ts":
          queryResult = await tryExecuteTs(
            finalQuery,
            filePath,
            dcApi
          );
          break;
        case "dc-tsx":
          queryResult = await tryExecuteTsx(
            finalQuery,
            filePath,
            dcApi
          );
          break;
        default:
          return match2.fullMatch;
      }
      const result = sanitizeHTMLToString(queryResult, serializer);
      if (isInsideCalloutDepth > 0) {
        return surroundWithCalloutBlock(result, isInsideCalloutDepth);
      }
      return result;
    } catch (error) {
      import_js_logger3.default.error(error);
      new import_obsidian6.Notice(`Quartz Syncer: Datacore query error: ${error}`);
      return match2.fullMatch;
    }
  }
};

// src/compiler/integrations/excalidraw.ts
init_esbuild_buffer_shim();
var import_obsidian7 = require("obsidian");
var import_js_logger4 = __toESM(require_logger());
var excalidrawScss = `
.excalidraw-svg {
  display: none;
  max-width: 100%;
  margin: 0 auto;
}

:root[saved-theme="light"] .excalidraw-svg.excalidraw-light {
  display: block;
}

:root[saved-theme="dark"] .excalidraw-svg.excalidraw-dark {
  display: block;
}
`;
function getExcalidrawAutomate() {
  if (isPluginEnabled(EXCALIDRAW_PLUGIN_ID) && window.ExcalidrawAutomate) {
    return window.ExcalidrawAutomate;
  }
  return void 0;
}
async function createThemedSVGs(path, ea) {
  try {
    const exportSettings = ea.getExportSettings(false, true);
    const darkLoader = ea.getEmbeddedFilesLoader(true);
    const lightLoader = ea.getEmbeddedFilesLoader(false);
    const svgDark = await ea.createSVG(
      path,
      false,
      exportSettings,
      darkLoader,
      "dark"
    );
    const svgLight = await ea.createSVG(
      path,
      false,
      exportSettings,
      lightLoader,
      "light"
    );
    svgDark.style.maxWidth = "100%";
    svgDark.style.height = "auto";
    svgDark.querySelectorAll("style.style-fonts, metadata, mask, defs")?.forEach((element2) => element2.remove());
    svgLight.style.maxWidth = "100%";
    svgLight.style.height = "auto";
    svgLight.querySelectorAll("style.style-fonts, metadata, mask, defs")?.forEach((element2) => element2.remove());
    return { dark: svgDark, light: svgLight };
  } catch (e) {
    import_js_logger4.default.error("Failed to create Excalidraw SVGs:", e);
    new import_obsidian7.Notice(
      "Quartz Syncer: Unable to render Excalidraw drawing. Check console for details."
    );
    return { dark: null, light: null };
  }
}
var ExcalidrawIntegration = {
  id: "excalidraw",
  name: "Excalidraw",
  settingKey: "useExcalidraw",
  priority: 50,
  assets: {
    scss: excalidrawScss
  },
  isAvailable() {
    return !!getExcalidrawAutomate();
  },
  getPatterns() {
    return [
      {
        id: "excalidraw-embed",
        pattern: /!\[\[(.+?\.excalidraw(?:\.md)?.*?)(?:\|(.+))?\]\]/g,
        type: "inline"
      },
      {
        id: "excalidraw-link",
        pattern: /\[\[(.+?\.excalidraw(?:\.md)?.*?)(?:\|(.+))?\]\]/g,
        type: "inline"
      }
    ];
  },
  shouldTransformFile(file) {
    return file.getFrontmatter()?.["excalidraw-plugin"] === "parsed";
  },
  async transformFile(file, _text, _context) {
    const ea = getExcalidrawAutomate();
    if (!ea) return _text;
    const { dark, light } = await createThemedSVGs(file.file.path, ea);
    if (!dark && !light) {
      return _text;
    }
    return `<div>
<div class="excalidraw-svg excalidraw-dark" style="background-image:url(${svgToData(dark)});background-size:contain;background-repeat:no-repeat;width:100%;aspect-ratio:${dark.viewBox.baseVal.width / dark.viewBox.baseVal.height};"></div>
<div class="excalidraw-svg excalidraw-light" style="background-image:url(${svgToData(light)});background-size:contain;background-repeat:no-repeat;width:100%;aspect-ratio:${light.viewBox.baseVal.width / light.viewBox.baseVal.height};"></div>
</div>`;
  },
  async compile(match2, context) {
    const ea = getExcalidrawAutomate();
    if (!ea) return match2.fullMatch;
    const filePath = match2.captures[0];
    const displayName = match2.captures[1];
    const isEmbedded = match2.descriptor.id === "excalidraw-embed";
    const fullLinkedFilePath = (0, import_obsidian7.getLinkpath)(filePath);
    const linkedFile = context.app.metadataCache.getFirstLinkpathDest(
      fullLinkedFilePath,
      context.file.getPath()
    );
    if (!linkedFile) {
      return match2.fullMatch;
    }
    const extensionlessPath = linkedFile.path.substring(
      0,
      linkedFile.path.lastIndexOf(".")
    );
    if (!isEmbedded) {
      const linkEl = createEl("a", {
        text: displayName || linkedFile.basename,
        href: extensionlessPath
      });
      return linkEl.outerHTML;
    }
    const { dark, light } = await createThemedSVGs(linkedFile.path, ea);
    if (!dark || !light) {
      return match2.fullMatch;
    }
    const width = `${dark.viewBox.baseVal.width}px`;
    const aspectRatio = dark.viewBox.baseVal.width / dark.viewBox.baseVal.height;
    dark.removeAttribute("width");
    dark.removeAttribute("height");
    dark.removeAttribute("viewBox");
    light.removeAttribute("width");
    light.removeAttribute("height");
    light.removeAttribute("viewBox");
    return `<div>
<div class="excalidraw-svg excalidraw-dark" style="background-image:url(${svgToData(dark)});background-size:cover;background-repeat:no-repeat;width:${width};height:auto;aspect-ratio:${aspectRatio};"></div>
<div class="excalidraw-svg excalidraw-light" style="background-image:url(${svgToData(light)});background-size:cover;background-repeat:no-repeat;width:${width};height:auto;aspect-ratio:${aspectRatio};"></div>
</div>`;
  }
};

// src/compiler/integrations/fantasy-statblocks.ts
init_esbuild_buffer_shim();
var import_obsidian8 = require("obsidian");
var import_js_logger5 = __toESM(require_logger());
var fantasyStatblocksScss = `
// Quartz fixes
.statblock {
  .statblock-item-container div {
    display: inline;
    &.tapered-rule,
    span.statblock-table-header {
      display: block;
    }
    &.statblock-table {
      display: flex;
    }
    &.traits {
      font-family: var(--active-traits-font);
      color: var(--active-traits-font-color);
      font-size: var(--active-traits-font-size);
      font-weight: var(--active-traits-font-weight);
      font-style: var(--active-traits-font-style);
    }
  }
  p {
    color: inherit;
    display: inline;
    font: inherit;
  }
}
// Quartz fixes end

:root {
  --statblock-primary-color: #7a200d;
  --statblock-rule-color: #922610;
  --statblock-background-color: #fdf1dc;

  --statblock-bar-color: #e69a28;
  --statblock-bar-border-size: 1px;
  --statblock-bar-border-color: #000;

  --statblock-image-width: 75px;
  --statblock-image-height: 75px;
  --statblock-image-border-size: 2px;
  --statblock-image-border-color: var(--statblock-primary-color);

  --statblock-border-size: 1px;
  --statblock-border-color: #ddd;

  --statblock-box-shadow-color: #ddd;
  --statblock-box-shadow-x-offset: 0;
  --statblock-box-shadow-y-offset: 0;
  --statblock-box-shadow-blur: 1.5em;

  --statblock-font-color: var(--statblock-primary-color);
  --statblock-font-weight: 700;

  --statblock-content-font: "Noto Sans", "Myriad Pro", Calibri, Helvetica, Arial, sans-serif;
  --statblock-content-font-size: 14px;

  --statblock-heading-font: "Libre Baskerville", "Lora", "Calisto MT", "Bookman Old Style", Bookman, "Goudy Old Style", Garamond, "Hoefler Text", "Bitstream Charter", Georgia, serif;
  --statblock-heading-font-color: var(--statblock-font-color);
  --statblock-heading-font-size: 23px;
  --statblock-heading-font-variant: small-caps;
  --statblock-heading-font-weight: var(--statblock-font-weight);
  --statblock-heading-line-height: inherit;

  --statblock-property-line-height: 1.4;
  --statblock-property-font-color: var(--statblock-font-color);
  --statblock-property-name-font-color: var(--statblock-font-color);
  --statblock-property-name-font-weight: bold;

  --statblock-section-heading-border-size: 1px;
  --statblock-section-heading-border-color: var(--statblock-primary-color);
  --statblock-section-heading-font-color: var(--statblock-font-color);
  --statblock-section-heading-font-size: 21px;
  --statblock-section-heading-font-variant: small-caps;
  --statblock-section-heading-font-weight: normal;

  --statblock-saves-line-height: 1.4;

  --statblock-spells-font-style: italic;

  --statblock-subheading-font-size: 12px;
  --statblock-subheading-font-style: italic;
  --statblock-subheading-font-weight: normal;

  --statblock-table-header-font-weight: bold;

  --statblock-traits-name-font-weight: bold;
  --statblock-traits-name-font-style: italic;

  --statblock-link-style: italic;
}

.statblock-item-container {
  margin-bottom: 0.25rem;
}

.statblock-item-inline {
  display: flex;
  justify-content: space-between;
}

.statblock {
  --active-primary-color: var(--statblock-primary-color);
  --active-rule-color: var(--statblock-rule-color);
  --active-background-color: var(--statblock-background-color);

  --active-bar-color: var(--statblock-bar-color);
  --active-bar-border-size: var(--statblock-bar-border-size);
  --active-bar-border-color: var(--statblock-bar-border-color);

  --active-image-width: var(--statblock-image-width);
  --active-image-height: var(--statblock-image-height);
  --active-image-border-size: var(--statblock-image-border-size);
  --active-image-border-color: var(--statblock-image-border-color, var(--active-primary-color));

  --active-border-size: var(--statblock-border-size);
  --active-border-color: var(--statblock-border-color);

  --active-box-shadow-color: var(--statblock-box-shadow-color);
  --active-box-shadow-x-offset: var(--statblock-box-shadow-x-offset);
  --active-box-shadow-y-offset: var(--statblock-box-shadow-y-offset);
  --active-box-shadow-blur: var(--statblock-box-shadow-blur);

  --active-font-color: var(--statblock-font-color, var(--active-primary-color));
  --active-font-weight: var(--statblock-font-weight);

  --active-content-font: var(--statblock-content-font);
  --active-content-font-size: var(--statblock-content-font-size);

  --active-heading-font: var(--statblock-heading-font);
  --active-heading-font-color: var(--statblock-heading-font-color);
  --active-heading-font-size: var(--statblock-heading-font-size);
  --active-heading-font-variant: var(--statblock-heading-font-variant);
  --active-heading-font-weight: var(--statblock-heading-font-weight);
  --active-heading-line-height: var(--statblock-heading-line-height);

  --active-property-line-height: var(--statblock-property-line-height);
  --active-property-font: var(--statblock-property-font);
  --active-property-font-color: var(--statblock-property-font-color);
  --active-property-font-variant: var(--statblock-property-font-variant);
  --active-property-font-size: var(--statblock-property-font-size);
  --active-property-font-weight: var(--statblock-property-font-weight);

  --active-property-name-font: var(--statblock-property-name-font);
  --active-property-name-font-color: var(--statblock-property-name-font-color);
  --active-property-name-font-variant: var(--statblock-property-name-font-variant);
  --active-property-name-font-size: var(--statblock-property-name-font-size);
  --active-property-name-font-weight: var(--statblock-property-name-font-weight);

  --active-section-heading-border-size: var(--statblock-section-heading-border-size);
  --active-section-heading-border-color: var(--statblock-section-heading-border-color);
  --active-section-heading-font: var(--statblock-section-heading-font);
  --active-section-heading-font-color: var(--statblock-section-heading-font-color);
  --active-section-heading-font-size: var(--statblock-section-heading-font-size);
  --active-section-heading-font-variant: var(--statblock-section-heading-font-variant);
  --active-section-heading-font-weight: var(--statblock-section-heading-font-weight);

  --active-saves-line-height: var(--statblock-saves-line-height);

  --active-spells-font-style: var(--statblock-spells-font-style);

  --active-subheading-font: var(--statblock-subheading-font);
  --active-subheading-font-color: var(--statblock-subheading-font-color);
  --active-subheading-font-size: var(--statblock-subheading-font-size);
  --active-subheading-font-style: var(--statblock-subheading-font-style);
  --active-subheading-font-weight: var(--statblock-subheading-font-weight);

  --active-table-header-font-weight: var(--statblock-table-header-font-weight);

  --active-traits-font: var(--statblock-traits-font);
  --active-traits-font-color: var(--statblock-traits-font-color);
  --active-traits-font-size: var(--statblock-traits-font-size);
  --active-traits-font-weight: var(--statblock-traits-font-weight);
  --active-traits-font-style: var(--statblock-traits-font-style);
  --active-traits-name-font: var(--statblock-traits-name-font);
  --active-traits-name-font-color: var(--statblock-traits-name-font-color);
  --active-traits-name-font-size: var(--statblock-traits-name-font-size);
  --active-traits-name-font-weight: var(--statblock-traits-name-font-weight);
  --active-traits-name-font-style: var(--statblock-traits-name-font-style);

  --active-link-style: var(--statblock-link-style);

  margin: 0 auto;
  position: relative;

  a {
    font-style: var(--statblock-link-style);
  }
}

.statblock-content-container {
  .statblock-content {
    font-family: var(--active-content-font);
    font-size: var(--active-content-font-size);
    color: var(--active-font-color);
    background-color: var(--active-background-color);
    padding: 0.5em;
    border: var(--active-border-size) var(--active-border-color) solid;
    box-shadow: var(--active-box-shadow-x-offset)
      var(--active-box-shadow-y-offset) var(--active-box-shadow-blur)
      var(--active-box-shadow-color);
    margin-left: 2px;
    margin-right: 2px;
    display: flex;
    gap: 1rem;

    > .column {
      width: var(--statblock-column-width, 400px);
    }

    @media screen and (max-width: 400px) {
      > .column {
        width: 75vw;
      }
    }
  }
}

.bar {
  height: 5px;
  background: var(--active-bar-color);
  border: var(--active-bar-border-size) solid var(--active-bar-border-color);
  z-index: 1;
  width: auto;
}

.heading,
.statblock-heading {
  font-family: var(--active-heading-font);
  color: var(--active-heading-font-color);
  font-weight: var(--active-heading-font-weight);
  font-variant: var(--active-heading-font-variant);
  font-size: var(--active-heading-font-size);
  line-height: var(--active-heading-line-height);
  margin: 0px;
  letter-spacing: 1px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.flex-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.subheading {
  font-weight: var(--active-subheading-font-weight);
  font-style: var(--active-subheading-font-style);
  font-size: var(--active-subheading-font-size);
  font-family: var(--active-subheading-font-family);
  color: var(--active-subheading-font-color);
  margin: 0;
}

.line {
  line-height: var(--active-property-line-height);
  display: block;
  font-family: var(--active-property-font);
  color: var(--active-property-font-color);
  font-variant: var(--active-property-font-variant);
  font-size: var(--active-property-font-size);
  font-weight: var(--active-property-font-weight);
}

.property-name {
  margin: 0;
  margin-right: 0.25em;
  display: inline;
  font-family: var(--active-property-name-font);
  color: var(--active-property-name-font-color);
  font-variant: var(--active-property-name-font-variant);
  font-size: var(--active-property-name-font-size);
  font-weight: var(--active-property-name-font-weight);
}

.section-header {
  border-bottom: var(--active-section-heading-border-size) solid var(--active-section-heading-border-color);
  color: var(--active-section-heading-font-color);
  font-size: var(--active-section-heading-font-size);
  font-variant: var(--active-section-heading-font-variant);
  font-weight: var(--active-section-heading-font-weight);
  font-family: var(--active-section-heading-font);
  letter-spacing: 1px;
  margin: 0;
  margin-bottom: 0.3em;
  break-inside: avoid-column;
  break-after: avoid-column;
}

.tapered-rule {
  width: auto;
  margin: 0.5em 0;
  height: 5px;
  background: linear-gradient(
    90deg,
    var(--active-rule-color) 0%,
    var(--active-rule-color) 50%,
    var(--active-background-color) 95%,
    var(--active-background-color) 100%
  );
  clip-path: polygon(0 0, 0 100%, 95% 50%);
}

.trait {
  font-family: var(--active-traits-font);
  color: var(--active-traits-font-color);
  font-size: var(--active-traits-font-size);
  font-weight: var(--active-traits-font-weight);
  font-style: var(--active-traits-font-style);
}

.trait-name {
  font-family: var(--active-traits-name-font);
  color: var(--active-traits-name-font-color);
  font-size: var(--active-traits-name-font-size);
  font-weight: var(--active-traits-name-font-weight);
  font-style: var(--active-traits-name-font-style);
}

.statblock-nested-traits {
  margin-left: 1rem;
}

.statblock-table {
  display: flex;
  justify-content: space-evenly;
  align-items: center;
  flex-wrap: wrap;
}

.table-item {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-flow: column nowrap;
}

.statblock-table-header {
  font-weight: var(--active-table-header-font-weight);
}

.calculated-modifier::before {
  content: "(";
}

.calculated-modifier::after {
  content: ")";
}

.info {
  .line {
    line-height: var(--active-saves-line-height);
    display: block;
    color: var(--active-font-color);

    .property-name {
      color: var(--active-property-name-font-color);
      margin: 0;
      margin-right: 0.25em;
      display: inline;
      font-weight: bold;
    }

    .property-text {
      display: inline;
      margin: 0;
    }
  }
}

.save-entry,
.save-name,
.save-value {
  display: inline;
}

.save-entry:not(:last-child) .save-value::after {
  content: ", ";
}

.image {
  width: var(--active-image-width);
  height: var(--active-image-height);

  &.pointer {
    cursor: pointer;
  }

  img {
    object-fit: cover;
    width: 100%;
    height: 100%;
    border-radius: 100%;
    border: var(--active-image-border-size) solid var(--active-image-border-color);
    object-position: center;
  }
}
`;
function getFantasyStatblocksApi() {
  if (isPluginEnabled(FANTASY_STATBLOCKS_PLUGIN_ID)) {
    return window.FantasyStatblocks;
  }
  return void 0;
}
async function tryRenderStatblock(query, filePath, api) {
  const div = createEl("div");
  const component = new import_obsidian8.Component();
  component.load();
  try {
    api.renderMarkdown(query, div, filePath, component);
  } catch (error) {
    import_js_logger5.default.error(error);
    new import_obsidian8.Notice(
      `Quartz Syncer: Fantasy Statblocks execution error: ${error}.`
    );
    return div;
  }
  await renderPromise(div, ".statblock", 5e3);
  return div;
}
var FantasyStatblocksIntegration = {
  id: "fantasy-statblocks",
  name: "Fantasy Statblocks",
  settingKey: "useFantasyStatblocks",
  priority: 100,
  assets: {
    scss: fantasyStatblocksScss
  },
  isAvailable() {
    return !!getFantasyStatblocksApi();
  },
  getPatterns() {
    return [
      {
        id: "statblock",
        pattern: /(```statblock\s.+?```)/gms,
        type: "block"
      }
    ];
  },
  async compile(match2, context) {
    const api = getFantasyStatblocksApi();
    if (!api) return match2.fullMatch;
    const query = match2.fullMatch.trim();
    if (!query) return match2.fullMatch;
    try {
      const renderedDiv = await tryRenderStatblock(
        query,
        context.file.getPath(),
        api
      );
      const selectorsToRemove = [
        ".clickable-icon.extra-setting-button",
        ".statblock-inline-item.action-container"
      ];
      selectorsToRemove.forEach((selector) => {
        renderedDiv.querySelectorAll(selector).forEach((el) => el.remove());
      });
      const modifiers = renderedDiv.querySelectorAll(
        "span.calculated-modifier"
      );
      modifiers.forEach((modifier) => {
        if (modifier.textContent) {
          modifier.textContent = `(${modifier.textContent})`;
        }
      });
      const serializer = new XMLSerializer();
      const renderedHTML = serializer.serializeToString(renderedDiv);
      return renderedHTML.replace(
        ' xmlns="http://www.w3.org/1999/xhtml"',
        ""
      );
    } catch (error) {
      import_js_logger5.default.error(error);
      return match2.fullMatch;
    }
  }
};

// src/compiler/integrations/auto-card-link.ts
init_esbuild_buffer_shim();
var import_obsidian9 = require("obsidian");
var import_js_logger6 = __toESM(require_logger());
var autoCardLinkScss = `
.auto-card-link-container {
  background-color: transparent;
  container-type: inline-size;
  position: relative;
  overflow: hidden;
  user-select: none;
  --auto-card-link-button-width: calc(var(--icon-size, 18px) + var(--size-2-3, 6px));
  --auto-card-link-indent-size: 2.5em;

  @for $i from 1 through 7 {
    &[data-auto-card-link-depth="#{$i}"] {
      margin-left: calc(var(--auto-card-link-indent-size) * #{$i});
    }
  }
}

.auto-card-link-title {
  white-space: normal !important;
  --lh: 1.5em;
  line-height: var(--lh);
  height: calc(var(--lh) * 3);
  overflow: hidden;
  text-overflow: ellipsis;
}

.auto-card-link-card {
  display: flex;
  flex-direction: row-reverse;
  height: 8em;
  transition: 20ms ease-in;
  cursor: pointer;
  text-decoration: none;
  color: var(--link-external-color, var(--highlight));
  background: var(--background-primary-alt, var(--darkgray));
  border: solid var(--border-width) var(--divider-color, var(--lightgray));
  border-radius: var(--radius-s, 4px);

  &:hover {
    color: var(--link-external-color-hover, var(--tertiary));
  }
}

.auto-card-link-main {
  display: flex;
  flex-grow: 1;
  flex-direction: column;
  justify-content: space-between;
  gap: 0.18em;
  padding: 0.5em 0.6em;
  overflow: hidden;
  text-align: left;
}

.auto-card-link-description {
  overflow: hidden;
  --lh: 1.4em;
  line-height: var(--lh);
  height: calc(var(--lh) * 3);
  color: var(--text-muted, var(--darkgray));
  font-size: var(--font-smallest, 0.9em);
}

.auto-card-link-host {
  font-size: var(--font-smallest, 0.9em);
  display: flex;
  flex-direction: row;
  align-items: center;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.auto-card-link-thumbnail {
  margin: 0;
  width: unset !important;
  max-height: 100%;
  object-fit: cover;
}

.auto-card-link-error-container {
  color: var(--text-error);
  padding: 0.5em;
  border: 1px solid var(--text-error);
  border-radius: var(--radius-s, 4px);
}
`;
var YamlParseError = class extends Error {
};
var NoRequiredParamsError = class extends Error {
};
var urlRegex = /^(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})$/i;
function isUrl(text2) {
  return new RegExp(urlRegex).test(text2);
}
function parseLinkMetadataFromYaml(source) {
  let yaml;
  let indent = -1;
  source = source.split(/\r?\n|\r|\n/g).map(
    (line) => line.replace(/^\t+/g, (tabs) => {
      const n2 = tabs.length;
      if (indent < 0) {
        indent = n2;
      }
      return " ".repeat(n2);
    })
  ).join("\n");
  try {
    yaml = (0, import_obsidian9.parseYaml)(source);
  } catch (error) {
    import_js_logger6.default.error(error);
    throw new YamlParseError(
      "failed to parse yaml. Check debug console for more detail."
    );
  }
  if (!yaml || !yaml.url || !yaml.title) {
    throw new NoRequiredParamsError(
      "required params[url, title] are not found."
    );
  }
  return {
    url: yaml.url,
    title: yaml.title,
    description: yaml.description,
    host: yaml.host,
    favicon: yaml.favicon,
    image: yaml.image,
    indent
  };
}
function genErrorEl(errorMsg) {
  const containerEl = createEl("div");
  containerEl.addClass("auto-card-link-error-container");
  const spanEl = createEl("span");
  spanEl.textContent = `cardlink error: ${errorMsg}`;
  containerEl.appendChild(spanEl);
  return containerEl;
}
function genLinkEl(data, app2) {
  const containerEl = createEl("div");
  containerEl.addClass("auto-card-link-container");
  containerEl.setAttr("data-auto-card-link-depth", data.indent);
  const cardEl = createEl("a");
  cardEl.addClass("auto-card-link-card");
  cardEl.setAttr("href", data.url);
  containerEl.appendChild(cardEl);
  const mainEl = createEl("div");
  mainEl.addClass("auto-card-link-main");
  cardEl.appendChild(mainEl);
  const titleEl = createEl("div");
  titleEl.addClass("auto-card-link-title");
  titleEl.textContent = data.title;
  mainEl.appendChild(titleEl);
  if (data.description) {
    const descriptionEl = createEl("div");
    descriptionEl.addClass("auto-card-link-description");
    descriptionEl.textContent = data.description;
    mainEl.appendChild(descriptionEl);
  }
  const hostEl = createEl("div");
  hostEl.addClass("auto-card-link-host");
  mainEl.appendChild(hostEl);
  if (data.host) {
    const hostNameEl = createEl("span");
    hostNameEl.textContent = data.host;
    hostEl.appendChild(hostNameEl);
  }
  if (data.image) {
    let imageSrc = data.image;
    if (!isUrl(imageSrc)) {
      const link = imageSrc.slice(2, -2);
      const imageRelativePath = app2.metadataCache.getFirstLinkpathDest(
        (0, import_obsidian9.getLinkpath)(link),
        ""
      )?.path;
      if (imageRelativePath) {
        imageSrc = app2.vault.adapter.getResourcePath(imageRelativePath);
      }
    }
    const thumbnailEl = createEl("img");
    thumbnailEl.addClass("auto-card-link-thumbnail");
    thumbnailEl.setAttr("src", imageSrc);
    thumbnailEl.setAttr("draggable", "false");
    cardEl.appendChild(thumbnailEl);
  }
  return containerEl;
}
var AutoCardLinkIntegration = {
  id: "auto-card-link",
  name: "Auto Card Link",
  settingKey: "useAutoCardLink",
  priority: 100,
  assets: {
    scss: autoCardLinkScss
  },
  isAvailable() {
    return isPluginEnabled(AUTO_CARD_LINK_PLUGIN_ID);
  },
  getPatterns() {
    return [
      {
        id: "cardlink",
        pattern: /```cardlink\s(.+?)```/gms,
        type: "block"
      }
    ];
  },
  async compile(match2, context) {
    const query = match2.captures[0];
    if (!query) return match2.fullMatch;
    const serializer = new XMLSerializer();
    try {
      const div = createEl("div");
      try {
        const data = parseLinkMetadataFromYaml(query);
        div.appendChild(genLinkEl(data, context.app));
      } catch (error) {
        if (error instanceof NoRequiredParamsError) {
          div.appendChild(genErrorEl(error.message));
        } else if (error instanceof YamlParseError) {
          div.appendChild(genErrorEl(error.message));
        } else if (error instanceof TypeError) {
          div.appendChild(
            genErrorEl(
              "internal links must be surrounded by quotes."
            )
          );
          import_js_logger6.default.error(error);
        } else {
          import_js_logger6.default.error("Code Block: cardlink unknown error", error);
        }
        return sanitizeHTMLToString(div, serializer);
      }
      return sanitizeHTMLToString(div, serializer);
    } catch (error) {
      import_js_logger6.default.error(error);
      new import_obsidian9.Notice(`Quartz Syncer: Auto Card Link error: ${error}`);
      return match2.fullMatch;
    }
  }
};

// src/compiler/integrations/index.ts
integrationRegistry.register(AutoCardLinkIntegration);
integrationRegistry.register(DataviewIntegration);
integrationRegistry.register(DatacoreIntegration);
integrationRegistry.register(ExcalidrawIntegration);
integrationRegistry.register(FantasyStatblocksIntegration);

// src/compiler/PluginCompiler.ts
var PluginCompiler = class {
  app;
  settings;
  constructor(app2, settings) {
    this.app = app2;
    this.settings = settings;
  }
  compile = (file) => {
    return async (text2) => {
      let compiledText = text2;
      const enabledIntegrations = integrationRegistry.getEnabled(
        this.settings
      );
      const context = {
        app: this.app,
        file
      };
      for (const integration of enabledIntegrations) {
        if (integration.shouldTransformFile?.(file)) {
          compiledText = await integration.transformFile(
            file,
            compiledText,
            context
          );
        }
      }
      for (const integration of enabledIntegrations) {
        compiledText = await this.compilePatterns(
          integration,
          compiledText,
          context
        );
      }
      return compiledText;
    };
  };
  async compilePatterns(integration, text2, context) {
    let compiledText = text2;
    const patterns = integration.getPatterns();
    for (const descriptor of patterns) {
      const regex = new RegExp(
        descriptor.pattern.source,
        descriptor.pattern.flags
      );
      const matches = [];
      let match2;
      while ((match2 = regex.exec(text2)) !== null) {
        matches.push({
          descriptor,
          fullMatch: match2[0],
          captures: match2.slice(1)
        });
      }
      for (const patternMatch of matches) {
        const replacement = await integration.compile(
          patternMatch,
          context
        );
        compiledText = compiledText.replace(
          patternMatch.fullMatch,
          replacement
        );
      }
    }
    return compiledText;
  }
  getEnabledIntegrations() {
    return integrationRegistry.getEnabled(this.settings);
  }
  getCollectedAssets() {
    return integrationRegistry.getCollectedAssets(this.settings);
  }
};

// src/compiler/SyncerPageCompiler.ts
var SyncerPageCompiler = class {
  app;
  vault;
  settings;
  metadataCache;
  getFilesMarkedForPublishing;
  rewriteRule;
  datastore;
  constructor(app2, vault, settings, metadataCache, datastore, getFilesMarkedForPublishing) {
    this.app = app2;
    this.vault = vault;
    this.settings = settings;
    this.metadataCache = metadataCache;
    this.datastore = datastore;
    this.getFilesMarkedForPublishing = getFilesMarkedForPublishing;
    this.rewriteRule = getRewriteRules(this.settings.vaultPath);
  }
  /**
   * Runs the compiler steps on the given text.
   * It applies each compiler step in order, passing the result of the previous step to the next one.
   *
   * @param file - The file that is being published.
   * @param compilerSteps - The array of compiler steps to apply.
   * @returns A function that takes the text to compile and returns the compiled text.
   */
  runCompilerSteps = (file, compilerSteps) => async (text2) => {
    return await compilerSteps.reduce(
      async (previousStep, compilerStep) => {
        const previousStepText = await previousStep;
        return compilerStep(file)(previousStepText);
      },
      Promise.resolve(text2)
    );
  };
  /**
   * Generates the markdown content for the given file.
   * It reads the file content, applies various compiler steps to it, and returns the compiled text along with the assets.
   *
   * @param file - The file to generate the markdown content for.
   * @returns A promise that resolves to a tuple containing the compiled text and the assets.
   * @throws If the file is an Excalidraw file, a warning is logged as Excalidraw files are not supported yet.
   */
  async generateMarkdown(file) {
    const vaultFileText = await file.cachedRead();
    if (this.settings.useExcalidraw) {
      if (file.file.name.endsWith(".excalidraw.md")) {
        console.warn("Excalidraw files are not supported yet.");
      }
    }
    const COMPILE_STEPS = [
      this.convertFrontMatter,
      this.createTranscludedText(0),
      this.convertIntegrations,
      this.convertLinksToFullPath,
      this.removeObsidianComments,
      this.createSvgEmbeds,
      this.linkTargeting,
      this.applyVaultPath
    ];
    const compiledText = await this.runCompilerSteps(
      file,
      COMPILE_STEPS
    )(vaultFileText);
    const [text2, blobs] = await this.convertFileLinks(file)(compiledText);
    return [text2, { blobs }];
  }
  /**
   * Applies the vault path to links in the text.
   * It replaces links that start with the vault path with Obsidian-style links (e.g. [[link]]) and Markdown-style links (e.g. [link](path)).
   * If the vault path is not set, or is the vault root, it does nothing.
   *
   * @returns A function that takes the text to compile and returns the compiled text.
   */
  applyVaultPath = () => (text2) => {
    const wikilinkRegex = new RegExp(
      "\\[\\[" + escapeRegExp(this.settings.vaultPath) + "(.*?)\\]\\]",
      "g"
    );
    const markdownLinkRegex = new RegExp(
      "\\[(.*?)\\]\\(" + escapeRegExp(this.settings.vaultPath) + "(.*?)\\)",
      "g"
    );
    if (this.settings.vaultPath !== "/" && this.settings.vaultPath !== "") {
      try {
        text2 = text2.replace(wikilinkRegex, "[[$1]]");
        text2 = text2.replace(markdownLinkRegex, "[$1]($2)");
      } catch (e) {
        import_js_logger7.default.error(
          `Error while applying vault path to text: ${text2}. Error: ${e}`
        );
      }
    }
    return text2;
  };
  /**
   * Removes Obsidian comments from the text.
   * It looks for comments in the form of %% comment %% and removes them, unless they are inside a code block, code fence, or excalidraw drawing.
   *
   * @param text - The text to compile.
   * @returns A function that takes the text to compile and returns the compiled text.
   */
  removeObsidianComments = () => (text2) => {
    const obsidianCommentsRegex = /%%.+?%%/gms;
    const obsidianCommentsMatches = text2.match(obsidianCommentsRegex);
    const codeBlocks = text2.match(CODEBLOCK_REGEX) || [];
    const codeFences = text2.match(CODE_FENCE_REGEX) || [];
    const excalidraw = text2.match(EXCALIDRAW_REGEX) || [];
    const matchesToSkip = [...codeBlocks, ...codeFences, ...excalidraw];
    if (!obsidianCommentsMatches) return text2;
    for (const commentMatch of obsidianCommentsMatches) {
      if (matchesToSkip.findIndex((x) => x.contains(commentMatch)) > -1) {
        continue;
      }
      text2 = text2.replace(commentMatch, "");
    }
    return text2;
  };
  /**
   * Converts the front matter of the file to a string.
   * It replaces the front matter in the text with the compiled front matter from the file.
   *
   * @param file - The file to compile the front matter for.
   * @returns A function that takes the text to compile and returns the compiled text.
   */
  convertFrontMatter = (file) => (text2) => {
    const compiledFrontmatter = file.getCompiledFrontmatter(text2);
    return text2.replace(FRONTMATTER_REGEX, () => compiledFrontmatter);
  };
  /**
   * Converts plugin integrations in the text to their results.
   *
   * @returns A function that takes the text to compile and returns the compiled text.
   */
  convertIntegrations = (file) => async (text2) => {
    const pluginCompiler = new PluginCompiler(this.app, this.settings);
    text2 = await pluginCompiler.compile(file)(text2);
    return text2;
  };
  /**
   * Removes the target="_blank" attribute from Dataview links in the text.
   * It uses a regular expression to find and remove the target attribute.
   *
   * @returns A function that takes the text to compile and returns the compiled text.
   */
  linkTargeting = () => (text2) => {
    return text2.replace(DATAVIEW_LINK_TARGET_BLANK_REGEX, "");
  };
  stripAwayCodeFencesAndFrontmatter = () => (text2) => {
    let textToBeProcessed = text2;
    textToBeProcessed = textToBeProcessed.replace(EXCALIDRAW_REGEX, "");
    textToBeProcessed = textToBeProcessed.replace(CODEBLOCK_REGEX, "");
    textToBeProcessed = textToBeProcessed.replace(CODE_FENCE_REGEX, "");
    textToBeProcessed = textToBeProcessed.replace(FRONTMATTER_REGEX, "");
    return textToBeProcessed;
  };
  /**
   * Converts links in the text to full paths.
   * It looks for links in the form of [[link]] and converts them to full paths.
   * It also handles links to headers and blocks, and removes the file extension if it is a Markdown file.
   *
   * @param file - The file to compile the links for.
   * @returns A function that takes the text to compile and returns the compiled text.
   */
  convertLinksToFullPath = (file) => async (text2) => {
    let convertedText = text2;
    const textToBeProcessed = await this.stripAwayCodeFencesAndFrontmatter(file)(text2);
    const linkedFileRegex = /\[\[(.+?)\]\]/g;
    const linkedFileMatches = textToBeProcessed.match(linkedFileRegex);
    if (linkedFileMatches) {
      for (const linkMatch of linkedFileMatches) {
        try {
          const textInsideBrackets = linkMatch.substring(
            linkMatch.indexOf("[") + 2,
            linkMatch.lastIndexOf("]") - 1
          );
          let [linkedFileName, linkDisplayName] = textInsideBrackets.split("|");
          if (linkedFileName.endsWith("\\")) {
            linkedFileName = linkedFileName.substring(
              0,
              linkedFileName.length - 1
            );
          }
          linkDisplayName = linkDisplayName ? `\\|${linkDisplayName}` : "";
          let headerPath = "";
          if (linkedFileName.includes("#")) {
            const headerSplit = linkedFileName.split("#");
            linkedFileName = headerSplit[0];
            headerPath = headerSplit.length > 1 ? `#${headerSplit[1]}` : "";
          }
          const fullLinkedFilePath = (0, import_obsidian10.getLinkpath)(linkedFileName);
          const linkedFile = this.metadataCache.getFirstLinkpathDest(
            fullLinkedFilePath,
            file.getPath()
          );
          if (!linkedFile) {
            convertedText = convertedText.replace(
              linkMatch,
              `[[${linkedFileName}${headerPath}${linkDisplayName}]]`
            );
            continue;
          }
          if (linkedFile.extension === "md") {
            const extensionlessPath = linkedFile.path.substring(
              0,
              linkedFile.path.lastIndexOf(".")
            );
            convertedText = convertedText.replace(
              linkMatch,
              `[[${extensionlessPath}${headerPath}${linkDisplayName}]]`
            );
          }
        } catch (e) {
          console.log(e);
          continue;
        }
      }
    }
    return convertedText;
  };
  /**
   * Creates transcluded text by replacing transclusion links with the content of the linked files.
   * It recursively processes transclusions up to a depth of 4 to avoid infinite loops.
   * It also applies the vault path to the transcluded text.
   *
   * @param currentDepth - The current depth of recursion.
   * @returns A function that takes the file and returns a function that takes the text to compile.
   */
  createTranscludedText = (currentDepth) => (file) => async (text2) => {
    if (currentDepth >= 4) {
      return text2;
    }
    if (!this.settings.applyEmbeds) {
      return text2;
    }
    const { notes: publishedFiles } = await this.getFilesMarkedForPublishing();
    let transcludedText = text2;
    const transcludedRegex = /!\[\[(.+?)\]\]/g;
    const transclusionMatches = text2.match(transcludedRegex);
    for (const transclusionMatch of transclusionMatches ?? []) {
      try {
        const [transclusionFileNameInitial, _] = transclusionMatch.substring(
          transclusionMatch.indexOf("[") + 2,
          transclusionMatch.indexOf("]")
        ).split("|");
        const transclusionFileName = transclusionFileNameInitial.endsWith("\\") ? transclusionFileNameInitial.substring(
          0,
          transclusionFileNameInitial.length - 1
        ) : transclusionFileNameInitial;
        const transclusionFilePath = (0, import_obsidian10.getLinkpath)(transclusionFileName);
        const linkedFile = this.metadataCache.getFirstLinkpathDest(
          transclusionFilePath,
          file.getPath()
        );
        if (!linkedFile) {
          console.error(
            `can't find transcluded file ${transclusionFilePath}`
          );
          continue;
        }
        const publishLinkedFile = new PublishFile({
          file: linkedFile,
          compiler: this,
          metadataCache: this.metadataCache,
          vault: this.vault,
          settings: this.settings,
          datastore: this.datastore
        });
        if (linkedFile.name.endsWith(".excalidraw.md")) {
          continue;
        } else if (linkedFile.extension === "md") {
          let fileText = await publishLinkedFile.cachedRead();
          const metadata = publishLinkedFile.getMetadata();
          if (transclusionFileName.includes("#^")) {
            const refBlock = transclusionFileName.split("#^")[1];
            const blockInFile = publishLinkedFile.getBlock(refBlock);
            if (blockInFile) {
              fileText = fileText.split("\n").slice(
                blockInFile.position.start.line,
                blockInFile.position.end.line + 1
              ).join("\n").replace(`^${refBlock}`, "");
            }
          } else if (transclusionFileName.includes("#")) {
            const refHeader = transclusionFileName.split("#")[1];
            const headerSlug = (0, import_slugify2.default)(refHeader, {
              separator: "-",
              lowercase: false
            });
            const headerInFile = metadata?.headings?.find(
              (header) => (0, import_slugify2.default)(header.heading, {
                separator: "-",
                lowercase: false
              }) === headerSlug
            );
            if (headerInFile && metadata?.headings) {
              const headerPosition = metadata.headings.indexOf(headerInFile);
              const cutTo = metadata.headings.slice(headerPosition + 1).find(
                (header) => header.level <= headerInFile.level
              );
              if (cutTo) {
                const cutToLine = cutTo?.position?.start?.line;
                fileText = fileText.split("\n").slice(
                  headerInFile.position.start.line,
                  cutToLine
                ).join("\n");
              } else {
                fileText = fileText.split("\n").slice(headerInFile.position.start.line).join("\n");
              }
            }
          }
          fileText = fileText.replace(FRONTMATTER_REGEX, "");
          fileText = await this.applyVaultPath(publishLinkedFile)(
            fileText
          );
          fileText = fileText.replace(BLOCKREF_REGEX, "");
          const publishedFilesContainsLinkedFile = publishedFiles.find(
            (f) => f.getPath() == linkedFile.path
          );
          if (publishedFilesContainsLinkedFile) {
            const permalink = metadata?.frontmatter && metadata.frontmatter["permalink"];
            const quartzPathFull = permalink ? sanitizePermalink(permalink) : sanitizePermalink(
              generateUrlPath(
                getSyncerPathForNote(
                  linkedFile.path,
                  this.rewriteRule
                )
              )
            );
            let quartzPath = quartzPathFull.endsWith("/") ? quartzPathFull.slice(0, -1) : quartzPathFull;
            if (this.settings.vaultPath !== "/" && this.settings.vaultPath !== "") {
              quartzPath = quartzPath.replace(
                this.settings.vaultPath,
                ""
              );
            }
          }
          if (fileText.match(transcludedRegex)) {
            fileText = await this.createTranscludedText(
              currentDepth + 1
            )(publishLinkedFile)(fileText);
          }
          fileText = fileText.replace(
            /(^|[^$])\$\$($)/gm,
            // only match double dollar signs (block math)
            "$1$$$$$$$$$2"
            // adding two extra dollar signs
          );
          transcludedText = transcludedText.replace(
            transclusionMatch,
            fileText
          );
        }
      } catch (error) {
        console.error(error);
        continue;
      }
    }
    return transcludedText;
  };
  /**
   * Creates SVG
   * It looks for SVG transclusions in the text and replaces them with the content of the linked SVG files.
   * It supports both transcluded SVGs in the form of ![blob.svg] and ![blob.svg|size] and transcluded SVGs in the form of [blob.svg|size].
   *
   * @param file - The file to compile the SVGs for.
   * @returns A function that takes the text to compile and returns the compiled text.
   */
  createSvgEmbeds = (file) => async (text2) => {
    function setWidth(svgText, size) {
      const parser = new DOMParser();
      const svgDoc = parser.parseFromString(svgText, "image/svg+xml");
      const svgElement = svgDoc.getElementsByTagName("svg")[0];
      svgElement.setAttribute("width", size);
      fixSvgForXmlSerializer(svgElement);
      const svgSerializer = new XMLSerializer();
      return svgSerializer.serializeToString(svgDoc);
    }
    const transcludedSvgs = text2.match(TRANSCLUDED_SVG_REGEX);
    if (transcludedSvgs) {
      for (const svg of transcludedSvgs) {
        try {
          const [blobName, size] = svg.substring(svg.indexOf("[") + 2, svg.indexOf("]")).split("|");
          const blobPath = (0, import_obsidian10.getLinkpath)(blobName);
          const linkedFile = this.metadataCache.getFirstLinkpathDest(
            blobPath,
            file.getPath()
          );
          if (!linkedFile) {
            continue;
          }
          let svgText = await this.vault.read(linkedFile);
          if (svgText && size) {
            svgText = setWidth(svgText, size);
          }
          if (svgText) {
            svgText = svgText.replace(/[\t\n\r]/g, "");
          }
          text2 = text2.replace(svg, svgText);
        } catch {
          continue;
        }
      }
    }
    const linkedSvgRegex = /!\[(.*?)\]\((.*?)(\.(svg))\)/g;
    const linkedSvgMatches = text2.match(linkedSvgRegex);
    if (linkedSvgMatches) {
      for (const svg of linkedSvgMatches) {
        try {
          const [_blobName, size] = svg.substring(svg.indexOf("[") + 2, svg.indexOf("]")).split("|");
          const pathStart = svg.lastIndexOf("(") + 1;
          const pathEnd = svg.lastIndexOf(")");
          const blobPath = svg.substring(pathStart, pathEnd);
          if (blobPath.startsWith("http")) {
            continue;
          }
          const linkedFile = this.metadataCache.getFirstLinkpathDest(
            blobPath,
            file.getPath()
          );
          if (!linkedFile) {
            continue;
          }
          let svgText = await this.vault.read(linkedFile);
          if (svgText && size) {
            svgText = setWidth(svgText, size);
          }
          text2 = text2.replace(svg, svgText);
        } catch {
          continue;
        }
      }
    }
    return text2;
  };
  /**
   * Extracts blob links from the file.
   * It looks for transcluded blobs in the form of ![[blob.png]] and ![](blob.png) and returns the paths of the linked files.
   *
   * @param file - The file to extract the blob links from.
   * @returns A promise that resolves to an array of asset paths.
   */
  extractBlobLinks = async (file) => {
    const text2 = await file.cachedRead();
    const assets = [];
    const transcludedBlobMatches = text2.match(TRANSCLUDED_FILE_REGEX);
    if (transcludedBlobMatches) {
      for (let i = 0; i < transcludedBlobMatches.length; i++) {
        try {
          const blobMatch = transcludedBlobMatches[i];
          const [blobName, _] = blobMatch.substring(
            blobMatch.indexOf("[") + 2,
            blobMatch.indexOf("]")
          ).split("|");
          let previous;
          let actualBlobName = blobName;
          do {
            previous = actualBlobName;
            actualBlobName = actualBlobName.replace(/\.\.\//g, "");
          } while (actualBlobName !== previous);
          const actualBlobPath = actualBlobName;
          const blobPath = (0, import_obsidian10.getLinkpath)(actualBlobPath);
          const linkedFile = this.metadataCache.getFirstLinkpathDest(
            blobPath,
            file.getPath()
          );
          if (!linkedFile) {
            continue;
          }
          assets.push(linkedFile.path);
        } catch (_error) {
          continue;
        }
      }
    }
    const blobMatches = text2.match(FILE_REGEX);
    if (blobMatches) {
      for (let i = 0; i < blobMatches.length; i++) {
        try {
          const blobMatch = blobMatches[i];
          const pathStart = blobMatch.lastIndexOf("(") + 1;
          const pathEnd = blobMatch.lastIndexOf(")");
          let blobPath = blobMatch.substring(pathStart, pathEnd);
          if (blobPath.startsWith("http")) {
            continue;
          }
          let previous;
          do {
            previous = blobPath;
            blobPath = blobPath.replace(/\.\.\//g, "");
          } while (blobPath !== previous);
          const actualBlobPath = blobPath;
          const decodedBlobPath = decodeURI(actualBlobPath);
          const linkedFile = this.metadataCache.getFirstLinkpathDest(
            decodedBlobPath,
            file.getPath()
          );
          if (!linkedFile) {
            continue;
          }
          assets.push(linkedFile.path);
        } catch {
          continue;
        }
      }
    }
    return assets;
  };
  /**
   * Converts file links in the text to their content.
   * It looks for transcluded blobs in the form of ![[blob.png]] and ![](blob.png) and replaces them with the content of the linked files.
   *
   * @param file - The file to compile the links for.
   * @returns A function that takes the text to compile and returns a tuple containing the compiled text and the assets.
   * @throws If the file is not found, it continues to the next match.
   */
  convertFileLinks = (file) => async (text2) => {
    const filePath = file.getPath();
    const assets = [];
    let blobText = text2;
    const transcludedBlobMatches = text2.match(TRANSCLUDED_FILE_REGEX);
    if (transcludedBlobMatches) {
      for (let i = 0; i < transcludedBlobMatches.length; i++) {
        try {
          const blobMatch = transcludedBlobMatches[i];
          const [blobName, ...metaDataAndSize] = blobMatch.substring(
            blobMatch.indexOf("[") + 2,
            blobMatch.indexOf("]")
          ).split("|");
          const lastValue = metaDataAndSize[metaDataAndSize.length - 1];
          const hasSeveralValues = metaDataAndSize.length > 0;
          const lastValueIsSize = hasSeveralValues && !isNaN(parseInt(lastValue));
          const lastValueIsMetaData = !lastValueIsSize && hasSeveralValues;
          const size = lastValueIsSize ? lastValue : null;
          let metaData = "";
          const metaDataIsMiddleValues = metaDataAndSize.length > 1;
          if (metaDataIsMiddleValues) {
            metaData = metaDataAndSize.slice(0, metaDataAndSize.length - 1).join(" ");
          }
          if (lastValueIsMetaData) {
            metaData = `${lastValue}`;
          }
          let blobPath = (0, import_obsidian10.getLinkpath)(blobName);
          const linkedFile = this.metadataCache.getFirstLinkpathDest(
            blobPath,
            filePath
          );
          if (!linkedFile) {
            continue;
          }
          const blob = await this.vault.readBinary(linkedFile);
          const blobBase64 = (0, import_obsidian10.arrayBufferToBase64)(blob);
          blobPath = this.metadataCache.fileToLinktext(
            linkedFile,
            this.settings.vaultPath
          );
          const blobFullPath = this.metadataCache.getFirstLinkpathDest(
            linkedFile.path,
            this.settings.vaultPath
          )?.path ?? blobPath;
          let name = "";
          if (metaData && size) {
            name = `|${metaData}|${size}`;
          } else if (size) {
            name = `|${size}`;
          } else if (metaData && metaData !== "") {
            name = `|${metaData}`;
          } else {
            name = "";
          }
          const blobMarkdown = `![[${blobFullPath}${name}]]`;
          assets.push({
            path: blobFullPath,
            content: blobBase64
          });
          blobText = blobText.replace(blobMatch, blobMarkdown);
        } catch (_error) {
          continue;
        }
      }
    }
    const blobMatches = text2.match(FILE_REGEX);
    if (blobMatches) {
      for (let i = 0; i < blobMatches.length; i++) {
        try {
          const blobMatch = blobMatches[i];
          const nameStart = blobMatch.indexOf("[") + 1;
          const nameEnd = blobMatch.indexOf("]");
          const blobName = blobMatch.substring(
            nameStart,
            nameEnd
          );
          const pathStart = blobMatch.lastIndexOf("(") + 1;
          const pathEnd = blobMatch.lastIndexOf(")");
          let blobPath = blobMatch.substring(pathStart, pathEnd);
          if (blobPath.startsWith("http")) {
            continue;
          }
          const decodedBlobPath = decodeURI(blobPath);
          const linkedFile = this.metadataCache.getFirstLinkpathDest(
            decodedBlobPath,
            filePath
          );
          if (!linkedFile) {
            continue;
          }
          const blob = await this.vault.readBinary(linkedFile);
          const blobBase64 = (0, import_obsidian10.arrayBufferToBase64)(blob);
          blobPath = this.metadataCache.fileToLinktext(
            linkedFile,
            this.settings.vaultPath
          );
          const blobFullPath = this.metadataCache.getFirstLinkpathDest(
            linkedFile.path,
            this.settings.vaultPath
          )?.path ?? blobPath;
          const blobMarkdown = `![${blobName}](${blobFullPath})`;
          assets.push({
            path: blobFullPath,
            content: blobBase64
          });
          blobText = blobText.replace(blobMatch, blobMarkdown);
        } catch {
          continue;
        }
      }
    }
    blobText = await this.applyVaultPath(file)(blobText);
    return [blobText, assets];
  };
};

// src/repositoryConnection/RepositoryConnection.ts
init_esbuild_buffer_shim();
var import_isomorphic_git = __toESM(require_isomorphic_git());
var import_lightning_fs = __toESM(require_src());
var import_obsidian11 = require("obsidian");
var import_js_logger8 = __toESM(require_logger());
var logger = import_js_logger8.default.get("repository-connection");
async function collectBody(body) {
  if (!body) return void 0;
  const chunks = [];
  for await (const chunk of body) {
    chunks.push(chunk);
  }
  const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
  const result = new Uint8Array(totalLength);
  let offset2 = 0;
  for (const chunk of chunks) {
    result.set(chunk, offset2);
    offset2 += chunk.length;
  }
  return result;
}
var obsidianHttpClient = {
  async request(config) {
    const { url, method = "GET", headers = {}, body } = config;
    try {
      const bodyData = await collectBody(body);
      const response = await (0, import_obsidian11.requestUrl)({
        url,
        method,
        headers,
        body: bodyData ? bodyData.buffer : void 0,
        throw: false
      });
      const responseHeaders = {};
      if (response.headers) {
        for (const [key, value] of Object.entries(response.headers)) {
          responseHeaders[key.toLowerCase()] = value;
        }
      }
      const responseBody = new Uint8Array(response.arrayBuffer);
      async function* bodyIterator() {
        yield responseBody;
      }
      return {
        url,
        method,
        headers: responseHeaders,
        body: bodyIterator(),
        statusCode: response.status,
        statusMessage: response.status >= 200 && response.status < 300 ? "OK" : "Error"
      };
    } catch (error) {
      logger.error("HTTP request failed", error);
      throw error;
    }
  }
};
var RepositoryConnection = class {
  remoteUrl;
  branch;
  corsProxyUrl;
  auth;
  fs = null;
  dir;
  contentFolder;
  vaultPath;
  initialized = false;
  constructor({
    gitSettings,
    contentFolder,
    vaultPath
  }) {
    this.remoteUrl = gitSettings.remoteUrl;
    this.branch = gitSettings.branch || "main";
    this.corsProxyUrl = gitSettings.corsProxyUrl || void 0;
    this.auth = gitSettings.auth;
    this.contentFolder = contentFolder;
    this.vaultPath = vaultPath;
    this.dir = "/repo";
  }
  getFs() {
    if (!this.fs) {
      try {
        const fsName = this.getFsName();
        this.fs = new import_lightning_fs.default(fsName);
      } catch (error) {
        logger.error("Failed to initialize LightningFS", error);
        throw new Error(
          "Failed to initialize filesystem. IndexedDB may not be available on this platform."
        );
      }
    }
    return this.fs;
  }
  getFsName() {
    const urlHash = this.hashString(this.remoteUrl + this.branch);
    return `quartz-syncer-${urlHash}`;
  }
  hashString(str) {
    let hash = 0;
    for (let i = 0; i < str.length; i++) {
      const char = str.charCodeAt(i);
      hash = (hash << 5) - hash + char;
      hash = hash & hash;
    }
    return Math.abs(hash).toString(36);
  }
  getOnAuth() {
    return () => {
      if (this.auth.type === "none") {
        return void 0;
      }
      if (this.auth.type === "bearer") {
        return {
          headers: {
            Authorization: `Bearer ${this.auth.secret}`
          }
        };
      }
      return {
        username: this.auth.username || "",
        password: this.auth.secret || ""
      };
    };
  }
  getGitConfig() {
    const config = {
      fs: this.getFs(),
      http: obsidianHttpClient,
      dir: this.dir
    };
    if (this.corsProxyUrl) {
      config.corsProxy = this.corsProxyUrl;
    }
    if (this.auth.type !== "none") {
      config.onAuth = this.getOnAuth();
    }
    return config;
  }
  getRepositoryName() {
    try {
      const url = new URL(this.remoteUrl);
      return url.pathname.replace(/^\//, "").replace(/\.git$/, "");
    } catch {
      return this.remoteUrl;
    }
  }
  getRepositoryPath(path) {
    const repositoryPath = path.startsWith(this.contentFolder) ? path.replace(this.contentFolder, "") : path;
    return repositoryPath.startsWith("/") ? repositoryPath.slice(1) : repositoryPath;
  }
  getVaultPath(path) {
    path = (0, import_obsidian11.normalizePath)(path);
    const vaultPath = path.startsWith(this.vaultPath) ? path.replace(this.vaultPath, "") : path;
    return vaultPath.startsWith("/") ? vaultPath.slice(1) : vaultPath;
  }
  setRepositoryPath(path) {
    path = (0, import_obsidian11.normalizePath)(path);
    const repositoryPath = path.startsWith(this.contentFolder) ? path : `${this.contentFolder}/${path}`;
    return repositoryPath.startsWith("/") ? repositoryPath.slice(1) : repositoryPath;
  }
  setVaultPath(path) {
    const separator = path.startsWith("/") ? "" : "/";
    const vaultPath = path.startsWith(this.vaultPath) ? path : `${this.vaultPath}${separator}${path}`;
    return vaultPath.startsWith("/") ? vaultPath.slice(1) : vaultPath;
  }
  repositoryToVaultPath(path) {
    return this.setVaultPath(this.getRepositoryPath(path));
  }
  repositoryToRepositoryPath(path) {
    return this.setRepositoryPath(this.getVaultPath(path));
  }
  async checkExistingRepo() {
    try {
      await this.getFs().promises.stat(this.dir);
      const remotes = await import_isomorphic_git.default.listRemotes({ ...this.getGitConfig() });
      return remotes.length > 0;
    } catch {
      return false;
    }
  }
  async createDirIfNotExists(path) {
    try {
      await this.getFs().promises.mkdir(path);
    } catch {
      logger.debug(`Directory ${path} already exists`);
    }
  }
  async ensureRepoInitialized() {
    if (this.initialized) {
      return;
    }
    const isExistingRepo = await this.checkExistingRepo();
    if (isExistingRepo) {
      this.initialized = true;
      return;
    }
    logger.info(`Cloning repository ${this.getRepositoryName()}`);
    await this.createDirIfNotExists(this.dir);
    try {
      await import_isomorphic_git.default.clone({
        ...this.getGitConfig(),
        url: this.remoteUrl,
        ref: this.branch,
        singleBranch: true,
        depth: 1,
        noCheckout: false
      });
      this.initialized = true;
    } catch (error) {
      logger.error("Failed to clone repository", error);
      throw new Error(
        `Could not clone repository ${this.getRepositoryName()}: ${error}`
      );
    }
  }
  async getContent(_branch) {
    try {
      await this.ensureRepoInitialized();
      await import_isomorphic_git.default.fetch({
        ...this.getGitConfig(),
        url: this.remoteUrl,
        ref: this.branch,
        singleBranch: true
      });
      const commitOid = await import_isomorphic_git.default.resolveRef({
        ...this.getGitConfig(),
        ref: `origin/${this.branch}`
      });
      const { commit } = await import_isomorphic_git.default.readCommit({
        ...this.getGitConfig(),
        oid: commitOid
      });
      const treeEntries = [];
      const readTreeRecursive = async (treeOid, prefix = "") => {
        const { tree } = await import_isomorphic_git.default.readTree({
          ...this.getGitConfig(),
          oid: treeOid
        });
        for (const entry of tree) {
          const fullPath = prefix ? `${prefix}/${entry.path}` : entry.path;
          treeEntries.push({
            path: fullPath,
            oid: entry.oid,
            type: entry.type
          });
          if (entry.type === "tree") {
            await readTreeRecursive(entry.oid, fullPath);
          }
        }
      };
      await readTreeRecursive(commit.tree);
      return {
        tree: treeEntries,
        sha: commitOid,
        truncated: false
      };
    } catch (error) {
      logger.error("Could not get repository content", error);
      throw new Error(
        `Could not get files from repository ${this.getRepositoryName()}`
      );
    }
  }
  async getFile(path, _branch) {
    path = this.setRepositoryPath(
      this.getVaultPath(this.getRepositoryPath(path))
    );
    logger.info(
      `Getting file ${path} from repository ${this.getRepositoryName()}`
    );
    try {
      await this.ensureRepoInitialized();
      const commitOid = await import_isomorphic_git.default.resolveRef({
        ...this.getGitConfig(),
        ref: `origin/${this.branch}`
      });
      const { blob, oid } = await import_isomorphic_git.default.readBlob({
        ...this.getGitConfig(),
        oid: commitOid,
        filepath: path
      });
      const content = Buffer.from(blob).toString("base64");
      return {
        content,
        sha: oid,
        path,
        type: "file"
      };
    } catch (error) {
      logger.error(`Could not get file ${path}`, error);
      throw new Error(
        `Could not get file ${path} from repository ${this.getRepositoryName()}`
      );
    }
  }
  /**
   * Gets a file from the repository without adding the content folder prefix.
   * Use this for files outside the content folder (e.g., quartz/styles/custom.scss).
   */
  async getRawFile(path) {
    logger.info(
      `Getting raw file ${path} from repository ${this.getRepositoryName()}`
    );
    try {
      await this.ensureRepoInitialized();
      const commitOid = await import_isomorphic_git.default.resolveRef({
        ...this.getGitConfig(),
        ref: `origin/${this.branch}`
      });
      const { blob, oid } = await import_isomorphic_git.default.readBlob({
        ...this.getGitConfig(),
        oid: commitOid,
        filepath: path
      });
      const content = Buffer.from(blob).toString("base64");
      return {
        content,
        sha: oid,
        path,
        type: "file"
      };
    } catch (error) {
      logger.error(`Could not get raw file ${path}`, error);
      throw new Error(
        `Could not get file ${path} from repository ${this.getRepositoryName()}`
      );
    }
  }
  async getLatestCommit() {
    try {
      await this.ensureRepoInitialized();
      await import_isomorphic_git.default.fetch({
        ...this.getGitConfig(),
        url: this.remoteUrl,
        ref: this.branch,
        singleBranch: true,
        depth: 1
      });
      const commitOid = await import_isomorphic_git.default.resolveRef({
        ...this.getGitConfig(),
        ref: `origin/${this.branch}`
      });
      const { commit } = await import_isomorphic_git.default.readCommit({
        ...this.getGitConfig(),
        oid: commitOid
      });
      return {
        sha: commitOid,
        commit: {
          tree: {
            sha: commit.tree
          }
        }
      };
    } catch (error) {
      logger.error("Could not get latest commit", error);
      return void 0;
    }
  }
  async deleteFiles(filePaths) {
    if (filePaths.length === 0) return;
    try {
      await this.ensureRepoInitialized();
      await import_isomorphic_git.default.fetch({
        ...this.getGitConfig(),
        url: this.remoteUrl,
        ref: this.branch,
        singleBranch: true
      });
      const remoteCommit = await import_isomorphic_git.default.resolveRef({
        ...this.getGitConfig(),
        ref: `origin/${this.branch}`
      });
      await import_isomorphic_git.default.checkout({
        ...this.getGitConfig(),
        ref: remoteCommit,
        force: true
      });
      await import_isomorphic_git.default.branch({
        ...this.getGitConfig(),
        ref: this.branch,
        object: remoteCommit,
        force: true
      });
      await import_isomorphic_git.default.checkout({
        ...this.getGitConfig(),
        ref: this.branch
      });
      const normalizeFilePath = (path) => {
        let previous;
        do {
          previous = path;
          path = path.replace(/\.\.\//g, "");
        } while (path !== previous);
        path = this.getVaultPath(path);
        return path.startsWith("/") ? `${this.contentFolder}${path}` : `${this.contentFolder}/${path}`;
      };
      for (const filePath of filePaths) {
        const normalizedPath = normalizeFilePath(filePath);
        const fullPath = `${this.dir}/${normalizedPath}`;
        try {
          await this.getFs().promises.unlink(fullPath);
          await import_isomorphic_git.default.remove({
            ...this.getGitConfig(),
            filepath: normalizedPath
          });
        } catch (error) {
          logger.warn(
            `Could not delete file ${normalizedPath}`,
            error
          );
        }
      }
      await import_isomorphic_git.default.commit({
        ...this.getGitConfig(),
        message: "Deleted multiple files",
        author: {
          name: "Quartz Syncer",
          email: "quartz-syncer@obsidian.md"
        }
      });
      await import_isomorphic_git.default.push({
        ...this.getGitConfig(),
        url: this.remoteUrl,
        remote: "origin",
        ref: this.branch
      });
    } catch (error) {
      logger.error("Failed to delete files", error);
      throw error;
    }
  }
  async updateFiles(files, rawFiles, rawFilesToDelete) {
    const hasContent = files.length > 0;
    const hasRawFiles = rawFiles && rawFiles.size > 0;
    const hasRawFilesToDelete = rawFilesToDelete && rawFilesToDelete.length > 0;
    if (!hasContent && !hasRawFiles && !hasRawFilesToDelete) return;
    try {
      await this.ensureRepoInitialized();
      await import_isomorphic_git.default.fetch({
        ...this.getGitConfig(),
        url: this.remoteUrl,
        ref: this.branch,
        singleBranch: true
      });
      const remoteCommit = await import_isomorphic_git.default.resolveRef({
        ...this.getGitConfig(),
        ref: `origin/${this.branch}`
      });
      await import_isomorphic_git.default.checkout({
        ...this.getGitConfig(),
        ref: remoteCommit,
        force: true
      });
      await import_isomorphic_git.default.branch({
        ...this.getGitConfig(),
        ref: this.branch,
        object: remoteCommit,
        force: true
      });
      await import_isomorphic_git.default.checkout({
        ...this.getGitConfig(),
        ref: this.branch
      });
      const normalizeFilePath = (path) => {
        let previous;
        do {
          previous = path;
          path = path.replace(/\.\.\//g, "");
        } while (path !== previous);
        path = this.getVaultPath(path);
        return path.startsWith("/") ? `${this.contentFolder}${path}` : `${this.contentFolder}/${path}`;
      };
      const ensureDirectory = async (filePath) => {
        const parts = filePath.split("/");
        parts.pop();
        let currentPath = this.dir;
        for (const part of parts) {
          if (!part) continue;
          currentPath = `${currentPath}/${part}`;
          try {
            await this.getFs().promises.mkdir(currentPath);
          } catch {
            logger.debug(`Directory ${currentPath} already exists`);
          }
        }
      };
      for (const file of files) {
        const [text2, metadata] = file.compiledFile;
        const normalizedPath = normalizeFilePath(file.getPath());
        const fullPath = `${this.dir}/${normalizedPath}`;
        await ensureDirectory(normalizedPath);
        await this.getFs().promises.writeFile(fullPath, text2);
        await import_isomorphic_git.default.add({
          ...this.getGitConfig(),
          filepath: normalizedPath
        });
        for (const asset of metadata.blobs) {
          const assetPath = normalizeFilePath(asset.path);
          const assetFullPath = `${this.dir}/${assetPath}`;
          await ensureDirectory(assetPath);
          const binaryContent = Uint8Array.from(
            atob(asset.content),
            (c) => c.charCodeAt(0)
          );
          await this.getFs().promises.writeFile(
            assetFullPath,
            binaryContent
          );
          await import_isomorphic_git.default.add({
            ...this.getGitConfig(),
            filepath: assetPath
          });
        }
      }
      if (rawFiles && rawFiles.size > 0) {
        await this.stageRawFiles(rawFiles);
      }
      if (rawFilesToDelete && rawFilesToDelete.length > 0) {
        await this.stageRawFileDeletions(rawFilesToDelete);
      }
      await import_isomorphic_git.default.commit({
        ...this.getGitConfig(),
        message: "Published multiple files",
        author: {
          name: "Quartz Syncer",
          email: "quartz-syncer@obsidian.md"
        }
      });
      await import_isomorphic_git.default.push({
        ...this.getGitConfig(),
        url: this.remoteUrl,
        remote: "origin",
        ref: this.branch
      });
    } catch (error) {
      logger.error("Failed to update files", error);
      throw error;
    }
  }
  async stageRawFiles(files) {
    if (files.size === 0) return;
    const ensureDirectory = async (filePath) => {
      const parts = filePath.split("/");
      parts.pop();
      let currentPath = this.dir;
      for (const part of parts) {
        if (!part) continue;
        currentPath = `${currentPath}/${part}`;
        try {
          await this.getFs().promises.mkdir(currentPath);
        } catch {
          logger.debug(`Directory ${currentPath} already exists`);
        }
      }
    };
    for (const [filepath, content] of files) {
      const fullPath = `${this.dir}/${filepath}`;
      await ensureDirectory(filepath);
      await this.getFs().promises.writeFile(fullPath, content);
      await import_isomorphic_git.default.add({
        ...this.getGitConfig(),
        filepath
      });
    }
  }
  async stageRawFileDeletions(filePaths) {
    if (filePaths.length === 0) return;
    for (const filepath of filePaths) {
      const fullPath = `${this.dir}/${filepath}`;
      try {
        await this.getFs().promises.unlink(fullPath);
        await import_isomorphic_git.default.remove({
          ...this.getGitConfig(),
          filepath
        });
      } catch (error) {
        logger.debug(`Could not delete file ${filepath}`, error);
      }
    }
  }
  async writeRawFiles(files) {
    if (files.size === 0) return;
    try {
      await this.ensureRepoInitialized();
      await import_isomorphic_git.default.fetch({
        ...this.getGitConfig(),
        url: this.remoteUrl,
        ref: this.branch,
        singleBranch: true
      });
      const remoteCommit = await import_isomorphic_git.default.resolveRef({
        ...this.getGitConfig(),
        ref: `origin/${this.branch}`
      });
      await import_isomorphic_git.default.checkout({
        ...this.getGitConfig(),
        ref: remoteCommit,
        force: true
      });
      await import_isomorphic_git.default.branch({
        ...this.getGitConfig(),
        ref: this.branch,
        object: remoteCommit,
        force: true
      });
      await import_isomorphic_git.default.checkout({
        ...this.getGitConfig(),
        ref: this.branch
      });
      await this.stageRawFiles(files);
      await import_isomorphic_git.default.commit({
        ...this.getGitConfig(),
        message: "Updated integration styles",
        author: {
          name: "Quartz Syncer",
          email: "quartz-syncer@obsidian.md"
        }
      });
      await import_isomorphic_git.default.push({
        ...this.getGitConfig(),
        url: this.remoteUrl,
        remote: "origin",
        ref: this.branch
      });
    } catch (error) {
      logger.error("Failed to write raw files", error);
      throw error;
    }
  }
  async testConnection() {
    try {
      await import_isomorphic_git.default.getRemoteInfo({
        http: obsidianHttpClient,
        url: this.remoteUrl,
        corsProxy: this.corsProxyUrl,
        onAuth: this.getOnAuth()
      });
      return true;
    } catch (error) {
      logger.error("Connection test failed", error);
      return false;
    }
  }
  async clearLocalCache() {
    const fsName = this.getFsName();
    try {
      if (typeof indexedDB !== "undefined") {
        indexedDB.deleteDatabase(fsName);
      }
      this.fs = null;
      this.initialized = false;
      logger.info("Local git cache cleared");
    } catch (error) {
      logger.error("Failed to clear local cache", error);
    }
  }
  static async fetchRemoteBranches(remoteUrl, auth, corsProxyUrl) {
    const getOnAuth = () => {
      if (auth.type === "none") {
        return void 0;
      }
      if (auth.type === "bearer") {
        return () => ({
          headers: {
            Authorization: `Bearer ${auth.secret}`
          }
        });
      }
      return () => ({
        username: auth.username || "",
        password: auth.secret || ""
      });
    };
    try {
      const refs = await import_isomorphic_git.default.listServerRefs({
        http: obsidianHttpClient,
        url: remoteUrl,
        corsProxy: corsProxyUrl,
        onAuth: getOnAuth(),
        prefix: "refs/heads/",
        symrefs: true
      });
      const branches = refs.filter((ref) => ref.ref.startsWith("refs/heads/")).map((ref) => ref.ref.replace("refs/heads/", ""));
      let defaultBranch = null;
      const headRef = refs.find((ref) => ref.ref === "HEAD");
      if (headRef?.target) {
        defaultBranch = headRef.target.replace("refs/heads/", "");
      }
      return { branches, defaultBranch };
    } catch (error) {
      logger.error("Failed to fetch remote branches", error);
      return { branches: [], defaultBranch: null };
    }
  }
};

// src/publisher/Publisher.ts
var import_js_logger9 = __toESM(require_logger());
var Publisher = class {
  app;
  plugin;
  vault;
  metadataCache;
  compiler;
  settings;
  rewriteRule;
  vaultPath;
  datastore;
  constructor(app2, plugin, vault, metadataCache, settings, datastore) {
    this.app = app2;
    this.plugin = plugin;
    this.vault = vault;
    this.metadataCache = metadataCache;
    this.settings = settings;
    this.rewriteRule = getRewriteRules(settings.vaultPath);
    this.vaultPath = settings.vaultPath;
    this.datastore = datastore;
    this.compiler = new SyncerPageCompiler(
      app2,
      vault,
      settings,
      metadataCache,
      datastore,
      () => this.getFilesMarkedForPublishing()
    );
  }
  /**
   * Checks if the file should be published based on its frontmatter.
   *
   * @param file - The file to check.
   * @returns true if the file should be published, false otherwise.
   */
  shouldPublish(file) {
    const frontMatter = this.metadataCache.getCache(file.path)?.frontmatter;
    return hasPublishFlag(
      this.settings.publishFrontmatterKey,
      frontMatter,
      this.settings.allNotesPublishableByDefault
    );
  }
  /**
   * Gets the files that are marked for publishing.
   *
   * @returns A promise that resolves to an object containing notes and blobs to be published.
   */
  async getFilesMarkedForPublishing() {
    const vaultIsRoot = this.settings.vaultPath === "/";
    const files = this.vault.getMarkdownFiles().filter(
      (file) => vaultIsRoot || file.path.startsWith(this.settings.vaultPath)
    );
    const notesToPublish = [];
    const blobsToPublish = /* @__PURE__ */ new Set();
    for (const file of files) {
      try {
        if (this.shouldPublish(file)) {
          const publishFile = new PublishFile({
            file,
            compiler: this.compiler,
            metadataCache: this.metadataCache,
            vault: this.vault,
            settings: this.settings,
            datastore: this.datastore
          });
          notesToPublish.push(publishFile);
          const blobs = await publishFile.getBlobLinks();
          blobs.forEach((i) => blobsToPublish.add(i));
        }
      } catch (e) {
        import_js_logger9.default.error(e);
      }
    }
    return {
      notes: notesToPublish.sort((a, b) => a.compare(b)),
      blobs: Array.from(blobsToPublish)
    };
  }
  /**
   * Deletes a batch of files from the repository.
   *
   * @param filePaths - An array of file paths to delete.
   * @returns A promise that resolves to true if the deletion was successful, false otherwise.
   */
  async deleteBatch(filePaths) {
    if (filePaths.length === 0) {
      return true;
    }
    try {
      const userQuartzConnection = new RepositoryConnection({
        gitSettings: this.plugin.getGitSettingsWithSecret(),
        contentFolder: this.settings.contentFolder,
        vaultPath: this.settings.vaultPath
      });
      await userQuartzConnection.deleteFiles(filePaths);
      if (this.settings.useCache) {
        for (const filePath of filePaths) {
          await this.datastore.dropFile(filePath);
        }
      }
      return true;
    } catch (error) {
      console.error(error);
      return false;
    }
  }
  async publishBatch(files) {
    const filesToPublish = files.filter(
      (f) => isPublishFrontmatterValid(
        this.settings.publishFrontmatterKey,
        f.frontmatter,
        this.settings.allNotesPublishableByDefault
      )
    );
    if (filesToPublish.length === 0) {
      return true;
    }
    try {
      const userQuartzConnection = new RepositoryConnection({
        gitSettings: this.plugin.getGitSettingsWithSecret(),
        contentFolder: this.settings.contentFolder,
        vaultPath: this.settings.vaultPath
      });
      const assetSyncer = new AssetSyncer(this.settings);
      const assetResult = await assetSyncer.collectAssets(userQuartzConnection);
      await userQuartzConnection.updateFiles(
        filesToPublish,
        assetResult.filesToStage,
        assetResult.filesToDelete
      );
      if (this.settings.useCache) {
        for (const file of filesToPublish) {
          const data = await this.datastore.loadFile(file.file.path);
          if (data && data.localData) {
            await this.datastore.storeRemoteFile(
              file.file.path,
              file.file.stat.mtime,
              data.localData
            );
          }
        }
      }
      return true;
    } catch (error) {
      console.error(error);
      return false;
    }
  }
};

// src/views/PublicationCenter/PublicationCenter.ts
init_esbuild_buffer_shim();
var import_obsidian15 = require("obsidian");

// src/views/PublicationCenter/PublicationCenter.svelte
init_esbuild_buffer_shim();

// node_modules/svelte/src/runtime/internal/index.js
init_esbuild_buffer_shim();

// node_modules/svelte/src/runtime/internal/animations.js
init_esbuild_buffer_shim();

// node_modules/svelte/src/runtime/internal/utils.js
init_esbuild_buffer_shim();
function noop() {
}
function run(fn) {
  return fn();
}
function blank_object() {
  return /* @__PURE__ */ Object.create(null);
}
function run_all(fns) {
  fns.forEach(run);
}
function is_function(thing) {
  return typeof thing === "function";
}
function safe_not_equal(a, b) {
  return a != a ? b == b : a !== b || a && typeof a === "object" || typeof a === "function";
}
function is_empty(obj) {
  return Object.keys(obj).length === 0;
}
function action_destroyer(action_result) {
  return action_result && is_function(action_result.destroy) ? action_result.destroy : noop;
}

// node_modules/svelte/src/runtime/internal/environment.js
init_esbuild_buffer_shim();

// node_modules/svelte/src/runtime/internal/loop.js
init_esbuild_buffer_shim();

// node_modules/svelte/src/runtime/internal/style_manager.js
init_esbuild_buffer_shim();

// node_modules/svelte/src/runtime/internal/dom.js
init_esbuild_buffer_shim();

// node_modules/svelte/src/runtime/internal/ResizeObserverSingleton.js
init_esbuild_buffer_shim();

// node_modules/svelte/src/runtime/internal/globals.js
init_esbuild_buffer_shim();
var globals = typeof window !== "undefined" ? window : typeof globalThis !== "undefined" ? globalThis : (
  // @ts-ignore Node typings have this
  globalThis
);

// node_modules/svelte/src/runtime/internal/ResizeObserverSingleton.js
var ResizeObserverSingleton = class _ResizeObserverSingleton {
  /**
   * @private
   * @readonly
   * @type {WeakMap<Element, import('./private.js').Listener>}
   */
  _listeners = "WeakMap" in globals ? /* @__PURE__ */ new WeakMap() : void 0;
  /**
   * @private
   * @type {ResizeObserver}
   */
  _observer = void 0;
  /** @type {ResizeObserverOptions} */
  options;
  /** @param {ResizeObserverOptions} options */
  constructor(options) {
    this.options = options;
  }
  /**
   * @param {Element} element
   * @param {import('./private.js').Listener} listener
   * @returns {() => void}
   */
  observe(element2, listener) {
    this._listeners.set(element2, listener);
    this._getObserver().observe(element2, this.options);
    return () => {
      this._listeners.delete(element2);
      this._observer.unobserve(element2);
    };
  }
  /**
   * @private
   */
  _getObserver() {
    return this._observer ?? (this._observer = new ResizeObserver((entries) => {
      for (const entry of entries) {
        _ResizeObserverSingleton.entries.set(entry.target, entry);
        this._listeners.get(entry.target)?.(entry);
      }
    }));
  }
};
ResizeObserverSingleton.entries = "WeakMap" in globals ? /* @__PURE__ */ new WeakMap() : void 0;

// node_modules/svelte/src/runtime/internal/dom.js
var is_hydrating = false;
function start_hydrating() {
  is_hydrating = true;
}
function end_hydrating() {
  is_hydrating = false;
}
function append(target, node) {
  target.appendChild(node);
}
function append_styles(target, style_sheet_id, styles) {
  const append_styles_to = get_root_for_style(target);
  if (!append_styles_to.getElementById(style_sheet_id)) {
    const style = element("style");
    style.id = style_sheet_id;
    style.textContent = styles;
    append_stylesheet(append_styles_to, style);
  }
}
function get_root_for_style(node) {
  if (!node) return document;
  const root = node.getRootNode ? node.getRootNode() : node.ownerDocument;
  if (root && /** @type {ShadowRoot} */
  root.host) {
    return (
      /** @type {ShadowRoot} */
      root
    );
  }
  return node.ownerDocument;
}
function append_stylesheet(node, style) {
  append(
    /** @type {Document} */
    node.head || node,
    style
  );
  return style.sheet;
}
function insert(target, node, anchor) {
  target.insertBefore(node, anchor || null);
}
function detach(node) {
  if (node.parentNode) {
    node.parentNode.removeChild(node);
  }
}
function destroy_each(iterations, detaching) {
  for (let i = 0; i < iterations.length; i += 1) {
    if (iterations[i]) iterations[i].d(detaching);
  }
}
function element(name) {
  return document.createElement(name);
}
function svg_element(name) {
  return document.createElementNS("http://www.w3.org/2000/svg", name);
}
function text(data) {
  return document.createTextNode(data);
}
function space() {
  return text(" ");
}
function empty() {
  return text("");
}
function listen(node, event, handler, options) {
  node.addEventListener(event, handler, options);
  return () => node.removeEventListener(event, handler, options);
}
function attr(node, attribute, value) {
  if (value == null) node.removeAttribute(attribute);
  else if (node.getAttribute(attribute) !== value) node.setAttribute(attribute, value);
}
function children(element2) {
  return Array.from(element2.childNodes);
}
function set_data(text2, data) {
  data = "" + data;
  if (text2.data === data) return;
  text2.data = /** @type {string} */
  data;
}
function toggle_class(element2, name, toggle) {
  element2.classList.toggle(name, !!toggle);
}
function custom_event(type, detail, { bubbles = false, cancelable = false } = {}) {
  return new CustomEvent(type, { detail, bubbles, cancelable });
}
var HtmlTag = class {
  /**
   * @private
   * @default false
   */
  is_svg = false;
  /** parent for creating node */
  e = void 0;
  /** html tag nodes */
  n = void 0;
  /** target */
  t = void 0;
  /** anchor */
  a = void 0;
  constructor(is_svg = false) {
    this.is_svg = is_svg;
    this.e = this.n = null;
  }
  /**
   * @param {string} html
   * @returns {void}
   */
  c(html) {
    this.h(html);
  }
  /**
   * @param {string} html
   * @param {HTMLElement | SVGElement} target
   * @param {HTMLElement | SVGElement} anchor
   * @returns {void}
   */
  m(html, target, anchor = null) {
    if (!this.e) {
      if (this.is_svg)
        this.e = svg_element(
          /** @type {keyof SVGElementTagNameMap} */
          target.nodeName
        );
      else
        this.e = element(
          /** @type {keyof HTMLElementTagNameMap} */
          target.nodeType === 11 ? "TEMPLATE" : target.nodeName
        );
      this.t = target.tagName !== "TEMPLATE" ? target : (
        /** @type {HTMLTemplateElement} */
        target.content
      );
      this.c(html);
    }
    this.i(anchor);
  }
  /**
   * @param {string} html
   * @returns {void}
   */
  h(html) {
    this.e.innerHTML = html;
    this.n = Array.from(
      this.e.nodeName === "TEMPLATE" ? this.e.content.childNodes : this.e.childNodes
    );
  }
  /**
   * @returns {void} */
  i(anchor) {
    for (let i = 0; i < this.n.length; i += 1) {
      insert(this.t, this.n[i], anchor);
    }
  }
  /**
   * @param {string} html
   * @returns {void}
   */
  p(html) {
    this.d();
    this.h(html);
    this.i(this.a);
  }
  /**
   * @returns {void} */
  d() {
    this.n.forEach(detach);
  }
};
function get_custom_elements_slots(element2) {
  const result = {};
  element2.childNodes.forEach(
    /** @param {Element} node */
    (node) => {
      result[node.slot || "default"] = true;
    }
  );
  return result;
}

// node_modules/svelte/src/runtime/internal/await_block.js
init_esbuild_buffer_shim();

// node_modules/svelte/src/runtime/internal/transitions.js
init_esbuild_buffer_shim();

// node_modules/svelte/src/runtime/internal/scheduler.js
init_esbuild_buffer_shim();

// node_modules/svelte/src/runtime/internal/lifecycle.js
init_esbuild_buffer_shim();
var current_component;
function set_current_component(component) {
  current_component = component;
}
function get_current_component() {
  if (!current_component) throw new Error("Function called outside component initialization");
  return current_component;
}
function onMount(fn) {
  get_current_component().$$.on_mount.push(fn);
}
function createEventDispatcher() {
  const component = get_current_component();
  return (type, detail, { cancelable = false } = {}) => {
    const callbacks = component.$$.callbacks[type];
    if (callbacks) {
      const event = custom_event(
        /** @type {string} */
        type,
        detail,
        { cancelable }
      );
      callbacks.slice().forEach((fn) => {
        fn.call(component, event);
      });
      return !event.defaultPrevented;
    }
    return true;
  };
}

// node_modules/svelte/src/runtime/internal/scheduler.js
var dirty_components = [];
var binding_callbacks = [];
var render_callbacks = [];
var flush_callbacks = [];
var resolved_promise = /* @__PURE__ */ Promise.resolve();
var update_scheduled = false;
function schedule_update() {
  if (!update_scheduled) {
    update_scheduled = true;
    resolved_promise.then(flush);
  }
}
function add_render_callback(fn) {
  render_callbacks.push(fn);
}
var seen_callbacks = /* @__PURE__ */ new Set();
var flushidx = 0;
function flush() {
  if (flushidx !== 0) {
    return;
  }
  const saved_component = current_component;
  do {
    try {
      while (flushidx < dirty_components.length) {
        const component = dirty_components[flushidx];
        flushidx++;
        set_current_component(component);
        update(component.$$);
      }
    } catch (e) {
      dirty_components.length = 0;
      flushidx = 0;
      throw e;
    }
    set_current_component(null);
    dirty_components.length = 0;
    flushidx = 0;
    while (binding_callbacks.length) binding_callbacks.pop()();
    for (let i = 0; i < render_callbacks.length; i += 1) {
      const callback = render_callbacks[i];
      if (!seen_callbacks.has(callback)) {
        seen_callbacks.add(callback);
        callback();
      }
    }
    render_callbacks.length = 0;
  } while (dirty_components.length);
  while (flush_callbacks.length) {
    flush_callbacks.pop()();
  }
  update_scheduled = false;
  seen_callbacks.clear();
  set_current_component(saved_component);
}
function update($$) {
  if ($$.fragment !== null) {
    $$.update();
    run_all($$.before_update);
    const dirty = $$.dirty;
    $$.dirty = [-1];
    $$.fragment && $$.fragment.p($$.ctx, dirty);
    $$.after_update.forEach(add_render_callback);
  }
}
function flush_render_callbacks(fns) {
  const filtered = [];
  const targets = [];
  render_callbacks.forEach((c) => fns.indexOf(c) === -1 ? filtered.push(c) : targets.push(c));
  targets.forEach((c) => c());
  render_callbacks = filtered;
}

// node_modules/svelte/src/runtime/internal/transitions.js
var outroing = /* @__PURE__ */ new Set();
var outros;
function group_outros() {
  outros = {
    r: 0,
    c: [],
    p: outros
    // parent group
  };
}
function check_outros() {
  if (!outros.r) {
    run_all(outros.c);
  }
  outros = outros.p;
}
function transition_in(block, local) {
  if (block && block.i) {
    outroing.delete(block);
    block.i(local);
  }
}
function transition_out(block, local, detach2, callback) {
  if (block && block.o) {
    if (outroing.has(block)) return;
    outroing.add(block);
    outros.c.push(() => {
      outroing.delete(block);
      if (callback) {
        if (detach2) block.d(1);
        callback();
      }
    });
    block.o(local);
  } else if (callback) {
    callback();
  }
}

// node_modules/svelte/src/runtime/internal/each.js
init_esbuild_buffer_shim();
function ensure_array_like(array_like_or_iterator) {
  return array_like_or_iterator?.length !== void 0 ? array_like_or_iterator : Array.from(array_like_or_iterator);
}

// node_modules/svelte/src/runtime/internal/spread.js
init_esbuild_buffer_shim();

// node_modules/svelte/src/runtime/internal/ssr.js
init_esbuild_buffer_shim();

// node_modules/svelte/src/shared/boolean_attributes.js
init_esbuild_buffer_shim();
var _boolean_attributes = (
  /** @type {const} */
  [
    "allowfullscreen",
    "allowpaymentrequest",
    "async",
    "autofocus",
    "autoplay",
    "checked",
    "controls",
    "default",
    "defer",
    "disabled",
    "formnovalidate",
    "hidden",
    "inert",
    "ismap",
    "loop",
    "multiple",
    "muted",
    "nomodule",
    "novalidate",
    "open",
    "playsinline",
    "readonly",
    "required",
    "reversed",
    "selected"
  ]
);
var boolean_attributes = /* @__PURE__ */ new Set([..._boolean_attributes]);

// node_modules/svelte/src/shared/utils/escape.js
init_esbuild_buffer_shim();

// node_modules/svelte/src/shared/utils/names.js
init_esbuild_buffer_shim();

// node_modules/svelte/src/runtime/internal/Component.js
init_esbuild_buffer_shim();
function create_component(block) {
  block && block.c();
}
function mount_component(component, target, anchor) {
  const { fragment, after_update } = component.$$;
  fragment && fragment.m(target, anchor);
  add_render_callback(() => {
    const new_on_destroy = component.$$.on_mount.map(run).filter(is_function);
    if (component.$$.on_destroy) {
      component.$$.on_destroy.push(...new_on_destroy);
    } else {
      run_all(new_on_destroy);
    }
    component.$$.on_mount = [];
  });
  after_update.forEach(add_render_callback);
}
function destroy_component(component, detaching) {
  const $$ = component.$$;
  if ($$.fragment !== null) {
    flush_render_callbacks($$.after_update);
    run_all($$.on_destroy);
    $$.fragment && $$.fragment.d(detaching);
    $$.on_destroy = $$.fragment = null;
    $$.ctx = [];
  }
}
function make_dirty(component, i) {
  if (component.$$.dirty[0] === -1) {
    dirty_components.push(component);
    schedule_update();
    component.$$.dirty.fill(0);
  }
  component.$$.dirty[i / 31 | 0] |= 1 << i % 31;
}
function init2(component, options, instance6, create_fragment6, not_equal, props, append_styles2 = null, dirty = [-1]) {
  const parent_component = current_component;
  set_current_component(component);
  const $$ = component.$$ = {
    fragment: null,
    ctx: [],
    // state
    props,
    update: noop,
    not_equal,
    bound: blank_object(),
    // lifecycle
    on_mount: [],
    on_destroy: [],
    on_disconnect: [],
    before_update: [],
    after_update: [],
    context: new Map(options.context || (parent_component ? parent_component.$$.context : [])),
    // everything else
    callbacks: blank_object(),
    dirty,
    skip_bound: false,
    root: options.target || parent_component.$$.root
  };
  append_styles2 && append_styles2($$.root);
  let ready = false;
  $$.ctx = instance6 ? instance6(component, options.props || {}, (i, ret, ...rest) => {
    const value = rest.length ? rest[0] : ret;
    if ($$.ctx && not_equal($$.ctx[i], $$.ctx[i] = value)) {
      if (!$$.skip_bound && $$.bound[i]) $$.bound[i](value);
      if (ready) make_dirty(component, i);
    }
    return ret;
  }) : [];
  $$.update();
  ready = true;
  run_all($$.before_update);
  $$.fragment = create_fragment6 ? create_fragment6($$.ctx) : false;
  if (options.target) {
    if (options.hydrate) {
      start_hydrating();
      const nodes = children(options.target);
      $$.fragment && $$.fragment.l(nodes);
      nodes.forEach(detach);
    } else {
      $$.fragment && $$.fragment.c();
    }
    if (options.intro) transition_in(component.$$.fragment);
    mount_component(component, options.target, options.anchor);
    end_hydrating();
    flush();
  }
  set_current_component(parent_component);
}
var SvelteElement;
if (typeof HTMLElement === "function") {
  SvelteElement = class extends HTMLElement {
    /** The Svelte component constructor */
    $$ctor;
    /** Slots */
    $$s;
    /** The Svelte component instance */
    $$c;
    /** Whether or not the custom element is connected */
    $$cn = false;
    /** Component props data */
    $$d = {};
    /** `true` if currently in the process of reflecting component props back to attributes */
    $$r = false;
    /** @type {Record<string, CustomElementPropDefinition>} Props definition (name, reflected, type etc) */
    $$p_d = {};
    /** @type {Record<string, Function[]>} Event listeners */
    $$l = {};
    /** @type {Map<Function, Function>} Event listener unsubscribe functions */
    $$l_u = /* @__PURE__ */ new Map();
    constructor($$componentCtor, $$slots, use_shadow_dom) {
      super();
      this.$$ctor = $$componentCtor;
      this.$$s = $$slots;
      if (use_shadow_dom) {
        this.attachShadow({ mode: "open" });
      }
    }
    addEventListener(type, listener, options) {
      this.$$l[type] = this.$$l[type] || [];
      this.$$l[type].push(listener);
      if (this.$$c) {
        const unsub = this.$$c.$on(type, listener);
        this.$$l_u.set(listener, unsub);
      }
      super.addEventListener(type, listener, options);
    }
    removeEventListener(type, listener, options) {
      super.removeEventListener(type, listener, options);
      if (this.$$c) {
        const unsub = this.$$l_u.get(listener);
        if (unsub) {
          unsub();
          this.$$l_u.delete(listener);
        }
      }
      if (this.$$l[type]) {
        const idx = this.$$l[type].indexOf(listener);
        if (idx >= 0) {
          this.$$l[type].splice(idx, 1);
        }
      }
    }
    async connectedCallback() {
      this.$$cn = true;
      if (!this.$$c) {
        let create_slot = function(name) {
          return () => {
            let node;
            const obj = {
              c: function create() {
                node = element("slot");
                if (name !== "default") {
                  attr(node, "name", name);
                }
              },
              /**
               * @param {HTMLElement} target
               * @param {HTMLElement} [anchor]
               */
              m: function mount(target, anchor) {
                insert(target, node, anchor);
              },
              d: function destroy(detaching) {
                if (detaching) {
                  detach(node);
                }
              }
            };
            return obj;
          };
        };
        await Promise.resolve();
        if (!this.$$cn || this.$$c) {
          return;
        }
        const $$slots = {};
        const existing_slots = get_custom_elements_slots(this);
        for (const name of this.$$s) {
          if (name in existing_slots) {
            $$slots[name] = [create_slot(name)];
          }
        }
        for (const attribute of this.attributes) {
          const name = this.$$g_p(attribute.name);
          if (!(name in this.$$d)) {
            this.$$d[name] = get_custom_element_value(name, attribute.value, this.$$p_d, "toProp");
          }
        }
        for (const key in this.$$p_d) {
          if (!(key in this.$$d) && this[key] !== void 0) {
            this.$$d[key] = this[key];
            delete this[key];
          }
        }
        this.$$c = new this.$$ctor({
          target: this.shadowRoot || this,
          props: {
            ...this.$$d,
            $$slots,
            $$scope: {
              ctx: []
            }
          }
        });
        const reflect_attributes = () => {
          this.$$r = true;
          for (const key in this.$$p_d) {
            this.$$d[key] = this.$$c.$$.ctx[this.$$c.$$.props[key]];
            if (this.$$p_d[key].reflect) {
              const attribute_value = get_custom_element_value(
                key,
                this.$$d[key],
                this.$$p_d,
                "toAttribute"
              );
              if (attribute_value == null) {
                this.removeAttribute(this.$$p_d[key].attribute || key);
              } else {
                this.setAttribute(this.$$p_d[key].attribute || key, attribute_value);
              }
            }
          }
          this.$$r = false;
        };
        this.$$c.$$.after_update.push(reflect_attributes);
        reflect_attributes();
        for (const type in this.$$l) {
          for (const listener of this.$$l[type]) {
            const unsub = this.$$c.$on(type, listener);
            this.$$l_u.set(listener, unsub);
          }
        }
        this.$$l = {};
      }
    }
    // We don't need this when working within Svelte code, but for compatibility of people using this outside of Svelte
    // and setting attributes through setAttribute etc, this is helpful
    attributeChangedCallback(attr2, _oldValue, newValue) {
      if (this.$$r) return;
      attr2 = this.$$g_p(attr2);
      this.$$d[attr2] = get_custom_element_value(attr2, newValue, this.$$p_d, "toProp");
      this.$$c?.$set({ [attr2]: this.$$d[attr2] });
    }
    disconnectedCallback() {
      this.$$cn = false;
      Promise.resolve().then(() => {
        if (!this.$$cn && this.$$c) {
          this.$$c.$destroy();
          this.$$c = void 0;
        }
      });
    }
    $$g_p(attribute_name) {
      return Object.keys(this.$$p_d).find(
        (key) => this.$$p_d[key].attribute === attribute_name || !this.$$p_d[key].attribute && key.toLowerCase() === attribute_name
      ) || attribute_name;
    }
  };
}
function get_custom_element_value(prop, value, props_definition, transform) {
  const type = props_definition[prop]?.type;
  value = type === "Boolean" && typeof value !== "boolean" ? value != null : value;
  if (!transform || !props_definition[prop]) {
    return value;
  } else if (transform === "toAttribute") {
    switch (type) {
      case "Object":
      case "Array":
        return value == null ? null : JSON.stringify(value);
      case "Boolean":
        return value ? "" : null;
      case "Number":
        return value == null ? null : value;
      default:
        return value;
    }
  } else {
    switch (type) {
      case "Object":
      case "Array":
        return value && JSON.parse(value);
      case "Boolean":
        return value;
      // conversion already handled above
      case "Number":
        return value != null ? +value : value;
      default:
        return value;
    }
  }
}
var SvelteComponent = class {
  /**
   * ### PRIVATE API
   *
   * Do not use, may change at any time
   *
   * @type {any}
   */
  $$ = void 0;
  /**
   * ### PRIVATE API
   *
   * Do not use, may change at any time
   *
   * @type {any}
   */
  $$set = void 0;
  /** @returns {void} */
  $destroy() {
    destroy_component(this, 1);
    this.$destroy = noop;
  }
  /**
   * @template {Extract<keyof Events, string>} K
   * @param {K} type
   * @param {((e: Events[K]) => void) | null | undefined} callback
   * @returns {() => void}
   */
  $on(type, callback) {
    if (!is_function(callback)) {
      return noop;
    }
    const callbacks = this.$$.callbacks[type] || (this.$$.callbacks[type] = []);
    callbacks.push(callback);
    return () => {
      const index = callbacks.indexOf(callback);
      if (index !== -1) callbacks.splice(index, 1);
    };
  }
  /**
   * @param {Partial<Props>} props
   * @returns {void}
   */
  $set(props) {
    if (this.$$set && !is_empty(props)) {
      this.$$.skip_bound = true;
      this.$$set(props);
      this.$$.skip_bound = false;
    }
  }
};

// node_modules/svelte/src/runtime/internal/dev.js
init_esbuild_buffer_shim();

// node_modules/svelte/src/shared/version.js
init_esbuild_buffer_shim();
var PUBLIC_VERSION = "4";

// node_modules/svelte/src/runtime/internal/disclose-version/index.js
init_esbuild_buffer_shim();
if (typeof window !== "undefined")
  (window.__svelte || (window.__svelte = { v: /* @__PURE__ */ new Set() })).v.add(PUBLIC_VERSION);

// src/views/PublicationCenter/PublicationCenter.svelte
var import_obsidian13 = require("obsidian");

// src/ui/TreeView/TreeView.svelte
init_esbuild_buffer_shim();

// src/ui/TreeView/TreeNode.svelte
init_esbuild_buffer_shim();

// node_modules/svelte/src/runtime/index.js
init_esbuild_buffer_shim();

// src/ui/Icon.svelte
init_esbuild_buffer_shim();
var import_obsidian12 = require("obsidian");
function create_fragment(ctx) {
  let html_tag;
  let raw_value = (0, import_obsidian12.getIcon)(
    /*name*/
    ctx[0]
  )?.outerHTML + "";
  let html_anchor;
  return {
    c() {
      html_tag = new HtmlTag(false);
      html_anchor = empty();
      html_tag.a = html_anchor;
    },
    m(target, anchor) {
      html_tag.m(raw_value, target, anchor);
      insert(target, html_anchor, anchor);
    },
    p(ctx2, [dirty]) {
      if (dirty & /*name*/
      1 && raw_value !== (raw_value = (0, import_obsidian12.getIcon)(
        /*name*/
        ctx2[0]
      )?.outerHTML + "")) html_tag.p(raw_value);
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(html_anchor);
        html_tag.d();
      }
    }
  };
}
function instance($$self, $$props, $$invalidate) {
  let { name = "book-heart" } = $$props;
  $$self.$$set = ($$props2) => {
    if ("name" in $$props2) $$invalidate(0, name = $$props2.name);
  };
  return [name];
}
var Icon = class extends SvelteComponent {
  constructor(options) {
    super();
    init2(this, options, instance, create_fragment, safe_not_equal, { name: 0 });
  }
};
var Icon_default = Icon;

// src/ui/TreeView/TreeNode.svelte
function get_each_context(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[13] = list[i];
  return child_ctx;
}
function create_if_block_5(ctx) {
  let span2;
  let span0;
  let t0;
  let icon;
  let t1;
  let t2;
  let span1;
  let t3_value = (
    /*tree*/
    ctx[0].name + ""
  );
  let t3;
  let t4;
  let current;
  let mounted;
  let dispose;
  icon = new Icon_default({ props: { name: "file" } });
  let if_block0 = !/*readOnly*/
  ctx[1] && create_if_block_7(ctx);
  let if_block1 = (
    /*enableShowDiff*/
    ctx[2] && create_if_block_6(ctx)
  );
  return {
    c() {
      span2 = element("span");
      span0 = element("span");
      t0 = space();
      create_component(icon.$$.fragment);
      t1 = space();
      if (if_block0) if_block0.c();
      t2 = space();
      span1 = element("span");
      t3 = text(t3_value);
      t4 = space();
      if (if_block1) if_block1.c();
      attr(span0, "class", "no-arrow");
    },
    m(target, anchor) {
      insert(target, span2, anchor);
      append(span2, span0);
      append(span2, t0);
      mount_component(icon, span2, null);
      append(span2, t1);
      if (if_block0) if_block0.m(span2, null);
      append(span2, t2);
      append(span2, span1);
      append(span1, t3);
      append(span2, t4);
      if (if_block1) if_block1.m(span2, null);
      current = true;
      if (!mounted) {
        dispose = listen(
          span1,
          "click",
          /*toggleExpansion*/
          ctx[6]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (!/*readOnly*/
      ctx2[1]) {
        if (if_block0) {
          if_block0.p(ctx2, dirty);
        } else {
          if_block0 = create_if_block_7(ctx2);
          if_block0.c();
          if_block0.m(span2, t2);
        }
      } else if (if_block0) {
        if_block0.d(1);
        if_block0 = null;
      }
      if ((!current || dirty & /*tree*/
      1) && t3_value !== (t3_value = /*tree*/
      ctx2[0].name + "")) set_data(t3, t3_value);
      if (
        /*enableShowDiff*/
        ctx2[2]
      ) {
        if (if_block1) {
          if_block1.p(ctx2, dirty);
          if (dirty & /*enableShowDiff*/
          4) {
            transition_in(if_block1, 1);
          }
        } else {
          if_block1 = create_if_block_6(ctx2);
          if_block1.c();
          transition_in(if_block1, 1);
          if_block1.m(span2, null);
        }
      } else if (if_block1) {
        group_outros();
        transition_out(if_block1, 1, 1, () => {
          if_block1 = null;
        });
        check_outros();
      }
    },
    i(local) {
      if (current) return;
      transition_in(icon.$$.fragment, local);
      transition_in(if_block1);
      current = true;
    },
    o(local) {
      transition_out(icon.$$.fragment, local);
      transition_out(if_block1);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(span2);
      }
      destroy_component(icon);
      if (if_block0) if_block0.d();
      if (if_block1) if_block1.d();
      mounted = false;
      dispose();
    }
  };
}
function create_if_block(ctx) {
  let span1;
  let span0;
  let icon;
  let t0;
  let current_block_type_index;
  let if_block0;
  let t1;
  let if_block1_anchor;
  let current;
  let mounted;
  let dispose;
  icon = new Icon_default({ props: { name: "chevron-right" } });
  const if_block_creators = [create_if_block_2, create_else_block];
  const if_blocks = [];
  function select_block_type_1(ctx2, dirty) {
    if (!/*isRoot*/
    ctx2[5]) return 0;
    return 1;
  }
  current_block_type_index = select_block_type_1(ctx, -1);
  if_block0 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
  let if_block1 = (
    /*expanded*/
    ctx[3] && create_if_block_1(ctx)
  );
  return {
    c() {
      span1 = element("span");
      span0 = element("span");
      create_component(icon.$$.fragment);
      t0 = space();
      if_block0.c();
      t1 = space();
      if (if_block1) if_block1.c();
      if_block1_anchor = empty();
      attr(span0, "class", "arrow");
      toggle_class(
        span0,
        "arrowDown",
        /*arrowDown*/
        ctx[4]
      );
    },
    m(target, anchor) {
      insert(target, span1, anchor);
      append(span1, span0);
      mount_component(icon, span0, null);
      append(span1, t0);
      if_blocks[current_block_type_index].m(span1, null);
      insert(target, t1, anchor);
      if (if_block1) if_block1.m(target, anchor);
      insert(target, if_block1_anchor, anchor);
      current = true;
      if (!mounted) {
        dispose = listen(
          span0,
          "click",
          /*toggleExpansion*/
          ctx[6]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (!current || dirty & /*arrowDown*/
      16) {
        toggle_class(
          span0,
          "arrowDown",
          /*arrowDown*/
          ctx2[4]
        );
      }
      if_block0.p(ctx2, dirty);
      if (
        /*expanded*/
        ctx2[3]
      ) {
        if (if_block1) {
          if_block1.p(ctx2, dirty);
          if (dirty & /*expanded*/
          8) {
            transition_in(if_block1, 1);
          }
        } else {
          if_block1 = create_if_block_1(ctx2);
          if_block1.c();
          transition_in(if_block1, 1);
          if_block1.m(if_block1_anchor.parentNode, if_block1_anchor);
        }
      } else if (if_block1) {
        group_outros();
        transition_out(if_block1, 1, 1, () => {
          if_block1 = null;
        });
        check_outros();
      }
    },
    i(local) {
      if (current) return;
      transition_in(icon.$$.fragment, local);
      transition_in(if_block0);
      transition_in(if_block1);
      current = true;
    },
    o(local) {
      transition_out(icon.$$.fragment, local);
      transition_out(if_block0);
      transition_out(if_block1);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(span1);
        detach(t1);
        detach(if_block1_anchor);
      }
      destroy_component(icon);
      if_blocks[current_block_type_index].d();
      if (if_block1) if_block1.d(detaching);
      mounted = false;
      dispose();
    }
  };
}
function create_if_block_7(ctx) {
  let input;
  let input_data_label_value;
  let input_checked_value;
  let input_indeterminate_value;
  let mounted;
  let dispose;
  return {
    c() {
      input = element("input");
      attr(input, "type", "checkbox");
      attr(input, "data-label", input_data_label_value = /*tree*/
      ctx[0].name);
      input.checked = input_checked_value = /*tree*/
      ctx[0].checked;
      input.indeterminate = input_indeterminate_value = /*tree*/
      ctx[0].indeterminate;
    },
    m(target, anchor) {
      insert(target, input, anchor);
      if (!mounted) {
        dispose = listen(
          input,
          "click",
          /*toggleCheck*/
          ctx[7]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty & /*tree*/
      1 && input_data_label_value !== (input_data_label_value = /*tree*/
      ctx2[0].name)) {
        attr(input, "data-label", input_data_label_value);
      }
      if (dirty & /*tree*/
      1 && input_checked_value !== (input_checked_value = /*tree*/
      ctx2[0].checked)) {
        input.checked = input_checked_value;
      }
      if (dirty & /*tree*/
      1 && input_indeterminate_value !== (input_indeterminate_value = /*tree*/
      ctx2[0].indeterminate)) {
        input.indeterminate = input_indeterminate_value;
      }
    },
    d(detaching) {
      if (detaching) {
        detach(input);
      }
      mounted = false;
      dispose();
    }
  };
}
function create_if_block_6(ctx) {
  let span;
  let icon;
  let current;
  let mounted;
  let dispose;
  icon = new Icon_default({ props: { name: "file-diff" } });
  return {
    c() {
      span = element("span");
      create_component(icon.$$.fragment);
      attr(span, "title", "Show changes");
      attr(span, "class", "quartz-syncer-icon-diff");
    },
    m(target, anchor) {
      insert(target, span, anchor);
      mount_component(icon, span, null);
      current = true;
      if (!mounted) {
        dispose = listen(
          span,
          "click",
          /*showDiff*/
          ctx[9]
        );
        mounted = true;
      }
    },
    p: noop,
    i(local) {
      if (current) return;
      transition_in(icon.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(icon.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(span);
      }
      destroy_component(icon);
      mounted = false;
      dispose();
    }
  };
}
function create_else_block(ctx) {
  let t0;
  let span;
  let t1_value = (
    /*tree*/
    ctx[0].name + ""
  );
  let t1;
  let mounted;
  let dispose;
  let if_block = !/*readOnly*/
  ctx[1] && create_if_block_4(ctx);
  return {
    c() {
      if (if_block) if_block.c();
      t0 = space();
      span = element("span");
      t1 = text(t1_value);
      attr(span, "class", "root-header");
    },
    m(target, anchor) {
      if (if_block) if_block.m(target, anchor);
      insert(target, t0, anchor);
      insert(target, span, anchor);
      append(span, t1);
      if (!mounted) {
        dispose = listen(
          span,
          "click",
          /*toggleExpansion*/
          ctx[6]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (!/*readOnly*/
      ctx2[1]) {
        if (if_block) {
          if_block.p(ctx2, dirty);
        } else {
          if_block = create_if_block_4(ctx2);
          if_block.c();
          if_block.m(t0.parentNode, t0);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
      if (dirty & /*tree*/
      1 && t1_value !== (t1_value = /*tree*/
      ctx2[0].name + "")) set_data(t1, t1_value);
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(t0);
        detach(span);
      }
      if (if_block) if_block.d(detaching);
      mounted = false;
      dispose();
    }
  };
}
function create_if_block_2(ctx) {
  let icon;
  let t0;
  let t1;
  let span;
  let t2_value = (
    /*tree*/
    ctx[0].name + ""
  );
  let t2;
  let current;
  let mounted;
  let dispose;
  icon = new Icon_default({ props: { name: "folder" } });
  let if_block = !/*readOnly*/
  ctx[1] && create_if_block_3(ctx);
  return {
    c() {
      create_component(icon.$$.fragment);
      t0 = space();
      if (if_block) if_block.c();
      t1 = space();
      span = element("span");
      t2 = text(t2_value);
    },
    m(target, anchor) {
      mount_component(icon, target, anchor);
      insert(target, t0, anchor);
      if (if_block) if_block.m(target, anchor);
      insert(target, t1, anchor);
      insert(target, span, anchor);
      append(span, t2);
      current = true;
      if (!mounted) {
        dispose = listen(
          span,
          "click",
          /*toggleExpansion*/
          ctx[6]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (!/*readOnly*/
      ctx2[1]) {
        if (if_block) {
          if_block.p(ctx2, dirty);
        } else {
          if_block = create_if_block_3(ctx2);
          if_block.c();
          if_block.m(t1.parentNode, t1);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
      if ((!current || dirty & /*tree*/
      1) && t2_value !== (t2_value = /*tree*/
      ctx2[0].name + "")) set_data(t2, t2_value);
    },
    i(local) {
      if (current) return;
      transition_in(icon.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(icon.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(t0);
        detach(t1);
        detach(span);
      }
      destroy_component(icon, detaching);
      if (if_block) if_block.d(detaching);
      mounted = false;
      dispose();
    }
  };
}
function create_if_block_4(ctx) {
  let input;
  let input_data_label_value;
  let input_checked_value;
  let input_indeterminate_value;
  let mounted;
  let dispose;
  return {
    c() {
      input = element("input");
      attr(input, "type", "checkbox");
      attr(input, "data-label", input_data_label_value = /*tree*/
      ctx[0].name);
      input.checked = input_checked_value = /*tree*/
      ctx[0].checked;
      input.indeterminate = input_indeterminate_value = /*tree*/
      ctx[0].indeterminate;
    },
    m(target, anchor) {
      insert(target, input, anchor);
      if (!mounted) {
        dispose = listen(
          input,
          "click",
          /*toggleCheck*/
          ctx[7]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty & /*tree*/
      1 && input_data_label_value !== (input_data_label_value = /*tree*/
      ctx2[0].name)) {
        attr(input, "data-label", input_data_label_value);
      }
      if (dirty & /*tree*/
      1 && input_checked_value !== (input_checked_value = /*tree*/
      ctx2[0].checked)) {
        input.checked = input_checked_value;
      }
      if (dirty & /*tree*/
      1 && input_indeterminate_value !== (input_indeterminate_value = /*tree*/
      ctx2[0].indeterminate)) {
        input.indeterminate = input_indeterminate_value;
      }
    },
    d(detaching) {
      if (detaching) {
        detach(input);
      }
      mounted = false;
      dispose();
    }
  };
}
function create_if_block_3(ctx) {
  let input;
  let input_data_label_value;
  let input_checked_value;
  let input_indeterminate_value;
  let mounted;
  let dispose;
  return {
    c() {
      input = element("input");
      attr(input, "type", "checkbox");
      attr(input, "data-label", input_data_label_value = /*tree*/
      ctx[0].name);
      input.checked = input_checked_value = /*tree*/
      ctx[0].checked;
      input.indeterminate = input_indeterminate_value = /*tree*/
      ctx[0].indeterminate;
    },
    m(target, anchor) {
      insert(target, input, anchor);
      if (!mounted) {
        dispose = listen(
          input,
          "click",
          /*toggleCheck*/
          ctx[7]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty & /*tree*/
      1 && input_data_label_value !== (input_data_label_value = /*tree*/
      ctx2[0].name)) {
        attr(input, "data-label", input_data_label_value);
      }
      if (dirty & /*tree*/
      1 && input_checked_value !== (input_checked_value = /*tree*/
      ctx2[0].checked)) {
        input.checked = input_checked_value;
      }
      if (dirty & /*tree*/
      1 && input_indeterminate_value !== (input_indeterminate_value = /*tree*/
      ctx2[0].indeterminate)) {
        input.indeterminate = input_indeterminate_value;
      }
    },
    d(detaching) {
      if (detaching) {
        detach(input);
      }
      mounted = false;
      dispose();
    }
  };
}
function create_if_block_1(ctx) {
  let each_1_anchor;
  let current;
  let each_value = ensure_array_like(
    /*tree*/
    ctx[0].children
  );
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block(get_each_context(ctx, each_value, i));
  }
  const out = (i) => transition_out(each_blocks[i], 1, 1, () => {
    each_blocks[i] = null;
  });
  return {
    c() {
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      each_1_anchor = empty();
    },
    m(target, anchor) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(target, anchor);
        }
      }
      insert(target, each_1_anchor, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      if (dirty & /*enableShowDiff, readOnly, tree, dispatchChecked, dispatchShowDiff*/
      1287) {
        each_value = ensure_array_like(
          /*tree*/
          ctx2[0].children
        );
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context(ctx2, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
            transition_in(each_blocks[i], 1);
          } else {
            each_blocks[i] = create_each_block(child_ctx);
            each_blocks[i].c();
            transition_in(each_blocks[i], 1);
            each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor);
          }
        }
        group_outros();
        for (i = each_value.length; i < each_blocks.length; i += 1) {
          out(i);
        }
        check_outros();
      }
    },
    i(local) {
      if (current) return;
      for (let i = 0; i < each_value.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      current = true;
    },
    o(local) {
      each_blocks = each_blocks.filter(Boolean);
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(each_1_anchor);
      }
      destroy_each(each_blocks, detaching);
    }
  };
}
function create_each_block(ctx) {
  let treenode;
  let current;
  treenode = new TreeNode({
    props: {
      enableShowDiff: (
        /*enableShowDiff*/
        ctx[2]
      ),
      readOnly: (
        /*readOnly*/
        ctx[1]
      ),
      tree: (
        /*child*/
        ctx[13]
      )
    }
  });
  treenode.$on(
    "toggle",
    /*dispatchChecked*/
    ctx[8]
  );
  treenode.$on(
    "showDiff",
    /*showDiff_handler*/
    ctx[11]
  );
  return {
    c() {
      create_component(treenode.$$.fragment);
    },
    m(target, anchor) {
      mount_component(treenode, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const treenode_changes = {};
      if (dirty & /*enableShowDiff*/
      4) treenode_changes.enableShowDiff = /*enableShowDiff*/
      ctx2[2];
      if (dirty & /*readOnly*/
      2) treenode_changes.readOnly = /*readOnly*/
      ctx2[1];
      if (dirty & /*tree*/
      1) treenode_changes.tree = /*child*/
      ctx2[13];
      treenode.$set(treenode_changes);
    },
    i(local) {
      if (current) return;
      transition_in(treenode.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(treenode.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(treenode, detaching);
    }
  };
}
function create_fragment2(ctx) {
  let ul;
  let li;
  let current_block_type_index;
  let if_block;
  let current;
  const if_block_creators = [create_if_block, create_if_block_5];
  const if_blocks = [];
  function select_block_type(ctx2, dirty) {
    if (
      /*tree*/
      ctx2[0].children
    ) return 0;
    if (!/*isRoot*/
    ctx2[5]) return 1;
    return -1;
  }
  if (~(current_block_type_index = select_block_type(ctx, -1))) {
    if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
  }
  return {
    c() {
      ul = element("ul");
      li = element("li");
      if (if_block) if_block.c();
      toggle_class(
        ul,
        "isRoot",
        /*isRoot*/
        ctx[5]
      );
    },
    m(target, anchor) {
      insert(target, ul, anchor);
      append(ul, li);
      if (~current_block_type_index) {
        if_blocks[current_block_type_index].m(li, null);
      }
      current = true;
    },
    p(ctx2, [dirty]) {
      let previous_block_index = current_block_type_index;
      current_block_type_index = select_block_type(ctx2, dirty);
      if (current_block_type_index === previous_block_index) {
        if (~current_block_type_index) {
          if_blocks[current_block_type_index].p(ctx2, dirty);
        }
      } else {
        if (if_block) {
          group_outros();
          transition_out(if_blocks[previous_block_index], 1, 1, () => {
            if_blocks[previous_block_index] = null;
          });
          check_outros();
        }
        if (~current_block_type_index) {
          if_block = if_blocks[current_block_type_index];
          if (!if_block) {
            if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
            if_block.c();
          } else {
            if_block.p(ctx2, dirty);
          }
          transition_in(if_block, 1);
          if_block.m(li, null);
        } else {
          if_block = null;
        }
      }
    },
    i(local) {
      if (current) return;
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(ul);
      }
      if (~current_block_type_index) {
        if_blocks[current_block_type_index].d();
      }
    }
  };
}
var _expansionState = {};
function instance2($$self, $$props, $$invalidate) {
  let arrowDown;
  let { tree } = $$props;
  let { readOnly = false } = $$props;
  let { enableShowDiff = false } = $$props;
  const dispatch = createEventDispatcher();
  let { isRoot } = tree;
  let expanded = _expansionState[tree.path] || false;
  const toggleExpansion = () => {
    $$invalidate(3, expanded = _expansionState[tree.path] = !expanded);
  };
  const toggleCheck = () => {
    $$invalidate(0, tree.checked = !tree.checked, tree);
    dispatch("toggle", { node: tree });
  };
  const dispatchChecked = (e) => {
    dispatch("toggle", { node: e.detail.node });
  };
  const showDiff = (e) => {
    e.stopPropagation();
    dispatch("showDiff", { node: tree });
  };
  const dispatchShowDiff = (node) => {
    dispatch("showDiff", { node });
  };
  const showDiff_handler = (e) => dispatchShowDiff(e.detail.node);
  $$self.$$set = ($$props2) => {
    if ("tree" in $$props2) $$invalidate(0, tree = $$props2.tree);
    if ("readOnly" in $$props2) $$invalidate(1, readOnly = $$props2.readOnly);
    if ("enableShowDiff" in $$props2) $$invalidate(2, enableShowDiff = $$props2.enableShowDiff);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*expanded*/
    8) {
      $: $$invalidate(4, arrowDown = expanded);
    }
  };
  return [
    tree,
    readOnly,
    enableShowDiff,
    expanded,
    arrowDown,
    isRoot,
    toggleExpansion,
    toggleCheck,
    dispatchChecked,
    showDiff,
    dispatchShowDiff,
    showDiff_handler
  ];
}
var TreeNode = class extends SvelteComponent {
  constructor(options) {
    super();
    init2(this, options, instance2, create_fragment2, safe_not_equal, { tree: 0, readOnly: 1, enableShowDiff: 2 });
  }
};
var TreeNode_default = TreeNode;

// src/ui/TreeView/TreeView.svelte
function create_fragment3(ctx) {
  let div;
  let node;
  let current;
  node = new TreeNode_default({
    props: {
      tree: (
        /*tree*/
        ctx[0]
      ),
      readOnly: (
        /*readOnly*/
        ctx[1]
      ),
      enableShowDiff: (
        /*enableShowDiff*/
        ctx[2]
      )
    }
  });
  node.$on(
    "toggle",
    /*rebuildTree*/
    ctx[4]
  );
  node.$on(
    "showDiff",
    /*showDiff_handler*/
    ctx[5]
  );
  return {
    c() {
      div = element("div");
      create_component(node.$$.fragment);
    },
    m(target, anchor) {
      insert(target, div, anchor);
      mount_component(node, div, null);
      current = true;
    },
    p(ctx2, [dirty]) {
      const node_changes = {};
      if (dirty & /*tree*/
      1) node_changes.tree = /*tree*/
      ctx2[0];
      if (dirty & /*readOnly*/
      2) node_changes.readOnly = /*readOnly*/
      ctx2[1];
      if (dirty & /*enableShowDiff*/
      4) node_changes.enableShowDiff = /*enableShowDiff*/
      ctx2[2];
      node.$set(node_changes);
    },
    i(local) {
      if (current) return;
      transition_in(node.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(node.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(div);
      }
      destroy_component(node);
    }
  };
}
function rebuildChildren(node, checkAsParent = true) {
  if (node.children) {
    for (const child of node.children) {
      if (checkAsParent) child.checked = !!node.checked;
      rebuildChildren(child, checkAsParent);
    }
    node.indeterminate = node.children.some((c) => c.indeterminate) || node.children.some((c) => !!c.checked) && node.children.some((c) => !c.checked);
  }
}
function instance3($$self, $$props, $$invalidate) {
  let { tree } = $$props;
  let { readOnly = false } = $$props;
  let { enableShowDiff = false } = $$props;
  let { showDiff } = $$props;
  const treeMap = {};
  function initTreeMap(tree2) {
    if (tree2.children) {
      for (const child of tree2.children) {
        treeMap[child.path] = tree2;
        initTreeMap(child);
      }
    }
  }
  initTreeMap(tree);
  function rebuildTree(e, checkAsParent = true) {
    const node = e.detail.node;
    let parent = treeMap[node.path];
    rebuildChildren(node, checkAsParent);
    while (parent) {
      const allCheck = parent?.children?.every((c) => !!c.checked);
      if (allCheck) {
        parent.indeterminate = false;
        parent.checked = true;
      } else {
        const haveCheckedOrIndetermine = parent?.children?.some((c) => !!c.checked || c.indeterminate);
        if (haveCheckedOrIndetermine) {
          parent.indeterminate = true;
        } else {
          parent.indeterminate = false;
        }
        parent.checked = false;
      }
      parent = treeMap[parent.path];
    }
    $$invalidate(0, tree);
  }
  rebuildTree({ detail: { node: tree } }, false);
  const showDiff_handler = (e) => showDiff(e.detail.node.path);
  $$self.$$set = ($$props2) => {
    if ("tree" in $$props2) $$invalidate(0, tree = $$props2.tree);
    if ("readOnly" in $$props2) $$invalidate(1, readOnly = $$props2.readOnly);
    if ("enableShowDiff" in $$props2) $$invalidate(2, enableShowDiff = $$props2.enableShowDiff);
    if ("showDiff" in $$props2) $$invalidate(3, showDiff = $$props2.showDiff);
  };
  return [tree, readOnly, enableShowDiff, showDiff, rebuildTree, showDiff_handler];
}
var TreeView = class extends SvelteComponent {
  constructor(options) {
    super();
    init2(this, options, instance3, create_fragment3, safe_not_equal, {
      tree: 0,
      readOnly: 1,
      enableShowDiff: 2,
      showDiff: 3
    });
  }
};
var TreeView_default = TreeView;

// src/views/PublicationCenter/PublicationCenter.svelte
function get_each_context2(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[30] = list[i];
  return child_ctx;
}
function get_each_context_1(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[33] = list[i];
  return child_ctx;
}
function create_if_block_10(ctx) {
  let hr;
  return {
    c() {
      hr = element("hr");
      attr(hr, "class", "quartz-syncer-publisher-title-separator");
    },
    m(target, anchor) {
      insert(target, hr, anchor);
    },
    d(detaching) {
      if (detaching) {
        detach(hr);
      }
    }
  };
}
function create_else_block2(ctx) {
  let div6;
  let div4;
  let div0;
  let t1;
  let div1;
  let t2_value = `${/*publishedPaths*/
  ctx[6].length} of ${/*unpublishedToPublish*/
  ctx[3].length + /*changedToPublish*/
  ctx[4].length + /*pathsToDelete*/
  ctx[5].length} notes published`;
  let t2;
  let t3;
  let t4;
  let div3;
  let div2;
  let publishProgressBarAction_action;
  let t5;
  let t6;
  let t7;
  let hr;
  let t8;
  let div5;
  let button;
  let current;
  let mounted;
  let dispose;
  let if_block = (
    /*failedPublish*/
    ctx[18].length > 0 && create_if_block_9(ctx)
  );
  let each_value_1 = ensure_array_like(
    /*unpublishedToPublish*/
    ctx[3].concat(
      /*changedToPublish*/
      ctx[4]
    )
  );
  let each_blocks_1 = [];
  for (let i = 0; i < each_value_1.length; i += 1) {
    each_blocks_1[i] = create_each_block_1(get_each_context_1(ctx, each_value_1, i));
  }
  const out = (i) => transition_out(each_blocks_1[i], 1, 1, () => {
    each_blocks_1[i] = null;
  });
  let each_value = ensure_array_like(
    /*pathsToDelete*/
    ctx[5]
  );
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block2(get_each_context2(ctx, each_value, i));
  }
  const out_1 = (i) => transition_out(each_blocks[i], 1, 1, () => {
    each_blocks[i] = null;
  });
  return {
    c() {
      div6 = element("div");
      div4 = element("div");
      div0 = element("div");
      div0.textContent = "Publishing Notes";
      t1 = space();
      div1 = element("div");
      t2 = text(t2_value);
      t3 = space();
      if (if_block) if_block.c();
      t4 = space();
      div3 = element("div");
      div2 = element("div");
      t5 = space();
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        each_blocks_1[i].c();
      }
      t6 = space();
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      t7 = space();
      hr = element("hr");
      t8 = space();
      div5 = element("div");
      button = element("button");
      button.textContent = "DONE";
      attr(div0, "class", "quartz-syncer-publisher-callout-title-inner");
      attr(div2, "class", "quartz-syncer-progress-bar-container");
      attr(div3, "class", "quartz-syncer-publisher-loading-container");
      attr(div4, "class", "quartz-syncer-publisher-callout");
      attr(hr, "class", "quartz-syncer-publisher-footer-separator");
      attr(button, "class", "quartz-syncer-publisher-button");
      attr(div5, "class", "quartz-syncer-publisher-footer");
    },
    m(target, anchor) {
      insert(target, div6, anchor);
      append(div6, div4);
      append(div4, div0);
      append(div4, t1);
      append(div4, div1);
      append(div1, t2);
      append(div4, t3);
      if (if_block) if_block.m(div4, null);
      append(div4, t4);
      append(div4, div3);
      append(div3, div2);
      append(div6, t5);
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        if (each_blocks_1[i]) {
          each_blocks_1[i].m(div6, null);
        }
      }
      append(div6, t6);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(div6, null);
        }
      }
      append(div6, t7);
      append(div6, hr);
      append(div6, t8);
      append(div6, div5);
      append(div5, button);
      current = true;
      if (!mounted) {
        dispose = [
          action_destroyer(publishProgressBarAction_action = /*publishProgressBarAction*/
          ctx[16].call(null, div2)),
          listen(button, "click", function() {
            if (is_function(
              /*close*/
              ctx[1]
            )) ctx[1].apply(this, arguments);
          })
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if ((!current || dirty[0] & /*publishedPaths, unpublishedToPublish, changedToPublish, pathsToDelete*/
      120) && t2_value !== (t2_value = `${/*publishedPaths*/
      ctx[6].length} of ${/*unpublishedToPublish*/
      ctx[3].length + /*changedToPublish*/
      ctx[4].length + /*pathsToDelete*/
      ctx[5].length} notes published`)) set_data(t2, t2_value);
      if (
        /*failedPublish*/
        ctx[18].length > 0
      ) if_block.p(ctx, dirty);
      if (dirty[0] & /*publishedPaths, unpublishedToPublish, changedToPublish, rotatingCog, processingPaths, failedPublish*/
      394328) {
        each_value_1 = ensure_array_like(
          /*unpublishedToPublish*/
          ctx[3].concat(
            /*changedToPublish*/
            ctx[4]
          )
        );
        let i;
        for (i = 0; i < each_value_1.length; i += 1) {
          const child_ctx = get_each_context_1(ctx, each_value_1, i);
          if (each_blocks_1[i]) {
            each_blocks_1[i].p(child_ctx, dirty);
            transition_in(each_blocks_1[i], 1);
          } else {
            each_blocks_1[i] = create_each_block_1(child_ctx);
            each_blocks_1[i].c();
            transition_in(each_blocks_1[i], 1);
            each_blocks_1[i].m(div6, t6);
          }
        }
        group_outros();
        for (i = each_value_1.length; i < each_blocks_1.length; i += 1) {
          out(i);
        }
        check_outros();
      }
      if (dirty[0] & /*publishedPaths, pathsToDelete, rotatingCog, processingPaths*/
      132192) {
        each_value = ensure_array_like(
          /*pathsToDelete*/
          ctx[5]
        );
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context2(ctx, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
            transition_in(each_blocks[i], 1);
          } else {
            each_blocks[i] = create_each_block2(child_ctx);
            each_blocks[i].c();
            transition_in(each_blocks[i], 1);
            each_blocks[i].m(div6, t7);
          }
        }
        group_outros();
        for (i = each_value.length; i < each_blocks.length; i += 1) {
          out_1(i);
        }
        check_outros();
      }
    },
    i(local) {
      if (current) return;
      for (let i = 0; i < each_value_1.length; i += 1) {
        transition_in(each_blocks_1[i]);
      }
      for (let i = 0; i < each_value.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      current = true;
    },
    o(local) {
      each_blocks_1 = each_blocks_1.filter(Boolean);
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        transition_out(each_blocks_1[i]);
      }
      each_blocks = each_blocks.filter(Boolean);
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(div6);
      }
      if (if_block) if_block.d();
      destroy_each(each_blocks_1, detaching);
      destroy_each(each_blocks, detaching);
      mounted = false;
      run_all(dispose);
    }
  };
}
function create_if_block_12(ctx) {
  let treeview0;
  let t0;
  let treeview1;
  let t1;
  let treeview2;
  let t2;
  let treeview3;
  let t3;
  let hr;
  let t4;
  let div;
  let button;
  let current;
  let mounted;
  let dispose;
  treeview0 = new TreeView_default({
    props: {
      tree: (
        /*unpublishedNoteTree*/
        ctx[13] ?? /*emptyNode*/
        ctx[20]
      ),
      showDiff: (
        /*showDiff*/
        ctx[0]
      )
    }
  });
  treeview1 = new TreeView_default({
    props: {
      tree: (
        /*changedNotesTree*/
        ctx[12] ?? /*emptyNode*/
        ctx[20]
      ),
      showDiff: (
        /*showDiff*/
        ctx[0]
      ),
      enableShowDiff: true
    }
  });
  treeview2 = new TreeView_default({
    props: {
      tree: (
        /*deletedNoteTree*/
        ctx[11] ?? /*emptyNode*/
        ctx[20]
      ),
      showDiff: (
        /*showDiff*/
        ctx[0]
      )
    }
  });
  treeview3 = new TreeView_default({
    props: {
      readOnly: true,
      tree: (
        /*publishedNotesTree*/
        ctx[14] ?? /*emptyNode*/
        ctx[20]
      ),
      showDiff: (
        /*showDiff*/
        ctx[0]
      )
    }
  });
  return {
    c() {
      create_component(treeview0.$$.fragment);
      t0 = space();
      create_component(treeview1.$$.fragment);
      t1 = space();
      create_component(treeview2.$$.fragment);
      t2 = space();
      create_component(treeview3.$$.fragment);
      t3 = space();
      hr = element("hr");
      t4 = space();
      div = element("div");
      button = element("button");
      button.textContent = "PUBLISH SELECTED CHANGES";
      attr(hr, "class", "quartz-syncer-publisher-footer-separator");
      attr(button, "class", "quartz-syncer-publisher-button");
      attr(div, "class", "quartz-syncer-publisher-footer");
    },
    m(target, anchor) {
      mount_component(treeview0, target, anchor);
      insert(target, t0, anchor);
      mount_component(treeview1, target, anchor);
      insert(target, t1, anchor);
      mount_component(treeview2, target, anchor);
      insert(target, t2, anchor);
      mount_component(treeview3, target, anchor);
      insert(target, t3, anchor);
      insert(target, hr, anchor);
      insert(target, t4, anchor);
      insert(target, div, anchor);
      append(div, button);
      current = true;
      if (!mounted) {
        dispose = listen(
          button,
          "click",
          /*publishMarkedNotes*/
          ctx[19]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      const treeview0_changes = {};
      if (dirty[0] & /*unpublishedNoteTree*/
      8192) treeview0_changes.tree = /*unpublishedNoteTree*/
      ctx2[13] ?? /*emptyNode*/
      ctx2[20];
      if (dirty[0] & /*showDiff*/
      1) treeview0_changes.showDiff = /*showDiff*/
      ctx2[0];
      treeview0.$set(treeview0_changes);
      const treeview1_changes = {};
      if (dirty[0] & /*changedNotesTree*/
      4096) treeview1_changes.tree = /*changedNotesTree*/
      ctx2[12] ?? /*emptyNode*/
      ctx2[20];
      if (dirty[0] & /*showDiff*/
      1) treeview1_changes.showDiff = /*showDiff*/
      ctx2[0];
      treeview1.$set(treeview1_changes);
      const treeview2_changes = {};
      if (dirty[0] & /*deletedNoteTree*/
      2048) treeview2_changes.tree = /*deletedNoteTree*/
      ctx2[11] ?? /*emptyNode*/
      ctx2[20];
      if (dirty[0] & /*showDiff*/
      1) treeview2_changes.showDiff = /*showDiff*/
      ctx2[0];
      treeview2.$set(treeview2_changes);
      const treeview3_changes = {};
      if (dirty[0] & /*publishedNotesTree*/
      16384) treeview3_changes.tree = /*publishedNotesTree*/
      ctx2[14] ?? /*emptyNode*/
      ctx2[20];
      if (dirty[0] & /*showDiff*/
      1) treeview3_changes.showDiff = /*showDiff*/
      ctx2[0];
      treeview3.$set(treeview3_changes);
    },
    i(local) {
      if (current) return;
      transition_in(treeview0.$$.fragment, local);
      transition_in(treeview1.$$.fragment, local);
      transition_in(treeview2.$$.fragment, local);
      transition_in(treeview3.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(treeview0.$$.fragment, local);
      transition_out(treeview1.$$.fragment, local);
      transition_out(treeview2.$$.fragment, local);
      transition_out(treeview3.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(t0);
        detach(t1);
        detach(t2);
        detach(t3);
        detach(hr);
        detach(t4);
        detach(div);
      }
      destroy_component(treeview0, detaching);
      destroy_component(treeview1, detaching);
      destroy_component(treeview2, detaching);
      destroy_component(treeview3, detaching);
      mounted = false;
      dispose();
    }
  };
}
function create_if_block2(ctx) {
  let div3;
  let div0;
  let loadingProgressBar_action;
  let t0;
  let div1;
  let t1;
  let t2;
  let div2;
  let t3;
  let mounted;
  let dispose;
  return {
    c() {
      div3 = element("div");
      div0 = element("div");
      t0 = space();
      div1 = element("div");
      t1 = text(
        /*progressIndexText*/
        ctx[9]
      );
      t2 = space();
      div2 = element("div");
      t3 = text(
        /*progressText*/
        ctx[8]
      );
      attr(div0, "class", "quartz-syncer-progress-bar-container");
      attr(div1, "class", "quartz-syncer-progress-bar-text");
      attr(div2, "class", "quartz-syncer-progress-bar-text");
      attr(div3, "class", "quartz-syncer-publisher-loading-msg");
    },
    m(target, anchor) {
      insert(target, div3, anchor);
      append(div3, div0);
      append(div3, t0);
      append(div3, div1);
      append(div1, t1);
      append(div3, t2);
      append(div3, div2);
      append(div2, t3);
      if (!mounted) {
        dispose = action_destroyer(loadingProgressBar_action = /*loadingProgressBar*/
        ctx[15].call(null, div0));
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*progressIndexText*/
      512) set_data(
        t1,
        /*progressIndexText*/
        ctx2[9]
      );
      if (dirty[0] & /*progressText*/
      256) set_data(
        t3,
        /*progressText*/
        ctx2[8]
      );
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(div3);
      }
      mounted = false;
      dispose();
    }
  };
}
function create_if_block_9(ctx) {
  let div;
  return {
    c() {
      div = element("div");
      div.textContent = `${`(${/*failedPublish*/
      ctx[18].length} failed)`}`;
    },
    m(target, anchor) {
      insert(target, div, anchor);
    },
    p: noop,
    d(detaching) {
      if (detaching) {
        detach(div);
      }
    }
  };
}
function create_else_block_2(ctx) {
  let icon;
  let current;
  icon = new Icon_default({ props: { name: "clock" } });
  return {
    c() {
      create_component(icon.$$.fragment);
    },
    m(target, anchor) {
      mount_component(icon, target, anchor);
      current = true;
    },
    p: noop,
    i(local) {
      if (current) return;
      transition_in(icon.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(icon.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(icon, detaching);
    }
  };
}
function create_if_block_8(ctx) {
  let icon;
  let current;
  icon = new Icon_default({ props: { name: "cross" } });
  return {
    c() {
      create_component(icon.$$.fragment);
    },
    m(target, anchor) {
      mount_component(icon, target, anchor);
      current = true;
    },
    p: noop,
    i(local) {
      if (current) return;
      transition_in(icon.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(icon.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(icon, detaching);
    }
  };
}
function create_if_block_72(ctx) {
  let icon;
  let current;
  icon = new Icon_default({ props: { name: "check" } });
  return {
    c() {
      create_component(icon.$$.fragment);
    },
    m(target, anchor) {
      mount_component(icon, target, anchor);
      current = true;
    },
    p: noop,
    i(local) {
      if (current) return;
      transition_in(icon.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(icon.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(icon, detaching);
    }
  };
}
function create_if_block_62(ctx) {
  let html_tag;
  let raw_value = (
    /*rotatingCog*/
    ctx[17]()?.outerHTML + ""
  );
  let html_anchor;
  return {
    c() {
      html_tag = new HtmlTag(false);
      html_anchor = empty();
      html_tag.a = html_anchor;
    },
    m(target, anchor) {
      html_tag.m(raw_value, target, anchor);
      insert(target, html_anchor, anchor);
    },
    p: noop,
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(html_anchor);
        html_tag.d();
      }
    }
  };
}
function create_if_block_52(ctx) {
  let span;
  return {
    c() {
      span = element("span");
      span.textContent = "- PUBLISHED";
      attr(span, "class", "quartz-syncer-publisher-published");
    },
    m(target, anchor) {
      insert(target, span, anchor);
    },
    d(detaching) {
      if (detaching) {
        detach(span);
      }
    }
  };
}
function create_each_block_1(ctx) {
  let div;
  let show_if_1;
  let show_if_2;
  let show_if_3;
  let current_block_type_index;
  let if_block0;
  let t0;
  let t1_value = (
    /*note*/
    ctx[33].file.name + ""
  );
  let t1;
  let t2;
  let show_if = (
    /*publishedPaths*/
    ctx[6].includes(
      /*note*/
      ctx[33].getVaultPath()
    )
  );
  let current;
  const if_block_creators = [create_if_block_62, create_if_block_72, create_if_block_8, create_else_block_2];
  const if_blocks = [];
  function select_block_type_1(ctx2, dirty) {
    if (dirty[0] & /*processingPaths, unpublishedToPublish, changedToPublish*/
    1048) show_if_1 = null;
    if (dirty[0] & /*publishedPaths, unpublishedToPublish, changedToPublish*/
    88) show_if_2 = null;
    if (dirty[0] & /*unpublishedToPublish, changedToPublish*/
    24) show_if_3 = null;
    if (show_if_1 == null) show_if_1 = !!/*processingPaths*/
    ctx2[10].includes(
      /*note*/
      ctx2[33].getVaultPath()
    );
    if (show_if_1) return 0;
    if (show_if_2 == null) show_if_2 = !!/*publishedPaths*/
    ctx2[6].includes(
      /*note*/
      ctx2[33].getVaultPath()
    );
    if (show_if_2) return 1;
    if (show_if_3 == null) show_if_3 = !!/*failedPublish*/
    ctx2[18].includes(
      /*note*/
      ctx2[33].getVaultPath()
    );
    if (show_if_3) return 2;
    return 3;
  }
  current_block_type_index = select_block_type_1(ctx, [-1, -1]);
  if_block0 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
  let if_block1 = show_if && create_if_block_52(ctx);
  return {
    c() {
      div = element("div");
      if_block0.c();
      t0 = space();
      t1 = text(t1_value);
      t2 = space();
      if (if_block1) if_block1.c();
      attr(div, "class", "quartz-syncer-publisher-note-list");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      if_blocks[current_block_type_index].m(div, null);
      append(div, t0);
      append(div, t1);
      append(div, t2);
      if (if_block1) if_block1.m(div, null);
      current = true;
    },
    p(ctx2, dirty) {
      let previous_block_index = current_block_type_index;
      current_block_type_index = select_block_type_1(ctx2, dirty);
      if (current_block_type_index === previous_block_index) {
        if_blocks[current_block_type_index].p(ctx2, dirty);
      } else {
        group_outros();
        transition_out(if_blocks[previous_block_index], 1, 1, () => {
          if_blocks[previous_block_index] = null;
        });
        check_outros();
        if_block0 = if_blocks[current_block_type_index];
        if (!if_block0) {
          if_block0 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
          if_block0.c();
        } else {
          if_block0.p(ctx2, dirty);
        }
        transition_in(if_block0, 1);
        if_block0.m(div, t0);
      }
      if ((!current || dirty[0] & /*unpublishedToPublish, changedToPublish*/
      24) && t1_value !== (t1_value = /*note*/
      ctx2[33].file.name + "")) set_data(t1, t1_value);
      if (dirty[0] & /*publishedPaths, unpublishedToPublish, changedToPublish*/
      88) show_if = /*publishedPaths*/
      ctx2[6].includes(
        /*note*/
        ctx2[33].getVaultPath()
      );
      if (show_if) {
        if (if_block1) {
        } else {
          if_block1 = create_if_block_52(ctx2);
          if_block1.c();
          if_block1.m(div, null);
        }
      } else if (if_block1) {
        if_block1.d(1);
        if_block1 = null;
      }
    },
    i(local) {
      if (current) return;
      transition_in(if_block0);
      current = true;
    },
    o(local) {
      transition_out(if_block0);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(div);
      }
      if_blocks[current_block_type_index].d();
      if (if_block1) if_block1.d();
    }
  };
}
function create_else_block_1(ctx) {
  let icon;
  let current;
  icon = new Icon_default({ props: { name: "clock" } });
  return {
    c() {
      create_component(icon.$$.fragment);
    },
    m(target, anchor) {
      mount_component(icon, target, anchor);
      current = true;
    },
    p: noop,
    i(local) {
      if (current) return;
      transition_in(icon.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(icon.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(icon, detaching);
    }
  };
}
function create_if_block_42(ctx) {
  let icon;
  let current;
  icon = new Icon_default({ props: { name: "check" } });
  return {
    c() {
      create_component(icon.$$.fragment);
    },
    m(target, anchor) {
      mount_component(icon, target, anchor);
      current = true;
    },
    p: noop,
    i(local) {
      if (current) return;
      transition_in(icon.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(icon.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(icon, detaching);
    }
  };
}
function create_if_block_32(ctx) {
  let html_tag;
  let raw_value = (
    /*rotatingCog*/
    ctx[17]()?.outerHTML + ""
  );
  let html_anchor;
  return {
    c() {
      html_tag = new HtmlTag(false);
      html_anchor = empty();
      html_tag.a = html_anchor;
    },
    m(target, anchor) {
      html_tag.m(raw_value, target, anchor);
      insert(target, html_anchor, anchor);
    },
    p: noop,
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(html_anchor);
        html_tag.d();
      }
    }
  };
}
function create_if_block_22(ctx) {
  let span;
  return {
    c() {
      span = element("span");
      span.textContent = "- DELETED";
      attr(span, "class", "quartz-syncer-publisher-deleted");
    },
    m(target, anchor) {
      insert(target, span, anchor);
    },
    d(detaching) {
      if (detaching) {
        detach(span);
      }
    }
  };
}
function create_each_block2(ctx) {
  let div;
  let show_if_1;
  let show_if_2;
  let current_block_type_index;
  let if_block0;
  let t0;
  let t1_value = (
    /*path*/
    ctx[30].split("/").last() + ""
  );
  let t1;
  let t2;
  let show_if = (
    /*publishedPaths*/
    ctx[6].includes(
      /*path*/
      ctx[30]
    )
  );
  let current;
  const if_block_creators = [create_if_block_32, create_if_block_42, create_else_block_1];
  const if_blocks = [];
  function select_block_type_2(ctx2, dirty) {
    if (dirty[0] & /*processingPaths, pathsToDelete*/
    1056) show_if_1 = null;
    if (dirty[0] & /*publishedPaths, pathsToDelete*/
    96) show_if_2 = null;
    if (show_if_1 == null) show_if_1 = !!/*processingPaths*/
    ctx2[10].includes(
      /*path*/
      ctx2[30]
    );
    if (show_if_1) return 0;
    if (show_if_2 == null) show_if_2 = !!/*publishedPaths*/
    ctx2[6].includes(
      /*path*/
      ctx2[30]
    );
    if (show_if_2) return 1;
    return 2;
  }
  current_block_type_index = select_block_type_2(ctx, [-1, -1]);
  if_block0 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
  let if_block1 = show_if && create_if_block_22(ctx);
  return {
    c() {
      div = element("div");
      if_block0.c();
      t0 = space();
      t1 = text(t1_value);
      t2 = space();
      if (if_block1) if_block1.c();
      attr(div, "class", "quartz-syncer-publisher-note-list");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      if_blocks[current_block_type_index].m(div, null);
      append(div, t0);
      append(div, t1);
      append(div, t2);
      if (if_block1) if_block1.m(div, null);
      current = true;
    },
    p(ctx2, dirty) {
      let previous_block_index = current_block_type_index;
      current_block_type_index = select_block_type_2(ctx2, dirty);
      if (current_block_type_index === previous_block_index) {
        if_blocks[current_block_type_index].p(ctx2, dirty);
      } else {
        group_outros();
        transition_out(if_blocks[previous_block_index], 1, 1, () => {
          if_blocks[previous_block_index] = null;
        });
        check_outros();
        if_block0 = if_blocks[current_block_type_index];
        if (!if_block0) {
          if_block0 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
          if_block0.c();
        } else {
          if_block0.p(ctx2, dirty);
        }
        transition_in(if_block0, 1);
        if_block0.m(div, t0);
      }
      if ((!current || dirty[0] & /*pathsToDelete*/
      32) && t1_value !== (t1_value = /*path*/
      ctx2[30].split("/").last() + "")) set_data(t1, t1_value);
      if (dirty[0] & /*publishedPaths, pathsToDelete*/
      96) show_if = /*publishedPaths*/
      ctx2[6].includes(
        /*path*/
        ctx2[30]
      );
      if (show_if) {
        if (if_block1) {
        } else {
          if_block1 = create_if_block_22(ctx2);
          if_block1.c();
          if_block1.m(div, null);
        }
      } else if (if_block1) {
        if_block1.d(1);
        if_block1 = null;
      }
    },
    i(local) {
      if (current) return;
      transition_in(if_block0);
      current = true;
    },
    o(local) {
      transition_out(if_block0);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(div);
      }
      if_blocks[current_block_type_index].d();
      if (if_block1) if_block1.d();
    }
  };
}
function create_fragment4(ctx) {
  let div;
  let t;
  let current_block_type_index;
  let if_block1;
  let current;
  let if_block0 = (
    /*publishStatus*/
    ctx[2] && create_if_block_10(ctx)
  );
  const if_block_creators = [create_if_block2, create_if_block_12, create_else_block2];
  const if_blocks = [];
  function select_block_type(ctx2, dirty) {
    if (!/*publishStatus*/
    ctx2[2]) return 0;
    if (!/*showPublishingView*/
    ctx2[7]) return 1;
    return 2;
  }
  current_block_type_index = select_block_type(ctx, [-1, -1]);
  if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
  return {
    c() {
      div = element("div");
      if (if_block0) if_block0.c();
      t = space();
      if_block1.c();
    },
    m(target, anchor) {
      insert(target, div, anchor);
      if (if_block0) if_block0.m(div, null);
      append(div, t);
      if_blocks[current_block_type_index].m(div, null);
      current = true;
    },
    p(ctx2, dirty) {
      if (
        /*publishStatus*/
        ctx2[2]
      ) {
        if (if_block0) {
        } else {
          if_block0 = create_if_block_10(ctx2);
          if_block0.c();
          if_block0.m(div, t);
        }
      } else if (if_block0) {
        if_block0.d(1);
        if_block0 = null;
      }
      let previous_block_index = current_block_type_index;
      current_block_type_index = select_block_type(ctx2, dirty);
      if (current_block_type_index === previous_block_index) {
        if_blocks[current_block_type_index].p(ctx2, dirty);
      } else {
        group_outros();
        transition_out(if_blocks[previous_block_index], 1, 1, () => {
          if_blocks[previous_block_index] = null;
        });
        check_outros();
        if_block1 = if_blocks[current_block_type_index];
        if (!if_block1) {
          if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
          if_block1.c();
        } else {
          if_block1.p(ctx2, dirty);
        }
        transition_in(if_block1, 1);
        if_block1.m(div, null);
      }
    },
    i(local) {
      if (current) return;
      transition_in(if_block1);
      current = true;
    },
    o(local) {
      transition_out(if_block1);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(div);
      }
      if (if_block0) if_block0.d();
      if_blocks[current_block_type_index].d();
    }
  };
}
function instance4($$self, $$props, $$invalidate) {
  let publishedNotesTree;
  let changedNotesTree;
  let deletedNoteTree;
  let unpublishedNoteTree;
  let publishProgress;
  let { publishStatusManager } = $$props;
  let { publisher } = $$props;
  let { showDiff } = $$props;
  let { close } = $$props;
  let publishStatus;
  let showPublishingView = false;
  let progressText = "Preparing to load...";
  let progressIndexText = "Notes processed: 0/0";
  let controller;
  let publishController;
  async function getPublishStatus() {
    $$invalidate(2, publishStatus = await publishStatusManager.getPublishStatus(controller));
  }
  onMount(getPublishStatus);
  function insertIntoTree(tree, filePath) {
    let currentNode = tree;
    const pathComponents = filePath.split("/");
    const isRemoteOnlyFile = publishStatus.deletedNotePaths.some((note) => note.path === filePath);
    for (let i = 0; i < pathComponents.length; i++) {
      const part = pathComponents[i];
      if (!currentNode.children) {
        currentNode.children = [];
      }
      let childNode = currentNode.children.find((child) => child.name === part);
      if (!childNode) {
        childNode = {
          name: part,
          isRoot: false,
          path: pathComponents.slice(0, i + 1).join("/"),
          indeterminate: false,
          checked: isRemoteOnlyFile
        };
        currentNode.children.push(childNode);
      }
      currentNode = childNode;
    }
  }
  function filePathsToTree(filePaths, rootName = "root") {
    const root = {
      name: rootName,
      isRoot: true,
      path: "/",
      indeterminate: false,
      checked: false
    };
    for (const filePath of filePaths) {
      insertIntoTree(root, filePath);
    }
    return root;
  }
  function loadingProgressBar(node) {
    const progressBar = new import_obsidian13.ProgressBarComponent(node);
    controller = {
      setProgress: (percentage) => {
        progressBar.setValue(percentage);
      },
      setIndexText: (indexText) => {
        $$invalidate(9, progressIndexText = indexText);
      },
      setText: (message) => {
        $$invalidate(8, progressText = message);
      }
    };
    return {
      destroy() {
      }
    };
  }
  function publishProgressBarAction(node) {
    const progressBar = new import_obsidian13.ProgressBarComponent(node);
    $$invalidate(23, publishController = {
      setProgress: (progress) => {
        progressBar.setValue(progress);
      },
      setIndexText: () => {
      },
      setText: () => {
      }
    });
    return {
      destroy() {
      }
    };
  }
  const rotatingCog = () => {
    let cog = (0, import_obsidian13.getIcon)("cog");
    cog?.classList.add("quartz-syncer-rotate", "quartz-syncer-cog");
    return cog;
  };
  const traverseTree = (tree) => {
    const paths = [];
    if (tree.children) {
      for (const child of tree.children) {
        paths.push(...traverseTree(child));
      }
    } else {
      if (tree.checked) {
        paths.push(tree.path);
      }
    }
    return paths;
  };
  let unpublishedToPublish = [];
  let changedToPublish = [];
  let pathsToDelete = [];
  let processingPaths = [];
  let publishedPaths = [];
  let failedPublish = [];
  const publishMarkedNotes = async () => {
    if (!unpublishedNoteTree || !changedNotesTree) return;
    if (!publishStatus) {
      throw new Error("Publish status is undefined");
    }
    const unpublishedPaths = traverseTree(unpublishedNoteTree);
    const changedPaths = traverseTree(changedNotesTree);
    $$invalidate(5, pathsToDelete = traverseTree(deletedNoteTree));
    const notesToDelete = pathsToDelete.filter((path) => publishStatus.deletedNotePaths.some((p) => p.path === path));
    const blobsToDelete = pathsToDelete.filter((path) => publishStatus.deletedBlobPaths.some((p) => p.path === path));
    $$invalidate(3, unpublishedToPublish = publishStatus.unpublishedNotes.filter((note) => unpublishedPaths.includes(note.getVaultPath())) ?? []);
    $$invalidate(4, changedToPublish = publishStatus?.changedNotes.filter((note) => changedPaths.includes(note.getVaultPath())) ?? []);
    $$invalidate(7, showPublishingView = true);
    const allNotesToPublish = unpublishedToPublish.concat(changedToPublish);
    $$invalidate(10, processingPaths = [...allNotesToPublish.map((note) => note.getVaultPath())]);
    await publisher.publishBatch(allNotesToPublish);
    $$invalidate(6, publishedPaths = [...processingPaths]);
    $$invalidate(10, processingPaths = []);
    const allPathsToDelete = [...notesToDelete, ...blobsToDelete];
    if (allPathsToDelete.length > 0) {
      $$invalidate(10, processingPaths = [...allPathsToDelete]);
      await publisher.deleteBatch(allPathsToDelete);
      $$invalidate(6, publishedPaths = [...publishedPaths, ...allPathsToDelete]);
      $$invalidate(10, processingPaths = []);
    }
  };
  const emptyNode = {
    name: "",
    isRoot: false,
    path: "",
    indeterminate: false,
    checked: false
  };
  $$self.$$set = ($$props2) => {
    if ("publishStatusManager" in $$props2) $$invalidate(21, publishStatusManager = $$props2.publishStatusManager);
    if ("publisher" in $$props2) $$invalidate(22, publisher = $$props2.publisher);
    if ("showDiff" in $$props2) $$invalidate(0, showDiff = $$props2.showDiff);
    if ("close" in $$props2) $$invalidate(1, close = $$props2.close);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty[0] & /*publishStatus*/
    4) {
      $: $$invalidate(14, publishedNotesTree = publishStatus && filePathsToTree(publishStatus.publishedNotes.map((note) => note.getVaultPath()), "Unchanged notes" + (publishStatus.publishedNotes.length > 0 ? ` (${publishStatus.publishedNotes.length === 1 ? "1 note" : `${publishStatus.publishedNotes.length} notes`})` : "")));
    }
    if ($$self.$$.dirty[0] & /*publishStatus*/
    4) {
      $: $$invalidate(12, changedNotesTree = publishStatus && filePathsToTree(publishStatus.changedNotes.map((note) => note.getVaultPath()), "Changed notes" + (publishStatus.changedNotes.length > 0 ? ` (${publishStatus.changedNotes.length === 1 ? "1 note" : `${publishStatus.changedNotes.length} notes`})` : "")));
    }
    if ($$self.$$.dirty[0] & /*publishStatus*/
    4) {
      $: $$invalidate(11, deletedNoteTree = publishStatus && filePathsToTree([...publishStatus.deletedNotePaths, ...publishStatus.deletedBlobPaths].map((path) => path.path), "Published notes (select to unpublish)" + (publishStatus.changedNotes.length + publishStatus.publishedNotes.length > 0 ? ` (${publishStatus.changedNotes.length + publishStatus.publishedNotes.length === 1 ? "1 note" : `${publishStatus.changedNotes.length + publishStatus.publishedNotes.length} notes`})` : "")));
    }
    if ($$self.$$.dirty[0] & /*publishStatus*/
    4) {
      $: $$invalidate(13, unpublishedNoteTree = publishStatus && filePathsToTree(publishStatus.unpublishedNotes.map((note) => note.getVaultPath()), "Unpublished notes" + (publishStatus.unpublishedNotes.length > 0 ? ` (${publishStatus.unpublishedNotes.length === 1 ? "1 note" : `${publishStatus.unpublishedNotes.length} notes`})` : "")));
    }
    if ($$self.$$.dirty[0] & /*publishedPaths, unpublishedToPublish, changedToPublish, pathsToDelete*/
    120) {
      $: $$invalidate(24, publishProgress = (publishedPaths.length + failedPublish.length) / (unpublishedToPublish.length + changedToPublish.length + pathsToDelete.length) * 100);
    }
    if ($$self.$$.dirty[0] & /*publishController, publishProgress*/
    25165824) {
      $: publishController?.setProgress(publishProgress);
    }
  };
  return [
    showDiff,
    close,
    publishStatus,
    unpublishedToPublish,
    changedToPublish,
    pathsToDelete,
    publishedPaths,
    showPublishingView,
    progressText,
    progressIndexText,
    processingPaths,
    deletedNoteTree,
    changedNotesTree,
    unpublishedNoteTree,
    publishedNotesTree,
    loadingProgressBar,
    publishProgressBarAction,
    rotatingCog,
    failedPublish,
    publishMarkedNotes,
    emptyNode,
    publishStatusManager,
    publisher,
    publishController,
    publishProgress
  ];
}
var PublicationCenter = class extends SvelteComponent {
  constructor(options) {
    super();
    init2(
      this,
      options,
      instance4,
      create_fragment4,
      safe_not_equal,
      {
        publishStatusManager: 21,
        publisher: 22,
        showDiff: 0,
        close: 1
      },
      null,
      [-1, -1]
    );
  }
};
var PublicationCenter_default = PublicationCenter;

// src/views/PublicationCenter/DiffView.svelte
init_esbuild_buffer_shim();

// node_modules/diff/libesm/index.js
init_esbuild_buffer_shim();

// node_modules/diff/libesm/diff/base.js
init_esbuild_buffer_shim();
var Diff = class {
  diff(oldStr, newStr, options = {}) {
    let callback;
    if (typeof options === "function") {
      callback = options;
      options = {};
    } else if ("callback" in options) {
      callback = options.callback;
    }
    const oldString = this.castInput(oldStr, options);
    const newString = this.castInput(newStr, options);
    const oldTokens = this.removeEmpty(this.tokenize(oldString, options));
    const newTokens = this.removeEmpty(this.tokenize(newString, options));
    return this.diffWithOptionsObj(oldTokens, newTokens, options, callback);
  }
  diffWithOptionsObj(oldTokens, newTokens, options, callback) {
    var _a;
    const done = (value) => {
      value = this.postProcess(value, options);
      if (callback) {
        setTimeout(function() {
          callback(value);
        }, 0);
        return void 0;
      } else {
        return value;
      }
    };
    const newLen = newTokens.length, oldLen = oldTokens.length;
    let editLength = 1;
    let maxEditLength = newLen + oldLen;
    if (options.maxEditLength != null) {
      maxEditLength = Math.min(maxEditLength, options.maxEditLength);
    }
    const maxExecutionTime = (_a = options.timeout) !== null && _a !== void 0 ? _a : Infinity;
    const abortAfterTimestamp = Date.now() + maxExecutionTime;
    const bestPath = [{ oldPos: -1, lastComponent: void 0 }];
    let newPos = this.extractCommon(bestPath[0], newTokens, oldTokens, 0, options);
    if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
      return done(this.buildValues(bestPath[0].lastComponent, newTokens, oldTokens));
    }
    let minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity;
    const execEditLength = () => {
      for (let diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) {
        let basePath;
        const removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1];
        if (removePath) {
          bestPath[diagonalPath - 1] = void 0;
        }
        let canAdd = false;
        if (addPath) {
          const addPathNewPos = addPath.oldPos - diagonalPath;
          canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen;
        }
        const canRemove = removePath && removePath.oldPos + 1 < oldLen;
        if (!canAdd && !canRemove) {
          bestPath[diagonalPath] = void 0;
          continue;
        }
        if (!canRemove || canAdd && removePath.oldPos < addPath.oldPos) {
          basePath = this.addToPath(addPath, true, false, 0, options);
        } else {
          basePath = this.addToPath(removePath, false, true, 1, options);
        }
        newPos = this.extractCommon(basePath, newTokens, oldTokens, diagonalPath, options);
        if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
          return done(this.buildValues(basePath.lastComponent, newTokens, oldTokens)) || true;
        } else {
          bestPath[diagonalPath] = basePath;
          if (basePath.oldPos + 1 >= oldLen) {
            maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1);
          }
          if (newPos + 1 >= newLen) {
            minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1);
          }
        }
      }
      editLength++;
    };
    if (callback) {
      (function exec() {
        setTimeout(function() {
          if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) {
            return callback(void 0);
          }
          if (!execEditLength()) {
            exec();
          }
        }, 0);
      })();
    } else {
      while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) {
        const ret = execEditLength();
        if (ret) {
          return ret;
        }
      }
    }
  }
  addToPath(path, added, removed, oldPosInc, options) {
    const last = path.lastComponent;
    if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
      return {
        oldPos: path.oldPos + oldPosInc,
        lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
      };
    } else {
      return {
        oldPos: path.oldPos + oldPosInc,
        lastComponent: { count: 1, added, removed, previousComponent: last }
      };
    }
  }
  extractCommon(basePath, newTokens, oldTokens, diagonalPath, options) {
    const newLen = newTokens.length, oldLen = oldTokens.length;
    let oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0;
    while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(oldTokens[oldPos + 1], newTokens[newPos + 1], options)) {
      newPos++;
      oldPos++;
      commonCount++;
      if (options.oneChangePerToken) {
        basePath.lastComponent = { count: 1, previousComponent: basePath.lastComponent, added: false, removed: false };
      }
    }
    if (commonCount && !options.oneChangePerToken) {
      basePath.lastComponent = { count: commonCount, previousComponent: basePath.lastComponent, added: false, removed: false };
    }
    basePath.oldPos = oldPos;
    return newPos;
  }
  equals(left, right, options) {
    if (options.comparator) {
      return options.comparator(left, right);
    } else {
      return left === right || !!options.ignoreCase && left.toLowerCase() === right.toLowerCase();
    }
  }
  removeEmpty(array) {
    const ret = [];
    for (let i = 0; i < array.length; i++) {
      if (array[i]) {
        ret.push(array[i]);
      }
    }
    return ret;
  }
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  castInput(value, options) {
    return value;
  }
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  tokenize(value, options) {
    return Array.from(value);
  }
  join(chars) {
    return chars.join("");
  }
  postProcess(changeObjects, options) {
    return changeObjects;
  }
  get useLongestToken() {
    return false;
  }
  buildValues(lastComponent, newTokens, oldTokens) {
    const components = [];
    let nextComponent;
    while (lastComponent) {
      components.push(lastComponent);
      nextComponent = lastComponent.previousComponent;
      delete lastComponent.previousComponent;
      lastComponent = nextComponent;
    }
    components.reverse();
    const componentLen = components.length;
    let componentPos = 0, newPos = 0, oldPos = 0;
    for (; componentPos < componentLen; componentPos++) {
      const component = components[componentPos];
      if (!component.removed) {
        if (!component.added && this.useLongestToken) {
          let value = newTokens.slice(newPos, newPos + component.count);
          value = value.map(function(value2, i) {
            const oldValue = oldTokens[oldPos + i];
            return oldValue.length > value2.length ? oldValue : value2;
          });
          component.value = this.join(value);
        } else {
          component.value = this.join(newTokens.slice(newPos, newPos + component.count));
        }
        newPos += component.count;
        if (!component.added) {
          oldPos += component.count;
        }
      } else {
        component.value = this.join(oldTokens.slice(oldPos, oldPos + component.count));
        oldPos += component.count;
      }
    }
    return components;
  }
};

// node_modules/diff/libesm/diff/line.js
init_esbuild_buffer_shim();
var LineDiff = class extends Diff {
  constructor() {
    super(...arguments);
    this.tokenize = tokenize;
  }
  equals(left, right, options) {
    if (options.ignoreWhitespace) {
      if (!options.newlineIsToken || !left.includes("\n")) {
        left = left.trim();
      }
      if (!options.newlineIsToken || !right.includes("\n")) {
        right = right.trim();
      }
    } else if (options.ignoreNewlineAtEof && !options.newlineIsToken) {
      if (left.endsWith("\n")) {
        left = left.slice(0, -1);
      }
      if (right.endsWith("\n")) {
        right = right.slice(0, -1);
      }
    }
    return super.equals(left, right, options);
  }
};
var lineDiff = new LineDiff();
function diffLines(oldStr, newStr, options) {
  return lineDiff.diff(oldStr, newStr, options);
}
function tokenize(value, options) {
  if (options.stripTrailingCr) {
    value = value.replace(/\r\n/g, "\n");
  }
  const retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/);
  if (!linesAndNewlines[linesAndNewlines.length - 1]) {
    linesAndNewlines.pop();
  }
  for (let i = 0; i < linesAndNewlines.length; i++) {
    const line = linesAndNewlines[i];
    if (i % 2 && !options.newlineIsToken) {
      retLines[retLines.length - 1] += line;
    } else {
      retLines.push(line);
    }
  }
  return retLines;
}

// src/views/PublicationCenter/DiffView.svelte
var import_obsidian14 = require("obsidian");
function add_css(target) {
  append_styles(target, "svelte-1o1t5ba", ".diff-view-wrapper.svelte-1o1t5ba.svelte-1o1t5ba{font-family:var(--font-monospace);font-size:12px;border:1px solid var(--background-modifier-border);border-radius:6px;overflow:hidden}.diff-header.svelte-1o1t5ba.svelte-1o1t5ba{display:flex;justify-content:space-between;align-items:center;padding:8px 12px;background:var(--background-secondary);border-bottom:1px solid var(--background-modifier-border)}.diff-info.svelte-1o1t5ba.svelte-1o1t5ba{display:flex;align-items:center;gap:12px}.diff-stats.svelte-1o1t5ba.svelte-1o1t5ba{display:flex;gap:8px;font-weight:500}.additions.svelte-1o1t5ba.svelte-1o1t5ba{color:var(--color-green)}.deletions.svelte-1o1t5ba.svelte-1o1t5ba{color:var(--color-red)}.diff-filename.svelte-1o1t5ba.svelte-1o1t5ba{color:var(--text-muted)}.diff-controls.svelte-1o1t5ba.svelte-1o1t5ba{display:flex;gap:4px}.view-toggle.svelte-1o1t5ba.svelte-1o1t5ba{padding:4px 12px;border:1px solid var(--background-modifier-border);background:var(--background-primary);border-radius:4px;cursor:pointer;font-size:11px;color:var(--text-muted)}.view-toggle.svelte-1o1t5ba.svelte-1o1t5ba:hover{background:var(--background-modifier-hover)}.view-toggle.active.svelte-1o1t5ba.svelte-1o1t5ba{background:var(--interactive-accent);color:var(--text-on-accent);border-color:var(--interactive-accent)}.diff-split.svelte-1o1t5ba.svelte-1o1t5ba{display:flex;height:50vh}.diff-pane.svelte-1o1t5ba.svelte-1o1t5ba{flex:1;display:flex;flex-direction:column;min-width:0;overflow:hidden}.diff-pane.svelte-1o1t5ba.svelte-1o1t5ba:first-child{border-right:1px solid var(--background-modifier-border)}.diff-pane-header.svelte-1o1t5ba.svelte-1o1t5ba{padding:6px 12px;background:var(--background-secondary);border-bottom:1px solid var(--background-modifier-border);font-size:11px;font-weight:500;color:var(--text-muted)}.diff-scroll-area.svelte-1o1t5ba.svelte-1o1t5ba{flex:1;overflow:auto}.diff-unified-scroll.svelte-1o1t5ba.svelte-1o1t5ba{height:50vh;overflow:auto}.diff-lines-inner.svelte-1o1t5ba.svelte-1o1t5ba{display:inline-block;min-width:100%}.diff-line.svelte-1o1t5ba.svelte-1o1t5ba{display:flex;line-height:20px;white-space:pre}.diff-line.added.svelte-1o1t5ba.svelte-1o1t5ba{--fallback-color-added:46, 160, 67;background:rgba(\n			var(\n				--background-modifier-success-rgb,\n				var(--color-green-rgb, var(--fallback-color-added))\n			),\n			0.15\n		)}.diff-line.removed.svelte-1o1t5ba.svelte-1o1t5ba{--fallback-color-removed:248, 81, 73;background:rgba(\n			var(\n				--background-modifier-error-rgb,\n				var(--color-red-rgb, var(--fallback-color-removed))\n			),\n			0.15\n		)}.diff-line.empty.svelte-1o1t5ba.svelte-1o1t5ba{background:var(--background-secondary)}.line-num.svelte-1o1t5ba.svelte-1o1t5ba{min-width:40px;padding:0 8px;text-align:right;color:var(--text-faint);background:var(--background-secondary);user-select:none;border-right:1px solid var(--background-modifier-border);flex-shrink:0}.diff-line.added.svelte-1o1t5ba>.line-num.svelte-1o1t5ba,.diff-line.removed.svelte-1o1t5ba>.line-num.svelte-1o1t5ba{background:transparent}.line-indicator.svelte-1o1t5ba.svelte-1o1t5ba{width:20px;min-width:20px;text-align:center;color:var(--text-muted);user-select:none;flex-shrink:0}.diff-line.added.svelte-1o1t5ba .line-indicator.svelte-1o1t5ba{color:var(--color-green);font-weight:bold}.diff-line.removed.svelte-1o1t5ba .line-indicator.svelte-1o1t5ba{color:var(--color-red);font-weight:bold}.line-content.svelte-1o1t5ba.svelte-1o1t5ba{flex:1;padding:0 8px}.diff-footer.svelte-1o1t5ba.svelte-1o1t5ba{padding:8px 12px;background:var(--background-secondary);border-top:1px solid var(--background-modifier-border);font-size:11px;color:var(--text-muted);font-family:var(--font-interface)}");
}
function get_each_context_2(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[24] = list[i];
  return child_ctx;
}
function get_each_context3(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[19] = list[i];
  return child_ctx;
}
function get_each_context_12(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[19] = list[i];
  return child_ctx;
}
function create_if_block_33(ctx) {
  let span;
  let t;
  return {
    c() {
      span = element("span");
      t = text(
        /*fileName*/
        ctx[0]
      );
      attr(span, "class", "diff-filename svelte-1o1t5ba");
    },
    m(target, anchor) {
      insert(target, span, anchor);
      append(span, t);
    },
    p(ctx2, dirty) {
      if (dirty & /*fileName*/
      1) set_data(
        t,
        /*fileName*/
        ctx2[0]
      );
    },
    d(detaching) {
      if (detaching) {
        detach(span);
      }
    }
  };
}
function create_else_block3(ctx) {
  let div1;
  let div0;
  let each_value_2 = ensure_array_like(
    /*unifiedLines*/
    ctx[4]
  );
  let each_blocks = [];
  for (let i = 0; i < each_value_2.length; i += 1) {
    each_blocks[i] = create_each_block_2(get_each_context_2(ctx, each_value_2, i));
  }
  return {
    c() {
      div1 = element("div");
      div0 = element("div");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      attr(div0, "class", "diff-lines-inner svelte-1o1t5ba");
      attr(div1, "class", "diff-unified-scroll svelte-1o1t5ba");
    },
    m(target, anchor) {
      insert(target, div1, anchor);
      append(div1, div0);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(div0, null);
        }
      }
    },
    p(ctx2, dirty) {
      if (dirty & /*unifiedLines*/
      16) {
        each_value_2 = ensure_array_like(
          /*unifiedLines*/
          ctx2[4]
        );
        let i;
        for (i = 0; i < each_value_2.length; i += 1) {
          const child_ctx = get_each_context_2(ctx2, each_value_2, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block_2(child_ctx);
            each_blocks[i].c();
            each_blocks[i].m(div0, null);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value_2.length;
      }
    },
    d(detaching) {
      if (detaching) {
        detach(div1);
      }
      destroy_each(each_blocks, detaching);
    }
  };
}
function create_if_block3(ctx) {
  let div8;
  let div3;
  let div0;
  let t1;
  let div2;
  let div1;
  let leftPaneAction_action;
  let t2;
  let div7;
  let div4;
  let t4;
  let div6;
  let div5;
  let rightPaneAction_action;
  let mounted;
  let dispose;
  let each_value_1 = ensure_array_like(
    /*splitLines*/
    ctx[5]
  );
  let each_blocks_1 = [];
  for (let i = 0; i < each_value_1.length; i += 1) {
    each_blocks_1[i] = create_each_block_12(get_each_context_12(ctx, each_value_1, i));
  }
  let each_value = ensure_array_like(
    /*splitLines*/
    ctx[5]
  );
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block3(get_each_context3(ctx, each_value, i));
  }
  return {
    c() {
      div8 = element("div");
      div3 = element("div");
      div0 = element("div");
      div0.textContent = "Remote (Published)";
      t1 = space();
      div2 = element("div");
      div1 = element("div");
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        each_blocks_1[i].c();
      }
      t2 = space();
      div7 = element("div");
      div4 = element("div");
      div4.textContent = "Local (Current)";
      t4 = space();
      div6 = element("div");
      div5 = element("div");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      attr(div0, "class", "diff-pane-header svelte-1o1t5ba");
      attr(div1, "class", "diff-lines-inner svelte-1o1t5ba");
      attr(div2, "class", "diff-scroll-area svelte-1o1t5ba");
      attr(div3, "class", "diff-pane svelte-1o1t5ba");
      attr(div4, "class", "diff-pane-header svelte-1o1t5ba");
      attr(div5, "class", "diff-lines-inner svelte-1o1t5ba");
      attr(div6, "class", "diff-scroll-area svelte-1o1t5ba");
      attr(div7, "class", "diff-pane svelte-1o1t5ba");
      attr(div8, "class", "diff-split svelte-1o1t5ba");
    },
    m(target, anchor) {
      insert(target, div8, anchor);
      append(div8, div3);
      append(div3, div0);
      append(div3, t1);
      append(div3, div2);
      append(div2, div1);
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        if (each_blocks_1[i]) {
          each_blocks_1[i].m(div1, null);
        }
      }
      append(div8, t2);
      append(div8, div7);
      append(div7, div4);
      append(div7, t4);
      append(div7, div6);
      append(div6, div5);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(div5, null);
        }
      }
      if (!mounted) {
        dispose = [
          action_destroyer(leftPaneAction_action = /*leftPaneAction*/
          ctx[6].call(null, div2)),
          action_destroyer(rightPaneAction_action = /*rightPaneAction*/
          ctx[7].call(null, div6))
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty & /*splitLines*/
      32) {
        each_value_1 = ensure_array_like(
          /*splitLines*/
          ctx2[5]
        );
        let i;
        for (i = 0; i < each_value_1.length; i += 1) {
          const child_ctx = get_each_context_12(ctx2, each_value_1, i);
          if (each_blocks_1[i]) {
            each_blocks_1[i].p(child_ctx, dirty);
          } else {
            each_blocks_1[i] = create_each_block_12(child_ctx);
            each_blocks_1[i].c();
            each_blocks_1[i].m(div1, null);
          }
        }
        for (; i < each_blocks_1.length; i += 1) {
          each_blocks_1[i].d(1);
        }
        each_blocks_1.length = each_value_1.length;
      }
      if (dirty & /*splitLines*/
      32) {
        each_value = ensure_array_like(
          /*splitLines*/
          ctx2[5]
        );
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context3(ctx2, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block3(child_ctx);
            each_blocks[i].c();
            each_blocks[i].m(div5, null);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value.length;
      }
    },
    d(detaching) {
      if (detaching) {
        detach(div8);
      }
      destroy_each(each_blocks_1, detaching);
      destroy_each(each_blocks, detaching);
      mounted = false;
      run_all(dispose);
    }
  };
}
function create_else_block_12(ctx) {
  let t_value = " ";
  let t;
  return {
    c() {
      t = text(t_value);
    },
    m(target, anchor) {
      insert(target, t, anchor);
    },
    d(detaching) {
      if (detaching) {
        detach(t);
      }
    }
  };
}
function create_if_block_23(ctx) {
  let t;
  return {
    c() {
      t = text("-");
    },
    m(target, anchor) {
      insert(target, t, anchor);
    },
    d(detaching) {
      if (detaching) {
        detach(t);
      }
    }
  };
}
function create_if_block_13(ctx) {
  let t;
  return {
    c() {
      t = text("+");
    },
    m(target, anchor) {
      insert(target, t, anchor);
    },
    d(detaching) {
      if (detaching) {
        detach(t);
      }
    }
  };
}
function create_each_block_2(ctx) {
  let div;
  let span0;
  let t0_value = (
    /*line*/
    (ctx[24].oldLineNum ?? "") + ""
  );
  let t0;
  let t1;
  let span1;
  let t2_value = (
    /*line*/
    (ctx[24].newLineNum ?? "") + ""
  );
  let t2;
  let t3;
  let span2;
  let t4;
  let span3;
  let t5_value = (
    /*line*/
    ctx[24].content + ""
  );
  let t5;
  let t6;
  function select_block_type_1(ctx2, dirty) {
    if (
      /*line*/
      ctx2[24].type === "added"
    ) return create_if_block_13;
    if (
      /*line*/
      ctx2[24].type === "removed"
    ) return create_if_block_23;
    return create_else_block_12;
  }
  let current_block_type = select_block_type_1(ctx, -1);
  let if_block = current_block_type(ctx);
  return {
    c() {
      div = element("div");
      span0 = element("span");
      t0 = text(t0_value);
      t1 = space();
      span1 = element("span");
      t2 = text(t2_value);
      t3 = space();
      span2 = element("span");
      if_block.c();
      t4 = space();
      span3 = element("span");
      t5 = text(t5_value);
      t6 = space();
      attr(span0, "class", "line-num svelte-1o1t5ba");
      attr(span1, "class", "line-num svelte-1o1t5ba");
      attr(span2, "class", "line-indicator svelte-1o1t5ba");
      attr(span3, "class", "line-content svelte-1o1t5ba");
      attr(div, "class", "diff-line svelte-1o1t5ba");
      toggle_class(
        div,
        "added",
        /*line*/
        ctx[24].type === "added"
      );
      toggle_class(
        div,
        "removed",
        /*line*/
        ctx[24].type === "removed"
      );
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, span0);
      append(span0, t0);
      append(div, t1);
      append(div, span1);
      append(span1, t2);
      append(div, t3);
      append(div, span2);
      if_block.m(span2, null);
      append(div, t4);
      append(div, span3);
      append(span3, t5);
      append(div, t6);
    },
    p(ctx2, dirty) {
      if (dirty & /*unifiedLines*/
      16 && t0_value !== (t0_value = /*line*/
      (ctx2[24].oldLineNum ?? "") + "")) set_data(t0, t0_value);
      if (dirty & /*unifiedLines*/
      16 && t2_value !== (t2_value = /*line*/
      (ctx2[24].newLineNum ?? "") + "")) set_data(t2, t2_value);
      if (current_block_type !== (current_block_type = select_block_type_1(ctx2, dirty))) {
        if_block.d(1);
        if_block = current_block_type(ctx2);
        if (if_block) {
          if_block.c();
          if_block.m(span2, null);
        }
      }
      if (dirty & /*unifiedLines*/
      16 && t5_value !== (t5_value = /*line*/
      ctx2[24].content + "")) set_data(t5, t5_value);
      if (dirty & /*unifiedLines*/
      16) {
        toggle_class(
          div,
          "added",
          /*line*/
          ctx2[24].type === "added"
        );
      }
      if (dirty & /*unifiedLines*/
      16) {
        toggle_class(
          div,
          "removed",
          /*line*/
          ctx2[24].type === "removed"
        );
      }
    },
    d(detaching) {
      if (detaching) {
        detach(div);
      }
      if_block.d();
    }
  };
}
function create_each_block_12(ctx) {
  let div;
  let span0;
  let t0_value = (
    /*row*/
    (ctx[19].leftLineNum ?? "") + ""
  );
  let t0;
  let t1;
  let span1;
  let t2_value = (
    /*row*/
    ctx[19].left?.type === "removed" ? "-" : " "
  );
  let t2;
  let t3;
  let span2;
  let t4_value = (
    /*row*/
    (ctx[19].left?.content ?? "") + ""
  );
  let t4;
  let t5;
  return {
    c() {
      div = element("div");
      span0 = element("span");
      t0 = text(t0_value);
      t1 = space();
      span1 = element("span");
      t2 = text(t2_value);
      t3 = space();
      span2 = element("span");
      t4 = text(t4_value);
      t5 = space();
      attr(span0, "class", "line-num svelte-1o1t5ba");
      attr(span1, "class", "line-indicator svelte-1o1t5ba");
      attr(span2, "class", "line-content svelte-1o1t5ba");
      attr(div, "class", "diff-line svelte-1o1t5ba");
      toggle_class(
        div,
        "removed",
        /*row*/
        ctx[19].left?.type === "removed"
      );
      toggle_class(
        div,
        "empty",
        /*row*/
        ctx[19].left === null
      );
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, span0);
      append(span0, t0);
      append(div, t1);
      append(div, span1);
      append(span1, t2);
      append(div, t3);
      append(div, span2);
      append(span2, t4);
      append(div, t5);
    },
    p(ctx2, dirty) {
      if (dirty & /*splitLines*/
      32 && t0_value !== (t0_value = /*row*/
      (ctx2[19].leftLineNum ?? "") + "")) set_data(t0, t0_value);
      if (dirty & /*splitLines*/
      32 && t2_value !== (t2_value = /*row*/
      ctx2[19].left?.type === "removed" ? "-" : " ")) set_data(t2, t2_value);
      if (dirty & /*splitLines*/
      32 && t4_value !== (t4_value = /*row*/
      (ctx2[19].left?.content ?? "") + "")) set_data(t4, t4_value);
      if (dirty & /*splitLines*/
      32) {
        toggle_class(
          div,
          "removed",
          /*row*/
          ctx2[19].left?.type === "removed"
        );
      }
      if (dirty & /*splitLines*/
      32) {
        toggle_class(
          div,
          "empty",
          /*row*/
          ctx2[19].left === null
        );
      }
    },
    d(detaching) {
      if (detaching) {
        detach(div);
      }
    }
  };
}
function create_each_block3(ctx) {
  let div;
  let span0;
  let t0_value = (
    /*row*/
    (ctx[19].rightLineNum ?? "") + ""
  );
  let t0;
  let t1;
  let span1;
  let t2_value = (
    /*row*/
    ctx[19].right?.type === "added" ? "+" : " "
  );
  let t2;
  let t3;
  let span2;
  let t4_value = (
    /*row*/
    (ctx[19].right?.content ?? "") + ""
  );
  let t4;
  let t5;
  return {
    c() {
      div = element("div");
      span0 = element("span");
      t0 = text(t0_value);
      t1 = space();
      span1 = element("span");
      t2 = text(t2_value);
      t3 = space();
      span2 = element("span");
      t4 = text(t4_value);
      t5 = space();
      attr(span0, "class", "line-num svelte-1o1t5ba");
      attr(span1, "class", "line-indicator svelte-1o1t5ba");
      attr(span2, "class", "line-content svelte-1o1t5ba");
      attr(div, "class", "diff-line svelte-1o1t5ba");
      toggle_class(
        div,
        "added",
        /*row*/
        ctx[19].right?.type === "added"
      );
      toggle_class(
        div,
        "empty",
        /*row*/
        ctx[19].right === null
      );
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, span0);
      append(span0, t0);
      append(div, t1);
      append(div, span1);
      append(span1, t2);
      append(div, t3);
      append(div, span2);
      append(span2, t4);
      append(div, t5);
    },
    p(ctx2, dirty) {
      if (dirty & /*splitLines*/
      32 && t0_value !== (t0_value = /*row*/
      (ctx2[19].rightLineNum ?? "") + "")) set_data(t0, t0_value);
      if (dirty & /*splitLines*/
      32 && t2_value !== (t2_value = /*row*/
      ctx2[19].right?.type === "added" ? "+" : " ")) set_data(t2, t2_value);
      if (dirty & /*splitLines*/
      32 && t4_value !== (t4_value = /*row*/
      (ctx2[19].right?.content ?? "") + "")) set_data(t4, t4_value);
      if (dirty & /*splitLines*/
      32) {
        toggle_class(
          div,
          "added",
          /*row*/
          ctx2[19].right?.type === "added"
        );
      }
      if (dirty & /*splitLines*/
      32) {
        toggle_class(
          div,
          "empty",
          /*row*/
          ctx2[19].right === null
        );
      }
    },
    d(detaching) {
      if (detaching) {
        detach(div);
      }
    }
  };
}
function create_fragment5(ctx) {
  let div4;
  let div2;
  let div0;
  let span2;
  let span0;
  let t0;
  let t1;
  let t2;
  let span1;
  let t3;
  let t4;
  let t5;
  let t6;
  let div1;
  let button0;
  let t8;
  let button1;
  let t10;
  let t11;
  let div3;
  let mounted;
  let dispose;
  let if_block0 = (
    /*fileName*/
    ctx[0] && create_if_block_33(ctx)
  );
  function select_block_type(ctx2, dirty) {
    if (
      /*viewMode*/
      ctx2[1] === "split"
    ) return create_if_block3;
    return create_else_block3;
  }
  let current_block_type = select_block_type(ctx, -1);
  let if_block1 = current_block_type(ctx);
  return {
    c() {
      div4 = element("div");
      div2 = element("div");
      div0 = element("div");
      span2 = element("span");
      span0 = element("span");
      t0 = text("+");
      t1 = text(
        /*additions*/
        ctx[3]
      );
      t2 = space();
      span1 = element("span");
      t3 = text("-");
      t4 = text(
        /*deletions*/
        ctx[2]
      );
      t5 = space();
      if (if_block0) if_block0.c();
      t6 = space();
      div1 = element("div");
      button0 = element("button");
      button0.textContent = "Split";
      t8 = space();
      button1 = element("button");
      button1.textContent = "Unified";
      t10 = space();
      if_block1.c();
      t11 = space();
      div3 = element("div");
      div3.textContent = "Differences between your local file and the published file. Content may\n		differ slightly due to plugin processing.";
      attr(span0, "class", "additions svelte-1o1t5ba");
      attr(span1, "class", "deletions svelte-1o1t5ba");
      attr(span2, "class", "diff-stats svelte-1o1t5ba");
      attr(div0, "class", "diff-info svelte-1o1t5ba");
      attr(button0, "class", "view-toggle svelte-1o1t5ba");
      toggle_class(
        button0,
        "active",
        /*viewMode*/
        ctx[1] === "split"
      );
      attr(button1, "class", "view-toggle svelte-1o1t5ba");
      toggle_class(
        button1,
        "active",
        /*viewMode*/
        ctx[1] === "unified"
      );
      attr(div1, "class", "diff-controls svelte-1o1t5ba");
      attr(div2, "class", "diff-header svelte-1o1t5ba");
      attr(div3, "class", "diff-footer svelte-1o1t5ba");
      attr(div4, "class", "quartz-syncer-diff-view diff-view-wrapper svelte-1o1t5ba");
    },
    m(target, anchor) {
      insert(target, div4, anchor);
      append(div4, div2);
      append(div2, div0);
      append(div0, span2);
      append(span2, span0);
      append(span0, t0);
      append(span0, t1);
      append(span2, t2);
      append(span2, span1);
      append(span1, t3);
      append(span1, t4);
      append(div0, t5);
      if (if_block0) if_block0.m(div0, null);
      append(div2, t6);
      append(div2, div1);
      append(div1, button0);
      append(div1, t8);
      append(div1, button1);
      append(div4, t10);
      if_block1.m(div4, null);
      append(div4, t11);
      append(div4, div3);
      if (!mounted) {
        dispose = [
          listen(
            button0,
            "click",
            /*click_handler*/
            ctx[12]
          ),
          listen(
            button1,
            "click",
            /*click_handler_1*/
            ctx[13]
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, [dirty]) {
      if (dirty & /*additions*/
      8) set_data(
        t1,
        /*additions*/
        ctx2[3]
      );
      if (dirty & /*deletions*/
      4) set_data(
        t4,
        /*deletions*/
        ctx2[2]
      );
      if (
        /*fileName*/
        ctx2[0]
      ) {
        if (if_block0) {
          if_block0.p(ctx2, dirty);
        } else {
          if_block0 = create_if_block_33(ctx2);
          if_block0.c();
          if_block0.m(div0, null);
        }
      } else if (if_block0) {
        if_block0.d(1);
        if_block0 = null;
      }
      if (dirty & /*viewMode*/
      2) {
        toggle_class(
          button0,
          "active",
          /*viewMode*/
          ctx2[1] === "split"
        );
      }
      if (dirty & /*viewMode*/
      2) {
        toggle_class(
          button1,
          "active",
          /*viewMode*/
          ctx2[1] === "unified"
        );
      }
      if (current_block_type === (current_block_type = select_block_type(ctx2, dirty)) && if_block1) {
        if_block1.p(ctx2, dirty);
      } else {
        if_block1.d(1);
        if_block1 = current_block_type(ctx2);
        if (if_block1) {
          if_block1.c();
          if_block1.m(div4, t11);
        }
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(div4);
      }
      if (if_block0) if_block0.d();
      if_block1.d();
      mounted = false;
      run_all(dispose);
    }
  };
}
function buildSplitLines(changes) {
  const result = [];
  let leftLineNum = 1;
  let rightLineNum = 1;
  for (const change of changes) {
    const lines = change.value.replace(/\n$/, "").split("\n");
    if (change.added) {
      for (const line of lines) {
        const lastRow = result[result.length - 1];
        if (lastRow && lastRow.right === null) {
          lastRow.right = { content: line, type: "added" };
          lastRow.rightLineNum = rightLineNum++;
        } else {
          result.push({
            left: null,
            right: { content: line, type: "added" },
            leftLineNum: null,
            rightLineNum: rightLineNum++
          });
        }
      }
    } else if (change.removed) {
      for (const line of lines) {
        result.push({
          left: { content: line, type: "removed" },
          right: null,
          leftLineNum: leftLineNum++,
          rightLineNum: null
        });
      }
    } else {
      for (const line of lines) {
        result.push({
          left: { content: line, type: "unchanged" },
          right: { content: line, type: "unchanged" },
          leftLineNum: leftLineNum++,
          rightLineNum: rightLineNum++
        });
      }
    }
  }
  return result;
}
function getUnifiedLines(changes) {
  const result = [];
  let oldLineNum = 1;
  let newLineNum = 1;
  for (const change of changes) {
    const lines = change.value.replace(/\n$/, "").split("\n");
    for (const line of lines) {
      if (change.added) {
        result.push({
          content: line,
          type: "added",
          oldLineNum: null,
          newLineNum: newLineNum++
        });
      } else if (change.removed) {
        result.push({
          content: line,
          type: "removed",
          oldLineNum: oldLineNum++,
          newLineNum: null
        });
      } else {
        result.push({
          content: line,
          type: "unchanged",
          oldLineNum: oldLineNum++,
          newLineNum: newLineNum++
        });
      }
    }
  }
  return result;
}
function instance5($$self, $$props, $$invalidate) {
  let diff;
  let splitLines;
  let unifiedLines;
  let additions;
  let deletions;
  let { oldContent } = $$props;
  let { newContent } = $$props;
  let { fileName = "" } = $$props;
  let { defaultViewStyle = "auto" } = $$props;
  function getInitialViewMode() {
    if (defaultViewStyle === "split") return "split";
    if (defaultViewStyle === "unified") return "unified";
    return import_obsidian14.Platform.isMobile ? "unified" : "split";
  }
  let viewMode = getInitialViewMode();
  let leftPane = null;
  let rightPane = null;
  let isSyncing = false;
  function syncScroll(source, target) {
    if (isSyncing) return;
    isSyncing = true;
    target.scrollTop = source.scrollTop;
    target.scrollLeft = source.scrollLeft;
    requestAnimationFrame(() => {
      isSyncing = false;
    });
  }
  function leftPaneAction(node) {
    leftPane = node;
    const handleScroll = () => {
      if (rightPane) syncScroll(node, rightPane);
    };
    node.addEventListener("scroll", handleScroll);
    return {
      destroy() {
        node.removeEventListener("scroll", handleScroll);
        leftPane = null;
      }
    };
  }
  function rightPaneAction(node) {
    rightPane = node;
    const handleScroll = () => {
      if (leftPane) syncScroll(node, leftPane);
    };
    node.addEventListener("scroll", handleScroll);
    return {
      destroy() {
        node.removeEventListener("scroll", handleScroll);
        rightPane = null;
      }
    };
  }
  const click_handler = () => $$invalidate(1, viewMode = "split");
  const click_handler_1 = () => $$invalidate(1, viewMode = "unified");
  $$self.$$set = ($$props2) => {
    if ("oldContent" in $$props2) $$invalidate(8, oldContent = $$props2.oldContent);
    if ("newContent" in $$props2) $$invalidate(9, newContent = $$props2.newContent);
    if ("fileName" in $$props2) $$invalidate(0, fileName = $$props2.fileName);
    if ("defaultViewStyle" in $$props2) $$invalidate(10, defaultViewStyle = $$props2.defaultViewStyle);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*oldContent, newContent*/
    768) {
      $: $$invalidate(11, diff = diffLines(oldContent, newContent));
    }
    if ($$self.$$.dirty & /*diff*/
    2048) {
      $: $$invalidate(5, splitLines = buildSplitLines(diff));
    }
    if ($$self.$$.dirty & /*diff*/
    2048) {
      $: $$invalidate(4, unifiedLines = getUnifiedLines(diff));
    }
    if ($$self.$$.dirty & /*diff*/
    2048) {
      $: $$invalidate(3, additions = diff.filter((c) => c.added).reduce((sum, c) => sum + c.count, 0));
    }
    if ($$self.$$.dirty & /*diff*/
    2048) {
      $: $$invalidate(2, deletions = diff.filter((c) => c.removed).reduce((sum, c) => sum + c.count, 0));
    }
  };
  return [
    fileName,
    viewMode,
    deletions,
    additions,
    unifiedLines,
    splitLines,
    leftPaneAction,
    rightPaneAction,
    oldContent,
    newContent,
    defaultViewStyle,
    diff,
    click_handler,
    click_handler_1
  ];
}
var DiffView = class extends SvelteComponent {
  constructor(options) {
    super();
    init2(
      this,
      options,
      instance5,
      create_fragment5,
      safe_not_equal,
      {
        oldContent: 8,
        newContent: 9,
        fileName: 0,
        defaultViewStyle: 10
      },
      add_css
    );
  }
};
var DiffView_default = DiffView;

// src/views/PublicationCenter/PublicationCenter.ts
var PublicationCenter2 = class {
  modal;
  settings;
  publishStatusManager;
  publisher;
  siteManager;
  vault;
  publicationCenterUi;
  constructor(app2, publishStatusManager, publisher, siteManager, settings) {
    this.modal = new import_obsidian15.Modal(app2);
    this.settings = settings;
    this.publishStatusManager = publishStatusManager;
    this.publisher = publisher;
    this.siteManager = siteManager;
    this.vault = app2.vault;
    this.modal.titleEl.createEl("span", { text: "Publication center" }).prepend(this.getIcon("quartz-syncer-icon"));
    this.modal.titleEl.addClass("quartz-syncer-modal-title");
    this.modal.contentEl.addClass("quartz-syncer-modal-content");
  }
  /**
   * Returns an icon element based on the provided name.
   * If the icon is not found, it returns a span element.
   *
   * @param name - The name of the icon to retrieve.
   * @returns A Node representing the icon.
   */
  getIcon(name) {
    const icon = (0, import_obsidian15.getIcon)(name) ?? document.createElement("span");
    if (icon instanceof SVGSVGElement) {
      icon.addClass("quartz-syncer-svg-icon");
    }
    return icon;
  }
  /**
   * Shows the diff between the remote and local versions of a note.
   * It retrieves the content of both versions, compares them, and displays the differences in a modal.
   *
   * @param notePath - The path of the note to compare.
   * @returns A promise that resolves when the diff is displayed.
   * @throws Will throw an error if the note content cannot be retrieved or compiled.
   */
  showDiff = async (notePath) => {
    try {
      let remoteContent, remoteFile, localContent, localFile;
      if (this.settings.useCache) {
        await this.publisher.datastore.loadRemoteFile(notePath);
        remoteFile = remoteContent ? remoteContent[0] : void 0;
      }
      if (!remoteContent || !this.settings.useCache) {
        remoteFile = await this.siteManager.getNoteContent(notePath);
      }
      let localNotePath = "";
      if (this.settings.vaultPath !== "/" && this.settings.vaultPath !== "") {
        localNotePath = this.settings.vaultPath + notePath;
      } else {
        localNotePath = notePath;
      }
      if (this.settings.useCache) {
        localContent = await this.publisher.datastore.loadLocalFile(localNotePath);
        localFile = localContent ? localContent[0] : void 0;
      } else {
        localContent = this.vault.getFileByPath(localNotePath);
        if (!(localContent instanceof import_obsidian15.TFile)) {
          localFile = "";
        } else {
          localContent = await this.publisher.compiler.generateMarkdown(
            new PublishFile({
              file: localContent,
              vault: this.vault,
              compiler: this.publisher.compiler,
              datastore: this.publisher.datastore,
              metadataCache: this.publisher.metadataCache,
              settings: this.settings
            })
          );
          if (!localContent) {
            throw new Error(
              `Failed to compile local file: ${localNotePath}. Compiler returned null.`
            );
          }
          localFile = localContent[0];
        }
      }
      if (remoteFile && localFile) {
        let diffView;
        const diffModal = new import_obsidian15.Modal(this.modal.app);
        const title = notePath.split("/").pop() || "Diff";
        diffModal.titleEl.createEl("span", {
          text: `${title}`
        }).prepend(this.getIcon("file-diff"));
        diffModal.onOpen = () => {
          diffView = new DiffView_default({
            target: diffModal.contentEl,
            props: {
              oldContent: remoteFile,
              newContent: localFile,
              fileName: title,
              defaultViewStyle: this.settings.diffViewStyle
            }
          });
        };
        diffModal.onClose = () => {
          if (diffView) {
            diffView.$destroy();
          }
        };
        diffModal.open();
      }
    } catch (e) {
      console.error(e);
    }
  };
  /**
   * Opens the publication center modal.
   * It sets up the modal's content and behavior, including the publication status manager and publisher.
   */
  open = () => {
    this.modal.onClose = () => {
      this.publicationCenterUi.$destroy();
    };
    this.modal.onOpen = () => {
      this.modal.contentEl.empty();
      this.publicationCenterUi = new PublicationCenter_default({
        target: this.modal.contentEl,
        props: {
          publishStatusManager: this.publishStatusManager,
          publisher: this.publisher,
          showDiff: this.showDiff,
          close: () => {
            this.modal.close();
          }
        }
      });
    };
    this.modal.open();
  };
};

// src/publisher/PublishStatusManager.ts
init_esbuild_buffer_shim();
var PublishStatusManager = class {
  siteManager;
  publisher;
  constructor(siteManager, publisher) {
    this.siteManager = siteManager;
    this.publisher = publisher;
  }
  /**
   * Gets the paths of deleted notes.
   *
   * @returns A promise that resolves to an array of deleted note paths.
   */
  getDeletedNotePaths() {
    throw new Error("Method not implemented.");
  }
  /**
   * Gets the paths of deleted blobs.
   *
   * @returns A promise that resolves to an array of deleted blob paths.
   */
  getDeletedBlobsPaths() {
    throw new Error("Method not implemented.");
  }
  generateDeletedContentPaths(remoteNoteHashes, marked) {
    const isJsFile = (key) => key.endsWith(".js");
    const isMarkedForPublish = (key) => marked.find((f) => f === key);
    const deletedPaths = Object.keys(remoteNoteHashes).filter(
      (key) => !isJsFile(key) && !isMarkedForPublish(key)
    );
    const pathsWithSha = deletedPaths.map((path) => {
      return {
        path,
        sha: remoteNoteHashes[path]
      };
    });
    return pathsWithSha;
  }
  /**
   * Gets the current publish status, including unpublished, published, changed notes,
   * and deleted note and blob paths.
   *
   * @param controller - The loading controller to manage the loading state.
   * @returns A promise that resolves to an object containing the publish status.
   */
  async getPublishStatus(controller) {
    const unpublishedNotes = [];
    const publishedNotes = [];
    const changedNotes = [];
    const deletedNotePaths = [];
    const deletedBlobPaths = [];
    if (controller) {
      controller.setText("Retrieving publish status...");
      controller.setProgress(0);
    }
    const contentTree = await this.siteManager.userSyncerConnection.getContent("HEAD");
    if (!contentTree) {
      throw new Error("Could not get content tree from base garden");
    }
    const remoteNoteHashes = await this.siteManager.getNoteHashes(contentTree);
    const remoteBlobHashes = await this.siteManager.getBlobHashes(contentTree);
    const remoteBlobHashesArray = Object.entries(remoteBlobHashes);
    const numberOfEntries = Object.entries(remoteNoteHashes).length;
    const padLength = numberOfEntries.toString().length;
    let index = 0;
    if (this.publisher.settings.useCache) {
      for (const [path, sha] of remoteBlobHashesArray) {
        if (!sha) {
          continue;
        }
        const hash = await this.publisher.datastore.loadRemoteHash(path);
        if ((!hash || hash !== sha) && path.endsWith(".md")) {
          if (controller) {
            index++;
            controller.setProgress(
              Math.floor(index / numberOfEntries * 100)
            );
            controller.setIndexText(
              `Notes processed: ${index.toString().padStart(padLength)}/${numberOfEntries}`
            );
            controller.setText(`Processing ${path}...`);
          }
          if (!this.publisher.vault.getFileByPath(path)) {
            continue;
          }
          const remoteContent = await this.siteManager.getNoteContent(path);
          if (!remoteContent) {
            continue;
          }
          const timestamp = await this.publisher.datastore.getTime(path) ?? Date.now();
          await this.publisher.datastore.storeRemoteFile(
            path,
            timestamp,
            [remoteContent, { blobs: [] }]
          );
          await this.publisher.datastore.storeRemoteHash(
            path,
            timestamp,
            sha
          );
        }
      }
    }
    if (controller) {
      controller.setText("Finishing up...");
      controller.setProgress(100);
    }
    const marked = await this.publisher.getFilesMarkedForPublishing();
    if (this.publisher.settings.useCache) {
      await this.publisher.datastore.synchronize(
        marked["notes"].map((f) => f.getPath())
      );
      if (this.publisher.settings.syncCache) {
        await this.publisher.plugin.compareDataToCache();
      }
    }
    for (const file of marked.notes) {
      const compiledFile = await file.compile();
      const [content, _] = compiledFile.getCompiledFile();
      const localHash = generateBlobHash(content);
      const remoteHash = remoteNoteHashes[file.getVaultPath()];
      if (!remoteHash) {
        unpublishedNotes.push(compiledFile);
      } else if (remoteHash === localHash) {
        compiledFile.setRemoteHash(remoteHash);
        publishedNotes.push(compiledFile);
      } else {
        compiledFile.setRemoteHash(remoteHash);
        changedNotes.push(compiledFile);
      }
    }
    deletedNotePaths.push(
      ...this.generateDeletedContentPaths(
        remoteNoteHashes,
        marked.notes.map((f) => f.getVaultPath())
      )
    );
    deletedBlobPaths.push(
      ...this.generateDeletedContentPaths(remoteBlobHashes, marked.blobs)
    );
    publishedNotes.sort((a, b) => a.compare(b));
    publishedNotes.sort((a, b) => a.compare(b));
    changedNotes.sort((a, b) => a.compare(b));
    deletedNotePaths.sort((a, b) => a.path.localeCompare(b.path));
    return {
      unpublishedNotes,
      publishedNotes,
      changedNotes,
      deletedNotePaths,
      deletedBlobPaths
    };
  }
};

// src/publishFile/ObsidianFrontMatterEngine.ts
init_esbuild_buffer_shim();
var ObsidianFrontMatterEngine = class {
  metadataCache;
  file;
  vault;
  fileManager;
  generatedFrontMatter = {};
  constructor(vault, metadataCache, file, fileManager) {
    this.metadataCache = metadataCache;
    this.vault = vault;
    this.file = file;
    this.fileManager = fileManager;
  }
  /**
   * Sets a key-value pair in the front matter.
   *
   * @param key - The key to set.
   * @param value - The value to set for the key.
   * @returns The current instance of ObsidianFrontMatterEngine for method chaining.
   */
  set(key, value) {
    this.generatedFrontMatter[key] = value;
    return this;
  }
  /**
   * Removes a key from the front matter.
   *
   * @param key - The key to remove.
   * @returns The current instance of ObsidianFrontMatterEngine for method chaining.
   */
  remove(key) {
    this.generatedFrontMatter[key] = void 0;
    return this;
  }
  /**
   * Gets the value of a key from the front matter.
   *
   * @param key - The key to get the value for.
   * @returns The value of the key, or undefined if the key does not exist.
   */
  get(key) {
    return this.getFrontMatterSnapshot()[key];
  }
  /**
   * Applies the changes made to the front matter to the file.
   * It reads the current content of the file, updates the front matter, and writes it back.
   *
   * @returns A promise that resolves when the changes are applied.
   */
  async apply() {
    const newFrontMatter = this.getFrontMatterSnapshot();
    await this.fileManager.processFrontMatter(this.file, (frontMatter) => {
      for (const key of Object.keys(newFrontMatter)) {
        frontMatter[key] = newFrontMatter[key];
      }
    });
  }
  /**
   * Converts the front matter object to a YAML string.
   * It removes any keys with undefined values and formats the remaining keys as YAML.
   *
   * @param frontMatter - The front matter object to convert.
   * @returns A YAML string representation of the front matter.
   */
  frontMatterToYaml(frontMatter) {
    for (const key of Object.keys(frontMatter)) {
      if (frontMatter[key] === void 0) {
        delete frontMatter[key];
      }
    }
    if (Object.keys(frontMatter).length === 0) {
      return "";
    }
    let yaml = "---\n";
    for (const key of Object.keys(frontMatter)) {
      yaml += `${key}: ${frontMatter[key]}
`;
    }
    yaml += "---";
    return yaml;
  }
  /**
   * Gets a snapshot of the current front matter, merging it with any generated front matter.
   * It retrieves the existing front matter from the metadata cache and combines it with the generated front matter.
   *
   * @returns An object containing the merged front matter.
   */
  getFrontMatterSnapshot() {
    const cachedFrontMatter = {
      ...this.metadataCache.getCache(this.file?.path)?.frontmatter
    };
    delete cachedFrontMatter["position"];
    return { ...cachedFrontMatter, ...this.generatedFrontMatter };
  }
};

// src/repositoryConnection/QuartzSyncerSiteManager.ts
init_esbuild_buffer_shim();

// node_modules/js-base64/base64.mjs
init_esbuild_buffer_shim();
var version = "3.7.7";
var VERSION2 = version;
var _hasBuffer = typeof Buffer === "function";
var _TD = typeof TextDecoder === "function" ? new TextDecoder() : void 0;
var _TE = typeof TextEncoder === "function" ? new TextEncoder() : void 0;
var b64ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var b64chs = Array.prototype.slice.call(b64ch);
var b64tab = ((a) => {
  let tab = {};
  a.forEach((c, i) => tab[c] = i);
  return tab;
})(b64chs);
var b64re = /^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/;
var _fromCC = String.fromCharCode.bind(String);
var _U8Afrom = typeof Uint8Array.from === "function" ? Uint8Array.from.bind(Uint8Array) : (it) => new Uint8Array(Array.prototype.slice.call(it, 0));
var _mkUriSafe = (src) => src.replace(/=/g, "").replace(/[+\/]/g, (m0) => m0 == "+" ? "-" : "_");
var _tidyB64 = (s2) => s2.replace(/[^A-Za-z0-9\+\/]/g, "");
var btoaPolyfill = (bin) => {
  let u32, c0, c1, c2, asc = "";
  const pad = bin.length % 3;
  for (let i = 0; i < bin.length; ) {
    if ((c0 = bin.charCodeAt(i++)) > 255 || (c1 = bin.charCodeAt(i++)) > 255 || (c2 = bin.charCodeAt(i++)) > 255)
      throw new TypeError("invalid character found");
    u32 = c0 << 16 | c1 << 8 | c2;
    asc += b64chs[u32 >> 18 & 63] + b64chs[u32 >> 12 & 63] + b64chs[u32 >> 6 & 63] + b64chs[u32 & 63];
  }
  return pad ? asc.slice(0, pad - 3) + "===".substring(pad) : asc;
};
var _btoa = typeof btoa === "function" ? (bin) => btoa(bin) : _hasBuffer ? (bin) => Buffer.from(bin, "binary").toString("base64") : btoaPolyfill;
var _fromUint8Array = _hasBuffer ? (u8a) => Buffer.from(u8a).toString("base64") : (u8a) => {
  const maxargs = 4096;
  let strs = [];
  for (let i = 0, l2 = u8a.length; i < l2; i += maxargs) {
    strs.push(_fromCC.apply(null, u8a.subarray(i, i + maxargs)));
  }
  return _btoa(strs.join(""));
};
var fromUint8Array = (u8a, urlsafe = false) => urlsafe ? _mkUriSafe(_fromUint8Array(u8a)) : _fromUint8Array(u8a);
var cb_utob = (c) => {
  if (c.length < 2) {
    var cc = c.charCodeAt(0);
    return cc < 128 ? c : cc < 2048 ? _fromCC(192 | cc >>> 6) + _fromCC(128 | cc & 63) : _fromCC(224 | cc >>> 12 & 15) + _fromCC(128 | cc >>> 6 & 63) + _fromCC(128 | cc & 63);
  } else {
    var cc = 65536 + (c.charCodeAt(0) - 55296) * 1024 + (c.charCodeAt(1) - 56320);
    return _fromCC(240 | cc >>> 18 & 7) + _fromCC(128 | cc >>> 12 & 63) + _fromCC(128 | cc >>> 6 & 63) + _fromCC(128 | cc & 63);
  }
};
var re_utob = /[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g;
var utob = (u) => u.replace(re_utob, cb_utob);
var _encode = _hasBuffer ? (s2) => Buffer.from(s2, "utf8").toString("base64") : _TE ? (s2) => _fromUint8Array(_TE.encode(s2)) : (s2) => _btoa(utob(s2));
var encode = (src, urlsafe = false) => urlsafe ? _mkUriSafe(_encode(src)) : _encode(src);
var encodeURI2 = (src) => encode(src, true);
var re_btou = /[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g;
var cb_btou = (cccc) => {
  switch (cccc.length) {
    case 4:
      var cp = (7 & cccc.charCodeAt(0)) << 18 | (63 & cccc.charCodeAt(1)) << 12 | (63 & cccc.charCodeAt(2)) << 6 | 63 & cccc.charCodeAt(3), offset2 = cp - 65536;
      return _fromCC((offset2 >>> 10) + 55296) + _fromCC((offset2 & 1023) + 56320);
    case 3:
      return _fromCC((15 & cccc.charCodeAt(0)) << 12 | (63 & cccc.charCodeAt(1)) << 6 | 63 & cccc.charCodeAt(2));
    default:
      return _fromCC((31 & cccc.charCodeAt(0)) << 6 | 63 & cccc.charCodeAt(1));
  }
};
var btou = (b) => b.replace(re_btou, cb_btou);
var atobPolyfill = (asc) => {
  asc = asc.replace(/\s+/g, "");
  if (!b64re.test(asc))
    throw new TypeError("malformed base64.");
  asc += "==".slice(2 - (asc.length & 3));
  let u24, bin = "", r1, r2;
  for (let i = 0; i < asc.length; ) {
    u24 = b64tab[asc.charAt(i++)] << 18 | b64tab[asc.charAt(i++)] << 12 | (r1 = b64tab[asc.charAt(i++)]) << 6 | (r2 = b64tab[asc.charAt(i++)]);
    bin += r1 === 64 ? _fromCC(u24 >> 16 & 255) : r2 === 64 ? _fromCC(u24 >> 16 & 255, u24 >> 8 & 255) : _fromCC(u24 >> 16 & 255, u24 >> 8 & 255, u24 & 255);
  }
  return bin;
};
var _atob = typeof atob === "function" ? (asc) => atob(_tidyB64(asc)) : _hasBuffer ? (asc) => Buffer.from(asc, "base64").toString("binary") : atobPolyfill;
var _toUint8Array = _hasBuffer ? (a) => _U8Afrom(Buffer.from(a, "base64")) : (a) => _U8Afrom(_atob(a).split("").map((c) => c.charCodeAt(0)));
var toUint8Array = (a) => _toUint8Array(_unURI(a));
var _decode = _hasBuffer ? (a) => Buffer.from(a, "base64").toString("utf8") : _TD ? (a) => _TD.decode(_toUint8Array(a)) : (a) => btou(_atob(a));
var _unURI = (a) => _tidyB64(a.replace(/[-_]/g, (m0) => m0 == "-" ? "+" : "/"));
var decode = (src) => _decode(_unURI(src));
var isValid = (src) => {
  if (typeof src !== "string")
    return false;
  const s2 = src.replace(/\s+/g, "").replace(/={0,2}$/, "");
  return !/[^\s0-9a-zA-Z\+/]/.test(s2) || !/[^\s0-9a-zA-Z\-_]/.test(s2);
};
var _noEnum = (v) => {
  return {
    value: v,
    enumerable: false,
    writable: true,
    configurable: true
  };
};
var extendString = function() {
  const _add = (name, body) => Object.defineProperty(String.prototype, name, _noEnum(body));
  _add("fromBase64", function() {
    return decode(this);
  });
  _add("toBase64", function(urlsafe) {
    return encode(this, urlsafe);
  });
  _add("toBase64URI", function() {
    return encode(this, true);
  });
  _add("toBase64URL", function() {
    return encode(this, true);
  });
  _add("toUint8Array", function() {
    return toUint8Array(this);
  });
};
var extendUint8Array = function() {
  const _add = (name, body) => Object.defineProperty(Uint8Array.prototype, name, _noEnum(body));
  _add("toBase64", function(urlsafe) {
    return fromUint8Array(this, urlsafe);
  });
  _add("toBase64URI", function() {
    return fromUint8Array(this, true);
  });
  _add("toBase64URL", function() {
    return fromUint8Array(this, true);
  });
};
var extendBuiltins = () => {
  extendString();
  extendUint8Array();
};
var gBase64 = {
  version,
  VERSION: VERSION2,
  atob: _atob,
  atobPolyfill,
  btoa: _btoa,
  btoaPolyfill,
  fromBase64: decode,
  toBase64: encode,
  encode,
  encodeURI: encodeURI2,
  encodeURL: encodeURI2,
  utob,
  btou,
  decode,
  isValid,
  fromUint8Array,
  toUint8Array,
  extendString,
  extendUint8Array,
  extendBuiltins
};

// src/repositoryConnection/QuartzSyncerSiteManager.ts
var QuartzSyncerSiteManager = class {
  settings;
  metadataCache;
  baseSyncerConnection;
  userSyncerConnection;
  constructor(metadataCache, settings, gitSettingsWithSecret) {
    this.settings = settings;
    this.metadataCache = metadataCache;
    this.baseSyncerConnection = new RepositoryConnection({
      gitSettings: {
        remoteUrl: "https://github.com/jackyzha0/quartz.git",
        branch: "v4",
        auth: { type: "none" }
      },
      contentFolder: "content",
      vaultPath: "/"
    });
    this.userSyncerConnection = new RepositoryConnection({
      gitSettings: gitSettingsWithSecret,
      contentFolder: settings.contentFolder,
      vaultPath: settings.vaultPath
    });
  }
  /**
   * Retrieves the content of a note from the remote repository.
   *
   * @param path - The path to the note file.
   * @returns A promise that resolves to the note content as a string.
   */
  async getNoteContent(path) {
    if (path.startsWith("/")) {
      path = path.substring(1);
    }
    const response = await this.userSyncerConnection.getFile(
      `${this.settings.contentFolder}/${path}`
    );
    if (!response) {
      return "";
    }
    const content = gBase64.decode(response.content);
    return content;
  }
  /**
   * Extracts note hashes from the repository content tree.
   *
   * @param contentTree - The repository content tree.
   * @returns A promise that resolves to a record mapping note paths to their hashes.
   */
  async getNoteHashes(contentTree) {
    const files = contentTree.tree;
    const notes = files.filter(
      (x) => typeof x.path === "string" && x.path.startsWith(this.settings.contentFolder) && x.type === "blob" && x.path.endsWith(".md")
    );
    const hashes = {};
    for (const note of notes) {
      const vaultPath = note.path.replace(
        this.settings.contentFolder,
        ""
      );
      const actualVaultPath = vaultPath.startsWith("/") ? vaultPath.substring(1) : vaultPath;
      hashes[actualVaultPath] = note.oid;
    }
    return hashes;
  }
  /**
   * Extracts blob hashes from the repository content tree.
   *
   * @param contentTree - The repository content tree.
   * @returns A promise that resolves to a record mapping blob paths to their hashes.
   */
  async getBlobHashes(contentTree) {
    const files = contentTree.tree ?? [];
    const blobs = files.filter(
      (x) => typeof x.path === "string" && x.path.startsWith(this.settings.contentFolder) && x.type === "blob"
    );
    const hashes = {};
    for (const blob of blobs) {
      const vaultPath = blob.path.replace(
        this.settings.contentFolder,
        ""
      );
      const actualVaultPath = vaultPath.startsWith("/") ? vaultPath.substring(1) : vaultPath;
      hashes[actualVaultPath] = blob.oid;
    }
    return hashes;
  }
};

// src/views/QuartzSyncerSettingTab.ts
init_esbuild_buffer_shim();
var import_obsidian25 = require("obsidian");

// src/views/SettingsView/SettingView.ts
init_esbuild_buffer_shim();
var import_obsidian24 = require("obsidian");

// src/views/SettingsView/Views/GitSettings.ts
init_esbuild_buffer_shim();
var import_obsidian17 = require("obsidian");

// src/ui/suggest/folder.ts
init_esbuild_buffer_shim();
var import_obsidian16 = require("obsidian");
var FolderSuggest = class extends import_obsidian16.AbstractInputSuggest {
  folders;
  inputEl;
  constructor(app2, inputEl) {
    super(app2, inputEl);
    this.inputEl = inputEl;
    this.folders = this.app.vault.getAllFolders(true).map((folder) => (0, import_obsidian16.normalizePath)(folder.path));
  }
  /**
   * Returns the suggestions to display based on the user's input.
   *
   * @param inputStr - The user's input string.
   * @returns An array of folder paths that match the input string.
   */
  getSuggestions(inputStr) {
    const inputLower = inputStr.toLowerCase();
    return this.folders.filter(
      (folder) => folder.toLowerCase().includes(inputLower)
    );
  }
  /**
   * Renders a suggestion in the dropdown.
   *
   * @param folder - The folder path to render.
   * @param el - The HTML element to render the suggestion in.
   */
  renderSuggestion(folder, el) {
    el.setText(folder);
  }
  /**
   * Handles the selection of a suggestion.
   *
   * @param folder - The selected folder path.
   */
  selectSuggestion(folder) {
    this.inputEl.value = folder;
    const event = new Event("input");
    this.inputEl.dispatchEvent(event);
    this.close();
  }
};

// src/utils/SecretStorageService.ts
init_esbuild_buffer_shim();
var import_js_logger10 = __toESM(require_logger());
var logger2 = import_js_logger10.default.get("secret-storage-service");
var GIT_AUTH_SECRET_ID = "quartz-syncer-git-token";
var SecretStorageService = class {
  secretStorage;
  cachedToken = null;
  constructor(app2) {
    this.secretStorage = app2.secretStorage;
  }
  getToken() {
    if (this.cachedToken !== null) {
      return this.cachedToken;
    }
    const token = this.secretStorage.getSecret(GIT_AUTH_SECRET_ID);
    this.cachedToken = token;
    return token;
  }
  setToken(token) {
    if (!token) {
      logger2.warn("Attempted to store empty token");
      return;
    }
    this.secretStorage.setSecret(GIT_AUTH_SECRET_ID, token);
    this.cachedToken = token;
    logger2.info("Git authentication token stored in secure storage");
  }
  clearToken() {
    this.secretStorage.setSecret(GIT_AUTH_SECRET_ID, "");
    this.cachedToken = null;
    logger2.info("Git authentication token cleared from secure storage");
  }
  hasToken() {
    const token = this.getToken();
    return token !== null && token !== "";
  }
  async migrateFromSettings(settings, saveSettings) {
    const legacyToken = settings.git?.auth?.secret;
    if (!legacyToken) {
      logger2.debug(
        "No legacy token found in settings, skipping migration"
      );
      return false;
    }
    const existingToken = this.getToken();
    if (existingToken && existingToken !== "") {
      logger2.debug(
        "Token already exists in secure storage, skipping migration"
      );
      if (settings.git?.auth?.secret) {
        settings.git.auth.secret = void 0;
        await saveSettings();
        logger2.info(
          "Cleared legacy token from settings (secure storage already has token)"
        );
      }
      return false;
    }
    this.setToken(legacyToken);
    settings.git.auth.secret = void 0;
    await saveSettings();
    logger2.info(
      "Successfully migrated Git authentication token from settings to secure storage"
    );
    return true;
  }
  listSecrets() {
    const allSecrets = this.secretStorage.listSecrets();
    return allSecrets.filter((id) => id.startsWith("quartz-syncer-"));
  }
};

// src/views/SettingsView/Views/GitSettings.ts
var GitSettings = class extends import_obsidian17.PluginSettingTab {
  app;
  plugin;
  settings;
  connectionStatus;
  settingsRootElement;
  connectionStatusElement;
  remoteBranches = [];
  defaultBranch = null;
  branchSettingEl = null;
  branchesLoaded = false;
  secretStorageService;
  constructor(app2, plugin, settings, settingsRootElement) {
    super(app2, plugin);
    this.app = app2;
    this.plugin = plugin;
    this.settings = settings;
    this.settingsRootElement = settingsRootElement;
    this.settingsRootElement.classList.add("settings-tab-content");
    this.connectionStatus = "loading";
    this.secretStorageService = new SecretStorageService(app2);
    this.connectionStatusElement = this.settingsRootElement.createEl(
      "span",
      {
        text: "pending..."
      }
    );
  }
  display() {
    this.settingsRootElement.empty();
    this.settingsRootElement.addClass("quartz-syncer-github-settings");
    this.branchSettingEl = null;
    this.initializeGitHeader();
    this.initializeRemoteUrlSetting();
    this.initializeBranchSetting();
    this.initializeProviderHintSetting();
    this.initializeAuthTypeSetting();
    this.initializeUsernameSetting();
    this.initializeSecretSetting();
    this.initializeCorsProxySetting();
    this.initializeVaultFolderSetting();
    this.settings.settings.lastUsedSettingsTab = "git";
    this.settings.plugin.saveSettings();
  }
  initializeGitHeader = () => {
    this.checkConnectionAndSaveSettings();
    const connectionStatusElement = createEl("span");
    connectionStatusElement.appendText(" (status: connection ");
    connectionStatusElement.append(this.connectionStatusElement);
    connectionStatusElement.appendText(")");
    connectionStatusElement.addClass(
      "quartz-syncer-connection-status",
      "quartz-syncer-connection-status-pending"
    );
    new import_obsidian17.Setting(this.settingsRootElement).setName("Git Repository").setDesc(
      "Configure your Git remote. Works with GitHub, GitLab, Bitbucket, and self-hosted Git servers."
    ).setHeading().nameEl.append(connectionStatusElement);
  };
  checkConnectionAndSaveSettings = async () => {
    this.settings.plugin.saveSettings();
    this.debouncedUpdateConnectionStatus();
  };
  updateConnectionStatus = async () => {
    const gitSettings = this.settings.settings.git;
    if (!gitSettings.remoteUrl) {
      this.connectionStatus = "error";
      this.remoteBranches = [];
      this.defaultBranch = null;
      this.updateConnectionStatusIndicator();
      return;
    }
    try {
      const authWithSecret = {
        ...gitSettings.auth,
        secret: this.secretStorageService.getToken() || void 0
      };
      const { branches, defaultBranch } = await RepositoryConnection.fetchRemoteBranches(
        gitSettings.remoteUrl,
        authWithSecret,
        gitSettings.corsProxyUrl
      );
      this.remoteBranches = branches;
      this.defaultBranch = defaultBranch;
      const hadBranches = this.branchesLoaded;
      if (branches.length > 0) {
        this.connectionStatus = "connected";
        this.branchesLoaded = true;
        if (!gitSettings.branch) {
          gitSettings.branch = defaultBranch || "v4";
          await this.settings.plugin.saveSettings();
        }
        if (!hadBranches) {
          this.refreshBranchSetting();
        }
      } else {
        this.connectionStatus = "error";
      }
    } catch {
      this.connectionStatus = "error";
      this.remoteBranches = [];
      this.defaultBranch = null;
    }
    this.updateConnectionStatusIndicator();
  };
  refreshBranchSetting() {
    if (this.branchSettingEl) {
      this.branchSettingEl.empty();
      this.initializeBranchSetting();
    }
  }
  debouncedUpdateConnectionStatus = (0, import_obsidian17.debounce)(
    this.updateConnectionStatus,
    500,
    true
  );
  updateConnectionStatusIndicator = () => {
    if (this.connectionStatusElement.parentElement === null) {
      return;
    }
    if (this.connectionStatus === "loading") {
      this.connectionStatusElement.innerText = "pending...";
      this.connectionStatusElement.parentElement.classList.remove(
        "quartz-syncer-connection-status-success",
        "quartz-syncer-connection-status-failed"
      );
      this.connectionStatusElement.parentElement.classList.add(
        "quartz-syncer-connection-status-pending"
      );
    }
    if (this.connectionStatus === "connected") {
      this.connectionStatusElement.innerText = "successful!";
      this.connectionStatusElement.parentElement.classList.remove(
        "quartz-syncer-connection-status-pending",
        "quartz-syncer-connection-status-failed"
      );
      this.connectionStatusElement.parentElement.classList.add(
        "quartz-syncer-connection-status-success"
      );
    }
    if (this.connectionStatus === "error") {
      this.connectionStatusElement.innerText = "failed!";
      this.connectionStatusElement.parentElement.classList.remove(
        "quartz-syncer-connection-status-pending",
        "quartz-syncer-connection-status-success"
      );
      this.connectionStatusElement.parentElement.classList.add(
        "quartz-syncer-connection-status-failed"
      );
    }
  };
  initializeRemoteUrlSetting() {
    new import_obsidian17.Setting(this.settingsRootElement).setName("Remote URL").setDesc(
      "The full URL of your Git repository (e.g., https://github.com/username/quartz.git)"
    ).addText(
      (text2) => text2.setPlaceholder("https://github.com/username/quartz.git").setValue(this.settings.settings.git.remoteUrl).onChange(async (value) => {
        this.settings.settings.git.remoteUrl = value;
        this.autoDetectProvider(value);
        await this.checkConnectionAndSaveSettings();
      })
    );
  }
  autoDetectProvider(url) {
    let hint = "custom";
    try {
      const hostname = new URL(url).hostname.toLowerCase();
      if (hostname === "github.com" || hostname.endsWith(".github.com")) {
        hint = "github";
      } else if (hostname === "gitlab.com" || hostname.endsWith(".gitlab.com")) {
        hint = "gitlab";
      } else if (hostname === "bitbucket.org" || hostname.endsWith(".bitbucket.org")) {
        hint = "bitbucket";
      } else if (hostname === "codeberg.org") {
        hint = "gitea";
      }
    } catch {
      hint = "custom";
    }
    this.settings.settings.git.providerHint = hint;
  }
  initializeBranchSetting() {
    if (!this.branchSettingEl) {
      this.branchSettingEl = this.settingsRootElement.createDiv();
    }
    const setting = new import_obsidian17.Setting(this.branchSettingEl).setName("Branch").setDesc("The branch to sync with");
    if (this.remoteBranches.length > 0) {
      setting.addDropdown((dropdown) => {
        for (const branch of this.remoteBranches) {
          const label = branch === this.defaultBranch ? `${branch} (default)` : branch;
          dropdown.addOption(branch, label);
        }
        const currentBranch = this.settings.settings.git.branch;
        if (currentBranch && this.remoteBranches.includes(currentBranch)) {
          dropdown.setValue(currentBranch);
        } else if (this.defaultBranch) {
          dropdown.setValue(this.defaultBranch);
          this.settings.settings.git.branch = this.defaultBranch;
        } else if (this.remoteBranches.includes("v4")) {
          dropdown.setValue("v4");
          this.settings.settings.git.branch = "v4";
        } else if (this.remoteBranches.length > 0) {
          dropdown.setValue(this.remoteBranches[0]);
          this.settings.settings.git.branch = this.remoteBranches[0];
        }
        dropdown.onChange(async (value) => {
          this.settings.settings.git.branch = value;
          await this.checkConnectionAndSaveSettings();
        });
      });
    } else {
      setting.addText(
        (text2) => text2.setPlaceholder("v4").setValue(this.settings.settings.git.branch).onChange(async (value) => {
          this.settings.settings.git.branch = value || "v4";
          await this.checkConnectionAndSaveSettings();
        })
      );
    }
  }
  initializeProviderHintSetting() {
    new import_obsidian17.Setting(this.settingsRootElement).setName("Provider").setDesc(
      "Select your Git provider for optimized authentication hints"
    ).addDropdown(
      (dropdown) => dropdown.addOption("github", "GitHub").addOption("gitlab", "GitLab").addOption("bitbucket", "Bitbucket").addOption("gitea", "Gitea / Codeberg").addOption("custom", "Custom / Self-hosted").setValue(
        this.settings.settings.git.providerHint || "github"
      ).onChange(async (value) => {
        this.settings.settings.git.providerHint = value;
        await this.checkConnectionAndSaveSettings();
      })
    );
  }
  initializeAuthTypeSetting() {
    new import_obsidian17.Setting(this.settingsRootElement).setName("Authentication Type").setDesc("How to authenticate with the Git server").addDropdown(
      (dropdown) => dropdown.addOption("basic", "Username & Token/Password").addOption("bearer", "Bearer Token").addOption("none", "None (public repos)").setValue(this.settings.settings.git.auth.type).onChange(async (value) => {
        this.settings.settings.git.auth.type = value;
        await this.checkConnectionAndSaveSettings();
        this.display();
      })
    );
  }
  initializeUsernameSetting() {
    if (this.settings.settings.git.auth.type !== "basic") {
      return;
    }
    const providerHint = this.settings.settings.git.providerHint;
    let placeholder = "username";
    let description = "Your username for authentication";
    if (providerHint === "gitlab") {
      placeholder = "oauth2 or username";
      description = "Use 'oauth2' for personal access tokens, or your username";
    } else if (providerHint === "bitbucket") {
      placeholder = "x-token-auth or username";
      description = "Use 'x-token-auth' for app passwords, or your username";
    }
    new import_obsidian17.Setting(this.settingsRootElement).setName("Username").setDesc(description).addText(
      (text2) => text2.setPlaceholder(placeholder).setValue(this.settings.settings.git.auth.username || "").onChange(async (value) => {
        this.settings.settings.git.auth.username = value;
        await this.checkConnectionAndSaveSettings();
      })
    );
  }
  initializeSecretSetting() {
    if (this.settings.settings.git.auth.type === "none") {
      return;
    }
    const providerHint = this.settings.settings.git.providerHint;
    let name = "Access Token";
    let description = "Your personal access token or password";
    if (providerHint === "github") {
      description = "A GitHub Personal Access Token (classic or fine-grained) with 'Contents' permission";
    } else if (providerHint === "gitlab") {
      description = "A GitLab Personal Access Token with 'write_repository' scope";
    } else if (providerHint === "bitbucket") {
      name = "App Password";
      description = "A Bitbucket App Password with repository write access";
    }
    const desc = document.createDocumentFragment();
    desc.createEl("span", { text: description + ". " });
    desc.createEl("a", {
      text: "Documentation",
      href: "https://saberzero1.github.io/quartz-syncer-docs/Guides/Generating-an-access-token"
    });
    const hasToken = this.secretStorageService.hasToken();
    const setting = new import_obsidian17.Setting(this.settingsRootElement).setName(name).setDesc(desc);
    const controlEl = setting.controlEl;
    const tokenContainer = controlEl.createDiv({
      cls: "quartz-syncer-token-container"
    });
    const statusIndicator = tokenContainer.createSpan({
      cls: `quartz-syncer-token-status ${hasToken ? "quartz-syncer-token-status-set" : "quartz-syncer-token-status-unset"}`
    });
    statusIndicator.setText(
      hasToken ? "Token stored securely" : "No token set"
    );
    const inputContainer = tokenContainer.createDiv({
      cls: "quartz-syncer-token-input-container"
    });
    const input = inputContainer.createEl("input", {
      type: "password",
      cls: "quartz-syncer-token-input",
      placeholder: hasToken ? "Enter new token to replace" : "Enter token"
    });
    const toggleBtn = inputContainer.createEl("button", {
      cls: "quartz-syncer-token-toggle clickable-icon",
      attr: { "aria-label": "Toggle token visibility" }
    });
    (0, import_obsidian17.setIcon)(toggleBtn, "eye");
    let isVisible = false;
    toggleBtn.addEventListener("click", (e) => {
      e.preventDefault();
      isVisible = !isVisible;
      input.type = isVisible ? "text" : "password";
      (0, import_obsidian17.setIcon)(toggleBtn, isVisible ? "eye-off" : "eye");
    });
    const buttonContainer = tokenContainer.createDiv({
      cls: "quartz-syncer-token-buttons"
    });
    const saveBtn = buttonContainer.createEl("button", {
      cls: "mod-cta",
      text: hasToken ? "Update" : "Save"
    });
    saveBtn.addEventListener("click", async () => {
      const value = input.value.trim();
      if (value) {
        this.secretStorageService.setToken(value);
        input.value = "";
        input.placeholder = "Enter new token to replace";
        statusIndicator.setText("Token stored securely");
        statusIndicator.removeClass("quartz-syncer-token-status-unset");
        statusIndicator.addClass("quartz-syncer-token-status-set");
        saveBtn.setText("Update");
        await this.checkConnectionAndSaveSettings();
      }
    });
    if (hasToken) {
      const clearBtn = buttonContainer.createEl("button", {
        cls: "mod-warning",
        text: "Clear"
      });
      clearBtn.addEventListener("click", async () => {
        this.secretStorageService.clearToken();
        input.value = "";
        input.placeholder = "Enter token";
        statusIndicator.setText("No token set");
        statusIndicator.removeClass("quartz-syncer-token-status-set");
        statusIndicator.addClass("quartz-syncer-token-status-unset");
        saveBtn.setText("Save");
        clearBtn.remove();
        await this.checkConnectionAndSaveSettings();
      });
    }
  }
  initializeCorsProxySetting() {
    const desc = document.createDocumentFragment();
    desc.createEl("span", {
      text: "A CORS proxy URL for browser environments. Required on mobile/web if your Git server doesn't support CORS. "
    });
    desc.createEl("a", {
      text: "Learn more",
      href: "https://github.com/isomorphic-git/cors-proxy"
    });
    new import_obsidian17.Setting(this.settingsRootElement).setName("CORS Proxy (optional)").setDesc(desc).addText(
      (text2) => text2.setPlaceholder("https://cors.isomorphic-git.org").setValue(this.settings.settings.git.corsProxyUrl || "").onChange(async (value) => {
        this.settings.settings.git.corsProxyUrl = value || void 0;
        await this.checkConnectionAndSaveSettings();
      })
    );
  }
  initializeVaultFolderSetting() {
    const app2 = this.settings.app;
    new import_obsidian17.Setting(this.settingsRootElement).setName("Vault root folder").setDesc(
      'The folder in your Obsidian vault to sync. Use "/" for the entire vault.'
    ).addSearch((text2) => {
      new FolderSuggest(app2, text2.inputEl);
      text2.setPlaceholder("/").setValue(this.settings.settings.vaultPath).onChange(async (value) => {
        value = (0, import_obsidian17.normalizePath)(value.trim());
        if (value === "/") {
          value = "";
        }
        this.settings.settings.vaultPath = `${value}/`;
        await this.checkConnectionAndSaveSettings();
      });
    });
  }
};

// src/views/SettingsView/Views/QuartzSettings.ts
init_esbuild_buffer_shim();
var import_obsidian18 = require("obsidian");
var QuartzSettings = class extends import_obsidian18.PluginSettingTab {
  app;
  plugin;
  settings;
  settingsRootElement;
  constructor(app2, plugin, settings, settingsRootElement) {
    super(app2, plugin);
    this.app = app2;
    this.plugin = plugin;
    this.settings = settings;
    this.settingsRootElement = settingsRootElement;
  }
  /**
   * Display the Quartz settings tab.
   * This method initializes and displays the Quartz-specific settings in the plugin's settings view.
   */
  display() {
    this.settingsRootElement.empty();
    this.settingsRootElement.addClass("quartz-syncer-github-settings");
    this.initializeQuartzHeader();
    this.initializeQuartzContentFolder();
    this.initializeUseFullImageResolutionSetting();
    this.initializeApplyEmbedsSetting();
    this.settings.settings.lastUsedSettingsTab = "quartz";
    this.settings.plugin.saveSettings();
  }
  /**
   * Initializes the Quartz header in the settings view.
   * This method creates a header for the Quartz settings section.
   */
  initializeQuartzHeader = () => {
    new import_obsidian18.Setting(this.settingsRootElement).setName("Quartz").setDesc(
      "Quartz Syncer will apply these settings to your Quartz notes."
    ).setHeading();
  };
  /**
   * Initializes the setting for using full image resolution.
   * This method creates a toggle setting that allows users to choose whether to use full resolution images.
   */
  initializeUseFullImageResolutionSetting() {
    new import_obsidian18.Setting(this.settingsRootElement).setName("Use full image resolution").setDesc(
      "By default, Quartz Syncer will use lower resolution images to save space. If you want to use the full resolution blob, enable this setting."
    ).addToggle(
      (toggle) => toggle.setValue(this.settings.settings.useFullResolutionImages).onChange(async (value) => {
        this.settings.settings.useFullResolutionImages = value;
        await this.settings.plugin.saveSettings();
      })
    );
  }
  /**
   * Initializes the setting for applying embeds.
   * This method creates a toggle setting that allows users to choose whether to apply embeds directly to their notes.
   */
  initializeApplyEmbedsSetting() {
    new import_obsidian18.Setting(this.settingsRootElement).setName("Apply embeds").setDesc(
      "By default, Quartz Syncer will apply embeds directly to your notes. If you want to let Quartz handle embeds, disable this setting."
    ).addToggle(
      (toggle) => toggle.setValue(this.settings.settings.applyEmbeds).onChange(async (value) => {
        this.settings.settings.applyEmbeds = value;
        await this.settings.plugin.saveSettings();
      })
    );
  }
  /**
   * Initializes the Quartz content folder setting.
   * This method creates a text input for the content folder where Quartz Syncer should store notes.
   */
  initializeQuartzContentFolder() {
    new import_obsidian18.Setting(this.settingsRootElement).setName("Content folder").setDesc(
      'The folder in your Quartz repository where Quartz Syncer should store your notes. By default "content"'
    ).addText(
      (text2) => text2.setPlaceholder("content").setValue(this.settings.settings.contentFolder).onChange(async (value) => {
        this.settings.settings.contentFolder = (0, import_obsidian18.normalizePath)(value);
        await this.settings.plugin.saveSettings();
      })
    );
  }
};

// src/views/SettingsView/Views/FrontmatterSettings.ts
init_esbuild_buffer_shim();
var import_obsidian19 = require("obsidian");
var FrontmatterSettings = class extends import_obsidian19.PluginSettingTab {
  app;
  plugin;
  settings;
  settingsRootElement;
  constructor(app2, plugin, settings, settingsRootElement) {
    super(app2, plugin);
    this.app = app2;
    this.plugin = plugin;
    this.settings = settings;
    this.plugin = plugin;
    this.settingsRootElement = settingsRootElement;
  }
  /**
   * Display the frontmatter settings.
   * This method initializes the settings UI for managing Quartz Syncer's frontmatter properties.
   */
  display() {
    this.settingsRootElement.empty();
    this.settingsRootElement.addClass("quartz-syncer-github-settings");
    this.initializeFrontmatterHeader();
    this.initializePublishFrontmatterKeySetting();
    this.initializeFrontmatterFormatSetting();
    this.initializeAllNotesPublishableByDefaultSetting();
    this.initializeShowCreatedTimestampSetting();
    this.initializeCreatedTimestampKeysSetting();
    this.initializeShowUpdatedTimestampSetting();
    this.initializeUpdatedTimestampKeysSetting();
    this.initializeShowPublishedTimestampSetting();
    this.initializePublishedTimestampKeysSetting();
    this.initializeEnablePermalinkSetting();
    this.initializeIncludeAllFrontmatterSetting();
    const oldCreatedDefaults = ["created"];
    if (this.settings.settings.createdTimestampKey === "" || oldCreatedDefaults.includes(
      this.settings.settings.createdTimestampKey
    )) {
      this.settings.settings.createdTimestampKey = "created, created_at, date";
    }
    const oldUpdatedDefaults = ["modified"];
    if (this.settings.settings.updatedTimestampKey === "" || oldUpdatedDefaults.includes(
      this.settings.settings.updatedTimestampKey
    )) {
      this.settings.settings.updatedTimestampKey = "modified, lastmod, updated, last-modified";
    }
    const oldPublishedDefaults = ["published"];
    if (this.settings.settings.publishedTimestampKey === "" || oldPublishedDefaults.includes(
      this.settings.settings.publishedTimestampKey
    )) {
      this.settings.settings.publishedTimestampKey = "published, publishDate, date";
    }
    this.settings.settings.lastUsedSettingsTab = "frontmatter";
    this.settings.plugin.saveSettings();
  }
  /**
   * Initializes the header for the frontmatter settings section.
   * This method creates a heading for the frontmatter settings in the UI.
   */
  initializeFrontmatterHeader = () => {
    new import_obsidian19.Setting(this.settingsRootElement).setName("Note properties (frontmatter)").setDesc(
      "Quartz Syncer will apply these settings to your Quartz notes' properties or frontmatter."
    ).setHeading();
  };
  initializeFrontmatterFormatSetting() {
    new import_obsidian19.Setting(this.settingsRootElement).setName("Frontmatter format").setDesc(
      "Output format for frontmatter in published notes. YAML is more readable, JSON is supported in case you need it."
    ).addDropdown(
      (dropdown) => dropdown.addOption("yaml", "YAML").addOption("json", "JSON").setValue(
        this.settings.settings.frontmatterFormat ?? "yaml"
      ).onChange(async (value) => {
        this.settings.settings.frontmatterFormat = value;
        await this.settings.plugin.saveSettings();
      })
    );
  }
  initializePublishFrontmatterKeySetting() {
    if (!this.settings.settings.allNotesPublishableByDefault) {
      new import_obsidian19.Setting(this.settingsRootElement).setName("Publish key").setDesc(
        'Note property key used to mark a note as eligible to publish. Quartz Syncer will ignore all notes without this property. By default "publish".'
      ).addText(
        (text2) => text2.setPlaceholder("publish").setValue(this.settings.settings.publishFrontmatterKey).onChange(async (value) => {
          if (value.length === 0) {
            value = "publish";
          }
          this.settings.settings.publishFrontmatterKey = value;
          await this.settings.plugin.saveSettings();
        })
      );
    }
  }
  /**
   * Initializes the setting to make all notes publishable by default.
   * This method allows users to override the publish key setting and make all notes eligible for publication.
   */
  initializeAllNotesPublishableByDefaultSetting() {
    new import_obsidian19.Setting(this.settingsRootElement).setName("All notes publishable by default").setDesc(
      "Make all notes publishable by default. This will override the publish key setting and make all notes eligible for publication."
    ).addToggle(
      (toggle) => toggle.setValue(
        this.settings.settings.allNotesPublishableByDefault
      ).onChange(async (value) => {
        this.settings.settings.allNotesPublishableByDefault = value;
        await this.settings.plugin.saveSettings();
        this.display();
      })
    );
  }
  /**
   * Initializes the setting to include all frontmatter properties.
   * This method allows users to include all note properties in the Quartz Syncer note,
   * overriding other property settings.
   */
  initializeIncludeAllFrontmatterSetting() {
    new import_obsidian19.Setting(this.settingsRootElement).setName("Include all properties").setDesc(
      "Include all note properties in the Quartz Syncer note. Enabling this will overrides other property settings to include all properties keys and values. Even note properties that are not used by Quartz will be included in the note's frontmatter. You shouldn't need this setting unless you have Quartz components that require non-standard properties."
    ).addToggle(
      (toggle) => toggle.setValue(this.settings.settings.includeAllFrontmatter).onChange(async (value) => {
        this.settings.settings.includeAllFrontmatter = value;
        await this.settings.plugin.saveSettings();
        this.display();
      })
    );
  }
  /**
   * Initializes the setting to show the created timestamp in the note's properties.
   * This method allows users to include the created timestamp in the Quartz Syncer note's frontmatter.
   */
  initializeShowCreatedTimestampSetting() {
    if (!this.settings.settings.includeAllFrontmatter) {
      new import_obsidian19.Setting(this.settingsRootElement).setName("Include created timestamp").setDesc(
        "Include the created timestamp in your note's properties."
      ).addToggle(
        (toggle) => toggle.setValue(this.settings.settings.showCreatedTimestamp).setDisabled(
          this.settings.settings.includeAllFrontmatter
        ).onChange(async (value) => {
          this.settings.settings.showCreatedTimestamp = value;
          await this.settings.plugin.saveSettings();
          this.display();
        })
      );
    }
  }
  /**
   * Initializes the setting to configure the created timestamp keys.
   * This method allows users to configure a comma-separated list of keys to look for to determine the created timestamp.
   */
  initializeCreatedTimestampKeysSetting() {
    if (!this.settings.settings.includeAllFrontmatter && this.settings.settings.showCreatedTimestamp) {
      new import_obsidian19.Setting(this.settingsRootElement).setName("Created timestamp keys").setDesc(
        "Comma-separated list of keys to look for to determine the created timestamp. By default, Quartz Syncer will look for 'created', 'created_at', and 'date'."
      ).addText(
        (text2) => text2.setPlaceholder("created, created_at, date").setValue(this.settings.settings.createdTimestampKey).setDisabled(
          this.settings.settings.includeAllFrontmatter
        ).onChange(async (value) => {
          if (value.length === 0 || this.settings.settings.createdTimestampKey === "") {
            value = "created, created_at, date";
          }
          this.settings.settings.createdTimestampKey = value;
          await this.settings.plugin.saveSettings();
        })
      );
    }
  }
  /**
   * Initializes the setting to show the updated timestamp in the note's properties.
   * This method allows users to include the updated timestamp in the Quartz Syncer note's frontmatter.
   */
  initializeShowUpdatedTimestampSetting() {
    if (!this.settings.settings.includeAllFrontmatter) {
      new import_obsidian19.Setting(this.settingsRootElement).setName("Include modified timestamp").setDesc(
        "Include the modified timestamp in your note's properties."
      ).addToggle(
        (toggle) => toggle.setValue(this.settings.settings.showUpdatedTimestamp).setDisabled(
          this.settings.settings.includeAllFrontmatter
        ).onChange(async (value) => {
          this.settings.settings.showUpdatedTimestamp = value;
          await this.settings.plugin.saveSettings();
          this.display();
        })
      );
    }
  }
  /**
   * Initializes the setting to configure the updated timestamp keys.
   * This method allows users to configure a comma-separated list of keys to look for to determine the updated timestamp.
   */
  initializeUpdatedTimestampKeysSetting() {
    if (!this.settings.settings.includeAllFrontmatter && this.settings.settings.showUpdatedTimestamp) {
      new import_obsidian19.Setting(this.settingsRootElement).setName("Modified timestamp keys").setDesc(
        "Comma-separated list of keys to look for to determine the modified timestamp. By default, Quartz Syncer will look for 'modified', 'lastmod', 'updated', and 'last-modified'."
      ).addText(
        (text2) => text2.setPlaceholder(
          "modified, lastmod, updated, last-modified"
        ).setValue(this.settings.settings.updatedTimestampKey).setDisabled(
          this.settings.settings.includeAllFrontmatter
        ).onChange(async (value) => {
          if (value.length === 0 || this.settings.settings.updatedTimestampKey === "") {
            value = "modified, lastmod, updated, last-modified";
          }
          this.settings.settings.updatedTimestampKey = value;
          await this.settings.plugin.saveSettings();
        })
      );
    }
  }
  /**
   * Initializes the setting to show the published timestamp in the note's properties.
   * This method allows users to include the published timestamp in the Quartz Syncer note's frontmatter.
   */
  initializeShowPublishedTimestampSetting() {
    if (!this.settings.settings.includeAllFrontmatter) {
      new import_obsidian19.Setting(this.settingsRootElement).setName("Include published timestamp").setDesc(
        "Include the published timestamp in your note's properties."
      ).addToggle(
        (toggle) => toggle.setValue(this.settings.settings.showPublishedTimestamp).setDisabled(
          this.settings.settings.includeAllFrontmatter
        ).onChange(async (value) => {
          this.settings.settings.showPublishedTimestamp = value;
          await this.settings.plugin.saveSettings();
          this.display();
        })
      );
    }
  }
  /**
   * Initializes the setting to configure the published timestamp keys.
   * This method allows users to configure a comma-separated list of keys to look for to determine the published timestamp.
   */
  initializePublishedTimestampKeysSetting() {
    if (!this.settings.settings.includeAllFrontmatter && this.settings.settings.showPublishedTimestamp) {
      new import_obsidian19.Setting(this.settingsRootElement).setName("Published timestamp keys").setDesc(
        "Comma-separated list of keys to look for to determine the published timestamp. By default, Quartz Syncer will look for 'published', 'publishDate', and 'date'."
      ).addText(
        (text2) => text2.setPlaceholder("published, publishDate, date").setValue(this.settings.settings.publishedTimestampKey).setDisabled(
          this.settings.settings.includeAllFrontmatter
        ).onChange(async (value) => {
          if (value.length === 0 || this.settings.settings.publishedTimestampKey === "") {
            value = "published, publishDate, date";
          }
          this.settings.settings.publishedTimestampKey = value;
          await this.settings.plugin.saveSettings();
        })
      );
    }
  }
  /**
   * Initializes the setting to enable permalinks in the note's properties.
   * This method allows users to use the note's permalink as the Quartz note's URL
   * even if "permalink" is not in the frontmatter.
   */
  initializeEnablePermalinkSetting() {
    new import_obsidian19.Setting(this.settingsRootElement).setName("Enable permalinks").setDesc(
      `Use the note's permalink as the Quartz note's URL if "permalink" is not in the frontmatter. This will override the default Quartz URL.`
    ).addToggle(
      (toggle) => toggle.setValue(this.settings.settings.usePermalink).setDisabled(this.settings.settings.includeAllFrontmatter).onChange(async (value) => {
        this.settings.settings.usePermalink = value;
        await this.settings.plugin.saveSettings();
      })
    );
  }
};

// src/views/SettingsView/Views/IntegrationSettings.ts
init_esbuild_buffer_shim();
var import_obsidian20 = require("obsidian");
var IntegrationSettings = class extends import_obsidian20.PluginSettingTab {
  app;
  plugin;
  settings;
  settingsRootElement;
  constructor(app2, plugin, settings, settingsRootElement) {
    super(app2, plugin);
    this.app = app2;
    this.plugin = plugin;
    this.settings = settings;
    this.settingsRootElement = settingsRootElement;
  }
  display() {
    this.settingsRootElement.empty();
    this.settingsRootElement.addClass("quartz-syncer-github-settings");
    this.initializePluginIntegrationHeader();
    for (const integration of integrationRegistry.getAll()) {
      this.initializeIntegrationSetting(integration);
    }
    this.initializeStylesHeader();
    this.initializeManageSyncerStylesSetting();
    this.settings.settings.lastUsedSettingsTab = "integration";
    this.settings.plugin.saveSettings();
  }
  initializePluginIntegrationHeader() {
    new import_obsidian20.Setting(this.settingsRootElement).setName("Plugin integration").setDesc(
      "Quartz Syncer will use these Obsidian plugins with your Quartz notes."
    ).setHeading();
  }
  initializeIntegrationSetting(integration) {
    const isAvailable = integration.isAvailable();
    const settingKey = integration.settingKey;
    const currentValue = this.settings.settings[settingKey];
    new import_obsidian20.Setting(this.settingsRootElement).setName(`Enable ${integration.name} integration`).setDesc(this.getIntegrationDescription(integration.id)).addToggle(
      (toggle) => toggle.setValue(currentValue && isAvailable).setDisabled(!isAvailable).onChange(async (value) => {
        this.settings.settings[settingKey] = value && isAvailable;
        await this.settings.plugin.saveSettings();
      })
    ).setClass(
      isAvailable ? "quartz-syncer-settings-enabled" : "quartz-syncer-settings-disabled"
    );
  }
  getIntegrationDescription(integrationId) {
    const descriptions = {
      dataview: "Converts Dataview queries into Quartz-compatible markdown.",
      datacore: "Converts Datacore queries into Quartz-compatible markdown. Currently experimental.",
      excalidraw: "Converts Excalidraw drawings into Quartz-compatible format.",
      "fantasy-statblocks": "Converts Fantasy Statblocks queries into Quartz-compatible format.",
      "auto-card-link": "Converts Auto Card Link queries into Quartz-compatible markdown."
    };
    return descriptions[integrationId] ?? `Enables ${integrationId} integration.`;
  }
  initializeStylesHeader() {
    new import_obsidian20.Setting(this.settingsRootElement).setName("Integration styles").setDesc(
      "Settings for managing integration styles in your Quartz project."
    ).setHeading();
  }
  initializeManageSyncerStylesSetting() {
    new import_obsidian20.Setting(this.settingsRootElement).setName("Manage integration styles").setDesc(
      "When enabled, Quartz Syncer will automatically write SCSS files for enabled integrations and ensure custom.scss imports them."
    ).addToggle(
      (toggle) => toggle.setValue(this.settings.settings.manageSyncerStyles).onChange(async (value) => {
        this.settings.settings.manageSyncerStyles = value;
        await this.settings.plugin.saveSettings();
      })
    );
  }
};

// src/views/SettingsView/Views/PerformanceSettings.ts
init_esbuild_buffer_shim();
var import_obsidian21 = require("obsidian");
var PerformanceSettings = class extends import_obsidian21.PluginSettingTab {
  app;
  plugin;
  settings;
  settingsRootElement;
  constructor(app2, plugin, settings, settingsRootElement) {
    super(app2, plugin);
    this.app = app2;
    this.plugin = plugin;
    this.settings = settings;
    this.settingsRootElement = settingsRootElement;
    this.settingsRootElement.classList.add("settings-tab-content");
  }
  /**
   * Displays the performance settings.
   * This method initializes the performance settings UI and sets up event listeners.
   */
  display() {
    this.settingsRootElement.empty();
    this.settingsRootElement.addClass("quartz-syncer-github-settings");
    this.initializePerformanceHeader();
    this.initializeEnableCacheSetting();
    this.initializeSyncCacheSetting();
    this.initializePersistCacheSetting();
    this.initializeClearCacheSetting();
    this.settings.settings.lastUsedSettingsTab = "performance";
    this.settings.plugin.saveSettings();
  }
  /**
   * Initializes the performance settings header.
   * This method creates a header for the performance settings section.
   */
  initializePerformanceHeader = () => {
    new import_obsidian21.Setting(this.settingsRootElement).setName("Performance").setDesc(
      "Quartz Syncer will use these settings to improve performance."
    ).setHeading();
  };
  /**
   * Initializes the enable cache setting.
   * This method creates a toggle for enabling or disabling the Quartz Syncer cache.
   */
  initializeEnableCacheSetting = () => {
    new import_obsidian21.Setting(this.settingsRootElement).setName("Enable caching").setDesc(
      "Enable or disable the Quartz Syncer cache. This can improve performance by storing compiled files locally."
    ).addToggle(
      (toggle) => toggle.setValue(this.settings.settings.useCache).onChange((value) => {
        this.settings.settings.useCache = value;
        this.settings.plugin.saveSettings();
        if (!value) {
          this.plugin.datastore.persister.clear();
          new import_obsidian21.Notice(
            "Quartz Syncer: Cache disabled. All cached data will be cleared."
          );
        }
        this.display();
      })
    );
  };
  /**
   * Initializes the sync cache setting.
   * This method creates a toggle for enabling or disabling the sync cache feature.
   * The sync cache feature allows the cache to be written to `data.json` for syncing across devices.
   */
  initializeSyncCacheSetting = () => {
    if (this.settings.settings.useCache) {
      new import_obsidian21.Setting(this.settingsRootElement).setName("Synchronize cache between devices").setDesc(
        "Whether to write the cache to `data.json`. This is useful for syncing the cache across devices. It is recommended to enable this setting if you are using Quartz Syncer on multiple devices."
      ).addToggle(
        (toggle) => toggle.setValue(this.settings.settings.syncCache).onChange((value) => {
          this.settings.settings.syncCache = value;
          this.settings.plugin.saveSettings();
        })
      );
    }
  };
  /**
   * Initializes the persist cache setting.
   * This method creates a toggle for enabling or disabling the persistence of the cache.
   * When enabled, the cache will not be removed when the plugin is unloaded
   * This is useful for users that start Obsidian with the plugin disabled.
   * For example, when using plugins that lazy-load Obsidian plugins.
   * When disabled, the cache will be removed when the plugin is unloaded.
   */
  initializePersistCacheSetting = () => {
    if (this.settings.settings.useCache) {
      new import_obsidian21.Setting(this.settingsRootElement).setName("Persist cache after unload").setDesc(
        "Whether to persist the cache when the plugin is unloaded. This is useful for users that start Obsidian with the plugin disabled."
      ).addToggle(
        (toggle) => toggle.setValue(this.settings.settings.persistCache).onChange((value) => {
          this.settings.settings.persistCache = value;
          this.settings.plugin.saveSettings();
        })
      );
    }
  };
  /**
   * Initializes the clear cache setting.
   * This method creates a button for clearing the Quartz Syncer cache.
   * When clicked, it will remove all cached files and force a re-fetch of all data from the remote repository.
   */
  initializeClearCacheSetting = () => {
    if (this.settings.settings.useCache) {
      new import_obsidian21.Setting(this.settingsRootElement).setName("Clear cache").setDesc(
        "Clear the Quartz Syncer cache. This will remove all cached files and force a re-fetch of all data from the remote repository."
      ).addButton(
        (button) => button.setButtonText("Clear cache").setCta().onClick(async () => {
          await this.plugin.datastore.dropAllFiles();
          this.settings.settings.cache = "{}";
          this.settings.plugin.saveSettings();
          new import_obsidian21.Notice("Quartz Syncer: cache cleared.");
        })
      );
    }
  };
};

// src/views/SettingsView/Views/ThemesSettings.ts
init_esbuild_buffer_shim();
var import_obsidian22 = require("obsidian");
var ThemesSettings = class extends import_obsidian22.PluginSettingTab {
  app;
  plugin;
  settings;
  settingsRootElement;
  constructor(app2, plugin, settings, settingsRootElement) {
    super(app2, plugin);
    this.app = app2;
    this.plugin = plugin;
    this.settings = settings;
    this.settingsRootElement = settingsRootElement;
    this.settingsRootElement.classList.add("settings-tab-content");
  }
  /**
   * Display the settings for Quartz themes.
   * This method initializes the settings UI for managing Quartz themes.
   */
  display() {
    this.settingsRootElement.empty();
    this.settingsRootElement.addClass("quartz-syncer-github-settings");
    this.initializeThemesHeader();
    this.initializeThemeSetting();
    this.settings.settings.lastUsedSettingsTab = "themes";
    this.settings.plugin.saveSettings();
  }
  /**
   * Unload the settings tab.
   * This method is called when the settings tab is unloaded.
   */
  initializeThemesHeader = () => {
    new import_obsidian22.Setting(this.settingsRootElement).setName("Themes").setDesc(
      "Quartz Themes is a project that aims to regularly convert Obsidian themes to a Quartz-compatible format. Quartz Syncer will install the chosen theme in Quartz from the Quartz Themes repository."
    ).setHeading();
  };
  /**
   * Initialize the theme setting.
   * This method creates a toggle for enabling or disabling the use of themes in Quartz.
   */
  initializeThemeSetting = () => {
    new import_obsidian22.Setting(this.settingsRootElement).setName("Theme").setDesc("Select the theme for your Quartz site.").addToggle(
      (toggle) => toggle.setValue(this.settings.settings.useThemes).setValue(false).setDisabled(true).onChange((value) => {
        this.settings.settings.useThemes = value;
        this.settings.plugin.saveSettings();
      })
    ).setClass("quartz-syncer-settings-upcoming");
  };
};

// src/views/SettingsView/Views/UISettings.ts
init_esbuild_buffer_shim();
var import_obsidian23 = require("obsidian");
var UISettings = class extends import_obsidian23.PluginSettingTab {
  app;
  plugin;
  settings;
  settingsRootElement;
  constructor(app2, plugin, settings, settingsRootElement) {
    super(app2, plugin);
    this.app = app2;
    this.plugin = plugin;
    this.settings = settings;
    this.settingsRootElement = settingsRootElement;
    this.settingsRootElement.classList.add("settings-tab-content");
  }
  display() {
    this.settingsRootElement.empty();
    this.settingsRootElement.addClass("quartz-syncer-github-settings");
    this.initializeUIHeader();
    this.initializeDiffViewStyleSetting();
    this.settings.settings.lastUsedSettingsTab = "ui";
    this.settings.plugin.saveSettings();
  }
  initializeUIHeader = () => {
    new import_obsidian23.Setting(this.settingsRootElement).setName("User Interface").setDesc("Customize the appearance and behavior of Quartz Syncer.").setHeading();
  };
  initializeDiffViewStyleSetting = () => {
    new import_obsidian23.Setting(this.settingsRootElement).setName("Diff view style").setDesc(
      "Choose how differences are displayed when comparing local and published files."
    ).addDropdown(
      (dropdown) => dropdown.addOption(
        "auto",
        "Auto (Split on desktop, Unified on mobile)"
      ).addOption("split", "Always Split (side-by-side)").addOption("unified", "Always Unified (single column)").setValue(this.settings.settings.diffViewStyle).onChange(async (value) => {
        this.settings.settings.diffViewStyle = value;
        await this.settings.plugin.saveSettings();
      })
    );
  };
};

// src/views/SettingsView/SettingView.ts
var SettingView = class {
  app;
  plugin;
  settingsRootElement;
  settings;
  datastore;
  constructor(app2, plugin, settingsRootElement, settings, datastore) {
    this.app = app2;
    this.plugin = plugin;
    this.settingsRootElement = settingsRootElement;
    this.settingsRootElement.classList.add("quartz-syncer-settings");
    if (import_obsidian24.Platform.isDesktop)
      this.settingsRootElement.classList.add("quartz-syncer-desktop");
    else if (import_obsidian24.Platform.isMobile)
      this.settingsRootElement.classList.add("quartz-syncer-mobile");
    this.settings = settings;
    this.datastore = datastore;
  }
  /**
   * Returns an icon element for the given name.
   * If the icon is not found, it returns a span element.
   *
   * @param name - The name of the icon to retrieve.
   * @returns A Node representing the icon.
   */
  getIcon(name) {
    return (0, import_obsidian24.getIcon)(name) ?? document.createElement("span");
  }
  /**
   * Initializes the settings view.
   * It creates the description, header, and content sections.
   * It also sets up the tabs and their corresponding settings views.
   */
  async initialize() {
    this.settingsRootElement.empty();
    const descriptionDiv = this.settingsRootElement.createEl("div", {
      cls: "quartz-syncer-settings-description"
    });
    descriptionDiv.createEl("span", {
      text: "Remember to read the "
    });
    descriptionDiv.createEl("a", {
      text: "documentation",
      href: "https://saberzero1.github.io/quartz-syncer-docs/"
    });
    descriptionDiv.createEl("span", {
      text: " if you haven't already. A "
    });
    descriptionDiv.createEl("a", {
      text: "setup guide",
      href: "https://saberzero1.github.io/quartz-syncer-docs/Setup-Guide"
    });
    descriptionDiv.createEl("span", {
      text: " and a "
    });
    descriptionDiv.createEl("a", {
      text: "usage guide",
      href: "https://saberzero1.github.io/quartz-syncer-docs/Usage-Guide"
    });
    descriptionDiv.createEl("span", {
      text: " are also available. If you encounter any issues, please see the "
    });
    descriptionDiv.createEl("a", {
      text: "troubleshooting section",
      href: "https://saberzero1.github.io/quartz-syncer-docs/Troubleshooting/"
    });
    descriptionDiv.createEl("span", {
      text: " for help."
    });
    const header = this.settingsRootElement.createEl("div", {
      cls: "quartz-syncer-setting-header"
    });
    const headerTabGroup = header.createEl("div", {
      cls: "quartz-syncer-setting-tab-group"
    });
    const gitTab = this.createTab("Git", "git-branch");
    const quartzTab = this.createTab("Quartz", "quartz-syncer-icon");
    const frontmatterTab = this.createTab("Frontmatter", "archive");
    const integrationTab = this.createTab("Integration", "cable");
    const performanceTab = this.createTab("Performance", "zap");
    const themesTab = this.createTab("Themes", "palette");
    const uiTab = this.createTab("UI", "layout");
    headerTabGroup.appendChild(gitTab);
    headerTabGroup.appendChild(quartzTab);
    headerTabGroup.appendChild(frontmatterTab);
    headerTabGroup.appendChild(integrationTab);
    headerTabGroup.appendChild(performanceTab);
    headerTabGroup.appendChild(themesTab);
    headerTabGroup.appendChild(uiTab);
    const content = this.settingsRootElement.createEl("div", {
      cls: "quartz-syncer-setting-content"
    });
    const settingTabs = [];
    settingTabs.push(
      new GitSettings(
        this.app,
        this.plugin,
        this,
        this.createSettingsTab(content, "Git")
      )
    );
    settingTabs.push(
      new QuartzSettings(
        this.app,
        this.plugin,
        this,
        this.createSettingsTab(content, "Quartz")
      )
    );
    settingTabs.push(
      new FrontmatterSettings(
        this.app,
        this.plugin,
        this,
        this.createSettingsTab(content, "Frontmatter")
      )
    );
    settingTabs.push(
      new IntegrationSettings(
        this.app,
        this.plugin,
        this,
        this.createSettingsTab(content, "Integration")
      )
    );
    settingTabs.push(
      new PerformanceSettings(
        this.app,
        this.plugin,
        this,
        this.createSettingsTab(content, "Performance")
      )
    );
    settingTabs.push(
      new ThemesSettings(
        this.app,
        this.plugin,
        this,
        this.createSettingsTab(content, "Themes")
      )
    );
    settingTabs.push(
      new UISettings(
        this.app,
        this.plugin,
        this,
        this.createSettingsTab(content, "UI")
      )
    );
    const tabs = this.settingsRootElement.querySelectorAll(
      "[data-quartz-syncer-tab]"
    );
    tabs.forEach((tab) => {
      tab.addEventListener("click", () => {
        const tabName = tab.getAttribute("data-quartz-syncer-tab");
        if (tabName) {
          this.setActiveTab(tabName, settingTabs);
        }
      });
    });
    this.setActiveTab(
      this.settings.lastUsedSettingsTab ?? "git",
      settingTabs
    );
  }
  /**
   * Creates a settings tab element with the specified name and icon.
   *
   * @param name - The name of the tab.
   * @param icon - The icon to display in the tab.
   * @returns The created tab element.
   */
  createTab(name, icon) {
    const tab = this.settingsRootElement.createEl("div", {
      cls: "quartz-syncer-navigation-item",
      attr: { "data-quartz-syncer-tab": name.toLowerCase() }
    });
    tab.createEl("span", {
      cls: "quartz-syncer-navigation-item-icon"
    }).appendChild(this.getIcon(icon));
    tab.createEl("span", {
      text: name,
      cls: "quartz-syncer-navigation-item-text"
    });
    return tab;
  }
  /**
   * Creates a settings tab content element with the specified name.
   *
   * @param parent - The parent element to append the tab to.
   * @param name - The name of the tab.
   * @returns The created tab content element.
   */
  createSettingsTab(parent, name) {
    const tab = parent.createEl("div", {
      cls: "quartz-syncer-tab-settings"
    });
    tab.id = `quartz-syncer-settings-tab-${name.toLowerCase()}`;
    return tab;
  }
  /**
   * Sets the active tab and displays the corresponding settings view.
   *
   * @param tabName - The name of the tab to set as active.
   * @param settingTabs - The collection of setting tabs to display.
   */
  setActiveTab(tabName, settingTabs) {
    const tabs = this.settingsRootElement.querySelectorAll(
      "[data-quartz-syncer-tab]"
    );
    tabs.forEach((tab) => {
      if (tab.getAttribute("data-quartz-syncer-tab") === tabName) {
        tab.addClass("quartz-syncer-navigation-item-active");
      } else {
        tab.removeClass("quartz-syncer-navigation-item-active");
      }
    });
    this.settingsRootElement.querySelectorAll(".quartz-syncer-tab-settings").forEach((tabContent, index) => {
      if (tabContent.id === `quartz-syncer-settings-tab-${tabName}`) {
        tabContent.classList.add(
          "quartz-syncer-tab-settings-active"
        );
        settingTabs[index].display();
      } else {
        tabContent.classList.remove(
          "quartz-syncer-tab-settings-active"
        );
      }
    });
  }
};

// src/views/QuartzSyncerSettingTab.ts
var QuartzSyncerSettingTab = class extends import_obsidian25.PluginSettingTab {
  app;
  plugin;
  constructor(app2, plugin) {
    super(app2, plugin);
    this.app = app2;
    this.plugin = plugin;
    if (!this.plugin.settings.noteSettingsIsInitialized) {
      this.plugin.settings.noteSettingsIsInitialized = true;
      this.plugin.saveSettings();
    }
  }
  /**
   * Display the settings tab.
   * This method initializes the SettingView and displays it in the container element.
   */
  async display() {
    const { containerEl } = this;
    const settingView = new SettingView(
      this.app,
      this.plugin,
      containerEl,
      this.plugin.settings,
      this.plugin.datastore
    );
    await settingView.initialize();
  }
};

// src/publishFile/DataStore.ts
init_esbuild_buffer_shim();
var import_localforage = __toESM(require_localforage());
var DataStore = class {
  /**
   * Create a new DataStore instance for caching metadata about files and sections.
   *
   * @param vaultName - The name of the vault to use for the cache instance.
   * @param appId - The application ID to use for the cache instance.
   * @param version - The version of the application to use for the cache instance.
   */
  constructor(vaultName, appId, version2) {
    this.vaultName = vaultName;
    this.appId = appId;
    this.version = version2;
    this.persister = import_localforage.default.createInstance({
      name: `quartz-syncer/cache/${vaultName}/${appId}/${version2}`,
      driver: [import_localforage.default.INDEXEDDB],
      description: "Cache metadata about files and sections in the quartz syncer index."
    });
  }
  persister;
  /**
   * Drop the entire cache instance and re-create a new fresh instance.
   *
   * @returns A promise that resolves when the cache is recreated.
   */
  async recreate() {
    await import_localforage.default.dropInstance({
      name: `quartz-syncer/cache/${this.vaultName}/${this.appId}/${this.version}`
    });
    await this.dropOutdatedCache();
    this.persister = import_localforage.default.createInstance({
      name: `quartz-syncer/cache/${this.vaultName}/${this.appId}/${this.version}`,
      driver: [import_localforage.default.INDEXEDDB],
      description: "Cache metadata about files and sections in the quartz syncer index."
    });
  }
  /**
   * Drop outdated cache instance. This is used to clear the cache when the version changes.
   *
   * returns A promise that resolves when the cache is dropped.
   */
  async dropOutdatedCache() {
    const instances = await indexedDB.databases();
    const matchingInstances = instances.filter(
      (instance6) => instance6.name && instance6.name.startsWith(
        `quartz-syncer/cache/${this.vaultName}/${this.appId}/`
      ) && instance6.name !== `quartz-syncer/cache/${this.vaultName}/${this.appId}/${this.version}`
      // Exclude the current version
    );
    for (const instance6 of matchingInstances) {
      indexedDB.deleteDatabase(instance6.name);
    }
  }
  /**
   * Check if a local file is outdated compared to the given timestamp and version.
   *
   * @param path - The file path to check for outdated status.
   * @param timestamp - The UNIX epoch time in milliseconds to compare against.
   * @returns A promise that resolves to true if the local file is outdated, false otherwise.
   */
  async isLocalFileOutdated(path, timestamp) {
    const data = await this.persister.getItem(
      this.fileKey(path)
    );
    if (data && data.localData) {
      if (data.hasDynamicContent) {
        return true;
      }
      return data.time < timestamp || data.version !== this.version;
    }
    return true;
  }
  /**
   * Check if a cached file has dynamic content flag set.
   *
   * @param path - The file path to check.
   * @returns A promise that resolves to true if the file has dynamic content, false otherwise.
   */
  async hasDynamicContentFlag(path) {
    const data = await this.persister.getItem(
      this.fileKey(path)
    );
    return data?.hasDynamicContent ?? false;
  }
  /**
   * Check if the remote file is outdated compared to the current version.
   *
   * @param path - The file path to check for outdated status.
   * @returns A promise that resolves to true if the remote file is outdated, false otherwise.
   */
  async isRemoteFileOutdated(path) {
    const data = await this.persister.getItem(
      this.fileKey(path)
    );
    if (data && data.remoteData) {
      return data.version !== this.version;
    }
    return true;
  }
  /**
   * Check if the local and remote files are identical in the cache.
   *
   * @param path - The file path to check for identity.
   * @returns A promise that resolves to true if they are identical, false otherwise.
   */
  async areLocalAndRemoteIdentical(path) {
    const data = await this.persister.getItem(
      this.fileKey(path)
    );
    if (data && data.localData && data.remoteData) {
      return data.localHash === data.remoteHash && data.version === this.version;
    }
    return false;
  }
  /**
   * Load a local file from the cache.
   *
   * @param path - The file path to load the local file for.
   * @returns A promise that resolves to the local file data, or null if not found.
   */
  async loadLocalFile(path) {
    const data = await this.persister.getItem(
      this.fileKey(path)
    );
    if (data && data.localData) {
      return data.localData;
    }
    return null;
  }
  /**
   * Load a remote file from the cache.
   *
   * @param path - The file path to load the remote file for.
   * @returns A promise that resolves to the remote file data, or null if not found.
   */
  async loadRemoteFile(path) {
    const data = await this.persister.getItem(
      this.fileKey(path)
    );
    if (data && data.remoteData) {
      return data.remoteData;
    }
    return null;
  }
  /**
   * Store a local file in the cache.
   *
   * @param path - The file path to store the local file for.
   * @param timestamp - The UNIX epoch time in milliseconds to set for the data.
   * @param data - The local file data to store.
   * @param hasDynamicContent - Whether the file contains dynamic content (Dataview, Datacore, etc.).
   */
  async storeLocalFile(path, timestamp, data, hasDynamicContent2) {
    const existingData = await this.persister.getItem(
      this.fileKey(path)
    );
    await this.persister.setItem(this.fileKey(path), {
      version: this.version,
      time: timestamp ?? Date.now(),
      localData: data,
      localHash: existingData?.localHash ?? generateBlobHash(data[0]),
      remoteData: existingData?.remoteData ?? null,
      // Preserve remote data if it exists
      remoteHash: existingData?.remoteHash,
      // Preserve remote hash if it exists
      hasDynamicContent: hasDynamicContent2 ?? existingData?.hasDynamicContent
    });
  }
  /**
   * Store a remote file in the cache.
   *
   * @param path - The file path to store the remote file for.
   * @param timestamp - The UNIX epoch time in milliseconds to set for the data.
   * @param data - The remote file data to store.
   */
  async storeRemoteFile(path, timestamp, data) {
    const existingData = await this.persister.getItem(
      this.fileKey(path)
    );
    await this.persister.setItem(this.fileKey(path), {
      version: this.version,
      time: timestamp ?? Date.now(),
      localData: existingData?.localData ?? null,
      // Preserve local data if it exists
      localHash: existingData?.localHash,
      // Preserve local hash if it exists
      remoteData: data,
      remoteHash: existingData?.remoteHash,
      // Preserve remote hash if it exists
      hasDynamicContent: existingData?.hasDynamicContent
      // Preserve dynamic content flag
    });
  }
  /**
   * Load the local file hash from the cache.
   *
   * @param path - The file path to load the local hash for.
   * @returns A promise that resolves to the local hash, or null if not found.
   */
  async loadLocalHash(path) {
    const data = await this.persister.getItem(
      this.fileKey(path)
    );
    if (data && data.localHash) {
      return data.localHash;
    }
    return null;
  }
  /**
   * Load the remote file hash from the cache.
   *
   * @param path - The file path to load the remote hash for.
   * @returns A promise that resolves to the remote hash, or null if not found.
   */
  async loadRemoteHash(path) {
    const data = await this.persister.getItem(
      this.fileKey(path)
    );
    if (data && data.remoteHash) {
      return data.remoteHash;
    }
    return null;
  }
  /**
   * Store a local file hash in the cache.
   *
   * @param path - The file path to store the local hash for.
   * @param timestamp - The UNIX epoch time in milliseconds to set for the data.
   * @param hash - The hash of the local file.
   */
  async storeLocalHash(path, timestamp, hash) {
    const existingData = await this.persister.getItem(
      this.fileKey(path)
    );
    await this.persister.setItem(this.fileKey(path), {
      version: this.version,
      time: timestamp ?? Date.now(),
      localData: existingData?.localData ?? null,
      // Preserve local data if it exists
      localHash: hash,
      remoteData: existingData?.remoteData ?? null,
      // Preserve remote data if it exists
      remoteHash: existingData?.remoteHash,
      // Preserve remote hash if it exists
      hasDynamicContent: existingData?.hasDynamicContent
      // Preserve dynamic content flag
    });
  }
  /**
   * Store the remote file hash in the cache.
   *
   * @param path - The file path to store the remote hash for.
   * @param timestamp - The UNIX epoch time in milliseconds to set for the remote hash.
   * @param hash - The hash of the remote file to store.
   * @returns A promise that resolves when the remote hash is stored.
   */
  async storeRemoteHash(path, timestamp, hash) {
    const existingData = await this.persister.getItem(
      this.fileKey(path)
    );
    await this.persister.setItem(this.fileKey(path), {
      version: this.version,
      time: timestamp ?? Date.now(),
      localData: existingData?.localData ?? null,
      // Preserve local data if it exists
      localHash: existingData?.localHash,
      // Preserve local hash if it exists
      remoteData: existingData?.remoteData ?? null,
      // Preserve remote data if it exists
      remoteHash: hash,
      hasDynamicContent: existingData?.hasDynamicContent
      // Preserve dynamic content flag
    });
  }
  /**
   * Get the time when the file was last cached.
   *
   * @param path - The file path to get the cached time for.
   * @returns A promise that resolves to the cached time in milliseconds, or null if not found.
   */
  async getTime(path) {
    const data = await this.persister.getItem(
      this.fileKey(path)
    );
    if (data) {
      return data.time;
    }
    return null;
  }
  /**
   * Load file metadata by path.
   *
   * @param path - The file path to load metadata for.
   * @returns A promise that resolves to the cached metadata for the file, or null if not found.
   */
  async loadFile(path) {
    return this.persister.getItem(this.fileKey(path)).then((raw) => {
      return raw;
    });
  }
  /**
   * Drop a file from the cache.
   *
   * @param path - The file path to drop from the cache.
   * @returns A promise that resolves when the file is dropped.
   */
  async dropFile(path) {
    await this.persister.removeItem(this.fileKey(path));
  }
  /**
   * Drop all files in the cache.
   *
   * @returns A promise that resolves when all files are dropped.
   */
  async dropAllFiles() {
    const keys = await this.allFiles();
    for (const key of keys) {
      await this.persister.removeItem(this.fileKey(key));
    }
  }
  /**
   * Drop old file keys that no longer exist.
   *
   * @param existing - A list of existing file paths to keep in the cache.
   * @returns A promise that resolves to a set of keys that were removed from the cache.
   */
  async synchronize(existing) {
    const keys = new Set(await this.allFiles());
    for (const exist of existing) keys.delete(exist);
    for (const key of keys)
      await this.persister.removeItem(this.fileKey(key));
    return keys;
  }
  /**
   * Serializes the data store to data.json file.
   *
   * @param timestamp - The UNIX epoch time in milliseconds to set for the data.
   * @param plugin - The QuartzSyncer plugin instance to use for saving settings.
   * @returns A promise that resolves to a tuple containing the saved timestamp and the DataStore as JSON string.
   */
  async saveToDataJson(timestamp, plugin) {
    const data = {};
    const keys = await this.allKeys();
    for (const key of keys) {
      if (!key.startsWith("file:")) continue;
      const value = await this.persister.getItem(key);
      if (value) {
        data[key] = value;
      }
    }
    Object.keys(data).sort();
    const jsonData = JSON.stringify(data, null, 2);
    plugin.settings.cache = jsonData;
    await plugin.saveSettings();
    await this.setLastUpdateTimestamp(timestamp, plugin);
  }
  /**
   * Load the data store from data.json file.
   *
   * @param timestamp - The UNIX epoch time in milliseconds to set for the data.
   * @param plugin - The QuartzSyncer plugin instance to use for loading settings.
   * @returns A promise that resolves when the cache is loaded from.
   */
  async loadFromDataJson(timestamp, plugin) {
    const cache = plugin.settings.cache;
    const data = JSON.parse(cache);
    for (const [key, value] of Object.entries(data)) {
      await this.persister.setItem(key, value);
    }
    await this.setLastUpdateTimestamp(timestamp, plugin);
    return;
  }
  /**
   * Obtain a list of all metadata keys.
   *
   * @returns A list of all keys in the cache.
   */
  async allKeys() {
    return this.persister.keys();
  }
  /**
   * Obtain a list of all persisted files.
   *
   * @returns A list of file paths that are stored in the cache.
   */
  async allFiles() {
    const keys = await this.allKeys();
    return keys.filter((k) => k.startsWith("file:")).map((k) => k.substring(5));
  }
  /**
   * Get a unique key for a given file path.
   *
   * @param path - The file path to generate a key for.
   * @returns A unique key for the file, prefixed with "file:".
   */
  fileKey(path) {
    return "file:" + path;
  }
  /**
   * Get the timestamp of the last cache update.
   * @returns A promise that resolves to the timestamp of the last cache update, or null if not found.
   */
  async getLastUpdateTimestamp() {
    const timestamp = await this.persister.getItem("data.json");
    if (timestamp) {
      return timestamp;
    }
    return null;
  }
  /**
   * Set the timestamp of the last cache update.
   * @param timestamp - The UNIX epoch time in milliseconds to set for the last update.
   * @param plugin - The QuartzSyncer plugin instance to use for saving settings.
   * @returns A promise that resolves when the timestamp is set.
   */
  async setLastUpdateTimestamp(timestamp, plugin) {
    plugin.settings.cacheTimestamp = timestamp;
    await this.persister.setItem("data.json", timestamp);
    await plugin.saveSettings();
  }
};

// main.ts
var import_js_logger11 = __toESM(require_logger());
var DEFAULT_SETTINGS = {
  git: {
    remoteUrl: "",
    branch: "v4",
    corsProxyUrl: "",
    auth: {
      type: "basic",
      username: ""
    },
    providerHint: "github"
  },
  vaultPath: "/",
  // Deprecated fields kept for migration
  githubRepo: void 0,
  githubUserName: void 0,
  githubToken: void 0,
  /** Quartz settings */
  contentFolder: "content",
  useFullResolutionImages: false,
  applyEmbeds: true,
  /** Frontmatter settings */
  publishFrontmatterKey: "publish",
  allNotesPublishableByDefault: false,
  showCreatedTimestamp: true,
  showUpdatedTimestamp: true,
  showPublishedTimestamp: false,
  usePermalink: false,
  includeAllFrontmatter: false,
  frontmatterFormat: "yaml",
  /**
   * @privateRemarks
   *
   * These values are not configurable, but are the defaults in Quartz.
   * They are included here in case the user wants to change them.
   * Or to nake it easier to adapt the plugin to future changes in Quartz.
   */
  pathRewriteRules: "",
  createdTimestampKey: "created, created_at, date",
  updatedTimestampKey: "modified, lastmod, updated, last-modified",
  publishedTimestampKey: "published, publishDate, date",
  timestampFormat: "MMM dd, yyyy h:mm a",
  /** Performance settings */
  useCache: true,
  syncCache: true,
  persistCache: false,
  cacheTimestamp: 0,
  cache: "{}",
  /** Integration settings */
  /**
   * Enable Auto Card Link integration.
   * This will allow the plugin to use Auto Card Link queries in the published notes.
   *
   * Auto Card Link documentation: {@link https://github.com/nekoshita/obsidian-auto-card-link}
   */
  useAutoCardLink: false,
  /**
   * Enable Dataview integration.
   * This will allow the plugin to use Dataview queries in the published notes.
   *
   * Dataview documentation: {@link https://blacksmithgu.github.io/obsidian-dataview/}
   */
  useDataview: true,
  /**
   * Enable Datacore integration.
   * This will allow the plugin to use Excalidraw drawings in the published notes.
   *
   * Excalidraw documentation: {@link https://blacksmithgu.github.io/datacore/}
   */
  useDatacore: false,
  /**
   * Enable Excalidraw integration.
   * This will allow the plugin to use Excalidraw drawings in the published notes.
   *
   * Excalidraw documentation: {@link https://excalidraw-obsidian.online/wiki/welcome}
   */
  useExcalidraw: false,
  /**
   * Enable Fantasy Statblocks integration.
   * This will allow the plugin to use Fantasy Statblocks queries in the published notes.
   *
   * Fantasy Statblocks documentation: {@link https://plugins.javalent.com/statblocks}
   */
  useFantasyStatblocks: false,
  manageSyncerStyles: true,
  /** Themes settings */
  /**
   * Enable themes integration.
   * This will allow the plugin to use themes in the published notes.
   *
   * Themes documentation: {@link https://github.com/saberzero1/quartz-themes}
   */
  useThemes: false,
  /** Plugin state variables */
  lastUsedSettingsTab: "git",
  noteSettingsIsInitialized: false,
  pluginVersion: "",
  /** UI settings */
  diffViewStyle: "auto",
  /** Developer settings */
  ENABLE_DEVELOPER_TOOLS: false,
  logLevel: import_js_logger11.default.OFF
};
import_js_logger11.default.useDefaults({
  defaultLevel: import_js_logger11.default.WARN,
  formatter: function(messages, _context) {
    messages.unshift((/* @__PURE__ */ new Date()).toUTCString());
    messages.unshift("QS: ");
  }
});
var QuartzSyncer = class extends import_obsidian27.Plugin {
  settings;
  appVersion;
  datastore;
  secretStorageService;
  publishModal;
  /**
   * Called when the plugin is loaded.
   * Initializes the plugin, loads settings, and sets up commands and icons.
   */
  async onload() {
    this.appVersion = this.manifest.version;
    await this.loadSettings();
    if (this.settings.logLevel) import_js_logger11.default.setLevel(this.settings.logLevel);
    import_js_logger11.default.info("Initializing QuartzSyncer plugin v" + this.appVersion);
    import_js_logger11.default.info("Quartz Syncer log level set to " + import_js_logger11.default.getLevel().name);
    this.addSettingTab(new QuartzSyncerSettingTab(this.app, this));
    await this.addCommands();
    (0, import_obsidian27.addIcon)("quartz-syncer-icon", quartzSyncerIcon);
    this.addRibbonIcon(
      "quartz-syncer-icon",
      "Quartz Syncer publication center",
      async () => {
        this.openPublishModal();
      }
    );
  }
  /**
   * Called when the plugin is unloaded.
   * Cleans up resources and saves settings.
   */
  onunload() {
    if (!this.settings.persistCache) {
      this.clearCacheForAllFiles(true);
    }
    super.onunload();
  }
  /**
   * Called when the plugin settings are changed externally.
   * This method can be used to handle changes made to the settings outside of the plugin.
   */
  async onExternalSettingsChange() {
    import_js_logger11.default.info("External settings change detected, reloading settings.");
    await this.compareDataToCache();
  }
  /**
   * Loads the plugin settings from data.json.
   * If the settings file does not exist, it initializes with default settings.
   *
   * @param initialLoad - If true, indicates that this is the initial load of the plugin.
   */
  async loadSettings() {
    this.settings = Object.assign(
      {},
      DEFAULT_SETTINGS,
      await this.loadData()
    );
    this.migrateGitHubSettings();
    this.secretStorageService = new SecretStorageService(this.app);
    await this.secretStorageService.migrateFromSettings(
      this.settings,
      () => this.saveSettings()
    );
    if (!this.datastore && this.settings.useCache) {
      this.datastore = new DataStore(
        this.app.vault.getName(),
        this.manifest.id,
        this.appVersion
      );
    }
    if (!this.settings || this.settings.pluginVersion !== this.appVersion) {
      await this.clearCacheForAllFiles(true);
      this.settings.pluginVersion = this.appVersion;
    }
    await this.compareDataToCache();
  }
  /**
   * Migrates legacy GitHub-specific settings to the new generic Git settings.
   * This ensures backwards compatibility for users upgrading from older versions.
   */
  migrateGitHubSettings() {
    const hasLegacySettings = this.settings.githubRepo || this.settings.githubUserName || this.settings.githubToken;
    const hasNewSettings = this.settings.git?.remoteUrl;
    if (hasLegacySettings && !hasNewSettings) {
      import_js_logger11.default.info(
        "Migrating legacy GitHub settings to generic Git settings"
      );
      const githubRepo = this.settings.githubRepo || "quartz";
      const githubUserName = this.settings.githubUserName || "";
      const githubToken = this.settings.githubToken || "";
      this.settings.git = {
        remoteUrl: githubUserName ? `https://github.com/${githubUserName}/${githubRepo}.git` : "",
        branch: "v4",
        corsProxyUrl: "",
        auth: {
          type: "basic",
          username: githubUserName,
          secret: githubToken
        },
        providerHint: "github"
      };
      if (this.settings.lastUsedSettingsTab === "github") {
        this.settings.lastUsedSettingsTab = "git";
      }
      this.settings.githubRepo = void 0;
      this.settings.githubUserName = void 0;
      this.settings.githubToken = void 0;
    }
  }
  async saveSettings() {
    await this.saveData(this.settings);
  }
  getGitSettingsWithSecret() {
    return {
      ...this.settings.git,
      auth: {
        ...this.settings.git.auth,
        secret: this.secretStorageService.getToken() || void 0
      }
    };
  }
  /**
   * Adds commands to the plugin.
   * These commands can be triggered from the command palette or ribbon icon.
   */
  async addCommands() {
    if (this.settings["ENABLE_DEVELOPER_TOOLS"] && import_obsidian27.Platform.isDesktop) {
      import_js_logger11.default.info("Developer tools enabled");
      const publisher = new Publisher(
        this.app,
        this,
        this.app.vault,
        this.app.metadataCache,
        this.settings,
        this.datastore
      );
      Promise.resolve().then(() => (init_generateSyncerSnapshot(), generateSyncerSnapshot_exports)).then((snapshotGen) => {
        this.addCommand({
          id: "generate-snapshot",
          name: "Generate snapshot",
          callback: async () => {
            await snapshotGen.generateSyncerSnapshot(
              this.settings,
              publisher
            );
          }
        });
      }).catch((e) => {
        import_js_logger11.default.error("Unable to load generateSyncerSnapshot", e);
      });
    }
    this.addCommand({
      id: "open-publish-modal",
      name: "Open publication center",
      callback: async () => {
        this.openPublishModal();
      }
    });
    this.addCommand({
      id: "mark-note-for-publish",
      name: "Add publication flag",
      callback: async () => {
        this.setPublishFlagValue(true);
      }
    });
    this.addCommand({
      id: "unmark-note-for-publish",
      name: "Remove publication flag",
      callback: async () => {
        this.setPublishFlagValue(false);
      }
    });
    this.addCommand({
      id: "mark-toggle-publish-status",
      name: "Toggle publication flag",
      callback: async () => {
        this.togglePublishFlag();
      }
    });
    if (this.settings.useCache) {
      this.addCommand({
        id: "clear-cache-for-active-file",
        name: "Clear cache for active file",
        callback: async () => {
          await this.clearCacheForActiveFile();
        }
      });
      this.addCommand({
        id: "clear-cache-for-all-files",
        name: "Clear cache for all files",
        callback: async () => {
          await this.clearCacheForAllFiles();
        }
      });
    }
  }
  /**
   * Retrieves the currently active file in the workspace.
   * If no file is active, it shows a notice to the user.
   *
   * @param workspace - The current workspace instance.
   * @returns The active file or null if no file is active.
   */
  getActiveFile(workspace) {
    const activeFile = workspace.getActiveFile();
    if (!activeFile) {
      new import_obsidian27.Notice(
        "Quartz Syncer: No file is open/active. Please open a file and try again."
      );
      return null;
    }
    return activeFile;
  }
  /**
   * Clears the cache for the currently active file.
   * If no file is active, it does nothing.
   */
  async clearCacheForActiveFile() {
    const activeFile = this.getActiveFile(this.app.workspace);
    if (!activeFile) {
      return;
    }
    const cacheKey = `file:${activeFile.path}`;
    if (this.settings.useCache) {
      await this.datastore.persister.removeItem(cacheKey);
      this.settings.cacheTimestamp = Date.now();
      await this.saveSettings();
      await this.datastore.setLastUpdateTimestamp(
        this.settings.cacheTimestamp,
        this
      );
      import_js_logger11.default.info(`Cache cleared for file: ${activeFile.path}`);
      new import_obsidian27.Notice(
        `Quartz Syncer: Cache cleared for file: ${activeFile.path}`
      );
    } else {
      import_js_logger11.default.warn("Cache is disabled, no action taken.");
      new import_obsidian27.Notice("Quartz Syncer: Cache is disabled, no action taken.");
    }
  }
  /**
   * Clears the cache for all files.
   * This method removes all cached data from the datastore.
   * If the cache is disabled, it does nothing.
   * It will show a confirmation dialog before clearing the cache.
   *
   * @param force - If true, skips the confirmation dialog.
   */
  async clearCacheForAllFiles(force = false) {
    if (!force) {
      const confirmation = confirm(
        "Are you sure you want to clear the Quartz Syncer cache for all files? This action cannot be undone."
      );
      if (!confirmation) {
        import_js_logger11.default.info("Cache clearing cancelled by user.");
        new import_obsidian27.Notice("Quartz Syncer: Cache clearing cancelled.");
        return;
      }
      if (this.settings.useCache) {
        this.settings.cache = "{}";
        this.settings.cacheTimestamp = Date.now();
        await this.saveSettings();
        await this.datastore.setLastUpdateTimestamp(
          this.settings.cacheTimestamp,
          this
        );
        await this.datastore.recreate();
        import_js_logger11.default.info("Cache cleared for all files.");
        new import_obsidian27.Notice("Quartz Syncer: Cache cleared for all files.");
      } else {
        import_js_logger11.default.warn("Cache is disabled, no action taken.");
        new import_obsidian27.Notice(
          "Quartz Syncer: Cache is disabled, no action taken."
        );
      }
    } else {
      if (this.datastore) {
        this.settings.cache = "{}";
        this.settings.cacheTimestamp = Date.now();
        await this.saveSettings();
        await this.datastore.persister.clear();
        await this.datastore.dropOutdatedCache();
      }
    }
  }
  /**
   * Sets the publication flag value in the frontmatter of the active file.
   * If no file is active, it does nothing.
   *
   * @param value - The value to set for the publication flag.
   */
  async setPublishFlagValue(value) {
    const activeFile = this.getActiveFile(this.app.workspace);
    if (!activeFile) {
      return;
    }
    const engine = new ObsidianFrontMatterEngine(
      this.app.vault,
      this.app.metadataCache,
      activeFile,
      this.app.fileManager
    );
    engine.set(this.settings.publishFrontmatterKey, value).apply();
  }
  /**
   * Toggles the publication flag value in the frontmatter of the active file.
   * If no file is active, it does nothing.
   */
  async togglePublishFlag() {
    const activeFile = this.getActiveFile(this.app.workspace);
    if (!activeFile) {
      return;
    }
    const engine = new ObsidianFrontMatterEngine(
      this.app.vault,
      this.app.metadataCache,
      activeFile,
      this.app.fileManager
    );
    engine.set(
      this.settings.publishFrontmatterKey,
      !engine.get(this.settings.publishFrontmatterKey)
    ).apply();
  }
  /**
   * Opens the publication center modal.
   * If the modal is not already created, it initializes it with the necessary components.
   */
  openPublishModal() {
    if (!this.publishModal) {
      const siteManager = new QuartzSyncerSiteManager(
        this.app.metadataCache,
        this.settings,
        this.getGitSettingsWithSecret()
      );
      const publisher = new Publisher(
        this.app,
        this,
        this.app.vault,
        this.app.metadataCache,
        this.settings,
        this.datastore
      );
      const publishStatusManager = new PublishStatusManager(
        siteManager,
        publisher
      );
      this.publishModal = new PublicationCenter2(
        this.app,
        publishStatusManager,
        publisher,
        siteManager,
        this.settings
      );
    }
    this.publishModal.open();
  }
  /**
   * Compares the current data.json cache with the saved cache.
   * If the cache is outdated, it loads the data from the saved cache.
   * If the cache is up-to-date, it does nothing.
   *
   * @remarks
   * This method is called on plugin load and when settings are changed.
   */
  async compareDataToCache() {
    if (!this.settings.useCache || !this.settings.syncCache) {
      return;
    }
    let timestamp = await this.datastore.getLastUpdateTimestamp();
    if (timestamp === null) {
      timestamp = 0;
    }
    if (timestamp < this.settings.cacheTimestamp) {
      await this.datastore.saveToDataJson(timestamp, this);
    } else {
      await this.datastore.loadFromDataJson(timestamp, this);
    }
  }
};
//!()[blob.svg]
//![[blob.png]]
//![](blob.png)
/*! Bundled license information:

buffer-es6/index.js:
  (*!
   * The buffer module from node.js, for the browser.
   *
   * @author   Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
   * @license  MIT
   *)

js-logger/src/logger.js:
  (*!
   * js-logger - http://github.com/jonnyreeves/js-logger
   * Jonny Reeves, http://jonnyreeves.co.uk/
   * js-logger may be freely distributed under the MIT license.
   *)

safe-buffer/index.js:
safe-buffer/index.js:
  (*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> *)

crc-32/crc32.js:
  (*! crc32.js (C) 2014-present SheetJS -- http://sheetjs.com *)

isomorphic-git/index.cjs:
  (*!
   * This code for `path.join` is directly copied from @zenfs/core/path for bundle size improvements.
   * SPDX-License-Identifier: LGPL-3.0-or-later
   * Copyright (c) James Prevett and other ZenFS contributors.
   *)

localforage/dist/localforage.js:
  (*!
      localForage -- Offline Storage, Improved
      Version 1.10.0
      https://localforage.github.io/localForage
      (c) 2013-2017 Mozilla, Apache License 2.0
  *)
*/

/* nosourcemap */