UNPKG

@xata.io/client

Version:

Xata.io SDK for TypeScript and JavaScript

5,611 lines • 191 kB
const defaultTrace = async (name, fn, _options) => {
  return await fn({
    name,
    setAttributes: () => {
      return;
    }
  });
};
const TraceAttributes = {
  KIND: "xata.trace.kind",
  VERSION: "xata.sdk.version",
  TABLE: "xata.table",
  HTTP_REQUEST_ID: "http.request_id",
  HTTP_STATUS_CODE: "http.status_code",
  HTTP_HOST: "http.host",
  HTTP_SCHEME: "http.scheme",
  HTTP_USER_AGENT: "http.user_agent",
  HTTP_METHOD: "http.method",
  HTTP_URL: "http.url",
  HTTP_ROUTE: "http.route",
  HTTP_TARGET: "http.target",
  CLOUDFLARE_RAY_ID: "cf.ray"
};

const lookup = [];
const revLookup = [];
const code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
for (let 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 getLens(b64) {
  const len = b64.length;
  if (len % 4 > 0) {
    throw new Error("Invalid string. Length must be a multiple of 4");
  }
  let validLen = b64.indexOf("=");
  if (validLen === -1) validLen = len;
  const placeHoldersLen = validLen === len ? 0 : 4 - validLen % 4;
  return [validLen, placeHoldersLen];
}
function _byteLength(_b64, validLen, placeHoldersLen) {
  return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
}
function toByteArray(b64) {
  let tmp;
  const lens = getLens(b64);
  const validLen = lens[0];
  const placeHoldersLen = lens[1];
  const arr = new Uint8Array(_byteLength(b64, validLen, placeHoldersLen));
  let curByte = 0;
  const len = placeHoldersLen > 0 ? validLen - 4 : validLen;
  let i;
  for (i = 0; i < len; i += 4) {
    tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)];
    arr[curByte++] = tmp >> 16 & 255;
    arr[curByte++] = tmp >> 8 & 255;
    arr[curByte++] = tmp & 255;
  }
  if (placeHoldersLen === 2) {
    tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4;
    arr[curByte++] = tmp & 255;
  }
  if (placeHoldersLen === 1) {
    tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2;
    arr[curByte++] = tmp >> 8 & 255;
    arr[curByte++] = 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) {
  let tmp;
  const output = [];
  for (let i = start; i < end; i += 3) {
    tmp = (uint8[i] << 16 & 16711680) + (uint8[i + 1] << 8 & 65280) + (uint8[i + 2] & 255);
    output.push(tripletToBase64(tmp));
  }
  return output.join("");
}
function fromByteArray(uint8) {
  let tmp;
  const len = uint8.length;
  const extraBytes = len % 3;
  const parts = [];
  const maxChunkLength = 16383;
  for (let 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];
    parts.push(lookup[tmp >> 2] + lookup[tmp << 4 & 63] + "==");
  } else if (extraBytes === 2) {
    tmp = (uint8[len - 2] << 8) + uint8[len - 1];
    parts.push(lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + "=");
  }
  return parts.join("");
}

