import "/error/node:fs?from=esbuild";
;
import "/error/node:os?from=esbuild";
;
import "/error/unknown:pnpapi?from=esbuild";
;
import "/error/node:child_process?from=esbuild";
;
import "/error/node:crypto?from=esbuild";
;
import "/error/node:tty?from=esbuild";
;
import "/error/node:worker_threads?from=esbuild";
;
import "/error/node:node:fs?from=esbuild";
;
import "/error/node:node:os?from=esbuild";
;
import "/error/node:node:child_process?from=esbuild";
;
import "/error/node:node:crypto?from=esbuild";
;
import "/error/node:node:tty?from=esbuild";
;
import "/error/node:node:worker_threads?from=esbuild";
;
var global$1 = typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};
var lookup = [];
var revLookup = [];
var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array;
var inited = false;
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, l, 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);
  l = placeHolders > 0 ? len - 4 : len;
  var L = 0;
  for (i = 0, j = 0; i < l; 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("");
}
function read(buffer, offset, isLE, mLen, nBytes) {
  var e, m;
  var eLen = nBytes * 8 - mLen - 1;
  var eMax = (1 << eLen) - 1;
  var eBias = eMax >> 1;
  var nBits = -7;
  var i = isLE ? nBytes - 1 : 0;
  var d = isLE ? -1 : 1;
  var s = buffer[offset + i];
  i += d;
  e = s & (1 << -nBits) - 1;
  s >>= -nBits;
  nBits += eLen;
  for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {
  }
  m = e & (1 << -nBits) - 1;
  e >>= -nBits;
  nBits += mLen;
  for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {
  }
  if (e === 0) {
    e = 1 - eBias;
  } else if (e === eMax) {
    return m ? NaN : (s ? -1 : 1) * Infinity;
  } else {
    m = m + Math.pow(2, mLen);
    e = e - eBias;
  }
  return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
}
function write(buffer, value, offset, isLE, mLen, nBytes) {
  var e, m, c;
  var eLen = nBytes * 8 - mLen - 1;
  var eMax = (1 << eLen) - 1;
  var eBias = eMax >> 1;
  var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
  var i = isLE ? 0 : nBytes - 1;
  var d = isLE ? 1 : -1;
  var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
  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[offset + i] = m & 255, i += d, m /= 256, mLen -= 8) {
  }
  e = e << mLen | m;
  eLen += mLen;
  for (; eLen > 0; buffer[offset + i] = e & 255, i += d, e /= 256, eLen -= 8) {
  }
  buffer[offset + i - d] |= s * 128;
}
var toString = {}.toString;
var isArray = Array.isArray || function(arr) {
  return toString.call(arr) == "[object Array]";
};
/*!
 * The buffer module from node.js, for the browser.
 *
 * @author   Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
 * @license  MIT
 */