const K_MAX_LENGTH = 2147483647;
const MAX_ARGUMENTS_LENGTH = 4096;
class Buffer extends Uint8Array {
  /**
   * Constructs a new `Buffer` instance.
   *
   * @param value
   * @param encodingOrOffset
   * @param length
   */
  constructor(value, encodingOrOffset, length) {
    if (typeof value === "number") {
      if (typeof encodingOrOffset === "string") {
        throw new TypeError("The first argument must be of type string, received type number");
      }
      if (value < 0) {
        throw new RangeError("The buffer size cannot be negative");
      }
      super(value < 0 ? 0 : Buffer._checked(value) | 0);
    } else if (typeof value === "string") {
      if (typeof encodingOrOffset !== "string") {
        encodingOrOffset = "utf8";
      }
      if (!Buffer.isEncoding(encodingOrOffset)) {
        throw new TypeError("Unknown encoding: " + encodingOrOffset);
      }
      const length2 = Buffer.byteLength(value, encodingOrOffset) | 0;
      super(length2);
      const written = this.write(value, 0, this.length, encodingOrOffset);
      if (written !== length2) {
        throw new TypeError(
          "Number of bytes written did not match expected length (wrote " + written + ", expected " + length2 + ")"
        );
      }
    } else if (ArrayBuffer.isView(value)) {
      if (Buffer._isInstance(value, Uint8Array)) {
        const copy = new Uint8Array(value);
        const array = copy.buffer;
        const byteOffset = copy.byteOffset;
        const length2 = copy.byteLength;
        if (byteOffset < 0 || array.byteLength < byteOffset) {
          throw new RangeError("offset is outside of buffer bounds");
        }
        if (array.byteLength < byteOffset + (length2 || 0)) {
          throw new RangeError("length is outside of buffer bounds");
        }
        super(new Uint8Array(array, byteOffset, length2));
      } else {
        const array = value;
        const length2 = array.length < 0 ? 0 : Buffer._checked(array.length) | 0;
        super(new Uint8Array(length2));
        for (let i = 0; i < length2; i++) {
          this[i] = array[i] & 255;
        }
      }
    } else if (value == null) {
      throw new TypeError(
        "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value
      );
    } else if (Buffer._isInstance(value, ArrayBuffer) || value && Buffer._isInstance(value.buffer, ArrayBuffer)) {
      const array = value;
      const byteOffset = encodingOrOffset;
      if (byteOffset < 0 || array.byteLength < byteOffset) {
        throw new RangeError("offset is outside of buffer bounds");
      }
      if (array.byteLength < byteOffset + (length || 0)) {
        throw new RangeError("length is outside of buffer bounds");
      }
      super(new Uint8Array(array, byteOffset, length));
    } else if (Array.isArray(value)) {
      const array = value;
      const length2 = array.length < 0 ? 0 : Buffer._checked(array.length) | 0;
      super(new Uint8Array(length2));
      for (let i = 0; i < length2; i++) {
        this[i] = array[i] & 255;
      }
    } else {
      throw new TypeError("Unable to determine the correct way to allocate buffer for type " + typeof value);
    }
  }
  /**
   * Return JSON representation of the buffer.
   */
  toJSON() {
    return {
      type: "Buffer",
      data: Array.prototype.slice.call(this)
    };
  }
  /**
   * Writes `string` to the buffer at `offset` according to the character encoding in `encoding`. The `length`
   * parameter is the number of bytes to write. If the buffer does not contain enough space to fit the entire string,
   * only part of `string` will be written. However, partially encoded characters will not be written.
   *
   * @param string String to write to `buf`.
   * @param offset Number of bytes to skip before starting to write `string`. Default: `0`.
   * @param length Maximum number of bytes to write: Default: `buf.length - offset`.
   * @param encoding The character encoding of `string`. Default: `utf8`.
   */
  write(string, offset, length, encoding) {
    if (typeof offset === "undefined") {
      encoding = "utf8";
      length = this.length;
      offset = 0;
    } else if (typeof length === "undefined" && typeof offset === "string") {
      encoding = offset;
      length = this.length;
      offset = 0;
    } else if (typeof offset === "number" && isFinite(offset)) {
      offset = offset >>> 0;
      if (typeof length === "number" && isFinite(length)) {
        length = length >>> 0;
        encoding ?? (encoding = "utf8");
      } else if (typeof length === "string") {
        encoding = length;
        length = void 0;
      }
    } else {
      throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");
    }
    const remaining = this.length - offset;
    if (typeof length === "undefined" || length > remaining) {
      length = remaining;
    }
    if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) {
      throw new RangeError("Attempt to write outside buffer bounds");
    }
    encoding || (encoding = "utf8");
    switch (Buffer._getEncoding(encoding)) {
      case "hex":
        return Buffer._hexWrite(this, string, offset, length);
      case "utf8":
        return Buffer._utf8Write(this, string, offset, length);
      case "ascii":
      case "latin1":
      case "binary":
        return Buffer._asciiWrite(this, string, offset, length);
      case "ucs2":
      case "utf16le":
        return Buffer._ucs2Write(this, string, offset, length);
      case "base64":
        return Buffer._base64Write(this, string, offset, length);
    }
  }
  /**
   * Decodes the buffer to a string according to the specified character encoding.
   * Passing `start` and `end` will decode only a subset of the buffer.
   *
   * Note that if the encoding is `utf8` and a byte sequence in the input is not valid UTF-8, then each invalid byte
   * will be replaced with `U+FFFD`.
   *
   * @param encoding
   * @param start
   * @param end
   */
  toString(encoding, start, end) {
    const length = this.length;
    if (length === 0) {
      return "";
    }
    if (arguments.length === 0) {
      return Buffer._utf8Slice(this, 0, length);
    }
    if (typeof start === "undefined" || start < 0) {
      start = 0;
    }
    if (start > this.length) {
      return "";
    }
    if (typeof end === "undefined" || end > this.length) {
      end = this.length;
    }
    if (end <= 0) {
      return "";
    }
    end >>>= 0;
    start >>>= 0;
    if (end <= start) {
      return "";
    }
    if (!encoding) {
      encoding = "utf8";
    }
    switch (Buffer._getEncoding(encoding)) {
      case "hex":
        return Buffer._hexSlice(this, start, end);
      case "utf8":
        return Buffer._utf8Slice(this, start, end);
      case "ascii":
        return Buffer._asciiSlice(this, start, end);
      case "latin1":
      case "binary":
        return Buffer._latin1Slice(this, start, end);
      case "ucs2":
      case "utf16le":
        return Buffer._utf16leSlice(this, start, end);
      case "base64":
        return Buffer._base64Slice(this, start, end);
    }
  }
  /**
   * Returns true if this buffer's is equal to the provided buffer, meaning they share the same exact data.
   *
   * @param otherBuffer
   */
  equals(otherBuffer) {
    if (!Buffer.isBuffer(otherBuffer)) {
      throw new TypeError("Argument must be a Buffer");
    }
    if (this === otherBuffer) {
      return true;
    }
    return Buffer.compare(this, otherBuffer) === 0;
  }
  /**
   * Compares the buffer with `otherBuffer` and returns a number indicating whether the buffer comes before, after,
   * or is the same as `otherBuffer` in sort order. Comparison is based on the actual sequence of bytes in each
   * buffer.
   *
   * - `0` is returned if `otherBuffer` is the same as this buffer.
   * - `1` is returned if `otherBuffer` should come before this buffer when sorted.
   * - `-1` is returned if `otherBuffer` should come after this buffer when sorted.
   *
   * @param otherBuffer The buffer to compare to.
   * @param targetStart The offset within `otherBuffer` at which to begin comparison.
   * @param targetEnd The offset within `otherBuffer` at which to end comparison (exclusive).
   * @param sourceStart The offset within this buffer at which to begin comparison.
   * @param sourceEnd The offset within this buffer at which to end the comparison (exclusive).
   */
  compare(otherBuffer, targetStart, targetEnd, sourceStart, sourceEnd) {
    if (Buffer._isInstance(otherBuffer, Uint8Array)) {
      otherBuffer = Buffer.from(otherBuffer, otherBuffer.byteOffset, otherBuffer.byteLength);
    }
    if (!Buffer.isBuffer(otherBuffer)) {
      throw new TypeError("Argument must be a Buffer or Uint8Array");
    }
    targetStart ?? (targetStart = 0);
    targetEnd ?? (targetEnd = otherBuffer ? otherBuffer.length : 0);
    sourceStart ?? (sourceStart = 0);
    sourceEnd ?? (sourceEnd = this.length);
    if (targetStart < 0 || targetEnd > otherBuffer.length || sourceStart < 0 || sourceEnd > this.length) {
      throw new RangeError("Out of range index");
    }
    if (sourceStart >= sourceEnd && targetStart >= targetEnd) {
      return 0;
    }
    if (sourceStart >= sourceEnd) {
      return -1;
    }
    if (targetStart >= targetEnd) {
      return 1;
    }
    targetStart >>>= 0;
    targetEnd >>>= 0;
    sourceStart >>>= 0;
    sourceEnd >>>= 0;
    if (this === otherBuffer) {
      return 0;
    }
    let x = sourceEnd - sourceStart;
    let y = targetEnd - targetStart;
    const len = Math.min(x, y);
    const thisCopy = this.slice(sourceStart, sourceEnd);
    const targetCopy = otherBuffer.slice(targetStart, targetEnd);
    for (let 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;
  }
  /**
   * Copies data from a region of this buffer to a region in `targetBuffer`, even if the `targetBuffer` memory
   * region overlaps with this buffer.
   *
   * @param targetBuffer The target buffer to copy into.
   * @param targetStart The offset within `targetBuffer` at which to begin writing.
   * @param sourceStart The offset within this buffer at which to begin copying.
   * @param sourceEnd The offset within this buffer at which to end copying (exclusive).
   */
  copy(targetBuffer, targetStart, sourceStart, sourceEnd) {
    if (!Buffer.isBuffer(targetBuffer)) throw new TypeError("argument should be a Buffer");
    if (!sourceStart) sourceStart = 0;
    if (!targetStart) targetStart = 0;
    if (!sourceEnd && sourceEnd !== 0) sourceEnd = this.length;
    if (targetStart >= targetBuffer.length) targetStart = targetBuffer.length;
    if (!targetStart) targetStart = 0;
    if (sourceEnd > 0 && sourceEnd < sourceStart) sourceEnd = sourceStart;
    if (sourceEnd === sourceStart) return 0;
    if (targetBuffer.length === 0 || this.length === 0) return 0;
    if (targetStart < 0) {
      throw new RangeError("targetStart out of bounds");
    }
    if (sourceStart < 0 || sourceStart >= this.length) throw new RangeError("Index out of range");
    if (sourceEnd < 0) throw new RangeError("sourceEnd out of bounds");
    if (sourceEnd > this.length) sourceEnd = this.length;
    if (targetBuffer.length - targetStart < sourceEnd - sourceStart) {
      sourceEnd = targetBuffer.length - targetStart + sourceStart;
    }
    const len = sourceEnd - sourceStart;
    if (this === targetBuffer && typeof Uint8Array.prototype.copyWithin === "function") {
      this.copyWithin(targetStart, sourceStart, sourceEnd);
    } else {
      Uint8Array.prototype.set.call(targetBuffer, this.subarray(sourceStart, sourceEnd), targetStart);
    }
    return len;
  }
  /**
   * Returns a new `Buffer` that references the same memory as the original, but offset and cropped by the `start`
   * and `end` indices. This is the same behavior as `buf.subarray()`.
   *
   * This method is not compatible with the `Uint8Array.prototype.slice()`, which is a superclass of Buffer. To copy
   * the slice, use `Uint8Array.prototype.slice()`.
   *
   * @param start
   * @param end
   */
  slice(start, end) {
    if (!start) {
      start = 0;
    }
    const len = this.length;
    start = ~~start;
    end = end === void 0 ? len : ~~end;
    if (start < 0) {
      start += len;
      if (start < 0) {
        start = 0;
      }
    } else if (start > len) {
      start = len;
    }
    if (end < 0) {
      end += len;
      if (end < 0) {
        end = 0;
      }
    } else if (end > len) {
      end = len;
    }
    if (end < start) {
      end = start;
    }
    const newBuf = this.subarray(start, end);
    Object.setPrototypeOf(newBuf, Buffer.prototype);
    return newBuf;
  }
  /**
   * Writes `byteLength` bytes of `value` to `buf` at the specified `offset` as little-endian. Supports up to 48 bits
   * of accuracy. Behavior is undefined when value is anything other than an unsigned integer.
   *
   * @param value Number to write.
   * @param offset Number of bytes to skip before starting to write.
   * @param byteLength Number of bytes to write, between 0 and 6.
   * @param noAssert
   * @returns `offset` plus the number of bytes written.
   */
  writeUIntLE(value, offset, byteLength, noAssert) {
    value = +value;
    offset = offset >>> 0;
    byteLength = byteLength >>> 0;
    if (!noAssert) {
      const maxBytes = Math.pow(2, 8 * byteLength) - 1;
      Buffer._checkInt(this, value, offset, byteLength, maxBytes, 0);
    }
    let mul = 1;
    let i = 0;
    this[offset] = value & 255;
    while (++i < byteLength && (mul *= 256)) {
      this[offset + i] = value / mul & 255;
    }
    return offset + byteLength;
  }
  /**
   * Writes `byteLength` bytes of `value` to `buf` at the specified `offset` as big-endian. Supports up to 48 bits of
   * accuracy. Behavior is undefined when `value` is anything other than an unsigned integer.
   *
   * @param value Number to write.
   * @param offset Number of bytes to skip before starting to write.
   * @param byteLength Number of bytes to write, between 0 and 6.
   * @param noAssert
   * @returns `offset` plus the number of bytes written.
   */
  writeUIntBE(value, offset, byteLength, noAssert) {
    value = +value;
    offset = offset >>> 0;
    byteLength = byteLength >>> 0;
    if (!noAssert) {
      const maxBytes = Math.pow(2, 8 * byteLength) - 1;
      Buffer._checkInt(this, value, offset, byteLength, maxBytes, 0);
    }
    let i = byteLength - 1;
    let mul = 1;
    this[offset + i] = value & 255;
    while (--i >= 0 && (mul *= 256)) {
      this[offset + i] = value / mul & 255;
    }
    return offset + byteLength;
  }
  /**
   * Writes `byteLength` bytes of `value` to `buf` at the specified `offset` as little-endian. Supports up to 48 bits
   * of accuracy. Behavior is undefined when `value` is anything other than a signed integer.
   *
   * @param value Number to write.
   * @param offset Number of bytes to skip before starting to write.
   * @param byteLength Number of bytes to write, between 0 and 6.
   * @param noAssert
   * @returns `offset` plus the number of bytes written.
   */
  writeIntLE(value, offset, byteLength, noAssert) {
    value = +value;
    offset = offset >>> 0;
    if (!noAssert) {
      const limit = Math.pow(2, 8 * byteLength - 1);
      Buffer._checkInt(this, value, offset, byteLength, limit - 1, -limit);
    }
    let i = 0;
    let mul = 1;
    let sub = 0;
    this[offset] = value & 255;
    while (++i < byteLength && (mul *= 256)) {
      if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
        sub = 1;
      }
      this[offset + i] = (value / mul >> 0) - sub & 255;
    }
    return offset + byteLength;
  }
  /**
   * Writes `byteLength` bytes of `value` to `buf` at the specified `offset` as big-endian. Supports up to 48 bits
   * of accuracy. Behavior is undefined when `value` is anything other than a signed integer.
   *
   * @param value Number to write.
   * @param offset Number of bytes to skip before starting to write.
   * @param byteLength Number of bytes to write, between 0 and 6.
   * @param noAssert
   * @returns `offset` plus the number of bytes written.
   */
  writeIntBE(value, offset, byteLength, noAssert) {
    value = +value;
    offset = offset >>> 0;
    if (!noAssert) {
      const limit = Math.pow(2, 8 * byteLength - 1);
      Buffer._checkInt(this, value, offset, byteLength, limit - 1, -limit);
    }
    let i = byteLength - 1;
    let mul = 1;
    let 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 + byteLength;
  }
  /**
   * Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result as an
   * unsigned, little-endian integer supporting up to 48 bits of accuracy.
   *
   * @param offset Number of bytes to skip before starting to read.
   * @param byteLength Number of bytes to read, between 0 and 6.
   * @param noAssert
   */
  readUIntLE(offset, byteLength, noAssert) {
    offset = offset >>> 0;
    byteLength = byteLength >>> 0;
    if (!noAssert) {
      Buffer._checkOffset(offset, byteLength, this.length);
    }
    let val = this[offset];
    let mul = 1;
    let i = 0;
    while (++i < byteLength && (mul *= 256)) {
      val += this[offset + i] * mul;
    }
    return val;
  }
  /**
   * Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result as an
   * unsigned, big-endian integer supporting up to 48 bits of accuracy.
   *
   * @param offset Number of bytes to skip before starting to read.
   * @param byteLength Number of bytes to read, between 0 and 6.
   * @param noAssert
   */
  readUIntBE(offset, byteLength, noAssert) {
    offset = offset >>> 0;
    byteLength = byteLength >>> 0;
    if (!noAssert) {
      Buffer._checkOffset(offset, byteLength, this.length);
    }
    let val = this[offset + --byteLength];
    let mul = 1;
    while (byteLength > 0 && (mul *= 256)) {
      val += this[offset + --byteLength] * mul;
    }
    return val;
  }
  /**
   * Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result as a
   * little-endian, two's complement signed value supporting up to 48 bits of accuracy.
   *
   * @param offset Number of bytes to skip before starting to read.
   * @param byteLength Number of bytes to read, between 0 and 6.
   * @param noAssert
   */
  readIntLE(offset, byteLength, noAssert) {
    offset = offset >>> 0;
    byteLength = byteLength >>> 0;
    if (!noAssert) {
      Buffer._checkOffset(offset, byteLength, this.length);
    }
    let val = this[offset];
    let mul = 1;
    let i = 0;
    while (++i < byteLength && (mul *= 256)) {
      val += this[offset + i] * mul;
    }
    mul *= 128;
    if (val >= mul) {
      val -= Math.pow(2, 8 * byteLength);
    }
    return val;
  }
  /**
   * Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result as a
   * big-endian, two's complement signed value supporting up to 48 bits of accuracy.
   *
   * @param offset Number of bytes to skip before starting to read.
   * @param byteLength Number of bytes to read, between 0 and 6.
   * @param noAssert
   */
  readIntBE(offset, byteLength, noAssert) {
    offset = offset >>> 0;
    byteLength = byteLength >>> 0;
    if (!noAssert) {
      Buffer._checkOffset(offset, byteLength, this.length);
    }
    let i = byteLength;
    let mul = 1;
    let val = this[offset + --i];
    while (i > 0 && (mul *= 256)) {
      val += this[offset + --i] * mul;
    }
    mul *= 128;
    if (val >= mul) {
      val -= Math.pow(2, 8 * byteLength);
    }
    return val;
  }
  /**
   * Reads an unsigned 8-bit integer from `buf` at the specified `offset`.
   *
   * @param offset Number of bytes to skip before starting to read.
   * @param noAssert
   */
  readUInt8(offset, noAssert) {
    offset = offset >>> 0;
    if (!noAssert) {
      Buffer._checkOffset(offset, 1, this.length);
    }
    return this[offset];
  }
  /**
   * Reads an unsigned, little-endian 16-bit integer from `buf` at the specified `offset`.
   *
   * @param offset Number of bytes to skip before starting to read.
   * @param noAssert
   */
  readUInt16LE(offset, noAssert) {
    offset = offset >>> 0;
    if (!noAssert) {
      Buffer._checkOffset(offset, 2, this.length);
    }
    return this[offset] | this[offset + 1] << 8;
  }
  /**
   * Reads an unsigned, big-endian 16-bit integer from `buf` at the specified `offset`.
   *
   * @param offset Number of bytes to skip before starting to read.
   * @param noAssert
   */
  readUInt16BE(offset, noAssert) {
    offset = offset >>> 0;
    if (!noAssert) {
      Buffer._checkOffset(offset, 2, this.length);
    }
    return this[offset] << 8 | this[offset + 1];
  }
  /**
   * Reads an unsigned, little-endian 32-bit integer from `buf` at the specified `offset`.
   *
   * @param offset Number of bytes to skip before starting to read.
   * @param noAssert
   */
  readUInt32LE(offset, noAssert) {
    offset = offset >>> 0;
    if (!noAssert) {
      Buffer._checkOffset(offset, 4, this.length);
    }
    return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 16777216;
  }
  /**
   * Reads an unsigned, big-endian 32-bit integer from `buf` at the specified `offset`.
   *
   * @param offset Number of bytes to skip before starting to read.
   * @param noAssert
   */
  readUInt32BE(offset, noAssert) {
    offset = offset >>> 0;
    if (!noAssert) {
      Buffer._checkOffset(offset, 4, this.length);
    }
    return this[offset] * 16777216 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]);
  }
  /**
   * Reads a signed 8-bit integer from `buf` at the specified `offset`. Integers read from a `Buffer` are interpreted
   * as two's complement signed values.
   *
   * @param offset Number of bytes to skip before starting to read.
   * @param noAssert
   */
  readInt8(offset, noAssert) {
    offset = offset >>> 0;
    if (!noAssert) {
      Buffer._checkOffset(offset, 1, this.length);
    }
    if (!(this[offset] & 128)) {
      return this[offset];
    }
    return (255 - this[offset] + 1) * -1;
  }
  /**
   * Reads a signed, little-endian 16-bit integer from `buf` at the specified `offset`. Integers read from a `Buffer`
   * are interpreted as two's complement signed values.
   *
   * @param offset Number of bytes to skip before starting to read.
   * @param noAssert
   */
  readInt16LE(offset, noAssert) {
    offset = offset >>> 0;
    if (!noAssert) {
      Buffer._checkOffset(offset, 2, this.length);
    }
    const val = this[offset] | this[offset + 1] << 8;
    return val & 32768 ? val | 4294901760 : val;
  }
  /**
   * Reads a signed, big-endian 16-bit integer from `buf` at the specified `offset`. Integers read from a `Buffer`
   * are interpreted as two's complement signed values.
   *
   * @param offset Number of bytes to skip before starting to read.
   * @param noAssert
   */
  readInt16BE(offset, noAssert) {
    offset = offset >>> 0;
    if (!noAssert) {
      Buffer._checkOffset(offset, 2, this.length);
    }
    const val = this[offset + 1] | this[offset] << 8;
    return val & 32768 ? val | 4294901760 : val;
  }
  /**
   * Reads a signed, little-endian 32-bit integer from `buf` at the specified `offset`. Integers read from a `Buffer`
   * are interpreted as two's complement signed values.
   *
   * @param offset Number of bytes to skip before starting to read.
   * @param noAssert
   */
  readInt32LE(offset, noAssert) {
    offset = offset >>> 0;
    if (!noAssert) {
      Buffer._checkOffset(offset, 4, this.length);
    }
    return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24;
  }
  /**
   * Reads a signed, big-endian 32-bit integer from `buf` at the specified `offset`. Integers read from a `Buffer`
   * are interpreted as two's complement signed values.
   *
   * @param offset Number of bytes to skip before starting to read.
   * @param noAssert
   */
  readInt32BE(offset, noAssert) {
    offset = offset >>> 0;
    if (!noAssert) {
      Buffer._checkOffset(offset, 4, this.length);
    }
    return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3];
  }
  /**
   * Interprets `buf` as an array of unsigned 16-bit integers and swaps the byte order in-place.
   * Throws a `RangeError` if `buf.length` is not a multiple of 2.
   */
  swap16() {
    const len = this.length;
    if (len % 2 !== 0) {
      throw new RangeError("Buffer size must be a multiple of 16-bits");
    }
    for (let i = 0; i < len; i += 2) {
      this._swap(this, i, i + 1);
    }
    return this;
  }
  /**
   * Interprets `buf` as an array of unsigned 32-bit integers and swaps the byte order in-place.
   * Throws a `RangeError` if `buf.length` is not a multiple of 4.
   */
  swap32() {
    const len = this.length;
    if (len % 4 !== 0) {
      throw new RangeError("Buffer size must be a multiple of 32-bits");
    }
    for (let i = 0; i < len; i += 4) {
      this._swap(this, i, i + 3);
      this._swap(this, i + 1, i + 2);
    }
    return this;
  }
  /**
   * Interprets `buf` as an array of unsigned 64-bit integers and swaps the byte order in-place.
   * Throws a `RangeError` if `buf.length` is not a multiple of 8.
   */
  swap64() {
    const len = this.length;
    if (len % 8 !== 0) {
      throw new RangeError("Buffer size must be a multiple of 64-bits");
    }
    for (let i = 0; i < len; i += 8) {
      this._swap(this, i, i + 7);
      this._swap(this, i + 1, i + 6);
      this._swap(this, i + 2, i + 5);
      this._swap(this, i + 3, i + 4);
    }
    return this;
  }
  /**
   * Swaps two octets.
   *
   * @param b
   * @param n
   * @param m
   */
  _swap(b, n, m) {
    const i = b[n];
    b[n] = b[m];
    b[m] = i;
  }
  /**
   * Writes `value` to `buf` at the specified `offset`. The `value` must be a valid unsigned 8-bit integer.
   * Behavior is undefined when `value` is anything other than an unsigned 8-bit integer.
   *
   * @param value Number to write.
   * @param offset Number of bytes to skip before starting to write.
   * @param noAssert
   * @returns `offset` plus the number of bytes written.
   */
  writeUInt8(value, offset, noAssert) {
    value = +value;
    offset = offset >>> 0;
    if (!noAssert) {
      Buffer._checkInt(this, value, offset, 1, 255, 0);
    }
    this[offset] = value & 255;
    return offset + 1;
  }
  /**
   * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid unsigned 16-bit
   * integer. Behavior is undefined when `value` is anything other than an unsigned 16-bit integer.
   *
   * @param value Number to write.
   * @param offset Number of bytes to skip before starting to write.
   * @param noAssert
   * @returns `offset` plus the number of bytes written.
   */
  writeUInt16LE(value, offset, noAssert) {
    value = +value;
    offset = offset >>> 0;
    if (!noAssert) {
      Buffer._checkInt(this, value, offset, 2, 65535, 0);
    }
    this[offset] = value & 255;
    this[offset + 1] = value >>> 8;
    return offset + 2;
  }
  /**
   * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid unsigned 16-bit
   * integer. Behavior is undefined when `value` is anything other than an unsigned 16-bit integer.
   *
   * @param value Number to write.
   * @param offset Number of bytes to skip before starting to write.
   * @param noAssert
   * @returns `offset` plus the number of bytes written.
   */
  writeUInt16BE(value, offset, noAssert) {
    value = +value;
    offset = offset >>> 0;
    if (!noAssert) {
      Buffer._checkInt(this, value, offset, 2, 65535, 0);
    }
    this[offset] = value >>> 8;
    this[offset + 1] = value & 255;
    return offset + 2;
  }
  /**
   * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid unsigned 32-bit
   * integer. Behavior is undefined when `value` is anything other than an unsigned 32-bit integer.
   *
   * @param value Number to write.
   * @param offset Number of bytes to skip before starting to write.
   * @param noAssert
   * @returns `offset` plus the number of bytes written.
   */
  writeUInt32LE(value, offset, noAssert) {
    value = +value;
    offset = offset >>> 0;
    if (!noAssert) {
      Buffer._checkInt(this, value, offset, 4, 4294967295, 0);
    }
    this[offset + 3] = value >>> 24;
    this[offset + 2] = value >>> 16;
    this[offset + 1] = value >>> 8;
    this[offset] = value & 255;
    return offset + 4;
  }
  /**
   * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid unsigned 32-bit
   * integer. Behavior is undefined when `value` is anything other than an unsigned 32-bit integer.
   *
   * @param value Number to write.
   * @param offset Number of bytes to skip before starting to write.
   * @param noAssert
   * @returns `offset` plus the number of bytes written.
   */
  writeUInt32BE(value, offset, noAssert) {
    value = +value;
    offset = offset >>> 0;
    if (!noAssert) {
      Buffer._checkInt(this, value, offset, 4, 4294967295, 0);
    }
    this[offset] = value >>> 24;
    this[offset + 1] = value >>> 16;
    this[offset + 2] = value >>> 8;
    this[offset + 3] = value & 255;
    return offset + 4;
  }
  /**
   * Writes `value` to `buf` at the specified `offset`. The `value` must be a valid signed 8-bit integer.
   * Behavior is undefined when `value` is anything other than a signed 8-bit integer.
   *
   * @param value Number to write.
   * @param offset Number of bytes to skip before starting to write.
   * @param noAssert
   * @returns `offset` plus the number of bytes written.
   */
  writeInt8(value, offset, noAssert) {
    value = +value;
    offset = offset >>> 0;
    if (!noAssert) {
      Buffer._checkInt(this, value, offset, 1, 127, -128);
    }
    if (value < 0) {
      value = 255 + value + 1;
    }
    this[offset] = value & 255;
    return offset + 1;
  }
  /**
   * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid signed 16-bit
   * integer. Behavior is undefined when `value` is anything other than a signed 16-bit integer.
   *
   * @param value Number to write.
   * @param offset Number of bytes to skip before starting to write.
   * @param noAssert
   * @returns `offset` plus the number of bytes written.
   */
  writeInt16LE(value, offset, noAssert) {
    value = +value;
    offset = offset >>> 0;
    if (!noAssert) {
      Buffer._checkInt(this, value, offset, 2, 32767, -32768);
    }
    this[offset] = value & 255;
    this[offset + 1] = value >>> 8;
    return offset + 2;
  }
  /**
   * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid signed 16-bit
   * integer. Behavior is undefined when `value` is anything other than a signed 16-bit integer.
   *
   * @param value Number to write.
   * @param offset Number of bytes to skip before starting to write.
   * @param noAssert
   * @returns `offset` plus the number of bytes written.
   */
  writeInt16BE(value, offset, noAssert) {
    value = +value;
    offset = offset >>> 0;
    if (!noAssert) {
      Buffer._checkInt(this, value, offset, 2, 32767, -32768);
    }
    this[offset] = value >>> 8;
    this[offset + 1] = value & 255;
    return offset + 2;
  }
  /**
   * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid signed 32-bit
   * integer. Behavior is undefined when `value` is anything other than a signed 32-bit integer.
   *
   * @param value Number to write.
   * @param offset Number of bytes to skip before starting to write.
   * @param noAssert
   * @returns `offset` plus the number of bytes written.
   */
  writeInt32LE(value, offset, noAssert) {
    value = +value;
    offset = offset >>> 0;
    if (!noAssert) {
      Buffer._checkInt(this, value, offset, 4, 2147483647, -2147483648);
    }
    this[offset] = value & 255;
    this[offset + 1] = value >>> 8;
    this[offset + 2] = value >>> 16;
    this[offset + 3] = value >>> 24;
    return offset + 4;
  }
  /**
   * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid signed 32-bit
   * integer. Behavior is undefined when `value` is anything other than a signed 32-bit integer.
   *
   * @param value Number to write.
   * @param offset Number of bytes to skip before starting to write.
   * @param noAssert
   * @returns `offset` plus the number of bytes written.
   */
  writeInt32BE(value, offset, noAssert) {
    value = +value;
    offset = offset >>> 0;
    if (!noAssert) {
      Buffer._checkInt(this, value, offset, 4, 2147483647, -2147483648);
    }
    if (value < 0) {
      value = 4294967295 + value + 1;
    }
    this[offset] = value >>> 24;
    this[offset + 1] = value >>> 16;
    this[offset + 2] = value >>> 8;
    this[offset + 3] = value & 255;
    return offset + 4;
  }
  /**
   * Fills `buf` with the specified `value`. If the `offset` and `end` are not given, the entire `buf` will be
   * filled. The `value` is coerced to a `uint32` value if it is not a string, `Buffer`, or integer. If the resulting
   * integer is greater than `255` (decimal), then `buf` will be filled with `value & 255`.
   *
   * If the final write of a `fill()` operation falls on a multi-byte character, then only the bytes of that
   * character that fit into `buf` are written.
   *
   * If `value` contains invalid characters, it is truncated; if no valid fill data remains, an exception is thrown.
   *
   * @param value
   * @param encoding
   */
  fill(value, offset, end, encoding) {
    if (typeof value === "string") {
      if (typeof offset === "string") {
        encoding = offset;
        offset = 0;
        end = this.length;
      } else if (typeof end === "string") {
        encoding = end;
        end = this.length;
      }
      if (encoding !== void 0 && typeof encoding !== "string") {
        throw new TypeError("encoding must be a string");
      }
      if (typeof encoding === "string" && !Buffer.isEncoding(encoding)) {
        throw new TypeError("Unknown encoding: " + encoding);
      }
      if (value.length === 1) {
        const code = value.charCodeAt(0);
        if (encoding === "utf8" && code < 128) {
          value = code;
        }
      }
    } else if (typeof value === "number") {
      value = value & 255;
    } else if (typeof value === "boolean") {
      value = Number(value);
    }
    offset ?? (offset = 0);
    end ?? (end = this.length);
    if (offset < 0 || this.length < offset || this.length < end) {
      throw new RangeError("Out of range index");
    }
    if (end <= offset) {
      return this;
    }
    offset = offset >>> 0;
    end = end === void 0 ? this.length : end >>> 0;
    value || (value = 0);
    let i;
    if (typeof value === "number") {
      for (i = offset; i < end; ++i) {
        this[i] = value;
      }
    } else {
      const bytes = Buffer.isBuffer(value) ? value : Buffer.from(value, encoding);
      const len = bytes.length;
      if (len === 0) {
        throw new TypeError('The value "' + value + '" is invalid for argument "value"');
      }
      for (i = 0; i < end - offset; ++i) {
        this[i + offset] = bytes[i % len];
      }
    }
    return this;
  }
  /**
   * Returns the index of the specified value.
   *
   * If `value` is:
   * - a string, `value` is interpreted according to the character encoding in `encoding`.
   * - a `Buffer` or `Uint8Array`, `value` will be used in its entirety. To compare a partial Buffer, use `slice()`.
   * - a number, `value` will be interpreted as an unsigned 8-bit integer value between `0` and `255`.
   *
   * Any other types will throw a `TypeError`.
   *
   * @param value What to search for.
   * @param byteOffset Where to begin searching in `buf`. If negative, then calculated from the end.
   * @param encoding If `value` is a string, this is the encoding used to search.
   * @returns The index of the first occurrence of `value` in `buf`, or `-1` if not found.
   */
  indexOf(value, byteOffset, encoding) {
    return this._bidirectionalIndexOf(this, value, byteOffset, encoding, true);
  }
  /**
   * Gets the last index of the specified value.
   *
   * @see indexOf()
   * @param value
   * @param byteOffset
   * @param encoding
   */
  lastIndexOf(value, byteOffset, encoding) {
    return this._bidirectionalIndexOf(this, value, byteOffset, encoding, false);
  }
  _bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) {
    if (buffer.length === 0) {
      return -1;
    }
    if (typeof byteOffset === "string") {
      encoding = byteOffset;
      byteOffset = 0;
    } else if (typeof byteOffset === "undefined") {
      byteOffset = 0;
    } else if (byteOffset > 2147483647) {
      byteOffset = 2147483647;
    } else if (byteOffset < -2147483648) {
      byteOffset = -2147483648;
    }
    byteOffset = +byteOffset;
    if (byteOffset !== 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 (Buffer.isBuffer(val)) {
      if (val.length === 0) {
        return -1;
      }
      return Buffer._arrayIndexOf(buffer, val, byteOffset, encoding, dir);
    } else if (typeof val === "number") {
      val = val & 255;
      if (typeof Uint8Array.prototype.indexOf === "function") {
        if (dir) {
          return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset);
        } else {
          return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset);
        }
      }
      return Buffer._arrayIndexOf(buffer, Buffer.from([val]), byteOffset, encoding, dir);
    }
    throw new TypeError("val must be string, number or Buffer");
  }
  /**
   * Equivalent to `buf.indexOf() !== -1`.
   *
   * @param value
   * @param byteOffset
   * @param encoding
   */
  includes(value, byteOffset, encoding) {
    return this.indexOf(value, byteOffset, encoding) !== -1;
  }
  /**
   * Creates a new buffer from the given parameters.
   *
   * @param data
   * @param encoding
   */
  static from(a, b, c) {
    return new Buffer(a, b, c);
  }
  /**
   * Returns true if `obj` is a Buffer.
   *
   * @param obj
   */
  static isBuffer(obj) {
    return obj != null && obj !== Buffer.prototype && Buffer._isInstance(obj, Buffer);
  }
  /**
   * Returns true if `encoding` is a supported encoding.
   *
   * @param encoding
   */
  static isEncoding(encoding) {
    switch (encoding.toLowerCase()) {
      case "hex":
      case "utf8":
      case "ascii":
      case "binary":
      case "latin1":
      case "ucs2":
      case "utf16le":
      case "base64":
        return true;
      default:
        return false;
    }
  }
  /**
   * Gives the actual byte length of a string for an encoding. This is not the same as `string.length` since that
   * returns the number of characters in the string.
   *
   * @param string The string to test.
   * @param encoding The encoding to use for calculation. Defaults is `utf8`.
   */
  static byteLength(string, encoding) {
    if (Buffer.isBuffer(string)) {
      return string.length;
    }
    if (typeof string !== "string" && (ArrayBuffer.isView(string) || Buffer._isInstance(string, ArrayBuffer))) {
      return string.byteLength;
    }
    if (typeof string !== "string") {
      throw new TypeError(
        'The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof string
      );
    }
    const len = string.length;
    const mustMatch = arguments.length > 2 && arguments[2] === true;
    if (!mustMatch && len === 0) {
      return 0;
    }
    switch (encoding?.toLowerCase()) {
      case "ascii":
      case "latin1":
      case "binary":
        return len;
      case "utf8":
        return Buffer._utf8ToBytes(string).length;
      case "hex":
        return len >>> 1;
      case "ucs2":
      case "utf16le":
        return len * 2;
      case "base64":
        return Buffer._base64ToBytes(string).length;
      default:
        return mustMatch ? -1 : Buffer._utf8ToBytes(string).length;
    }
  }
  /**
   * Returns a Buffer which is the result of concatenating all the buffers in the list together.
   *
   * - If the list has no items, or if the `totalLength` is 0, then it returns a zero-length buffer.
   * - If the list has exactly one item, then the first item is returned.
   * - If the list has more than one item, then a new buffer is created.
   *
   * It is faster to provide the `totalLength` if it is known. However, it will be calculated if not provided at
   * a small computational expense.
   *
   * @param list An array of Buffer objects to concatenate.
   * @param totalLength Total length of the buffers when concatenated.
   */
  static concat(list, totalLength) {
    if (!Array.isArray(list)) {
      throw new TypeError('"list" argument must be an Array of Buffers');
    }
    if (list.length === 0) {
      return Buffer.alloc(0);
    }
    let i;
    if (totalLength === void 0) {
      totalLength = 0;
      for (i = 0; i < list.length; ++i) {
        totalLength += list[i].length;
      }
    }
    const buffer = Buffer.allocUnsafe(totalLength);
    let pos = 0;
    for (i = 0; i < list.length; ++i) {
      let buf = list[i];
      if (Buffer._isInstance(buf, Uint8Array)) {
        if (pos + buf.length > buffer.length) {
          if (!Buffer.isBuffer(buf)) {
            buf = Buffer.from(buf);
          }
          buf.copy(buffer, pos);
        } else {
          Uint8Array.prototype.set.call(buffer, buf, pos);
        }
      } else if (!Buffer.isBuffer(buf)) {
        throw new TypeError('"list" argument must be an Array of Buffers');
      } else {
        buf.copy(buffer, pos);
      }
      pos += buf.length;
    }
    return buffer;
  }
  /**
   * The same as `buf1.compare(buf2)`.
   */
  static compare(buf1, buf2) {
    if (Buffer._isInstance(buf1, Uint8Array)) {
      buf1 = Buffer.from(buf1, buf1.byteOffset, buf1.byteLength);
    }
    if (Buffer._isInstance(buf2, Uint8Array)) {
      buf2 = Buffer.from(buf2, buf2.byteOffset, buf2.byteLength);
    }
    if (!Buffer.isBuffer(buf1) || !Buffer.isBuffer(buf2)) {
      throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');
    }
    if (buf1 === buf2) {
      return 0;
    }
    let x = buf1.length;
    let y = buf2.length;
    for (let i = 0, len = Math.min(x, y); i < len; ++i) {
      if (buf1[i] !== buf2[i]) {
        x = buf1[i];
        y = buf2[i];
        break;
      }
    }
    if (x < y) {
      return -1;
    }
    if (y < x) {
      return 1;
    }
    return 0;
  }
  /**
   * Allocates a new buffer of `size` octets.
   *
   * @param size The number of octets to allocate.
   * @param fill If specified, the buffer will be initialized by calling `buf.fill(fill)`, or with zeroes otherwise.
   * @param encoding The encoding used for the call to `buf.fill()` while initializing.
   */
  static alloc(size, fill, encoding) {
    if (typeof size !== "number") {
      throw new TypeError('"size" argument must be of type number');
    } else if (size < 0) {
      throw new RangeError('The value "' + size + '" is invalid for option "size"');
    }
    if (size <= 0) {
      return new Buffer(size);
    }
    if (fill !== void 0) {
      return typeof encoding === "string" ? new Buffer(size).fill(fill, 0, size, encoding) : new Buffer(size).fill(fill);
    }
    return new Buffer(size);
  }
  /**
   * Allocates a new buffer of `size` octets without initializing memory. The contents of the buffer are unknown.
   *
   * @param size
   */
  static allocUnsafe(size) {
    if (typeof size !== "number") {
      throw new TypeError('"size" argument must be of type number');
    } else if (size < 0) {
      throw new RangeError('The value "' + size + '" is invalid for option "size"');
    }
    return new Buffer(size < 0 ? 0 : Buffer._checked(size) | 0);
  }
  /**
   * Returns true if the given `obj` is an instance of `type`.
   *
   * @param obj
   * @param type
   */
  static _isInstance(obj, type) {
    return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name;
  }
  static _checked(length) {
    if (length >= K_MAX_LENGTH) {
      throw new RangeError(
        "Attempt to allocate Buffer larger than maximum size: 0x" + K_MAX_LENGTH.toString(16) + " bytes"
      );
    }
    return length | 0;
  }
  static _blitBuffer(src, dst, offset, length) {
    let i;
    for (i = 0; i < length; ++i) {
      if (i + offset >= dst.length || i >= src.length) {
        break;
      }
      dst[i + offset] = src[i];
    }
    return i;
  }
  static _utf8Write(buf, string, offset, length) {
    return Buffer._blitBuffer(Buffer._utf8ToBytes(string, buf.length - offset), buf, offset, length);
  }
  static _asciiWrite(buf, string, offset, length) {
    return Buffer._blitBuffer(Buffer._asciiToBytes(string), buf, offset, length);
  }
  static _base64Write(buf, string, offset, length) {
    return Buffer._blitBuffer(Buffer._base64ToBytes(string), buf, offset, length);
  }
  static _ucs2Write(buf, string, offset, length) {
    return Buffer._blitBuffer(Buffer._utf16leToBytes(string, buf.length - offset), buf, offset, length);
  }
  static _hexWrite(buf, string, offset, length) {
    offset = Number(offset) || 0;
    const remaining = buf.length - offset;
    if (!length) {
      length = remaining;
    } else {
      length = Number(length);
      if (length > remaining) {
        length = remaining;
      }
    }
    const strLen = string.length;
    if (length > strLen / 2) {
      length = strLen / 2;
    }
    let i;
    for (i = 0; i < length; ++i) {
      const parsed = parseInt(string.substr(i * 2, 2), 16);
      if (parsed !== parsed) {
        return i;
      }
      buf[offset + i] = parsed;
    }
    return i;
  }
  static _utf8ToBytes(string, units) {
    units = units || Infinity;
    const length = string.length;
    const bytes = [];
    let codePoint;
    let leadSurrogate = null;
    for (let 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;
  }
  static _base64ToBytes(str) {
    return toByteArray(base64clean(str));
  }
  static _asciiToBytes(str) {
    const byteArray = [];
    for (let i = 0; i < str.length; ++i) {
      byteArray.push(str.charCodeAt(i) & 255);
    }
    return byteArray;
  }
  static _utf16leToBytes(str, units) {
    let c, hi, lo;
    const byteArray = [];
    for (let 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;
  }
  static _hexSlice(buf, start, end) {
    const len = buf.length;
    if (!start || start < 0) {
      start = 0;
    }
    if (!end || end < 0 || end > len) {
      end = len;
    }
    let out = "";
    for (let i = start; i < end; ++i) {
      out += hexSliceLookupTable[buf[i]];
    }
    return out;
  }
  static _base64Slice(buf, start, end) {
    if (start === 0 && end === buf.length) {
      return fromByteArray(buf);
    } else {
      return fromByteArray(buf.slice(start, end));
    }
  }
  static _utf8Slice(buf, start, end) {
    end = Math.min(buf.length, end);
    const res = [];
    let i = start;
    while (i < end) {
      const firstByte = buf[i];
      let codePoint = null;
      let bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1;
      if (i + bytesPerSequence <= end) {
        let 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 Buffer._decodeCodePointsArray(res);
  }
  static _decodeCodePointsArray(codePoints) {
    const len = codePoints.length;
    if (len <= MAX_ARGUMENTS_LENGTH) {
      return String.fromCharCode.apply(String, codePoints);
    }
    let res = "";
    let i = 0;
    while (i < len) {
      res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH));
    }
    return res;
  }
  static _asciiSlice(buf, start, end) {
    let ret = "";
    end = Math.min(buf.length, end);
    for (let i = start; i < end; ++i) {
      ret += String.fromCharCode(buf[i] & 127);
    }
    return ret;
  }
  static _latin1Slice(buf, start, end) {
    let ret = "";
    end = Math.min(buf.length, end);
    for (let i = start; i < end; ++i) {
      ret += String.fromCharCode(buf[i]);
    }
    return ret;
  }
  static _utf16leSlice(buf, start, end) {
    const bytes = buf.slice(start, end);
    let res = "";
    for (let i = 0; i < bytes.length - 1; i += 2) {
      res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
    }
    return res;
  }
  static _arrayIndexOf(arr, val, byteOffset, encoding, dir) {
    let indexSize = 1;
    let arrLength = arr.length;
    let valLength = val.length;
    if (encoding !== void 0) {
      encoding = Buffer._getEncoding(encoding);
      if (encoding === "ucs2" || encoding === "utf16le") {
        if (arr.length < 2 || val.length < 2) {
          return -1;
        }
        indexSize = 2;
        arrLength /= 2;
        valLength /= 2;
        byteOffset /= 2;
      }
    }
    function read(buf, i2) {
      if (indexSize === 1) {
        return buf[i2];
      } else {
        return buf.readUInt16BE(i2 * indexSize);
      }
    }
    let i;
    if (dir) {
      let foundIndex = -1;
      for (i = byteOffset; i < arrLength; i++) {
        if (read(arr, i) === read(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--) {
        let found = true;
        for (let j = 0; j < valLength; j++) {
          if (read(arr, i + j) !== read(val, j)) {
            found = false;
            break;
          }
        }
        if (found) {
          return i;
        }
      }
    }
    return -1;
  }
  static _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");
  }
  static _checkInt(buf, value, offset, ext, max, min) {
    if (!Buffer.isBuffer(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");
  }
  static _getEncoding(encoding) {
    let toLowerCase = false;
    let originalEncoding = "";
    for (; ; ) {
      switch (encoding) {
        case "hex":
          return "hex";
        case "utf8":
          return "utf8";
        case "ascii":
          return "ascii";
        case "binary":
          return "binary";
        case "latin1":
          return "latin1";
        case "ucs2":
          return "ucs2";
        case "utf16le":
          return "utf16le";
        case "base64":
          return "base64";
        default: {
          if (toLowerCase) {
            throw new TypeError("Unknown or unsupported encoding: " + originalEncoding);
          }
          toLowerCase = true;
          originalEncoding = encoding;
          encoding = encoding.toLowerCase();
        }
      }
    }
  }
}
const hexSliceLookupTable = function() {
  const alphabet = "0123456789abcdef";
  const table = new Array(256);
  for (let i = 0; i < 16; ++i) {
    const i16 = i * 16;
    for (let j = 0; j < 16; ++j) {
      table[i16 + j] = alphabet[i] + alphabet[j];
    }
  }
  return table;
}();
const INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g;
function base64clean(str) {
  str = str.split("=")[0];
  str = str.trim().replace(INVALID_BASE64_RE, "");
  if (str.length < 2) return "";
  while (str.length % 4 !== 0) {
    str = str + "=";
  }
  return str;
}

function notEmpty(value) {
  return value !== null && value !== void 0;
}
function compact(arr) {
  return arr.filter(notEmpty);
}
function compactObject(obj) {
  return Object.fromEntries(Object.entries(obj).filter(([, value]) => notEmpty(value)));
}
function isBlob(value) {
  try {
    return value instanceof Blob;
  } catch (error) {
    return false;
  }
}
function isObject(value) {
  return Boolean(value) && typeof value === "object" && !Array.isArray(value) && !(value instanceof Date) && !isBlob(value);
}
function isDefined(value) {
  return value !== null && value !== void 0;
}
function isString(value) {
  return isDefined(value) && typeof value === "string";
}
function isStringArray(value) {
  return isDefined(value) && Array.isArray(value) && value.every(isString);
}
function isNumber(value) {
  return isDefined(value) && typeof value === "number";
}
function parseNumber(value) {
  if (isNumber(value)) {
    return value;
  }
  if (isString(value)) {
    const parsed = Number(value);
    if (!Number.isNaN(parsed)) {
      return parsed;
    }
  }
  return void 0;
}
function toBase64(value) {
  try {
    return btoa(value);
  } catch (err) {
    const buf = Buffer;
    return buf.from(value).toString("base64");
  }
}
function deepMerge(a, b) {
  const result = { ...a };
  for (const [key, value] of Object.entries(b)) {
    if (isObject(value) && isObject(result[key])) {
      result[key] = deepMerge(result[key], value);
    } else {
      result[key] = value;
    }
  }
  return result;
}
function chunk(array, chunkSize) {
  const result = [];
  for (let i = 0; i < array.length; i += chunkSize) {
    result.push(array.slice(i, i + chunkSize));
  }
  return result;
}
async function timeout(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}
function timeoutWithCancel(ms) {
  let timeoutId;
  const promise = new Promise((resolve) => {
    timeoutId = setTimeout(() => {
      resolve();
    }, ms);
  });
  return {
    cancel: () => clearTimeout(timeoutId),
    promise
  };
}
function promiseMap(inputValues, mapper) {
  const reducer = (acc$, inputValue) => acc$.then(
    (acc) => mapper(inputValue).then((result) => {
      acc.push(result);
      return acc;
    })
  );
  return inputValues.reduce(reducer, Promise.resolve([]));
}

function getEnvironment() {
  try {
    if (isDefined(process) && isDefined(process.env)) {
      return {
        apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
        databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
        branch: process.env.XATA_BRANCH ?? getGlobalBranch(),
        deployPreview: process.env.XATA_PREVIEW,
        deployPreviewBranch: process.env.XATA_PREVIEW_BRANCH,
        vercelGitCommitRef: process.env.VERCEL_GIT_COMMIT_REF,
        vercelGitRepoOwner: process.env.VERCEL_GIT_REPO_OWNER
      };
    }
  } catch (err) {
  }
  try {
    if (isObject(Deno) && isObject(Deno.env)) {
      return {
        apiKey: Deno.env.get("XATA_API_KEY") ?? getGlobalApiKey(),
        databaseURL: Deno.env.get("XATA_DATABASE_URL") ?? getGlobalDatabaseURL(),
        branch: Deno.env.get("XATA_BRANCH") ?? getGlobalBranch(),
        deployPreview: Deno.env.get("XATA_PREVIEW"),
        deployPreviewBranch: Deno.env.get("XATA_PREVIEW_BRANCH"),
        vercelGitCommitRef: Deno.env.get("VERCEL_GIT_COMMIT_REF"),
        vercelGitRepoOwner: Deno.env.get("VERCEL_GIT_REPO_OWNER")
      };
    }
  } catch (err) {
  }
  return {
    apiKey: getGlobalApiKey(),
    databaseURL: getGlobalDatabaseURL(),
    branch: getGlobalBranch(),
    deployPreview: void 0,
    deployPreviewBranch: void 0,
    vercelGitCommitRef: void 0,
    vercelGitRepoOwner: void 0
  };
}
function getEnableBrowserVariable() {
  try {
    if (isObject(process) && isObject(process.env) && process.env.XATA_ENABLE_BROWSER !== void 0) {
      return process.env.XATA_ENABLE_BROWSER === "true";
    }
  } catch (err) {
  }
  try {
    if (isObject(Deno) && isObject(Deno.env) && Deno.env.get("XATA_ENABLE_BROWSER") !== void 0) {
      return Deno.env.get("XATA_ENABLE_BROWSER") === "true";
    }
  } catch (err) {
  }
  try {
    return XATA_ENABLE_BROWSER === true || XATA_ENABLE_BROWSER === "true";
  } catch (err) {
    return void 0;
  }
}
function getGlobalApiKey() {
  try {
    return XATA_API_KEY;
  } catch (err) {
    return void 0;
  }
}
function getGlobalDatabaseURL() {
  try {
    return XATA_DATABASE_URL;
  } catch (err) {
    return void 0;
  }
}
function getGlobalBranch() {
  try {
    return XATA_BRANCH;
  } catch (err) {
    return void 0;
  }
}
function getDatabaseURL() {
  try {
    const { databaseURL } = getEnvironment();
    return databaseURL;
  } catch (err) {
    return void 0;
  }
}
function getAPIKey() {
  try {
    const { apiKey } = getEnvironment();
    return apiKey;
  } catch (err) {
    return void 0;
  }
}
function getBranch() {
  try {
    const { branch } = getEnvironment();
    return branch;
  } catch (err) {
    return void 0;
  }
}
function buildPreviewBranchName({ org, branch }) {
  return `preview-${org}-${branch}`;
}
function getPreviewBranch() {
  try {
    const { deployPreview, deployPreviewBranch, vercelGitCommitRef, vercelGitRepoOwner } = getEnvironment();
    if (deployPreviewBranch) return deployPreviewBranch;
    switch (deployPreview) {
      case "vercel": {
        if (!vercelGitCommitRef || !vercelGitRepoOwner) {
          console.warn("XATA_PREVIEW=vercel but VERCEL_GIT_COMMIT_REF or VERCEL_GIT_REPO_OWNER is not valid");
          return void 0;
        }
        return buildPreviewBranchName({ org: vercelGitRepoOwner, branch: vercelGitCommitRef });
      }
    }
    return void 0;
  } catch (err) {
    return void 0;
  }
}

var __typeError$7 = (msg) => {
  throw TypeError(msg);
};
var __accessCheck$7 = (obj, member, msg) => member.has(obj) || __typeError$7("Cannot " + msg);
var __privateGet$6 = (obj, member, getter) => (__accessCheck$7(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd$7 = (obj, member, value) => member.has(obj) ? __typeError$7("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateSet$5 = (obj, member, value, setter) => (__accessCheck$7(obj, member, "write to private field"), member.set(obj, value), value);
var __privateMethod$4 = (obj, member, method) => (__accessCheck$7(obj, member, "access private method"), method);
var _fetch, _queue, _concurrency, _ApiRequestPool_instances, enqueue_fn;
const REQUEST_TIMEOUT = 5 * 60 * 1e3;
function getFetchImplementation(userFetch) {
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
  const globalThisFetch = typeof globalThis !== "undefined" ? globalThis.fetch : void 0;
  const fetchImpl = userFetch ?? globalFetch ?? globalThisFetch;
  if (!fetchImpl) {
    throw new Error(`Couldn't find a global \`fetch\`. Pass a fetch implementation explicitly.`);
  }
  return fetchImpl;
}
class ApiRequestPool {
  constructor(concurrency = 10) {
    __privateAdd$7(this, _ApiRequestPool_instances);
    __privateAdd$7(this, _fetch);
    __privateAdd$7(this, _queue);
    __privateAdd$7(this, _concurrency);
    __privateSet$5(this, _queue, []);
    __privateSet$5(this, _concurrency, concurrency);
    this.running = 0;
    this.started = 0;
  }
  setFetch(fetch2) {
    __privateSet$5(this, _fetch, fetch2);
  }
  getFetch() {
    if (!__privateGet$6(this, _fetch)) {
      throw new Error("Fetch not set");
    }
    return __privateGet$6(this, _fetch);
  }
  request(url, options) {
    const start = /* @__PURE__ */ new Date();
    const fetchImpl = this.getFetch();
    const runRequest = async (stalled = false) => {
      const { promise, cancel } = timeoutWithCancel(REQUEST_TIMEOUT);
      const response = await Promise.race([fetchImpl(url, options), promise.then(() => null)]).finally(cancel);
      if (!response) {
        throw new Error("Request timed out");
      }
      if (response.status === 429) {
        const rateLimitReset = parseNumber(response.headers?.get("x-ratelimit-reset")) ?? 1;
        await timeout(rateLimitReset * 1e3);
        return await runRequest(true);
      }
      if (stalled) {
        const stalledTime = (/* @__PURE__ */ new Date()).getTime() - start.getTime();
        console.warn(`A request to Xata hit branch rate limits, was retried and stalled for ${stalledTime}ms`);
      }
      return response;
    };
    return __privateMethod$4(this, _ApiRequestPool_instances, enqueue_fn).call(this, async () => {
      return await runRequest();
    });
  }
}
_fetch = new WeakMap();
_queue = new WeakMap();
_concurrency = new WeakMap();
_ApiRequestPool_instances = new WeakSet();
enqueue_fn = function(task) {
  const promise = new Promise((resolve) => __privateGet$6(this, _queue).push(resolve)).finally(() => {
    this.started--;
    this.running++;
  }).then(() => task()).finally(() => {
    this.running--;
    const next = __privateGet$6(this, _queue).shift();
    if (next !== void 0) {
      this.started++;
      next();
    }
  });
  if (this.running + this.started < __privateGet$6(this, _concurrency)) {
    const next = __privateGet$6(this, _queue).shift();
    if (next !== void 0) {
      this.started++;
      next();
    }
  }
  return promise;
};

function generateUUID() {
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
    const r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8;
    return v.toString(16);
  });
}

async function getBytes(stream, onChunk) {
  const reader = stream.getReader();
  let result;
  while (!(result = await reader.read()).done) {
    onChunk(result.value);
  }
}
function getLines(onLine) {
  let buffer;
  let position;
  let fieldLength;
  let discardTrailingNewline = false;
  return function onChunk(arr) {
    if (buffer === void 0) {
      buffer = arr;
      position = 0;
      fieldLength = -1;
    } else {
      buffer = concat(buffer, arr);
    }
    const bufLength = buffer.length;
    let lineStart = 0;
    while (position < bufLength) {
      if (discardTrailingNewline) {
        if (buffer[position] === 10 /* NewLine */) {
          lineStart = ++position;
        }
        discardTrailingNewline = false;
      }
      let lineEnd = -1;
      for (; position < bufLength && lineEnd === -1; ++position) {
        switch (buffer[position]) {
          case 58 /* Colon */:
            if (fieldLength === -1) {
              fieldLength = position - lineStart;
            }
            break;
          // @ts-ignore:7029 \r case below should fallthrough to \n:
          case 13 /* CarriageReturn */:
            discardTrailingNewline = true;
          case 10 /* NewLine */:
            lineEnd = position;
            break;
        }
      }
      if (lineEnd === -1) {
        break;
      }
      onLine(buffer.subarray(lineStart, lineEnd), fieldLength);
      lineStart = position;
      fieldLength = -1;
    }
    if (lineStart === bufLength) {
      buffer = void 0;
    } else if (lineStart !== 0) {
      buffer = buffer.subarray(lineStart);
      position -= lineStart;
    }
  };
}
function getMessages(onId, onRetry, onMessage) {
  let message = newMessage();
  const decoder = new TextDecoder();
  return function onLine(line, fieldLength) {
    if (line.length === 0) {
      onMessage?.(message);
      message = newMessage();
    } else if (fieldLength > 0) {
      const field = decoder.decode(line.subarray(0, fieldLength));
      const valueOffset = fieldLength + (line[fieldLength + 1] === 32 /* Space */ ? 2 : 1);
      const value = decoder.decode(line.subarray(valueOffset));
      switch (field) {
        case "data":
          message.data = message.data ? message.data + "\n" + value : value;
          break;
        case "event":
          message.event = value;
          break;
        case "id":
          onId(message.id = value);
          break;
        case "retry":
          const retry = parseInt(value, 10);
          if (!isNaN(retry)) {
            onRetry(message.retry = retry);
          }
          break;
      }
    }
  };
}
function concat(a, b) {
  const res = new Uint8Array(a.length + b.length);
  res.set(a);
  res.set(b, a.length);
  return res;
}
function newMessage() {
  return {
    data: "",
    event: "",
    id: "",
    retry: void 0
  };
}
const EventStreamContentType = "text/event-stream";
const LastEventId = "last-event-id";
function fetchEventSource(input, {
  signal: inputSignal,
  headers: inputHeaders,
  onopen: inputOnOpen,
  onmessage,
  onclose,
  onerror,
  fetch: inputFetch,
  ...rest
}) {
  return new Promise((resolve, reject) => {
    const headers = { ...inputHeaders };
    if (!headers.accept) {
      headers.accept = EventStreamContentType;
    }
    let curRequestController;
    function dispose() {
      curRequestController.abort();
    }
    inputSignal?.addEventListener("abort", () => {
      dispose();
      resolve();
    });
    const fetchImpl = inputFetch ?? fetch;
    const onopen = inputOnOpen ?? defaultOnOpen;
    async function create() {
      curRequestController = new AbortController();
      try {
        const response = await fetchImpl(input, {
          ...rest,
          headers,
          signal: curRequestController.signal
        });
        await onopen(response);
        await getBytes(
          response.body,
          getLines(
            getMessages(
              (id) => {
                if (id) {
                  headers[LastEventId] = id;
                } else {
                  delete headers[LastEventId];
                }
              },
              (_retry) => {
              },
              onmessage
            )
          )
        );
        onclose?.();
        dispose();
        resolve();
      } catch (err) {
      }
    }
    create();
  });
}
function defaultOnOpen(response) {
  const contentType = response.headers?.get("content-type");
  if (!contentType?.startsWith(EventStreamContentType)) {
    throw new Error(`Expected content-type to be ${EventStreamContentType}, Actual: ${contentType}`);
  }
}

const VERSION = "0.30.1";

class ErrorWithCause extends Error {
  constructor(message, options) {
    super(message, options);
  }
}
class FetcherError extends ErrorWithCause {
  constructor(status, data, requestId) {
    super(getMessage(data));
    this.status = status;
    this.errors = isBulkError(data) ? data.errors : [{ message: getMessage(data), status }];
    this.requestId = requestId;
    if (data instanceof Error) {
      this.stack = data.stack;
      this.cause = data.cause;
    }
  }
  toString() {
    const error = super.toString();
    return `[${this.status}] (${this.requestId ?? "Unknown"}): ${error}`;
  }
}
function isBulkError(error) {
  return isObject(error) && Array.isArray(error.errors);
}
function isErrorWithMessage(error) {
  return isObject(error) && isString(error.message);
}
function getMessage(data) {
  if (data instanceof Error) {
    return data.message;
  } else if (isString(data)) {
    return data;
  } else if (isErrorWithMessage(data)) {
    return data.message;
  } else if (isBulkError(data)) {
    return "Bulk operation failed";
  } else {
    return "Unexpected error";
  }
}

function getHostUrl(provider, type) {
  if (isHostProviderAlias(provider)) {
    return providers[provider][type];
  } else if (isHostProviderBuilder(provider)) {
    return provider[type];
  }
  throw new Error("Invalid API provider");
}
const providers = {
  production: {
    main: "https://api.xata.io",
    workspaces: "https://{workspaceId}.{region}.xata.sh"
  },
  staging: {
    main: "https://api.staging-xata.dev",
    workspaces: "https://{workspaceId}.{region}.staging-xata.dev"
  },
  dev: {
    main: "https://api.dev-xata.dev",
    workspaces: "https://{workspaceId}.{region}.dev-xata.dev"
  },
  local: {
    main: "http://localhost:6001",
    workspaces: "http://{workspaceId}.{region}.localhost:6001"
  }
};
function isHostProviderAlias(alias) {
  return isString(alias) && Object.keys(providers).includes(alias);
}
function isHostProviderBuilder(builder) {
  return isObject(builder) && isString(builder.main) && isString(builder.workspaces);
}
function parseProviderString(provider = "production") {
  if (isHostProviderAlias(provider)) {
    return provider;
  }
  const [main, workspaces] = provider.split(",");
  if (!main || !workspaces) return null;
  return { main, workspaces };
}
function buildProviderString(provider) {
  if (isHostProviderAlias(provider)) return provider;
  return `${provider.main},${provider.workspaces}`;
}
function parseWorkspacesUrlParts(url) {
  if (!isString(url)) return null;
  const matches = {
    production: url.match(/(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.sh\/db\/([^:]+):?(.*)?/),
    staging: url.match(/(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.staging-xata\.dev\/db\/([^:]+):?(.*)?/),
    dev: url.match(/(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.dev-xata\.dev\/db\/([^:]+):?(.*)?/),
    local: url.match(/(?:https?:\/\/)?([^.]+)(?:\.([^.]+))\.localhost:(?:\d+)\/db\/([^:]+):?(.*)?/)
  };
  const [host, match] = Object.entries(matches).find(([, match2]) => match2 !== null) ?? [];
  if (!isHostProviderAlias(host) || !match) return null;
  return { workspace: match[1], region: match[2], database: match[3], branch: match[4], host };
}

const pool = new ApiRequestPool();
const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
  const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
    if (value === void 0 || value === null) return acc;
    return { ...acc, [key]: value };
  }, {});
  const query = new URLSearchParams(cleanQueryParams).toString();
  const queryString = query.length > 0 ? `?${query}` : "";
  const cleanPathParams = Object.entries(pathParams).reduce((acc, [key, value]) => {
    return { ...acc, [key]: encodeURIComponent(String(value ?? "")).replace(/%3A/g, ":") };
  }, {});
  return url.replace(/\{\w*\}/g, (key) => cleanPathParams[key.slice(1, -1)]) + queryString;
};
function buildBaseUrl({
  method,
  endpoint,
  path,
  workspacesApiUrl,
  apiUrl,
  pathParams = {}
}) {
  if (endpoint === "dataPlane") {
    let url = isString(workspacesApiUrl) ? `${workspacesApiUrl}${path}` : workspacesApiUrl(path, pathParams);
    if (method.toUpperCase() === "PUT" && [
      "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
      "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}"
    ].includes(path)) {
      const { host } = parseWorkspacesUrlParts(url) ?? {};
      switch (host) {
        case "production":
          url = url.replace("xata.sh", "upload.xata.sh");
          break;
        case "staging":
          url = url.replace("staging-xata.dev", "upload.staging-xata.dev");
          break;
        case "dev":
          url = url.replace("dev-xata.dev", "upload.dev-xata.dev");
          break;
      }
    }
    const urlWithWorkspace = isString(pathParams.workspace) ? url.replace("{workspaceId}", String(pathParams.workspace)) : url;
    return isString(pathParams.region) ? urlWithWorkspace.replace("{region}", String(pathParams.region)) : urlWithWorkspace;
  }
  return `${apiUrl}${path}`;
}
function hostHeader(url) {
  const pattern = /.*:\/\/(?<host>[^/]+).*/;
  const { groups } = pattern.exec(url) ?? {};
  return groups?.host ? { Host: groups.host } : {};
}
async function parseBody(body, headers) {
  if (!isDefined(body)) return void 0;
  if (isBlob(body) || typeof body.text === "function") {
    return body;
  }
  const { "Content-Type": contentType } = headers ?? {};
  if (String(contentType).toLowerCase() === "application/json" && isObject(body)) {
    return JSON.stringify(body);
  }
  return body;
}
const defaultClientID = generateUUID();
async function fetch$1({
  url: path,
  method,
  body,
  headers: customHeaders,
  pathParams,
  queryParams,
  fetch: fetch2,
  apiKey,
  endpoint,
  apiUrl,
  workspacesApiUrl,
  trace,
  signal,
  clientID,
  sessionID,
  clientName,
  xataAgentExtra,
  fetchOptions = {},
  rawResponse = false
}) {
  pool.setFetch(fetch2);
  return await trace(
    `${method.toUpperCase()} ${path}`,
    async ({ setAttributes }) => {
      const baseUrl = buildBaseUrl({ method, endpoint, path, workspacesApiUrl, pathParams, apiUrl });
      const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
      const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\.[^.]+\./, "http://") : fullUrl;
      setAttributes({
        [TraceAttributes.HTTP_URL]: url,
        [TraceAttributes.HTTP_TARGET]: resolveUrl(path, queryParams, pathParams)
      });
      const xataAgent = compact([
        ["client", "TS_SDK"],
        ["version", VERSION],
        isDefined(clientName) ? ["service", clientName] : void 0,
        ...Object.entries(xataAgentExtra ?? {})
      ]).map(([key, value]) => `${key}=${value}`).join("; ");
      const headers = compactObject({
        "Accept-Encoding": "identity",
        "Content-Type": "application/json",
        "X-Xata-Client-ID": clientID ?? defaultClientID,
        "X-Xata-Session-ID": sessionID ?? generateUUID(),
        "X-Xata-Agent": xataAgent,
        ...customHeaders,
        ...hostHeader(fullUrl),
        Authorization: `Bearer ${apiKey}`
      });
      const response = await pool.request(url, {
        ...fetchOptions,
        method: method.toUpperCase(),
        body: await parseBody(body, headers),
        headers,
        signal
      });
      const { host, protocol } = parseUrl(response.url);
      const requestId = response.headers?.get("x-request-id") ?? void 0;
      setAttributes({
        [TraceAttributes.KIND]: "http",
        [TraceAttributes.HTTP_REQUEST_ID]: requestId,
        [TraceAttributes.HTTP_STATUS_CODE]: response.status,
        [TraceAttributes.HTTP_HOST]: host,
        [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", ""),
        [TraceAttributes.CLOUDFLARE_RAY_ID]: response.headers?.get("cf-ray") ?? void 0
      });
      const message = response.headers?.get("x-xata-message");
      if (message) console.warn(message);
      if (response.status === 204) {
        return {};
      }
      if (response.status === 429) {
        throw new FetcherError(response.status, "Rate limit exceeded", requestId);
      }
      try {
        const jsonResponse = rawResponse ? await response.blob() : await response.json();
        if (response.ok) {
          return jsonResponse;
        }
        throw new FetcherError(response.status, jsonResponse, requestId);
      } catch (error) {
        throw new FetcherError(response.status, error, requestId);
      }
    },
    { [TraceAttributes.HTTP_METHOD]: method.toUpperCase(), [TraceAttributes.HTTP_ROUTE]: path }
  );
}
function fetchSSERequest({
  url: path,
  method,
  body,
  headers: customHeaders,
  pathParams,
  queryParams,
  fetch: fetch2,
  apiKey,
  endpoint,
  apiUrl,
  workspacesApiUrl,
  onMessage,
  onError,
  onClose,
  signal,
  clientID,
  sessionID,
  clientName,
  xataAgentExtra
}) {
  const baseUrl = buildBaseUrl({ method, endpoint, path, workspacesApiUrl, pathParams, apiUrl });
  const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
  const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
  void fetchEventSource(url, {
    method,
    body: JSON.stringify(body),
    fetch: fetch2,
    signal,
    headers: {
      "X-Xata-Client-ID": clientID ?? defaultClientID,
      "X-Xata-Session-ID": sessionID ?? generateUUID(),
      "X-Xata-Agent": compact([
        ["client", "TS_SDK"],
        ["version", VERSION],
        isDefined(clientName) ? ["service", clientName] : void 0,
        ...Object.entries(xataAgentExtra ?? {})
      ]).map(([key, value]) => `${key}=${value}`).join("; "),
      ...customHeaders,
      Authorization: `Bearer ${apiKey}`,
      "Content-Type": "application/json"
    },
    onmessage(ev) {
      onMessage?.(JSON.parse(ev.data));
    },
    onerror(ev) {
      onError?.(JSON.parse(ev.data));
    },
    onclose() {
      onClose?.();
    }
  });
}
function parseUrl(url) {
  try {
    const { host, protocol } = new URL(url);
    return { host, protocol };
  } catch (error) {
    return {};
  }
}

const dataPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "dataPlane" });

const getTasks = (variables, signal) => dataPlaneFetch({
  url: "/tasks",
  method: "get",
  ...variables,
  signal
});
const getTaskStatus = (variables, signal) => dataPlaneFetch({
  url: "/tasks/{taskId}",
  method: "get",
  ...variables,
  signal
});
const listClusterBranches = (variables, signal) => dataPlaneFetch({
  url: "/cluster/{clusterId}/branches",
  method: "get",
  ...variables,
  signal
});
const listClusterExtensions = (variables, signal) => dataPlaneFetch({
  url: "/cluster/{clusterId}/extensions",
  method: "get",
  ...variables,
  signal
});
const installClusterExtension = (variables, signal) => dataPlaneFetch({
  url: "/cluster/{clusterId}/extensions",
  method: "post",
  ...variables,
  signal
});
const dropClusterExtension = (variables, signal) => dataPlaneFetch({
  url: "/cluster/{clusterId}/extensions",
  method: "delete",
  ...variables,
  signal
});
const getClusterMetrics = (variables, signal) => dataPlaneFetch({
  url: "/cluster/{clusterId}/metrics",
  method: "get",
  ...variables,
  signal
});
const applyMigration = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/migrations/apply",
  method: "post",
  ...variables,
  signal
});
const startMigration = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/migrations/start",
  method: "post",
  ...variables,
  signal
});
const completeMigration = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/migrations/complete",
  method: "post",
  ...variables,
  signal
});
const rollbackMigration = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/migrations/rollback",
  method: "post",
  ...variables,
  signal
});
const adaptTable = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/migrations/adapt/{tableName}",
  method: "post",
  ...variables,
  signal
});
const adaptAllTables = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/migrations/adapt",
  method: "post",
  ...variables,
  signal
});
const getBranchMigrationJobStatus = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/migrations/status",
  method: "get",
  ...variables,
  signal
});
const getMigrationJobs = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/migrations/jobs",
  method: "get",
  ...variables,
  signal
});
const getMigrationJobStatus = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/migrations/jobs/{jobId}",
  method: "get",
  ...variables,
  signal
});
const getMigrationHistory = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/migrations/history",
  method: "get",
  ...variables,
  signal
});
const getBranchList = (variables, signal) => dataPlaneFetch({
  url: "/dbs/{dbName}",
  method: "get",
  ...variables,
  signal
});
const getDatabaseSettings = (variables, signal) => dataPlaneFetch({
  url: "/dbs/{dbName}/settings",
  method: "get",
  ...variables,
  signal
});
const updateDatabaseSettings = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/settings", method: "patch", ...variables, signal });
const createBranchAsync = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/async", method: "put", ...variables, signal });
const getBranchDetails = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}",
  method: "get",
  ...variables,
  signal
});
const createBranch = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}", method: "put", ...variables, signal });
const deleteBranch = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}",
  method: "delete",
  ...variables,
  signal
});
const getSchema = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/schema",
  method: "get",
  ...variables,
  signal
});
const getSchemas = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/schemas",
  method: "get",
  ...variables,
  signal
});
const copyBranch = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/copy",
  method: "post",
  ...variables,
  signal
});
const getBranchMoveStatus = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/move", method: "get", ...variables, signal });
const moveBranch = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/move",
  method: "put",
  ...variables,
  signal
});
const updateBranchMetadata = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/metadata",
  method: "put",
  ...variables,
  signal
});
const getBranchMetadata = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/metadata",
  method: "get",
  ...variables,
  signal
});
const getBranchStats = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/stats",
  method: "get",
  ...variables,
  signal
});
const getGitBranchesMapping = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables, signal });
const addGitBranchesEntry = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables, signal });
const removeGitBranchesEntry = (variables, signal) => dataPlaneFetch({
  url: "/dbs/{dbName}/gitBranches",
  method: "delete",
  ...variables,
  signal
});
const resolveBranch = (variables, signal) => dataPlaneFetch({
  url: "/dbs/{dbName}/resolveBranch",
  method: "get",
  ...variables,
  signal
});
const getBranchMigrationHistory = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/migrations",
  method: "get",
  ...variables,
  signal
});
const getBranchMigrationPlan = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/migrations/plan",
  method: "post",
  ...variables,
  signal
});
const executeBranchMigrationPlan = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/migrations/execute",
  method: "post",
  ...variables,
  signal
});
const queryMigrationRequests = (variables, signal) => dataPlaneFetch({
  url: "/dbs/{dbName}/migrations/query",
  method: "post",
  ...variables,
  signal
});
const createMigrationRequest = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations", method: "post", ...variables, signal });
const getMigrationRequest = (variables, signal) => dataPlaneFetch({
  url: "/dbs/{dbName}/migrations/{mrNumber}",
  method: "get",
  ...variables,
  signal
});
const updateMigrationRequest = (variables, signal) => dataPlaneFetch({
  url: "/dbs/{dbName}/migrations/{mrNumber}",
  method: "patch",
  ...variables,
  signal
});
const listMigrationRequestsCommits = (variables, signal) => dataPlaneFetch({
  url: "/dbs/{dbName}/migrations/{mrNumber}/commits",
  method: "post",
  ...variables,
  signal
});
const compareMigrationRequest = (variables, signal) => dataPlaneFetch({
  url: "/dbs/{dbName}/migrations/{mrNumber}/compare",
  method: "post",
  ...variables,
  signal
});
const getMigrationRequestIsMerged = (variables, signal) => dataPlaneFetch({
  url: "/dbs/{dbName}/migrations/{mrNumber}/merge",
  method: "get",
  ...variables,
  signal
});
const mergeMigrationRequest = (variables, signal) => dataPlaneFetch({
  url: "/dbs/{dbName}/migrations/{mrNumber}/merge",
  method: "post",
  ...variables,
  signal
});
const getBranchSchemaHistory = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/schema/history",
  method: "post",
  ...variables,
  signal
});
const compareBranchWithUserSchema = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/schema/compare",
  method: "post",
  ...variables,
  signal
});
const compareBranchSchemas = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/schema/compare/{branchName}",
  method: "post",
  ...variables,
  signal
});
const updateBranchSchema = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/schema/update",
  method: "post",
  ...variables,
  signal
});
const previewBranchSchemaEdit = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/schema/preview",
  method: "post",
  ...variables,
  signal
});
const applyBranchSchemaEdit = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/schema/apply",
  method: "post",
  ...variables,
  signal
});
const pushBranchMigrations = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/schema/push",
  method: "post",
  ...variables,
  signal
});
const createTable = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/tables/{tableName}",
  method: "put",
  ...variables,
  signal
});
const deleteTable = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/tables/{tableName}",
  method: "delete",
  ...variables,
  signal
});
const updateTable = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/tables/{tableName}",
  method: "patch",
  ...variables,
  signal
});
const getTableSchema = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/tables/{tableName}/schema",
  method: "get",
  ...variables,
  signal
});
const setTableSchema = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/tables/{tableName}/schema",
  method: "put",
  ...variables,
  signal
});
const getTableColumns = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/tables/{tableName}/columns",
  method: "get",
  ...variables,
  signal
});
const addTableColumn = (variables, signal) => dataPlaneFetch(
  {
    url: "/db/{dbBranchName}/tables/{tableName}/columns",
    method: "post",
    ...variables,
    signal
  }
);
const getColumn = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}",
  method: "get",
  ...variables,
  signal
});
const updateColumn = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}",
  method: "patch",
  ...variables,
  signal
});
const deleteColumn = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}",
  method: "delete",
  ...variables,
  signal
});
const branchTransaction = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/transaction",
  method: "post",
  ...variables,
  signal
});
const insertRecord = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/tables/{tableName}/data",
  method: "post",
  ...variables,
  signal
});
const getFileItem = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
  method: "get",
  ...variables,
  signal
});
const putFileItem = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
  method: "put",
  ...variables,
  signal
});
const deleteFileItem = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
  method: "delete",
  ...variables,
  signal
});
const getFile = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
  method: "get",
  ...variables,
  signal
});
const putFile = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
  method: "put",
  ...variables,
  signal
});
const deleteFile = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
  method: "delete",
  ...variables,
  signal
});
const getRecord = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
  method: "get",
  ...variables,
  signal
});
const insertRecordWithID = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
  method: "put",
  ...variables,
  signal
});
const updateRecordWithID = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
  method: "patch",
  ...variables,
  signal
});
const upsertRecordWithID = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
  method: "post",
  ...variables,
  signal
});
const deleteRecord = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
  method: "delete",
  ...variables,
  signal
});
const bulkInsertTableRecords = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/tables/{tableName}/bulk",
  method: "post",
  ...variables,
  signal
});
const queryTable = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/tables/{tableName}/query",
  method: "post",
  ...variables,
  signal
});
const searchBranch = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/search",
  method: "post",
  ...variables,
  signal
});
const searchTable = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/tables/{tableName}/search",
  method: "post",
  ...variables,
  signal
});
const vectorSearchTable = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/tables/{tableName}/vectorSearch",
  method: "post",
  ...variables,
  signal
});
const askTable = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/tables/{tableName}/ask",
  method: "post",
  ...variables,
  signal
});
const askTableSession = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/tables/{tableName}/ask/{sessionId}",
  method: "post",
  ...variables,
  signal
});
const summarizeTable = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/tables/{tableName}/summarize",
  method: "post",
  ...variables,
  signal
});
const aggregateTable = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/tables/{tableName}/aggregate",
  method: "post",
  ...variables,
  signal
});
const fileAccess = (variables, signal) => dataPlaneFetch({
  url: "/file/{fileId}",
  method: "get",
  ...variables,
  signal
});
const fileUpload = (variables, signal) => dataPlaneFetch({
  url: "/file/{fileId}",
  method: "put",
  ...variables,
  signal
});
const sqlQuery = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/sql",
  method: "post",
  ...variables,
  signal
});
const sqlBatchQuery = (variables, signal) => dataPlaneFetch({
  url: "/db/{dbBranchName}/sql/batch",
  method: "post",
  ...variables,
  signal
});
const operationsByTag$2 = {
  tasks: { getTasks, getTaskStatus },
  cluster: {
    listClusterBranches,
    listClusterExtensions,
    installClusterExtension,
    dropClusterExtension,
    getClusterMetrics
  },
  migrations: {
    applyMigration,
    startMigration,
    completeMigration,
    rollbackMigration,
    adaptTable,
    adaptAllTables,
    getBranchMigrationJobStatus,
    getMigrationJobs,
    getMigrationJobStatus,
    getMigrationHistory,
    getSchema,
    getSchemas,
    getBranchMigrationHistory,
    getBranchMigrationPlan,
    executeBranchMigrationPlan,
    getBranchSchemaHistory,
    compareBranchWithUserSchema,
    compareBranchSchemas,
    updateBranchSchema,
    previewBranchSchemaEdit,
    applyBranchSchemaEdit,
    pushBranchMigrations
  },
  branch: {
    getBranchList,
    createBranchAsync,
    getBranchDetails,
    createBranch,
    deleteBranch,
    copyBranch,
    getBranchMoveStatus,
    moveBranch,
    updateBranchMetadata,
    getBranchMetadata,
    getBranchStats,
    getGitBranchesMapping,
    addGitBranchesEntry,
    removeGitBranchesEntry,
    resolveBranch
  },
  database: { getDatabaseSettings, updateDatabaseSettings },
  migrationRequests: {
    queryMigrationRequests,
    createMigrationRequest,
    getMigrationRequest,
    updateMigrationRequest,
    listMigrationRequestsCommits,
    compareMigrationRequest,
    getMigrationRequestIsMerged,
    mergeMigrationRequest
  },
  table: {
    createTable,
    deleteTable,
    updateTable,
    getTableSchema,
    setTableSchema,
    getTableColumns,
    addTableColumn,
    getColumn,
    updateColumn,
    deleteColumn
  },
  records: {
    branchTransaction,
    insertRecord,
    getRecord,
    insertRecordWithID,
    updateRecordWithID,
    upsertRecordWithID,
    deleteRecord,
    bulkInsertTableRecords
  },
  files: {
    getFileItem,
    putFileItem,
    deleteFileItem,
    getFile,
    putFile,
    deleteFile,
    fileAccess,
    fileUpload
  },
  searchAndFilter: {
    queryTable,
    searchBranch,
    searchTable,
    vectorSearchTable,
    askTable,
    askTableSession,
    summarizeTable,
    aggregateTable
  },
  sql: { sqlQuery, sqlBatchQuery }
};

const controlPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "controlPlane" });

const getAuthorizationCode = (variables, signal) => controlPlaneFetch({ url: "/oauth/authorize", method: "get", ...variables, signal });
const grantAuthorizationCode = (variables, signal) => controlPlaneFetch({ url: "/oauth/authorize", method: "post", ...variables, signal });
const getUser = (variables, signal) => controlPlaneFetch({
  url: "/user",
  method: "get",
  ...variables,
  signal
});
const updateUser = (variables, signal) => controlPlaneFetch({
  url: "/user",
  method: "put",
  ...variables,
  signal
});
const deleteUser = (variables, signal) => controlPlaneFetch({
  url: "/user",
  method: "delete",
  ...variables,
  signal
});
const getUserAPIKeys = (variables, signal) => controlPlaneFetch({
  url: "/user/keys",
  method: "get",
  ...variables,
  signal
});
const createUserAPIKey = (variables, signal) => controlPlaneFetch({
  url: "/user/keys/{keyName}",
  method: "post",
  ...variables,
  signal
});
const deleteUserAPIKey = (variables, signal) => controlPlaneFetch({
  url: "/user/keys/{keyName}",
  method: "delete",
  ...variables,
  signal
});
const getUserOAuthClients = (variables, signal) => controlPlaneFetch({
  url: "/user/oauth/clients",
  method: "get",
  ...variables,
  signal
});
const deleteUserOAuthClient = (variables, signal) => controlPlaneFetch({
  url: "/user/oauth/clients/{clientId}",
  method: "delete",
  ...variables,
  signal
});
const getUserOAuthAccessTokens = (variables, signal) => controlPlaneFetch({
  url: "/user/oauth/tokens",
  method: "get",
  ...variables,
  signal
});
const deleteOAuthAccessToken = (variables, signal) => controlPlaneFetch({
  url: "/user/oauth/tokens/{token}",
  method: "delete",
  ...variables,
  signal
});
const updateOAuthAccessToken = (variables, signal) => controlPlaneFetch({
  url: "/user/oauth/tokens/{token}",
  method: "patch",
  ...variables,
  signal
});
const getWorkspacesList = (variables, signal) => controlPlaneFetch({
  url: "/workspaces",
  method: "get",
  ...variables,
  signal
});
const createWorkspace = (variables, signal) => controlPlaneFetch({
  url: "/workspaces",
  method: "post",
  ...variables,
  signal
});
const getWorkspace = (variables, signal) => controlPlaneFetch({
  url: "/workspaces/{workspaceId}",
  method: "get",
  ...variables,
  signal
});
const updateWorkspace = (variables, signal) => controlPlaneFetch({
  url: "/workspaces/{workspaceId}",
  method: "put",
  ...variables,
  signal
});
const deleteWorkspace = (variables, signal) => controlPlaneFetch({
  url: "/workspaces/{workspaceId}",
  method: "delete",
  ...variables,
  signal
});
const getWorkspaceSettings = (variables, signal) => controlPlaneFetch({
  url: "/workspaces/{workspaceId}/settings",
  method: "get",
  ...variables,
  signal
});
const updateWorkspaceSettings = (variables, signal) => controlPlaneFetch({
  url: "/workspaces/{workspaceId}/settings",
  method: "patch",
  ...variables,
  signal
});
const getWorkspaceMembersList = (variables, signal) => controlPlaneFetch({
  url: "/workspaces/{workspaceId}/members",
  method: "get",
  ...variables,
  signal
});
const updateWorkspaceMemberRole = (variables, signal) => controlPlaneFetch({
  url: "/workspaces/{workspaceId}/members/{userId}",
  method: "put",
  ...variables,
  signal
});
const removeWorkspaceMember = (variables, signal) => controlPlaneFetch({
  url: "/workspaces/{workspaceId}/members/{userId}",
  method: "delete",
  ...variables,
  signal
});
const inviteWorkspaceMember = (variables, signal) => controlPlaneFetch({
  url: "/workspaces/{workspaceId}/invites",
  method: "post",
  ...variables,
  signal
});
const updateWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({
  url: "/workspaces/{workspaceId}/invites/{inviteId}",
  method: "patch",
  ...variables,
  signal
});
const cancelWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({
  url: "/workspaces/{workspaceId}/invites/{inviteId}",
  method: "delete",
  ...variables,
  signal
});
const acceptWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({
  url: "/workspaces/{workspaceId}/invites/{inviteKey}/accept",
  method: "post",
  ...variables,
  signal
});
const resendWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({
  url: "/workspaces/{workspaceId}/invites/{inviteId}/resend",
  method: "post",
  ...variables,
  signal
});
const listClusters = (variables, signal) => controlPlaneFetch({
  url: "/workspaces/{workspaceId}/clusters",
  method: "get",
  ...variables,
  signal
});
const createCluster = (variables, signal) => controlPlaneFetch({
  url: "/workspaces/{workspaceId}/clusters",
  method: "post",
  ...variables,
  signal
});
const getCluster = (variables, signal) => controlPlaneFetch({
  url: "/workspaces/{workspaceId}/clusters/{clusterId}",
  method: "get",
  ...variables,
  signal
});
const updateCluster = (variables, signal) => controlPlaneFetch({
  url: "/workspaces/{workspaceId}/clusters/{clusterId}",
  method: "patch",
  ...variables,
  signal
});
const deleteCluster = (variables, signal) => controlPlaneFetch({
  url: "/workspaces/{workspaceId}/clusters/{clusterId}",
  method: "delete",
  ...variables,
  signal
});
const getDatabaseList = (variables, signal) => controlPlaneFetch({
  url: "/workspaces/{workspaceId}/dbs",
  method: "get",
  ...variables,
  signal
});
const createDatabase = (variables, signal) => controlPlaneFetch({
  url: "/workspaces/{workspaceId}/dbs/{dbName}",
  method: "put",
  ...variables,
  signal
});
const deleteDatabase = (variables, signal) => controlPlaneFetch({
  url: "/workspaces/{workspaceId}/dbs/{dbName}",
  method: "delete",
  ...variables,
  signal
});
const getDatabaseMetadata = (variables, signal) => controlPlaneFetch({
  url: "/workspaces/{workspaceId}/dbs/{dbName}",
  method: "get",
  ...variables,
  signal
});
const updateDatabaseMetadata = (variables, signal) => controlPlaneFetch({
  url: "/workspaces/{workspaceId}/dbs/{dbName}",
  method: "patch",
  ...variables,
  signal
});
const renameDatabase = (variables, signal) => controlPlaneFetch({
  url: "/workspaces/{workspaceId}/dbs/{dbName}/rename",
  method: "post",
  ...variables,
  signal
});
const getDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({
  url: "/workspaces/{workspaceId}/dbs/{dbName}/github",
  method: "get",
  ...variables,
  signal
});
const updateDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({
  url: "/workspaces/{workspaceId}/dbs/{dbName}/github",
  method: "put",
  ...variables,
  signal
});
const deleteDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({
  url: "/workspaces/{workspaceId}/dbs/{dbName}/github",
  method: "delete",
  ...variables,
  signal
});
const listRegions = (variables, signal) => controlPlaneFetch({
  url: "/workspaces/{workspaceId}/regions",
  method: "get",
  ...variables,
  signal
});
const operationsByTag$1 = {
  oAuth: {
    getAuthorizationCode,
    grantAuthorizationCode,
    getUserOAuthClients,
    deleteUserOAuthClient,
    getUserOAuthAccessTokens,
    deleteOAuthAccessToken,
    updateOAuthAccessToken
  },
  users: { getUser, updateUser, deleteUser },
  authentication: { getUserAPIKeys, createUserAPIKey, deleteUserAPIKey },
  workspaces: {
    getWorkspacesList,
    createWorkspace,
    getWorkspace,
    updateWorkspace,
    deleteWorkspace,
    getWorkspaceSettings,
    updateWorkspaceSettings,
    getWorkspaceMembersList,
    updateWorkspaceMemberRole,
    removeWorkspaceMember
  },
  invites: {
    inviteWorkspaceMember,
    updateWorkspaceMemberInvite,
    cancelWorkspaceMemberInvite,
    acceptWorkspaceMemberInvite,
    resendWorkspaceMemberInvite
  },
  xbcontrolOther: {
    listClusters,
    createCluster,
    getCluster,
    updateCluster,
    deleteCluster
  },
  databases: {
    getDatabaseList,
    createDatabase,
    deleteDatabase,
    getDatabaseMetadata,
    updateDatabaseMetadata,
    renameDatabase,
    getDatabaseGithubSettings,
    updateDatabaseGithubSettings,
    deleteDatabaseGithubSettings,
    listRegions
  }
};