var INSPECT_MAX_BYTES = 50;
Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== void 0 ? global$1.TYPED_ARRAY_SUPPORT : true;
function kMaxLength() {
  return Buffer.TYPED_ARRAY_SUPPORT ? 2147483647 : 1073741823;
}
function createBuffer(that, length) {
  if (kMaxLength() < length) {
    throw new RangeError("Invalid typed array length");
  }
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    that = new Uint8Array(length);
    that.__proto__ = Buffer.prototype;
  } else {
    if (that === null) {
      that = new Buffer(length);
    }
    that.length = length;
  }
  return that;
}
function Buffer(arg, encodingOrOffset, length) {
  if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
    return new Buffer(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);
}
Buffer.poolSize = 8192;
Buffer._augment = function(arr) {
  arr.__proto__ = Buffer.prototype;
  return arr;
};
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);
}
Buffer.from = function(value, encodingOrOffset, length) {
  return from(null, value, encodingOrOffset, length);
};
if (Buffer.TYPED_ARRAY_SUPPORT) {
  Buffer.prototype.__proto__ = Uint8Array.prototype;
  Buffer.__proto__ = Uint8Array;
}
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);
}
Buffer.alloc = function(size, fill2, encoding) {
  return alloc(null, size, fill2, encoding);
};
function allocUnsafe(that, size) {
  assertSize(size);
  that = createBuffer(that, size < 0 ? 0 : checked(size) | 0);
  if (!Buffer.TYPED_ARRAY_SUPPORT) {
    for (var i = 0; i < size; ++i) {
      that[i] = 0;
    }
  }
  return that;
}
Buffer.allocUnsafe = function(size) {
  return allocUnsafe(null, size);
};
Buffer.allocUnsafeSlow = function(size) {
  return allocUnsafe(null, size);
};
function fromString(that, string, encoding) {
  if (typeof encoding !== "string" || encoding === "") {
    encoding = "utf8";
  }
  if (!Buffer.isEncoding(encoding)) {
    throw new TypeError('"encoding" must be a valid string encoding');
  }
  var length = byteLength(string, encoding) | 0;
  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 (Buffer.TYPED_ARRAY_SUPPORT) {
    that = array;
    that.__proto__ = Buffer.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(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;
}
Buffer.isBuffer = isBuffer;
function internalIsBuffer(b) {
  return !!(b != null && b._isBuffer);
}
Buffer.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;
};
Buffer.isEncoding = function isEncoding(encoding) {
  switch (String(encoding).toLowerCase()) {
    case "hex":
    case "utf8":
    case "utf-8":
    case "ascii":
    case "latin1":
    case "binary":
    case "base64":
    case "ucs2":
    case "ucs-2":
    case "utf16le":
    case "utf-16le":
      return true;
    default:
      return false;
  }
};
Buffer.concat = function concat(list, length) {
  if (!isArray(list)) {
    throw new TypeError('"list" argument must be an Array of Buffers');
  }
  if (list.length === 0) {
    return Buffer.alloc(0);
  }
  var i;
  if (length === void 0) {
    length = 0;
    for (i = 0; i < list.length; ++i) {
      length += list[i].length;
    }
  }
  var buffer = Buffer.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;
};
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;
    }
  }
}
Buffer.byteLength = byteLength;
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;
    }
  }
}
Buffer.prototype._isBuffer = true;
function swap(b, n, m) {
  var i = b[n];
  b[n] = b[m];
  b[m] = i;
}
Buffer.prototype.swap16 = function swap16() {
  var len = this.length;
  if (len % 2 !== 0) {
    throw new RangeError("Buffer size must be a multiple of 16-bits");
  }
  for (var i = 0; i < len; i += 2) {
    swap(this, i, i + 1);
  }
  return this;
};
Buffer.prototype.swap32 = function swap32() {
  var len = this.length;
  if (len % 4 !== 0) {
    throw new RangeError("Buffer size must be a multiple of 32-bits");
  }
  for (var i = 0; i < len; i += 4) {
    swap(this, i, i + 3);
    swap(this, i + 1, i + 2);
  }
  return this;
};
Buffer.prototype.swap64 = function swap64() {
  var len = this.length;
  if (len % 8 !== 0) {
    throw new RangeError("Buffer size must be a multiple of 64-bits");
  }
  for (var i = 0; i < len; i += 8) {
    swap(this, i, i + 7);
    swap(this, i + 1, i + 6);
    swap(this, i + 2, i + 5);
    swap(this, i + 3, i + 4);
  }
  return this;
};
Buffer.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);
};
Buffer.prototype.equals = function equals(b) {
  if (!internalIsBuffer(b))
    throw new TypeError("Argument must be a Buffer");
  if (this === b)
    return true;
  return Buffer.compare(this, b) === 0;
};
Buffer.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 + ">";
};
Buffer.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;
};
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 = Buffer.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 (Buffer.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;
}
Buffer.prototype.includes = function includes(val, byteOffset, encoding) {
  return this.indexOf(val, byteOffset, encoding) !== -1;
};
Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) {
  return bidirectionalIndexOf(this, val, byteOffset, encoding, true);
};
Buffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) {
  return bidirectionalIndexOf(this, val, byteOffset, encoding, false);
};
function hexWrite(buf, string, offset, length) {
  offset = Number(offset) || 0;
  var remaining = buf.length - offset;
  if (!length) {
    length = remaining;
  } else {
    length = Number(length);
    if (length > remaining) {
      length = remaining;
    }
  }
  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[offset + i] = parsed;
  }
  return i;
}
function utf8Write(buf, string, offset, length) {
  return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length);
}
function asciiWrite(buf, string, offset, length) {
  return blitBuffer(asciiToBytes(string), buf, offset, length);
}
function latin1Write(buf, string, offset, length) {
  return asciiWrite(buf, string, offset, length);
}
function base64Write(buf, string, offset, length) {
  return blitBuffer(base64ToBytes(string), buf, offset, length);
}
function ucs2Write(buf, string, offset, length) {
  return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length);
}
Buffer.prototype.write = function write2(string, offset, length, encoding) {
  if (offset === void 0) {
    encoding = "utf8";
    length = this.length;
    offset = 0;
  } else if (length === void 0 && typeof offset === "string") {
    encoding = offset;
    length = this.length;
    offset = 0;
  } else if (isFinite(offset)) {
    offset = offset | 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 - offset;
  if (length === void 0 || length > remaining)
    length = remaining;
  if (string.length > 0 && (length < 0 || offset < 0) || offset > 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, offset, length);
      case "utf8":
      case "utf-8":
        return utf8Write(this, string, offset, length);
      case "ascii":
        return asciiWrite(this, string, offset, length);
      case "latin1":
      case "binary":
        return latin1Write(this, string, offset, length);
      case "base64":
        return base64Write(this, string, offset, length);
      case "ucs2":
      case "ucs-2":
      case "utf16le":
      case "utf-16le":
        return ucs2Write(this, string, offset, length);
      default:
        if (loweredCase)
          throw new TypeError("Unknown encoding: " + encoding);
        encoding = ("" + encoding).toLowerCase();
        loweredCase = true;
    }
  }
};
Buffer.prototype.toJSON = function toJSON() {
  return {
    type: "Buffer",
    data: Array.prototype.slice.call(this._arr || this, 0)
  };
};
function base64Slice(buf, start, end) {
  if (start === 0 && end === buf.length) {
    return 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);
}
var MAX_ARGUMENTS_LENGTH = 4096;
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;
}
Buffer.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 (Buffer.TYPED_ARRAY_SUPPORT) {
    newBuf = this.subarray(start, end);
    newBuf.__proto__ = Buffer.prototype;
  } else {
    var sliceLen = end - start;
    newBuf = new Buffer(sliceLen, void 0);
    for (var i = 0; i < sliceLen; ++i) {
      newBuf[i] = this[i + start];
    }
  }
  return newBuf;
};
function checkOffset(offset, ext, length) {
  if (offset % 1 !== 0 || offset < 0)
    throw new RangeError("offset is not uint");
  if (offset + ext > length)
    throw new RangeError("Trying to access beyond buffer length");
}
Buffer.prototype.readUIntLE = function readUIntLE(offset, byteLength2, noAssert) {
  offset = offset | 0;
  byteLength2 = byteLength2 | 0;
  if (!noAssert)
    checkOffset(offset, byteLength2, this.length);
  var val = this[offset];
  var mul = 1;
  var i = 0;
  while (++i < byteLength2 && (mul *= 256)) {
    val += this[offset + i] * mul;
  }
  return val;
};
Buffer.prototype.readUIntBE = function readUIntBE(offset, byteLength2, noAssert) {
  offset = offset | 0;
  byteLength2 = byteLength2 | 0;
  if (!noAssert) {
    checkOffset(offset, byteLength2, this.length);
  }
  var val = this[offset + --byteLength2];
  var mul = 1;
  while (byteLength2 > 0 && (mul *= 256)) {
    val += this[offset + --byteLength2] * mul;
  }
  return val;
};
Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) {
  if (!noAssert)
    checkOffset(offset, 1, this.length);
  return this[offset];
};
Buffer.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) {
  if (!noAssert)
    checkOffset(offset, 2, this.length);
  return this[offset] | this[offset + 1] << 8;
};
Buffer.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) {
  if (!noAssert)
    checkOffset(offset, 2, this.length);
  return this[offset] << 8 | this[offset + 1];
};
Buffer.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) {
  if (!noAssert)
    checkOffset(offset, 4, this.length);
  return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 16777216;
};
Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) {
  if (!noAssert)
    checkOffset(offset, 4, this.length);
  return this[offset] * 16777216 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]);
};
Buffer.prototype.readIntLE = function readIntLE(offset, byteLength2, noAssert) {
  offset = offset | 0;
  byteLength2 = byteLength2 | 0;
  if (!noAssert)
    checkOffset(offset, byteLength2, this.length);
  var val = this[offset];
  var mul = 1;
  var i = 0;
  while (++i < byteLength2 && (mul *= 256)) {
    val += this[offset + i] * mul;
  }
  mul *= 128;
  if (val >= mul)
    val -= Math.pow(2, 8 * byteLength2);
  return val;
};
Buffer.prototype.readIntBE = function readIntBE(offset, byteLength2, noAssert) {
  offset = offset | 0;
  byteLength2 = byteLength2 | 0;
  if (!noAssert)
    checkOffset(offset, byteLength2, this.length);
  var i = byteLength2;
  var mul = 1;
  var val = this[offset + --i];
  while (i > 0 && (mul *= 256)) {
    val += this[offset + --i] * mul;
  }
  mul *= 128;
  if (val >= mul)
    val -= Math.pow(2, 8 * byteLength2);
  return val;
};
Buffer.prototype.readInt8 = function readInt8(offset, noAssert) {
  if (!noAssert)
    checkOffset(offset, 1, this.length);
  if (!(this[offset] & 128))
    return this[offset];
  return (255 - this[offset] + 1) * -1;
};
Buffer.prototype.readInt16LE = function readInt16LE(offset, noAssert) {
  if (!noAssert)
    checkOffset(offset, 2, this.length);
  var val = this[offset] | this[offset + 1] << 8;
  return val & 32768 ? val | 4294901760 : val;
};
Buffer.prototype.readInt16BE = function readInt16BE(offset, noAssert) {
  if (!noAssert)
    checkOffset(offset, 2, this.length);
  var val = this[offset + 1] | this[offset] << 8;
  return val & 32768 ? val | 4294901760 : val;
};
Buffer.prototype.readInt32LE = function readInt32LE(offset, noAssert) {
  if (!noAssert)
    checkOffset(offset, 4, this.length);
  return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24;
};
Buffer.prototype.readInt32BE = function readInt32BE(offset, noAssert) {
  if (!noAssert)
    checkOffset(offset, 4, this.length);
  return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3];
};
Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) {
  if (!noAssert)
    checkOffset(offset, 4, this.length);
  return read(this, offset, true, 23, 4);
};
Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) {
  if (!noAssert)
    checkOffset(offset, 4, this.length);
  return read(this, offset, false, 23, 4);
};
Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) {
  if (!noAssert)
    checkOffset(offset, 8, this.length);
  return read(this, offset, true, 52, 8);
};
Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) {
  if (!noAssert)
    checkOffset(offset, 8, this.length);
  return read(this, offset, false, 52, 8);
};
function checkInt(buf, value, offset, 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 (offset + ext > buf.length)
    throw new RangeError("Index out of range");
}
Buffer.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength2, noAssert) {
  value = +value;
  offset = offset | 0;
  byteLength2 = byteLength2 | 0;
  if (!noAssert) {
    var maxBytes = Math.pow(2, 8 * byteLength2) - 1;
    checkInt(this, value, offset, byteLength2, maxBytes, 0);
  }
  var mul = 1;
  var i = 0;
  this[offset] = value & 255;
  while (++i < byteLength2 && (mul *= 256)) {
    this[offset + i] = value / mul & 255;
  }
  return offset + byteLength2;
};
Buffer.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength2, noAssert) {
  value = +value;
  offset = offset | 0;
  byteLength2 = byteLength2 | 0;
  if (!noAssert) {
    var maxBytes = Math.pow(2, 8 * byteLength2) - 1;
    checkInt(this, value, offset, byteLength2, maxBytes, 0);
  }
  var i = byteLength2 - 1;
  var mul = 1;
  this[offset + i] = value & 255;
  while (--i >= 0 && (mul *= 256)) {
    this[offset + i] = value / mul & 255;
  }
  return offset + byteLength2;
};
Buffer.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) {
  value = +value;
  offset = offset | 0;
  if (!noAssert)
    checkInt(this, value, offset, 1, 255, 0);
  if (!Buffer.TYPED_ARRAY_SUPPORT)
    value = Math.floor(value);
  this[offset] = value & 255;
  return offset + 1;
};
function objectWriteUInt16(buf, value, offset, littleEndian) {
  if (value < 0)
    value = 65535 + value + 1;
  for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
    buf[offset + i] = (value & 255 << 8 * (littleEndian ? i : 1 - i)) >>> (littleEndian ? i : 1 - i) * 8;
  }
}
Buffer.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) {
  value = +value;
  offset = offset | 0;
  if (!noAssert)
    checkInt(this, value, offset, 2, 65535, 0);
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    this[offset] = value & 255;
    this[offset + 1] = value >>> 8;
  } else {
    objectWriteUInt16(this, value, offset, true);
  }
  return offset + 2;
};
Buffer.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) {
  value = +value;
  offset = offset | 0;
  if (!noAssert)
    checkInt(this, value, offset, 2, 65535, 0);
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    this[offset] = value >>> 8;
    this[offset + 1] = value & 255;
  } else {
    objectWriteUInt16(this, value, offset, false);
  }
  return offset + 2;
};
function objectWriteUInt32(buf, value, offset, littleEndian) {
  if (value < 0)
    value = 4294967295 + value + 1;
  for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
    buf[offset + i] = value >>> (littleEndian ? i : 3 - i) * 8 & 255;
  }
}
Buffer.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) {
  value = +value;
  offset = offset | 0;
  if (!noAssert)
    checkInt(this, value, offset, 4, 4294967295, 0);
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    this[offset + 3] = value >>> 24;
    this[offset + 2] = value >>> 16;
    this[offset + 1] = value >>> 8;
    this[offset] = value & 255;
  } else {
    objectWriteUInt32(this, value, offset, true);
  }
  return offset + 4;
};
Buffer.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) {
  value = +value;
  offset = offset | 0;
  if (!noAssert)
    checkInt(this, value, offset, 4, 4294967295, 0);
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    this[offset] = value >>> 24;
    this[offset + 1] = value >>> 16;
    this[offset + 2] = value >>> 8;
    this[offset + 3] = value & 255;
  } else {
    objectWriteUInt32(this, value, offset, false);
  }
  return offset + 4;
};
Buffer.prototype.writeIntLE = function writeIntLE(value, offset, byteLength2, noAssert) {
  value = +value;
  offset = offset | 0;
  if (!noAssert) {
    var limit = Math.pow(2, 8 * byteLength2 - 1);
    checkInt(this, value, offset, byteLength2, limit - 1, -limit);
  }
  var i = 0;
  var mul = 1;
  var sub = 0;
  this[offset] = value & 255;
  while (++i < byteLength2 && (mul *= 256)) {
    if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
      sub = 1;
    }
    this[offset + i] = (value / mul >> 0) - sub & 255;
  }
  return offset + byteLength2;
};
Buffer.prototype.writeIntBE = function writeIntBE(value, offset, byteLength2, noAssert) {
  value = +value;
  offset = offset | 0;
  if (!noAssert) {
    var limit = Math.pow(2, 8 * byteLength2 - 1);
    checkInt(this, value, offset, byteLength2, limit - 1, -limit);
  }
  var i = byteLength2 - 1;
  var mul = 1;
  var sub = 0;
  this[offset + i] = value & 255;
  while (--i >= 0 && (mul *= 256)) {
    if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
      sub = 1;
    }
    this[offset + i] = (value / mul >> 0) - sub & 255;
  }
  return offset + byteLength2;
};
Buffer.prototype.writeInt8 = function writeInt8(value, offset, noAssert) {
  value = +value;
  offset = offset | 0;
  if (!noAssert)
    checkInt(this, value, offset, 1, 127, -128);
  if (!Buffer.TYPED_ARRAY_SUPPORT)
    value = Math.floor(value);
  if (value < 0)
    value = 255 + value + 1;
  this[offset] = value & 255;
  return offset + 1;
};
Buffer.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) {
  value = +value;
  offset = offset | 0;
  if (!noAssert)
    checkInt(this, value, offset, 2, 32767, -32768);
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    this[offset] = value & 255;
    this[offset + 1] = value >>> 8;
  } else {
    objectWriteUInt16(this, value, offset, true);
  }
  return offset + 2;
};
Buffer.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) {
  value = +value;
  offset = offset | 0;
  if (!noAssert)
    checkInt(this, value, offset, 2, 32767, -32768);
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    this[offset] = value >>> 8;
    this[offset + 1] = value & 255;
  } else {
    objectWriteUInt16(this, value, offset, false);
  }
  return offset + 2;
};
Buffer.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) {
  value = +value;
  offset = offset | 0;
  if (!noAssert)
    checkInt(this, value, offset, 4, 2147483647, -2147483648);
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    this[offset] = value & 255;
    this[offset + 1] = value >>> 8;
    this[offset + 2] = value >>> 16;
    this[offset + 3] = value >>> 24;
  } else {
    objectWriteUInt32(this, value, offset, true);
  }
  return offset + 4;
};
Buffer.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) {
  value = +value;
  offset = offset | 0;
  if (!noAssert)
    checkInt(this, value, offset, 4, 2147483647, -2147483648);
  if (value < 0)
    value = 4294967295 + value + 1;
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    this[offset] = value >>> 24;
    this[offset + 1] = value >>> 16;
    this[offset + 2] = value >>> 8;
    this[offset + 3] = value & 255;
  } else {
    objectWriteUInt32(this, value, offset, false);
  }
  return offset + 4;
};
function checkIEEE754(buf, value, offset, ext, max, min) {
  if (offset + ext > buf.length)
    throw new RangeError("Index out of range");
  if (offset < 0)
    throw new RangeError("Index out of range");
}
function writeFloat(buf, value, offset, littleEndian, noAssert) {
  if (!noAssert) {
    checkIEEE754(buf, value, offset, 4);
  }
  write(buf, value, offset, littleEndian, 23, 4);
  return offset + 4;
}
Buffer.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) {
  return writeFloat(this, value, offset, true, noAssert);
};
Buffer.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) {
  return writeFloat(this, value, offset, false, noAssert);
};
function writeDouble(buf, value, offset, littleEndian, noAssert) {
  if (!noAssert) {
    checkIEEE754(buf, value, offset, 8);
  }
  write(buf, value, offset, littleEndian, 52, 8);
  return offset + 8;
}
Buffer.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) {
  return writeDouble(this, value, offset, true, noAssert);
};
Buffer.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) {
  return writeDouble(this, value, offset, false, noAssert);
};
Buffer.prototype.copy = function copy(target, targetStart, start, end) {
  if (!start)
    start = 0;
  if (!end && end !== 0)
    end = this.length;
  if (targetStart >= target.length)
    targetStart = target.length;
  if (!targetStart)
    targetStart = 0;
  if (end > 0 && end < start)
    end = start;
  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 || !Buffer.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;
};
Buffer.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" && !Buffer.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 Buffer(val, encoding).toString());
    var len = bytes.length;
    for (i = 0; i < end - start; ++i) {
      this[i + start] = bytes[i % len];
    }
  }
  return this;
};
var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g;
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(n) {
  if (n < 16)
    return "0" + n.toString(16);
  return n.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, offset, length) {
  for (var i = 0; i < length; ++i) {
    if (i + offset >= dst.length || i >= src.length)
      break;
    dst[i + offset] = src[i];
  }
  return i;
}
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 __filename = "/tmp/cdn/_kyFj18PjhGK81wOlm4r7/node_modules/esbuild/lib";
var __dirname = "/tmp/cdn/_kyFj18PjhGK81wOlm4r7/node_modules/esbuild/lib";
function defaultSetTimout() {
  throw new Error("setTimeout has not been defined");
}
function defaultClearTimeout() {
  throw new Error("clearTimeout has not been defined");
}
var cachedSetTimeout = defaultSetTimout;
var cachedClearTimeout = defaultClearTimeout;
var globalContext;
if (typeof window !== "undefined") {
  globalContext = window;
} else if (typeof self !== "undefined") {
  globalContext = self;
} else {
  globalContext = {};
}
if (typeof globalContext.setTimeout === "function") {
  cachedSetTimeout = setTimeout;
}
if (typeof globalContext.clearTimeout === "function") {
  cachedClearTimeout = clearTimeout;
}
function runTimeout(fun) {
  if (cachedSetTimeout === setTimeout) {
    return setTimeout(fun, 0);
  }
  if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
    cachedSetTimeout = setTimeout;
    return setTimeout(fun, 0);
  }
  try {
    return cachedSetTimeout(fun, 0);
  } catch (e) {
    try {
      return cachedSetTimeout.call(null, fun, 0);
    } catch (e2) {
      return cachedSetTimeout.call(this, fun, 0);
    }
  }
}
function runClearTimeout(marker) {
  if (cachedClearTimeout === clearTimeout) {
    return clearTimeout(marker);
  }
  if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
    cachedClearTimeout = clearTimeout;
    return clearTimeout(marker);
  }
  try {
    return cachedClearTimeout(marker);
  } catch (e) {
    try {
      return cachedClearTimeout.call(null, marker);
    } catch (e2) {
      return cachedClearTimeout.call(this, marker);
    }
  }
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
  if (!draining || !currentQueue) {
    return;
  }
  draining = false;
  if (currentQueue.length) {
    queue = currentQueue.concat(queue);
  } else {
    queueIndex = -1;
  }
  if (queue.length) {
    drainQueue();
  }
}
function drainQueue() {
  if (draining) {
    return;
  }
  var timeout = runTimeout(cleanUpNextTick);
  draining = true;
  var len = queue.length;
  while (len) {
    currentQueue = queue;
    queue = [];
    while (++queueIndex < len) {
      if (currentQueue) {
        currentQueue[queueIndex].run();
      }
    }
    queueIndex = -1;
    len = queue.length;
  }
  currentQueue = null;
  draining = false;
  runClearTimeout(timeout);
}
function nextTick(fun) {
  var args = new Array(arguments.length - 1);
  if (arguments.length > 1) {
    for (var i = 1; i < arguments.length; i++) {
      args[i - 1] = arguments[i];
    }
  }
  queue.push(new Item(fun, args));
  if (queue.length === 1 && !draining) {
    runTimeout(drainQueue);
  }
}
function Item(fun, array) {
  this.fun = fun;
  this.array = array;
}
Item.prototype.run = function() {
  this.fun.apply(null, this.array);
};
var title = "browser";
var platform = "browser";
var browser = true;
var argv = [];
var version = "";
var versions = {};
var release = {};
var config = {};
function noop() {
}
var on = noop;
var addListener = noop;
var once = noop;
var off = noop;
var removeListener = noop;
var removeAllListeners = noop;
var emit = noop;
function binding(name) {
  throw new Error("process.binding is not supported");
}
function cwd() {
  return "/";
}
function chdir(dir) {
  throw new Error("process.chdir is not supported");
}
function umask() {
  return 0;
}
var performance = globalContext.performance || {};
var performanceNow = performance.now || performance.mozNow || performance.msNow || performance.oNow || performance.webkitNow || function() {
  return new Date().getTime();
};
function hrtime(previousTimestamp) {
  var clocktime = performanceNow.call(performance) * 1e-3;
  var seconds = Math.floor(clocktime);
  var nanoseconds = Math.floor(clocktime % 1 * 1e9);
  if (previousTimestamp) {
    seconds = seconds - previousTimestamp[0];
    nanoseconds = nanoseconds - previousTimestamp[1];
    if (nanoseconds < 0) {
      seconds--;
      nanoseconds += 1e9;
    }
  }
  return [seconds, nanoseconds];
}
var startTime = new Date();
function uptime() {
  var currentTime = new Date();
  var dif = currentTime - startTime;
  return dif / 1e3;
}
var process = {
  nextTick,
  title,
  browser,
  env: {NODE_ENV: "production"},
  argv,
  version,
  versions,
  on,
  addListener,
  once,
  off,
  removeListener,
  removeAllListeners,
  emit,
  binding,
  cwd,
  chdir,
  umask,
  hrtime,
  platform,
  release,
  config,
  uptime
};
function getDefaultExportFromCjs(x) {
  return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
}
function createCommonjsModule(fn, basedir, module) {
  return module = {
    path: basedir,
    exports: {},
    require: function(path2, base) {
      return commonjsRequire(path2, base === void 0 || base === null ? module.path : base);
    }
  }, fn(module, module.exports), module.exports;
}
function commonjsRequire() {
  throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs");
}
function normalizeArray(parts, allowAboveRoot) {
  var up = 0;
  for (var i = parts.length - 1; i >= 0; i--) {
    var last = parts[i];
    if (last === ".") {
      parts.splice(i, 1);
    } else if (last === "..") {
      parts.splice(i, 1);
      up++;
    } else if (up) {
      parts.splice(i, 1);
      up--;
    }
  }
  if (allowAboveRoot) {
    for (; up--; up) {
      parts.unshift("..");
    }
  }
  return parts;
}
var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
var splitPath = function(filename) {
  return splitPathRe.exec(filename).slice(1);
};
function resolve() {
  var resolvedPath = "", resolvedAbsolute = false;
  for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
    var path2 = i >= 0 ? arguments[i] : "/";
    if (typeof path2 !== "string") {
      throw new TypeError("Arguments to path.resolve must be strings");
    } else if (!path2) {
      continue;
    }
    resolvedPath = path2 + "/" + resolvedPath;
    resolvedAbsolute = path2.charAt(0) === "/";
  }
  resolvedPath = normalizeArray(filter(resolvedPath.split("/"), function(p) {
    return !!p;
  }), !resolvedAbsolute).join("/");
  return (resolvedAbsolute ? "/" : "") + resolvedPath || ".";
}
function normalize(path2) {
  var isPathAbsolute = isAbsolute(path2), trailingSlash = substr(path2, -1) === "/";
  path2 = normalizeArray(filter(path2.split("/"), function(p) {
    return !!p;
  }), !isPathAbsolute).join("/");
  if (!path2 && !isPathAbsolute) {
    path2 = ".";
  }
  if (path2 && trailingSlash) {
    path2 += "/";
  }
  return (isPathAbsolute ? "/" : "") + path2;
}
function isAbsolute(path2) {
  return path2.charAt(0) === "/";
}
function join() {
  var paths = Array.prototype.slice.call(arguments, 0);
  return normalize(filter(paths, function(p, index) {
    if (typeof p !== "string") {
      throw new TypeError("Arguments to path.join must be strings");
    }
    return p;
  }).join("/"));
}
function relative(from2, to) {
  from2 = resolve(from2).substr(1);
  to = resolve(to).substr(1);
  function trim(arr) {
    var start = 0;
    for (; start < arr.length; start++) {
      if (arr[start] !== "")
        break;
    }
    var end = arr.length - 1;
    for (; end >= 0; end--) {
      if (arr[end] !== "")
        break;
    }
    if (start > end)
      return [];
    return arr.slice(start, end - start + 1);
  }
  var fromParts = trim(from2.split("/"));
  var toParts = trim(to.split("/"));
  var length = Math.min(fromParts.length, toParts.length);
  var samePartsLength = length;
  for (var i = 0; i < length; i++) {
    if (fromParts[i] !== toParts[i]) {
      samePartsLength = i;
      break;
    }
  }
  var outputParts = [];
  for (var i = samePartsLength; i < fromParts.length; i++) {
    outputParts.push("..");
  }
  outputParts = outputParts.concat(toParts.slice(samePartsLength));
  return outputParts.join("/");
}
var sep = "/";
var delimiter = ":";
function dirname(path2) {
  var result = splitPath(path2), root = result[0], dir = result[1];
  if (!root && !dir) {
    return ".";
  }
  if (dir) {
    dir = dir.substr(0, dir.length - 1);
  }
  return root + dir;
}
function basename(path2, ext) {
  var f = splitPath(path2)[2];
  if (ext && f.substr(-1 * ext.length) === ext) {
    f = f.substr(0, f.length - ext.length);
  }
  return f;
}
function extname(path2) {
  return splitPath(path2)[3];
}
var path = {
  extname,
  basename,
  dirname,
  sep,
  delimiter,
  relative,
  join,
  isAbsolute,
  normalize,
  resolve
};
function filter(xs, f) {
  if (xs.filter)
    return xs.filter(f);
  var res = [];
  for (var i = 0; i < xs.length; i++) {
    if (f(xs[i], i, xs))
      res.push(xs[i]);
  }
  return res;
}
var substr = "ab".substr(-1) === "b" ? function(str, start, len) {
  return str.substr(start, len);
} : function(str, start, len) {
  if (start < 0)
    start = str.length + start;
  return str.substr(start, len);
};
var path$1 = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  resolve,
  normalize,
  isAbsolute,
  join,
  relative,
  sep,
  delimiter,
  dirname,
  basename,
  extname,
  default: path
});
var main = createCommonjsModule(function(module) {
  var __defProp = Object.defineProperty;
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  var __getOwnPropNames = Object.getOwnPropertyNames;
  var __hasOwnProp = Object.prototype.hasOwnProperty;
  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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", {value: true}), mod);
  var node_exports = {};
  __export(node_exports, {
    analyzeMetafile: () => analyzeMetafile2,
    analyzeMetafileSync: () => analyzeMetafileSync2,
    build: () => build2,
    buildSync: () => buildSync2,
    context: () => context2,
    default: () => node_default,
    formatMessages: () => formatMessages2,
    formatMessagesSync: () => formatMessagesSync2,
    initialize: () => initialize2,
    stop: () => stop2,
    transform: () => transform2,
    transformSync: () => transformSync2,
    version: () => version2
  });
  module.exports = __toCommonJS(node_exports);
  function encodePacket(packet) {
    let visit = (value) => {
      if (value === null) {
        bb.write8(0);
      } else if (typeof value === "boolean") {
        bb.write8(1);
        bb.write8(+value);
      } else if (typeof value === "number") {
        bb.write8(2);
        bb.write32(value | 0);
      } else if (typeof value === "string") {
        bb.write8(3);
        bb.write(encodeUTF8(value));
      } else if (value instanceof Uint8Array) {
        bb.write8(4);
        bb.write(value);
      } else if (value instanceof Array) {
        bb.write8(5);
        bb.write32(value.length);
        for (let item of value) {
          visit(item);
        }
      } else {
        let keys = Object.keys(value);
        bb.write8(6);
        bb.write32(keys.length);
        for (let key of keys) {
          bb.write(encodeUTF8(key));
          visit(value[key]);
        }
      }
    };
    let bb = new ByteBuffer();
    bb.write32(0);
    bb.write32(packet.id << 1 | +!packet.isRequest);
    visit(packet.value);
    writeUInt32LE2(bb.buf, bb.len - 4, 0);
    return bb.buf.subarray(0, bb.len);
  }
  function decodePacket(bytes) {
    let visit = () => {
      switch (bb.read8()) {
        case 0:
          return null;
        case 1:
          return !!bb.read8();
        case 2:
          return bb.read32();
        case 3:
          return decodeUTF8(bb.read());
        case 4:
          return bb.read();
        case 5: {
          let count = bb.read32();
          let value2 = [];
          for (let i = 0; i < count; i++) {
            value2.push(visit());
          }
          return value2;
        }
        case 6: {
          let count = bb.read32();
          let value2 = {};
          for (let i = 0; i < count; i++) {
            value2[decodeUTF8(bb.read())] = visit();
          }
          return value2;
        }
        default:
          throw new Error("Invalid packet");
      }
    };
    let bb = new ByteBuffer(bytes);
    let id = bb.read32();
    let isRequest = (id & 1) === 0;
    id >>>= 1;
    let value = visit();
    if (bb.ptr !== bytes.length) {
      throw new Error("Invalid packet");
    }
    return {id, isRequest, value};
  }
  var ByteBuffer = class {
    constructor(buf = new Uint8Array(1024)) {
      this.buf = buf;
      this.len = 0;
      this.ptr = 0;
    }
    _write(delta) {
      if (this.len + delta > this.buf.length) {
        let clone = new Uint8Array((this.len + delta) * 2);
        clone.set(this.buf);
        this.buf = clone;
      }
      this.len += delta;
      return this.len - delta;
    }
    write8(value) {
      let offset = this._write(1);
      this.buf[offset] = value;
    }
    write32(value) {
      let offset = this._write(4);
      writeUInt32LE2(this.buf, value, offset);
    }
    write(bytes) {
      let offset = this._write(4 + bytes.length);
      writeUInt32LE2(this.buf, bytes.length, offset);
      this.buf.set(bytes, offset + 4);
    }
    _read(delta) {
      if (this.ptr + delta > this.buf.length) {
        throw new Error("Invalid packet");
      }
      this.ptr += delta;
      return this.ptr - delta;
    }
    read8() {
      return this.buf[this._read(1)];
    }
    read32() {
      return readUInt32LE2(this.buf, this._read(4));
    }
    read() {
      let length = this.read32();
      let bytes = new Uint8Array(length);
      let ptr = this._read(bytes.length);
      bytes.set(this.buf.subarray(ptr, ptr + length));
      return bytes;
    }
  };
  var encodeUTF8;
  var decodeUTF8;
  var encodeInvariant;
  if (typeof TextEncoder !== "undefined" && typeof TextDecoder !== "undefined") {
    let encoder = new TextEncoder();
    let decoder = new TextDecoder();
    encodeUTF8 = (text) => encoder.encode(text);
    decodeUTF8 = (bytes) => decoder.decode(bytes);
    encodeInvariant = 'new TextEncoder().encode("")';
  } else if (typeof Buffer !== "undefined") {
    encodeUTF8 = (text) => Buffer.from(text);
    decodeUTF8 = (bytes) => {
      let {buffer, byteOffset, byteLength: byteLength2} = bytes;
      return Buffer.from(buffer, byteOffset, byteLength2).toString();
    };
    encodeInvariant = 'Buffer.from("")';
  } else {
    throw new Error("No UTF-8 codec found");
  }
  if (!(encodeUTF8("") instanceof Uint8Array))
    throw new Error(`Invariant violation: "${encodeInvariant} instanceof Uint8Array" is incorrectly false

This indicates that your JavaScript environment is broken. You cannot use
esbuild in this environment because esbuild relies on this invariant. This
is not a problem with esbuild. You need to fix your environment instead.
`);
  function readUInt32LE2(buffer, offset) {
    return (buffer[offset++] | buffer[offset++] << 8 | buffer[offset++] << 16 | buffer[offset++] << 24) >>> 0;
  }
  function writeUInt32LE2(buffer, value, offset) {
    buffer[offset++] = value;
    buffer[offset++] = value >> 8;
    buffer[offset++] = value >> 16;
    buffer[offset++] = value >> 24;
  }
  var fromCharCode = String.fromCharCode;
  function throwSyntaxError(bytes, index, message) {
    const c = bytes[index];
    let line = 1;
    let column = 0;
    for (let i = 0; i < index; i++) {
      if (bytes[i] === 10) {
        line++;
        column = 0;
      } else {
        column++;
      }
    }
    throw new SyntaxError(message ? message : index === bytes.length ? "Unexpected end of input while parsing JSON" : c >= 32 && c <= 126 ? `Unexpected character ${fromCharCode(c)} in JSON at position ${index} (line ${line}, column ${column})` : `Unexpected byte 0x${c.toString(16)} in JSON at position ${index} (line ${line}, column ${column})`);
  }
  function JSON_parse(bytes) {
    if (!(bytes instanceof Uint8Array)) {
      throw new Error(`JSON input must be a Uint8Array`);
    }
    const propertyStack = [];
    const objectStack = [];
    const stateStack = [];
    const length = bytes.length;
    let property = null;
    let state = 0;
    let object;
    let i = 0;
    while (i < length) {
      let c = bytes[i++];
      if (c <= 32) {
        continue;
      }
      let value;
      if (state === 2 && property === null && c !== 34 && c !== 125) {
        throwSyntaxError(bytes, --i);
      }
      switch (c) {
        case 116: {
          if (bytes[i++] !== 114 || bytes[i++] !== 117 || bytes[i++] !== 101) {
            throwSyntaxError(bytes, --i);
          }
          value = true;
          break;
        }
        case 102: {
          if (bytes[i++] !== 97 || bytes[i++] !== 108 || bytes[i++] !== 115 || bytes[i++] !== 101) {
            throwSyntaxError(bytes, --i);
          }
          value = false;
          break;
        }
        case 110: {
          if (bytes[i++] !== 117 || bytes[i++] !== 108 || bytes[i++] !== 108) {
            throwSyntaxError(bytes, --i);
          }
          value = null;
          break;
        }
        case 45:
        case 46:
        case 48:
        case 49:
        case 50:
        case 51:
        case 52:
        case 53:
        case 54:
        case 55:
        case 56:
        case 57: {
          let index = i;
          value = fromCharCode(c);
          c = bytes[i];
          while (true) {
            switch (c) {
              case 43:
              case 45:
              case 46:
              case 48:
              case 49:
              case 50:
              case 51:
              case 52:
              case 53:
              case 54:
              case 55:
              case 56:
              case 57:
              case 101:
              case 69: {
                value += fromCharCode(c);
                c = bytes[++i];
                continue;
              }
            }
            break;
          }
          value = +value;
          if (isNaN(value)) {
            throwSyntaxError(bytes, --index, "Invalid number");
          }
          break;
        }
        case 34: {
          value = "";
          while (true) {
            if (i >= length) {
              throwSyntaxError(bytes, length);
            }
            c = bytes[i++];
            if (c === 34) {
              break;
            } else if (c === 92) {
              switch (bytes[i++]) {
                case 34:
                  value += '"';
                  break;
                case 47:
                  value += "/";
                  break;
                case 92:
                  value += "\\";
                  break;
                case 98:
                  value += "\b";
                  break;
                case 102:
                  value += "\f";
                  break;
                case 110:
                  value += "\n";
                  break;
                case 114:
                  value += "\r";
                  break;
                case 116:
                  value += "	";
                  break;
                case 117: {
                  let code = 0;
                  for (let j = 0; j < 4; j++) {
                    c = bytes[i++];
                    code <<= 4;
                    if (c >= 48 && c <= 57)
                      code |= c - 48;
                    else if (c >= 97 && c <= 102)
                      code |= c + (10 - 97);
                    else if (c >= 65 && c <= 70)
                      code |= c + (10 - 65);
                    else
                      throwSyntaxError(bytes, --i);
                  }
                  value += fromCharCode(code);
                  break;
                }
                default:
                  throwSyntaxError(bytes, --i);
                  break;
              }
            } else if (c <= 127) {
              value += fromCharCode(c);
            } else if ((c & 224) === 192) {
              value += fromCharCode((c & 31) << 6 | bytes[i++] & 63);
            } else if ((c & 240) === 224) {
              value += fromCharCode((c & 15) << 12 | (bytes[i++] & 63) << 6 | bytes[i++] & 63);
            } else if ((c & 248) == 240) {
              let codePoint = (c & 7) << 18 | (bytes[i++] & 63) << 12 | (bytes[i++] & 63) << 6 | bytes[i++] & 63;
              if (codePoint > 65535) {
                codePoint -= 65536;
                value += fromCharCode(codePoint >> 10 & 1023 | 55296);
                codePoint = 56320 | codePoint & 1023;
              }
              value += fromCharCode(codePoint);
            }
          }
          value[0];
          break;
        }
        case 91: {
          value = [];
          propertyStack.push(property);
          objectStack.push(object);
          stateStack.push(state);
          property = null;
          object = value;
          state = 1;
          continue;
        }
        case 123: {
          value = {};
          propertyStack.push(property);
          objectStack.push(object);
          stateStack.push(state);
          property = null;
          object = value;
          state = 2;
          continue;
        }
        case 93: {
          if (state !== 1) {
            throwSyntaxError(bytes, --i);
          }
          value = object;
          property = propertyStack.pop();
          object = objectStack.pop();
          state = stateStack.pop();
          break;
        }
        case 125: {
          if (state !== 2) {
            throwSyntaxError(bytes, --i);
          }
          value = object;
          property = propertyStack.pop();
          object = objectStack.pop();
          state = stateStack.pop();
          break;
        }
        default: {
          throwSyntaxError(bytes, --i);
        }
      }
      c = bytes[i];
      while (c <= 32) {
        c = bytes[++i];
      }
      switch (state) {
        case 0: {
          if (i === length) {
            return value;
          }
          break;
        }
        case 1: {
          object.push(value);
          if (c === 44) {
            i++;
            continue;
          }
          if (c === 93) {
            continue;
          }
          break;
        }
        case 2: {
          if (property === null) {
            property = value;
            if (c === 58) {
              i++;
              continue;
            }
          } else {
            object[property] = value;
            property = null;
            if (c === 44) {
              i++;
              continue;
            }
            if (c === 125) {
              continue;
            }
          }
          break;
        }
      }
      break;
    }
    throwSyntaxError(bytes, i);
  }
  var quote = JSON.stringify;
  var buildLogLevelDefault = "warning";
  var transformLogLevelDefault = "silent";
  function validateAndJoinStringArray(values, what) {
    const toJoin = [];
    for (const value of values) {
      validateStringValue(value, what);
      if (value.indexOf(",") >= 0)
        throw new Error(`Invalid ${what}: ${value}`);
      toJoin.push(value);
    }
    return toJoin.join(",");
  }
  var canBeAnything = () => null;
  var mustBeBoolean = (value) => typeof value === "boolean" ? null : "a boolean";
  var mustBeString = (value) => typeof value === "string" ? null : "a string";
  var mustBeRegExp = (value) => value instanceof RegExp ? null : "a RegExp object";
  var mustBeInteger = (value) => typeof value === "number" && value === (value | 0) ? null : "an integer";
  var mustBeValidPortNumber = (value) => typeof value === "number" && value === (value | 0) && value >= 0 && value <= 65535 ? null : "a valid port number";
  var mustBeFunction = (value) => typeof value === "function" ? null : "a function";
  var mustBeArray = (value) => Array.isArray(value) ? null : "an array";
  var mustBeArrayOfStrings = (value) => Array.isArray(value) && value.every((x) => typeof x === "string") ? null : "an array of strings";
  var mustBeObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? null : "an object";
  var mustBeEntryPoints = (value) => typeof value === "object" && value !== null ? null : "an array or an object";
  var mustBeWebAssemblyModule = (value) => value instanceof WebAssembly.Module ? null : "a WebAssembly.Module";
  var mustBeObjectOrNull = (value) => typeof value === "object" && !Array.isArray(value) ? null : "an object or null";
  var mustBeStringOrBoolean = (value) => typeof value === "string" || typeof value === "boolean" ? null : "a string or a boolean";
  var mustBeStringOrObject = (value) => typeof value === "string" || typeof value === "object" && value !== null && !Array.isArray(value) ? null : "a string or an object";
  var mustBeStringOrArrayOfStrings = (value) => typeof value === "string" || Array.isArray(value) && value.every((x) => typeof x === "string") ? null : "a string or an array of strings";
  var mustBeStringOrUint8Array = (value) => typeof value === "string" || value instanceof Uint8Array ? null : "a string or a Uint8Array";
  var mustBeStringOrURL = (value) => typeof value === "string" || value instanceof URL ? null : "a string or a URL";
  function getFlag(object, keys, key, mustBeFn) {
    let value = object[key];
    keys[key + ""] = true;
    if (value === void 0)
      return void 0;
    let mustBe = mustBeFn(value);
    if (mustBe !== null)
      throw new Error(`${quote(key)} must be ${mustBe}`);
    return value;
  }
  function checkForInvalidFlags(object, keys, where) {
    for (let key in object) {
      if (!(key in keys)) {
        throw new Error(`Invalid option ${where}: ${quote(key)}`);
      }
    }
  }
  function validateInitializeOptions(options) {
    let keys = /* @__PURE__ */ Object.create(null);
    let wasmURL = getFlag(options, keys, "wasmURL", mustBeStringOrURL);
    let wasmModule = getFlag(options, keys, "wasmModule", mustBeWebAssemblyModule);
    let worker = getFlag(options, keys, "worker", mustBeBoolean);
    checkForInvalidFlags(options, keys, "in initialize() call");
    return {
      wasmURL,
      wasmModule,
      worker
    };
  }
  function validateMangleCache(mangleCache) {
    let validated;
    if (mangleCache !== void 0) {
      validated = /* @__PURE__ */ Object.create(null);
      for (let key in mangleCache) {
        let value = mangleCache[key];
        if (typeof value === "string" || value === false) {
          validated[key] = value;
        } else {
          throw new Error(`Expected ${quote(key)} in mangle cache to map to either a string or false`);
        }
      }
    }
    return validated;
  }
  function pushLogFlags(flags, options, keys, isTTY2, logLevelDefault) {
    let color = getFlag(options, keys, "color", mustBeBoolean);
    let logLevel = getFlag(options, keys, "logLevel", mustBeString);
    let logLimit = getFlag(options, keys, "logLimit", mustBeInteger);
    if (color !== void 0)
      flags.push(`--color=${color}`);
    else if (isTTY2)
      flags.push(`--color=true`);
    flags.push(`--log-level=${logLevel || logLevelDefault}`);
    flags.push(`--log-limit=${logLimit || 0}`);
  }
  function validateStringValue(value, what, key) {
    if (typeof value !== "string") {
      throw new Error(`Expected value for ${what}${key !== void 0 ? " " + quote(key) : ""} to be a string, got ${typeof value} instead`);
    }
    return value;
  }
  function pushCommonFlags(flags, options, keys) {
    let legalComments = getFlag(options, keys, "legalComments", mustBeString);
    let sourceRoot = getFlag(options, keys, "sourceRoot", mustBeString);
    let sourcesContent = getFlag(options, keys, "sourcesContent", mustBeBoolean);
    let target = getFlag(options, keys, "target", mustBeStringOrArrayOfStrings);
    let format = getFlag(options, keys, "format", mustBeString);
    let globalName = getFlag(options, keys, "globalName", mustBeString);
    let mangleProps = getFlag(options, keys, "mangleProps", mustBeRegExp);
    let reserveProps = getFlag(options, keys, "reserveProps", mustBeRegExp);
    let mangleQuoted = getFlag(options, keys, "mangleQuoted", mustBeBoolean);
    let minify = getFlag(options, keys, "minify", mustBeBoolean);
    let minifySyntax = getFlag(options, keys, "minifySyntax", mustBeBoolean);
    let minifyWhitespace = getFlag(options, keys, "minifyWhitespace", mustBeBoolean);
    let minifyIdentifiers = getFlag(options, keys, "minifyIdentifiers", mustBeBoolean);
    let lineLimit = getFlag(options, keys, "lineLimit", mustBeInteger);
    let drop = getFlag(options, keys, "drop", mustBeArrayOfStrings);
    let dropLabels = getFlag(options, keys, "dropLabels", mustBeArrayOfStrings);
    let charset = getFlag(options, keys, "charset", mustBeString);
    let treeShaking = getFlag(options, keys, "treeShaking", mustBeBoolean);
    let ignoreAnnotations = getFlag(options, keys, "ignoreAnnotations", mustBeBoolean);
    let jsx = getFlag(options, keys, "jsx", mustBeString);
    let jsxFactory = getFlag(options, keys, "jsxFactory", mustBeString);
    let jsxFragment = getFlag(options, keys, "jsxFragment", mustBeString);
    let jsxImportSource = getFlag(options, keys, "jsxImportSource", mustBeString);
    let jsxDev = getFlag(options, keys, "jsxDev", mustBeBoolean);
    let jsxSideEffects = getFlag(options, keys, "jsxSideEffects", mustBeBoolean);
    let define = getFlag(options, keys, "define", mustBeObject);
    let logOverride = getFlag(options, keys, "logOverride", mustBeObject);
    let supported = getFlag(options, keys, "supported", mustBeObject);
    let pure = getFlag(options, keys, "pure", mustBeArrayOfStrings);
    let keepNames = getFlag(options, keys, "keepNames", mustBeBoolean);
    let platform2 = getFlag(options, keys, "platform", mustBeString);
    let tsconfigRaw = getFlag(options, keys, "tsconfigRaw", mustBeStringOrObject);
    let absPaths = getFlag(options, keys, "absPaths", mustBeArrayOfStrings);
    if (legalComments)
      flags.push(`--legal-comments=${legalComments}`);
    if (sourceRoot !== void 0)
      flags.push(`--source-root=${sourceRoot}`);
    if (sourcesContent !== void 0)
      flags.push(`--sources-content=${sourcesContent}`);
    if (target)
      flags.push(`--target=${validateAndJoinStringArray(Array.isArray(target) ? target : [target], "target")}`);
    if (format)
      flags.push(`--format=${format}`);
    if (globalName)
      flags.push(`--global-name=${globalName}`);
    if (platform2)
      flags.push(`--platform=${platform2}`);
    if (tsconfigRaw)
      flags.push(`--tsconfig-raw=${typeof tsconfigRaw === "string" ? tsconfigRaw : JSON.stringify(tsconfigRaw)}`);
    if (minify)
      flags.push("--minify");
    if (minifySyntax)
      flags.push("--minify-syntax");
    if (minifyWhitespace)
      flags.push("--minify-whitespace");
    if (minifyIdentifiers)
      flags.push("--minify-identifiers");
    if (lineLimit)
      flags.push(`--line-limit=${lineLimit}`);
    if (charset)
      flags.push(`--charset=${charset}`);
    if (treeShaking !== void 0)
      flags.push(`--tree-shaking=${treeShaking}`);
    if (ignoreAnnotations)
      flags.push(`--ignore-annotations`);
    if (drop)
      for (let what of drop)
        flags.push(`--drop:${validateStringValue(what, "drop")}`);
    if (dropLabels)
      flags.push(`--drop-labels=${validateAndJoinStringArray(dropLabels, "drop label")}`);
    if (absPaths)
      flags.push(`--abs-paths=${validateAndJoinStringArray(absPaths, "abs paths")}`);
    if (mangleProps)
      flags.push(`--mangle-props=${jsRegExpToGoRegExp(mangleProps)}`);
    if (reserveProps)
      flags.push(`--reserve-props=${jsRegExpToGoRegExp(reserveProps)}`);
    if (mangleQuoted !== void 0)
      flags.push(`--mangle-quoted=${mangleQuoted}`);
    if (jsx)
      flags.push(`--jsx=${jsx}`);
    if (jsxFactory)
      flags.push(`--jsx-factory=${jsxFactory}`);
    if (jsxFragment)
      flags.push(`--jsx-fragment=${jsxFragment}`);
    if (jsxImportSource)
      flags.push(`--jsx-import-source=${jsxImportSource}`);
    if (jsxDev)
      flags.push(`--jsx-dev`);
    if (jsxSideEffects)
      flags.push(`--jsx-side-effects`);
    if (define) {
      for (let key in define) {
        if (key.indexOf("=") >= 0)
          throw new Error(`Invalid define: ${key}`);
        flags.push(`--define:${key}=${validateStringValue(define[key], "define", key)}`);
      }
    }
    if (logOverride) {
      for (let key in logOverride) {
        if (key.indexOf("=") >= 0)
          throw new Error(`Invalid log override: ${key}`);
        flags.push(`--log-override:${key}=${validateStringValue(logOverride[key], "log override", key)}`);
      }
    }
    if (supported) {
      for (let key in supported) {
        if (key.indexOf("=") >= 0)
          throw new Error(`Invalid supported: ${key}`);
        const value = supported[key];
        if (typeof value !== "boolean")
          throw new Error(`Expected value for supported ${quote(key)} to be a boolean, got ${typeof value} instead`);
        flags.push(`--supported:${key}=${value}`);
      }
    }
    if (pure)
      for (let fn of pure)
        flags.push(`--pure:${validateStringValue(fn, "pure")}`);
    if (keepNames)
      flags.push(`--keep-names`);
  }
  function flagsForBuildOptions(callName, options, isTTY2, logLevelDefault, writeDefault) {
    var _a2;
    let flags = [];
    let entries = [];
    let keys = /* @__PURE__ */ Object.create(null);
    let stdinContents = null;
    let stdinResolveDir = null;
    pushLogFlags(flags, options, keys, isTTY2, logLevelDefault);
    pushCommonFlags(flags, options, keys);
    let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
    let bundle = getFlag(options, keys, "bundle", mustBeBoolean);
    let splitting = getFlag(options, keys, "splitting", mustBeBoolean);
    let preserveSymlinks = getFlag(options, keys, "preserveSymlinks", mustBeBoolean);
    let metafile = getFlag(options, keys, "metafile", mustBeBoolean);
    let outfile = getFlag(options, keys, "outfile", mustBeString);
    let outdir = getFlag(options, keys, "outdir", mustBeString);
    let outbase = getFlag(options, keys, "outbase", mustBeString);
    let tsconfig = getFlag(options, keys, "tsconfig", mustBeString);
    let resolveExtensions = getFlag(options, keys, "resolveExtensions", mustBeArrayOfStrings);
    let nodePathsInput = getFlag(options, keys, "nodePaths", mustBeArrayOfStrings);
    let mainFields = getFlag(options, keys, "mainFields", mustBeArrayOfStrings);
    let conditions = getFlag(options, keys, "conditions", mustBeArrayOfStrings);
    let external = getFlag(options, keys, "external", mustBeArrayOfStrings);
    let packages = getFlag(options, keys, "packages", mustBeString);
    let alias = getFlag(options, keys, "alias", mustBeObject);
    let loader = getFlag(options, keys, "loader", mustBeObject);
    let outExtension = getFlag(options, keys, "outExtension", mustBeObject);
    let publicPath = getFlag(options, keys, "publicPath", mustBeString);
    let entryNames = getFlag(options, keys, "entryNames", mustBeString);
    let chunkNames = getFlag(options, keys, "chunkNames", mustBeString);
    let assetNames = getFlag(options, keys, "assetNames", mustBeString);
    let inject = getFlag(options, keys, "inject", mustBeArrayOfStrings);
    let banner = getFlag(options, keys, "banner", mustBeObject);
    let footer = getFlag(options, keys, "footer", mustBeObject);
    let entryPoints = getFlag(options, keys, "entryPoints", mustBeEntryPoints);
    let absWorkingDir = getFlag(options, keys, "absWorkingDir", mustBeString);
    let stdin = getFlag(options, keys, "stdin", mustBeObject);
    let write3 = (_a2 = getFlag(options, keys, "write", mustBeBoolean)) != null ? _a2 : writeDefault;
    let allowOverwrite = getFlag(options, keys, "allowOverwrite", mustBeBoolean);
    let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject);
    keys.plugins = true;
    checkForInvalidFlags(options, keys, `in ${callName}() call`);
    if (sourcemap)
      flags.push(`--sourcemap${sourcemap === true ? "" : `=${sourcemap}`}`);
    if (bundle)
      flags.push("--bundle");
    if (allowOverwrite)
      flags.push("--allow-overwrite");
    if (splitting)
      flags.push("--splitting");
    if (preserveSymlinks)
      flags.push("--preserve-symlinks");
    if (metafile)
      flags.push(`--metafile`);
    if (outfile)
      flags.push(`--outfile=${outfile}`);
    if (outdir)
      flags.push(`--outdir=${outdir}`);
    if (outbase)
      flags.push(`--outbase=${outbase}`);
    if (tsconfig)
      flags.push(`--tsconfig=${tsconfig}`);
    if (packages)
      flags.push(`--packages=${packages}`);
    if (resolveExtensions)
      flags.push(`--resolve-extensions=${validateAndJoinStringArray(resolveExtensions, "resolve extension")}`);
    if (publicPath)
      flags.push(`--public-path=${publicPath}`);
    if (entryNames)
      flags.push(`--entry-names=${entryNames}`);
    if (chunkNames)
      flags.push(`--chunk-names=${chunkNames}`);
    if (assetNames)
      flags.push(`--asset-names=${assetNames}`);
    if (mainFields)
      flags.push(`--main-fields=${validateAndJoinStringArray(mainFields, "main field")}`);
    if (conditions)
      flags.push(`--conditions=${validateAndJoinStringArray(conditions, "condition")}`);
    if (external)
      for (let name of external)
        flags.push(`--external:${validateStringValue(name, "external")}`);
    if (alias) {
      for (let old in alias) {
        if (old.indexOf("=") >= 0)
          throw new Error(`Invalid package name in alias: ${old}`);
        flags.push(`--alias:${old}=${validateStringValue(alias[old], "alias", old)}`);
      }
    }
    if (banner) {
      for (let type in banner) {
        if (type.indexOf("=") >= 0)
          throw new Error(`Invalid banner file type: ${type}`);
        flags.push(`--banner:${type}=${validateStringValue(banner[type], "banner", type)}`);
      }
    }
    if (footer) {
      for (let type in footer) {
        if (type.indexOf("=") >= 0)
          throw new Error(`Invalid footer file type: ${type}`);
        flags.push(`--footer:${type}=${validateStringValue(footer[type], "footer", type)}`);
      }
    }
    if (inject)
      for (let path3 of inject)
        flags.push(`--inject:${validateStringValue(path3, "inject")}`);
    if (loader) {
      for (let ext in loader) {
        if (ext.indexOf("=") >= 0)
          throw new Error(`Invalid loader extension: ${ext}`);
        flags.push(`--loader:${ext}=${validateStringValue(loader[ext], "loader", ext)}`);
      }
    }
    if (outExtension) {
      for (let ext in outExtension) {
        if (ext.indexOf("=") >= 0)
          throw new Error(`Invalid out extension: ${ext}`);
        flags.push(`--out-extension:${ext}=${validateStringValue(outExtension[ext], "out extension", ext)}`);
      }
    }
    if (entryPoints) {
      if (Array.isArray(entryPoints)) {
        for (let i = 0, n = entryPoints.length; i < n; i++) {
          let entryPoint = entryPoints[i];
          if (typeof entryPoint === "object" && entryPoint !== null) {
            let entryPointKeys = /* @__PURE__ */ Object.create(null);
            let input = getFlag(entryPoint, entryPointKeys, "in", mustBeString);
            let output = getFlag(entryPoint, entryPointKeys, "out", mustBeString);
            checkForInvalidFlags(entryPoint, entryPointKeys, "in entry point at index " + i);
            if (input === void 0)
              throw new Error('Missing property "in" for entry point at index ' + i);
            if (output === void 0)
              throw new Error('Missing property "out" for entry point at index ' + i);
            entries.push([output, input]);
          } else {
            entries.push(["", validateStringValue(entryPoint, "entry point at index " + i)]);
          }
        }
      } else {
        for (let key in entryPoints) {
          entries.push([key, validateStringValue(entryPoints[key], "entry point", key)]);
        }
      }
    }
    if (stdin) {
      let stdinKeys = /* @__PURE__ */ Object.create(null);
      let contents = getFlag(stdin, stdinKeys, "contents", mustBeStringOrUint8Array);
      let resolveDir = getFlag(stdin, stdinKeys, "resolveDir", mustBeString);
      let sourcefile = getFlag(stdin, stdinKeys, "sourcefile", mustBeString);
      let loader2 = getFlag(stdin, stdinKeys, "loader", mustBeString);
      checkForInvalidFlags(stdin, stdinKeys, 'in "stdin" object');
      if (sourcefile)
        flags.push(`--sourcefile=${sourcefile}`);
      if (loader2)
        flags.push(`--loader=${loader2}`);
      if (resolveDir)
        stdinResolveDir = resolveDir;
      if (typeof contents === "string")
        stdinContents = encodeUTF8(contents);
      else if (contents instanceof Uint8Array)
        stdinContents = contents;
    }
    let nodePaths = [];
    if (nodePathsInput) {
      for (let value of nodePathsInput) {
        value += "";
        nodePaths.push(value);
      }
    }
    return {
      entries,
      flags,
      write: write3,
      stdinContents,
      stdinResolveDir,
      absWorkingDir,
      nodePaths,
      mangleCache: validateMangleCache(mangleCache)
    };
  }
  function flagsForTransformOptions(callName, options, isTTY2, logLevelDefault) {
    let flags = [];
    let keys = /* @__PURE__ */ Object.create(null);
    pushLogFlags(flags, options, keys, isTTY2, logLevelDefault);
    pushCommonFlags(flags, options, keys);
    let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
    let sourcefile = getFlag(options, keys, "sourcefile", mustBeString);
    let loader = getFlag(options, keys, "loader", mustBeString);
    let banner = getFlag(options, keys, "banner", mustBeString);
    let footer = getFlag(options, keys, "footer", mustBeString);
    let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject);
    checkForInvalidFlags(options, keys, `in ${callName}() call`);
    if (sourcemap)
      flags.push(`--sourcemap=${sourcemap === true ? "external" : sourcemap}`);
    if (sourcefile)
      flags.push(`--sourcefile=${sourcefile}`);
    if (loader)
      flags.push(`--loader=${loader}`);
    if (banner)
      flags.push(`--banner=${banner}`);
    if (footer)
      flags.push(`--footer=${footer}`);
    return {
      flags,
      mangleCache: validateMangleCache(mangleCache)
    };
  }
  function createChannel(streamIn) {
    const requestCallbacksByKey = {};
    const closeData = {didClose: false, reason: ""};
    let responseCallbacks = {};
    let nextRequestID = 0;
    let nextBuildKey = 0;
    let stdout = new Uint8Array(16 * 1024);
    let stdoutUsed = 0;
    let readFromStdout = (chunk) => {
      let limit = stdoutUsed + chunk.length;
      if (limit > stdout.length) {
        let swap2 = new Uint8Array(limit * 2);
        swap2.set(stdout);
        stdout = swap2;
      }
      stdout.set(chunk, stdoutUsed);
      stdoutUsed += chunk.length;
      let offset = 0;
      while (offset + 4 <= stdoutUsed) {
        let length = readUInt32LE2(stdout, offset);
        if (offset + 4 + length > stdoutUsed) {
          break;
        }
        offset += 4;
        handleIncomingPacket(stdout.subarray(offset, offset + length));
        offset += length;
      }
      if (offset > 0) {
        stdout.copyWithin(0, offset, stdoutUsed);
        stdoutUsed -= offset;
      }
    };
    let afterClose = (error) => {
      closeData.didClose = true;
      if (error)
        closeData.reason = ": " + (error.message || error);
      const text = "The service was stopped" + closeData.reason;
      for (let id in responseCallbacks) {
        responseCallbacks[id](text, null);
      }
      responseCallbacks = {};
    };
    let sendRequest = (refs, value, callback) => {
      if (closeData.didClose)
        return callback("The service is no longer running" + closeData.reason, null);
      let id = nextRequestID++;
      responseCallbacks[id] = (error, response) => {
        try {
          callback(error, response);
        } finally {
          if (refs)
            refs.unref();
        }
      };
      if (refs)
        refs.ref();
      streamIn.writeToStdin(encodePacket({id, isRequest: true, value}));
    };
    let sendResponse = (id, value) => {
      if (closeData.didClose)
        throw new Error("The service is no longer running" + closeData.reason);
      streamIn.writeToStdin(encodePacket({id, isRequest: false, value}));
    };
    let handleRequest = async (id, request) => {
      try {
        if (request.command === "ping") {
          sendResponse(id, {});
          return;
        }
        if (typeof request.key === "number") {
          const requestCallbacks = requestCallbacksByKey[request.key];
          if (!requestCallbacks) {
            return;
          }
          const callback = requestCallbacks[request.command];
          if (callback) {
            await callback(id, request);
            return;
          }
        }
        throw new Error(`Invalid command: ` + request.command);
      } catch (e) {
        const errors = [extractErrorMessageV8(e, streamIn, null, void 0, "")];
        try {
          sendResponse(id, {errors});
        } catch {
        }
      }
    };
    let isFirstPacket = true;
    let handleIncomingPacket = (bytes) => {
      if (isFirstPacket) {
        isFirstPacket = false;
        let binaryVersion = String.fromCharCode(...bytes);
        if (binaryVersion !== "0.28.0") {
          throw new Error(`Cannot start service: Host version "${"0.28.0"}" does not match binary version ${quote(binaryVersion)}`);
        }
        return;
      }
      let packet = decodePacket(bytes);
      if (packet.isRequest) {
        handleRequest(packet.id, packet.value);
      } else {
        let callback = responseCallbacks[packet.id];
        delete responseCallbacks[packet.id];
        if (packet.value.error)
          callback(packet.value.error, {});
        else
          callback(null, packet.value);
      }
    };
    let buildOrContext = ({callName, refs, options, isTTY: isTTY2, defaultWD: defaultWD2, callback}) => {
      let refCount = 0;
      const buildKey = nextBuildKey++;
      const requestCallbacks = {};
      const buildRefs = {
        ref() {
          if (++refCount === 1) {
            if (refs)
              refs.ref();
          }
        },
        unref() {
          if (--refCount === 0) {
            delete requestCallbacksByKey[buildKey];
            if (refs)
              refs.unref();
          }
        }
      };
      requestCallbacksByKey[buildKey] = requestCallbacks;
      buildRefs.ref();
      buildOrContextImpl(callName, buildKey, sendRequest, sendResponse, buildRefs, streamIn, requestCallbacks, options, isTTY2, defaultWD2, (err, res) => {
        try {
          callback(err, res);
        } finally {
          buildRefs.unref();
        }
      });
    };
    let transform22 = ({callName, refs, input, options, isTTY: isTTY2, fs: fs3, callback}) => {
      const details = createObjectStash();
      let start = (inputPath) => {
        try {
          if (typeof input !== "string" && !(input instanceof Uint8Array))
            throw new Error('The input to "transform" must be a string or a Uint8Array');
          let {
            flags,
            mangleCache
          } = flagsForTransformOptions(callName, options, isTTY2, transformLogLevelDefault);
          let request = {
            command: "transform",
            flags,
            inputFS: inputPath !== null,
            input: inputPath !== null ? encodeUTF8(inputPath) : typeof input === "string" ? encodeUTF8(input) : input
          };
          if (mangleCache)
            request.mangleCache = mangleCache;
          sendRequest(refs, request, (error, response) => {
            if (error)
              return callback(new Error(error), null);
            let errors = replaceDetailsInMessages(response.errors, details);
            let warnings = replaceDetailsInMessages(response.warnings, details);
            let outstanding = 1;
            let next = () => {
              if (--outstanding === 0) {
                let result = {
                  warnings,
                  code: response.code,
                  map: response.map,
                  mangleCache: void 0,
                  legalComments: void 0
                };
                if ("legalComments" in response)
                  result.legalComments = response == null ? void 0 : response.legalComments;
                if (response.mangleCache)
                  result.mangleCache = response == null ? void 0 : response.mangleCache;
                callback(null, result);
              }
            };
            if (errors.length > 0)
              return callback(failureErrorWithLog("Transform failed", errors, warnings), null);
            if (response.codeFS) {
              outstanding++;
              fs3.readFile(response.code, (err, contents) => {
                if (err !== null) {
                  callback(err, null);
                } else {
                  response.code = contents;
                  next();
                }
              });
            }
            if (response.mapFS) {
              outstanding++;
              fs3.readFile(response.map, (err, contents) => {
                if (err !== null) {
                  callback(err, null);
                } else {
                  response.map = contents;
                  next();
                }
              });
            }
            next();
          });
        } catch (e) {
          let flags = [];
          try {
            pushLogFlags(flags, options, {}, isTTY2, transformLogLevelDefault);
          } catch {
          }
          const error = extractErrorMessageV8(e, streamIn, details, void 0, "");
          sendRequest(refs, {command: "error", flags, error}, () => {
            error.detail = details.load(error.detail);
            callback(failureErrorWithLog("Transform failed", [error], []), null);
          });
        }
      };
      if ((typeof input === "string" || input instanceof Uint8Array) && input.length > 1024 * 1024) {
        let next = start;
        start = () => fs3.writeFile(input, next);
      }
      start(null);
    };
    let formatMessages22 = ({callName, refs, messages, options, callback}) => {
      if (!options)
        throw new Error(`Missing second argument in ${callName}() call`);
      let keys = {};
      let kind = getFlag(options, keys, "kind", mustBeString);
      let color = getFlag(options, keys, "color", mustBeBoolean);
      let terminalWidth = getFlag(options, keys, "terminalWidth", mustBeInteger);
      checkForInvalidFlags(options, keys, `in ${callName}() call`);
      if (kind === void 0)
        throw new Error(`Missing "kind" in ${callName}() call`);
      if (kind !== "error" && kind !== "warning")
        throw new Error(`Expected "kind" to be "error" or "warning" in ${callName}() call`);
      let request = {
        command: "format-msgs",
        messages: sanitizeMessages(messages, "messages", null, "", terminalWidth),
        isWarning: kind === "warning"
      };
      if (color !== void 0)
        request.color = color;
      if (terminalWidth !== void 0)
        request.terminalWidth = terminalWidth;
      sendRequest(refs, request, (error, response) => {
        if (error)
          return callback(new Error(error), null);
        callback(null, response.messages);
      });
    };
    let analyzeMetafile22 = ({callName, refs, metafile, options, callback}) => {
      if (options === void 0)
        options = {};
      let keys = {};
      let color = getFlag(options, keys, "color", mustBeBoolean);
      let verbose = getFlag(options, keys, "verbose", mustBeBoolean);
      checkForInvalidFlags(options, keys, `in ${callName}() call`);
      let request = {
        command: "analyze-metafile",
        metafile
      };
      if (color !== void 0)
        request.color = color;
      if (verbose !== void 0)
        request.verbose = verbose;
      sendRequest(refs, request, (error, response) => {
        if (error)
          return callback(new Error(error), null);
        callback(null, response.result);
      });
    };
    return {
      readFromStdout,
      afterClose,
      service: {
        buildOrContext,
        transform: transform22,
        formatMessages: formatMessages22,
        analyzeMetafile: analyzeMetafile22
      }
    };
  }
  function buildOrContextImpl(callName, buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, options, isTTY2, defaultWD2, callback) {
    const details = createObjectStash();
    const isContext = callName === "context";
    const handleError = (e, pluginName) => {
      const flags = [];
      try {
        pushLogFlags(flags, options, {}, isTTY2, buildLogLevelDefault);
      } catch {
      }
      const message = extractErrorMessageV8(e, streamIn, details, void 0, pluginName);
      sendRequest(refs, {command: "error", flags, error: message}, () => {
        message.detail = details.load(message.detail);
        callback(failureErrorWithLog(isContext ? "Context failed" : "Build failed", [message], []), null);
      });
    };
    let plugins;
    if (typeof options === "object") {
      const value = options.plugins;
      if (value !== void 0) {
        if (!Array.isArray(value))
          return handleError(new Error(`"plugins" must be an array`), "");
        plugins = value;
      }
    }
    if (plugins && plugins.length > 0) {
      if (streamIn.isSync)
        return handleError(new Error("Cannot use plugins in synchronous API calls"), "");
      handlePlugins(buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, options, plugins, details).then((result) => {
        if (!result.ok)
          return handleError(result.error, result.pluginName);
        try {
          buildOrContextContinue(result.requestPlugins, result.runOnEndCallbacks, result.scheduleOnDisposeCallbacks);
        } catch (e) {
          handleError(e, "");
        }
      }, (e) => handleError(e, ""));
      return;
    }
    try {
      buildOrContextContinue(null, (result, done) => done([], []), () => {
      });
    } catch (e) {
      handleError(e, "");
    }
    function buildOrContextContinue(requestPlugins, runOnEndCallbacks, scheduleOnDisposeCallbacks) {
      const writeDefault = streamIn.hasFS;
      const {
        entries,
        flags,
        write: write3,
        stdinContents,
        stdinResolveDir,
        absWorkingDir,
        nodePaths,
        mangleCache
      } = flagsForBuildOptions(callName, options, isTTY2, buildLogLevelDefault, writeDefault);
      if (write3 && !streamIn.hasFS)
        throw new Error(`The "write" option is unavailable in this environment`);
      const request = {
        command: "build",
        key: buildKey,
        entries,
        flags,
        write: write3,
        stdinContents,
        stdinResolveDir,
        absWorkingDir: absWorkingDir || defaultWD2,
        nodePaths,
        context: isContext
      };
      if (requestPlugins)
        request.plugins = requestPlugins;
      if (mangleCache)
        request.mangleCache = mangleCache;
      const buildResponseToResult = (response, callback2) => {
        const result = {
          errors: replaceDetailsInMessages(response.errors, details),
          warnings: replaceDetailsInMessages(response.warnings, details),
          outputFiles: void 0,
          metafile: void 0,
          mangleCache: void 0
        };
        const originalErrors = result.errors.slice();
        const originalWarnings = result.warnings.slice();
        if (response.outputFiles)
          result.outputFiles = response.outputFiles.map(convertOutputFiles);
        if (response.metafile && response.metafile.length)
          result.metafile = parseJSON(response.metafile);
        if (response.mangleCache)
          result.mangleCache = response.mangleCache;
        if (response.writeToStdout !== void 0)
          console.log(decodeUTF8(response.writeToStdout).replace(/\n$/, ""));
        runOnEndCallbacks(result, (onEndErrors, onEndWarnings) => {
          if (originalErrors.length > 0 || onEndErrors.length > 0) {
            const error = failureErrorWithLog("Build failed", originalErrors.concat(onEndErrors), originalWarnings.concat(onEndWarnings));
            return callback2(error, null, onEndErrors, onEndWarnings);
          }
          callback2(null, result, onEndErrors, onEndWarnings);
        });
      };
      let latestResultPromise;
      let provideLatestResult;
      if (isContext)
        requestCallbacks["on-end"] = (id, request2) => new Promise((resolve2) => {
          buildResponseToResult(request2, (err, result, onEndErrors, onEndWarnings) => {
            const response = {
              errors: onEndErrors,
              warnings: onEndWarnings
            };
            if (provideLatestResult)
              provideLatestResult(err, result);
            latestResultPromise = void 0;
            provideLatestResult = void 0;
            sendResponse(id, response);
            resolve2();
          });
        });
      sendRequest(refs, request, (error, response) => {
        if (error)
          return callback(new Error(error), null);
        if (!isContext) {
          return buildResponseToResult(response, (err, res) => {
            scheduleOnDisposeCallbacks();
            return callback(err, res);
          });
        }
        if (response.errors.length > 0) {
          return callback(failureErrorWithLog("Context failed", response.errors, response.warnings), null);
        }
        let didDispose = false;
        const result = {
          rebuild: () => {
            if (!latestResultPromise)
              latestResultPromise = new Promise((resolve2, reject) => {
                let settlePromise;
                provideLatestResult = (err, result2) => {
                  if (!settlePromise)
                    settlePromise = () => err ? reject(err) : resolve2(result2);
                };
                const triggerAnotherBuild = () => {
                  const request2 = {
                    command: "rebuild",
                    key: buildKey
                  };
                  sendRequest(refs, request2, (error2, response2) => {
                    if (error2) {
                      reject(new Error(error2));
                    } else if (settlePromise) {
                      settlePromise();
                    } else {
                      triggerAnotherBuild();
                    }
                  });
                };
                triggerAnotherBuild();
              });
            return latestResultPromise;
          },
          watch: (options2 = {}) => new Promise((resolve2, reject) => {
            if (!streamIn.hasFS)
              throw new Error(`Cannot use the "watch" API in this environment`);
            const keys = {};
            const delay = getFlag(options2, keys, "delay", mustBeInteger);
            checkForInvalidFlags(options2, keys, `in watch() call`);
            const request2 = {
              command: "watch",
              key: buildKey
            };
            if (delay)
              request2.delay = delay;
            sendRequest(refs, request2, (error2) => {
              if (error2)
                reject(new Error(error2));
              else
                resolve2(void 0);
            });
          }),
          serve: (options2 = {}) => new Promise((resolve2, reject) => {
            if (!streamIn.hasFS)
              throw new Error(`Cannot use the "serve" API in this environment`);
            const keys = {};
            const port = getFlag(options2, keys, "port", mustBeValidPortNumber);
            const host = getFlag(options2, keys, "host", mustBeString);
            const servedir = getFlag(options2, keys, "servedir", mustBeString);
            const keyfile = getFlag(options2, keys, "keyfile", mustBeString);
            const certfile = getFlag(options2, keys, "certfile", mustBeString);
            const fallback = getFlag(options2, keys, "fallback", mustBeString);
            const cors = getFlag(options2, keys, "cors", mustBeObject);
            const onRequest = getFlag(options2, keys, "onRequest", mustBeFunction);
            checkForInvalidFlags(options2, keys, `in serve() call`);
            const request2 = {
              command: "serve",
              key: buildKey,
              onRequest: !!onRequest
            };
            if (port !== void 0)
              request2.port = port;
            if (host !== void 0)
              request2.host = host;
            if (servedir !== void 0)
              request2.servedir = servedir;
            if (keyfile !== void 0)
              request2.keyfile = keyfile;
            if (certfile !== void 0)
              request2.certfile = certfile;
            if (fallback !== void 0)
              request2.fallback = fallback;
            if (cors) {
              const corsKeys = {};
              const origin = getFlag(cors, corsKeys, "origin", mustBeStringOrArrayOfStrings);
              checkForInvalidFlags(cors, corsKeys, `on "cors" object`);
              if (Array.isArray(origin))
                request2.corsOrigin = origin;
              else if (origin !== void 0)
                request2.corsOrigin = [origin];
            }
            sendRequest(refs, request2, (error2, response2) => {
              if (error2)
                return reject(new Error(error2));
              if (onRequest) {
                requestCallbacks["serve-request"] = (id, request3) => {
                  onRequest(request3.args);
                  sendResponse(id, {});
                };
              }
              resolve2(response2);
            });
          }),
          cancel: () => new Promise((resolve2) => {
            if (didDispose)
              return resolve2();
            const request2 = {
              command: "cancel",
              key: buildKey
            };
            sendRequest(refs, request2, () => {
              resolve2();
            });
          }),
          dispose: () => new Promise((resolve2) => {
            if (didDispose)
              return resolve2();
            didDispose = true;
            const request2 = {
              command: "dispose",
              key: buildKey
            };
            sendRequest(refs, request2, () => {
              resolve2();
              scheduleOnDisposeCallbacks();
              refs.unref();
            });
          })
        };
        refs.ref();
        callback(null, result);
      });
    }
  }
  var handlePlugins = async (buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, initialOptions, plugins, details) => {
    let onStartCallbacks = [];
    let onEndCallbacks = [];
    let onResolveCallbacks = {};
    let onLoadCallbacks = {};
    let onDisposeCallbacks = [];
    let nextCallbackID = 0;
    let i = 0;
    let requestPlugins = [];
    let isSetupDone = false;
    plugins = [...plugins];
    for (let item of plugins) {
      let keys = {};
      if (typeof item !== "object")
        throw new Error(`Plugin at index ${i} must be an object`);
      const name = getFlag(item, keys, "name", mustBeString);
      if (typeof name !== "string" || name === "")
        throw new Error(`Plugin at index ${i} is missing a name`);
      try {
        let setup = getFlag(item, keys, "setup", mustBeFunction);
        if (typeof setup !== "function")
          throw new Error(`Plugin is missing a setup function`);
        checkForInvalidFlags(item, keys, `on plugin ${quote(name)}`);
        let plugin = {
          name,
          onStart: false,
          onEnd: false,
          onResolve: [],
          onLoad: []
        };
        i++;
        let resolve2 = (path3, options = {}) => {
          if (!isSetupDone)
            throw new Error('Cannot call "resolve" before plugin setup has completed');
          if (typeof path3 !== "string")
            throw new Error(`The path to resolve must be a string`);
          let keys2 = /* @__PURE__ */ Object.create(null);
          let pluginName = getFlag(options, keys2, "pluginName", mustBeString);
          let importer = getFlag(options, keys2, "importer", mustBeString);
          let namespace = getFlag(options, keys2, "namespace", mustBeString);
          let resolveDir = getFlag(options, keys2, "resolveDir", mustBeString);
          let kind = getFlag(options, keys2, "kind", mustBeString);
          let pluginData = getFlag(options, keys2, "pluginData", canBeAnything);
          let importAttributes = getFlag(options, keys2, "with", mustBeObject);
          checkForInvalidFlags(options, keys2, "in resolve() call");
          return new Promise((resolve22, reject) => {
            const request = {
              command: "resolve",
              path: path3,
              key: buildKey,
              pluginName: name
            };
            if (pluginName != null)
              request.pluginName = pluginName;
            if (importer != null)
              request.importer = importer;
            if (namespace != null)
              request.namespace = namespace;
            if (resolveDir != null)
              request.resolveDir = resolveDir;
            if (kind != null)
              request.kind = kind;
            else
              throw new Error(`Must specify "kind" when calling "resolve"`);
            if (pluginData != null)
              request.pluginData = details.store(pluginData);
            if (importAttributes != null)
              request.with = sanitizeStringMap(importAttributes, "with");
            sendRequest(refs, request, (error, response) => {
              if (error !== null)
                reject(new Error(error));
              else
                resolve22({
                  errors: replaceDetailsInMessages(response.errors, details),
                  warnings: replaceDetailsInMessages(response.warnings, details),
                  path: response.path,
                  external: response.external,
                  sideEffects: response.sideEffects,
                  namespace: response.namespace,
                  suffix: response.suffix,
                  pluginData: details.load(response.pluginData)
                });
            });
          });
        };
        let promise = setup({
          initialOptions,
          resolve: resolve2,
          onStart(callback) {
            let registeredText = `This error came from the "onStart" callback registered here:`;
            let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onStart");
            onStartCallbacks.push({name, callback, note: registeredNote});
            plugin.onStart = true;
          },
          onEnd(callback) {
            let registeredText = `This error came from the "onEnd" callback registered here:`;
            let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onEnd");
            onEndCallbacks.push({name, callback, note: registeredNote});
            plugin.onEnd = true;
          },
          onResolve(options, callback) {
            let registeredText = `This error came from the "onResolve" callback registered here:`;
            let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onResolve");
            let keys2 = {};
            let filter2 = getFlag(options, keys2, "filter", mustBeRegExp);
            let namespace = getFlag(options, keys2, "namespace", mustBeString);
            checkForInvalidFlags(options, keys2, `in onResolve() call for plugin ${quote(name)}`);
            if (filter2 == null)
              throw new Error(`onResolve() call is missing a filter`);
            let id = nextCallbackID++;
            onResolveCallbacks[id] = {name, callback, note: registeredNote};
            plugin.onResolve.push({id, filter: jsRegExpToGoRegExp(filter2), namespace: namespace || ""});
          },
          onLoad(options, callback) {
            let registeredText = `This error came from the "onLoad" callback registered here:`;
            let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onLoad");
            let keys2 = {};
            let filter2 = getFlag(options, keys2, "filter", mustBeRegExp);
            let namespace = getFlag(options, keys2, "namespace", mustBeString);
            checkForInvalidFlags(options, keys2, `in onLoad() call for plugin ${quote(name)}`);
            if (filter2 == null)
              throw new Error(`onLoad() call is missing a filter`);
            let id = nextCallbackID++;
            onLoadCallbacks[id] = {name, callback, note: registeredNote};
            plugin.onLoad.push({id, filter: jsRegExpToGoRegExp(filter2), namespace: namespace || ""});
          },
          onDispose(callback) {
            onDisposeCallbacks.push(callback);
          },
          esbuild: streamIn.esbuild
        });
        if (promise)
          await promise;
        requestPlugins.push(plugin);
      } catch (e) {
        return {ok: false, error: e, pluginName: name};
      }
    }
    requestCallbacks["on-start"] = async (id, request) => {
      details.clear();
      let response = {errors: [], warnings: []};
      await Promise.all(onStartCallbacks.map(async ({name, callback, note}) => {
        try {
          let result = await callback();
          if (result != null) {
            if (typeof result !== "object")
              throw new Error(`Expected onStart() callback in plugin ${quote(name)} to return an object`);
            let keys = {};
            let errors = getFlag(result, keys, "errors", mustBeArray);
            let warnings = getFlag(result, keys, "warnings", mustBeArray);
            checkForInvalidFlags(result, keys, `from onStart() callback in plugin ${quote(name)}`);
            if (errors != null)
              response.errors.push(...sanitizeMessages(errors, "errors", details, name, void 0));
            if (warnings != null)
              response.warnings.push(...sanitizeMessages(warnings, "warnings", details, name, void 0));
          }
        } catch (e) {
          response.errors.push(extractErrorMessageV8(e, streamIn, details, note && note(), name));
        }
      }));
      sendResponse(id, response);
    };
    requestCallbacks["on-resolve"] = async (id, request) => {
      let response = {}, name = "", callback, note;
      for (let id2 of request.ids) {
        try {
          ({name, callback, note} = onResolveCallbacks[id2]);
          let result = await callback({
            path: request.path,
            importer: request.importer,
            namespace: request.namespace,
            resolveDir: request.resolveDir,
            kind: request.kind,
            pluginData: details.load(request.pluginData),
            with: request.with
          });
          if (result != null) {
            if (typeof result !== "object")
              throw new Error(`Expected onResolve() callback in plugin ${quote(name)} to return an object`);
            let keys = {};
            let pluginName = getFlag(result, keys, "pluginName", mustBeString);
            let path3 = getFlag(result, keys, "path", mustBeString);
            let namespace = getFlag(result, keys, "namespace", mustBeString);
            let suffix = getFlag(result, keys, "suffix", mustBeString);
            let external = getFlag(result, keys, "external", mustBeBoolean);
            let sideEffects = getFlag(result, keys, "sideEffects", mustBeBoolean);
            let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
            let errors = getFlag(result, keys, "errors", mustBeArray);
            let warnings = getFlag(result, keys, "warnings", mustBeArray);
            let watchFiles = getFlag(result, keys, "watchFiles", mustBeArrayOfStrings);
            let watchDirs = getFlag(result, keys, "watchDirs", mustBeArrayOfStrings);
            checkForInvalidFlags(result, keys, `from onResolve() callback in plugin ${quote(name)}`);
            response.id = id2;
            if (pluginName != null)
              response.pluginName = pluginName;
            if (path3 != null)
              response.path = path3;
            if (namespace != null)
              response.namespace = namespace;
            if (suffix != null)
              response.suffix = suffix;
            if (external != null)
              response.external = external;
            if (sideEffects != null)
              response.sideEffects = sideEffects;
            if (pluginData != null)
              response.pluginData = details.store(pluginData);
            if (errors != null)
              response.errors = sanitizeMessages(errors, "errors", details, name, void 0);
            if (warnings != null)
              response.warnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
            if (watchFiles != null)
              response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
            if (watchDirs != null)
              response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
            break;
          }
        } catch (e) {
          response = {id: id2, errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)]};
          break;
        }
      }
      sendResponse(id, response);
    };
    requestCallbacks["on-load"] = async (id, request) => {
      let response = {}, name = "", callback, note;
      for (let id2 of request.ids) {
        try {
          ({name, callback, note} = onLoadCallbacks[id2]);
          let result = await callback({
            path: request.path,
            namespace: request.namespace,
            suffix: request.suffix,
            pluginData: details.load(request.pluginData),
            with: request.with
          });
          if (result != null) {
            if (typeof result !== "object")
              throw new Error(`Expected onLoad() callback in plugin ${quote(name)} to return an object`);
            let keys = {};
            let pluginName = getFlag(result, keys, "pluginName", mustBeString);
            let contents = getFlag(result, keys, "contents", mustBeStringOrUint8Array);
            let resolveDir = getFlag(result, keys, "resolveDir", mustBeString);
            let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
            let loader = getFlag(result, keys, "loader", mustBeString);
            let errors = getFlag(result, keys, "errors", mustBeArray);
            let warnings = getFlag(result, keys, "warnings", mustBeArray);
            let watchFiles = getFlag(result, keys, "watchFiles", mustBeArrayOfStrings);
            let watchDirs = getFlag(result, keys, "watchDirs", mustBeArrayOfStrings);
            checkForInvalidFlags(result, keys, `from onLoad() callback in plugin ${quote(name)}`);
            response.id = id2;
            if (pluginName != null)
              response.pluginName = pluginName;
            if (contents instanceof Uint8Array)
              response.contents = contents;
            else if (contents != null)
              response.contents = encodeUTF8(contents);
            if (resolveDir != null)
              response.resolveDir = resolveDir;
            if (pluginData != null)
              response.pluginData = details.store(pluginData);
            if (loader != null)
              response.loader = loader;
            if (errors != null)
              response.errors = sanitizeMessages(errors, "errors", details, name, void 0);
            if (warnings != null)
              response.warnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
            if (watchFiles != null)
              response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
            if (watchDirs != null)
              response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
            break;
          }
        } catch (e) {
          response = {id: id2, errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)]};
          break;
        }
      }
      sendResponse(id, response);
    };
    let runOnEndCallbacks = (result, done) => done([], []);
    if (onEndCallbacks.length > 0) {
      runOnEndCallbacks = (result, done) => {
        (async () => {
          const onEndErrors = [];
          const onEndWarnings = [];
          for (const {name, callback, note} of onEndCallbacks) {
            let newErrors;
            let newWarnings;
            try {
              const value = await callback(result);
              if (value != null) {
                if (typeof value !== "object")
                  throw new Error(`Expected onEnd() callback in plugin ${quote(name)} to return an object`);
                let keys = {};
                let errors = getFlag(value, keys, "errors", mustBeArray);
                let warnings = getFlag(value, keys, "warnings", mustBeArray);
                checkForInvalidFlags(value, keys, `from onEnd() callback in plugin ${quote(name)}`);
                if (errors != null)
                  newErrors = sanitizeMessages(errors, "errors", details, name, void 0);
                if (warnings != null)
                  newWarnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
              }
            } catch (e) {
              newErrors = [extractErrorMessageV8(e, streamIn, details, note && note(), name)];
            }
            if (newErrors) {
              onEndErrors.push(...newErrors);
              try {
                result.errors.push(...newErrors);
              } catch {
              }
            }
            if (newWarnings) {
              onEndWarnings.push(...newWarnings);
              try {
                result.warnings.push(...newWarnings);
              } catch {
              }
            }
          }
          done(onEndErrors, onEndWarnings);
        })();
      };
    }
    let scheduleOnDisposeCallbacks = () => {
      for (const cb of onDisposeCallbacks) {
        setTimeout(() => cb(), 0);
      }
    };
    isSetupDone = true;
    return {
      ok: true,
      requestPlugins,
      runOnEndCallbacks,
      scheduleOnDisposeCallbacks
    };
  };
  function createObjectStash() {
    const map = /* @__PURE__ */ new Map();
    let nextID = 0;
    return {
      clear() {
        map.clear();
      },
      load(id) {
        return map.get(id);
      },
      store(value) {
        if (value === void 0)
          return -1;
        const id = nextID++;
        map.set(id, value);
        return id;
      }
    };
  }
  function extractCallerV8(e, streamIn, ident) {
    let note;
    let tried = false;
    return () => {
      if (tried)
        return note;
      tried = true;
      try {
        let lines = (e.stack + "").split("\n");
        lines.splice(1, 1);
        let location = parseStackLinesV8(streamIn, lines, ident);
        if (location) {
          note = {text: e.message, location};
          return note;
        }
      } catch {
      }
    };
  }
  function extractErrorMessageV8(e, streamIn, stash, note, pluginName) {
    let text = "Internal error";
    let location = null;
    try {
      text = (e && e.message || e) + "";
    } catch {
    }
    try {
      location = parseStackLinesV8(streamIn, (e.stack + "").split("\n"), "");
    } catch {
    }
    return {id: "", pluginName, text, location, notes: note ? [note] : [], detail: stash ? stash.store(e) : -1};
  }
  function parseStackLinesV8(streamIn, lines, ident) {
    let at = "    at ";
    if (streamIn.readFileSync && !lines[0].startsWith(at) && lines[1].startsWith(at)) {
      for (let i = 1; i < lines.length; i++) {
        let line = lines[i];
        if (!line.startsWith(at))
          continue;
        line = line.slice(at.length);
        while (true) {
          let match = /^(?:new |async )?\S+ \((.*)\)$/.exec(line);
          if (match) {
            line = match[1];
            continue;
          }
          match = /^eval at \S+ \((.*)\)(?:, \S+:\d+:\d+)?$/.exec(line);
          if (match) {
            line = match[1];
            continue;
          }
          match = /^(\S+):(\d+):(\d+)$/.exec(line);
          if (match) {
            let contents;
            try {
              contents = streamIn.readFileSync(match[1], "utf8");
            } catch {
              break;
            }
            let lineText = contents.split(/\r\n|\r|\n|\u2028|\u2029/)[+match[2] - 1] || "";
            let column = +match[3] - 1;
            let length = lineText.slice(column, column + ident.length) === ident ? ident.length : 0;
            return {
              file: match[1],
              namespace: "file",
              line: +match[2],
              column: encodeUTF8(lineText.slice(0, column)).length,
              length: encodeUTF8(lineText.slice(column, column + length)).length,
              lineText: lineText + "\n" + lines.slice(1).join("\n"),
              suggestion: ""
            };
          }
          break;
        }
      }
    }
    return null;
  }
  function failureErrorWithLog(text, errors, warnings) {
    let limit = 5;
    text += errors.length < 1 ? "" : ` with ${errors.length} error${errors.length < 2 ? "" : "s"}:` + errors.slice(0, limit + 1).map((e, i) => {
      if (i === limit)
        return "\n...";
      if (!e.location)
        return `
error: ${e.text}`;
      let {file, line, column} = e.location;
      let pluginText = e.pluginName ? `[plugin: ${e.pluginName}] ` : "";
      return `
${file}:${line}:${column}: ERROR: ${pluginText}${e.text}`;
    }).join("");
    let error = new Error(text);
    for (const [key, value] of [["errors", errors], ["warnings", warnings]]) {
      Object.defineProperty(error, key, {
        configurable: true,
        enumerable: true,
        get: () => value,
        set: (value2) => Object.defineProperty(error, key, {
          configurable: true,
          enumerable: true,
          value: value2
        })
      });
    }
    return error;
  }
  function replaceDetailsInMessages(messages, stash) {
    for (const message of messages) {
      message.detail = stash.load(message.detail);
    }
    return messages;
  }
  function sanitizeLocation(location, where, terminalWidth) {
    if (location == null)
      return null;
    let keys = {};
    let file = getFlag(location, keys, "file", mustBeString);
    let namespace = getFlag(location, keys, "namespace", mustBeString);
    let line = getFlag(location, keys, "line", mustBeInteger);
    let column = getFlag(location, keys, "column", mustBeInteger);
    let length = getFlag(location, keys, "length", mustBeInteger);
    let lineText = getFlag(location, keys, "lineText", mustBeString);
    let suggestion = getFlag(location, keys, "suggestion", mustBeString);
    checkForInvalidFlags(location, keys, where);
    if (lineText) {
      const relevantASCII = lineText.slice(0, (column && column > 0 ? column : 0) + (length && length > 0 ? length : 0) + (terminalWidth && terminalWidth > 0 ? terminalWidth : 80));
      if (!/[\x7F-\uFFFF]/.test(relevantASCII) && !/\n/.test(lineText)) {
        lineText = relevantASCII;
      }
    }
    return {
      file: file || "",
      namespace: namespace || "",
      line: line || 0,
      column: column || 0,
      length: length || 0,
      lineText: lineText || "",
      suggestion: suggestion || ""
    };
  }
  function sanitizeMessages(messages, property, stash, fallbackPluginName, terminalWidth) {
    let messagesClone = [];
    let index = 0;
    for (const message of messages) {
      let keys = {};
      let id = getFlag(message, keys, "id", mustBeString);
      let pluginName = getFlag(message, keys, "pluginName", mustBeString);
      let text = getFlag(message, keys, "text", mustBeString);
      let location = getFlag(message, keys, "location", mustBeObjectOrNull);
      let notes = getFlag(message, keys, "notes", mustBeArray);
      let detail = getFlag(message, keys, "detail", canBeAnything);
      let where = `in element ${index} of "${property}"`;
      checkForInvalidFlags(message, keys, where);
      let notesClone = [];
      if (notes) {
        for (const note of notes) {
          let noteKeys = {};
          let noteText = getFlag(note, noteKeys, "text", mustBeString);
          let noteLocation = getFlag(note, noteKeys, "location", mustBeObjectOrNull);
          checkForInvalidFlags(note, noteKeys, where);
          notesClone.push({
            text: noteText || "",
            location: sanitizeLocation(noteLocation, where, terminalWidth)
          });
        }
      }
      messagesClone.push({
        id: id || "",
        pluginName: pluginName || fallbackPluginName,
        text: text || "",
        location: sanitizeLocation(location, where, terminalWidth),
        notes: notesClone,
        detail: stash ? stash.store(detail) : -1
      });
      index++;
    }
    return messagesClone;
  }
  function sanitizeStringArray(values, property) {
    const result = [];
    for (const value of values) {
      if (typeof value !== "string")
        throw new Error(`${quote(property)} must be an array of strings`);
      result.push(value);
    }
    return result;
  }
  function sanitizeStringMap(map, property) {
    const result = /* @__PURE__ */ Object.create(null);
    for (const key in map) {
      const value = map[key];
      if (typeof value !== "string")
        throw new Error(`key ${quote(key)} in object ${quote(property)} must be a string`);
      result[key] = value;
    }
    return result;
  }
  function convertOutputFiles({path: path3, contents, hash}) {
    let text = null;
    return {
      path: path3,
      contents,
      hash,
      get text() {
        const binary = this.contents;
        if (text === null || binary !== contents) {
          contents = binary;
          text = decodeUTF8(binary);
        }
        return text;
      }
    };
  }
  function jsRegExpToGoRegExp(regexp) {
    let result = regexp.source;
    if (regexp.flags)
      result = `(?${regexp.flags})${result}`;
    return result;
  }
  function parseJSON(bytes) {
    let text;
    try {
      text = decodeUTF8(bytes);
    } catch {
      return JSON_parse(bytes);
    }
    return JSON.parse(text);
  }
  var ESBUILD_BINARY_PATH = process.env.ESBUILD_BINARY_PATH || ESBUILD_BINARY_PATH;
  var isValidBinaryPath = (x) => !!x && x !== "/usr/bin/esbuild";
  var packageDarwin_arm64 = "@esbuild/darwin-arm64";
  var packageDarwin_x64 = "@esbuild/darwin-x64";
  var knownWindowsPackages = {
    "win32 arm64 LE": "@esbuild/win32-arm64",
    "win32 ia32 LE": "@esbuild/win32-ia32",
    "win32 x64 LE": "@esbuild/win32-x64"
  };
  var knownUnixlikePackages = {
    "aix ppc64 BE": "@esbuild/aix-ppc64",
    "android arm64 LE": "@esbuild/android-arm64",
    "darwin arm64 LE": "@esbuild/darwin-arm64",
    "darwin x64 LE": "@esbuild/darwin-x64",
    "freebsd arm64 LE": "@esbuild/freebsd-arm64",
    "freebsd x64 LE": "@esbuild/freebsd-x64",
    "linux arm LE": "@esbuild/linux-arm",
    "linux arm64 LE": "@esbuild/linux-arm64",
    "linux ia32 LE": "@esbuild/linux-ia32",
    "linux mips64el LE": "@esbuild/linux-mips64el",
    "linux ppc64 LE": "@esbuild/linux-ppc64",
    "linux riscv64 LE": "@esbuild/linux-riscv64",
    "linux s390x BE": "@esbuild/linux-s390x",
    "linux x64 LE": "@esbuild/linux-x64",
    "linux loong64 LE": "@esbuild/linux-loong64",
    "netbsd arm64 LE": "@esbuild/netbsd-arm64",
    "netbsd x64 LE": "@esbuild/netbsd-x64",
    "openbsd arm64 LE": "@esbuild/openbsd-arm64",
    "openbsd x64 LE": "@esbuild/openbsd-x64",
    "sunos x64 LE": "@esbuild/sunos-x64"
  };
  var knownWebAssemblyFallbackPackages = {
    "android arm LE": "@esbuild/android-arm",
    "android x64 LE": "@esbuild/android-x64",
    "openharmony arm64 LE": "@esbuild/openharmony-arm64"
  };
  function pkgAndSubpathForCurrentPlatform() {
    let pkg;
    let subpath;
    let isWASM = false;
    let platformKey = `${process.platform} ${os.arch()} ${os.endianness()}`;
    if (platformKey in knownWindowsPackages) {
      pkg = knownWindowsPackages[platformKey];
      subpath = "esbuild.exe";
    } else if (platformKey in knownUnixlikePackages) {
      pkg = knownUnixlikePackages[platformKey];
      subpath = "bin/esbuild";
    } else if (platformKey in knownWebAssemblyFallbackPackages) {
      pkg = knownWebAssemblyFallbackPackages[platformKey];
      subpath = "bin/esbuild";
      isWASM = true;
    } else {
      throw new Error(`Unsupported platform: ${platformKey}`);
    }
    return {pkg, subpath, isWASM};
  }
  function pkgForSomeOtherPlatform() {
    const libMainJS = require.resolve("esbuild");
    const nodeModulesDirectory = path$1.dirname(path$1.dirname(path$1.dirname(libMainJS)));
    if (path$1.basename(nodeModulesDirectory) === "node_modules") {
      for (const unixKey in knownUnixlikePackages) {
        try {
          const pkg = knownUnixlikePackages[unixKey];
          if (fs.existsSync(path$1.join(nodeModulesDirectory, pkg)))
            return pkg;
        } catch {
        }
      }
      for (const windowsKey in knownWindowsPackages) {
        try {
          const pkg = knownWindowsPackages[windowsKey];
          if (fs.existsSync(path$1.join(nodeModulesDirectory, pkg)))
            return pkg;
        } catch {
        }
      }
    }
    return null;
  }
  function downloadedBinPath(pkg, subpath) {
    const esbuildLibDir = path$1.dirname(require.resolve("esbuild"));
    return path$1.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path$1.basename(subpath)}`);
  }
  function generateBinPath() {
    if (isValidBinaryPath(ESBUILD_BINARY_PATH)) {
      if (!fs.existsSync(ESBUILD_BINARY_PATH)) {
        console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`);
      } else {
        return {binPath: ESBUILD_BINARY_PATH, isWASM: false};
      }
    }
    const {pkg, subpath, isWASM} = pkgAndSubpathForCurrentPlatform();
    let binPath;
    try {
      binPath = require.resolve(`${pkg}/${subpath}`);
    } catch (e) {
      binPath = downloadedBinPath(pkg, subpath);
      if (!fs.existsSync(binPath)) {
        try {
          require.resolve(pkg);
        } catch {
          const otherPkg = pkgForSomeOtherPlatform();
          if (otherPkg) {
            let suggestions = `
Specifically the "${otherPkg}" package is present but this platform
needs the "${pkg}" package instead. People often get into this
situation by installing esbuild on Windows or macOS and copying "node_modules"
into a Docker image that runs Linux, or by copying "node_modules" between
Windows and WSL environments.

If you are installing with npm, you can try not copying the "node_modules"
directory when you copy the files over, and running "npm ci" or "npm install"
on the destination platform after the copy. Or you could consider using yarn
instead of npm which has built-in support for installing a package on multiple
platforms simultaneously.

If you are installing with yarn, you can try listing both this platform and the
other platform in your ".yarnrc.yml" file using the "supportedArchitectures"
feature: https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
Keep in mind that this means multiple copies of esbuild will be present.
`;
            if (pkg === packageDarwin_x64 && otherPkg === packageDarwin_arm64 || pkg === packageDarwin_arm64 && otherPkg === packageDarwin_x64) {
              suggestions = `
Specifically the "${otherPkg}" package is present but this platform
needs the "${pkg}" package instead. People often get into this
situation by installing esbuild with npm running inside of Rosetta 2 and then
trying to use it with node running outside of Rosetta 2, or vice versa (Rosetta
2 is Apple's on-the-fly x86_64-to-arm64 translation service).

If you are installing with npm, you can try ensuring that both npm and node are
not running under Rosetta 2 and then reinstalling esbuild. This likely involves
changing how you installed npm and/or node. For example, installing node with
the universal installer here should work: https://nodejs.org/en/download/. Or
you could consider using yarn instead of npm which has built-in support for
installing a package on multiple platforms simultaneously.

If you are installing with yarn, you can try listing both "arm64" and "x64"
in your ".yarnrc.yml" file using the "supportedArchitectures" feature:
https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
Keep in mind that this means multiple copies of esbuild will be present.
`;
            }
            throw new Error(`
You installed esbuild for another platform than the one you're currently using.
This won't work because esbuild is written with native code and needs to
install a platform-specific binary executable.
${suggestions}
Another alternative is to use the "esbuild-wasm" package instead, which works
the same way on all platforms. But it comes with a heavy performance cost and
can sometimes be 10x slower than the "esbuild" package, so you may also not
want to do that.
`);
          }
          throw new Error(`The package "${pkg}" could not be found, and is needed by esbuild.

If you are installing esbuild with npm, make sure that you don't specify the
"--no-optional" or "--omit=optional" flags. The "optionalDependencies" feature
of "package.json" is used by esbuild to install the correct binary executable
for your current platform.`);
        }
        throw e;
      }
    }
    if (/\.zip\//.test(binPath)) {
      let pnpapi;
      try {
        pnpapi = require$$0;
      } catch (e) {
      }
      if (pnpapi) {
        const root = pnpapi.getPackageInformation(pnpapi.topLevel).packageLocation;
        const binTargetPath = path$1.join(root, "node_modules", ".cache", "esbuild", `pnpapi-${pkg.replace("/", "-")}-${"0.28.0"}-${path$1.basename(subpath)}`);
        if (!fs.existsSync(binTargetPath)) {
          fs.mkdirSync(path$1.dirname(binTargetPath), {recursive: true});
          fs.copyFileSync(binPath, binTargetPath);
          fs.chmodSync(binTargetPath, 493);
        }
        return {binPath: binTargetPath, isWASM};
      }
    }
    return {binPath, isWASM};
  }
  var path2 = path$1;
  var fs2 = fs;
  var os2 = os;
  var worker_threads;
  if (process.env.ESBUILD_WORKER_THREADS !== "0") {
    try {
      worker_threads = require$$1;
    } catch {
    }
    let [major, minor] = process.versions.node.split(".");
    if (+major < 12 || +major === 12 && +minor < 17 || +major === 13 && +minor < 13) {
      worker_threads = void 0;
    }
  }
  var _a;
  var isInternalWorkerThread = ((_a = worker_threads == null ? void 0 : worker_threads.workerData) == null ? void 0 : _a.esbuildVersion) === "0.28.0";
  var esbuildCommandAndArgs = () => {
    if ((!ESBUILD_BINARY_PATH || false) && (path2.basename(__filename) !== "main.js" || path2.basename(__dirname) !== "lib")) {
      throw new Error(`The esbuild JavaScript API cannot be bundled. Please mark the "esbuild" package as external so it's not included in the bundle.

More information: The file containing the code for esbuild's JavaScript API (${__filename}) does not appear to be inside the esbuild package on the file system, which usually means that the esbuild package was bundled into another file. This is problematic because the API needs to run a binary executable inside the esbuild package which is located using a relative path from the API code to the executable. If the esbuild package is bundled, the relative path will be incorrect and the executable won't be found.`);
    }
    {
      const {binPath, isWASM} = generateBinPath();
      if (isWASM) {
        return ["node", [binPath]];
      } else {
        return [binPath, []];
      }
    }
  };
  var isTTY = () => tty.isatty(2);
  var fsSync = {
    readFile(tempFile, callback) {
      try {
        let contents = fs2.readFileSync(tempFile, "utf8");
        try {
          fs2.unlinkSync(tempFile);
        } catch {
        }
        callback(null, contents);
      } catch (err) {
        callback(err, null);
      }
    },
    writeFile(contents, callback) {
      try {
        let tempFile = randomFileName();
        fs2.writeFileSync(tempFile, contents);
        callback(tempFile);
      } catch {
        callback(null);
      }
    }
  };
  var fsAsync = {
    readFile(tempFile, callback) {
      try {
        fs2.readFile(tempFile, "utf8", (err, contents) => {
          try {
            fs2.unlink(tempFile, () => callback(err, contents));
          } catch {
            callback(err, contents);
          }
        });
      } catch (err) {
        callback(err, null);
      }
    },
    writeFile(contents, callback) {
      try {
        let tempFile = randomFileName();
        fs2.writeFile(tempFile, contents, (err) => err !== null ? callback(null) : callback(tempFile));
      } catch {
        callback(null);
      }
    }
  };
  var version2 = "0.28.0";
  var build2 = (options) => ensureServiceIsRunning().build(options);
  var context2 = (buildOptions) => ensureServiceIsRunning().context(buildOptions);
  var transform2 = (input, options) => ensureServiceIsRunning().transform(input, options);
  var formatMessages2 = (messages, options) => ensureServiceIsRunning().formatMessages(messages, options);
  var analyzeMetafile2 = (messages, options) => ensureServiceIsRunning().analyzeMetafile(messages, options);
  var buildSync2 = (options) => {
    if (worker_threads && !isInternalWorkerThread) {
      if (!workerThreadService)
        workerThreadService = startWorkerThreadService(worker_threads);
      return workerThreadService.buildSync(options);
    }
    let result;
    runServiceSync((service) => service.buildOrContext({
      callName: "buildSync",
      refs: null,
      options,
      isTTY: isTTY(),
      defaultWD,
      callback: (err, res) => {
        if (err)
          throw err;
        result = res;
      }
    }));
    return result;
  };
  var transformSync2 = (input, options) => {
    if (worker_threads && !isInternalWorkerThread) {
      if (!workerThreadService)
        workerThreadService = startWorkerThreadService(worker_threads);
      return workerThreadService.transformSync(input, options);
    }
    let result;
    runServiceSync((service) => service.transform({
      callName: "transformSync",
      refs: null,
      input,
      options: options || {},
      isTTY: isTTY(),
      fs: fsSync,
      callback: (err, res) => {
        if (err)
          throw err;
        result = res;
      }
    }));
    return result;
  };
  var formatMessagesSync2 = (messages, options) => {
    if (worker_threads && !isInternalWorkerThread) {
      if (!workerThreadService)
        workerThreadService = startWorkerThreadService(worker_threads);
      return workerThreadService.formatMessagesSync(messages, options);
    }
    let result;
    runServiceSync((service) => service.formatMessages({
      callName: "formatMessagesSync",
      refs: null,
      messages,
      options,
      callback: (err, res) => {
        if (err)
          throw err;
        result = res;
      }
    }));
    return result;
  };
  var analyzeMetafileSync2 = (metafile, options) => {
    if (worker_threads && !isInternalWorkerThread) {
      if (!workerThreadService)
        workerThreadService = startWorkerThreadService(worker_threads);
      return workerThreadService.analyzeMetafileSync(metafile, options);
    }
    let result;
    runServiceSync((service) => service.analyzeMetafile({
      callName: "analyzeMetafileSync",
      refs: null,
      metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile),
      options,
      callback: (err, res) => {
        if (err)
          throw err;
        result = res;
      }
    }));
    return result;
  };
  var stop2 = () => {
    if (stopService)
      stopService();
    if (workerThreadService)
      workerThreadService.stop();
    return Promise.resolve();
  };
  var initializeWasCalled = false;
  var initialize2 = (options) => {
    options = validateInitializeOptions(options || {});
    if (options.wasmURL)
      throw new Error(`The "wasmURL" option only works in the browser`);
    if (options.wasmModule)
      throw new Error(`The "wasmModule" option only works in the browser`);
    if (options.worker)
      throw new Error(`The "worker" option only works in the browser`);
    if (initializeWasCalled)
      throw new Error('Cannot call "initialize" more than once');
    ensureServiceIsRunning();
    initializeWasCalled = true;
    return Promise.resolve();
  };
  var defaultWD = process.cwd();
  var longLivedService;
  var stopService;
  var ensureServiceIsRunning = () => {
    if (longLivedService)
      return longLivedService;
    let [command, args] = esbuildCommandAndArgs();
    let child = child_process.spawn(command, args.concat(`--service=${"0.28.0"}`, "--ping"), {
      windowsHide: true,
      stdio: ["pipe", "pipe", "inherit"],
      cwd: defaultWD
    });
    let {readFromStdout, afterClose, service} = createChannel({
      writeToStdin(bytes) {
        child.stdin.write(bytes, (err) => {
          if (err)
            afterClose(err);
        });
      },
      readFileSync: fs2.readFileSync,
      isSync: false,
      hasFS: true,
      esbuild: node_exports
    });
    child.stdin.on("error", afterClose);
    child.on("error", afterClose);
    const stdin = child.stdin;
    const stdout = child.stdout;
    stdout.on("data", readFromStdout);
    stdout.on("end", afterClose);
    stopService = () => {
      stdin.destroy();
      stdout.destroy();
      child.kill();
      initializeWasCalled = false;
      longLivedService = void 0;
      stopService = void 0;
    };
    let refCount = 0;
    child.unref();
    if (stdin.unref) {
      stdin.unref();
    }
    if (stdout.unref) {
      stdout.unref();
    }
    const refs = {
      ref() {
        if (++refCount === 1)
          child.ref();
      },
      unref() {
        if (--refCount === 0)
          child.unref();
      }
    };
    longLivedService = {
      build: (options) => new Promise((resolve2, reject) => {
        service.buildOrContext({
          callName: "build",
          refs,
          options,
          isTTY: isTTY(),
          defaultWD,
          callback: (err, res) => err ? reject(err) : resolve2(res)
        });
      }),
      context: (options) => new Promise((resolve2, reject) => service.buildOrContext({
        callName: "context",
        refs,
        options,
        isTTY: isTTY(),
        defaultWD,
        callback: (err, res) => err ? reject(err) : resolve2(res)
      })),
      transform: (input, options) => new Promise((resolve2, reject) => service.transform({
        callName: "transform",
        refs,
        input,
        options: options || {},
        isTTY: isTTY(),
        fs: fsAsync,
        callback: (err, res) => err ? reject(err) : resolve2(res)
      })),
      formatMessages: (messages, options) => new Promise((resolve2, reject) => service.formatMessages({
        callName: "formatMessages",
        refs,
        messages,
        options,
        callback: (err, res) => err ? reject(err) : resolve2(res)
      })),
      analyzeMetafile: (metafile, options) => new Promise((resolve2, reject) => service.analyzeMetafile({
        callName: "analyzeMetafile",
        refs,
        metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile),
        options,
        callback: (err, res) => err ? reject(err) : resolve2(res)
      }))
    };
    return longLivedService;
  };
  var runServiceSync = (callback) => {
    let [command, args] = esbuildCommandAndArgs();
    let stdin = new Uint8Array();
    let {readFromStdout, afterClose, service} = createChannel({
      writeToStdin(bytes) {
        if (stdin.length !== 0)
          throw new Error("Must run at most one command");
        stdin = bytes;
      },
      isSync: true,
      hasFS: true,
      esbuild: node_exports
    });
    callback(service);
    let stdout = child_process.execFileSync(command, args.concat(`--service=${"0.28.0"}`), {
      cwd: defaultWD,
      windowsHide: true,
      input: stdin,
      maxBuffer: +process.env.ESBUILD_MAX_BUFFER || 16 * 1024 * 1024
    });
    readFromStdout(stdout);
    afterClose(null);
  };
  var randomFileName = () => {
    return path2.join(os2.tmpdir(), `esbuild-${crypto.randomBytes(32).toString("hex")}`);
  };
  var workerThreadService = null;
  var startWorkerThreadService = (worker_threads2) => {
    let {port1: mainPort, port2: workerPort} = new worker_threads2.MessageChannel();
    let worker = new worker_threads2.Worker(__filename, {
      workerData: {workerPort, defaultWD, esbuildVersion: "0.28.0"},
      transferList: [workerPort],
      execArgv: []
    });
    let nextID = 0;
    let fakeBuildError = (text) => {
      let error = new Error(`Build failed with 1 error:
error: ${text}`);
      let errors = [{id: "", pluginName: "", text, location: null, notes: [], detail: void 0}];
      error.errors = errors;
      error.warnings = [];
      return error;
    };
    let validateBuildSyncOptions = (options) => {
      if (!options)
        return;
      let plugins = options.plugins;
      if (plugins && plugins.length > 0)
        throw fakeBuildError(`Cannot use plugins in synchronous API calls`);
    };
    let applyProperties = (object, properties) => {
      for (let key in properties) {
        object[key] = properties[key];
      }
    };
    let runCallSync = (command, args) => {
      let id = nextID++;
      let sharedBuffer = new SharedArrayBuffer(8);
      let sharedBufferView = new Int32Array(sharedBuffer);
      let msg = {sharedBuffer, id, command, args};
      worker.postMessage(msg);
      let status = Atomics.wait(sharedBufferView, 0, 0);
      if (status !== "ok" && status !== "not-equal")
        throw new Error("Internal error: Atomics.wait() failed: " + status);
      let {message: {id: id2, resolve: resolve2, reject, properties}} = worker_threads2.receiveMessageOnPort(mainPort);
      if (id !== id2)
        throw new Error(`Internal error: Expected id ${id} but got id ${id2}`);
      if (reject) {
        applyProperties(reject, properties);
        throw reject;
      }
      return resolve2;
    };
    worker.unref();
    return {
      buildSync(options) {
        validateBuildSyncOptions(options);
        return runCallSync("build", [options]);
      },
      transformSync(input, options) {
        return runCallSync("transform", [input, options]);
      },
      formatMessagesSync(messages, options) {
        return runCallSync("formatMessages", [messages, options]);
      },
      analyzeMetafileSync(metafile, options) {
        return runCallSync("analyzeMetafile", [metafile, options]);
      },
      stop() {
        worker.terminate();
        workerThreadService = null;
      }
    };
  };
  var startSyncServiceWorker = () => {
    let workerPort = worker_threads.workerData.workerPort;
    let parentPort = worker_threads.parentPort;
    let extractProperties = (object) => {
      let properties = {};
      if (object && typeof object === "object") {
        for (let key in object) {
          properties[key] = object[key];
        }
      }
      return properties;
    };
    try {
      let service = ensureServiceIsRunning();
      defaultWD = worker_threads.workerData.defaultWD;
      parentPort.on("message", (msg) => {
        (async () => {
          let {sharedBuffer, id, command, args} = msg;
          let sharedBufferView = new Int32Array(sharedBuffer);
          try {
            switch (command) {
              case "build":
                workerPort.postMessage({id, resolve: await service.build(args[0])});
                break;
              case "transform":
                workerPort.postMessage({id, resolve: await service.transform(args[0], args[1])});
                break;
              case "formatMessages":
                workerPort.postMessage({id, resolve: await service.formatMessages(args[0], args[1])});
                break;
              case "analyzeMetafile":
                workerPort.postMessage({id, resolve: await service.analyzeMetafile(args[0], args[1])});
                break;
              default:
                throw new Error(`Invalid command: ${command}`);
            }
          } catch (reject) {
            workerPort.postMessage({id, reject, properties: extractProperties(reject)});
          }
          Atomics.add(sharedBufferView, 0, 1);
          Atomics.notify(sharedBufferView, 0, Infinity);
        })();
      });
    } catch (reject) {
      parentPort.on("message", (msg) => {
        let {sharedBuffer, id} = msg;
        let sharedBufferView = new Int32Array(sharedBuffer);
        workerPort.postMessage({id, reject, properties: extractProperties(reject)});
        Atomics.add(sharedBufferView, 0, 1);
        Atomics.notify(sharedBufferView, 0, Infinity);
      });
    }
  };
  if (isInternalWorkerThread) {
    startSyncServiceWorker();
  }
  var node_default = node_exports;
});
var __pika_web_default_export_for_treeshaking__ = /* @__PURE__ */ getDefaultExportFromCjs(main);
var analyzeMetafile = main.analyzeMetafile;
var analyzeMetafileSync = main.analyzeMetafileSync;
var build = main.build;
var buildSync = main.buildSync;
var context = main.context;
export default __pika_web_default_export_for_treeshaking__;
var formatMessages = main.formatMessages;
var formatMessagesSync = main.formatMessagesSync;
var initialize = main.initialize;
var stop = main.stop;
var transform = main.transform;
var transformSync = main.transformSync;
var version$1 = main.version;
export {main as __moduleExports, analyzeMetafile, analyzeMetafileSync, build, buildSync, context, formatMessages, formatMessagesSync, initialize, stop, transform, transformSync, version$1 as version};