const operationsByTag = deepMerge(operationsByTag$2, operationsByTag$1);

const buildApiClient = () => class {
  constructor(options = {}) {
    const provider = options.host ?? "production";
    const apiKey = options.apiKey ?? getAPIKey();
    const trace = options.trace ?? defaultTrace;
    const clientID = generateUUID();
    if (!apiKey) {
      throw new Error("Could not resolve a valid apiKey");
    }
    const extraProps = {
      apiUrl: getHostUrl(provider, "main"),
      workspacesApiUrl: getHostUrl(provider, "workspaces"),
      fetch: getFetchImplementation(options.fetch),
      apiKey,
      trace,
      clientName: options.clientName,
      xataAgentExtra: options.xataAgentExtra,
      clientID
    };
    return new Proxy(this, {
      get: (_target, namespace) => {
        if (operationsByTag[namespace] === void 0) {
          return void 0;
        }
        return new Proxy(
          {},
          {
            get: (_target2, operation) => {
              if (operationsByTag[namespace][operation] === void 0) {
                return void 0;
              }
              const method = operationsByTag[namespace][operation];
              return async (params) => {
                return await method({ ...params, ...extraProps });
              };
            }
          }
        );
      }
    });
  }
};
class XataApiClient extends buildApiClient() {
}

class XataApiPlugin {
  build(options) {
    return new XataApiClient(options);
  }
}

class XataPlugin {
}

function buildTransformString(transformations) {
  return transformations.flatMap(
    (t) => Object.entries(t).map(([key, value]) => {
      if (key === "trim") {
        const { left = 0, top = 0, right = 0, bottom = 0 } = value;
        return `${key}=${[top, right, bottom, left].join(";")}`;
      }
      if (key === "gravity" && typeof value === "object") {
        const { x = 0.5, y = 0.5 } = value;
        return `${key}=${[x, y].join("x")}`;
      }
      return `${key}=${value}`;
    })
  ).join(",");
}
function transformImage(url, ...transformations) {
  if (!isDefined(url)) return void 0;
  const newTransformations = buildTransformString(transformations);
  const { hostname, pathname, search } = new URL(url);
  const pathParts = pathname.split("/");
  const transformIndex = pathParts.findIndex((part) => part === "transform");
  const removedItems = transformIndex >= 0 ? pathParts.splice(transformIndex, 2) : [];
  const transform = `/transform/${[removedItems[1], newTransformations].filter(isDefined).join(",")}`;
  const path = pathParts.join("/");
  return `https://${hostname}${transform}${path}${search}`;
}

class XataFile {
  constructor(file) {
    this.id = file.id;
    this.name = file.name;
    this.mediaType = file.mediaType;
    this.base64Content = file.base64Content;
    this.enablePublicUrl = file.enablePublicUrl;
    this.signedUrlTimeout = file.signedUrlTimeout;
    this.uploadUrlTimeout = file.uploadUrlTimeout;
    this.size = file.size;
    this.version = file.version;
    this.url = file.url;
    this.signedUrl = file.signedUrl;
    this.uploadUrl = file.uploadUrl;
    this.attributes = file.attributes;
  }
  static fromBuffer(buffer, options = {}) {
    const base64Content = buffer.toString("base64");
    return new XataFile({ ...options, base64Content });
  }
  toBuffer() {
    if (!this.base64Content) {
      throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
    }
    return Buffer.from(this.base64Content, "base64");
  }
  static fromArrayBuffer(arrayBuffer, options = {}) {
    const uint8Array = new Uint8Array(arrayBuffer);
    return this.fromUint8Array(uint8Array, options);
  }
  toArrayBuffer() {
    if (!this.base64Content) {
      throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
    }
    const binary = atob(this.base64Content);
    return new ArrayBuffer(binary.length);
  }
  static fromUint8Array(uint8Array, options = {}) {
    let binary = "";
    for (let i = 0; i < uint8Array.byteLength; i++) {
      binary += String.fromCharCode(uint8Array[i]);
    }
    const base64Content = btoa(binary);
    return new XataFile({ ...options, base64Content });
  }
  toUint8Array() {
    if (!this.base64Content) {
      throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
    }
    const binary = atob(this.base64Content);
    const uint8Array = new Uint8Array(binary.length);
    for (let i = 0; i < binary.length; i++) {
      uint8Array[i] = binary.charCodeAt(i);
    }
    return uint8Array;
  }
  static async fromBlob(file, options = {}) {
    const name = options.name ?? file.name;
    const mediaType = file.type;
    const arrayBuffer = await file.arrayBuffer();
    return this.fromArrayBuffer(arrayBuffer, { ...options, name, mediaType });
  }
  toBlob() {
    if (!this.base64Content) {
      throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
    }
    const binary = atob(this.base64Content);
    const uint8Array = new Uint8Array(binary.length);
    for (let i = 0; i < binary.length; i++) {
      uint8Array[i] = binary.charCodeAt(i);
    }
    return new Blob([uint8Array], { type: this.mediaType });
  }
  static fromString(string, options = {}) {
    const base64Content = btoa(string);
    return new XataFile({ ...options, base64Content });
  }
  toString() {
    if (!this.base64Content) {
      throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
    }
    return atob(this.base64Content);
  }
  static fromBase64(base64Content, options = {}) {
    return new XataFile({ ...options, base64Content });
  }
  toBase64() {
    if (!this.base64Content) {
      throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
    }
    return this.base64Content;
  }
  transform(...options) {
    return {
      url: transformImage(this.url, ...options),
      signedUrl: transformImage(this.signedUrl, ...options),
      metadataUrl: transformImage(this.url, ...options, { format: "json" }),
      metadataSignedUrl: transformImage(this.signedUrl, ...options, { format: "json" })
    };
  }
}
const parseInputFileEntry = async (entry) => {
  if (!isDefined(entry)) return null;
  const { id, name, mediaType, base64Content, enablePublicUrl, signedUrlTimeout, uploadUrlTimeout } = await entry;
  return compactObject({
    id,
    // Name cannot be an empty string in our API
    name: name ? name : void 0,
    mediaType,
    base64Content,
    enablePublicUrl,
    signedUrlTimeout,
    uploadUrlTimeout
  });
};

function cleanFilter(filter) {
  if (!isDefined(filter)) return void 0;
  if (!isObject(filter)) return filter;
  const values = Object.fromEntries(
    Object.entries(filter).reduce((acc, [key, value]) => {
      if (!isDefined(value)) return acc;
      if (Array.isArray(value)) {
        const clean = value.map((item) => cleanFilter(item)).filter((item) => isDefined(item));
        if (clean.length === 0) return acc;
        return [...acc, [key, clean]];
      }
      if (isObject(value)) {
        const clean = cleanFilter(value);
        if (!isDefined(clean)) return acc;
        return [...acc, [key, clean]];
      }
      return [...acc, [key, value]];
    }, [])
  );
  return Object.keys(values).length > 0 ? values : void 0;
}

function stringifyJson(value) {
  if (!isDefined(value)) return value;
  if (isString(value)) return value;
  try {
    return JSON.stringify(value);
  } catch (e) {
    return value;
  }
}
function parseJson(value) {
  try {
    return JSON.parse(value);
  } catch (e) {
    return value;
  }
}

var __typeError$6 = (msg) => {
  throw TypeError(msg);
};
var __accessCheck$6 = (obj, member, msg) => member.has(obj) || __typeError$6("Cannot " + msg);
var __privateGet$5 = (obj, member, getter) => (__accessCheck$6(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd$6 = (obj, member, value) => member.has(obj) ? __typeError$6("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateSet$4 = (obj, member, value, setter) => (__accessCheck$6(obj, member, "write to private field"), member.set(obj, value), value);
var _query, _page;
class Page {
  constructor(query, meta, records = []) {
    __privateAdd$6(this, _query);
    __privateSet$4(this, _query, query);
    this.meta = meta;
    this.records = new PageRecordArray(this, records);
  }
  /**
   * Retrieves the next page of results.
   * @param size Maximum number of results to be retrieved.
   * @param offset Number of results to skip when retrieving the results.
   * @returns The next page or results.
   */
  async nextPage(size, offset) {
    return __privateGet$5(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
  }
  /**
   * Retrieves the previous page of results.
   * @param size Maximum number of results to be retrieved.
   * @param offset Number of results to skip when retrieving the results.
   * @returns The previous page or results.
   */
  async previousPage(size, offset) {
    return __privateGet$5(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
  }
  /**
   * Retrieves the start page of results.
   * @param size Maximum number of results to be retrieved.
   * @param offset Number of results to skip when retrieving the results.
   * @returns The start page or results.
   */
  async startPage(size, offset) {
    return __privateGet$5(this, _query).getPaginated({ pagination: { size, offset, start: this.meta.page.cursor } });
  }
  /**
   * Retrieves the end page of results.
   * @param size Maximum number of results to be retrieved.
   * @param offset Number of results to skip when retrieving the results.
   * @returns The end page or results.
   */
  async endPage(size, offset) {
    return __privateGet$5(this, _query).getPaginated({ pagination: { size, offset, end: this.meta.page.cursor } });
  }
  /**
   * Shortcut method to check if there will be additional results if the next page of results is retrieved.
   * @returns Whether or not there will be additional results in the next page of results.
   */
  hasNextPage() {
    return this.meta.page.more;
  }
}
_query = new WeakMap();
const PAGINATION_MAX_SIZE = 1e3;
const PAGINATION_DEFAULT_SIZE = 20;
const PAGINATION_MAX_OFFSET = 49e3;
const PAGINATION_DEFAULT_OFFSET = 0;
function isCursorPaginationOptions(options) {
  return isDefined(options) && (isDefined(options.start) || isDefined(options.end) || isDefined(options.after) || isDefined(options.before));
}
class RecordArray extends Array {
  constructor(...args) {
    super(...RecordArray.parseConstructorParams(...args));
  }
  static parseConstructorParams(...args) {
    if (args.length === 1 && typeof args[0] === "number") {
      return new Array(args[0]);
    }
    if (args.length <= 1 && Array.isArray(args[0] ?? [])) {
      const result = args[0] ?? [];
      return new Array(...result);
    }
    return new Array(...args);
  }
  toArray() {
    return new Array(...this);
  }
  toSerializable() {
    return JSON.parse(this.toString());
  }
  toString() {
    return JSON.stringify(this.toArray());
  }
  map(callbackfn, thisArg) {
    return this.toArray().map(callbackfn, thisArg);
  }
}
const _PageRecordArray = class _PageRecordArray extends Array {
  constructor(...args) {
    super(..._PageRecordArray.parseConstructorParams(...args));
    __privateAdd$6(this, _page);
    __privateSet$4(this, _page, isObject(args[0]?.meta) ? args[0] : { meta: { page: { cursor: "", more: false } }, records: [] });
  }
  static parseConstructorParams(...args) {
    if (args.length === 1 && typeof args[0] === "number") {
      return new Array(args[0]);
    }
    if (args.length <= 2 && isObject(args[0]?.meta) && Array.isArray(args[1] ?? [])) {
      const result = args[1] ?? args[0].records ?? [];
      return new Array(...result);
    }
    return new Array(...args);
  }
  toArray() {
    return new Array(...this);
  }
  toSerializable() {
    return JSON.parse(this.toString());
  }
  toString() {
    return JSON.stringify(this.toArray());
  }
  map(callbackfn, thisArg) {
    return this.toArray().map(callbackfn, thisArg);
  }
  /**
   * Retrieve next page of records
   *
   * @returns A new array of objects
   */
  async nextPage(size, offset) {
    const newPage = await __privateGet$5(this, _page).nextPage(size, offset);
    return new _PageRecordArray(newPage);
  }
  /**
   * Retrieve previous page of records
   *
   * @returns A new array of objects
   */
  async previousPage(size, offset) {
    const newPage = await __privateGet$5(this, _page).previousPage(size, offset);
    return new _PageRecordArray(newPage);
  }
  /**
   * Retrieve start page of records
   *
   * @returns A new array of objects
   */
  async startPage(size, offset) {
    const newPage = await __privateGet$5(this, _page).startPage(size, offset);
    return new _PageRecordArray(newPage);
  }
  /**
   * Retrieve end page of records
   *
   * @returns A new array of objects
   */
  async endPage(size, offset) {
    const newPage = await __privateGet$5(this, _page).endPage(size, offset);
    return new _PageRecordArray(newPage);
  }
  /**
   * @returns Boolean indicating if there is a next page
   */
  hasNextPage() {
    return __privateGet$5(this, _page).meta.page.more;
  }
};
_page = new WeakMap();
let PageRecordArray = _PageRecordArray;

var __typeError$5 = (msg) => {
  throw TypeError(msg);
};
var __accessCheck$5 = (obj, member, msg) => member.has(obj) || __typeError$5("Cannot " + msg);
var __privateGet$4 = (obj, member, getter) => (__accessCheck$5(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd$5 = (obj, member, value) => member.has(obj) ? __typeError$5("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateSet$3 = (obj, member, value, setter) => (__accessCheck$5(obj, member, "write to private field"), member.set(obj, value), value);
var __privateMethod$3 = (obj, member, method) => (__accessCheck$5(obj, member, "access private method"), method);
var _table$1, _repository, _data, _Query_instances, cleanFilterConstraint_fn;
const _Query = class _Query {
  constructor(repository, table, data, rawParent) {
    __privateAdd$5(this, _Query_instances);
    __privateAdd$5(this, _table$1);
    __privateAdd$5(this, _repository);
    __privateAdd$5(this, _data, { filter: {} });
    // Implements pagination
    this.meta = { page: { cursor: "start", more: true, size: PAGINATION_DEFAULT_SIZE } };
    this.records = new PageRecordArray(this, []);
    __privateSet$3(this, _table$1, table);
    if (repository) {
      __privateSet$3(this, _repository, repository);
    } else {
      __privateSet$3(this, _repository, this);
    }
    const parent = cleanParent(data, rawParent);
    __privateGet$4(this, _data).filter = data.filter ?? parent?.filter ?? {};
    __privateGet$4(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
    __privateGet$4(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
    __privateGet$4(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
    __privateGet$4(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
    __privateGet$4(this, _data).sort = data.sort ?? parent?.sort;
    __privateGet$4(this, _data).columns = data.columns ?? parent?.columns;
    __privateGet$4(this, _data).consistency = data.consistency ?? parent?.consistency;
    __privateGet$4(this, _data).pagination = data.pagination ?? parent?.pagination;
    __privateGet$4(this, _data).cache = data.cache ?? parent?.cache;
    __privateGet$4(this, _data).fetchOptions = data.fetchOptions ?? parent?.fetchOptions;
    this.any = this.any.bind(this);
    this.all = this.all.bind(this);
    this.not = this.not.bind(this);
    this.filter = this.filter.bind(this);
    this.sort = this.sort.bind(this);
    this.none = this.none.bind(this);
    Object.defineProperty(this, "table", { enumerable: false });
    Object.defineProperty(this, "repository", { enumerable: false });
  }
  getQueryOptions() {
    return __privateGet$4(this, _data);
  }
  key() {
    const { columns = [], filter = {}, sort = [], pagination = {} } = __privateGet$4(this, _data);
    const key = JSON.stringify({ columns, filter, sort, pagination });
    return toBase64(key);
  }
  /**
   * Builds a new query object representing a logical OR between the given subqueries.
   * @param queries An array of subqueries.
   * @returns A new Query object.
   */
  any(...queries) {
    const $any = queries.map((query) => query.getQueryOptions().filter ?? {});
    return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $any } }, __privateGet$4(this, _data));
  }
  /**
   * Builds a new query object representing a logical AND between the given subqueries.
   * @param queries An array of subqueries.
   * @returns A new Query object.
   */
  all(...queries) {
    const $all = queries.map((query) => query.getQueryOptions().filter ?? {});
    return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
  }
  /**
   * Builds a new query object representing a logical OR negating each subquery. In pseudo-code: !q1 OR !q2
   * @param queries An array of subqueries.
   * @returns A new Query object.
   */
  not(...queries) {
    const $not = queries.map((query) => query.getQueryOptions().filter ?? {});
    return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $not } }, __privateGet$4(this, _data));
  }
  /**
   * Builds a new query object representing a logical AND negating each subquery. In pseudo-code: !q1 AND !q2
   * @param queries An array of subqueries.
   * @returns A new Query object.
   */
  none(...queries) {
    const $none = queries.map((query) => query.getQueryOptions().filter ?? {});
    return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $none } }, __privateGet$4(this, _data));
  }
  filter(a, b) {
    if (arguments.length === 1) {
      const constraints = Object.entries(a ?? {}).map(([column, constraint]) => ({
        [column]: __privateMethod$3(this, _Query_instances, cleanFilterConstraint_fn).call(this, column, constraint)
      }));
      const $all = compact([__privateGet$4(this, _data).filter?.$all].flat().concat(constraints));
      return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
    } else {
      const constraints = isDefined(a) && isDefined(b) ? [{ [a]: __privateMethod$3(this, _Query_instances, cleanFilterConstraint_fn).call(this, a, b) }] : void 0;
      const $all = compact([__privateGet$4(this, _data).filter?.$all].flat().concat(constraints));
      return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
    }
  }
  sort(column, direction = "asc") {
    const originalSort = [__privateGet$4(this, _data).sort ?? []].flat();
    const sort = [...originalSort, { column, direction }];
    return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { sort }, __privateGet$4(this, _data));
  }
  /**
   * Builds a new query specifying the set of columns to be returned in the query response.
   * @param columns Array of column names to be returned by the query.
   * @returns A new Query object.
   */
  select(columns) {
    return new _Query(
      __privateGet$4(this, _repository),
      __privateGet$4(this, _table$1),
      { columns },
      __privateGet$4(this, _data)
    );
  }
  getPaginated(options = {}) {
    const query = new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), options, __privateGet$4(this, _data));
    return __privateGet$4(this, _repository).query(query);
  }
  /**
   * Get results in an iterator
   *
   * @async
   * @returns Async interable of results
   */
  async *[Symbol.asyncIterator]() {
    for await (const [record] of this.getIterator({ batchSize: 1 })) {
      yield record;
    }
  }
  async *getIterator(options = {}) {
    const { batchSize = 1 } = options;
    let page = await this.getPaginated({ ...options, pagination: { size: batchSize, offset: 0 } });
    let more = page.hasNextPage();
    yield page.records;
    while (more) {
      page = await page.nextPage();
      more = page.hasNextPage();
      yield page.records;
    }
  }
  async getMany(options = {}) {
    const { pagination = {}, ...rest } = options;
    const { size = PAGINATION_DEFAULT_SIZE, offset } = pagination;
    const batchSize = size <= PAGINATION_MAX_SIZE ? size : PAGINATION_MAX_SIZE;
    let page = await this.getPaginated({ ...rest, pagination: { size: batchSize, offset } });
    const results = [...page.records];
    while (page.hasNextPage() && results.length < size) {
      page = await page.nextPage();
      results.push(...page.records);
    }
    if (page.hasNextPage() && options.pagination?.size === void 0) {
      console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
    }
    const array = new PageRecordArray(page, results.slice(0, size));
    return array;
  }
  async getAll(options = {}) {
    const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
    const results = [];
    for await (const page of this.getIterator({ ...rest, batchSize })) {
      results.push(...page);
    }
    return new RecordArray(results);
  }
  async getFirst(options = {}) {
    const records = await this.getMany({ ...options, pagination: { size: 1 } });
    return records[0] ?? null;
  }
  async getFirstOrThrow(options = {}) {
    const records = await this.getMany({ ...options, pagination: { size: 1 } });
    if (records[0] === void 0) throw new Error("No results found.");
    return records[0];
  }
  async summarize(params = {}) {
    const { summaries, summariesFilter, ...options } = params;
    const query = new _Query(
      __privateGet$4(this, _repository),
      __privateGet$4(this, _table$1),
      options,
      __privateGet$4(this, _data)
    );
    return __privateGet$4(this, _repository).summarizeTable(query, summaries, summariesFilter);
  }
  /**
   * Builds a new query object adding a cache TTL in milliseconds.
   * @param ttl The cache TTL in milliseconds.
   * @returns A new Query object.
   */
  cache(ttl) {
    return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { cache: ttl }, __privateGet$4(this, _data));
  }
  /**
   * Retrieve next page of records
   *
   * @returns A new page object.
   */
  nextPage(size, offset) {
    return this.startPage(size, offset);
  }
  /**
   * Retrieve previous page of records
   *
   * @returns A new page object
   */
  previousPage(size, offset) {
    return this.startPage(size, offset);
  }
  /**
   * Retrieve start page of records
   *
   * @returns A new page object
   */
  startPage(size, offset) {
    return this.getPaginated({ pagination: { size, offset } });
  }
  /**
   * Retrieve last page of records
   *
   * @returns A new page object
   */
  endPage(size, offset) {
    return this.getPaginated({ pagination: { size, offset, before: "end" } });
  }
  /**
   * @returns Boolean indicating if there is a next page
   */
  hasNextPage() {
    return this.meta.page.more;
  }
};
_table$1 = new WeakMap();
_repository = new WeakMap();
_data = new WeakMap();
_Query_instances = new WeakSet();
cleanFilterConstraint_fn = function(column, value) {
  const columnType = __privateGet$4(this, _table$1).schema?.columns.find(({ name }) => name === column)?.type;
  if (columnType === "multiple" && (isString(value) || isStringArray(value))) {
    return { $includes: value };
  }
  if (columnType === "link" && isObject(value) && isString(value.id)) {
    return value.id;
  }
  return value;
};
let Query = _Query;
function cleanParent(data, parent) {
  if (isCursorPaginationOptions(data.pagination)) {
    return { ...parent, sort: void 0, filter: void 0 };
  }
  return parent;
}

const RecordColumnTypes = [
  "bool",
  "int",
  "float",
  "string",
  "text",
  "email",
  "multiple",
  "link",
  "datetime",
  "vector",
  "file[]",
  "file",
  "json"
];
function isIdentifiable(x) {
  return isObject(x) && isString(x?.id);
}
function isXataRecord(x) {
  const record = x;
  const metadata = record?.getMetadata();
  return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
}

function isValidExpandedColumn(column) {
  return isObject(column) && isString(column.name);
}
function isValidSelectableColumns(columns) {
  if (!Array.isArray(columns)) {
    return false;
  }
  return columns.every((column) => {
    if (typeof column === "string") {
      return true;
    }
    if (typeof column === "object") {
      return isValidExpandedColumn(column);
    }
    return false;
  });
}

function isSortFilterString(value) {
  return isString(value);
}
function isSortFilterBase(filter) {
  return isObject(filter) && Object.entries(filter).every(([key, value]) => {
    if (key === "*") return value === "random";
    return value === "asc" || value === "desc";
  });
}
function isSortFilterObject(filter) {
  return isObject(filter) && !isSortFilterBase(filter) && filter.column !== void 0;
}
function buildSortFilter(filter) {
  if (isSortFilterString(filter)) {
    return { [filter]: "asc" };
  } else if (Array.isArray(filter)) {
    return filter.map((item) => buildSortFilter(item));
  } else if (isSortFilterBase(filter)) {
    return filter;
  } else if (isSortFilterObject(filter)) {
    return { [filter.column]: filter.direction ?? "asc" };
  } else {
    throw new Error(`Invalid sort filter: ${filter}`);
  }
}

var __typeError$4 = (msg) => {
  throw TypeError(msg);
};
var __accessCheck$4 = (obj, member, msg) => member.has(obj) || __typeError$4("Cannot " + msg);
var __privateGet$3 = (obj, member, getter) => (__accessCheck$4(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd$4 = (obj, member, value) => member.has(obj) ? __typeError$4("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateSet$2 = (obj, member, value, setter) => (__accessCheck$4(obj, member, "write to private field"), member.set(obj, value), value);
var __privateMethod$2 = (obj, member, method) => (__accessCheck$4(obj, member, "access private method"), method);
var _table, _getFetchProps, _db, _cache, _schemaTables, _trace, _RestRepository_instances, insertRecordWithoutId_fn, insertRecordWithId_fn, insertRecords_fn, updateRecordWithID_fn, updateRecords_fn, upsertRecordWithID_fn, deleteRecord_fn, deleteRecords_fn, setCacheQuery_fn, getCacheQuery_fn, getSchemaTables_fn, transformObjectToApi_fn;
const BULK_OPERATION_MAX_SIZE = 1e3;
class Repository extends Query {
}
class RestRepository extends Query {
  constructor(options) {
    super(
      null,
      { name: options.table, schema: options.schemaTables?.find((table) => table.name === options.table) },
      {}
    );
    __privateAdd$4(this, _RestRepository_instances);
    __privateAdd$4(this, _table);
    __privateAdd$4(this, _getFetchProps);
    __privateAdd$4(this, _db);
    __privateAdd$4(this, _cache);
    __privateAdd$4(this, _schemaTables);
    __privateAdd$4(this, _trace);
    __privateSet$2(this, _table, options.table);
    __privateSet$2(this, _db, options.db);
    __privateSet$2(this, _cache, options.pluginOptions.cache);
    __privateSet$2(this, _schemaTables, options.schemaTables);
    __privateSet$2(this, _getFetchProps, () => ({ ...options.pluginOptions, sessionID: generateUUID() }));
    const trace = options.pluginOptions.trace ?? defaultTrace;
    __privateSet$2(this, _trace, async (name, fn, options2 = {}) => {
      return trace(name, fn, {
        ...options2,
        [TraceAttributes.TABLE]: __privateGet$3(this, _table),
        [TraceAttributes.KIND]: "sdk-operation",
        [TraceAttributes.VERSION]: VERSION
      });
    });
  }
  async create(a, b, c, d) {
    return __privateGet$3(this, _trace).call(this, "create", async () => {
      const ifVersion = parseIfVersion(b, c, d);
      if (Array.isArray(a)) {
        if (a.length === 0) return [];
        const ids = await __privateMethod$2(this, _RestRepository_instances, insertRecords_fn).call(this, a, { ifVersion, createOnly: true });
        const columns = isValidSelectableColumns(b) ? b : ["*"];
        const result = await this.read(ids, columns);
        return result;
      }
      if (isString(a) && isObject(b)) {
        if (a === "") throw new Error("The id can't be empty");
        const columns = isValidSelectableColumns(c) ? c : void 0;
        return await __privateMethod$2(this, _RestRepository_instances, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: true, ifVersion });
      }
      if (isObject(a) && isString(a.id)) {
        if (a.id === "") throw new Error("The id can't be empty");
        const columns = isValidSelectableColumns(b) ? b : void 0;
        return await __privateMethod$2(this, _RestRepository_instances, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: true, ifVersion });
      }
      if (isObject(a)) {
        const columns = isValidSelectableColumns(b) ? b : void 0;
        return __privateMethod$2(this, _RestRepository_instances, insertRecordWithoutId_fn).call(this, a, columns);
      }
      throw new Error("Invalid arguments for create method");
    });
  }
  async read(a, b) {
    return __privateGet$3(this, _trace).call(this, "read", async () => {
      const columns = isValidSelectableColumns(b) ? b : ["*"];
      if (Array.isArray(a)) {
        if (a.length === 0) return [];
        const ids = a.map((item) => extractId(item));
        const finalObjects = await this.getAll({ filter: { id: { $any: compact(ids) } }, columns });
        const dictionary = finalObjects.reduce((acc, object) => {
          acc[object.id] = object;
          return acc;
        }, {});
        return ids.map((id2) => dictionary[id2 ?? ""] ?? null);
      }
      const id = extractId(a);
      if (id) {
        try {
          const response = await getRecord({
            pathParams: {
              workspace: "{workspaceId}",
              dbBranchName: "{dbBranch}",
              region: "{region}",
              tableName: __privateGet$3(this, _table),
              recordId: id
            },
            queryParams: { columns },
            ...__privateGet$3(this, _getFetchProps).call(this)
          });
          const schemaTables = await __privateMethod$2(this, _RestRepository_instances, getSchemaTables_fn).call(this);
          return initObject(
            __privateGet$3(this, _db),
            schemaTables,
            __privateGet$3(this, _table),
            response,
            columns
          );
        } catch (e) {
          if (isObject(e) && e.status === 404) {
            return null;
          }
          throw e;
        }
      }
      return null;
    });
  }
  async readOrThrow(a, b) {
    return __privateGet$3(this, _trace).call(this, "readOrThrow", async () => {
      const result = await this.read(a, b);
      if (Array.isArray(result)) {
        const missingIds = compact(
          a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
        );
        if (missingIds.length > 0) {
          throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
        }
        return result;
      }
      if (result === null) {
        const id = extractId(a) ?? "unknown";
        throw new Error(`Record with id ${id} not found`);
      }
      return result;
    });
  }
  async update(a, b, c, d) {
    return __privateGet$3(this, _trace).call(this, "update", async () => {
      const ifVersion = parseIfVersion(b, c, d);
      if (Array.isArray(a)) {
        if (a.length === 0) return [];
        const existing = await this.read(a, ["id"]);
        const updates = a.filter((_item, index) => existing[index] !== null);
        await __privateMethod$2(this, _RestRepository_instances, updateRecords_fn).call(this, updates, {
          ifVersion,
          upsert: false
        });
        const columns = isValidSelectableColumns(b) ? b : ["*"];
        const result = await this.read(a, columns);
        return result;
      }
      try {
        if (isString(a) && isObject(b)) {
          const columns = isValidSelectableColumns(c) ? c : void 0;
          return await __privateMethod$2(this, _RestRepository_instances, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
        }
        if (isObject(a) && isString(a.id)) {
          const columns = isValidSelectableColumns(b) ? b : void 0;
          return await __privateMethod$2(this, _RestRepository_instances, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
        }
      } catch (error) {
        if (error.status === 422) return null;
        throw error;
      }
      throw new Error("Invalid arguments for update method");
    });
  }
  async updateOrThrow(a, b, c, d) {
    return __privateGet$3(this, _trace).call(this, "updateOrThrow", async () => {
      const result = await this.update(a, b, c, d);
      if (Array.isArray(result)) {
        const missingIds = compact(
          a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
        );
        if (missingIds.length > 0) {
          throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
        }
        return result;
      }
      if (result === null) {
        const id = extractId(a) ?? "unknown";
        throw new Error(`Record with id ${id} not found`);
      }
      return result;
    });
  }
  async createOrUpdate(a, b, c, d) {
    return __privateGet$3(this, _trace).call(this, "createOrUpdate", async () => {
      const ifVersion = parseIfVersion(b, c, d);
      if (Array.isArray(a)) {
        if (a.length === 0) return [];
        await __privateMethod$2(this, _RestRepository_instances, updateRecords_fn).call(this, a, {
          ifVersion,
          upsert: true
        });
        const columns = isValidSelectableColumns(b) ? b : ["*"];
        const result = await this.read(a, columns);
        return result;
      }
      if (isString(a) && isObject(b)) {
        if (a === "") throw new Error("The id can't be empty");
        const columns = isValidSelectableColumns(c) ? c : void 0;
        return await __privateMethod$2(this, _RestRepository_instances, upsertRecordWithID_fn).call(this, a, b, columns, { ifVersion });
      }
      if (isObject(a) && isString(a.id)) {
        if (a.id === "") throw new Error("The id can't be empty");
        const columns = isValidSelectableColumns(c) ? c : void 0;
        return await __privateMethod$2(this, _RestRepository_instances, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
      }
      if (!isDefined(a) && isObject(b)) {
        return await this.create(b, c);
      }
      if (isObject(a) && !isDefined(a.id)) {
        return await this.create(a, b);
      }
      throw new Error("Invalid arguments for createOrUpdate method");
    });
  }
  async createOrReplace(a, b, c, d) {
    return __privateGet$3(this, _trace).call(this, "createOrReplace", async () => {
      const ifVersion = parseIfVersion(b, c, d);
      if (Array.isArray(a)) {
        if (a.length === 0) return [];
        const ids = await __privateMethod$2(this, _RestRepository_instances, insertRecords_fn).call(this, a, { ifVersion, createOnly: false });
        const columns = isValidSelectableColumns(b) ? b : ["*"];
        const result = await this.read(ids, columns);
        return result;
      }
      if (isString(a) && isObject(b)) {
        if (a === "") throw new Error("The id can't be empty");
        const columns = isValidSelectableColumns(c) ? c : void 0;
        return await __privateMethod$2(this, _RestRepository_instances, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: false, ifVersion });
      }
      if (isObject(a) && isString(a.id)) {
        if (a.id === "") throw new Error("The id can't be empty");
        const columns = isValidSelectableColumns(c) ? c : void 0;
        return await __privateMethod$2(this, _RestRepository_instances, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: false, ifVersion });
      }
      if (!isDefined(a) && isObject(b)) {
        return await this.create(b, c);
      }
      if (isObject(a) && !isDefined(a.id)) {
        return await this.create(a, b);
      }
      throw new Error("Invalid arguments for createOrReplace method");
    });
  }
  async delete(a, b) {
    return __privateGet$3(this, _trace).call(this, "delete", async () => {
      if (Array.isArray(a)) {
        if (a.length === 0) return [];
        const ids = a.map((o) => {
          if (isString(o)) return o;
          if (isString(o.id)) return o.id;
          throw new Error("Invalid arguments for delete method");
        });
        const columns = isValidSelectableColumns(b) ? b : ["*"];
        const result = await this.read(a, columns);
        await __privateMethod$2(this, _RestRepository_instances, deleteRecords_fn).call(this, ids);
        return result;
      }
      if (isString(a)) {
        return __privateMethod$2(this, _RestRepository_instances, deleteRecord_fn).call(this, a, b);
      }
      if (isObject(a) && isString(a.id)) {
        return __privateMethod$2(this, _RestRepository_instances, deleteRecord_fn).call(this, a.id, b);
      }
      throw new Error("Invalid arguments for delete method");
    });
  }
  async deleteOrThrow(a, b) {
    return __privateGet$3(this, _trace).call(this, "deleteOrThrow", async () => {
      const result = await this.delete(a, b);
      if (Array.isArray(result)) {
        const missingIds = compact(
          a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
        );
        if (missingIds.length > 0) {
          throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
        }
        return result;
      } else if (result === null) {
        const id = extractId(a) ?? "unknown";
        throw new Error(`Record with id ${id} not found`);
      }
      return result;
    });
  }
  async search(query, options = {}) {
    return __privateGet$3(this, _trace).call(this, "search", async () => {
      const { records, totalCount } = await searchTable({
        pathParams: {
          workspace: "{workspaceId}",
          dbBranchName: "{dbBranch}",
          region: "{region}",
          tableName: __privateGet$3(this, _table)
        },
        body: {
          query,
          fuzziness: options.fuzziness,
          prefix: options.prefix,
          highlight: options.highlight,
          filter: options.filter,
          boosters: options.boosters,
          page: options.page,
          target: options.target
        },
        ...__privateGet$3(this, _getFetchProps).call(this)
      });
      const schemaTables = await __privateMethod$2(this, _RestRepository_instances, getSchemaTables_fn).call(this);
      return {
        records: records.map((item) => initObject(__privateGet$3(this, _db), schemaTables, __privateGet$3(this, _table), item, ["*"])),
        totalCount
      };
    });
  }
  async vectorSearch(column, query, options) {
    return __privateGet$3(this, _trace).call(this, "vectorSearch", async () => {
      const { records, totalCount } = await vectorSearchTable({
        pathParams: {
          workspace: "{workspaceId}",
          dbBranchName: "{dbBranch}",
          region: "{region}",
          tableName: __privateGet$3(this, _table)
        },
        body: {
          column,
          queryVector: query,
          similarityFunction: options?.similarityFunction,
          size: options?.size,
          filter: options?.filter
        },
        ...__privateGet$3(this, _getFetchProps).call(this)
      });
      const schemaTables = await __privateMethod$2(this, _RestRepository_instances, getSchemaTables_fn).call(this);
      return {
        records: records.map((item) => initObject(__privateGet$3(this, _db), schemaTables, __privateGet$3(this, _table), item, ["*"])),
        totalCount
      };
    });
  }
  async aggregate(aggs, filter) {
    return __privateGet$3(this, _trace).call(this, "aggregate", async () => {
      const result = await aggregateTable({
        pathParams: {
          workspace: "{workspaceId}",
          dbBranchName: "{dbBranch}",
          region: "{region}",
          tableName: __privateGet$3(this, _table)
        },
        body: { aggs, filter },
        ...__privateGet$3(this, _getFetchProps).call(this)
      });
      return result;
    });
  }
  async query(query) {
    return __privateGet$3(this, _trace).call(this, "query", async () => {
      const cacheQuery = await __privateMethod$2(this, _RestRepository_instances, getCacheQuery_fn).call(this, query);
      if (cacheQuery) return new Page(query, cacheQuery.meta, cacheQuery.records);
      const data = query.getQueryOptions();
      const { meta, records: objects } = await queryTable({
        pathParams: {
          workspace: "{workspaceId}",
          dbBranchName: "{dbBranch}",
          region: "{region}",
          tableName: __privateGet$3(this, _table)
        },
        body: {
          filter: cleanFilter(data.filter),
          sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
          page: data.pagination,
          columns: data.columns ?? ["*"],
          consistency: data.consistency
        },
        fetchOptions: data.fetchOptions,
        ...__privateGet$3(this, _getFetchProps).call(this)
      });
      const schemaTables = await __privateMethod$2(this, _RestRepository_instances, getSchemaTables_fn).call(this);
      const records = objects.map(
        (record) => initObject(
          __privateGet$3(this, _db),
          schemaTables,
          __privateGet$3(this, _table),
          record,
          data.columns ?? ["*"]
        )
      );
      await __privateMethod$2(this, _RestRepository_instances, setCacheQuery_fn).call(this, query, meta, records);
      return new Page(query, meta, records);
    });
  }
  async summarizeTable(query, summaries, summariesFilter) {
    return __privateGet$3(this, _trace).call(this, "summarize", async () => {
      const data = query.getQueryOptions();
      const result = await summarizeTable({
        pathParams: {
          workspace: "{workspaceId}",
          dbBranchName: "{dbBranch}",
          region: "{region}",
          tableName: __privateGet$3(this, _table)
        },
        body: {
          filter: cleanFilter(data.filter),
          sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
          columns: data.columns,
          consistency: data.consistency,
          page: data.pagination?.size !== void 0 ? { size: data.pagination?.size } : void 0,
          summaries,
          summariesFilter
        },
        ...__privateGet$3(this, _getFetchProps).call(this)
      });
      const schemaTables = await __privateMethod$2(this, _RestRepository_instances, getSchemaTables_fn).call(this);
      return {
        ...result,
        summaries: result.summaries.map(
          (summary) => initObject(__privateGet$3(this, _db), schemaTables, __privateGet$3(this, _table), summary, data.columns ?? [])
        )
      };
    });
  }
  ask(question, options) {
    const questionParam = options?.sessionId ? { message: question } : { question };
    const params = {
      pathParams: {
        workspace: "{workspaceId}",
        dbBranchName: "{dbBranch}",
        region: "{region}",
        tableName: __privateGet$3(this, _table),
        sessionId: options?.sessionId
      },
      body: {
        ...questionParam,
        rules: options?.rules,
        searchType: options?.searchType,
        search: options?.searchType === "keyword" ? options?.search : void 0,
        vectorSearch: options?.searchType === "vector" ? options?.vectorSearch : void 0
      },
      ...__privateGet$3(this, _getFetchProps).call(this)
    };
    if (options?.onMessage) {
      fetchSSERequest({
        endpoint: "dataPlane",
        url: "/db/{dbBranchName}/tables/{tableName}/ask/{sessionId}",
        method: "POST",
        onMessage: (message) => {
          options.onMessage?.({ answer: message.text, records: message.records });
        },
        ...params
      });
    } else {
      return askTableSession(params);
    }
  }
}
_table = new WeakMap();
_getFetchProps = new WeakMap();
_db = new WeakMap();
_cache = new WeakMap();
_schemaTables = new WeakMap();
_trace = new WeakMap();
_RestRepository_instances = new WeakSet();
insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
  const record = await __privateMethod$2(this, _RestRepository_instances, transformObjectToApi_fn).call(this, object);
  const response = await insertRecord({
    pathParams: {
      workspace: "{workspaceId}",
      dbBranchName: "{dbBranch}",
      region: "{region}",
      tableName: __privateGet$3(this, _table)
    },
    queryParams: { columns },
    body: record,
    ...__privateGet$3(this, _getFetchProps).call(this)
  });
  const schemaTables = await __privateMethod$2(this, _RestRepository_instances, getSchemaTables_fn).call(this);
  return initObject(__privateGet$3(this, _db), schemaTables, __privateGet$3(this, _table), response, columns);
};
insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { createOnly, ifVersion }) {
  if (!recordId) return null;
  const record = await __privateMethod$2(this, _RestRepository_instances, transformObjectToApi_fn).call(this, object);
  const response = await insertRecordWithID({
    pathParams: {
      workspace: "{workspaceId}",
      dbBranchName: "{dbBranch}",
      region: "{region}",
      tableName: __privateGet$3(this, _table),
      recordId
    },
    body: record,
    queryParams: { createOnly, columns, ifVersion },
    ...__privateGet$3(this, _getFetchProps).call(this)
  });
  const schemaTables = await __privateMethod$2(this, _RestRepository_instances, getSchemaTables_fn).call(this);
  return initObject(__privateGet$3(this, _db), schemaTables, __privateGet$3(this, _table), response, columns);
};
insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
  const operations = await promiseMap(objects, async (object) => {
    const record = await __privateMethod$2(this, _RestRepository_instances, transformObjectToApi_fn).call(this, object);
    return { insert: { table: __privateGet$3(this, _table), record, createOnly, ifVersion } };
  });
  const chunkedOperations = chunk(operations, BULK_OPERATION_MAX_SIZE);
  const ids = [];
  for (const operations2 of chunkedOperations) {
    const { results } = await branchTransaction({
      pathParams: {
        workspace: "{workspaceId}",
        dbBranchName: "{dbBranch}",
        region: "{region}"
      },
      body: { operations: operations2 },
      ...__privateGet$3(this, _getFetchProps).call(this)
    });
    for (const result of results) {
      if (result.operation === "insert") {
        ids.push(result.id);
      } else {
        ids.push(null);
      }
    }
  }
  return ids;
};
updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
  if (!recordId) return null;
  const { id: _id, ...record } = await __privateMethod$2(this, _RestRepository_instances, transformObjectToApi_fn).call(this, object);
  try {
    const response = await updateRecordWithID({
      pathParams: {
        workspace: "{workspaceId}",
        dbBranchName: "{dbBranch}",
        region: "{region}",
        tableName: __privateGet$3(this, _table),
        recordId
      },
      queryParams: { columns, ifVersion },
      body: record,
      ...__privateGet$3(this, _getFetchProps).call(this)
    });
    const schemaTables = await __privateMethod$2(this, _RestRepository_instances, getSchemaTables_fn).call(this);
    return initObject(__privateGet$3(this, _db), schemaTables, __privateGet$3(this, _table), response, columns);
  } catch (e) {
    if (isObject(e) && e.status === 404) {
      return null;
    }
    throw e;
  }
};
updateRecords_fn = async function(objects, { ifVersion, upsert }) {
  const operations = await promiseMap(objects, async ({ id, ...object }) => {
    const fields = await __privateMethod$2(this, _RestRepository_instances, transformObjectToApi_fn).call(this, object);
    return { update: { table: __privateGet$3(this, _table), id, ifVersion, upsert, fields } };
  });
  const chunkedOperations = chunk(operations, BULK_OPERATION_MAX_SIZE);
  const ids = [];
  for (const operations2 of chunkedOperations) {
    const { results } = await branchTransaction({
      pathParams: {
        workspace: "{workspaceId}",
        dbBranchName: "{dbBranch}",
        region: "{region}"
      },
      body: { operations: operations2 },
      ...__privateGet$3(this, _getFetchProps).call(this)
    });
    for (const result of results) {
      if (result.operation === "update") {
        ids.push(result.id);
      } else {
        ids.push(null);
      }
    }
  }
  return ids;
};
upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
  if (!recordId) return null;
  const response = await upsertRecordWithID({
    pathParams: {
      workspace: "{workspaceId}",
      dbBranchName: "{dbBranch}",
      region: "{region}",
      tableName: __privateGet$3(this, _table),
      recordId
    },
    queryParams: { columns, ifVersion },
    body: object,
    ...__privateGet$3(this, _getFetchProps).call(this)
  });
  const schemaTables = await __privateMethod$2(this, _RestRepository_instances, getSchemaTables_fn).call(this);
  return initObject(__privateGet$3(this, _db), schemaTables, __privateGet$3(this, _table), response, columns);
};
deleteRecord_fn = async function(recordId, columns = ["*"]) {
  if (!recordId) return null;
  try {
    const response = await deleteRecord({
      pathParams: {
        workspace: "{workspaceId}",
        dbBranchName: "{dbBranch}",
        region: "{region}",
        tableName: __privateGet$3(this, _table),
        recordId
      },
      queryParams: { columns },
      ...__privateGet$3(this, _getFetchProps).call(this)
    });
    const schemaTables = await __privateMethod$2(this, _RestRepository_instances, getSchemaTables_fn).call(this);
    return initObject(__privateGet$3(this, _db), schemaTables, __privateGet$3(this, _table), response, columns);
  } catch (e) {
    if (isObject(e) && e.status === 404) {
      return null;
    }
    throw e;
  }
};
deleteRecords_fn = async function(recordIds) {
  const chunkedOperations = chunk(
    compact(recordIds).map((id) => ({ delete: { table: __privateGet$3(this, _table), id } })),
    BULK_OPERATION_MAX_SIZE
  );
  for (const operations of chunkedOperations) {
    await branchTransaction({
      pathParams: {
        workspace: "{workspaceId}",
        dbBranchName: "{dbBranch}",
        region: "{region}"
      },
      body: { operations },
      ...__privateGet$3(this, _getFetchProps).call(this)
    });
  }
};
setCacheQuery_fn = async function(query, meta, records) {
  await __privateGet$3(this, _cache)?.set(`query_${__privateGet$3(this, _table)}:${query.key()}`, { date: /* @__PURE__ */ new Date(), meta, records });
};
getCacheQuery_fn = async function(query) {
  const key = `query_${__privateGet$3(this, _table)}:${query.key()}`;
  const result = await __privateGet$3(this, _cache)?.get(key);
  if (!result) return null;
  const defaultTTL = __privateGet$3(this, _cache)?.defaultQueryTTL ?? -1;
  const { cache: ttl = defaultTTL } = query.getQueryOptions();
  if (ttl < 0) return null;
  const hasExpired = result.date.getTime() + ttl < Date.now();
  return hasExpired ? null : result;
};
getSchemaTables_fn = async function() {
  if (__privateGet$3(this, _schemaTables)) return __privateGet$3(this, _schemaTables);
  const { schema } = await getBranchDetails({
    pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
    ...__privateGet$3(this, _getFetchProps).call(this)
  });
  __privateSet$2(this, _schemaTables, schema.tables);
  return schema.tables;
};
transformObjectToApi_fn = async function(object) {
  const schemaTables = await __privateMethod$2(this, _RestRepository_instances, getSchemaTables_fn).call(this);
  const schema = schemaTables.find((table) => table.name === __privateGet$3(this, _table));
  if (!schema) throw new Error(`Table ${__privateGet$3(this, _table)} not found in schema`);
  const result = {};
  for (const [key, value] of Object.entries(object)) {
    if (key === "xata") continue;
    const type = schema.columns.find((column) => column.name === key)?.type;
    switch (type) {
      case "link": {
        result[key] = isIdentifiable(value) ? value.id : value;
        break;
      }
      case "datetime": {
        result[key] = value instanceof Date ? value.toISOString() : value;
        break;
      }
      case `file`:
        result[key] = await parseInputFileEntry(value);
        break;
      case "file[]":
        result[key] = await promiseMap(value, (item) => parseInputFileEntry(item));
        break;
      case "json":
        result[key] = stringifyJson(value);
        break;
      default:
        result[key] = value;
    }
  }
  return result;
};
const initObject = (db, schemaTables, table, object, selectedColumns) => {
  const data = {};
  const { xata, ...rest } = object ?? {};
  Object.assign(data, rest);
  const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
  if (!columns) console.error(`Table ${table} not found in schema`);
  for (const column of columns ?? []) {
    if (!isValidColumn(selectedColumns, column)) continue;
    const value = data[column.name];
    switch (column.type) {
      case "datetime": {
        const date = value !== void 0 ? new Date(value) : null;
        if (date !== null && isNaN(date.getTime())) {
          console.error(`Failed to parse date ${value} for field ${column.name}`);
        } else {
          data[column.name] = date;
        }
        break;
      }
      case "link": {
        const linkTable = column.link?.table;
        if (!linkTable) {
          console.error(`Failed to parse link for field ${column.name}`);
        } else if (isObject(value)) {
          const selectedLinkColumns = selectedColumns.reduce((acc, item) => {
            if (item === column.name) {
              return [...acc, "*"];
            }
            if (isString(item) && item.startsWith(`${column.name}.`)) {
              const [, ...path] = item.split(".");
              return [...acc, path.join(".")];
            }
            return acc;
          }, []);
          data[column.name] = initObject(
            db,
            schemaTables,
            linkTable,
            value,
            selectedLinkColumns
          );
        } else {
          data[column.name] = null;
        }
        break;
      }
      case "file":
        data[column.name] = isDefined(value) ? new XataFile(value) : null;
        break;
      case "file[]":
        data[column.name] = value?.map((item) => new XataFile(item)) ?? null;
        break;
      case "json":
        data[column.name] = parseJson(value);
        break;
      default:
        data[column.name] = value ?? null;
        if (column.notNull === true && value === null) {
          console.error(`Parse error, column ${column.name} is non nullable and value resolves null`);
        }
        break;
    }
  }
  const record = { ...data };
  const metadata = xata !== void 0 ? { ...xata, createdAt: new Date(xata.createdAt), updatedAt: new Date(xata.updatedAt) } : void 0;
  record.read = function(columns2) {
    return db[table].read(record["id"], columns2);
  };
  record.update = function(data2, b, c) {
    const columns2 = isValidSelectableColumns(b) ? b : ["*"];
    const ifVersion = parseIfVersion(b, c);
    return db[table].update(record["id"], data2, columns2, { ifVersion });
  };
  record.replace = function(data2, b, c) {
    const columns2 = isValidSelectableColumns(b) ? b : ["*"];
    const ifVersion = parseIfVersion(b, c);
    return db[table].createOrReplace(record["id"], data2, columns2, { ifVersion });
  };
  record.delete = function() {
    return db[table].delete(record["id"]);
  };
  if (metadata !== void 0) {
    record.xata = Object.freeze(metadata);
  }
  record.getMetadata = function() {
    return record.xata;
  };
  record.toSerializable = function() {
    return JSON.parse(JSON.stringify(record));
  };
  record.toString = function() {
    return JSON.stringify(record);
  };
  for (const prop of ["read", "update", "replace", "delete", "getMetadata", "toSerializable", "toString"]) {
    Object.defineProperty(record, prop, { enumerable: false });
  }
  Object.freeze(record);
  return record;
};
function extractId(value) {
  if (isString(value)) return value;
  if (isObject(value) && isString(value.id)) return value.id;
  return void 0;
}
function isValidColumn(columns, column) {
  if (columns.includes("*")) return true;
  return columns.filter((item) => isString(item) && item.startsWith(column.name)).length > 0;
}
function parseIfVersion(...args) {
  for (const arg of args) {
    if (isObject(arg) && isNumber(arg.ifVersion)) {
      return arg.ifVersion;
    }
  }
  return void 0;
}

var __typeError$3 = (msg) => {
  throw TypeError(msg);
};
var __accessCheck$3 = (obj, member, msg) => member.has(obj) || __typeError$3("Cannot " + msg);
var __privateGet$2 = (obj, member, getter) => (__accessCheck$3(obj, member, "read from private field"), member.get(obj));
var __privateAdd$3 = (obj, member, value) => member.has(obj) ? __typeError$3("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateSet$1 = (obj, member, value, setter) => (__accessCheck$3(obj, member, "write to private field"), member.set(obj, value), value);
var _map;
class SimpleCache {
  constructor(options = {}) {
    __privateAdd$3(this, _map);
    __privateSet$1(this, _map, /* @__PURE__ */ new Map());
    this.capacity = options.max ?? 500;
    this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
  }
  async getAll() {
    return Object.fromEntries(__privateGet$2(this, _map));
  }
  async get(key) {
    return __privateGet$2(this, _map).get(key) ?? null;
  }
  async set(key, value) {
    await this.delete(key);
    __privateGet$2(this, _map).set(key, value);
    if (__privateGet$2(this, _map).size > this.capacity) {
      const leastRecentlyUsed = __privateGet$2(this, _map).keys().next().value;
      if (leastRecentlyUsed) await this.delete(leastRecentlyUsed);
    }
  }
  async delete(key) {
    __privateGet$2(this, _map).delete(key);
  }
  async clear() {
    return __privateGet$2(this, _map).clear();
  }
}
_map = new WeakMap();

const greaterThan = (value) => ({ $gt: value });
const gt = greaterThan;
const greaterThanEquals = (value) => ({ $ge: value });
const greaterEquals = greaterThanEquals;
const gte = greaterThanEquals;
const ge = greaterThanEquals;
const lessThan = (value) => ({ $lt: value });
const lt = lessThan;
const lessThanEquals = (value) => ({ $le: value });
const lessEquals = lessThanEquals;
const lte = lessThanEquals;
const le = lessThanEquals;
const exists = (column) => ({ $exists: column });
const notExists = (column) => ({ $notExists: column });
const startsWith = (value) => ({ $startsWith: value });
const endsWith = (value) => ({ $endsWith: value });
const pattern = (value) => ({ $pattern: value });
const iPattern = (value) => ({ $iPattern: value });
const is = (value) => ({ $is: value });
const equals = is;
const isNot = (value) => ({ $isNot: value });
const contains = (value) => ({ $contains: value });
const iContains = (value) => ({ $iContains: value });
const includes = (value) => ({ $includes: value });
const includesAll = (value) => ({ $includesAll: value });
const includesNone = (value) => ({ $includesNone: value });
const includesAny = (value) => ({ $includesAny: value });

var __typeError$2 = (msg) => {
  throw TypeError(msg);
};
var __accessCheck$2 = (obj, member, msg) => member.has(obj) || __typeError$2("Cannot " + msg);
var __privateGet$1 = (obj, member, getter) => (__accessCheck$2(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd$2 = (obj, member, value) => member.has(obj) ? __typeError$2("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var _tables;
class SchemaPlugin extends XataPlugin {
  constructor() {
    super();
    __privateAdd$2(this, _tables, {});
  }
  build(pluginOptions) {
    const db = new Proxy(
      {},
      {
        get: (_target, table) => {
          if (!isString(table)) throw new Error("Invalid table name");
          if (__privateGet$1(this, _tables)[table] === void 0) {
            __privateGet$1(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, schemaTables: pluginOptions.tables });
          }
          return __privateGet$1(this, _tables)[table];
        }
      }
    );
    const tableNames = pluginOptions.tables?.map(({ name }) => name) ?? [];
    for (const table of tableNames) {
      db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: pluginOptions.tables });
    }
    return db;
  }
}
_tables = new WeakMap();

class FilesPlugin extends XataPlugin {
  build(pluginOptions) {
    return {
      download: async (location) => {
        const { table, record, column, fileId = "" } = location ?? {};
        return await getFileItem({
          pathParams: {
            workspace: "{workspaceId}",
            dbBranchName: "{dbBranch}",
            region: "{region}",
            tableName: table ?? "",
            recordId: record ?? "",
            columnName: column ?? "",
            fileId
          },
          ...pluginOptions,
          rawResponse: true
        });
      },
      upload: async (location, file, options) => {
        const { table, record, column, fileId = "" } = location ?? {};
        const resolvedFile = await file;
        const contentType = options?.mediaType || getContentType(resolvedFile);
        const body = resolvedFile instanceof XataFile ? resolvedFile.toBlob() : resolvedFile;
        return await putFileItem({
          ...pluginOptions,
          pathParams: {
            workspace: "{workspaceId}",
            dbBranchName: "{dbBranch}",
            region: "{region}",
            tableName: table ?? "",
            recordId: record ?? "",
            columnName: column ?? "",
            fileId
          },
          body,
          headers: { "Content-Type": contentType }
        });
      },
      delete: async (location) => {
        const { table, record, column, fileId = "" } = location ?? {};
        return await deleteFileItem({
          pathParams: {
            workspace: "{workspaceId}",
            dbBranchName: "{dbBranch}",
            region: "{region}",
            tableName: table ?? "",
            recordId: record ?? "",
            columnName: column ?? "",
            fileId
          },
          ...pluginOptions
        });
      }
    };
  }
}
function getContentType(file) {
  if (typeof file === "string") {
    return "text/plain";
  }
  if ("mediaType" in file && file.mediaType !== void 0) {
    return file.mediaType;
  }
  if (isBlob(file)) {
    return file.type;
  }
  try {
    return file.type;
  } catch (e) {
  }
  return "application/octet-stream";
}

var __typeError$1 = (msg) => {
  throw TypeError(msg);
};
var __accessCheck$1 = (obj, member, msg) => member.has(obj) || __typeError$1("Cannot " + msg);
var __privateAdd$1 = (obj, member, value) => member.has(obj) ? __typeError$1("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateMethod$1 = (obj, member, method) => (__accessCheck$1(obj, member, "access private method"), method);
var _SearchPlugin_instances, search_fn;
class SearchPlugin extends XataPlugin {
  constructor(db) {
    super();
    this.db = db;
    __privateAdd$1(this, _SearchPlugin_instances);
  }
  build(pluginOptions) {
    return {
      all: async (query, options = {}) => {
        const { records, totalCount } = await __privateMethod$1(this, _SearchPlugin_instances, search_fn).call(this, query, options, pluginOptions);
        return {
          totalCount,
          records: records.map((record) => {
            const { table = "orphan" } = record.xata;
            return { table, record: initObject(this.db, pluginOptions.tables, table, record, ["*"]) };
          })
        };
      },
      byTable: async (query, options = {}) => {
        const { records: rawRecords, totalCount } = await __privateMethod$1(this, _SearchPlugin_instances, search_fn).call(this, query, options, pluginOptions);
        const records = rawRecords.reduce((acc, record) => {
          const { table = "orphan" } = record.xata;
          const items = acc[table] ?? [];
          const item = initObject(this.db, pluginOptions.tables, table, record, ["*"]);
          return { ...acc, [table]: [...items, item] };
        }, {});
        return { totalCount, records };
      }
    };
  }
}
_SearchPlugin_instances = new WeakSet();
search_fn = async function(query, options, pluginOptions) {
  const { tables, fuzziness, highlight, prefix, page } = options ?? {};
  const { records, totalCount } = await searchBranch({
    pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
    // @ts-expect-error Filter properties do not match inferred type
    body: { tables, query, fuzziness, prefix, highlight, page },
    ...pluginOptions
  });
  return { records, totalCount };
};

function escapeElement(elementRepresentation) {
  const escaped = elementRepresentation.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
  return '"' + escaped + '"';
}
function arrayString(val) {
  let result = "{";
  for (let i = 0; i < val.length; i++) {
    if (i > 0) {
      result = result + ",";
    }
    if (val[i] === null || typeof val[i] === "undefined") {
      result = result + "NULL";
    } else if (Array.isArray(val[i])) {
      result = result + arrayString(val[i]);
    } else if (val[i] instanceof Buffer) {
      result += "\\\\x" + val[i].toString("hex");
    } else {
      result += escapeElement(prepareValue(val[i]));
    }
  }
  result = result + "}";
  return result;
}
function prepareValue(value) {
  if (!isDefined(value)) return null;
  if (value instanceof Date) {
    return value.toISOString();
  }
  if (Array.isArray(value)) {
    return arrayString(value);
  }
  if (isObject(value)) {
    return JSON.stringify(value);
  }
  try {
    return value.toString();
  } catch (e) {
    return value;
  }
}
function prepareParams(param1, param2) {
  if (isString(param1)) {
    return { statement: param1, params: param2?.map((value) => prepareValue(value)) };
  }
  if (isStringArray(param1)) {
    const statement = param1.reduce((acc, curr, index) => {
      return acc + curr + (index < (param2?.length ?? 0) ? "$" + (index + 1) : "");
    }, "");
    return { statement, params: param2?.map((value) => prepareValue(value)) };
  }
  if (isObject(param1)) {
    const { statement, params, consistency, responseType } = param1;
    return { statement, params: params?.map((value) => prepareValue(value)), consistency, responseType };
  }
  throw new Error("Invalid query");
}

class SQLPlugin extends XataPlugin {
  build(pluginOptions) {
    const sqlFunction = async (query, ...parameters) => {
      if (!isParamsObject(query) && (!isTemplateStringsArray(query) || !Array.isArray(parameters))) {
        throw new Error("Invalid usage of `xata.sql`. Please use it as a tagged template or with an object.");
      }
      const { statement, params, consistency, responseType } = prepareParams(query, parameters);
      const { warning, columns, ...response } = await sqlQuery({
        pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
        body: { statement, params, consistency, responseType },
        ...pluginOptions
      });
      const records = "records" in response ? response.records : void 0;
      const rows = "rows" in response ? response.rows : void 0;
      return { records, rows, warning, columns };
    };
    sqlFunction.connectionString = buildConnectionString(pluginOptions);
    sqlFunction.batch = async (query) => {
      const { results } = await sqlBatchQuery({
        pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
        body: {
          statements: query.statements.map(({ statement, params }) => ({ statement, params })),
          consistency: query.consistency,
          responseType: query.responseType
        },
        ...pluginOptions
      });
      return { results };
    };
    return sqlFunction;
  }
}
function isTemplateStringsArray(strings) {
  return Array.isArray(strings) && "raw" in strings && Array.isArray(strings.raw);
}
function isParamsObject(params) {
  return isObject(params) && "statement" in params;
}
function buildDomain(host, region) {
  switch (host) {
    case "production":
      return `${region}.sql.xata.sh`;
    case "staging":
      return `${region}.sql.staging-xata.dev`;
    case "dev":
      return `${region}.sql.dev-xata.dev`;
    case "local":
      return "localhost:7654";
    default:
      throw new Error("Invalid host provider");
  }
}
function buildConnectionString({ apiKey, workspacesApiUrl, branch }) {
  const url = isString(workspacesApiUrl) ? workspacesApiUrl : workspacesApiUrl("", {});
  const parts = parseWorkspacesUrlParts(url);
  if (!parts) throw new Error("Invalid workspaces URL");
  const { workspace: workspaceSlug, region, database, host } = parts;
  const domain = buildDomain(host, region);
  const workspace = workspaceSlug.split("-").pop();
  if (!workspace || !region || !database || !apiKey || !branch) {
    throw new Error("Unable to build xata connection string");
  }
  return `postgresql://${workspace}:${apiKey}@${domain}/${database}:${branch}?sslmode=require`;
}

class TransactionPlugin extends XataPlugin {
  build(pluginOptions) {
    return {
      run: async (operations) => {
        const response = await branchTransaction({
          pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
          body: { operations },
          ...pluginOptions
        });
        return response;
      }
    };
  }
}

var __typeError = (msg) => {
  throw TypeError(msg);
};
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value);
var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
const buildClient = (plugins) => {
  var _options, _instances, parseOptions_fn, getFetchProps_fn, _a;
  return _a = class {
    constructor(options = {}, tables) {
      __privateAdd(this, _instances);
      __privateAdd(this, _options);
      const safeOptions = __privateMethod(this, _instances, parseOptions_fn).call(this, options);
      __privateSet(this, _options, safeOptions);
      const pluginOptions = {
        ...__privateMethod(this, _instances, getFetchProps_fn).call(this, safeOptions),
        cache: safeOptions.cache,
        host: safeOptions.host,
        tables,
        branch: safeOptions.branch
      };
      const db = new SchemaPlugin().build(pluginOptions);
      const search = new SearchPlugin(db).build(pluginOptions);
      const transactions = new TransactionPlugin().build(pluginOptions);
      const sql = new SQLPlugin().build(pluginOptions);
      const files = new FilesPlugin().build(pluginOptions);
      this.schema = { tables };
      this.db = db;
      this.search = search;
      this.transactions = transactions;
      this.sql = sql;
      this.files = files;
      for (const [key, namespace] of Object.entries(plugins ?? {})) {
        if (namespace === void 0) continue;
        this[key] = namespace.build(pluginOptions);
      }
    }
    async getConfig() {
      const databaseURL = __privateGet(this, _options).databaseURL;
      const branch = __privateGet(this, _options).branch;
      return { databaseURL, branch };
    }
  }, _options = new WeakMap(), _instances = new WeakSet(), parseOptions_fn = function(options) {
    const enableBrowser = options?.enableBrowser ?? getEnableBrowserVariable() ?? false;
    const isBrowser = typeof window !== "undefined" && typeof Deno === "undefined";
    if (isBrowser && !enableBrowser) {
      throw new Error(
        "You are trying to use Xata from the browser, which is potentially a non-secure environment. How to fix: https://xata.io/docs/messages/api-key-browser-error"
      );
    }
    const fetch = getFetchImplementation(options?.fetch);
    const databaseURL = options?.databaseURL || getDatabaseURL();
    const apiKey = options?.apiKey || getAPIKey();
    const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
    const trace = options?.trace ?? defaultTrace;
    const clientName = options?.clientName;
    const host = options?.host ?? "production";
    const xataAgentExtra = options?.xataAgentExtra;
    if (!apiKey) {
      throw new Error("Option apiKey is required");
    }
    if (!databaseURL) {
      throw new Error("Option databaseURL is required");
    }
    const envBranch = getBranch();
    const previewBranch = getPreviewBranch();
    const branch = options?.branch || previewBranch || envBranch || "main";
    if (!!previewBranch && branch !== previewBranch) {
      console.warn(
        `Ignoring preview branch ${previewBranch} because branch option was passed to the client constructor with value ${branch}`
      );
    } else if (!!envBranch && branch !== envBranch) {
      console.warn(
        `Ignoring branch ${envBranch} because branch option was passed to the client constructor with value ${branch}`
      );
    } else if (!!previewBranch && !!envBranch && previewBranch !== envBranch) {
      console.warn(
        `Ignoring preview branch ${previewBranch} and branch ${envBranch} because branch option was passed to the client constructor with value ${branch}`
      );
    } else if (!previewBranch && !envBranch && options?.branch === void 0) {
      console.warn(
        `No branch was passed to the client constructor. Using default branch ${branch}. You can set the branch with the environment variable XATA_BRANCH or by passing the branch option to the client constructor.`
      );
    }
    return {
      fetch,
      databaseURL,
      apiKey,
      branch,
      cache,
      trace,
      host,
      clientID: generateUUID(),
      enableBrowser,
      clientName,
      xataAgentExtra
    };
  }, getFetchProps_fn = function({
    fetch,
    apiKey,
    databaseURL,
    branch,
    trace,
    clientID,
    clientName,
    xataAgentExtra
  }) {
    return {
      fetch,
      apiKey,
      apiUrl: "",
      // Instead of using workspace and dbBranch, we inject a probably CNAME'd URL
      workspacesApiUrl: (path, params) => {
        const hasBranch = params.dbBranchName ?? params.branch;
        const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branch}` : "");
        return databaseURL + newPath;
      },
      trace,
      clientID,
      clientName,
      xataAgentExtra
    };
  }, _a;
};
class BaseClient extends buildClient() {
}

const META = "__";
const VALUE = "___";
class Serializer {
  constructor() {
    this.classes = {};
  }
  add(clazz) {
    this.classes[clazz.name] = clazz;
  }
  toJSON(data) {
    function visit(obj) {
      if (Array.isArray(obj)) return obj.map(visit);
      const type = typeof obj;
      if (type === "undefined") return { [META]: "undefined" };
      if (type === "bigint") return { [META]: "bigint", [VALUE]: obj.toString() };
      if (obj === null || type !== "object") return obj;
      const constructor = obj.constructor;
      const o = { [META]: constructor.name };
      for (const [key, value] of Object.entries(obj)) {
        o[key] = visit(value);
      }
      if (constructor === Date) o[VALUE] = obj.toISOString();
      if (constructor === Map) o[VALUE] = Object.fromEntries(obj);
      if (constructor === Set) o[VALUE] = [...obj];
      return o;
    }
    return JSON.stringify(visit(data));
  }
  fromJSON(json) {
    return JSON.parse(json, (key, value) => {
      if (value && typeof value === "object" && !Array.isArray(value)) {
        const { [META]: clazz, [VALUE]: val, ...rest } = value;
        const constructor = this.classes[clazz];
        if (constructor) {
          return Object.assign(Object.create(constructor.prototype), rest);
        }
        if (clazz === "Date") return new Date(val);
        if (clazz === "Set") return new Set(val);
        if (clazz === "Map") return new Map(Object.entries(val));
        if (clazz === "bigint") return BigInt(val);
        if (clazz === "undefined") return void 0;
        return rest;
      }
      return value;
    });
  }
}
const defaultSerializer = new Serializer();
const serialize = (data) => {
  return defaultSerializer.toJSON(data);
};
const deserialize = (json) => {
  return defaultSerializer.fromJSON(json);
};

class XataError extends Error {
  constructor(message, status) {
    super(message);
    this.status = status;
  }
}

export { BaseClient, Buffer, FetcherError, FilesPlugin, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, PageRecordArray, Query, RecordArray, RecordColumnTypes, Repository, RestRepository, SQLPlugin, SchemaPlugin, SearchPlugin, Serializer, SimpleCache, TransactionPlugin, XataApiClient, XataApiPlugin, XataError, XataFile, XataPlugin, acceptWorkspaceMemberInvite, adaptAllTables, adaptTable, addGitBranchesEntry, addTableColumn, aggregateTable, applyBranchSchemaEdit, applyMigration, askTable, askTableSession, branchTransaction, buildClient, buildPreviewBranchName, buildProviderString, bulkInsertTableRecords, cancelWorkspaceMemberInvite, compareBranchSchemas, compareBranchWithUserSchema, compareMigrationRequest, completeMigration, contains, copyBranch, createBranch, createBranchAsync, createCluster, createDatabase, createMigrationRequest, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteCluster, deleteColumn, deleteDatabase, deleteDatabaseGithubSettings, deleteFile, deleteFileItem, deleteOAuthAccessToken, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteUserOAuthClient, deleteWorkspace, deserialize, dropClusterExtension, endsWith, equals, executeBranchMigrationPlan, exists, fileAccess, fileUpload, ge, getAPIKey, getAuthorizationCode, getBranch, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationJobStatus, getBranchMigrationPlan, getBranchMoveStatus, getBranchSchemaHistory, getBranchStats, getCluster, getClusterMetrics, getColumn, getDatabaseGithubSettings, getDatabaseList, getDatabaseMetadata, getDatabaseSettings, getDatabaseURL, getFile, getFileItem, getGitBranchesMapping, getHostUrl, getMigrationHistory, getMigrationJobStatus, getMigrationJobs, getMigrationRequest, getMigrationRequestIsMerged, getPreviewBranch, getRecord, getSchema, getSchemas, getTableColumns, getTableSchema, getTaskStatus, getTasks, getUser, getUserAPIKeys, getUserOAuthAccessTokens, getUserOAuthClients, getWorkspace, getWorkspaceMembersList, getWorkspaceSettings, getWorkspacesList, grantAuthorizationCode, greaterEquals, greaterThan, greaterThanEquals, gt, gte, iContains, iPattern, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, installClusterExtension, inviteWorkspaceMember, is, isCursorPaginationOptions, isHostProviderAlias, isHostProviderBuilder, isIdentifiable, isNot, isValidExpandedColumn, isValidSelectableColumns, isXataRecord, le, lessEquals, lessThan, lessThanEquals, listClusterBranches, listClusterExtensions, listClusters, listMigrationRequestsCommits, listRegions, lt, lte, mergeMigrationRequest, moveBranch, notExists, operationsByTag, parseProviderString, parseWorkspacesUrlParts, pattern, previewBranchSchemaEdit, pushBranchMigrations, putFile, putFileItem, queryMigrationRequests, queryTable, removeGitBranchesEntry, removeWorkspaceMember, renameDatabase, resendWorkspaceMemberInvite, resolveBranch, rollbackMigration, searchBranch, searchTable, serialize, setTableSchema, sqlBatchQuery, sqlQuery, startMigration, startsWith, summarizeTable, transformImage, updateBranchMetadata, updateBranchSchema, updateCluster, updateColumn, updateDatabaseGithubSettings, updateDatabaseMetadata, updateDatabaseSettings, updateMigrationRequest, updateOAuthAccessToken, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberInvite, updateWorkspaceMemberRole, updateWorkspaceSettings, upsertRecordWithID, vectorSearchTable };
//# sourceMappingURL=index.mjs.map